@rulecad/variables 0.1.6 → 0.1.7
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/package.json +1 -1
- package/variables.d.mts +13 -6
- package/variables.mjs +87 -14
package/package.json
CHANGED
package/variables.d.mts
CHANGED
|
@@ -6,11 +6,20 @@ export function checkName(name: any, d: any, v: any): string | number;
|
|
|
6
6
|
* @returns {number}
|
|
7
7
|
*/
|
|
8
8
|
export function evaluate(src: string | number, lookup: (name: string) => number): number;
|
|
9
|
+
/**
|
|
10
|
+
* The unit an expression comes to, and any mixing of units on the way (mm added to degrees, a sine of millimetres).
|
|
11
|
+
* @param {string | number} src @param {(name: string) => string | undefined} unitOf a name's unit
|
|
12
|
+
* @returns {{ unit: string | null, problems: string[] }}
|
|
13
|
+
*/
|
|
14
|
+
export function unitsOf(src: string | number, unitOf: (name: string) => string | undefined): {
|
|
15
|
+
unit: string | null;
|
|
16
|
+
problems: string[];
|
|
17
|
+
};
|
|
9
18
|
/**
|
|
10
19
|
* Every variable's value, and an entry for each variable and rule for checks and rule cards.
|
|
11
20
|
* @param {DesignObject} object
|
|
12
21
|
* @param {{ sets?: Record<string, RuleSet>, set?: Record<string, number | string>, display?: Record<string, number | string>, load?: (name: string) => RuleSet }} [options]
|
|
13
|
-
* @returns {{ values: Record<string, any>, entries: Entry[] }}
|
|
22
|
+
* @returns {{ values: Record<string, any>, entries: Entry[], deps: Record<string, string[]> }} deps: each name with the names its own expression reads
|
|
14
23
|
*/
|
|
15
24
|
export function resolve(object: DesignObject, { sets, set, display, load }?: {
|
|
16
25
|
sets?: Record<string, RuleSet>;
|
|
@@ -20,6 +29,7 @@ export function resolve(object: DesignObject, { sets, set, display, load }?: {
|
|
|
20
29
|
}): {
|
|
21
30
|
values: Record<string, any>;
|
|
22
31
|
entries: Entry[];
|
|
32
|
+
deps: Record<string, string[]>;
|
|
23
33
|
};
|
|
24
34
|
/**
|
|
25
35
|
* Number literals in a design's code other than 0, 1 and 2 (outside comments and strings).
|
|
@@ -30,10 +40,6 @@ export function lint(source: string): {
|
|
|
30
40
|
line: number;
|
|
31
41
|
text: string;
|
|
32
42
|
}[];
|
|
33
|
-
/** @typedef {{ value: number | string, unit?: string, rule?: string, kind?: 'spec' | 'community' | 'default' | 'estimate' | 'measured', source?: string, checked?: string, label?: string, show?: boolean, interface?: boolean, tweak?: { min: number, max: number }, choice?: string[], type?: 'text' | 'anchor' | 'layout' }} Variable */
|
|
34
|
-
/** @typedef {{ name?: string, rules: Record<string, Variable> }} RuleSet */
|
|
35
|
-
/** @typedef {{ uses?: string[], variables?: Record<string, Variable>, [field: string]: any }} DesignObject */
|
|
36
|
-
/** @typedef {{ name: string, value: number | string, used?: boolean, set?: boolean, [field: string]: any }} Entry */
|
|
37
43
|
export const ANCHORS: string[];
|
|
38
44
|
export function isName(d: any): boolean;
|
|
39
45
|
export function options(d: any): any;
|
|
@@ -42,8 +48,9 @@ export type Variable = {
|
|
|
42
48
|
value: number | string;
|
|
43
49
|
unit?: string;
|
|
44
50
|
rule?: string;
|
|
45
|
-
kind?: "spec" | "community" | "default" | "estimate" | "measured";
|
|
51
|
+
kind?: "spec" | "community" | "default" | "estimate" | "measured" | "derived";
|
|
46
52
|
source?: string;
|
|
53
|
+
licence?: string;
|
|
47
54
|
checked?: string;
|
|
48
55
|
label?: string;
|
|
49
56
|
show?: boolean;
|
package/variables.mjs
CHANGED
|
@@ -7,11 +7,14 @@
|
|
|
7
7
|
// No imports and no file access: it runs in a browser as well. Rule sets are handed in (sets) or fetched by name
|
|
8
8
|
// through load(name), such as one that reads rules/<name>.json.
|
|
9
9
|
|
|
10
|
-
/** @typedef {{ value: number | string, unit?: string, rule?: string, kind?: 'spec' | 'community' | 'default' | 'estimate' | 'measured', source?: string, checked?: string, label?: string, show?: boolean, interface?: boolean, tweak?: { min: number, max: number }, choice?: string[], type?: 'text' | 'anchor' | 'layout' }} Variable */
|
|
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' }} Variable */
|
|
11
11
|
/** @typedef {{ name?: string, rules: Record<string, Variable> }} RuleSet */
|
|
12
12
|
/** @typedef {{ uses?: string[], variables?: Record<string, Variable>, [field: string]: any }} DesignObject */
|
|
13
13
|
/** @typedef {{ name: string, value: number | string, used?: boolean, set?: boolean, [field: string]: any }} Entry */
|
|
14
14
|
|
|
15
|
+
// An error with a code (var.unknown, set.range, …) and, where known, the JSON path to fix (variables.cap_h.value)
|
|
16
|
+
const fail = (code, message, path) => Object.assign(new Error(message), { code, ...(path ? { path } : {}) });
|
|
17
|
+
|
|
15
18
|
export const ANCHORS = ['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br'];
|
|
16
19
|
// A variable that holds a name or text, and the names it may hold (null: any text)
|
|
17
20
|
export const isName = (d) => !!(d.choice || ['text', 'anchor', 'layout'].includes(d.type));
|
|
@@ -75,6 +78,58 @@ export function evaluate(src, lookup) {
|
|
|
75
78
|
}
|
|
76
79
|
|
|
77
80
|
|
|
81
|
+
// ---------- units ----------
|
|
82
|
+
// A unit as powers of its parts: "mm" {mm: 1}, "mm²" {mm: 2}, "deg" {deg: 1}. Numbers and names with no unit are
|
|
83
|
+
// unknown (null), which matches anything: only units that are both known and different are a problem.
|
|
84
|
+
const SUP = { '²': 2, '³': 3 }, ALIAS = { '°': 'deg', degrees: 'deg', degree: 'deg' };
|
|
85
|
+
// Physical units only: counts (keys, u, rows, %) are plain numbers, so 12 keys × 19.05 mm is a length
|
|
86
|
+
const PHYSICAL = new Set(['mm', 'cm', 'm', 'in', 'deg', 'rad', 'g', 'kg', 'N', 'W', 'V', 'A', 's', 'ms', 'Hz', 'mAh', 'Wh']);
|
|
87
|
+
function parseUnit(u) {
|
|
88
|
+
if (u == null || u === '') return null;
|
|
89
|
+
const base = /^([a-zA-Z°]+)/.exec(String(u).trim())?.[1];
|
|
90
|
+
if (!PHYSICAL.has(ALIAS[base] || base)) return null;
|
|
91
|
+
const m = /^([a-zA-Z°]+)([²³])?$/.exec(String(u).trim());
|
|
92
|
+
if (!m) return { [String(u)]: 1 };
|
|
93
|
+
return { [ALIAS[m[1]] || m[1]]: m[2] ? SUP[m[2]] : 1 };
|
|
94
|
+
}
|
|
95
|
+
const showUnit = (x) => (x == null ? 'a number' : Object.keys(x).length ? Object.entries(x).map(([k, n]) => (n === 1 ? k : n === 2 ? `${k}²` : n === 3 ? `${k}³` : `${k}^${n}`)).join('·') : 'a plain number');
|
|
96
|
+
const sameUnit = (a, b) => a == null || b == null || (Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, n]) => b[k] === n));
|
|
97
|
+
const combine = (a, b, sign) => { if (a == null) return sign > 0 ? b : null; if (b == null) return a; const o = { ...a }; for (const [k, n] of Object.entries(b)) { o[k] = (o[k] || 0) + sign * n; if (!o[k]) delete o[k]; } return o; };
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The unit an expression comes to, and any mixing of units on the way (mm added to degrees, a sine of millimetres).
|
|
101
|
+
* @param {string | number} src @param {(name: string) => string | undefined} unitOf a name's unit
|
|
102
|
+
* @returns {{ unit: string | null, problems: string[] }}
|
|
103
|
+
*/
|
|
104
|
+
export function unitsOf(src, unitOf) {
|
|
105
|
+
if (typeof src === 'number') return { unit: null, problems: [] };
|
|
106
|
+
const t = tokens(String(src)), problems = [];
|
|
107
|
+
let i = 0;
|
|
108
|
+
const take = (op) => (t[i]?.op === op ? (i++, true) : false);
|
|
109
|
+
const add = (a, b, op) => { if (!sameUnit(a, b)) problems.push(`${op === '+' ? 'adds' : 'takes'} ${showUnit(b)} ${op === '+' ? 'to' : 'from'} ${showUnit(a)}`); return a ?? b; };
|
|
110
|
+
const expr = () => { let v = term(); for (;;) { if (take('+')) v = add(v, term(), '+'); else if (take('-')) v = add(v, term(), '-'); else return v; } };
|
|
111
|
+
const term = () => { let v = unary(); for (;;) { if (take('*')) v = combine(v, unary(), 1); else if (take('/')) v = combine(v, unary(), -1); else return v; } };
|
|
112
|
+
const unary = () => (take('-') || take('+') ? unary() : atom());
|
|
113
|
+
const atom = () => {
|
|
114
|
+
const k = t[i++];
|
|
115
|
+
if (!k) return null;
|
|
116
|
+
if (k.n != null) return null;
|
|
117
|
+
if (k.op === '(') { const v = expr(); take(')'); return v; }
|
|
118
|
+
if (k.id && FNS[k.id] && take('(')) {
|
|
119
|
+
const args = [expr()];
|
|
120
|
+
while (take(',')) args.push(expr());
|
|
121
|
+
take(')');
|
|
122
|
+
if (['sind', 'cosd', 'tand'].includes(k.id)) { if (args[0] && !sameUnit(args[0], { deg: 1 })) problems.push(`takes ${k.id} of ${showUnit(args[0])}, not degrees`); return {}; }
|
|
123
|
+
if (k.id === 'round') return args[0];
|
|
124
|
+
return args.reduce((a, b) => add(a, b, '+'));
|
|
125
|
+
}
|
|
126
|
+
return k.id ? parseUnit(unitOf(k.id)) : null;
|
|
127
|
+
};
|
|
128
|
+
const v = expr();
|
|
129
|
+
return { unit: v == null ? null : showUnit(v), problems, value: v };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
|
|
78
133
|
|
|
79
134
|
// resolve(object, { sets, set }) -> { values, entries }
|
|
80
135
|
// values: { stem_arm: 1.27, x1c: { line: 0.42, … }, mx: { … } } for the design's main()
|
|
@@ -94,44 +149,53 @@ export function evaluate(src, lookup) {
|
|
|
94
149
|
* Every variable's value, and an entry for each variable and rule for checks and rule cards.
|
|
95
150
|
* @param {DesignObject} object
|
|
96
151
|
* @param {{ sets?: Record<string, RuleSet>, set?: Record<string, number | string>, display?: Record<string, number | string>, load?: (name: string) => RuleSet }} [options]
|
|
97
|
-
* @returns {{ values: Record<string, any>, entries: Entry[] }}
|
|
152
|
+
* @returns {{ values: Record<string, any>, entries: Entry[], deps: Record<string, string[]> }} deps: each name with the names its own expression reads
|
|
98
153
|
*/
|
|
99
154
|
export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}) {
|
|
100
155
|
const ruleSets = Object.fromEntries((object.uses || []).map((u) => {
|
|
101
156
|
const s = sets[u] || (load ? load(u) : null);
|
|
102
|
-
if (!s) throw
|
|
157
|
+
if (!s) throw fail('rules.missing', `no rule set "${u}" (hand it in as sets.${u}, or give a load function)`, 'uses');
|
|
103
158
|
return [s.name || u, s];
|
|
104
159
|
}));
|
|
105
160
|
const vars = object.variables || {};
|
|
106
161
|
for (const [k, v] of Object.entries(set)) {
|
|
107
162
|
const d = vars[k];
|
|
108
|
-
if (!d) throw
|
|
163
|
+
if (!d) throw fail('set.unknown', `no variable "${k}" to set (variables: ${Object.keys(vars).join(', ')})`, `variables.${k}`);
|
|
109
164
|
if (isName(d)) { checkName(k, d, v); continue; }
|
|
110
|
-
if (!d.tweak) throw
|
|
165
|
+
if (!d.tweak) throw fail('set.fixed', `"${k}" is fixed by its rule; only variables with a tweak range can be set`, `variables.${k}.tweak`);
|
|
111
166
|
const n = Number(v);
|
|
112
|
-
if (!Number.isFinite(n) || n < d.tweak.min || n > d.tweak.max) throw
|
|
167
|
+
if (!Number.isFinite(n) || n < d.tweak.min || n > d.tweak.max) throw fail('set.range', `${k} must be a number from ${d.tweak.min} to ${d.tweak.max}`, `variables.${k}.tweak`);
|
|
113
168
|
}
|
|
114
169
|
|
|
115
|
-
|
|
170
|
+
// deps: each name's own references (what its expression reads), for explaining a value; stack: whose expression is being read
|
|
171
|
+
const done = new Map(), busy = new Set(), deps = new Map(), stack = [];
|
|
172
|
+
const pathOf = (name) => (name.includes('.') ? `rules.${name}.value` : `variables.${name}.value`);
|
|
116
173
|
const lookup = (name) => {
|
|
174
|
+
if (stack.length) deps.get(stack[stack.length - 1]).add(name);
|
|
117
175
|
if (done.has(name)) return done.get(name);
|
|
118
|
-
if (busy.has(name)) throw
|
|
176
|
+
if (busy.has(name)) throw fail('var.cycle', `"${name}" refers back to itself`, pathOf(name));
|
|
119
177
|
busy.add(name);
|
|
120
178
|
let src, where;
|
|
121
179
|
if (name.includes('.')) {
|
|
122
180
|
let [s, r] = name.split('.');
|
|
123
181
|
if (!ruleSets[s] && ruleSets[s.replace(/_/g, '-')]) s = s.replace(/_/g, '-'); // mx_switch.housing_top reads the set named mx-switch (a - is a minus here)
|
|
124
|
-
if (!ruleSets[s]) throw
|
|
125
|
-
if (!ruleSets[s].rules[r]) throw
|
|
182
|
+
if (!ruleSets[s]) throw fail('var.unknown-set', `"${name}": rule set "${s}" isn't in uses (${Object.keys(ruleSets).join(', ') || 'none'})`);
|
|
183
|
+
if (!ruleSets[s].rules[r]) throw fail('var.unknown-rule', `"${name}": no rule "${r}" in ${s}`);
|
|
126
184
|
src = ruleSets[s].rules[r].value; where = (n) => (n.includes('.') ? n : `${s}.${n}`); // a rule's names are its own set's
|
|
127
185
|
} else {
|
|
128
|
-
if (!vars[name]) throw
|
|
186
|
+
if (!vars[name]) throw fail('var.unknown', `no variable "${name}"`);
|
|
129
187
|
if (isName(vars[name])) { busy.delete(name); const c = checkName(name, vars[name], name in display ? display[name] : name in set ? set[name] : vars[name].value); done.set(name, c); return c; }
|
|
130
188
|
src = name in display ? display[name] : name in set ? Number(set[name]) : vars[name].value; where = (n) => n; // display: the screen's settings win
|
|
131
189
|
}
|
|
132
190
|
let v;
|
|
133
|
-
|
|
134
|
-
|
|
191
|
+
deps.set(name, new Set()); stack.push(name);
|
|
192
|
+
try { v = evaluate(src, (n) => lookup(where(n))); } catch (e) {
|
|
193
|
+
busy.delete(name); stack.pop();
|
|
194
|
+
const out = e.message.startsWith('"') || e.message.startsWith('no ') ? e : fail(e.code || 'var.expression', `"${name}" = ${JSON.stringify(src)}: ${e.message}`);
|
|
195
|
+
if (!out.path) out.path = pathOf(name); // the first expression that reads the bad name: where to fix it
|
|
196
|
+
throw out;
|
|
197
|
+
}
|
|
198
|
+
stack.pop(); busy.delete(name); done.set(name, v);
|
|
135
199
|
return v;
|
|
136
200
|
};
|
|
137
201
|
|
|
@@ -140,6 +204,15 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
|
|
|
140
204
|
values[name] = lookup(name);
|
|
141
205
|
entries.push({ name, ...d, value: values[name], expr: typeof d.value === 'string' ? d.value : undefined, set: name in set });
|
|
142
206
|
}
|
|
207
|
+
// Units: each variable's expression, its names' units mixed only where they agree, and coming to the unit it says
|
|
208
|
+
const unitOf = (n) => (n.includes('.') ? ruleSets[n.split('.')[0].replace(/_/g, '-')]?.rules[n.split('.')[1]]?.unit ?? ruleSets[n.split('.')[0]]?.rules[n.split('.')[1]]?.unit : vars[n]?.unit);
|
|
209
|
+
const units = [];
|
|
210
|
+
for (const [name, d] of Object.entries(vars)) {
|
|
211
|
+
if (typeof d.value !== 'string' || isName(d)) continue;
|
|
212
|
+
const r = unitsOf(d.value, unitOf), said = parseUnit(d.unit);
|
|
213
|
+
for (const p of r.problems) units.push({ name, path: `variables.${name}.value`, message: `"${name}" = ${d.value}: ${p}` });
|
|
214
|
+
if (said && r.value && !sameUnit(said, r.value)) units.push({ name, path: `variables.${name}.unit`, message: `"${name}" comes to ${r.unit}, but its unit says ${showUnit(said)}` });
|
|
215
|
+
}
|
|
143
216
|
const used = new Set(done.keys()); // rules the variables actually refer to (directly or through other rules)
|
|
144
217
|
for (const [s, rs] of Object.entries(ruleSets)) {
|
|
145
218
|
values[s] = {};
|
|
@@ -149,7 +222,7 @@ export function resolve(object, { sets = {}, set = {}, display = {}, load } = {}
|
|
|
149
222
|
}
|
|
150
223
|
if (rs.footprints) values[s].footprints = rs.footprints; // pad data for boards (v.esp32c6.footprints.module), as the set gives it
|
|
151
224
|
}
|
|
152
|
-
return { values, entries };
|
|
225
|
+
return { values, entries, deps: Object.fromEntries([...deps].map(([k, v]) => [k, [...v]])), units };
|
|
153
226
|
}
|
|
154
227
|
|
|
155
228
|
// Round for display: at most 2 decimals, no trailing zeros.
|