Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Agents and scripts: Part Properties and Change Part Properties describe their exact parameters and reply (#12609) (#12634)

PeppaWutz3d49d0cb0b65
diff --git a/crates/engine/src/cmd/bom.rs b/crates/engine/src/cmd/bom.rs
index 02ce9e1ec5..7b0ab5db74 100644
--- a/crates/engine/src/cmd/bom.rs
+++ b/crates/engine/src/cmd/bom.rs
@@ -13,30 +13,45 @@
use std::collections::{BTreeMap, HashSet};
-use serde_json::{Map, Value, json};
+use serde_json::{Value, json};
use solidcraft_doc::BomType;
-use solidcraft_doc::metadata::{BOM_KEYS, BOM_TYPE, MAX_KEYS, Owner, check_text, key_list};
+use solidcraft_doc::metadata::{BOM_KEYS, BOM_TYPE, DESCRIPTION, MAX_KEYS, Owner, PART_NUMBER, REVISION, check_text, key_list};
use super::CommandSpec;
use crate::params::{bad, str_};
-use crate::schema::bom::{Bom, BomChild, BomParams, BomRow};
+use crate::schema::bom::{
+ Bom, BomChild, BomParams, BomRow, ComponentMetadataParams, ComponentMetadataResult, ComponentMetadataSetParams, ComponentMetadataSetResult,
+};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
const BOM_CONTRACT: TypedContract<BomParams> = TypedContract::new();
+const METADATA_CONTRACT: TypedContract<ComponentMetadataParams> = TypedContract::new();
+const METADATA_SET_CONTRACT: TypedContract<ComponentMetadataSetParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("component.metadata", "Part Properties", read).icon("settings").noundo().doc_only().params(
- "component: id or name (0 or \"root\": the design's own properties) → component, name, part_number, description, revision, \
+ CommandSpec::new("component.metadata", "Part Properties", crate::checked!("component.metadata", read))
+ .icon("settings")
+ .noundo()
+ .doc_only()
+ .contract(&METADATA_CONTRACT)
+ .output(output_schema_for::<ComponentMetadataResult>)
+ .params(
+ "component: id or name (0 or \"root\": the design's own properties) → component, name, part_number, description, revision, \
bom_type (components only), metadata (as saved, other tools' keys too), properties: {name: text}",
- ),
- CommandSpec::new("component.metadata.set", "Change Part Properties", set).icon("settings").doc_only().params(
- "component: id or name (not the root: use document.metadata.set); part_number?, description?, revision?: text (empty or null \
+ ),
+ CommandSpec::new("component.metadata.set", "Change Part Properties", crate::checked!("component.metadata.set", set))
+ .icon("settings")
+ .doc_only()
+ .contract(&METADATA_SET_CONTRACT)
+ .output(output_schema_for::<ComponentMetadataSetResult>)
+ .params(
+ "component: id or name (not the root: use document.metadata.set); part_number?, description?, revision?: text (empty or null \
removes); bom_type?: normal|phantom|reference|purchased|inseparable (empty or null: normal); values?: {key: value} \
(SolidCraft's keys, as document.metadata's properties lists them, bom_type, or a reverse-DNS key holding an object); \
properties?: {name: text, …} (free properties; empty or null removes). All or nothing, one undo step → component, \
metadata, properties, changed: [keys]",
- ),
+ ),
CommandSpec::new("assembly.bom", "Bill of Materials", crate::checked!("assembly.bom", bom))
.at("SOLID", "INSPECT")
.icon("bom")
@@ -80,24 +95,25 @@ fn read(s: &mut Session, p: &Value) -> Result<Value> {
let id = component_id(s, p, cmd)?;
// The root is the design: its own properties, and no free ones.
let (name, m, properties) = if id == 0 {
- (&s.doc.name, &s.doc.metadata, json!({}))
+ (&s.doc.name, &s.doc.metadata, BTreeMap::new())
} else {
let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?;
- (&c.name, &c.metadata, json!(c.properties))
+ (&c.name, &c.metadata, c.properties.clone())
};
- let mut out = Map::new();
- out.insert("component".into(), json!(id));
- out.insert("name".into(), json!(name));
- for k in BOM_KEYS {
- out.insert(k.to_string(), json!(m.text(k)));
- }
- // A bill of materials type is a component's; the design has none.
- if id != 0 {
- out.insert(BOM_TYPE.into(), json!(m.bom_type().as_str()));
- }
- out.insert("metadata".into(), json!(m));
- out.insert("properties".into(), properties);
- Ok(Value::Object(out))
+ let text = |k: &str| m.text(k).map(str::to_string);
+ let reply = ComponentMetadataResult {
+ component: id,
+ name: name.clone(),
+ part_number: text(PART_NUMBER),
+ description: text(DESCRIPTION),
+ revision: text(REVISION),
+ // A bill of materials type is a component's; the design has none.
+ bom_type: (id != 0).then(|| m.bom_type().as_str().to_string()),
+ metadata: m.0.clone(),
+ properties,
+ param_warnings: Vec::new(),
+ };
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}
/// A free property as it may be saved (`None`: remove it), or why not.
@@ -178,8 +194,15 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
c.metadata = metadata;
c.properties = properties;
}
- let c = s.doc.components.iter().find(|c| c.id == id);
- Ok(json!({"component": id, "metadata": c.map(|c| &c.metadata), "properties": c.map(|c| &c.properties), "changed": changed}))
+ let c = s.doc.components.iter().find(|c| c.id == id).ok_or_else(|| bad(cmd, format!("no component `{id}`")))?;
+ let reply = ComponentMetadataSetResult {
+ component: id,
+ metadata: c.metadata.0.clone(),
+ properties: c.properties.clone(),
+ changed,
+ param_warnings: Vec::new(),
+ };
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}
#[derive(Clone, Copy, PartialEq)]
diff --git a/crates/engine/src/schema/bom.rs b/crates/engine/src/schema/bom.rs
index 00938a8049..5e1396624b 100644
--- a/crates/engine/src/schema/bom.rs
+++ b/crates/engine/src/schema/bom.rs
@@ -1,4 +1,11 @@
-//! Contract and result types for `assembly.bom` in `cmd/bom.rs` (#11075).
+//! Contracts and result types for the commands in `cmd/bom.rs`: `assembly.bom` (#11075), and
+//! `component.metadata` and `component.metadata.set` (#12609).
+//!
+//! The part property handlers read their parameters from the raw JSON, so each key here reads as
+//! its handler reads it and fails with the handler's message. A `component` the handlers refuse
+//! when it is left out is optional in the type and required in the schema, so that the handler's
+//! message, not the check's "is required", is what a caller sees. Whether a component exists
+//! (and that the root is not one `component.metadata.set` changes) stays the handler's to check.
use std::borrow::Cow;
use std::collections::BTreeMap;
@@ -6,9 +13,204 @@ use std::collections::BTreeMap;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
-use serde_json::Value;
+use serde_json::{Map, Value};
+use solidcraft_doc::metadata::MAX_KEYS;
use super::check::whole;
+use super::motion::require;
+
+/// A component's id or name, as `component_id` in the handlers reads it: anything else, `null`
+/// included, is refused with the handler's message.
+fn component_key<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Number(n) => Ok(Some(n.to_string())),
+ Value::String(s) => Ok(Some(s)),
+ _ => Err(D::Error::custom(whole("`component` must be a component id or name"))),
+ }
+}
+
+fn component_required(schema: &mut Schema) {
+ require(schema, "component");
+}
+
+fn component_id_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "The component, by id or name (0 or \"root\": the design itself).", "type": ["number", "string"]})
+}
+
+fn text_or_null_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": ["string", "null"]})
+}
+
+/// Read the part properties of a component, or of the design itself (`0` or `root`): part
+/// number, description, revision, bill of materials type, the `metadata` object as saved and the
+/// free properties.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_required)]
+pub struct ComponentMetadataParams {
+ #[serde(default, deserialize_with = "component_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "component_id_schema")]
+ pub component: Option<String>,
+}
+
+/// What `component.metadata` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ComponentMetadataResult {
+ /// The component, by id (0: the design).
+ pub component: u64,
+ /// Its name (the design's name for 0).
+ pub name: String,
+ /// The part number, or null when it has none.
+ pub part_number: Option<String>,
+ /// The description, or null when it has none.
+ pub description: Option<String>,
+ /// The revision, or null when it has none.
+ pub revision: Option<String>,
+ /// `normal`, `phantom`, `reference`, `purchased` or `inseparable`. Not given for the design.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bom_type: Option<String>,
+ /// The metadata object as saved, other tools' keys included.
+ pub metadata: Map<String, Value>,
+ /// The free properties, `{name: text}`. Empty for the design.
+ pub properties: BTreeMap<String, String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// An object, as `component.metadata.set` reads `values` and `properties`: an object of at
+/// most 256 entries, with the handler's messages for anything else (`null` included). Each
+/// entry's value is left to the handler, which has its own message for each.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Entries(pub Map<String, Value>);
+
+fn entries<'de, D: Deserializer<'de>>(d: D, key: &str, what: &str, shape: &str) -> Result<Option<Entries>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Object(v) if v.len() <= MAX_KEYS => Ok(Some(Entries(v))),
+ Value::Object(_) => Err(D::Error::custom(whole(format!("`{key}` can hold at most {MAX_KEYS} {what}")))),
+ _ => Err(D::Error::custom(whole(format!("`{key}` must be an object: {shape}")))),
+ }
+}
+
+fn values<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Entries>, D::Error> {
+ entries(d, "values", "keys", "{key: value, …}")
+}
+
+fn free_properties<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Entries>, D::Error> {
+ entries(d, "properties", "names", "{name: text, …}")
+}
+
+fn values_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Several properties at once, {key: value, …}, at most 256 keys: SolidCraft's keys (the ones `document.metadata`'s `properties` lists) and `bom_type`, which take text, or a reverse-DNS key such as `com.example.tool`, which takes an object. Each key reads its value as the parameter of the same name does (`part_number`, `bom_type`, …): for a text key, empty text or null removes it; for `bom_type` it means `normal`.",
+ "type": "object",
+ "maxProperties": MAX_KEYS
+ })
+}
+
+fn properties_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Free properties, {name: text, …}, at most 256 names (a name is 1 to 128 bytes of text without control characters; a number or boolean is kept as its text). Empty text or null removes a property.",
+ "type": "object",
+ "maxProperties": MAX_KEYS,
+ "additionalProperties": {"type": ["string", "number", "boolean", "null"]}
+ })
+}
+
+// Deserialize is written out below rather than derived: the handler reads the other keys only for
+// a component that is not the design, so for `0` or `root` they are neither read nor checked.
+/// Change a component's part properties in one undo step (all or nothing): `part_number`,
+/// `description`, `revision` and `bom_type`, `values` for several keys at once (also another
+/// tool's reverse-DNS keys), and `properties` for free properties. Not the design's own
+/// (`document.metadata.set`). Give at least one of them. A change that sets what is already
+/// there makes no undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = component_required)]
+pub struct ComponentMetadataSetParams {
+ #[serde(default, deserialize_with = "component_key", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "component_id_schema")]
+ pub component: Option<String>,
+ /// The part number: text of at most 4096 bytes. Empty text or null removes it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_or_null_schema")]
+ pub part_number: Option<Value>,
+ /// The description: text of at most 4096 bytes. Empty text or null removes it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_or_null_schema")]
+ pub description: Option<Value>,
+ /// The revision: text of at most 4096 bytes. Empty text or null removes it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_or_null_schema")]
+ pub revision: Option<Value>,
+ /// How the component counts in the bill of materials: `normal`, `phantom`, `reference`,
+ /// `purchased` or `inseparable`. Empty text or null: `normal`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_or_null_schema")]
+ pub bom_type: Option<Value>,
+ #[serde(default, deserialize_with = "values", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "values_schema")]
+ pub values: Option<Entries>,
+ #[serde(default, deserialize_with = "free_properties", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "properties_schema")]
+ pub properties: Option<Entries>,
+}
+
+impl<'de> Deserialize<'de> for ComponentMetadataSetParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let p = Map::<String, Value>::deserialize(d)?;
+ set_form(&p).map_err(D::Error::custom)
+ }
+}
+
+/// A key's value through its reader, or `None` when the key is left out.
+fn key_with<'a, T>(
+ p: &'a Map<String, Value>,
+ key: &str,
+ read: impl FnOnce(&'a Value) -> Result<Option<T>, serde_json::Error>,
+) -> Result<Option<T>, serde_json::Error> {
+ p.get(key).map_or(Ok(None), read)
+}
+
+/// The keys `component.metadata.set`'s handler reads, in its order: the component, and for any
+/// but the design (`0`, `root` in any case), the text keys, `values` and then `properties`.
+fn set_form(p: &Map<String, Value>) -> Result<ComponentMetadataSetParams, serde_json::Error> {
+ let component = key_with(p, "component", component_key)?;
+ let mut form = ComponentMetadataSetParams {
+ component,
+ part_number: None,
+ description: None,
+ revision: None,
+ bom_type: None,
+ values: None,
+ properties: None,
+ };
+ if form.component.as_deref().is_some_and(|c| c == "0" || c.eq_ignore_ascii_case("root")) {
+ return Ok(form);
+ }
+ form.values = key_with(p, "values", values)?;
+ form.part_number = p.get("part_number").cloned();
+ form.description = p.get("description").cloned();
+ form.revision = p.get("revision").cloned();
+ form.bom_type = p.get("bom_type").cloned();
+ form.properties = key_with(p, "properties", free_properties)?;
+ Ok(form)
+}
+
+/// What `component.metadata.set` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ComponentMetadataSetResult {
+ /// The component, by id.
+ pub component: u64,
+ /// Its metadata object after the change.
+ pub metadata: Map<String, Value>,
+ /// Its free properties after the change.
+ pub properties: BTreeMap<String, String>,
+ /// What changed: the keys whose value changed, and `properties.<name>` for each free
+ /// property. Empty when nothing did (and then nothing was added to undo).
+ pub changed: Vec<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
/// The bill of materials below a component: its parts, counted through subassemblies, by part
/// number. Each component's bom type counts: a phantom has no row (what it holds counts where it
diff --git a/crates/engine/src/schema/bom_tests.rs b/crates/engine/src/schema/bom_tests.rs
index 55e86a7632..fd1a9f0077 100644
--- a/crates/engine/src/schema/bom_tests.rs
+++ b/crates/engine/src/schema/bom_tests.rs
@@ -1,6 +1,6 @@
use serde_json::{Value, json};
-use super::{Bom, BomParams};
+use super::{Bom, BomParams, ComponentMetadataParams, ComponentMetadataResult, ComponentMetadataSetParams, ComponentMetadataSetResult};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
@@ -31,6 +31,11 @@ fn assembly(s: &mut Session) {
#[test]
fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<BomParams>(), &["component", "format", "group_by", "group_children", "levels", "path"]);
+ assert_keys(input_schema_for::<ComponentMetadataParams>(), &["component"]);
+ assert_keys(
+ input_schema_for::<ComponentMetadataSetParams>(),
+ &["bom_type", "component", "description", "part_number", "properties", "revision", "values"],
+ );
}
#[test]
@@ -50,7 +55,50 @@ fn strict_keeps_todays_errors() {
("assembly.bom", json!({"group_children": "yes"})),
("assembly.bom", json!({"path": file.replace(".csv", ".txt")})),
("assembly.bom", json!({"path": file, "format": "xml"})),
+ ("component.metadata", json!({})),
+ ("component.metadata", json!({"component": null})),
+ ("component.metadata", json!({"component": true})),
+ ("component.metadata", json!({"component": [1]})),
+ ("component.metadata", json!({"component": "Nope"})),
+ ("component.metadata.set", json!({})),
+ ("component.metadata.set", json!({"component": null, "part_number": "A"})),
+ ("component.metadata.set", json!({"component": {"id": 1}, "part_number": "A"})),
+ ("component.metadata.set", json!({"component": "Nope", "part_number": "A"})),
+ ("component.metadata.set", json!({"component": 0, "part_number": "A"})),
+ ("component.metadata.set", json!({"component": "root", "part_number": "A"})),
+ ("component.metadata.set", json!({"component": 0, "values": 5})),
]);
+ // The cases that need a component to be there: a part with properties to set badly.
+ let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() };
+ let mut off = Session { param_check: ParamCheck::Off, ..Session::default() };
+ for session in [&mut s, &mut off] {
+ run(session, "component.create", json!({"name": "Plate"}));
+ }
+ for p in [
+ json!({"component": "Plate"}),
+ json!({"component": "Plate", "values": null}),
+ json!({"component": "Plate", "values": [1]}),
+ json!({"component": "Plate", "values": "x"}),
+ json!({"component": "Plate", "properties": null}),
+ json!({"component": "Plate", "properties": ["a"]}),
+ json!({"component": "Plate", "values": (0..257).map(|i| (format!("org.k{i}"), json!({}))).collect::<serde_json::Map<_, _>>()}),
+ json!({"component": "Plate", "properties": (0..257).map(|i| (format!("p{i}"), json!("x"))).collect::<serde_json::Map<_, _>>()}),
+ json!({"component": "Plate", "part_number": 5}),
+ json!({"component": "Plate", "part_number": ["A"]}),
+ json!({"component": "Plate", "bom_type": "kit"}),
+ json!({"component": "Plate", "bom_type": 1}),
+ json!({"component": "Plate", "values": {"nope": "x"}}),
+ json!({"component": "Plate", "values": {"com.example.tool": "x"}}),
+ json!({"component": "Plate", "properties": {"": "x"}}),
+ json!({"component": "Plate", "properties": {"a": ["x"]}}),
+ json!({"component": "Plate", "properties": {"a": {"b": 1}}}),
+ json!({"component": "Plate", "description": "bad\u{7}"}),
+ json!({"component": "Plate", "properties": {"a": "bad\u{7}"}}),
+ ] {
+ let (a, b) = (off.execute("component.metadata.set", &p), s.execute("component.metadata.set", &p));
+ assert!(a.is_err(), "{p} should fail today");
+ assert_eq!(a.map_err(|e| e.to_string()), b.map_err(|e| e.to_string()), "{p}");
+ }
}
/// #11075: a bill of materials replies as its output schema says, in Warn without warnings for
@@ -84,3 +132,140 @@ fn a_bill_of_materials_replies_with_its_schema() {
}
matches(&run(&mut s, "assembly.bom", json!({"level": "top"})), true);
}
+
+fn matches(schema: schemars::Schema, id: &str, reply: &Value, warned: bool) {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
+ assert_eq!(reply.get("param_warnings").is_some(), warned, "{id}: {reply}");
+}
+
+/// #12609: the types read each key as the handlers do, with their messages, and the check
+/// accepts every form a handler takes today.
+#[test]
+fn the_part_property_types_read_keys_as_the_handlers_do() {
+ let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
+ let none = Vec::<String>::new();
+ for id in ["component.metadata", "component.metadata.set"] {
+ let p = |component: Value| {
+ if id == "component.metadata" { json!({"component": component}) } else { json!({"component": component, "revision": "A"}) }
+ };
+ assert_eq!(issues(id, p(json!(3))), none, "{id}");
+ assert_eq!(issues(id, p(json!("Plate"))), none, "{id}");
+ assert_eq!(issues(id, p(json!(0))), none, "{id}");
+ assert_eq!(issues(id, p(json!("root"))), none, "{id}");
+ for bad in [json!(null), json!(true), json!([1]), json!({"a": 1})] {
+ assert_eq!(issues(id, p(bad.clone())), ["`component` must be a component id or name"], "{id} {bad}");
+ }
+ assert_eq!(issues(id, json!({"component": 1, "compnent": 1})).len(), 1, "{id}");
+ }
+ let set = |p: Value| issues("component.metadata.set", p);
+ // The keys that take text hand any value to the handler, which names what it refuses.
+ for k in ["part_number", "description", "revision", "bom_type"] {
+ for v in [json!("x"), json!(""), json!(null), json!(5), json!(["x"])] {
+ assert_eq!(set(json!({"component": 1, k: v})), none, "{k}");
+ }
+ }
+ assert_eq!(set(json!({"component": 1, "values": {"com.example.tool": {"a": 1}, "author": 5}})), none);
+ assert_eq!(set(json!({"component": 1, "properties": {"a": "x", "b": 2, "c": true, "d": null, "e": ["x"]}})), none);
+ // For the design the handler refuses before it reads anything else, so nothing else is read.
+ for root in [json!(0), json!("0"), json!("root"), json!("ROOT")] {
+ assert_eq!(set(json!({"component": root, "values": 5, "properties": null})), none, "{root}");
+ }
+ assert_eq!(set(json!({"component": 1, "values": null})), ["`values` must be an object: {key: value, …}"]);
+ assert_eq!(set(json!({"component": 1, "values": [1]})), ["`values` must be an object: {key: value, …}"]);
+ assert_eq!(set(json!({"component": 1, "properties": "a"})), ["`properties` must be an object: {name: text, …}"]);
+ let many = |prefix: &str| (0..257).map(|i| (format!("{prefix}{i}"), json!("x"))).collect::<serde_json::Map<_, _>>();
+ assert_eq!(set(json!({"component": 1, "values": many("org.k")})), ["`values` can hold at most 256 keys"]);
+ assert_eq!(set(json!({"component": 1, "properties": many("p")})), ["`properties` can hold at most 256 names"]);
+ let mut full = many("p");
+ full.remove("p256");
+ assert_eq!(set(json!({"component": 1, "properties": full, "values": {}})), none);
+}
+
+/// The schemas say what the handlers need: `component` is required though the types leave it to
+/// the handlers' message, and the limits and shapes are those of the handlers.
+#[test]
+fn the_part_property_schemas_take_what_the_handlers_read() {
+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
+ let schema = schema.as_value();
+ for (p, takes) in cases {
+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");
+ }
+ };
+ takes(
+ input_schema_for::<ComponentMetadataParams>(),
+ &[(json!({"component": "Plate"}), true), (json!({"component": 0}), true), (json!({}), false), (json!({"component": true}), false)],
+ );
+ takes(
+ input_schema_for::<ComponentMetadataSetParams>(),
+ &[
+ (json!({"component": "Plate", "part_number": "P-1", "description": null, "revision": "", "bom_type": "phantom"}), true),
+ (
+ json!({"component": 2, "values": {"com.example.tool": {"a": 1}}, "properties": {"finish": "zinc", "n": 3, "b": true, "gone": null}}),
+ true,
+ ),
+ (json!({"part_number": "P-1"}), false),
+ (json!({"component": "Plate", "part_number": 5}), false),
+ (json!({"component": "Plate", "values": []}), false),
+ ],
+ );
+}
+
+/// Read and change part properties of a component and of the design, in Warn: each real reply
+/// matches its output schema and carries no warning; a misspelt key's warning still matches.
+#[test]
+fn part_property_replies_match_the_output_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ assembly(&mut s);
+ let read = |s: &mut Session, p: Value| {
+ let r = run(s, "component.metadata", p);
+ matches(output_schema_for::<ComponentMetadataResult>(), "component.metadata", &r, false);
+ r
+ };
+ let change = |s: &mut Session, p: Value| {
+ let r = run(s, "component.metadata.set", p);
+ matches(output_schema_for::<ComponentMetadataSetResult>(), "component.metadata.set", &r, false);
+ r
+ };
+ let plate = read(&mut s, json!({"component": "Plate"}));
+ assert_eq!(
+ (plate["part_number"].as_str(), plate["revision"].as_str(), plate["bom_type"].as_str()),
+ (Some("PL-100"), Some("B"), Some("normal")),
+ "{plate}"
+ );
+ let pin = read(&mut s, json!({"component": "Pin"}));
+ assert_eq!((pin["properties"]["finish"].as_str(), pin["revision"].is_null()), (Some("zinc"), true), "{pin}");
+ let root = read(&mut s, json!({"component": 0}));
+ assert!(root.get("bom_type").is_none() && root["properties"] == json!({}), "{root}");
+ read(&mut s, json!({"component": "root"}));
+ let by_id = read(&mut s, json!({"component": plate["component"]}));
+ assert_eq!(by_id["name"], "Plate");
+
+ let r = change(
+ &mut s,
+ json!({"component": "Plate", "revision": "C", "bom_type": "purchased", "properties": {"material": "1.4301", "n": 3, "ok": true}}),
+ );
+ assert_eq!(r["changed"], json!(["revision", "bom_type", "properties.material", "properties.n", "properties.ok"]), "{r}");
+ let r = change(
+ &mut s,
+ json!({"component": "Plate", "values": {"com.example.tool": {"a": 1}, "description": "Plate"}, "part_number": null, "properties": {"n": ""}}),
+ );
+ assert_eq!(r["changed"], json!(["com.example.tool", "description", "part_number", "properties.n"]), "{r}");
+ assert_eq!(r["properties"], json!({"material": "1.4301", "ok": "true"}), "{r}");
+ let r = change(&mut s, json!({"component": "Plate", "revision": "C"}));
+ assert_eq!(r["changed"], json!([]), "{r}");
+ assert_eq!(read(&mut s, json!({"component": "Plate"}))["metadata"]["com.example.tool"], json!({"a": 1}));
+
+ for (id, p) in [
+ ("component.metadata", json!({"component": "Plate", "compnent": 1})),
+ ("component.metadata.set", json!({"component": "Plate", "revision": "D", "revison": "E"})),
+ ] {
+ let warned = run(&mut s, id, p);
+ assert!(warned["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{warned}");
+ if id == "component.metadata" {
+ matches(output_schema_for::<ComponentMetadataResult>(), id, &warned, true);
+ } else {
+ matches(output_schema_for::<ComponentMetadataSetResult>(), id, &warned, true);
+ }
+ }
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index e08d44814b..7b0e7dc020 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -8,8 +8,6 @@ component.create
component.delete
component.from_bodies
component.list
-component.metadata
-component.metadata.set
component.move_bodies
component.move_sketches
component.paste_new