@rulecad/variables 0.3.2 → 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 +3 -0
- package/package.json +1 -1
- package/variables.d.mts +13 -4
- package/variables.mjs +41 -11
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
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):
|
|
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)
|
|
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.
|
|
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
|
};
|
|
@@ -196,6 +199,7 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
|
|
|
196
199
|
// deps: each name's own references (what its expression reads), for explaining a value; stack: whose expression is being read
|
|
197
200
|
const done = new Map(), busy = new Set(), deps = new Map(), stack = [];
|
|
198
201
|
const pathOf = (name) => (name.includes('.') ? `rules.${name}.value` : `variables.${name}.value`);
|
|
202
|
+
const ruleOf = (name) => { let [t, r] = name.split('.'); if (!own(ruleSets, t)) t = t.replace(/_/g, '-'); return ruleSets[t]?.rules[r]; };
|
|
199
203
|
const lookup = (name) => {
|
|
200
204
|
if (stack.length) deps.get(stack[stack.length - 1]).add(name);
|
|
201
205
|
if (done.has(name)) return done.get(name);
|
|
@@ -216,11 +220,16 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
|
|
|
216
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; }
|
|
217
221
|
src = shown ? display[name] : given ? Number(set[name]) : d.value; where = (n) => n; // display: the screen's settings win
|
|
218
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`);
|
|
219
224
|
}
|
|
220
225
|
let v;
|
|
221
226
|
deps.set(name, new Set()); stack.push(name);
|
|
222
|
-
|
|
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) {
|
|
223
230
|
busy.delete(name); stack.pop();
|
|
231
|
+
// A rule with words for a value and no unit (a bearing's "radial", a pinout) is text, read as it is
|
|
232
|
+
if (name.includes('.') && typeof src === 'string' && !ruleOf(name)?.unit) { done.set(name, src); return src; }
|
|
224
233
|
const out = e.message.startsWith('"') || e.message.startsWith('no ') ? e : fail(e.code || 'var.expression', `"${name}" = ${JSON.stringify(src)}: ${e.message}`);
|
|
225
234
|
if (!out.path) out.path = pathOf(name); // the first expression that reads the bad name: where to fix it
|
|
226
235
|
throw out;
|
|
@@ -263,33 +272,54 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
|
|
|
263
272
|
// A published rule set, held to what makes it traceable: every value says what it is, how far to trust it, where it
|
|
264
273
|
// comes from and when it was checked. A set with "part" (a motor) uses the shared names in vocabulary (the rule sets'
|
|
265
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.
|
|
266
279
|
const KINDS = ['measured', 'spec', 'community', 'default', 'derived', 'estimate'];
|
|
280
|
+
const finite = (x) => typeof x === 'number' && Number.isFinite(x);
|
|
267
281
|
/**
|
|
268
282
|
* @param {RuleSet & { part?: string, interface?: Record<string, string> }} set
|
|
269
|
-
* @param {{ units: string[], prefixes: string[], fields: Record<string, { unit?: string, choice?: string[] }>, parts: Record<string, string[]> }} vocabulary
|
|
270
|
-
* @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
|
|
271
285
|
*/
|
|
272
286
|
export function checkRuleSet(set, vocabulary) {
|
|
273
|
-
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;
|
|
274
288
|
if (!rules || typeof rules !== 'object' || !Object.keys(rules).length) { f('rules.shape', 'it has no rules'); return out; }
|
|
275
289
|
for (const [name, r] of Object.entries(rules)) {
|
|
276
|
-
|
|
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] }); }
|
|
277
293
|
if (!(typeof r.rule === 'string' && r.rule.length > 5)) f('rules.says', `${name} doesn't say what it is ("rule")`, name);
|
|
278
294
|
if (!KINDS.includes(r.kind)) f('rules.kind', `${name}: kind ${JSON.stringify(r.kind)} is not one of ${KINDS.join(', ')}`, name);
|
|
279
295
|
if (!(typeof r.source === 'string' && r.source)) f('rules.source', `${name} has no source`, name);
|
|
280
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);
|
|
281
297
|
if (set.part) {
|
|
282
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);
|
|
283
|
-
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);
|
|
284
300
|
const field = fields[name];
|
|
285
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);
|
|
286
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);
|
|
287
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);
|
|
288
305
|
}
|
|
289
306
|
}
|
|
290
307
|
if (set.part) {
|
|
291
308
|
if (!parts[set.part]) f('rules.part', `part ${JSON.stringify(set.part)} is not one of ${Object.keys(parts).join(', ')}`);
|
|
292
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
|
+
}
|
|
293
323
|
}
|
|
294
324
|
for (const [shared, own] of Object.entries(set.interface || {})) {
|
|
295
325
|
if (!fields[shared]) f('rules.name', `interface: ${shared} is not in the vocabulary`, own);
|
|
@@ -303,7 +333,7 @@ export function checkRuleSet(set, vocabulary) {
|
|
|
303
333
|
return out;
|
|
304
334
|
}
|
|
305
335
|
|
|
306
|
-
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
|
|
307
337
|
|
|
308
338
|
// lint(source) -> [{ line, text }]: number literals in a design's code that should be variables. Every measurement
|
|
309
339
|
// belongs in a variable that says where it comes from; only 0, 1 and 2 (and numbers in comments and strings) pass.
|