@rulecad/variables 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,6 +28,9 @@ entries // every variable and rule with its value, source and whet
28
28
 
29
29
  - **Expressions:** `+ - * /`, brackets, `min`, `max`, `round(x, step)`, and `sind`/`cosd`/`tand` in degrees, over
30
30
  numbers and names. `evaluate(src, lookup)` runs one on its own.
31
+ - **Lists:** a rule may hold a list, `"value": [5, 6, 8, 10]` with one `unit` for all of it (the lengths a screw is
32
+ sold in). Each entry is a number or an expression. A design reads it as an array; in an expression only `min()` and
33
+ `max()` take a list, and anything else refuses it by name.
31
34
  - **Rule sets** are handed in through `sets`, or fetched by name with `load: (name) => …` (from files, a URL, anywhere).
32
35
  - **Tweaks:** only variables with a `tweak` range can be set, and only within it. Errors say which variable and why.
33
36
  - **Names, not numbers:** `choice: [...]`, `type: 'text'` or `type: 'anchor'` (one of `ANCHORS`: tl tc tr / ml mc
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/variables",
3
- "version": "0.3.3",
3
+ "version": "0.3.4",
4
4
  "description": "Design values you can trace: every number says where it comes from, and expressions are parsed, never run.",
5
5
  "type": "module",
6
6
  "exports": {
package/variables.d.mts CHANGED
@@ -33,8 +33,8 @@ export function resolve(object: DesignObject, { sets, set, display, load }?: {
33
33
  };
34
34
  /**
35
35
  * @param {RuleSet & { part?: string, interface?: Record<string, string> }} set
36
- * @param {{ units: string[], prefixes: string[], fields: Record<string, { unit?: string, choice?: string[] }>, parts: Record<string, string[]> }} vocabulary
37
- * @returns {{ level: 'fail', code: string, text: string, rule?: string }[]} what's wrong with it: nothing, if it passes
36
+ * @param {{ units: string[], prefixes: string[], fields: Record<string, { unit?: string, choice?: string[], list?: boolean }>, parts: Record<string, string[]>, checks?: Record<string, { ascending?: string[], near?: string, to?: string, within?: string, says: string }[]> }} vocabulary
37
+ * @returns {{ level: 'fail', code: string, text: string, rule?: string, values?: Record<string, number> }[]} what's wrong with it: nothing, if it passes
38
38
  */
39
39
  export function checkRuleSet(set: RuleSet & {
40
40
  part?: string;
@@ -45,13 +45,22 @@ export function checkRuleSet(set: RuleSet & {
45
45
  fields: Record<string, {
46
46
  unit?: string;
47
47
  choice?: string[];
48
+ list?: boolean;
48
49
  }>;
49
50
  parts: Record<string, string[]>;
51
+ checks?: Record<string, {
52
+ ascending?: string[];
53
+ near?: string;
54
+ to?: string;
55
+ within?: string;
56
+ says: string;
57
+ }[]>;
50
58
  }): {
51
59
  level: "fail";
52
60
  code: string;
53
61
  text: string;
54
62
  rule?: string;
63
+ values?: Record<string, number>;
55
64
  }[];
56
65
  /**
57
66
  * Number literals in a design's code other than 0, 1 and 2 (outside comments and strings).
@@ -65,9 +74,9 @@ export function lint(source: string): {
65
74
  export const ANCHORS: string[];
66
75
  export function isName(d: any): boolean;
67
76
  export function options(d: any): any;
68
- export function fmt(n: any): string;
77
+ export function fmt(n: any): any;
69
78
  export type Variable = {
70
- value: number | string;
79
+ value: number | string | (number | string)[];
71
80
  unit?: string;
72
81
  rule?: string;
73
82
  kind?: "spec" | "community" | "default" | "estimate" | "measured" | "derived";
package/variables.mjs CHANGED
@@ -4,10 +4,13 @@
4
4
  // Expressions are arithmetic only (+ - * / and brackets, min, max, round, and sind, cosd, tand of degrees) over numbers
5
5
  // and names: parsed here, never
6
6
  // eval'd, so a JSON file can't run code.
7
+ // A rule may hold a list (the lengths a screw is sold in): "value": [5, 6, 8, 10], each entry a number or an expression
8
+ // like any other value, all in the rule's one unit. A design reads it as an array (v.m3.lengths); in an expression only
9
+ // min() and max() take a list, and anything else refuses it by name.
7
10
  // No imports and no file access: it runs in a browser as well. Rule sets are handed in (sets) or fetched by name
8
11
  // through load(name), such as one that reads rules/<name>.json.
9
12
 
10
- /** @typedef {{ value: number | string, unit?: string, rule?: string, kind?: 'spec' | 'community' | 'default' | 'estimate' | 'measured' | 'derived', source?: string, licence?: string, checked?: string, label?: string, show?: boolean, interface?: boolean, tweak?: { min: number, max: number }, choice?: string[], type?: 'text' | 'anchor' | 'layout' | 'problem' }} Variable */
13
+ /** @typedef {{ value: number | string | (number | string)[], unit?: string, rule?: string, kind?: 'spec' | 'community' | 'default' | 'estimate' | 'measured' | 'derived', source?: string, licence?: string, checked?: string, label?: string, show?: boolean, interface?: boolean, tweak?: { min: number, max: number }, choice?: string[], type?: 'text' | 'anchor' | 'layout' | 'problem' }} Variable */
11
14
  /** @typedef {{ name?: string, rules: Record<string, Variable> }} RuleSet */
12
15
  /** @typedef {{ uses?: string[], variables?: Record<string, Variable>, [field: string]: any }} DesignObject */
13
16
  /** @typedef {{ name: string, value: number | string, used?: boolean, set?: boolean, [field: string]: any }} Entry */
@@ -86,12 +89,12 @@ function parse(src) {
86
89
  */
87
90
  export function evaluate(src, lookup = (name) => { throw new Error(`no value for "${name}"`); }) {
88
91
  if (typeof src === 'number') { if (!Number.isFinite(src)) throw new Error('is not a finite number'); return src; }
89
- const walk = (x) => {
92
+ const walk = (x, list = false) => { // list: inside min() or max(), where a name may be a list rule
90
93
  if (x.n != null) return x.n;
91
- if (x.id != null) return lookup(x.id);
94
+ if (x.id != null) { const v = lookup(x.id); if (Array.isArray(v) && !list) throw new Error(`"${x.id}" is a list: take min(${x.id}) or max(${x.id}), or read it in the design`); return v; }
92
95
  if (x.neg) return -walk(x.neg);
93
96
  if (x.pos) return walk(x.pos);
94
- if (x.fn) return FNS[x.fn](...x.args.map(walk));
97
+ if (x.fn) { const spread = x.fn === 'min' || x.fn === 'max'; return FNS[x.fn](...x.args.flatMap((a) => walk(a, spread))); }
95
98
  const a = walk(x.a), b = walk(x.b);
96
99
  return x.op === '+' ? a + b : x.op === '-' ? a - b : x.op === '*' ? a * b : a / b;
97
100
  };
@@ -217,10 +220,13 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
217
220
  if (isName(d)) { busy.delete(name); const c = checkName(name, d, shown ? display[name] : given ? set[name] : d.value); done.set(name, c); return c; }
218
221
  src = shown ? display[name] : given ? Number(set[name]) : d.value; where = (n) => n; // display: the screen's settings win
219
222
  if (src === undefined) throw fail('var.value', `"${name}" has no value`, `variables.${name}`);
223
+ if (Array.isArray(src)) throw fail('var.list', `"${name}" is a list: only a rule in a rule set holds a list (a design reads it as v.<set>.<rule>)`, `variables.${name}.value`);
220
224
  }
221
225
  let v;
222
226
  deps.set(name, new Set()); stack.push(name);
223
- try { v = evaluate(src, (n) => lookup(where(n))); } catch (e) {
227
+ // A list rule: each entry through the same grammar, so the list is numbers by the time a design reads it
228
+ const each = (x) => { if (typeof x !== 'number' && typeof x !== 'string') throw new Error('each entry of a list is a number or an expression'); const n = evaluate(x, (k) => lookup(where(k))); if (Array.isArray(n)) throw new Error('holds a list inside a list'); return n; };
229
+ try { v = Array.isArray(src) ? src.map(each) : evaluate(src, (n) => lookup(where(n))); if (Array.isArray(v) && !v.length) throw new Error('is an empty list'); } catch (e) {
224
230
  busy.delete(name); stack.pop();
225
231
  // A rule with words for a value and no unit (a bearing's "radial", a pinout) is text, read as it is
226
232
  if (name.includes('.') && typeof src === 'string' && !ruleOf(name)?.unit) { done.set(name, src); return src; }
@@ -266,33 +272,54 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
266
272
  // A published rule set, held to what makes it traceable: every value says what it is, how far to trust it, where it
267
273
  // comes from and when it was checked. A set with "part" (a motor) uses the shared names in vocabulary (the rule sets'
268
274
  // vocabulary.json), every required one, each in its unit; an older set says which of its rules is which in "interface".
275
+ // A vocabulary may also say what must hold between a part's figures, in "checks": { "<part>": [ … ] }, each one of
276
+ // { "ascending": ["tap_drill", "major_diameter", "clearance"], "says": "…" } the names it has, each larger than the last
277
+ // { "near": "tap_drill", "to": "major_diameter - pitch", "within": "0.2 * pitch", "says": "…" } expressions over its own rules
278
+ // and a field marked "list": true holds a list (the lengths a screw is sold in), which must ascend.
269
279
  const KINDS = ['measured', 'spec', 'community', 'default', 'derived', 'estimate'];
280
+ const finite = (x) => typeof x === 'number' && Number.isFinite(x);
270
281
  /**
271
282
  * @param {RuleSet & { part?: string, interface?: Record<string, string> }} set
272
- * @param {{ units: string[], prefixes: string[], fields: Record<string, { unit?: string, choice?: string[] }>, parts: Record<string, string[]> }} vocabulary
273
- * @returns {{ level: 'fail', code: string, text: string, rule?: string }[]} what's wrong with it: nothing, if it passes
283
+ * @param {{ units: string[], prefixes: string[], fields: Record<string, { unit?: string, choice?: string[], list?: boolean }>, parts: Record<string, string[]>, checks?: Record<string, { ascending?: string[], near?: string, to?: string, within?: string, says: string }[]> }} vocabulary
284
+ * @returns {{ level: 'fail', code: string, text: string, rule?: string, values?: Record<string, number> }[]} what's wrong with it: nothing, if it passes
274
285
  */
275
286
  export function checkRuleSet(set, vocabulary) {
276
- const out = [], f = (code, text, rule) => out.push({ level: 'fail', code, text, ...(rule ? { rule } : {}) }), { units, prefixes, fields, parts } = vocabulary, rules = set?.rules;
287
+ const out = [], f = (code, text, rule, values) => out.push({ level: 'fail', code, text, ...(rule ? { rule } : {}), ...(values ? { values } : {}) }), { units, prefixes, fields, parts } = vocabulary, rules = set?.rules;
277
288
  if (!rules || typeof rules !== 'object' || !Object.keys(rules).length) { f('rules.shape', 'it has no rules'); return out; }
278
289
  for (const [name, r] of Object.entries(rules)) {
279
- if (!(typeof r.value === 'number' ? Number.isFinite(r.value) : typeof r.value === 'string' && r.value)) f('rules.value', `${name} has no value`, name);
290
+ const list = Array.isArray(r.value);
291
+ if (!(list ? r.value.length && r.value.every(finite) : finite(r.value) || (typeof r.value === 'string' && r.value))) f('rules.value', list ? `${name} is a list, so every entry is a number and there is at least one` : `${name} has no value`, name);
292
+ else if (list) { const i = r.value.findIndex((x, k) => k && x <= r.value[k - 1]); if (i > 0) f('rules.order', `${name} is a list in ascending order: ${r.value[i]} follows ${r.value[i - 1]}`, name, { before: r.value[i - 1], after: r.value[i] }); }
280
293
  if (!(typeof r.rule === 'string' && r.rule.length > 5)) f('rules.says', `${name} doesn't say what it is ("rule")`, name);
281
294
  if (!KINDS.includes(r.kind)) f('rules.kind', `${name}: kind ${JSON.stringify(r.kind)} is not one of ${KINDS.join(', ')}`, name);
282
295
  if (!(typeof r.source === 'string' && r.source)) f('rules.source', `${name} has no source`, name);
283
296
  if (!/^\d{4}-\d{2}-\d{2}$/.test(String(r.checked))) f('rules.checked', `${name}: checked is the date it was last checked, YYYY-MM-DD (got ${JSON.stringify(r.checked)})`, name);
284
297
  if (set.part) {
285
298
  if (r.unit != null && !units.includes(r.unit)) f('rules.unit', `${name}: unit ${JSON.stringify(r.unit)} is not one of ${units.filter(Boolean).join(', ')}`, name);
286
- if (typeof r.value === 'number' && r.unit == null) f('rules.unit', `${name} is a number with no unit (give "unit", "" if it has none)`, name);
299
+ if ((typeof r.value === 'number' || list) && r.unit == null) f('rules.unit', `${name} is a number with no unit (give "unit", "" if it has none)`, name);
287
300
  const field = fields[name];
288
301
  if (prefixes.some((p) => name.startsWith(p)) && !field) f('rules.name', `${name} is not in the vocabulary (a name starting ${prefixes.join(', ')} says how a part mounts, so everything reads it the same way)`, name);
289
302
  if (field?.unit != null && r.unit !== field.unit) f('rules.unit', `${name} is in ${JSON.stringify(field.unit)}, not ${JSON.stringify(r.unit ?? null)}`, name);
290
303
  if (field?.choice && !field.choice.includes(r.value)) f('rules.choice', `${name} is one of ${field.choice.join(', ')} (got ${JSON.stringify(r.value)})`, name);
304
+ if (field && !!field.list !== list) f('rules.list', field.list ? `${name} is a list: "value": [ … ] (got ${JSON.stringify(r.value)})` : `${name} is one value, not a list`, name);
291
305
  }
292
306
  }
293
307
  if (set.part) {
294
308
  if (!parts[set.part]) f('rules.part', `part ${JSON.stringify(set.part)} is not one of ${Object.keys(parts).join(', ')}`);
295
309
  else for (const name of parts[set.part]) if (!rules[name]) f('rules.missing', `a ${set.part} needs ${name}`, name);
310
+ // What must hold between its figures: only over the numbers it has, so a size made without a head form passes
311
+ const num = (name) => (finite(rules[name]?.value) ? rules[name].value : undefined);
312
+ const work = (src) => { try { return evaluate(src, (n) => { const v = num(n); if (v === undefined) throw new Error('absent'); return v; }); } catch { return undefined; } };
313
+ for (const c of vocabulary.checks?.[set.part] || []) {
314
+ if (c.ascending) {
315
+ const have = c.ascending.filter((n) => num(n) !== undefined);
316
+ for (let i = 1; i < have.length; i++) if (!(num(have[i]) > num(have[i - 1]))) f('rules.order', `${have[i]} (${num(have[i])}) is not larger than ${have[i - 1]} (${num(have[i - 1])}): ${c.says}`, have[i], { [have[i - 1]]: num(have[i - 1]), [have[i]]: num(have[i]) });
317
+ }
318
+ if (c.near) {
319
+ const v = num(c.near), to = work(c.to), within = work(c.within);
320
+ if (v !== undefined && to !== undefined && within !== undefined && !(Math.abs(v - to) <= within + 1e-9)) f('rules.near', `${c.near} (${v}) is not within ${fmt(within)} of ${c.to} (${fmt(to)}): ${c.says}`, c.near, { [c.near]: v, expected: to, within });
321
+ }
322
+ }
296
323
  }
297
324
  for (const [shared, own] of Object.entries(set.interface || {})) {
298
325
  if (!fields[shared]) f('rules.name', `interface: ${shared} is not in the vocabulary`, own);
@@ -306,7 +333,7 @@ export function checkRuleSet(set, vocabulary) {
306
333
  return out;
307
334
  }
308
335
 
309
- export const fmt = (n) => (typeof n === 'number' ? String(Number(n.toFixed(2))) : String(n)); // choices are names
336
+ export const fmt = (n) => (typeof n === 'number' ? String(Number(n.toFixed(2))) : Array.isArray(n) ? n.map(fmt).join(', ') : String(n)); // choices are names; a list rule, each entry
310
337
 
311
338
  // lint(source) -> [{ line, text }]: number literals in a design's code that should be variables. Every measurement
312
339
  // belongs in a variable that says where it comes from; only 0, 1 and 2 (and numbers in comments and strings) pass.