SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Configure, Configuration Column, Row and Rule describe their exact parameters and reply (#11895) (#11896)
austin62jake80889762ce46
diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rsindex 6bf8a3071a..cd43fbd321 100644--- a/crates/engine/src/cmd/config.rs+++ b/crates/engine/src/cmd/config.rs@@ -7,15 +7,27 @@ use solidcraft_doc::config::{Column, ConfigRow, MAX_COLUMNS, MAX_ROWS};use super::CommandSpec;use crate::params::{bad, bool_, str_, string_list};-use crate::schema::config::{ConfigActivation, ConfigRowParams, ConfigTable, ConfigTableParams, ConfigTableReply, ConfigTableRow, ConfigTarget};+use crate::schema::config::{+ ConfigActivation, ConfigColumnParams, ConfigConfigureParams, ConfigRowEditParams, ConfigRowParams, ConfigRuleParams, ConfigTable,+ ConfigTableParams, ConfigTableReply, ConfigTableRow, ConfigTarget,+};use crate::schema::{TypedContract, output_schema_for};use crate::{Result, Session};const TABLE_CONTRACT: TypedContract<ConfigTableParams> = TypedContract::new();const ROW_CONTRACT: TypedContract<ConfigRowParams> = TypedContract::new();+const CONFIGURE_CONTRACT: TypedContract<ConfigConfigureParams> = TypedContract::new();+const COLUMN_CONTRACT: TypedContract<ConfigColumnParams> = TypedContract::new();+const ROW_EDIT_CONTRACT: TypedContract<ConfigRowEditParams> = TypedContract::new();+const RULE_CONTRACT: TypedContract<ConfigRuleParams> = TypedContract::new();pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("config.configure", "Configure", configure).at("SOLID", "CONFIGURE").icon("params").params(+ CommandSpec::new("config.configure", "Configure", crate::checked!("config.configure", configure))+ .at("SOLID", "CONFIGURE")+ .icon("params")+ .contract(&CONFIGURE_CONTRACT)+ .output(output_schema_for::<ConfigTableReply>)+ .params("params?: [parameter names]; features?: [feature names]; materials?: [body names]; appearances?: [body names] (columns to add; with no rows yet, a \"Default\" row takes the current values)",),CommandSpec::new("config.table", "Display Configuration Table", crate::checked!("config.table", show))@@ -25,8 +37,16 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&TABLE_CONTRACT).output(output_schema_for::<ConfigTableReply>).params("→ columns (param:<name> or suppress:<feature>), rows, the active row and whether the design still matches it"),- CommandSpec::new("config.column", "Configuration Column", column).icon("configuration_table").params("param? | feature? | material? | appearance? (target name); delete?: bool"),- CommandSpec::new("config.row", "Configuration Row", row).icon("configuration_table").params(+ CommandSpec::new("config.column", "Configuration Column", crate::checked!("config.column", column))+ .icon("configuration_table")+ .contract(&COLUMN_CONTRACT)+ .output(output_schema_for::<ConfigTableReply>)+ .params("param? | feature? | material? | appearance? (target name); delete?: bool"),+ CommandSpec::new("config.row", "Configuration Row", crate::checked!("config.row", row))+ .icon("configuration_table")+ .contract(&ROW_EDIT_CONTRACT)+ .output(output_schema_for::<ConfigTableReply>)+ .params("name; from? (row to copy; default current values); values?: {column key: expression, suppression, material name, appearance name or Look object}; rename?; delete?: bool",),CommandSpec::new("config.activate", "Activate Configuration", crate::checked!("config.activate", activate))@@ -40,7 +60,11 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&ROW_CONTRACT).output(output_schema_for::<ConfigActivation>).params("row: name — validates a rebuild without changing the design or history"),- CommandSpec::new("config.rule", "Configuration Rule", rule).icon("configuration_table").params(+ CommandSpec::new("config.rule", "Configuration Rule", crate::checked!("config.rule", rule))+ .icon("configuration_table")+ .contract(&RULE_CONTRACT)+ .output(output_schema_for::<ConfigTableReply>)+ .params("rule?: {id,name,enabled,condition,effect}; rules?: [rule…] (added or replaced together, then the rows checked once); id? + delete?; id? + index? (ordered move)",),CommandSpec::new("config.rules", "Configuration Rules", crate::checked!("config.rules", show))diff --git a/crates/engine/src/params.rs b/crates/engine/src/params.rsindex 8de8f269f1..7ae0df2d42 100644--- a/crates/engine/src/params.rs+++ b/crates/engine/src/params.rs@@ -88,14 +88,16 @@ pub fn req_expr(cmd: &str, p: &Value, k: &str) -> Result<Expr> {}/// The most names a list parameter may carry.-const MAX_STRING_LIST: usize = 10_000;+pub(crate) const MAX_STRING_LIST: usize = 10_000;/// The command name for a caller that does not know it: the engine names the command that ran/// when the error reaches it.pub const UNKNOWN_COMMAND: &str = "";-/// A short description of a value that is not a name, for the message that refuses it.-fn json_brief(v: &Value) -> String {+/// A short description of a value that is not a name, for the message that refuses it. The+/// schema contracts quote it too (`schema::config::NameList`), so strict refuses with the same+/// words.+pub(crate) fn json_brief(v: &Value) -> String {match v {Value::Null => "null".to_string(),Value::Bool(b) => b.to_string(),diff --git a/crates/engine/src/schema/config.rs b/crates/engine/src/schema/config.rsindex 876e6a963f..cd946b025e 100644--- a/crates/engine/src/schema/config.rs+++ b/crates/engine/src/schema/config.rs@@ -1,14 +1,24 @@-//! Contracts and result types for the configuration commands in `cmd/config.rs` that read the-//! table and switch between its rows (#11059).+//! Contracts and result types for the configuration commands in `cmd/config.rs`: those that read+//! the table and switch between its rows (#11059), and those that change the table (#11895):+//! `config.configure`, `config.column`, `config.row` and `config.rule`.+//!+//! The 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. What only the design can answer (does the+//! parameter, feature, body, component or row exist; does a rule hold for every row) stays the+//! handler's to check. A key the handler reads only with another (`index` without `delete`, a+//! row's `values` without `delete`) is checked whenever it is given.+use std::borrow::Cow;use std::collections::BTreeMap;-use schemars::JsonSchema;+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::config::{MAX_COLUMNS, MAX_RULES};use super::check::whole;+use crate::params::{self, MAX_STRING_LIST, json_brief};/// The configuration table: its columns, rows and rules, the active row, and whether the design/// still matches it. Read-only.@@ -35,6 +45,459 @@ fn row<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {}}+/// Add columns to the configuration table: parameters, feature suppressions, and bodies' and+/// components' materials and looks, each filled in every row with the design's current value. A+/// column the table has is left as it is. With no rows yet, a "Default" row takes the current+/// values and becomes the active row. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ConfigConfigureParams {+ /// Parameters to configure, by name, as `parameters.list` gives them.+ #[serde(default)]+ pub params: Option<NameList>,+ /// Features whose suppression to configure, by name.+ #[serde(default)]+ pub features: Option<NameList>,+ /// Bodies whose material to configure, by name.+ #[serde(default)]+ pub materials: Option<NameList>,+ /// Bodies whose look to configure, by name.+ #[serde(default)]+ pub appearances: Option<NameList>,+ /// Components whose look to configure: each a component's name or id, or an occurrence's name+ /// (its component). At most 500.+ #[serde(default, deserialize_with = "component_keys", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "component_keys_schema")]+ pub component_appearances: Option<Vec<ComponentKey>>,+ /// Faces whose look to configure, each picked as `face_appearance` is for `config.column`+ /// (not by a column key). At most 500.+ #[serde(default, deserialize_with = "face_picks", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "face_picks_schema")]+ pub face_appearances: Option<Vec<Value>>,+}++/// Add a column to the configuration table, or delete one: give exactly one of `param`,+/// `feature`, `material`, `appearance`, `component_appearance` and `face_appearance`. An added+/// column is filled in every row with the design's current value; the rows are checked against+/// the table's rules afterwards. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = exactly_one_target)]+pub struct ConfigColumnParams {+ /// A parameter, by name: its value in each row.+ #[serde(default, deserialize_with = "target_name", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String")]+ pub param: Option<String>,+ /// A feature, by name: whether each row suppresses it.+ #[serde(default, deserialize_with = "target_name", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String")]+ pub feature: Option<String>,+ /// A body, by name: its material in each row.+ #[serde(default, deserialize_with = "target_name", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String")]+ pub material: Option<String>,+ /// A body, by name: its look in each row.+ #[serde(default, deserialize_with = "target_name", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String")]+ pub appearance: Option<String>,+ /// A component, by name or id, or an occurrence by name (its component): its look in each row.+ #[serde(default, deserialize_with = "some_component_key", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ComponentKey")]+ pub component_appearance: Option<ComponentKey>,+ #[serde(default, deserialize_with = "face_column", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "face_column_schema")]+ pub face_appearance: Option<Value>,+ /// Delete the column instead of adding it. Default: false.+ #[serde(default)]+ pub delete: Option<bool>,+}++/// Add a row to the configuration table, change one, rename it or delete it. A new row starts+/// from `from`'s cells, or the design's current values; `values` then sets cells. Rows are checked+/// against the table's rules, and a parameter value against the parameters it drives, before+/// anything changes. The design keeps its active row's values until a row is activated. One undo+/// step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ConfigRowEditParams {+ /// The row, by name: 1 to 128 bytes once spaces at either end are dropped. A name the table+ /// doesn't have adds a row (at most 2000).+ #[serde(deserialize_with = "row_name")]+ #[schemars(length(min = 1, max = 128))]+ pub name: String,+ /// A row to copy the cells of, by name. Default: the row's own cells, or the design's current+ /// values for a new row.+ #[serde(default)]+ pub from: Option<String>,+ #[serde(default, deserialize_with = "row_values", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "row_values_schema")]+ pub values: Option<Map<String, Value>>,+ /// A new name for the row, which must exist: 1 to 128 bytes once spaces at either end are+ /// dropped, not another row's.+ #[serde(default, deserialize_with = "rename", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String", length(min = 1, max = 128))]+ pub rename: Option<String>,+ /// Delete the row instead; `from`, `values` and `rename` are then not used. The last row can't+ /// be deleted while the table has rules. Default: false.+ #[serde(default)]+ pub delete: Option<bool>,+}++/// Add, replace, delete or move the configuration table's rules, which drive parameters and+/// suppressions from conditions, in the order they run. Give `rule`, `rules`, or `id` with+/// `delete` or `index`. Every row is then checked against the rules; if one fails, nothing+/// changes. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ConfigRuleParams {+ /// A rule to add, or to replace the rule with its id.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "rule_schema")]+ pub rule: Option<Value>,+ /// Without `rule`: rules to add or replace together, the rows then checked once with all of+ /// them in place (rules that only hold together can be added). At most 2048.+ #[serde(default, deserialize_with = "rule_list", skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "rule_list_schema")]+ pub rules: Option<Vec<Value>>,+ /// Without `rule` or `rules`: the rule to delete or move, by id.+ #[serde(default, deserialize_with = "rule_id")]+ #[schemars(with = "Option<String>")]+ pub id: Option<String>,+ /// With `id`: delete the rule. Default: false (move it to `index`).+ #[serde(default)]+ pub delete: Option<bool>,+ /// With `id` and without `delete`: where to move the rule, from 0 (it runs first); less than+ /// the number of rules.+ #[serde(default, deserialize_with = "rule_index", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "u64")]+ pub index: Option<u64>,+}++/// A name or a list of names, as `params::string_list` reads it, with its messages: a list of+/// at most 10 000 names, or one name as text. `null` is left out (`Option`), as the reader reads+/// it.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct NameList(pub Vec<String>);++impl<'de> Deserialize<'de> for NameList {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ // Each message starts with "must", so the check names the key in front, as the reader+ // does: "`params` must list names; the entry 2 is 5".+ match Value::deserialize(d)? {+ Value::String(name) => Ok(NameList(vec![name])),+ Value::Array(list) if list.len() > MAX_STRING_LIST => Err(D::Error::custom(format!("must list at most {MAX_STRING_LIST} names"))),+ Value::Array(list) => list+ .iter()+ .enumerate()+ .map(|(i, v)| {+ v.as_str()+ .map(str::to_string)+ .ok_or_else(|| D::Error::custom(format!("must list names; the entry {} is {}", i + 1, json_brief(v))))+ })+ .collect::<Result<_, _>>()+ .map(NameList),+ v => Err(D::Error::custom(format!("must be a list of names; it is {}", json_brief(&v)))),+ }+ }+}++impl JsonSchema for NameList {+ fn schema_name() -> Cow<'static, str> {+ "NameList".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A name, or a list of names (at most 10000).",+ "anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": MAX_STRING_LIST}]+ })+ }+}++/// A component's name or id, or an occurrence's name, as `config.column` reads+/// `component_appearance`: text or a whole number of 0 or more, with its message.+#[derive(Clone, Debug, PartialEq)]+pub struct ComponentKey(pub String);++impl ComponentKey {+ fn read(v: &Value) -> Option<Self> {+ v.as_str().map(str::to_string).or_else(|| v.as_u64().map(|id| id.to_string())).map(ComponentKey)+ }+}++impl<'de> Deserialize<'de> for ComponentKey {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ ComponentKey::read(&Value::deserialize(d)?).ok_or_else(|| D::Error::custom(whole("component name or ID required")))+ }+}++impl JsonSchema for ComponentKey {+ fn schema_name() -> Cow<'static, str> {+ "ComponentKey".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A component's name or id, or an occurrence's name (its component).",+ "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0}]+ })+ }+}++/// `component_appearance`: given, `null` included, it must be a [`ComponentKey`], as the+/// handler reads it whenever the key is there.+fn some_component_key<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentKey>, D::Error> {+ ComponentKey::deserialize(d).map(Some)+}++/// `component_appearances`: a list of at most 500 [`ComponentKey`]s; given, `null` included, it+/// must be a list, as the handler reads it.+fn component_keys<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<ComponentKey>>, D::Error> {+ let list = bounded_targets(Value::deserialize(d)?).map_err(D::Error::custom)?;+ list.iter()+ .map(|v| ComponentKey::read(v).ok_or_else(|| D::Error::custom(whole("component name or ID required"))))+ .collect::<Result<_, _>>()+ .map(Some)+}++fn component_keys_schema(generator: &mut SchemaGenerator) -> Schema {+ let key = generator.subschema_for::<ComponentKey>();+ json_schema!({"type": "array", "items": key, "maxItems": MAX_COLUMNS})+}++/// The list `config.configure` reads `component_appearances` and `face_appearances` as: at most+/// 500 targets, with its message for anything else.+fn bounded_targets(v: Value) -> Result<Vec<Value>, String> {+ match v {+ Value::Array(list) if list.len() <= MAX_COLUMNS => Ok(list),+ _ => Err(whole("configuration targets must be a bounded array")),+ }+}++/// Why `column_of` refuses `v` as a face to pick, before looking at the design: a face is+/// `{target}` (which the handler checks), or `{body, point}` with a body's name and a point+/// [x, y, z] on it.+fn face_pick_problem(v: &Value) -> Option<&'static str> {+ if v.get("target").is_some() {+ return None;+ }+ if v.get("body").and_then(Value::as_str).is_none() {+ return Some("face body required");+ }+ v.get("point").and_then(params::vec3).is_none().then_some("finite face point required")+}++/// `config.column`'s `face_appearance`: a face to pick ([`face_pick_problem`]), or the key of a+/// face column to delete. Given, `null` included, it must be one of them.+fn face_column<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {+ let v = Value::deserialize(d)?;+ match face_pick_problem(&v) {+ Some(problem) if !v.is_string() => Err(D::Error::custom(whole(problem))),+ _ => Ok(Some(v)),+ }+}++/// `config.configure`'s `face_appearances`: a list of faces to pick, each as for `config.column`.+/// A column key is refused here, as the handler refuses it.+fn face_picks<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<Value>>, D::Error> {+ let list = bounded_targets(Value::deserialize(d)?).map_err(D::Error::custom)?;+ if let Some(problem) = list.iter().find_map(face_pick_problem) {+ return Err(D::Error::custom(whole(problem)));+ }+ Ok(Some(list))+}++/// A face to pick, as `config.column` and `config.configure` read it.+fn face_pick_schema() -> Value {+ serde_json::json!({+ "description": "A face: `{body, point}` picks the face of the body (by name) at the point [x, y, z] (world, mm), which must be on a solid's face; or `{target}` gives a face column's target as `config.table` lists it.",+ "type": "object",+ "anyOf": [{"required": ["target"]}, {"required": ["body", "point"]}],+ "properties": {+ "body": {"type": "string"},+ "point": {"type": "array", "items": {"type": "number"}, "minItems": 3, "maxItems": 3},+ "target": {"type": "object"}+ }+ })+}++fn face_column_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A face, whose look each row sets; to delete its column (with `delete`), the column's key as `config.table` lists it.",+ "anyOf": [face_pick_schema(), {"type": "string"}]+ })+}++fn face_picks_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"type": "array", "items": face_pick_schema(), "maxItems": MAX_COLUMNS})+}++/// `param`, `feature`, `material` and `appearance` for `config.column`: a name. Given, `null`+/// included, anything but text gets the handler's message, as it reads the key as absent and+/// then finds no target.+fn target_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ match Value::deserialize(d)? {+ Value::String(name) => Ok(Some(name)),+ _ => Err(D::Error::custom(whole("give `param` or `feature`"))),+ }+}++/// `config.column` takes exactly one target, as the handler counts them. (A target given as+/// `null` counts, and its reader refuses it.)+fn exactly_one_target(schema: &mut Schema) {+ let one: Vec<Value> = ["param", "feature", "material", "appearance", "component_appearance", "face_appearance"]+ .iter()+ .map(|key| serde_json::json!({"required": [key]}))+ .collect();+ schema.insert("oneOf".into(), Value::Array(one));+}++/// A row's name as `config.row` reads `name`: text that, without spaces at either end, is 1 to+/// 128 bytes, with the handler's message for anything else.+fn row_name<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {+ match Value::deserialize(d)? {+ Value::String(name) if is_row_name(&name) => Ok(name),+ _ => Err(D::Error::custom(whole("`name` is required"))),+ }+}++fn is_row_name(name: &str) -> bool {+ let name = name.trim();+ !name.is_empty() && name.len() <= 128+}++/// `rename`: given, `null` included, it must be a row name ([`row_name`]), with the handler's+/// message.+fn rename<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ match Value::deserialize(d)? {+ Value::String(name) if is_row_name(&name) => Ok(Some(name)),+ _ => Err(D::Error::custom(whole("rename requires an existing row and a nonempty name up to 128 bytes"))),+ }+}++/// The column-key prefixes whose cells take a look given as an object.+const LOOK_COLUMNS: [&str; 3] = ["appearance:", "component_appearance:", "face_appearance:"];++/// `values`: an object of cells by column key, as `config.row` reads it. Each cell is text (an+/// expression, a material's or a look's name), true or false, or a number, and for a look+/// column also an object; at most 4096 bytes as the cell saves it. Given, `null` included, it+/// must be an object.+fn row_values<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Map<String, Value>>, D::Error> {+ let Value::Object(cells) = Value::deserialize(d)? else {+ return Err(D::Error::custom(whole("`values` must map columns to values")));+ };+ for (key, v) in &cells {+ let saved = match v {+ Value::String(text) => text.len(),+ Value::Bool(b) => b.to_string().len(),+ Value::Number(n) => n.to_string().len(),+ Value::Object(_) if LOOK_COLUMNS.iter().any(|prefix| key.starts_with(prefix)) => {+ serde_json::to_string(v).map_err(D::Error::custom)?.len()+ }+ _ => return Err(D::Error::custom(whole(format!("value for `{key}` must be an expression or true/false")))),+ };+ if saved > 4096 {+ return Err(D::Error::custom(whole("value too long")));+ }+ }+ Ok(Some(cells))+}++fn row_values_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "Cells to set, by column key as `config.table` lists it (`param:W`, `suppress:Block`, `material:Body1`…), or by a parameter's or a suppressed feature's name. A cell is an expression for a parameter, true or false (suppressed) for a feature, a material's name for a material column, and a look's name or a look object for a look column; at most 4096 bytes. Each key must be a column the table has.",+ "type": "object",+ "additionalProperties": {"type": ["string", "boolean", "number", "object"]}+ })+}++/// A configuration rule, as `config.rule` takes it and `config.table` lists it. The handler+/// checks it (`validate_rules_json`, then the doc crate's own reading), so only the schema says+/// what it holds.+fn rule_value_schema() -> Value {+ let text = |description: &str| serde_json::json!({"description": description, "type": "string", "minLength": 1, "maxLength": 4096});+ let parameter = serde_json::json!({"description": "A parameter, by name.", "type": "string", "minLength": 1, "maxLength": 64});+ let feature = serde_json::json!({"description": "A feature, by id.", "type": "integer", "minimum": 0});+ let effect = |kind: &str, fields: Value, required: &[&str]| {+ let mut properties = serde_json::json!({"type": {"enum": [kind]}});+ if let (Some(all), Some(more)) = (properties.as_object_mut(), fields.as_object()) {+ all.extend(more.clone());+ }+ let mut required: Vec<&str> = required.to_vec();+ required.insert(0, "type");+ serde_json::json!({"type": "object", "required": required, "properties": properties, "additionalProperties": false})+ };+ serde_json::json!({+ "type": "object",+ "required": ["id", "name", "condition", "effect"],+ "additionalProperties": false,+ "properties": {+ "id": {"description": "The rule's id: 1 to 64 characters, not only spaces. A rule with an id the table has replaces it.", "type": "string", "minLength": 1, "maxLength": 64},+ "name": {"description": "A name to show: 1 to 128 characters, not only spaces.", "type": "string", "minLength": 1, "maxLength": 128},+ "enabled": {"description": "Whether the rule runs. Default: true.", "type": "boolean"},+ "length_unit": {"description": "The unit of plain numbers in the rule's length expressions. Default: the replaced rule's, or the design's unit.", "enum": ["mm", "cm", "m", "in", "ft"]},+ "condition": {+ "description": "When the rule applies, by `type`: `always`; `all` or `any` of `conditions` (1 to 64); `not` (`condition`); `parameter`, a parameter compared (`operator`) with an `expression`; or `suppression`, whether a feature (`feature`, by id) is suppressed (`value`). At most 64 conditions, 8 deep.",+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {"enum": ["always", "all", "any", "not", "parameter", "suppression"]},+ "conditions": {"type": "array", "items": {"type": "object"}, "minItems": 1, "maxItems": 64},+ "condition": {"type": "object"},+ "parameter": parameter,+ "operator": {"enum": ["eq", "ne", "lt", "le", "gt", "ge"]},+ "expression": text("An expression the parameter is compared with."),+ "feature": feature,+ "value": {"type": "boolean"}+ }+ },+ "effect": {+ "description": "What the rule does when its condition holds, by `type`: `drive_parameter` sets a parameter to an `expression`; `drive_suppression` suppresses a feature (`value` true) or not; `parameter_range` keeps a parameter from `minimum` to `maximum`; `allow_parameter_values` allows only the values of `expressions` (1 to 128).",+ "anyOf": [+ effect("drive_parameter", serde_json::json!({"parameter": parameter, "expression": text("The parameter's value.")}), &["parameter", "expression"]),+ effect("drive_suppression", serde_json::json!({"feature": feature, "value": {"type": "boolean"}}), &["feature", "value"]),+ effect("parameter_range", serde_json::json!({"parameter": parameter, "minimum": text("The lowest value."), "maximum": text("The highest value.")}), &["parameter", "minimum", "maximum"]),+ effect("allow_parameter_values", serde_json::json!({"parameter": parameter, "expressions": {"type": "array", "items": text("An allowed value."), "minItems": 1, "maxItems": 128}}), &["parameter", "expressions"])+ ]+ }+ }+ })+}++fn rule_schema(_: &mut SchemaGenerator) -> Schema {+ let mut rule = rule_value_schema();+ if let Some(rule) = rule.as_object_mut() {+ rule.insert("description".into(), "A rule to add, or to replace the rule with its id.".into());+ }+ Schema::try_from(rule).unwrap_or_default()+}++/// `rules`: given, `null` included, a list of at most 2048 rules, with the handler's messages.+/// The handler checks each rule.+fn rule_list<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<Value>>, D::Error> {+ match Value::deserialize(d)? {+ Value::Array(list) if list.len() > MAX_RULES => Err(D::Error::custom(whole("too many rules"))),+ Value::Array(list) => Ok(Some(list)),+ _ => Err(D::Error::custom(whole("`rules` is a list of rules"))),+ }+}++fn rule_list_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"type": "array", "items": rule_value_schema(), "maxItems": MAX_RULES})+}++/// `id`: text; `null` is left out, as the handler reads it. Anything else gets the message the+/// handler gives when it finds no `rule`, `rules` or `id`.+fn rule_id<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ Value::String(id) => Ok(Some(id)),+ _ => Err(D::Error::custom(whole("give rule, rules or id"))),+ }+}++/// `index`: given, `null` included, a whole number of 0 or more, with the handler's message.+fn rule_index<'de, D: Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {+ Value::deserialize(d)?.as_u64().map(Some).ok_or_else(|| D::Error::custom(whole("valid index required")))+}+/// The configuration table, as `config.table` and `config.rules` return it and an activation/// returns it after the switch.#[derive(Debug, Serialize, JsonSchema)]diff --git a/crates/engine/src/schema/config_tests.rs b/crates/engine/src/schema/config_tests.rsindex 2adf132d95..43f828a661 100644--- a/crates/engine/src/schema/config_tests.rs+++ b/crates/engine/src/schema/config_tests.rs@@ -1,6 +1,9 @@use serde_json::{Value, json};-use super::{ConfigActivation, ConfigRowParams, ConfigTableParams, ConfigTableReply};+use super::{+ ConfigActivation, ConfigColumnParams, ConfigConfigureParams, ConfigRowEditParams, ConfigRowParams, ConfigRuleParams, ConfigTableParams,+ ConfigTableReply,+};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};@@ -23,6 +26,16 @@ fn configured(s: &mut Session) {fn schemas_and_the_key_check_agree() {assert_keys(input_schema_for::<ConfigTableParams>(), &[]);assert_keys(input_schema_for::<ConfigRowParams>(), &["row"]);+ assert_keys(+ input_schema_for::<ConfigConfigureParams>(),+ &["appearances", "component_appearances", "face_appearances", "features", "materials", "params"],+ );+ assert_keys(+ input_schema_for::<ConfigColumnParams>(),+ &["appearance", "component_appearance", "delete", "face_appearance", "feature", "material", "param"],+ );+ assert_keys(input_schema_for::<ConfigRowEditParams>(), &["delete", "from", "name", "rename", "values"]);+ assert_keys(input_schema_for::<ConfigRuleParams>(), &["delete", "id", "index", "rule", "rules"]);}#[test]@@ -31,9 +44,108 @@ fn strict_keeps_todays_errors() {("config.activate", json!({})),("config.activate", json!({"row": 5})),("config.activate", json!({"row": "Nope"})),+ ("config.configure", json!({"params": 5})),+ ("config.configure", json!({"params": ["W", 1]})),+ ("config.configure", json!({"params": "Nope"})),+ ("config.configure", json!({"features": {"Block": true}})),+ ("config.configure", json!({"materials": ["Nope"]})),+ ("config.configure", json!({"component_appearances": null})),+ ("config.configure", json!({"component_appearances": [true]})),+ ("config.configure", json!({"component_appearances": ["Nope"]})),+ ("config.configure", json!({"face_appearances": ["appearance:A"]})),+ ("config.configure", json!({"face_appearances": [{"body": "A"}]})),+ ("config.configure", json!({"face_appearances": [{"body": "Nope", "point": [0, 0, 0]}]})),+ ("config.column", json!({})),+ ("config.column", json!({"param": "W", "feature": "Block"})),+ ("config.column", json!({"param": 5})),+ ("config.column", json!({"param": null})),+ ("config.column", json!({"material": 5})),+ ("config.column", json!({"param": "Nope"})),+ ("config.column", json!({"feature": "Nope"})),+ ("config.column", json!({"component_appearance": -1})),+ ("config.column", json!({"face_appearance": 5})),+ ("config.column", json!({"face_appearance": {"body": "A", "point": [0, 0]}})),+ ("config.column", json!({"face_appearance": "face_appearance:A"})),+ ("config.column", json!({"face_appearance": "face_appearance:A", "delete": true})),+ ("config.row", json!({})),+ ("config.row", json!({"name": 5})),+ ("config.row", json!({"name": " "})),+ ("config.row", json!({"name": "R".repeat(129)})),+ ("config.row", json!({"name": "R", "values": 5})),+ ("config.row", json!({"name": "R", "values": null})),+ ("config.row", json!({"name": "R", "values": {"param:W": []}})),+ ("config.row", json!({"name": "R", "values": {"param:W": {"r": 1}}})),+ ("config.row", json!({"name": "R", "values": {"param:W": "1".repeat(4097)}})),+ ("config.row", json!({"name": "R", "values": {"param:W": "1"}})),+ ("config.row", json!({"name": "R", "from": "Nope"})),+ ("config.row", json!({"name": "R", "rename": null})),+ ("config.row", json!({"name": "R", "rename": "S"})),+ ("config.row", json!({"name": "R", "delete": true})),+ ("config.rule", json!({})),+ ("config.rule", json!({"id": 5})),+ ("config.rule", json!({"id": "r1"})),+ ("config.rule", json!({"rules": 5})),+ ("config.rule", json!({"rules": null})),+ ("config.rule", json!({"rules": vec![json!({}); 2049]})),+ ("config.rule", json!({"rule": 5})),+ ("config.rule", json!({"rule": null})),+ ("config.rule", json!({"rule": always("r1", "W", "1")})),]);}+/// A rule `id` that always drives the parameter `parameter` to `expression`.+fn always(id: &str, parameter: &str, expression: &str) -> Value {+ json!({"id": id, "name": id, "condition": {"type": "always"}, "effect": {"type": "drive_parameter", "parameter": parameter, "expression": expression}})+}++/// Moving a rule reads `index` only once the rule is found, so these calls need a design with+/// one.+#[test]+fn strict_keeps_the_rule_moves_errors() {+ for p in [json!({"id": "r1"}), json!({"id": "r1", "index": -1}), json!({"id": "r1", "index": "0"}), json!({"id": "r1", "index": 5})] {+ let error = |level: ParamCheck| {+ let mut s = Session::default();+ configured(&mut s);+ run(&mut s, "config.rule", json!({"rule": always("r1", "W", "15 mm")}));+ s.param_check = level;+ s.execute("config.rule", &p).err().map(|e| e.to_string())+ };+ let off = error(ParamCheck::Off);+ assert!(off.is_some(), "{p} should fail today");+ assert_eq!(error(ParamCheck::Strict), off, "{p}");+ }+}++/// #11895: each schema takes what its handler reads, and refuses what the handler refuses before+/// looking at the design: a list of names or one name, a column's one target, a face picked or+/// a face column's key, a row's cells and a rule.+#[test]+fn the_table_editing_schemas_take_what_the_handlers_read() {+ let check = |schema: schemars::Schema, p: Value, takes: bool| {+ let schema = schema.as_value();+ assert_eq!(conforms(schema, schema, &p), takes, "{p}");+ };+ check(input_schema_for::<ConfigConfigureParams>(), json!({"params": "W", "features": ["Block"], "materials": null}), true);+ check(input_schema_for::<ConfigConfigureParams>(), json!({"params": [1]}), false);+ check(input_schema_for::<ConfigConfigureParams>(), json!({"component_appearances": ["Arm", 3]}), true);+ check(input_schema_for::<ConfigConfigureParams>(), json!({"component_appearances": [-3]}), false);+ check(input_schema_for::<ConfigConfigureParams>(), json!({"face_appearances": [{"body": "A", "point": [0, 0, 5]}]}), true);+ check(input_schema_for::<ConfigConfigureParams>(), json!({"face_appearances": ["face_appearance:A"]}), false);+ check(input_schema_for::<ConfigColumnParams>(), json!({"face_appearance": "face_appearance:A", "delete": true}), true);+ check(input_schema_for::<ConfigColumnParams>(), json!({"param": null}), false);+ check(input_schema_for::<ConfigRowEditParams>(), json!({"name": "R", "values": {"param:W": "20 mm", "suppress:Block": true}}), true);+ check(input_schema_for::<ConfigRowEditParams>(), json!({"values": {}}), false);+ check(input_schema_for::<ConfigRuleParams>(), json!({"rule": always("r1", "W", "1")}), true);+ check(input_schema_for::<ConfigRuleParams>(), json!({"rules": [always("r1", "W", "1"), {"id": "r2", "name": "r2"}]}), false);+ check(input_schema_for::<ConfigRuleParams>(), json!({"id": "r1", "index": 0}), true);+ check(input_schema_for::<ConfigRuleParams>(), json!({"id": "r1", "index": -1}), false);+ // The schema of `config.column` says that exactly one target is given (`conforms` doesn't+ // read `oneOf`).+ let column = input_schema_for::<ConfigColumnParams>();+ let one_of = column.as_value()["oneOf"].as_array().map(Vec::len);+ assert_eq!(one_of, Some(6), "{}", column.as_value());+}+/// A preview runs the activation, whose messages name `config.activate`, where strict names/// `config.preview`; the message after the name is the same.#[test]@@ -76,3 +188,41 @@ fn configuration_commands_reply_with_their_schemas() {matches(&table, &run(&mut s, "config.table", json!({"row": "Big"})), true);matches(&activation, &run(&mut s, "config.activate", json!({"row": "Default", "rows": 1})), true);}++/// #11895: configuring, a column added and deleted, a row added, edited, renamed and deleted,+/// and rules added, moved and deleted, each reply as `config.table` does, in Warn without+/// warnings; a misspelt key gets one.+#[test]+fn table_edits_reply_with_the_table() {+ let table = output_schema_for::<ConfigTableReply>();+ let schema = table.as_value();+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ run(&mut s, "parameters.add", json!({"name": "W", "expression": "10 mm"}));+ run(&mut s, "parameters.add", json!({"name": "H", "expression": "5 mm"}));+ run(&mut s, "solid.box", json!({"length": "W", "width": 10, "height": "H", "body_name": "A", "name": "Block"}));+ let mut edit = |id: &str, p: Value, warned: bool| {+ let r = run(&mut s, id, p);+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");+ assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");+ r+ };+ let r = edit("config.configure", json!({"params": "W", "features": ["Block"], "materials": null}), false);+ assert_eq!((r["active"].as_str(), r["columns"].as_array().map(Vec::len)), (Some("Default"), Some(2)), "{r}");+ edit("config.column", json!({"param": "H"}), false);+ edit("config.column", json!({"material": "A"}), false);+ let r = edit("config.column", json!({"material": "A", "delete": true}), false);+ assert_eq!(r["columns"].as_array().map(Vec::len), Some(3), "{r}");+ edit("config.row", json!({"name": "Big", "values": {"W": "20 mm", "suppress:Block": false}}), false);+ edit("config.row", json!({"name": "Bigger", "from": "Big", "values": {"param:H": "8 mm"}}), false);+ let r = edit("config.row", json!({"name": "Big", "rename": "Large"}), false);+ let rows: Vec<&str> = r["rows"].as_array().into_iter().flatten().filter_map(|row| row["name"].as_str()).collect();+ assert_eq!(rows, ["Default", "Large", "Bigger"], "{r}");+ edit("config.row", json!({"name": "Bigger", "delete": true}), false);+ edit("config.rule", json!({"rules": [always("r1", "H", "6 mm"), always("r2", "H", "7 mm")]}), false);+ let r = edit("config.rule", json!({"id": "r2", "index": 0}), false);+ assert_eq!((r["rules"][0]["id"].as_str(), r["rules"][1]["id"].as_str()), (Some("r2"), Some("r1")), "{r}");+ let r = edit("config.rule", json!({"id": "r1", "delete": true}), false);+ assert_eq!(r["rules"].as_array().map(Vec::len), Some(1), "{r}");+ edit("config.row", json!({"name": "Default", "valuse": {"W": "12 mm"}}), true);+ edit("config.column", json!({"param": "W", "delet": true}), true);+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex be6b92633e..3b317f3123 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -39,10 +39,6 @@ component.replace_with_linkcomponent.revert_positioncomponent.unlockcomponent.update_links-config.column-config.configure-config.row-config.rulecontact.checkcontact.createcontact.disable_all