Agents and scripts: the standard part commands describe their exact parameters and reply (#11003) (#11004)
* claim: #11003 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Standard parts: input and output schemas (#11003) parts.library, parts.insert, parts.fastener and parts.resize get typed contracts and reply types in schema/parts.rs and leave unconverted.txt. Each key reads as the handler reads it, with its message; the replies are built from PartsLibrary, InsertedPart and ResizedPart, with the same JSON as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Standard parts schema: Vec3 comes from solidcore_record Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Standard parts schema: hole picks must start with a list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * parts.insert schema: the first hole pick must be a point, not any list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
@@ -15,27 +15,43 @@ use solidcraft_geom::prelude::*;
|
||||
|
||||
use super::CommandSpec;
|
||||
use crate::params::{bad, num, str_, vec3};
|
||||
use crate::schema::parts::{InsertedPart, PartFamily, PartsInsertParams, PartsLibrary, PartsLibraryParams, PartsResizeParams, ResizedPart};
|
||||
use crate::schema::{TypedContract, output_schema_for};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
const LIBRARY_CONTRACT: TypedContract<PartsLibraryParams> = TypedContract::new();
|
||||
const INSERT_CONTRACT: TypedContract<PartsInsertParams> = TypedContract::new();
|
||||
const RESIZE_CONTRACT: TypedContract<PartsResizeParams> = TypedContract::new();
|
||||
|
||||
pub static COMMANDS: &[CommandSpec] = &[
|
||||
CommandSpec::new("parts.library", "Standard Parts", library)
|
||||
CommandSpec::new("parts.library", "Standard Parts", crate::checked!("parts.library", library))
|
||||
.icon("library")
|
||||
.noundo()
|
||||
.contract(&LIBRARY_CONTRACT)
|
||||
.output(output_schema_for::<PartsLibrary>)
|
||||
.params("family? → families (name, standard, system: metric|inch, sizes, lengths) and, with family, each size's dimensions (mm)"),
|
||||
CommandSpec::new("parts.fastener", "Insert Fastener", insert_atomic)
|
||||
CommandSpec::new("parts.fastener", "Insert Fastener", crate::checked!("parts.fastener", insert_atomic))
|
||||
.at("SOLID", "INSERT")
|
||||
.icon("fastener")
|
||||
.contract(&INSERT_CONTRACT)
|
||||
.output(output_schema_for::<InsertedPart>)
|
||||
.params("the Insert Part dialog's command (same as parts.insert): family, size, length?, at?|point?+direction?, name?"),
|
||||
CommandSpec::new("parts.insert", "Insert Part", insert_atomic).icon("fastener").params(
|
||||
"family (socket_head_cap_screw | button_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing | \
|
||||
CommandSpec::new("parts.insert", "Insert Part", crate::checked!("parts.insert", insert_atomic))
|
||||
.icon("fastener")
|
||||
.contract(&INSERT_CONTRACT)
|
||||
.output(output_schema_for::<InsertedPart>)
|
||||
.params(
|
||||
"family (socket_head_cap_screw | button_head_cap_screw | hex_bolt | hex_nut | washer | set_screw | dowel_pin | bearing | \
|
||||
hex_cap_screw_inch | hex_nut_inch | washer_sae | washer_uss); size (\"M6\", \"608\" for bearings, \"1/2-13 UNC\" for inch screws and nuts, \
|
||||
\"1/2\" for inch washers); length? (mm, inch parts too; screws, bolts, set screws, pins; default a standard length near 2.5 d); \
|
||||
at?: [x,y,z] on a hole's rim or wall (the part seats on the hole's face with a rigid joint), or a list of them (one component, \
|
||||
placed and seated once per hole) | point?: [x,y,z] with direction?: [x,y,z] (no joint); name? → component, occurrence, joint?, \
|
||||
and with at: occurrences, joints (one per hole, in pick order)",
|
||||
),
|
||||
CommandSpec::new("parts.resize", "Change Part Size", resize_atomic)
|
||||
),
|
||||
CommandSpec::new("parts.resize", "Change Part Size", crate::checked!("parts.resize", resize_atomic))
|
||||
.icon("scale")
|
||||
.contract(&RESIZE_CONTRACT)
|
||||
.output(output_schema_for::<ResizedPart>)
|
||||
.params("component: id|name of an inserted part; size?; length? — rebuilds it (joints keep it seated)"),
|
||||
];
|
||||
|
||||
@@ -572,7 +588,7 @@ fn build(s: &mut Session, sh: &Shape) -> Result<()> {
|
||||
}
|
||||
|
||||
fn library(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fam = |id: &str| -> Value {
|
||||
let fam = |id: &str| -> PartFamily {
|
||||
let mut sizes: Vec<Value> = match id {
|
||||
"socket_head_cap_screw" => SHCS.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "head_diameter": r.1, "head_height": r.2, "socket": r.3, "socket_depth": r.4})).collect(),
|
||||
"button_head_cap_screw" => BHCS.iter().map(|r| json!({"size": r.0, "d": metric(r.0).map(|m| m.0), "pitch": metric(r.0).map(|m| m.1), "head_diameter": r.1, "head_height": r.2, "socket": r.3, "socket_depth": r.4})).collect(),
|
||||
@@ -612,15 +628,24 @@ fn library(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
let system = if is_inch(id) { "inch" } else { "metric" };
|
||||
json!({"family": id, "name": name, "standard": standard, "system": system, "sizes": sizes, "lengths": lengths})
|
||||
PartFamily { family: id.into(), name: name.into(), standard: standard.into(), system: system.into(), sizes, lengths }
|
||||
};
|
||||
match str_(p, "family") {
|
||||
Some(f) if FAMILIES.iter().any(|x| x.0 == f) => Ok(fam(f)),
|
||||
Some(f) if FAMILIES.iter().any(|x| x.0 == f) => {
|
||||
reply("parts.library", PartsLibrary { families: None, family: Some(fam(f)), param_warnings: Vec::new() })
|
||||
}
|
||||
Some(f) => Err(bad("parts.library", format!("unknown part family `{f}`"))),
|
||||
None => Ok(json!({"families": FAMILIES.iter().map(|f| fam(f.0)).collect::<Vec<_>>()})),
|
||||
None => reply(
|
||||
"parts.library",
|
||||
PartsLibrary { families: Some(FAMILIES.iter().map(|f| fam(f.0)).collect()), family: None, param_warnings: Vec::new() },
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
|
||||
serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
|
||||
}
|
||||
|
||||
fn part_name(family: &str, size: &str, sh: &Shape) -> String {
|
||||
match sh {
|
||||
Shape::Screw { len, .. } | Shape::Rod { len, .. } => format!("{} {}", label(family), size_with_length(family, size, *len)),
|
||||
@@ -747,14 +772,26 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.doc_mut().parts.insert(comp, solidcraft_doc::StandardPart { family: family.clone(), size: size.clone(), length: shape_len(&sh) });
|
||||
set_identity(s, comp, identity(&family, &size, &sh), None);
|
||||
run(s, "component.activate", json!({"component": active}))?;
|
||||
let mut out = json!({"component": comp, "occurrence": occ, "name": name});
|
||||
let mut out = InsertedPart {
|
||||
component: comp,
|
||||
occurrence: occ,
|
||||
name: name.clone(),
|
||||
joint: None,
|
||||
occurrences: None,
|
||||
joints: None,
|
||||
param_warnings: Vec::new(),
|
||||
};
|
||||
if !holes.is_empty() {
|
||||
// The first hole has the placement the component came with; each further hole places the
|
||||
// same part again. All are made before any is seated, while each is still at the part's
|
||||
// own origin, where the joint below takes the part's seating point to be.
|
||||
let mut occurrences = vec![json!(occ)];
|
||||
let mut occurrences = vec![occ];
|
||||
for _ in 1..holes.len() {
|
||||
occurrences.push(run(s, "occurrence.copy", json!({"component": comp}))?["occurrence"].clone());
|
||||
occurrences.push(
|
||||
run(s, "occurrence.copy", json!({"component": comp}))?["occurrence"]
|
||||
.as_u64()
|
||||
.ok_or_else(|| bad(cmd, "the copy has no occurrence"))?,
|
||||
);
|
||||
}
|
||||
let mut joints = Vec::new();
|
||||
for (i, ((a, h), o)) in holes.into_iter().zip(&occurrences).enumerate() {
|
||||
@@ -766,11 +803,11 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"joint.create",
|
||||
json!({"type": "rigid", "a": {"occurrence": h, "circle": a}, "b": {"occurrence": o, "point": [0, 0, 0], "z": [0, 0, -1]}, "name": seat}),
|
||||
)?;
|
||||
joints.push(j["joint"].clone());
|
||||
joints.push(j["joint"].as_u64().ok_or_else(|| bad(cmd, "the joint has no id"))?);
|
||||
}
|
||||
out["joint"] = joints.first().cloned().unwrap_or(Value::Null);
|
||||
out["occurrences"] = Value::Array(occurrences);
|
||||
out["joints"] = Value::Array(joints);
|
||||
out.joint = joints.first().copied();
|
||||
out.occurrences = Some(occurrences);
|
||||
out.joints = Some(joints);
|
||||
} else if let Some(pt) = p.get("point").and_then(vec3) {
|
||||
// Placed at a point, its +z along `direction`.
|
||||
let dir = p.get("direction").and_then(vec3).and_then(|d| d.normalized()).unwrap_or(Vec3::Z);
|
||||
@@ -789,7 +826,7 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.transform = m;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
reply(cmd, out)
|
||||
}
|
||||
|
||||
/// The most holes one insert seats a part in.
|
||||
@@ -887,7 +924,7 @@ fn resize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some(e) = s.model.results.iter().find_map(|r| r.error.clone()) {
|
||||
return Err(EngineError::Other(e));
|
||||
}
|
||||
Ok(json!({"component": comp, "name": name, "size": size, "length": shape_len(&sh)}))
|
||||
reply(cmd, ResizedPart { component: comp, name, size, length: shape_len(&sh), param_warnings: Vec::new() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -74,6 +74,7 @@ pub mod material_properties;
|
||||
pub mod metadata;
|
||||
pub mod motion;
|
||||
pub mod panels;
|
||||
pub mod parts;
|
||||
pub mod print_face;
|
||||
pub mod render;
|
||||
pub mod render_library;
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Contracts and result types for the commands in `cmd/parts.rs`: standard parts (#11003).
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
|
||||
use serde::de::Error as _;
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use serde_json::Value;
|
||||
use solidcore_record::Vec3;
|
||||
|
||||
use super::check::whole;
|
||||
use super::types::Point3;
|
||||
use crate::params;
|
||||
|
||||
/// List the standard part families, or one family's sizes with their dimensions (mm).
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PartsLibraryParams {
|
||||
/// One family, as the list names it (default: every family).
|
||||
#[serde(default)]
|
||||
pub family: Option<String>,
|
||||
}
|
||||
|
||||
/// Insert a standard part as a new component: seated in holes with a rigid joint each (`at`),
|
||||
/// placed at a point (`point`), or at the origin. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PartsInsertParams {
|
||||
/// The family, as `parts.library` lists it: socket_head_cap_screw, button_head_cap_screw,
|
||||
/// hex_bolt, hex_nut, washer, set_screw, dowel_pin, bearing, hex_cap_screw_inch,
|
||||
/// hex_nut_inch, washer_sae or washer_uss.
|
||||
#[serde(deserialize_with = "family")]
|
||||
pub family: String,
|
||||
/// The size, as `parts.library` lists it: `M6`, `608` for a bearing, `1/2-13 UNC` for an
|
||||
/// inch screw or nut, `1/2` for an inch washer.
|
||||
#[serde(deserialize_with = "size")]
|
||||
pub size: String,
|
||||
#[serde(default, deserialize_with = "length")]
|
||||
#[schemars(schema_with = "length_schema")]
|
||||
pub length: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub at: Option<HolePicks>,
|
||||
/// Without `at`: where the part's origin goes, with no joint.
|
||||
#[serde(default)]
|
||||
pub point: Option<Point3>,
|
||||
/// With `point`: the direction the part's +Z turns to (default +Z), a non-zero `[x, y, z]`.
|
||||
#[serde(default)]
|
||||
pub direction: Option<Point3>,
|
||||
/// The component's name (default: the part's, such as `Socket Head Cap Screw M6x20`).
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
/// Change an inserted standard part's size or length, rebuilding it in place; its joints keep it
|
||||
/// seated. One undo step.
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PartsResizeParams {
|
||||
/// The part's component, by id or name.
|
||||
#[serde(deserialize_with = "component")]
|
||||
#[schemars(schema_with = "component_schema")]
|
||||
pub component: String,
|
||||
/// The new size (default: the part's).
|
||||
#[serde(default)]
|
||||
pub size: Option<String>,
|
||||
#[serde(default, deserialize_with = "length")]
|
||||
#[schemars(schema_with = "length_schema")]
|
||||
pub length: Option<f64>,
|
||||
}
|
||||
|
||||
/// The family, with the handler's message for anything that isn't text.
|
||||
fn family<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(s),
|
||||
_ => Err(D::Error::custom(whole("`family` is required (parts.library)"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The size, with the handler's message for anything that isn't text.
|
||||
fn size<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::String(s) => Ok(s),
|
||||
_ => Err(D::Error::custom(whole("`size` is required"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A part's length, as the handler reads it: `null` is the default, else above 0 and at most
|
||||
/// 2000 mm.
|
||||
fn length<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Null => Ok(None),
|
||||
v => v
|
||||
.as_f64()
|
||||
.and_then(params::finite)
|
||||
.filter(|l| *l > 0.0 && *l <= 2000.0)
|
||||
.map(Some)
|
||||
.ok_or_else(|| D::Error::custom(whole("`length` must be 0…2000 mm"))),
|
||||
}
|
||||
}
|
||||
|
||||
fn length_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({
|
||||
"description": "For screws, bolts, set screws and pins: the length in mm, inch parts too (default: a standard length near 2.5 diameters).",
|
||||
"type": ["number", "null"],
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 2000
|
||||
})
|
||||
}
|
||||
|
||||
/// A component's id or name, as the resize reads it, with its message.
|
||||
fn component<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
|
||||
match Value::deserialize(d)? {
|
||||
Value::Number(n) => Ok(n.to_string()),
|
||||
Value::String(s) => Ok(s),
|
||||
_ => Err(D::Error::custom("must be an id or a name")),
|
||||
}
|
||||
}
|
||||
|
||||
fn component_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"description": "The part's component, by id or name.", "type": ["number", "string"]})
|
||||
}
|
||||
|
||||
/// The most holes one insert seats a part in.
|
||||
const MAX_HOLES: usize = 1000;
|
||||
|
||||
/// Points on the rims or walls of holes, as the insert reads them: one point, or a list of up to
|
||||
/// 1000 (a list's first item is a list, or it is empty), with its messages. The part seats on
|
||||
/// each hole's face with a rigid joint, placed once per hole as one component.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct HolePicks(pub Vec<Vec3>);
|
||||
|
||||
impl<'de> Deserialize<'de> for HolePicks {
|
||||
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
let fail = || D::Error::custom(whole("`at` must be [x,y,z] or a list of them"));
|
||||
let one = |v: &Value| params::vec3(v).ok_or_else(fail);
|
||||
match Value::deserialize(d)? {
|
||||
Value::Array(list) if list.first().is_some_and(Value::is_array) || list.is_empty() => {
|
||||
if list.len() > MAX_HOLES {
|
||||
return Err(D::Error::custom(whole(format!("`at` takes at most {MAX_HOLES} holes"))));
|
||||
}
|
||||
list.iter().map(one).collect::<Result<_, _>>().map(HolePicks)
|
||||
}
|
||||
v => Ok(HolePicks(vec![one(&v)?])),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl JsonSchema for HolePicks {
|
||||
fn schema_name() -> Cow<'static, str> {
|
||||
"HolePicks".into()
|
||||
}
|
||||
fn inline_schema() -> bool {
|
||||
true
|
||||
}
|
||||
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
|
||||
let point = generator.subschema_for::<Point3>();
|
||||
json_schema!({
|
||||
"description": "A point on a hole's rim or wall, or a list of them (one per hole, at most 1000): the part seats on each hole's face with a rigid joint.",
|
||||
"anyOf": [point.clone(), {"type": "array", "prefixItems": [{"allOf": [{"type": "array"}, point.clone()]}], "items": point, "maxItems": MAX_HOLES}]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What `parts.library` returns: every family, or the one asked for.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PartsLibrary {
|
||||
/// Without `family`: every family.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub families: Option<Vec<PartFamily>>,
|
||||
/// With `family`: that family.
|
||||
#[serde(flatten)]
|
||||
pub family: Option<PartFamily>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// A standard part family.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct PartFamily {
|
||||
/// Its id, as `parts.insert` takes it.
|
||||
pub family: String,
|
||||
pub name: String,
|
||||
/// The standard its sizes follow.
|
||||
pub standard: String,
|
||||
/// `metric` or `inch`.
|
||||
pub system: String,
|
||||
/// Each size with its dimensions in mm (which depend on the family), and `default_length`
|
||||
/// where the part has a length.
|
||||
#[schemars(schema_with = "sizes_schema")]
|
||||
pub sizes: Vec<Value>,
|
||||
/// The standard lengths (mm), for the families that have one; else `null`.
|
||||
pub lengths: Option<Vec<f64>>,
|
||||
}
|
||||
|
||||
fn sizes_schema(_: &mut SchemaGenerator) -> Schema {
|
||||
json_schema!({"type": "array", "items": {"type": "object", "properties": {"size": {"type": "string"}}, "required": ["size"]}})
|
||||
}
|
||||
|
||||
/// What `parts.insert` and `parts.fastener` return.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct InsertedPart {
|
||||
/// The new component's id.
|
||||
pub component: u64,
|
||||
/// Its first occurrence's id.
|
||||
pub occurrence: u64,
|
||||
/// The component's name.
|
||||
pub name: String,
|
||||
/// With `at`: the first hole's joint.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub joint: Option<u64>,
|
||||
/// With `at`: an occurrence per hole, in pick order.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub occurrences: Option<Vec<u64>>,
|
||||
/// With `at`: a joint per hole, in pick order.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub joints: Option<Vec<u64>>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
/// What `parts.resize` returns.
|
||||
#[derive(Debug, Serialize, JsonSchema)]
|
||||
pub struct ResizedPart {
|
||||
pub component: u64,
|
||||
/// The component's new name.
|
||||
pub name: String,
|
||||
pub size: String,
|
||||
/// Its length (mm), for a part that has one; else `null`.
|
||||
pub length: Option<f64>,
|
||||
/// 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 = "parts_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,128 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::{InsertedPart, PartsInsertParams, PartsLibrary, PartsLibraryParams, PartsResizeParams, ResizedPart};
|
||||
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 run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
/// A 40 x 30 x 10 plate with two 6.4 mm holes through its top face, as in the command's tests:
|
||||
/// a point on each hole's rim.
|
||||
fn plate(s: &mut Session) -> [[f64; 3]; 2] {
|
||||
run(s, "solid.box", json!({"length": 40, "width": 30, "height": 10, "body_name": "Plate"}));
|
||||
run(s, "solid.hole", json!({"position": [10, 15, 10], "diameter": 6.4}));
|
||||
run(s, "solid.hole", json!({"position": [30, 15, 10], "diameter": 6.4}));
|
||||
[[13.2, 15.0, 10.0], [33.2, 15.0, 10.0]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_the_key_check_agree() {
|
||||
assert_keys(input_schema_for::<PartsLibraryParams>(), &["family"]);
|
||||
assert_keys(input_schema_for::<PartsInsertParams>(), &["at", "direction", "family", "length", "name", "point", "size"]);
|
||||
assert_keys(input_schema_for::<PartsResizeParams>(), &["component", "length", "size"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_keeps_todays_errors() {
|
||||
assert_strict_keeps_todays_errors(&[
|
||||
("parts.library", json!({"family": "nope"})),
|
||||
("parts.resize", json!({"component": true})),
|
||||
("parts.resize", json!({"component": "Nope"})),
|
||||
]);
|
||||
}
|
||||
|
||||
/// The insert names itself `parts.insert (Insert Fastener)` in its messages, under either id,
|
||||
/// where strict names the id called; the message after the name is the same.
|
||||
#[test]
|
||||
fn the_insert_keeps_its_messages_in_strict() {
|
||||
let many = vec![[0, 0, 0]; 1001];
|
||||
let message = |s: &mut Session, id: &str, p: &Value| s.execute(id, p).err().map(|e| e.to_string().split_once("`: ").map(|m| m.1.to_string()));
|
||||
for p in [
|
||||
json!({"family": 5, "size": "M6"}),
|
||||
json!({"family": "washer"}),
|
||||
json!({"family": "washer", "size": 6}),
|
||||
json!({"family": "nope", "size": "M6"}),
|
||||
json!({"family": "socket_head_cap_screw", "size": "M6", "length": 0}),
|
||||
json!({"family": "socket_head_cap_screw", "size": "M6", "length": "x"}),
|
||||
json!({"family": "socket_head_cap_screw", "size": "M6", "length": 3000}),
|
||||
json!({"family": "washer", "size": "M6", "at": "x"}),
|
||||
json!({"family": "washer", "size": "M6", "at": [[1, 2]]}),
|
||||
json!({"family": "washer", "size": "M6", "at": many}),
|
||||
] {
|
||||
for id in ["parts.insert", "parts.fastener"] {
|
||||
let off = message(&mut Session::default(), id, &p);
|
||||
assert!(off.as_ref().is_some_and(Option::is_some), "{id} {p} should fail today");
|
||||
let strict = message(&mut Session { param_check: ParamCheck::Strict, ..Session::default() }, id, &p);
|
||||
assert_eq!(strict, off, "{id} {p}");
|
||||
}
|
||||
}
|
||||
// A resize's length is read once the part is found.
|
||||
let error = |level: ParamCheck| {
|
||||
let mut s = Session { param_check: level, ..Session::default() };
|
||||
let c = run(&mut s, "parts.insert", json!({"family": "washer", "size": "M6"}))["component"].clone();
|
||||
s.execute("parts.resize", &json!({"component": c, "length": 0})).err().map(|e| e.to_string())
|
||||
};
|
||||
let off = error(ParamCheck::Off);
|
||||
assert!(off.is_some());
|
||||
assert_eq!(error(ParamCheck::Strict), off);
|
||||
}
|
||||
|
||||
/// #11003: the library, an insert and a resize reply as their output schemas say, in Warn
|
||||
/// without warnings for good calls and with them for a misspelt key: every family and one, a
|
||||
/// part at a point turned to a direction, one seated in two holes under the dialog's id, and a
|
||||
/// resize.
|
||||
#[test]
|
||||
fn part_commands_reply_with_their_schemas() {
|
||||
let (library, inserted, resized) = (output_schema_for::<PartsLibrary>(), output_schema_for::<InsertedPart>(), output_schema_for::<ResizedPart>());
|
||||
let matches = |schema: &schemars::Schema, r: &Value, warned: bool| {
|
||||
let schema = schema.as_value();
|
||||
assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
|
||||
assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
|
||||
};
|
||||
let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
|
||||
let r = run(&mut s, "parts.library", json!({}));
|
||||
matches(&library, &r, false);
|
||||
assert!(r["families"].as_array().is_some_and(|f| f.len() > 5) && r.get("family").is_none(), "{r}");
|
||||
let r = run(&mut s, "parts.library", json!({"family": "socket_head_cap_screw"}));
|
||||
matches(&library, &r, false);
|
||||
assert!(r["family"] == "socket_head_cap_screw" && r["lengths"].is_array() && r.get("families").is_none(), "{r}");
|
||||
matches(&library, &run(&mut s, "parts.library", json!({"family": "bearing"})), false);
|
||||
|
||||
let holes = plate(&mut s);
|
||||
let r = run(
|
||||
&mut s,
|
||||
"parts.insert",
|
||||
json!({"family": "hex_nut", "size": "M6", "point": [60, 0, 0], "direction": {"x": 1, "y": 0, "z": 0}, "name": "Nut"}),
|
||||
);
|
||||
matches(&inserted, &r, false);
|
||||
assert!(r.get("joint").is_none() && r["name"] == "Nut", "{r}");
|
||||
let r = run(&mut s, "parts.fastener", json!({"family": "socket_head_cap_screw", "size": "M6", "length": 20, "at": holes}));
|
||||
matches(&inserted, &r, false);
|
||||
assert_eq!((r["occurrences"].as_array().map(Vec::len), r["joints"].as_array().map(Vec::len)), (Some(2), Some(2)), "{r}");
|
||||
let screw = r["component"].clone();
|
||||
let r = run(&mut s, "parts.resize", json!({"component": screw, "size": "M8", "length": 25}));
|
||||
matches(&resized, &r, false);
|
||||
assert_eq!((r["size"].as_str(), r["length"].as_f64()), (Some("M8"), Some(25.0)), "{r}");
|
||||
|
||||
matches(&library, &run(&mut s, "parts.library", json!({"familly": "washer"})), true);
|
||||
matches(&inserted, &run(&mut s, "parts.insert", json!({"family": "washer", "size": "M6", "lenght": 3})), true);
|
||||
matches(&resized, &run(&mut s, "parts.resize", json!({"component": screw, "sise": "M6"})), true);
|
||||
}
|
||||
|
||||
/// A list of hole picks starts with a point (a list of three numbers), not an object and not a
|
||||
/// shorter list; a single point or a list of points is fine.
|
||||
#[test]
|
||||
fn hole_picks_schema_requires_a_first_point() {
|
||||
let root = serde_json::to_value(input_schema_for::<PartsInsertParams>()).unwrap();
|
||||
let at = &root["properties"]["at"];
|
||||
let ok = |v: Value| conforms(&root, at, &v);
|
||||
assert!(ok(json!([[1, 2, 3]])));
|
||||
assert!(ok(json!([1, 2, 3])));
|
||||
assert!(ok(json!([[1, 2, 3], [4, 5, 6]])));
|
||||
assert!(!ok(json!([[1, 2]])));
|
||||
assert!(!ok(json!([[1, 2, 3], [1, 2]])));
|
||||
assert!(!ok(json!([{"x": 1}])));
|
||||
}
|
||||
@@ -479,6 +479,11 @@ pub(super) fn conforms(root: &Value, node: &Value, v: &Value) -> bool {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(branches) = node.get("allOf").and_then(Value::as_array)
|
||||
&& !branches.iter().all(|b| conforms(root, b, v))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if node.get("not").is_some_and(|n| conforms(root, n, v)) {
|
||||
return false;
|
||||
}
|
||||
@@ -500,8 +505,15 @@ pub(super) fn conforms(root: &Value, node: &Value, v: &Value) -> bool {
|
||||
if !typed {
|
||||
return false;
|
||||
}
|
||||
// `prefixItems` checks the leading elements; `items` then covers the rest.
|
||||
let prefix = node.get("prefixItems").and_then(Value::as_array);
|
||||
if let (Some(prefix), Some(a)) = (prefix, v.as_array())
|
||||
&& !prefix.iter().zip(a).all(|(p, x)| conforms(root, p, x))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let (Some(items), Some(a)) = (node.get("items"), v.as_array())
|
||||
&& !a.iter().all(|x| conforms(root, items, x))
|
||||
&& !a.iter().skip(prefix.map_or(0, Vec::len)).all(|x| conforms(root, items, x))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -132,10 +132,6 @@ parameters.list
|
||||
parameters.move
|
||||
parameters.rename
|
||||
parameters.users
|
||||
parts.fastener
|
||||
parts.insert
|
||||
parts.library
|
||||
parts.resize
|
||||
plastic.assign_rule
|
||||
plastic.boss
|
||||
plastic.lip
|
||||
|
||||
Reference in New Issue
Block a user