SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Copy and Paste Features, Add Recorded Feature and Export Command Script describe their exact parameters and reply (#12502) (#12595)
PeppaWutz7a2f2949a7c4
diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rsindex 7fc75dbb2e..310606c93c 100644--- a/crates/engine/src/cmd/clipboard.rs+++ b/crates/engine/src/cmd/clipboard.rs@@ -4,37 +4,70 @@use std::collections::BTreeMap;-use serde_json::{Value, json};+use serde_json::Value;use solidcraft_doc::{FeatureKind, PlaneRef};use super::CommandSpec;use crate::params::{bad, name_or_id_values, vec3};+use crate::schema::timeline_clipboard::{CopyParams, CopyResult, PasteError, PasteParams, PasteResult, Pasted};+use crate::schema::{TypedContract, output_schema_for};use crate::{Result, Session};+const COPY_CONTRACT: TypedContract<CopyParams> = TypedContract::new();+const PASTE_CONTRACT: TypedContract<PasteParams> = TypedContract::new();+pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("timeline.copy", "Copy Features", copy).icon("copy").noundo().params("features: [ids or names] (in timeline order on paste)"),- CommandSpec::new("timeline.paste", "Paste Features", paste).icon("paste").params(- "translate?: [x,y,z] (moves the copies' geometry); component?: where the copies go (default: the active one), \+ CommandSpec::new("timeline.copy", "Copy Features", crate::checked!("timeline.copy", copy))+ .icon("copy")+ .noundo()+ .contract(©_CONTRACT)+ .output(output_schema_for::<CopyResult>)+ .params("features: [ids or names] (in timeline order on paste)"),+ CommandSpec::new("timeline.paste", "Paste Features", crate::checked!("timeline.paste", paste))+ .icon("paste")+ .contract(&PASTE_CONTRACT)+ .output(output_schema_for::<PasteResult>)+ .params(+ "translate?: [x,y,z] (moves the copies' geometry); component?: where the copies go (default: the active one), \component_path?: its placement (default: the active one, else its only one); the copies go at the marker, each where \its original is in the world (copies into their own component keep its coordinates); body transfers are left out; \from_design?: true to paste sketch features from the host's cross-design clipboard snapshot",- ),+ ),];-fn copy(s: &mut Session, p: &Value) -> Result<Value> {+/// A command's reply as JSON: they build their replies from the types their output schemas+/// describe, so the two can't drift apart.+fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))+}++/// The `features` of `timeline.copy`: named or numbered, both kinds in one list, 1…1000 of them.+/// The reader the command's contract uses too.+pub(crate) fn copy_keys(p: &Value) -> Result<&[Value]> {let cmd = "timeline.copy";- // The features are named or numbered, and both kinds can sit in one list.let keys = name_or_id_values(cmd, p, "features")?;if keys.is_empty() || keys.len() > 1000 {return Err(bad(cmd, "`features` must list 1…1000 features"));}+ Ok(keys)+}++/// A `component_path` of `timeline.paste`: 0 to 64 occurrence ids. The reader both pastes and the+/// command's contract use.+pub(crate) fn component_path_form(v: &Value) -> Option<Vec<u64>> {+ v.as_array().filter(|a| a.len() <= 64).and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())+}++fn copy(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "timeline.copy";+ let keys = copy_keys(p)?;let ids = keys.iter().map(|key| super::edit::feature_id(s, Some(key), cmd)).collect::<Result<Vec<_>>>()?;// Keep timeline order so sketches come before the features that use them.let copied: Vec<solidcraft_doc::Feature> = s.doc.features.iter().filter(|f| ids.contains(&f.id)).cloned().collect();let names: Vec<String> = copied.iter().map(|f| f.name.clone()).collect();s.clipboard = copied;s.foreign_copy = Some(std::sync::Arc::new(crate::ForeignCopy::of_features(s)));- Ok(json!({"copied": names}))+ reply(cmd, CopyResult { copied: names, param_warnings: Vec::new() })}/// Origin planes become explicit planes so a translation can move them.@@ -86,12 +119,7 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {};let given_path = match p.get("component_path") {None => None,- Some(v) => Some(- v.as_array()- .filter(|a| a.len() <= 64)- .and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())- .ok_or_else(|| bad(cmd, "`component_path` must list 0..64 occurrence ids"))?,- ),+ Some(v) => Some(component_path_form(v).ok_or_else(|| bad(cmd, "`component_path` must list 0..64 occurrence ids"))?),};let mut sketches: BTreeMap<u64, u64> = BTreeMap::new();let mut bodies: BTreeMap<String, String> = BTreeMap::new();@@ -230,15 +258,15 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {let new_name = doc.feature(id).map(|x| x.name.clone()).unwrap_or_default();sketches.insert(f.id, id);names.insert(f.name.clone(), new_name.clone());- made.push(json!({"id": id, "name": new_name, "from": f.name}));+ made.push(Pasted { id, name: new_name, from: f.name.clone() });}s.refresh();- let errors: Vec<Value> = made+ let errors: Vec<PasteError> = made.iter()- .filter_map(|m| m["id"].as_u64())- .filter_map(|id| s.model.result(id).and_then(|r| r.error.clone()).map(|e| json!({"feature": id, "error": e})))+ .map(|m| m.id)+ .filter_map(|id| s.model.result(id).and_then(|r| r.error.clone()).map(|error| PasteError { feature: id, error })).collect();- Ok(json!({"pasted": made, "errors": errors, "notices":notices}))+ reply(cmd, PasteResult { pasted: made, errors, notices, param_warnings: Vec::new() })}#[cfg(test)]diff --git a/crates/engine/src/cmd/clipboard_foreign.rs b/crates/engine/src/cmd/clipboard_foreign.rsindex c69124a9fc..b2043eedd6 100644--- a/crates/engine/src/cmd/clipboard_foreign.rs+++ b/crates/engine/src/cmd/clipboard_foreign.rs@@ -2,10 +2,11 @@use std::collections::{BTreeMap, BTreeSet};-use serde_json::{Value, json};+use serde_json::Value;use solidcraft_doc::{Document, Feature, FeatureKind, Mat, PlaneRef};use crate::params::{bad, vec3};+use crate::schema::timeline_clipboard::{PasteResult, Pasted};use crate::{Result, Sel, Session};const CMD: &str = "timeline.paste";@@ -186,11 +187,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {}};let path = match p.get("component_path") {- Some(v) => v- .as_array()- .filter(|a| a.len() <= 64)- .and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())- .ok_or_else(|| bad(CMD, "`component_path` must list 0..64 occurrence ids"))?,+ Some(v) => super::clipboard::component_path_form(v).ok_or_else(|| bad(CMD, "`component_path` must list 0..64 occurrence ids"))?,None if component == s.active_component => s.active_occurrence_path.clone().unwrap_or_else(|| s.doc.first_path(component)),None => super::component::placing::placement_of(s, &s.design_document(), component, None, "component_path", CMD)?.0,};@@ -249,7 +246,7 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {}ids.insert(feature.id, id);names.insert(feature.name.clone(), name.clone());- made.push(json!({"id": id, "name": name, "from": feature.name}));+ made.push(Pasted { id, name: name.clone(), from: feature.name.clone() });}parameters(scratch.doc_mut(), ©.doc, ©.features, &mut mapped)?;let source_values = copy.doc.param_values().0;@@ -307,5 +304,6 @@ pub(super) fn paste(s: &mut Session, p: &Value) -> Result<Value> {}scratch.selection = ids.values().map(|id| Sel::Feature { id: *id }).collect();s.accept_computed(scratch);- Ok(json!({"pasted": made, "errors": [], "notices": []}))+ serde_json::to_value(PasteResult { pasted: made, errors: Vec::new(), notices: Vec::new(), param_warnings: Vec::new() })+ .map_err(|e| bad(CMD, e.to_string()))}diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex af84b788d0..53002222d3 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -85,8 +85,10 @@ mod point_cloud;mod script;mod section;pub mod settings;+pub(crate) use clipboard::{component_path_form, copy_keys};pub(crate) use measure_sel::{measure_items, shape_of};pub(crate) use measure_shape::Shape;+pub(crate) use script::step_params;#[cfg(test)]mod kernel_heal_tests;mod panels;diff --git a/crates/engine/src/cmd/script.rs b/crates/engine/src/cmd/script.rsindex 24a4a13dcd..86b46fb8f2 100644--- a/crates/engine/src/cmd/script.rs+++ b/crates/engine/src/cmd/script.rs@@ -11,15 +11,30 @@ use solidcraft_doc::{Document, Feature, FeatureKind, Param, expr};use super::CommandSpec;use crate::params::{bad, str_};+use crate::schema::timeline_clipboard::{AddParams, AddResult, ExportScriptParams, ExportScriptResult, Script, ScriptAbout, ScriptStep};+use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};+const ADD_CONTRACT: TypedContract<AddParams> = TypedContract::new();+const EXPORT_SCRIPT_CONTRACT: TypedContract<ExportScriptParams> = TypedContract::new();+pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("timeline.add", "Add Recorded Feature", add).icon("new").params(+ CommandSpec::new("timeline.add", "Add Recorded Feature", crate::checked!("timeline.add", add))+ .icon("new")+ .contract(&ADD_CONTRACT)+ .output(output_schema_for::<AddResult>)+ .params("feature: a feature as the design file and timeline.inspect hold it ({type, name?, id?, …}; the name is kept even when another \feature has it, the id is kept and refused when another feature has it, so later steps can refer to them); params?: [{name, expression, unit?, comment?}] (the model parameters its sketch \dimensions use); the feature goes at the marker → feature, name, error, warning",),- CommandSpec::new("timeline.export_script", "Export Command Script", export_script).icon("export").noundo().doc_only().params(+ CommandSpec::new("timeline.export_script", "Export Command Script", crate::checked!("timeline.export_script", export_script))+ .icon("export")+ .noundo()+ .doc_only()+ .contract(&EXPORT_SCRIPT_CONTRACT)+ .output(output_schema_for::<ExportScriptResult>)+ .params("path?: write the script to this file → script: {commands: [...]} that rebuilds the design (solidcraft-cli eval/run), \steps, omitted: what the script leaves out (appearances, folders, views, configurations, print-face assignments); components and assemblies \are not supported yet",@@ -56,7 +71,14 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {s.refresh();let name = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();let r = s.model.result(id);- Ok(json!({"feature": id, "name": name, "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone())}))+ let reply = AddResult {+ feature: id,+ name,+ error: r.and_then(|r| r.error.clone()),+ warning: r.and_then(|r| r.warning.clone()),+ param_warnings: Vec::new(),+ };+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))}/// timeline.add keeps accepting legacy name-keyed pattern and mirror seeds and construction@@ -139,7 +161,8 @@ fn recorded_feature(cmd: &str, raw: &Map<String, Value>) -> Result<Feature> {Ok(f)}-fn step_params(cmd: &str, v: Option<&Value>) -> Result<Vec<Param>> {+/// The model parameters of a `timeline.add` step. The reader the command's contract uses too.+pub(crate) fn step_params(cmd: &str, v: Option<&Value>) -> Result<Vec<Param>> {let Some(v) = v.filter(|v| !v.is_null()) else { return Ok(Vec::new()) };let list = v.as_array().filter(|a| a.len() <= MAX_STEP_PARAMS).ok_or_else(|| bad(cmd, "`params` must be a list of parameters"))?;let text = |p: &Value, k: &str| match p.get(k) {@@ -164,15 +187,15 @@ fn export_script(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "timeline.export_script";let (commands, omitted) = script_steps(&s.doc)?;let steps = commands.len();- let script = json!({- "about": {- "design": s.doc.name,- "format": solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT),- "version": env!("CARGO_PKG_VERSION"),- "replay": "solidcraft-cli eval script.json (timeline.add steps need a build that reads this design format)",+ let script = Script {+ about: ScriptAbout {+ design: s.doc.name.clone(),+ format: solidcraft_doc::format::format_string(solidcraft_doc::format::FORMAT),+ replay: "solidcraft-cli eval script.json (timeline.add steps need a build that reads this design format)".into(),+ version: env!("CARGO_PKG_VERSION").into(),},- "commands": commands,- });+ commands,+ };let path = str_(p, "path");if let Some(path) = path {let text = serde_json::to_string_pretty(&script).map_err(|e| EngineError::Other(e.to_string()))?;@@ -180,11 +203,12 @@ fn export_script(s: &mut Session, p: &Value) -> Result<Value> {} else if p.get("path").is_some_and(|v| !v.is_null()) {return Err(bad(cmd, "`path` must be a file path"));}- Ok(json!({"script": script, "steps": steps, "omitted": omitted, "path": path}))+ let path = path.map(str::to_string);+ serde_json::to_value(ExportScriptResult { omitted, path, script, steps, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))}fn step(command: &str, params: Value) -> Value {- json!({"command": command, "params": params})+ serde_json::to_value(ScriptStep { command: command.to_string(), params }).unwrap_or_default()}fn not_supported(what: &str) -> EngineError {diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex b10567fe00..0f4f743eff 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -114,6 +114,7 @@ pub mod sketch_shapes;pub mod surface_analysis;pub mod surface_boundary;pub mod surface_match;+pub mod timeline_clipboard;pub mod ui_prefs;pub mod view_navigation;diff --git a/crates/engine/src/schema/timeline_clipboard.rs b/crates/engine/src/schema/timeline_clipboard.rsnew file mode 100644index 0000000000..2d8b55ddcf--- /dev/null+++ b/crates/engine/src/schema/timeline_clipboard.rs@@ -0,0 +1,426 @@+//! Contracts and result types for the commands in `cmd/clipboard.rs` and `cmd/script.rs`:+//! `timeline.copy`, `timeline.paste`, `timeline.add` and `timeline.export_script` (#12502).+//!+//! 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; where a reader is shared with the handler+//! (`copy_keys`, `component_path_form`, `step_params`) the type calls it. Whether a feature, a+//! component or a file exists stays the handler's to check. A key the handler refuses when it is+//! left out (`features`, `feature`) 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. A call with several+//! problems may get a different one first in strict than with the check off (the check goes key by+//! key, the handlers in their own order).++use std::borrow::Cow;++use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};+use serde::de::Error as _;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::{Map, Value, json};+use solidcore_record::Vec3;++use super::check::whole;+use super::component_link::ComponentRef;+use super::motion::require;+use super::types::not_blank_pattern;+use crate::EngineError;+use crate::params;++/// The most features one `timeline.copy` lists, as the handler reads them.+const MAX_COPY: usize = 1000;+/// The most occurrence ids in a `component_path`, as the handler reads them.+const MAX_PATH: usize = 64;++/// The message of a handler's refusal, to pass on as it is.+fn handler_message(e: EngineError) -> String {+ match e {+ EngineError::BadParams { msg, .. } => whole(msg),+ other => whole(other),+ }+}++// ---- timeline.copy ----++/// The features `timeline.copy` lists: one name, or a list of names and ids, in any mix.+#[derive(Clone, Debug, PartialEq)]+pub struct FeatureKeys(pub Vec<Value>);++impl<'de> Deserialize<'de> for FeatureKeys {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let wrapped = json!({ "features": Value::deserialize(d)? });+ crate::cmd::copy_keys(&wrapped).map(|keys| FeatureKeys(keys.to_vec())).map_err(|e| D::Error::custom(handler_message(e)))+ }+}++impl JsonSchema for FeatureKeys {+ fn schema_name() -> Cow<'static, str> {+ "FeatureKeys".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ let key = json!({"anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0}]});+ json_schema!({+ "description": "Features by name or id: one name, or a list of names and ids in any mix.",+ "anyOf": [+ {"type": "string"},+ {"type": "array", "items": key, "minItems": 1, "maxItems": MAX_COPY}+ ]+ })+ }+}++/// Copy features to the session's clipboard, and a snapshot of them for pasting into another+/// design. The features stay where they are; the clipboard replaces what was copied before. Not an+/// undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = features_required)]+pub struct CopyParams {+ // Optional in the type and required in the schema (`features_required`).+ /// The features to copy, by name or id: one name, or 1 to 1000 names and ids. Pasted in+ /// timeline order whatever the order given.+ #[serde(default, deserialize_with = "features", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "FeatureKeys")]+ pub features: Option<FeatureKeys>,+}++/// `features`, with the handler's message for anything else, `null` and an empty list included.+fn features<'de, D: Deserializer<'de>>(d: D) -> Result<Option<FeatureKeys>, D::Error> {+ FeatureKeys::deserialize(d).map(Some)+}++fn features_required(schema: &mut Schema) {+ require(schema, "features");+}++/// What `timeline.copy` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CopyResult {+ /// The names of the features copied, in timeline order.+ pub copied: 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>,+}++// ---- timeline.paste ----++/// A `translate` as `timeline.paste` reads it: `[x, y, z]` or `{x, y, z}` of numbers in mm, each+/// under 1e9 in size.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PasteTranslation(pub Vec3);++impl<'de> Deserialize<'de> for PasteTranslation {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::vec3(&Value::deserialize(d)?).map(PasteTranslation).ok_or_else(|| D::Error::custom(whole("`translate` must be [x, y, z]")))+ }+}++impl JsonSchema for PasteTranslation {+ fn schema_name() -> Cow<'static, str> {+ "PasteTranslation".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ let c = json!({"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9});+ json_schema!({+ "description": "A distance in mm, as [x, y, z] or {\"x\", \"y\", \"z\"}.",+ "anyOf": [+ {"type": "array", "items": c, "minItems": 3, "maxItems": 3},+ {"type": "object", "properties": {"x": c, "y": c, "z": c}, "required": ["x", "y", "z"]}+ ]+ })+ }+}++/// A `component_path` as `timeline.paste` reads it: 0 to 64 occurrence ids.+#[derive(Clone, Debug, PartialEq)]+pub struct PastePath(pub Vec<u64>);++impl<'de> Deserialize<'de> for PastePath {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ crate::cmd::component_path_form(&Value::deserialize(d)?)+ .map(PastePath)+ .ok_or_else(|| D::Error::custom(whole("`component_path` must list 0..64 occurrence ids")))+ }+}++impl JsonSchema for PastePath {+ fn schema_name() -> Cow<'static, str> {+ "PastePath".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "The occurrence ids from the top of the design down to a placement.",+ "type": "array",+ "items": {"type": "integer", "minimum": 0},+ "maxItems": MAX_PATH+ })+ }+}++fn paste_component<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ComponentRef>, D::Error> {+ match Value::deserialize(d)? {+ Value::Number(n) => Ok(Some(ComponentRef(n.to_string()))),+ Value::String(s) => Ok(Some(ComponentRef(s))),+ _ => Err(D::Error::custom(whole("`component` must be a component id or name"))),+ }+}++fn paste_path<'de, D: Deserializer<'de>>(d: D) -> Result<Option<PastePath>, D::Error> {+ PastePath::deserialize(d).map(Some)+}++fn paste_translate<'de, D: Deserializer<'de>>(d: D) -> Result<Option<PasteTranslation>, D::Error> {+ PasteTranslation::deserialize(d).map(Some)+}++/// `from_design` is true or false; `null` is refused, as the handler does.+fn from_design<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {+ match Value::deserialize(d)? {+ Value::Bool(b) => Ok(Some(b)),+ _ => Err(D::Error::custom(whole("`from_design` must be true or false"))),+ }+}++/// Paste the copied features as independent copies at the timeline marker: sketches get their own+/// dimension parameters, features their own names, and references inside the copied set point at+/// the copies. Body transfers are left out. One undo step. With `from_design`, only sketch+/// features are pasted, from the snapshot another design's copy left. Every key reads the same+/// either way.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct PasteParams {+ /// Move the copies' geometry by this much, in mm. Default: not moved.+ #[serde(default, deserialize_with = "paste_translate", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "PasteTranslation")]+ pub translate: Option<PasteTranslation>,+ /// The component the copies go into, by id or name. Default: the active one.+ #[serde(default, deserialize_with = "paste_component", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ComponentRef")]+ pub component: Option<ComponentRef>,+ /// The placement of that component the copies are authored in, as occurrence ids. Default: the+ /// active placement for the active component, else the component's only placement.+ #[serde(default, deserialize_with = "paste_path", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "PastePath")]+ pub component_path: Option<PastePath>,+ /// True pastes the sketch features of the clipboard snapshot of another design, with their+ /// parameters. Default: false, the features copied in this design.+ #[serde(default, deserialize_with = "from_design", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "bool")]+ pub from_design: Option<bool>,+}++/// A feature a paste made.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Pasted {+ /// The new feature, by id.+ pub id: u64,+ /// Its name.+ pub name: String,+ /// The name of the feature it is a copy of.+ pub from: String,+}++/// A pasted feature that did not rebuild.+#[derive(Debug, Serialize, JsonSchema)]+pub struct PasteError {+ /// The pasted feature, by id.+ pub feature: u64,+ /// Why it did not rebuild.+ pub error: String,+}++/// What `timeline.paste` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct PasteResult {+ /// The features made, in timeline order.+ pub pasted: Vec<Pasted>,+ /// The pasted features that did not rebuild.+ pub errors: Vec<PasteError>,+ /// What the paste left out or kept (body transfers, external face attachments).+ pub notices: 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>,+}++// ---- timeline.add ----++/// The `feature` of `timeline.add`: an object, as a design file or `timeline.inspect` holds a+/// feature.+#[derive(Clone, Debug, PartialEq)]+pub struct RecordedFeature(pub Map<String, Value>);++impl<'de> Deserialize<'de> for RecordedFeature {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::Object(o) => Ok(RecordedFeature(o)),+ _ => Err(D::Error::custom(whole("`feature` must be a feature object, as a design file or timeline.inspect has it"))),+ }+ }+}++impl JsonSchema for RecordedFeature {+ fn schema_name() -> Cow<'static, str> {+ "RecordedFeature".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A feature as the design file and timeline.inspect hold it: {type, name?, id?, …}. \+ The name is kept even when another feature has it; the id is kept, and refused when another \+ feature has it. Whether the rest is a feature is the command's to check.",+ "type": "object"+ })+ }+}++/// The model parameters of `timeline.add`: read by the handler's own reader.+#[derive(Clone, Debug)]+pub struct StepParams(pub Vec<solidcraft_doc::Param>);++impl<'de> Deserialize<'de> for StepParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let value = Value::deserialize(d)?;+ crate::cmd::step_params("timeline.add", Some(&value)).map(StepParams).map_err(|e| D::Error::custom(handler_message(e)))+ }+}++impl JsonSchema for StepParams {+ fn schema_name() -> Cow<'static, str> {+ "StepParams".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ let text = json!({"type": ["string", "null"]});+ json_schema!({+ "description": "Model parameters the feature's sketch dimensions use.",+ "type": "array",+ "maxItems": solidcraft_sketch::MAX_CONSTRAINTS,+ "items": {+ "type": "object",+ "properties": {+ "name": {"type": "string", "description": "The parameter's name."},+ "expression": {+ "description": "Its value: a number or an expression that is not blank.",+ "anyOf": [{"type": "string", "pattern": not_blank_pattern()}, {"type": "number"}]+ },+ "unit": text.clone(),+ "comment": text+ },+ "required": ["name", "expression"]+ }+ })+ }+}++fn recorded<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RecordedFeature>, D::Error> {+ RecordedFeature::deserialize(d).map(Some)+}++fn feature_required(schema: &mut Schema) {+ require(schema, "feature");+}++/// Append one recorded feature to the timeline, as the design file holds it, so every feature+/// kind replays exactly: the same ids, names, parameter names and stored edge and face names (the+/// steps `timeline.export_script` writes). It goes at the timeline marker. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = feature_required)]+pub struct AddParams {+ // Optional in the type and required in the schema (`feature_required`).+ /// The feature, as a design file or `timeline.inspect` has it.+ #[serde(default, deserialize_with = "recorded", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "RecordedFeature")]+ pub feature: Option<RecordedFeature>,+ /// The model parameters its sketch dimensions use, each {name, expression, unit?, comment?}.+ /// Default: none.+ #[serde(default)]+ #[schemars(with = "StepParams")]+ pub params: Option<StepParams>,+}++/// What `timeline.add` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct AddResult {+ /// The new feature, by id.+ pub feature: u64,+ /// Its name.+ pub name: String,+ /// Why it did not build, or null.+ pub error: Option<String>,+ /// A warning from building it, or null.+ pub warning: Option<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>,+}++// ---- timeline.export_script ----++fn script_path<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {+ match Value::deserialize(d)? {+ Value::Null => Ok(None),+ Value::String(s) => Ok(Some(s)),+ _ => Err(D::Error::custom(whole("`path` must be a file path"))),+ }+}++/// Write the design's history as a command script that rebuilds it (`solidcraft-cli eval` and+/// `run` replay it): one step per setting and feature, and a list of what the script leaves out.+/// A design with components or joints is refused for now. The design is not changed.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ExportScriptParams {+ /// A file to write the script to, as JSON. Default: none, the script is only returned.+ #[serde(default, deserialize_with = "script_path", skip_serializing_if = "Option::is_none")]+ pub path: Option<String>,+}++/// One step of a command script.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ScriptStep {+ /// The command the step runs.+ pub command: String,+ /// Its parameters.+ pub params: Value,+}++/// Where a script came from and how to replay it. Fields stay in alphabetical order: a script file+/// is written from this type, and its keys have always been sorted.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ScriptAbout {+ /// The design's name.+ pub design: String,+ /// The design file format the `timeline.add` steps hold features in.+ pub format: String,+ /// How to replay the script.+ pub replay: String,+ /// The version of SolidCraft that wrote it.+ pub version: String,+}++/// A command script. Fields stay in alphabetical order (see [`ScriptAbout`]).+#[derive(Debug, Serialize, JsonSchema)]+pub struct Script {+ pub about: ScriptAbout,+ /// The steps that rebuild the design on an empty one.+ #[schemars(with = "Vec<ScriptStep>")]+ pub commands: Vec<Value>,+}++/// What `timeline.export_script` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ExportScriptResult {+ /// What the script leaves out (appearances, folders, views, configurations, print-face+ /// assignments…).+ pub omitted: Vec<String>,+ /// The file written, or null.+ pub path: Option<String>,+ /// The script.+ pub script: Script,+ /// How many steps it has.+ pub steps: usize,+ /// 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>,+}++#[cfg(test)]+#[path = "timeline_clipboard_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/timeline_clipboard_tests.rs b/crates/engine/src/schema/timeline_clipboard_tests.rsnew file mode 100644index 0000000000..c0e3739db0--- /dev/null+++ b/crates/engine/src/schema/timeline_clipboard_tests.rs@@ -0,0 +1,410 @@+use serde_json::{Value, json};++use super::{AddParams, AddResult, CopyParams, CopyResult, ExportScriptParams, ExportScriptResult, PasteParams, PasteResult};+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};++fn warn_session() -> Session {+ Session { param_check: ParamCheck::Warn, ..Session::default() }+}++fn run(s: &mut Session, id: &str, p: Value) -> Value {+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))+}++/// A dimensioned sketch named S, extruded into Body, for the commands to work on.+fn plate(s: &mut Session) {+ run(s, "parameters.change", json!({"name": "base", "expression": "5 mm"}));+ run(s, "sketch.create", json!({"plane": "XY", "name": "S"}));+ run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]}));+ run(s, "sketch.constraint.coincident", json!({"a": "p1", "b": "origin"}));+ run(s, "sketch.dimension", json!({"entities": ["l1"], "value": "base * 4"}));+ run(s, "sketch.finish", json!({}));+ run(s, "solid.extrude", json!({"sketch": "S", "distance": 5, "name": "E"}));+}++fn matches(schema: schemars::Schema, id: &str, reply: &Value) {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");+ assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");+}++fn issues(id: &str, p: Value) -> Vec<String> {+ crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()+}++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<CopyParams>(), &["features"]);+ assert_keys(input_schema_for::<PasteParams>(), &["component", "component_path", "from_design", "translate"]);+ assert_keys(input_schema_for::<AddParams>(), &["feature", "params"]);+ assert_keys(input_schema_for::<ExportScriptParams>(), &["path"]);+}++/// Strict gives the handlers' own messages for what they already refuse (a missing `features` or+/// `feature` included: the handlers' words, not "is required").+#[test]+fn strict_keeps_todays_errors() {+ let key = |k: Value| json!({"feature": {"type": "box", "length": "1", "width": "1", "height": "1", "corner": [0, 0, 0]}, "params": k});+ assert_strict_keeps_todays_errors(&[+ ("timeline.copy", json!({})),+ ("timeline.copy", json!({"features": null})),+ ("timeline.copy", json!({"features": []})),+ ("timeline.copy", json!({"features": 3})),+ ("timeline.copy", json!({"features": true})),+ ("timeline.copy", json!({"features": [true]})),+ ("timeline.copy", json!({"features": ["S", -1]})),+ ("timeline.copy", json!({"features": ["S", 1.5]})),+ ("timeline.copy", json!({"features": vec!["S"; 1001]})),+ ("timeline.copy", json!({"features": vec!["S"; 10_001]})),+ ("timeline.copy", json!({"features": ["Nope"]})),+ ("timeline.paste", json!({"from_design": null})),+ ("timeline.paste", json!({"from_design": 1})),+ ("timeline.paste", json!({"from_design": "true"})),+ ("timeline.add", json!({})),+ ("timeline.add", json!({"feature": null})),+ ("timeline.add", json!({"feature": [1, 2, 3]})),+ ("timeline.add", json!({"feature": "box"})),+ ("timeline.add", key(json!("q"))),+ ("timeline.add", key(json!({"name": "q"}))),+ ("timeline.add", key(json!(vec![json!({"name": "q", "expression": "1"}); 40_001]))),+ ("timeline.add", key(json!([1]))),+ ("timeline.add", key(json!([{"expression": "1"}]))),+ ("timeline.add", key(json!([{"name": 4, "expression": "1"}]))),+ ("timeline.add", key(json!([{"name": "q"}]))),+ ("timeline.add", key(json!([{"name": "q", "expression": " "}]))),+ ("timeline.add", key(json!([{"name": "q", "expression": true}]))),+ ("timeline.add", key(json!([{"name": "q", "expression": "1", "unit": 3}]))),+ ("timeline.add", key(json!([{"name": "q", "expression": "1", "comment": []}]))),+ ("timeline.export_script", json!({"path": 7})),+ ("timeline.export_script", json!({"path": true})),+ ("timeline.export_script", json!({"path": ["a"]})),+ ]);+}++/// A paste with something to paste (in this design, or from another one): strict gives the+/// handler's message for each key it refuses. Without anything copied the handler says so before+/// it reads the other keys.+#[test]+fn paste_strict_keeps_todays_errors() {+ let mut source = Session::default();+ plate(&mut source);+ run(&mut source, "timeline.copy", json!({"features": ["S"]}));+ let cases = [+ json!({"translate": [1, 2]}),+ json!({"translate": null}),+ json!({"translate": "1,2,3"}),+ json!({"translate": [1e9, 0, 0]}),+ json!({"component": true}),+ json!({"component": null}),+ json!({"component_path": "0"}),+ json!({"component_path": null}),+ json!({"component_path": [-1]}),+ json!({"component_path": vec![0; 65]}),+ ];+ for design in [false, true] {+ for case in &cases {+ let mut p = case.clone();+ p["from_design"] = json!(design);+ let error = |level: ParamCheck| {+ let mut s = Session { param_check: level, ..Session::default() };+ plate(&mut s);+ s.foreign_copy = source.foreign_copy.clone();+ run(&mut s, "timeline.copy", json!({"features": ["S"]}));+ s.foreign_copy = source.foreign_copy.clone();+ s.execute("timeline.paste", &p).err().map(|e| e.to_string())+ };+ let off = error(ParamCheck::Off);+ assert!(off.is_some_and(|e| !e.contains("nothing copied")), "{p} should fail on the key");+ assert_eq!(error(ParamCheck::Strict), error(ParamCheck::Off), "{p}");+ }+ }+}++/// The types read each key as the handlers do: what the handler's reader takes the type takes,+/// and a refusal has the handler's message.+#[test]+fn the_types_read_each_key_as_the_handlers_do() {+ let ok = |id: &str, p: Value| assert_eq!(issues(id, p.clone()), Vec::<String>::new(), "{p}");+ let refused = |id: &str, p: Value, message: &str| assert_eq!(issues(id, p.clone()), [message], "{p}");++ // timeline.copy: a name, or names and ids in any mix; null is not absent.+ ok("timeline.copy", json!({"features": "S"}));+ ok("timeline.copy", json!({"features": ["S", 3, "E"]}));+ ok("timeline.copy", json!({"features": vec!["S"; 1000]}));+ refused("timeline.copy", json!({"features": []}), "`features` must list 1…1000 features");+ refused("timeline.copy", json!({"features": null}), "`features` must list 1…1000 features");+ refused("timeline.copy", json!({"features": vec!["S"; 1001]}), "`features` must list 1…1000 features");+ refused("timeline.copy", json!({"features": 3}), "`features` must be a list of names or ids; it is 3");+ refused("timeline.copy", json!({"features": ["S", true]}), "`features` must list names or ids; the entry 2 is true");++ // timeline.paste: the same keys with or without from_design.+ for design in [json!({}), json!({"from_design": false}), json!({"from_design": true})] {+ let with = |k: &str, v: Value| {+ let mut p = design.clone();+ p[k] = v;+ p+ };+ ok("timeline.paste", design.clone());+ ok("timeline.paste", with("translate", json!([1, 2.5, -3])));+ ok("timeline.paste", with("translate", json!({"x": 1, "y": 2, "z": 3})));+ ok("timeline.paste", with("component", json!("Plate")));+ ok("timeline.paste", with("component", json!(4)));+ ok("timeline.paste", with("component_path", json!([])));+ ok("timeline.paste", with("component_path", json!([1, 2])));+ refused("timeline.paste", with("translate", json!([1, 2])), "`translate` must be [x, y, z]");+ refused("timeline.paste", with("translate", json!(null)), "`translate` must be [x, y, z]");+ refused("timeline.paste", with("component", json!(null)), "`component` must be a component id or name");+ refused("timeline.paste", with("component", json!([1])), "`component` must be a component id or name");+ refused("timeline.paste", with("component_path", json!(null)), "`component_path` must list 0..64 occurrence ids");+ refused("timeline.paste", with("component_path", json!([1.5])), "`component_path` must list 0..64 occurrence ids");+ refused("timeline.paste", with("component_path", json!(vec![0; 65])), "`component_path` must list 0..64 occurrence ids");+ }+ ok("timeline.paste", json!({"component_path": vec![0; 64]}));+ refused("timeline.paste", json!({"from_design": null}), "`from_design` must be true or false");+ refused("timeline.paste", json!({"from_design": 0}), "`from_design` must be true or false");++ // timeline.add: the feature is an object; params are read by the handler's own reader.+ let feature = json!({"type": "box", "length": "1", "width": "1", "height": "1", "corner": [0, 0, 0]});+ ok("timeline.add", json!({"feature": feature}));+ ok("timeline.add", json!({"feature": feature, "params": null}));+ ok("timeline.add", json!({"feature": feature, "params": []}));+ ok("timeline.add", json!({"feature": feature, "params": [{"name": "q", "expression": 5}]}));+ ok("timeline.add", json!({"feature": feature, "params": [{"name": "q", "expression": "5", "unit": null, "comment": null, "extra": 1}]}));+ ok("timeline.add", json!({"feature": feature, "params": [{"name": " q ", "expression": " 5 ", "unit": "mm", "comment": "c"}]}));+ let message = "`feature` must be a feature object, as a design file or timeline.inspect has it";+ refused("timeline.add", json!({"feature": 1}), message);+ refused("timeline.add", json!({"feature": null}), message);+ refused("timeline.add", json!({"feature": feature, "params": {}}), "`params` must be a list of parameters");+ refused("timeline.add", json!({"feature": feature, "params": [{}]}), "each parameter needs a `name`");+ refused("timeline.add", json!({"feature": feature, "params": [{"name": "q"}]}), "parameter `q` needs an `expression`");+ refused(+ "timeline.add",+ json!({"feature": feature, "params": [{"name": "q", "expression": "1", "unit": 1}]}),+ "parameter `q`: `unit` must be text",+ );+ refused(+ "timeline.add",+ json!({"feature": feature, "params": [{"name": "q", "expression": "1", "comment": 1}]}),+ "parameter `q`: `comment` must be text",+ );+ // The feature's own keys are the design file's to check, not the contract's.+ ok("timeline.add", json!({"feature": {"type": "warp_drive", "anything": [1, 2]}}));++ // timeline.export_script: text, or null for no file.+ ok("timeline.export_script", json!({}));+ ok("timeline.export_script", json!({"path": null}));+ ok("timeline.export_script", json!({"path": "script.json"}));+ refused("timeline.export_script", json!({"path": 1}), "`path` must be a file path");+}++/// The schemas say what the handlers need: the keys a handler refuses without are required, and+/// each value is the form its reader takes.+#[test]+fn the_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::<CopyParams>(),+ &[+ (json!({"features": "S"}), true),+ (json!({"features": ["S", 2]}), true),+ (json!({}), false),+ (json!({"features": []}), false),+ (json!({"features": 2}), false),+ (json!({"features": [true]}), false),+ (json!({"features": [-1]}), false),+ (json!({"features": vec!["S"; 1001]}), false),+ ],+ );+ takes(+ input_schema_for::<PasteParams>(),+ &[+ (json!({}), true),+ (json!({"translate": [1, 2, 3], "component": "P", "component_path": [1], "from_design": true}), true),+ (json!({"translate": {"x": 1, "y": 2, "z": 3}, "component": 2}), true),+ (json!({"translate": [1, 2]}), false),+ (json!({"translate": [1e9, 0, 0]}), false),+ (json!({"component": true}), false),+ (json!({"component_path": [-1]}), false),+ (json!({"component_path": vec![0; 65]}), false),+ (json!({"from_design": null}), false),+ (json!({"from_design": "yes"}), false),+ ],+ );+ takes(+ input_schema_for::<AddParams>(),+ &[+ (json!({"feature": {"type": "box"}}), true),+ (json!({"feature": {"type": "box"}, "params": [{"name": "q", "expression": 5, "unit": "mm", "comment": null}]}), true),+ (json!({"feature": {"type": "box"}, "params": [{"name": "q", "expression": "5"}]}), true),+ (json!({}), false),+ (json!({"feature": []}), false),+ (json!({"feature": {"type": "box"}, "params": [{"name": "q"}]}), false),+ (json!({"feature": {"type": "box"}, "params": {"name": "q"}}), false),+ ],+ );+ takes(+ input_schema_for::<ExportScriptParams>(),+ &[(json!({}), true), (json!({"path": "a.json"}), true), (json!({"path": 3}), false), (json!({"file": "a.json"}), false)],+ );+}++/// Copy (a name, an id, both), paste (as it is, moved, into a component, from another design),+/// in Warn: each real reply matches its output schema and carries no warning.+#[test]+fn copy_and_paste_replies_match_the_output_schema() {+ let mut s = warn_session();+ plate(&mut s);+ let sketch_id = s.doc.find_feature("S").map(|f| f.id).unwrap_or_default();++ for features in [json!("S"), json!(["S"]), json!([sketch_id]), json!(["S", "E"]), json!(["E", sketch_id])] {+ let copied = run(&mut s, "timeline.copy", json!({"features": features}));+ assert!(copied["copied"].as_array().is_some_and(|c| !c.is_empty()), "{copied}");+ matches(output_schema_for::<CopyResult>(), "timeline.copy", &copied);+ }+ assert_eq!(run(&mut s, "timeline.copy", json!({"features": ["E", "S"]}))["copied"], json!(["S", "E"]), "timeline order");++ let pasted = run(&mut s, "timeline.paste", json!({}));+ assert_eq!(pasted["pasted"].as_array().map(Vec::len), Some(2), "{pasted}");+ assert_eq!(pasted["pasted"][0]["from"], "S", "{pasted}");+ assert_eq!(pasted["pasted"][0]["name"], "S (2)", "{pasted}");+ assert!(pasted["pasted"][0]["id"].is_u64(), "{pasted}");+ assert_eq!(pasted["errors"], json!([]), "{pasted}");+ assert_eq!(pasted["notices"], json!([]), "{pasted}");+ matches(output_schema_for::<PasteResult>(), "timeline.paste", &pasted);++ for p in [json!({"translate": [30, 0, 0]}), json!({"translate": {"x": 0, "y": 30, "z": 0}, "from_design": false})] {+ let moved = run(&mut s, "timeline.paste", p);+ matches(output_schema_for::<PasteResult>(), "timeline.paste", &moved);+ }++ // Into a component, by name and by id, with its placement.+ let made = run(&mut s, "component.create", json!({"name": "Plate", "grounded": false}));+ run(&mut s, "component.activate", json!({"component": 0}));+ let (component, occurrence) = (made["component"].clone(), made["occurrence"].clone());+ let into = run(&mut s, "timeline.paste", json!({"component": "Plate", "component_path": [occurrence.clone()]}));+ matches(output_schema_for::<PasteResult>(), "timeline.paste", &into);+ let by_id = run(&mut s, "timeline.paste", json!({"component": component, "translate": [0, 0, 20]}));+ matches(output_schema_for::<PasteResult>(), "timeline.paste", &by_id);++ // From another design: its copy is in the snapshot, pasted with the same keys.+ let mut source = warn_session();+ plate(&mut source);+ run(&mut source, "timeline.copy", json!({"features": ["S"]}));+ let mut target = warn_session();+ target.foreign_copy = source.foreign_copy.clone();+ let foreign = run(&mut target, "timeline.paste", json!({"from_design": true, "translate": [5, 0, 0], "component_path": []}));+ assert_eq!(foreign["pasted"][0]["from"], "S", "{foreign}");+ assert_eq!(foreign["errors"], json!([]), "{foreign}");+ assert_eq!(foreign["notices"], json!([]), "{foreign}");+ matches(output_schema_for::<PasteResult>(), "timeline.paste", &foreign);++ // A copy of a feature that is not a sketch, by id.+ let mut notices = warn_session();+ run(&mut notices, "solid.box", json!({"length": 5, "width": 5, "height": 5}));+ let nothing = run(&mut notices, "timeline.copy", json!({"features": [1]}));+ matches(output_schema_for::<CopyResult>(), "timeline.copy", ¬hing);+}++/// Add every step of a design's script in Warn, with its parameters: each `timeline.add` reply+/// matches the output schema without warnings, a feature that does not build says why, and the+/// script is returned and written as before.+#[test]+fn add_and_export_replies_match_the_output_schema() {+ let mut s = warn_session();+ plate(&mut s);+ let exported = run(&mut s, "timeline.export_script", json!({}));+ matches(output_schema_for::<ExportScriptResult>(), "timeline.export_script", &exported);+ assert_eq!(exported["path"], Value::Null, "{exported}");+ assert_eq!(exported["omitted"], json!([]), "{exported}");+ assert_eq!(exported["steps"].as_u64(), exported["script"]["commands"].as_array().map(|c| c.len() as u64), "{exported}");+ let mut about: Vec<_> = exported["script"]["about"].as_object().into_iter().flat_map(|o| o.keys().cloned()).collect();+ about.sort();+ assert_eq!(about, ["design", "format", "replay", "version"], "{exported}");+ assert!(exported["script"]["commands"].as_array().is_some_and(|c| c.iter().all(|c| c["command"].is_string() && c.get("params").is_some())));++ let mut t = warn_session();+ let mut added = 0;+ for step in exported["script"]["commands"].as_array().into_iter().flatten() {+ let reply = run(&mut t, step["command"].as_str().unwrap_or_default(), step["params"].clone());+ if step["command"] == "timeline.add" {+ added += 1;+ assert!(reply["error"].is_null() && reply["warning"].is_null(), "{reply}");+ matches(output_schema_for::<AddResult>(), "timeline.add", &reply);+ }+ }+ assert!(added >= 2, "a sketch and an extrude");+ assert!(+ exported["script"]["commands"].as_array().is_some_and(|c| c.iter().any(|c| c["params"]["params"].is_array())),+ "a step brings parameters"+ );++ // Parameters as a number, with text and null in the other keys; a feature that doesn't build.+ let mut u = warn_session();+ let reply = run(+ &mut u,+ "timeline.add",+ json!({"feature": {"type": "box", "length": "q", "width": "5", "height": "5", "corner": [0, 0, 0]}, "params": [{"name": "q", "expression": 8, "unit": null, "comment": "a size"}]}),+ );+ assert_eq!(reply["name"], "Box1", "{reply}");+ matches(output_schema_for::<AddResult>(), "timeline.add", &reply);+ let broken = run(&mut u, "timeline.add", json!({"feature": {"type": "box", "length": "0", "width": "5", "height": "5", "corner": [0, 0, 0]}}));+ assert!(broken["error"].is_string() || broken["warning"].is_string(), "{broken}");+ matches(output_schema_for::<AddResult>(), "timeline.add", &broken);++ // With a path the script is written, and the reply names the file.+ let dir = std::env::temp_dir().join(format!("solidcraft-timeline-schema-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("{e}"));+ let file = dir.join("script.json");+ let written = run(&mut s, "timeline.export_script", json!({"path": file}));+ let text = std::fs::read_to_string(&file).unwrap_or_default();+ let _ = std::fs::remove_dir_all(&dir);+ assert_eq!(serde_json::from_str::<Value>(&text).ok(), Some(written["script"].clone()));+ // The file's text is the pretty-printed script with its keys sorted, as it has always been.+ let sorted = serde_json::to_string_pretty(&written["script"]).unwrap_or_default();+ assert_eq!(text, sorted);+ assert_eq!(written["path"], json!(file), "{written}");+ matches(output_schema_for::<ExportScriptResult>(), "timeline.export_script", &written);+}++/// A misspelt key still runs in Warn, and says so, with a reply that matches its schema.+#[test]+fn a_misspelt_key_is_reported_in_warn() {+ let mut s = warn_session();+ plate(&mut s);+ let sketch = json!({"type": "box", "length": "1", "width": "1", "height": "1", "corner": [0, 0, 0]});+ let cases = [+ ("timeline.copy", json!({"features": ["S"], "featurs": 1}), output_schema_for::<CopyResult>()),+ ("timeline.paste", json!({"translat": [1, 0, 0]}), output_schema_for::<PasteResult>()),+ ("timeline.add", json!({"feature": sketch, "param": []}), output_schema_for::<AddResult>()),+ ("timeline.export_script", json!({"paht": "x.json"}), output_schema_for::<ExportScriptResult>()),+ ];+ for (id, p, schema) in cases {+ if id == "timeline.paste" {+ run(&mut s, "timeline.copy", json!({"features": ["S"]}));+ }+ let reply = run(&mut s, id, p);+ let warnings = reply["param_warnings"].as_array().cloned().unwrap_or_default();+ assert!(warnings.len() == 1 && warnings[0].as_str().is_some_and(|w| w.contains("unknown key")), "{id}: {reply}");+ assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{id}: {reply}");+ }+ // In strict the call is refused before it runs.+ s.param_check = ParamCheck::Strict;+ let refused = s.execute("timeline.export_script", &json!({"paht": "x.json"}));+ assert!(refused.is_err_and(|e| e.to_string().contains("unknown key `paht`")));+}++/// The expression of a parameter that isn't blank once trimmed: the pattern is the one the+/// shared check builds from `trim`'s whitespace.+#[test]+fn a_blank_expression_is_refused_by_the_pattern() {+ let schema = input_schema_for::<AddParams>();+ let pattern = schema.as_value()["$defs"]["StepParams"]["items"]["properties"]["expression"]["anyOf"][0]["pattern"].clone();+ assert_eq!(pattern, json!(crate::schema::types::not_blank_pattern()));+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex cdd7e2aefb..6e405d3b64 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -178,13 +178,9 @@ surface.thickensurface.trimsurface.unstitchsurface.untrim-timeline.add-timeline.copy-timeline.export_scripttimeline.grouptimeline.move_manytimeline.move_to_group-timeline.pastetimeline.redefinetimeline.rename_grouptimeline.reorder