@floless/app 0.170.0 → 0.171.0

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.
Files changed (53) hide show
  1. package/dist/floless-server.cjs +33000 -22928
  2. package/dist/schemas/steel.model.v2.schema.json +194 -3
  3. package/dist/skills/floless-app-bridge/SKILL.md +3 -3
  4. package/dist/skills/floless-app-knowledge/SKILL.md +4 -3
  5. package/dist/skills/floless-app-onboarding/SKILL.md +5 -4
  6. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +0 -3
  7. package/dist/skills/floless-app-queue/SKILL.md +2 -3
  8. package/dist/skills/floless-app-report-issue/SKILL.md +2 -2
  9. package/dist/skills/floless-app-steel-model/SKILL.md +35 -35
  10. package/dist/skills/floless-app-steel-model/references/custom-connections.md +47 -0
  11. package/dist/skills/floless-app-steel-model/references/custom-sections.md +32 -0
  12. package/dist/skills/floless-app-ui/SKILL.md +71 -126
  13. package/dist/web/add-ons.js +407 -0
  14. package/dist/web/analytics.js +1 -1
  15. package/dist/web/app.css +108 -189
  16. package/dist/web/app.js +11 -12
  17. package/dist/web/aware.js +49 -29
  18. package/dist/web/chat.css +6 -1
  19. package/dist/web/chat.js +133 -18
  20. package/dist/web/commands-filter.js +23 -0
  21. package/dist/web/commands-shell.js +39 -67
  22. package/dist/web/commands-steel.js +9 -1
  23. package/dist/web/commands-tekla-parser.js +23 -0
  24. package/dist/web/connections.js +14 -3
  25. package/dist/web/failure-copy.js +1 -0
  26. package/dist/web/guide.js +3 -3
  27. package/dist/web/index.html +29 -56
  28. package/dist/web/instructor.js +2 -2
  29. package/dist/web/kb-categories.js +64 -7
  30. package/dist/web/model-change-findings.js +430 -0
  31. package/dist/web/model-change-review.js +414 -0
  32. package/dist/web/model-editor-steel-adapter.js +2 -2
  33. package/dist/web/project-history.js +7 -1
  34. package/dist/web/revit-editor.css +85 -0
  35. package/dist/web/revit-editor.js +36 -1
  36. package/dist/web/sha256-sync.js +62 -0
  37. package/dist/web/steel-3d-core.js +7 -0
  38. package/dist/web/steel-3d-flo.js +127 -3
  39. package/dist/web/steel-3d-view.js +25 -2
  40. package/dist/web/steel-custom-connection.js +161 -0
  41. package/dist/web/steel-custom-sections.js +1796 -0
  42. package/dist/web/steel-editor.html +279 -41
  43. package/dist/web/steel-filter-usage.js +299 -0
  44. package/dist/web/steel-filter.html +101 -4
  45. package/dist/web/steel-model-v2-client-validation.js +3 -0
  46. package/dist/web/steel-model-v2-commands.js +95 -6
  47. package/dist/web/steel-model-v2-projection.js +1 -1
  48. package/dist/web/steel-read-confidence.js +1 -56
  49. package/dist/web/tekla-editor.html +1 -0
  50. package/dist/web/workspaces.js +263 -28
  51. package/launch.mjs +87 -9
  52. package/package.json +1 -1
  53. package/dist/web/panels.js +0 -831
@@ -0,0 +1,1796 @@
1
+ /*
2
+ * Custom sections in steel.model/v2 (add-ons S1a, design §4).
3
+ *
4
+ * A model carries two kinds of entry for a section that is not in the catalogue:
5
+ *
6
+ * - `section_definitions[]` — a definition (a recipe with parameters) inside a versioned extension
7
+ * envelope `{ envelope: 1, kind, kindVersion, id, digest, payload }`. The schema checks the envelope only
8
+ * and keeps `payload` opaque, so a definition this FloLess cannot read is still preserved as the same
9
+ * JSON value. A known kind's payload is checked here, in code.
10
+ * - `custom_sections[]` — one evaluated section per distinct use: the definition id, the parameter values,
11
+ * the evaluator version and the MATERIALIZED result (outline in mm, area, extents, an optional canonical
12
+ * shape). Every consumer (geometry, quantities, exports) reads the materialized result, never formulas,
13
+ * so a later evaluator cannot silently change an existing model's quantities.
14
+ *
15
+ * A member points at its evaluated section with `customSectionId`, separate from `profile` (which stays the
16
+ * display designation). A member with a `customSectionId` never consults the catalogue for its section.
17
+ *
18
+ * This module is shared by the server and the browser so the two cannot disagree about an id, a digest, an
19
+ * outline or a mass. It is pure: no I/O, no DOM.
20
+ */
21
+
22
+ import { sha256Hex } from './sha256-sync.js';
23
+ import { STEEL_ENVIRONMENT_IDS } from './steel-environments.js';
24
+
25
+ export const ENVELOPE_VERSION = 1;
26
+ export const SECTION_PROFILE_KIND = 'floless.section-profile';
27
+ /** Kinds this FloLess can read, with the kind versions it can read. */
28
+ export const KNOWN_KINDS = Object.freeze({ [SECTION_PROFILE_KIND]: Object.freeze([1, 2]) });
29
+ /**
30
+ * The evaluator a version-1 definition is evaluated with (S1a's meaning, kept so nothing that reads it changes).
31
+ * Every evaluated section records the evaluator it was made with, and is verified with THAT one, never the newest.
32
+ */
33
+ export const EVALUATOR_VERSION = 1;
34
+ /** Every evaluator this build implements. One per version, kept forever: a version is added, never replaced. */
35
+ export const EVALUATOR_VERSIONS = Object.freeze([1, 2]);
36
+ /** The evaluator a new section of each kind version is made with (epic #3382 §4.2). */
37
+ export const EVALUATOR_FOR_KIND_VERSION = Object.freeze({ 1: 1, 2: 2 });
38
+
39
+ export const DEFINITION_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}\/[a-z0-9][a-z0-9-]{0,63}@[1-9][0-9]{0,8}$/;
40
+ export const DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/;
41
+ const PARAM_NAME = /^[a-z][a-z0-9_]{0,31}$/;
42
+ const MAX_VERTICES = 256;
43
+ const MAX_PARAMETERS = 32;
44
+ const MAX_FORMULA_LENGTH = 200;
45
+ const MAX_COORDINATE_MM = 1e5;
46
+ /** Coordinates and areas are stored rounded to a micrometre so the JSON stays readable and stable. */
47
+ const ROUND = 1e6;
48
+ const round = (value) => {
49
+ const r = Math.round(value * ROUND) / ROUND;
50
+ return Object.is(r, -0) ? 0 : r;
51
+ };
52
+
53
+ const isObj = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
54
+
55
+ /**
56
+ * Canonical JSON: object keys sorted, no whitespace. The identity of a definition and of an evaluated
57
+ * section is a digest of this text, so key order and spacing can never make two ids for one thing.
58
+ * @param {unknown} value
59
+ * @returns {string}
60
+ */
61
+ export function canonicalJson(value) {
62
+ // Iterative on purpose: an add-on payload is opaque and may nest deeper than the call stack, and a stack
63
+ // overflow here would read as a changed definition on save. Each task is a value to write or a literal.
64
+ /** @type {string[]} */
65
+ const out = [];
66
+ /** @type {Array<{ text: string } | { value: unknown }>} */
67
+ const tasks = [{ value }];
68
+ while (tasks.length) {
69
+ const task = /** @type {{ text: string } | { value: unknown }} */ (tasks.pop());
70
+ if ('text' in task) { out.push(task.text); continue; }
71
+ const v = task.value;
72
+ if (Array.isArray(v)) {
73
+ const next = [{ text: ']' }];
74
+ for (let i = v.length - 1; i >= 0; i -= 1) {
75
+ // JSON.stringify writes an undefined array slot as null; keep that, so the text stays valid JSON.
76
+ next.push({ value: v[i] === undefined ? null : v[i] });
77
+ if (i > 0) next.push({ text: ',' });
78
+ }
79
+ next.push({ text: '[' });
80
+ for (const t of next) tasks.push(t);
81
+ } else if (isObj(v)) {
82
+ const keys = Object.keys(v).sort().filter((key) => v[key] !== undefined);
83
+ const next = [{ text: '}' }];
84
+ for (let i = keys.length - 1; i >= 0; i -= 1) {
85
+ next.push({ value: v[keys[i]] }, { text: `${JSON.stringify(keys[i])}:` });
86
+ if (i > 0) next.push({ text: ',' });
87
+ }
88
+ next.push({ text: '{' });
89
+ for (const t of next) tasks.push(t);
90
+ } else {
91
+ if (typeof v === 'number' && !Number.isFinite(v)) throw new Error('canonical JSON cannot hold a non-finite number');
92
+ out.push(JSON.stringify(v));
93
+ }
94
+ }
95
+ return out.join('');
96
+ }
97
+
98
+ /** The digest a definition is bound to: its kind, kind version and payload. @returns {string} */
99
+ export function definitionDigest({ kind, kindVersion, payload }) {
100
+ return `sha256:${sha256Hex(`floless:section-definition:v1\0${canonicalJson({ kind, kindVersion, payload })}`)}`;
101
+ }
102
+
103
+ /**
104
+ * An evaluated section's id: the definition id, the definition's DIGEST, the parameter values and the
105
+ * evaluator version. The digest is there so the id is bound to what the definition says, not only to its
106
+ * name: a definition re-bound under the same id by any path makes its sections stop verifying.
107
+ */
108
+ export function sectionIdFor(definitionId, definitionDigestValue, params, evaluatorVersion) {
109
+ return `sha256:${sha256Hex(`floless:custom-section:v1\0${canonicalJson([definitionId, definitionDigestValue, params, evaluatorVersion])}`)}`;
110
+ }
111
+
112
+ // ---- formulas (evaluator v1) -------------------------------------------------------------------------
113
+ // Grammar: expr := term (('+'|'-') term)* ; term := unary (('*'|'/') unary)* ;
114
+ // unary := '-' unary | primary ; primary := number | name | ('min'|'max') '(' expr ',' expr ')' | '(' expr ')'.
115
+ // Hand-written on purpose: a definition arrives from the AI chat or an imported model, and nothing in it may
116
+ // ever reach `eval` or `Function`.
117
+
118
+ export class FormulaError extends Error {}
119
+
120
+ /**
121
+ * @param {string} source
122
+ * @param {Set<string>} names the parameter names the formula may use
123
+ */
124
+ export function parseFormula(source, names) {
125
+ if (typeof source !== 'string' && typeof source !== 'number') throw new FormulaError('a formula must be text or a number');
126
+ const text = String(source);
127
+ if (!text.trim()) throw new FormulaError('a formula is empty');
128
+ if (text.length > MAX_FORMULA_LENGTH) throw new FormulaError(`a formula is longer than ${MAX_FORMULA_LENGTH} characters`);
129
+ const tokens = [];
130
+ for (let i = 0; i < text.length;) {
131
+ const ch = text[i];
132
+ if (/\s/.test(ch)) { i++; continue; }
133
+ const number = /^(?:\d+(?:\.\d*)?|\.\d+)/.exec(text.slice(i));
134
+ if (number) { tokens.push({ t: 'num', v: Number(number[0]) }); i += number[0].length; continue; }
135
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(i));
136
+ if (word) { tokens.push({ t: 'id', v: word[0] }); i += word[0].length; continue; }
137
+ if ('+-*/(),'.includes(ch)) { tokens.push({ t: ch }); i++; continue; }
138
+ throw new FormulaError(`“${ch}” is not allowed in a formula (use numbers, parameter names, + - * /, brackets, min and max)`);
139
+ }
140
+ let pos = 0;
141
+ const peek = () => tokens[pos];
142
+ const take = (type) => {
143
+ const token = tokens[pos];
144
+ if (!token || token.t !== type) throw new FormulaError(`formula “${text}” is not complete or has a misplaced “${token ? (token.v ?? token.t) : 'end'}”`);
145
+ pos++;
146
+ return token;
147
+ };
148
+ const expr = () => {
149
+ let node = term();
150
+ while (peek() && (peek().t === '+' || peek().t === '-')) node = { op: take(peek().t).t, a: node, b: term() };
151
+ return node;
152
+ };
153
+ const term = () => {
154
+ let node = unary();
155
+ while (peek() && (peek().t === '*' || peek().t === '/')) node = { op: take(peek().t).t, a: node, b: unary() };
156
+ return node;
157
+ };
158
+ const unary = () => {
159
+ if (peek() && peek().t === '-') { take('-'); return { op: 'neg', a: unary() }; }
160
+ return primary();
161
+ };
162
+ const primary = () => {
163
+ const token = peek();
164
+ if (!token) throw new FormulaError(`formula “${text}” ends too early`);
165
+ if (token.t === 'num') { pos++; return { num: token.v }; }
166
+ if (token.t === '(') { take('('); const node = expr(); take(')'); return node; }
167
+ if (token.t === 'id') {
168
+ pos++;
169
+ if (token.v === 'min' || token.v === 'max') {
170
+ take('('); const a = expr(); take(','); const b = expr(); take(')');
171
+ return { op: token.v, a, b };
172
+ }
173
+ if (!names.has(token.v)) throw new FormulaError(`formula “${text}” uses “${token.v}”, which is not one of the parameters`);
174
+ return { name: token.v };
175
+ }
176
+ throw new FormulaError(`formula “${text}” has a misplaced “${token.t}”`);
177
+ };
178
+ const tree = expr();
179
+ if (pos !== tokens.length) throw new FormulaError(`formula “${text}” has something extra after “${text.slice(0, 20)}”`);
180
+ return tree;
181
+ }
182
+
183
+ /** @returns {number} */
184
+ export function evalFormula(node, params) {
185
+ if ('num' in node) return node.num;
186
+ if ('name' in node) return params[node.name];
187
+ const a = evalFormula(node.a, params);
188
+ if (node.op === 'neg') return -a;
189
+ const b = evalFormula(node.b, params);
190
+ switch (node.op) {
191
+ case '+': return a + b;
192
+ case '-': return a - b;
193
+ case '*': return a * b;
194
+ case '/': return a / b;
195
+ case 'min': return Math.min(a, b);
196
+ case 'max': return Math.max(a, b);
197
+ default: throw new FormulaError(`unknown operation ${node.op}`);
198
+ }
199
+ }
200
+
201
+ // ---- the known kind: floless.section-profile v1 --------------------------------------------------------
202
+
203
+ /**
204
+ * Plain-English problems with a `floless.section-profile` v1 payload; empty when it is readable.
205
+ * @param {unknown} payload
206
+ * @returns {string[]}
207
+ */
208
+ export function checkSectionProfileV1(payload) {
209
+ const problems = [];
210
+ if (!isObj(payload)) return ['the definition has no content'];
211
+ const allowed = new Set(['name', 'source', 'parameters', 'outline', 'designation', 'export', 'description']);
212
+ for (const key of Object.keys(payload)) if (!allowed.has(key)) problems.push(`the definition has a field “${key}” this kind does not use`);
213
+ if (typeof payload.name !== 'string' || !payload.name.trim() || payload.name.length > 80) problems.push('the definition needs a name of 1 to 80 characters');
214
+ if (payload.description !== undefined && (typeof payload.description !== 'string' || payload.description.length > 500)) problems.push('the description must be text of at most 500 characters');
215
+ if (payload.source !== undefined) {
216
+ if (!isObj(payload.source) || typeof payload.source.addOnId !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(payload.source.addOnId)
217
+ || (payload.source.addOnVersion !== undefined && (typeof payload.source.addOnVersion !== 'string' || payload.source.addOnVersion.length > 64))
218
+ || Object.keys(payload.source).some((key) => key !== 'addOnId' && key !== 'addOnVersion')) {
219
+ problems.push('the source must name the add-on id (lower-case letters, digits and dashes) and, optionally, its version');
220
+ }
221
+ }
222
+ const names = new Set();
223
+ if (!Array.isArray(payload.parameters) || payload.parameters.length < 1 || payload.parameters.length > MAX_PARAMETERS) {
224
+ problems.push(`the definition needs 1 to ${MAX_PARAMETERS} parameters`);
225
+ } else {
226
+ payload.parameters.forEach((param, i) => {
227
+ if (!isObj(param) || typeof param.name !== 'string' || !PARAM_NAME.test(param.name)) {
228
+ problems.push(`parameter ${i + 1} needs a name in lower case (letters, digits, underscores)`);
229
+ return;
230
+ }
231
+ if (names.has(param.name)) problems.push(`parameter “${param.name}” is listed twice`);
232
+ if (param.name === 'min' || param.name === 'max') problems.push(`“${param.name}” cannot be a parameter name`);
233
+ names.add(param.name);
234
+ for (const key of Object.keys(param)) if (!['name', 'label', 'unit', 'min', 'max'].includes(key)) problems.push(`parameter “${param.name}” has a field “${key}” this kind does not use`);
235
+ if (param.unit !== undefined && param.unit !== 'mm') problems.push(`parameter “${param.name}” must be in mm`);
236
+ if (param.label !== undefined && (typeof param.label !== 'string' || param.label.length > 80)) problems.push(`parameter “${param.name}” has a label that is not short text`);
237
+ for (const bound of ['min', 'max']) {
238
+ if (param[bound] !== undefined && !(typeof param[bound] === 'number' && Number.isFinite(param[bound]))) problems.push(`parameter “${param.name}” has a ${bound} that is not a number`);
239
+ }
240
+ });
241
+ }
242
+ const formula = (source, where) => {
243
+ try { parseFormula(source, names); } catch (error) { problems.push(`${where}: ${error.message}`); }
244
+ };
245
+ if (!Array.isArray(payload.outline) || payload.outline.length < 3 || payload.outline.length > MAX_VERTICES) {
246
+ problems.push(`the outline needs 3 to ${MAX_VERTICES} corners`);
247
+ } else {
248
+ payload.outline.forEach((vertex, i) => {
249
+ if (!Array.isArray(vertex) || vertex.length !== 2) { problems.push(`outline corner ${i + 1} must be a pair [x, y]`); return; }
250
+ formula(vertex[0], `outline corner ${i + 1} x`);
251
+ formula(vertex[1], `outline corner ${i + 1} y`);
252
+ });
253
+ }
254
+ if (payload.designation !== undefined) {
255
+ if (typeof payload.designation !== 'string' || !payload.designation.trim() || payload.designation.length > 120) problems.push('the designation template must be text of at most 120 characters');
256
+ else for (const [, hole] of payload.designation.matchAll(/\{([^}]*)\}/g)) if (!names.has(hole)) problems.push(`the designation names “{${hole}}”, which is not a parameter`);
257
+ }
258
+ if (payload.export !== undefined) {
259
+ if (!isObj(payload.export) || Object.keys(payload.export).some((key) => key !== 'canonical')) problems.push('the export map may only hold “canonical”');
260
+ else if (payload.export.canonical !== undefined) {
261
+ const canonical = payload.export.canonical;
262
+ if (!isObj(canonical) || canonical.shape !== 'i') problems.push('the only canonical export shape this FloLess knows is “i”');
263
+ else {
264
+ for (const key of Object.keys(canonical)) if (!['shape', 'd', 'bf', 'tw', 'tf'].includes(key)) problems.push(`the canonical “i” has a field “${key}” it does not use`);
265
+ for (const key of ['d', 'bf', 'tw', 'tf']) {
266
+ if (canonical[key] === undefined) problems.push(`the canonical “i” needs “${key}”`);
267
+ else formula(canonical[key], `the canonical “i” ${key}`);
268
+ }
269
+ }
270
+ }
271
+ }
272
+ return problems;
273
+ }
274
+
275
+ /** A number printed the one way a designation prints it: up to 3 decimals, no trailing zeros. */
276
+ export function formatValue(value) {
277
+ return String(round(Math.round(value * 1000) / 1000));
278
+ }
279
+
280
+ function designationFor(payload, params) {
281
+ if (typeof payload.designation === 'string') {
282
+ return payload.designation.replace(/\{([^}]*)\}/g, (_, name) => formatValue(params[name]));
283
+ }
284
+ return `${payload.name.trim()} ${payload.parameters.map((param) => formatValue(params[param.name])).join('x')}`;
285
+ }
286
+
287
+ const signedArea = (pts) => {
288
+ let sum = 0;
289
+ for (let i = 0; i < pts.length; i++) {
290
+ const [x0, y0] = pts[i], [x1, y1] = pts[(i + 1) % pts.length];
291
+ sum += x0 * y1 - x1 * y0;
292
+ }
293
+ return sum / 2;
294
+ };
295
+
296
+ const orient = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
297
+ const sign = (v) => (v > 0 ? 1 : v < 0 ? -1 : 0);
298
+ const onSegment = (p, q, r) => Math.min(p[0], q[0]) <= r[0] && r[0] <= Math.max(p[0], q[0])
299
+ && Math.min(p[1], q[1]) <= r[1] && r[1] <= Math.max(p[1], q[1]);
300
+
301
+ /** True when segments ab and cd share ANY point: a crossing, an endpoint on the other, or a collinear overlap. */
302
+ function segmentsTouch(a, b, c, d) {
303
+ const o1 = sign(orient(a, b, c)), o2 = sign(orient(a, b, d)), o3 = sign(orient(c, d, a)), o4 = sign(orient(c, d, b));
304
+ if (o1 !== o2 && o3 !== o4) return true;
305
+ return (o1 === 0 && onSegment(a, b, c)) || (o2 === 0 && onSegment(a, b, d))
306
+ || (o3 === 0 && onSegment(c, d, a)) || (o4 === 0 && onSegment(c, d, b));
307
+ }
308
+
309
+ /**
310
+ * True when the closed polygon is not simple: two non-adjacent edges touch at all, or two adjacent edges fold
311
+ * back over each other (the corner between them lies on a straight line that turns back).
312
+ */
313
+ function notSimple(pts) {
314
+ const n = pts.length;
315
+ for (let i = 0; i < n; i++) {
316
+ const a = pts[(i + n - 1) % n], b = pts[i], c = pts[(i + 1) % n];
317
+ // Adjacent edges a-b and b-c: collinear with c pointing back towards a is a fold.
318
+ if (orient(a, b, c) === 0 && ((c[0] - b[0]) * (a[0] - b[0]) + (c[1] - b[1]) * (a[1] - b[1])) > 0) return true;
319
+ }
320
+ for (let i = 0; i < n; i++) {
321
+ for (let j = i + 1; j < n; j++) {
322
+ if (j === i + 1 || (i === 0 && j === n - 1)) continue;
323
+ if (segmentsTouch(pts[i], pts[(i + 1) % n], pts[j], pts[(j + 1) % n])) return true;
324
+ }
325
+ }
326
+ return false;
327
+ }
328
+
329
+ /** The 12 corners of the I that AWARE's canonical `i` describes, centred, counter-clockwise. */
330
+ export function canonicalIOutline({ d, bf, tw, tf }) {
331
+ const hw = bf / 2, hd = d / 2;
332
+ return [[-hw, -hd], [hw, -hd], [hw, -hd + tf], [tw / 2, -hd + tf], [tw / 2, hd - tf], [hw, hd - tf],
333
+ [hw, hd], [-hw, hd], [-hw, hd - tf], [-tw / 2, hd - tf], [-tw / 2, -hd + tf], [-hw, -hd + tf]];
334
+ }
335
+
336
+ const vertexKey = ([x, y]) => `${round(x)},${round(y)}`;
337
+
338
+ /**
339
+ * True when `outline` IS the canonical I: the same boundary, corner after corner, starting anywhere. Both run
340
+ * counter-clockwise (the evaluator normalises the outline; `canonicalIOutline` is written that way). A set of
341
+ * corners is not enough — the same twelve points joined in another order are another polygon.
342
+ */
343
+ export function outlineIsCanonicalI(outline, canonical) {
344
+ const { d, bf, tw, tf } = canonical;
345
+ if (![d, bf, tw, tf].every((v) => Number.isFinite(v) && v > 0) || tw >= bf || 2 * tf >= d) return false;
346
+ const expected = canonicalIOutline(canonical).map(vertexKey);
347
+ const have = outline.map(vertexKey);
348
+ if (have.length !== expected.length) return false;
349
+ const start = have.indexOf(expected[0]);
350
+ if (start < 0) return false;
351
+ return expected.every((key, i) => have[(start + i) % have.length] === key);
352
+ }
353
+
354
+ /**
355
+ * Evaluate a definition at one set of parameter values into the materialized `custom_sections` entry.
356
+ * @param {{kind:string, kindVersion:number, id:string, payload:any}} definition
357
+ * @param {Record<string, number>} params
358
+ * @returns {{ section: any, problems?: undefined } | { section?: undefined, problems: string[] }}
359
+ */
360
+ export function evaluateSection(definition, params) {
361
+ if (isObj(definition) && definition.kind === SECTION_PROFILE_KIND && definition.kindVersion === 2) {
362
+ return evaluateSectionV2(definition, params);
363
+ }
364
+ return evaluateSectionV1(definition, params);
365
+ }
366
+
367
+ /** Evaluator 1, exactly as Add-ons S1a shipped it. Its outputs are pinned by `custom-sections-v1-golden.test.ts`. */
368
+ function evaluateSectionV1(definition, params) {
369
+ if (!isObj(definition) || definition.kind !== SECTION_PROFILE_KIND || definition.kindVersion !== 1) {
370
+ return { problems: [`this FloLess cannot evaluate a definition of kind “${definition?.kind}” version ${definition?.kindVersion}`] };
371
+ }
372
+ if (typeof definition.id !== 'string' || !DEFINITION_ID_PATTERN.test(definition.id)) {
373
+ return { problems: ['the definition id must look like “add-on-id/definition-name@1” (lower case, digits and dashes)'] };
374
+ }
375
+ const payloadProblems = checkSectionProfileV1(definition.payload);
376
+ if (payloadProblems.length) return { problems: payloadProblems };
377
+ const payload = definition.payload;
378
+ const problems = [];
379
+ if (!isObj(params)) return { problems: ['the parameter values must be an object of numbers'] };
380
+ const names = new Set(payload.parameters.map((param) => param.name));
381
+ for (const key of Object.keys(params)) if (!names.has(key)) problems.push(`“${key}” is not a parameter of ${payload.name}`);
382
+ for (const param of payload.parameters) {
383
+ const value = params[param.name];
384
+ if (!(typeof value === 'number' && Number.isFinite(value))) { problems.push(`${param.label || param.name} needs a value in mm`); continue; }
385
+ if (typeof param.min === 'number' && value < param.min) problems.push(`${param.label || param.name} is ${formatValue(value)} mm, below the definition's minimum of ${formatValue(param.min)} mm`);
386
+ if (typeof param.max === 'number' && value > param.max) problems.push(`${param.label || param.name} is ${formatValue(value)} mm, above the definition's maximum of ${formatValue(param.max)} mm`);
387
+ }
388
+ if (problems.length) return { problems };
389
+ const clean = Object.fromEntries(payload.parameters.map((param) => [param.name, params[param.name]]));
390
+
391
+ let raw;
392
+ try {
393
+ raw = payload.outline.map(([x, y]) => [evalFormula(parseFormula(x, names), clean), evalFormula(parseFormula(y, names), clean)]);
394
+ } catch (error) {
395
+ return { problems: [error.message] };
396
+ }
397
+ if (!raw.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y))) {
398
+ return { problems: ['at these values the outline has a corner that is not a finite number (a division by zero?)'] };
399
+ }
400
+ // A cross-section larger than 100 m across is not a steel section, and the bound keeps every derived number
401
+ // (area, extents) finite, so nothing JSON would turn into `null` can be stored.
402
+ if (!raw.every(([x, y]) => Math.abs(x) <= MAX_COORDINATE_MM && Math.abs(y) <= MAX_COORDINATE_MM)) {
403
+ return { problems: [`at these values the outline reaches more than ${MAX_COORDINATE_MM / 1000} m from its origin, which is not a section FloLess can store`] };
404
+ }
405
+ // Centred on the bounding box and rounded to a micrometre FIRST, so every check below runs on exactly the
406
+ // numbers that are stored.
407
+ let loX = Infinity, loY = Infinity, hiX = -Infinity, hiY = -Infinity;
408
+ for (const [x, y] of raw) { loX = Math.min(loX, x); hiX = Math.max(hiX, x); loY = Math.min(loY, y); hiY = Math.max(hiY, y); }
409
+ const cx = (loX + hiX) / 2, cy = (loY + hiY) / 2;
410
+ const centred = raw.map(([x, y]) => [round(x - cx), round(y - cy)]);
411
+ let outline = centred.filter((p, i) => vertexKey(p) !== vertexKey(centred[(i + centred.length - 1) % centred.length]));
412
+ if (outline.length < 3 || new Set(outline.map(vertexKey)).size !== outline.length) {
413
+ return { problems: ['at these values the outline has fewer than 3 distinct corners, or visits a corner twice'] };
414
+ }
415
+ if (notSimple(outline)) return { problems: ['at these values the outline touches or crosses itself'] };
416
+ const area0 = signedArea(outline);
417
+ if (!(Math.abs(area0) > 1e-6)) return { problems: ['at these values the outline has no area'] };
418
+ if (area0 < 0) outline = outline.slice().reverse();
419
+
420
+ let canonical;
421
+ if (payload.export?.canonical) {
422
+ const map = payload.export.canonical;
423
+ const dims = {};
424
+ try {
425
+ for (const key of ['d', 'bf', 'tw', 'tf']) dims[key] = round(evalFormula(parseFormula(map[key], names), clean));
426
+ } catch (error) {
427
+ return { problems: [error.message] };
428
+ }
429
+ if (outlineIsCanonicalI(outline, dims)) canonical = { shape: 'i', ...dims };
430
+ }
431
+
432
+ const section = {
433
+ sectionId: sectionIdFor(definition.id, definitionDigest(definition), clean, EVALUATOR_VERSION),
434
+ definitionId: definition.id,
435
+ params: clean,
436
+ evaluatorVersion: EVALUATOR_VERSION,
437
+ units: 'mm',
438
+ designation: designationFor(payload, clean).slice(0, 120),
439
+ outline,
440
+ area: round(Math.abs(signedArea(outline))),
441
+ width: round(Math.max(...outline.map((p) => p[0])) - Math.min(...outline.map((p) => p[0]))),
442
+ depth: round(Math.max(...outline.map((p) => p[1])) - Math.min(...outline.map((p) => p[1]))),
443
+ ...(canonical ? { canonical } : {}),
444
+ };
445
+ if (![section.area, section.width, section.depth, ...outline.flat(), ...Object.values(clean)].every(Number.isFinite)) {
446
+ return { problems: ['at these values the section has a size that is not a finite number'] };
447
+ }
448
+ return { section };
449
+ }
450
+
451
+ /** The materialized fields a re-evaluation must reproduce (everything but the person's assumption). */
452
+ const MATERIALIZED_KEYS = ['sectionId', 'definitionId', 'params', 'evaluatorVersion', 'units', 'designation', 'outline', 'area', 'width', 'depth', 'canonical'];
453
+ /** Version 2's: every field its result stores, so an accepted assumption is bound to the holes, the reference and the tessellation too. */
454
+ const MATERIALIZED_KEYS_V2 = ['sectionId', 'definitionId', 'params', 'evaluatorVersion', 'units', 'designation', 'outline', 'start', 'end',
455
+ 'tapered', 'reference', 'bounds', 'area', 'width', 'depth', 'canonical', 'tessellation'];
456
+ const isV2Section = (section) => isObj(section) && section.evaluatorVersion === 2;
457
+ const materializedWith = (section, keys) => canonicalJson(Object.fromEntries(keys.filter((key) => section[key] !== undefined).map((key) => [key, section[key]])));
458
+ const materialized = (section) => materializedWith(section, isV2Section(section) ? MATERIALIZED_KEYS_V2 : MATERIALIZED_KEYS);
459
+
460
+ /**
461
+ * The digest of exactly the values a person accepts when they proceed on an assumption. An assumption is
462
+ * bound to it: if any stored value changes afterwards, the old acceptance no longer covers the section.
463
+ */
464
+ export function resultDigest(section) {
465
+ // Version 2 has its own domain prefix, so no v1 result and no v2 result can ever share a digest.
466
+ if (isV2Section(section)) return `sha256:${sha256Hex(`floless:custom-section-result:v2\0${materialized(section)}`)}`;
467
+ return `sha256:${sha256Hex(`floless:custom-section-result:v1\0${materialized(section)}`)}`;
468
+ }
469
+
470
+ /**
471
+ * The words an assumption is recorded with: the person's own, or the standard sentence when they gave none (or an
472
+ * empty one). One function, so the card the chat shows quotes exactly what is stored.
473
+ * @param {unknown} statement
474
+ * @returns {string}
475
+ */
476
+ export function assumptionStatement(statement) {
477
+ return String(statement || 'Proceed on the stored shape of this custom section as a stated assumption.').slice(0, 300);
478
+ }
479
+
480
+ /** The person's "proceed on assumption" record for a section as it is stored now. */
481
+ export function assumptionFor(section, acceptedAt, statement) {
482
+ return {
483
+ acceptedAt,
484
+ resultDigest: resultDigest(section),
485
+ statement: assumptionStatement(statement),
486
+ };
487
+ }
488
+
489
+ /** A definition envelope with its digest computed by FloLess (the caller's digest, if any, is ignored). */
490
+ export function sealDefinition({ kind, kindVersion, id, payload }) {
491
+ return { envelope: ENVELOPE_VERSION, kind, kindVersion, id, digest: definitionDigest({ kind, kindVersion, payload }), payload };
492
+ }
493
+
494
+ /** Whether this FloLess can read a definition's kind at its kind version. */
495
+ export function kindIsKnown(definition) {
496
+ return isObj(definition) && Object.hasOwn(KNOWN_KINDS, definition.kind) && KNOWN_KINDS[definition.kind].includes(definition.kindVersion);
497
+ }
498
+
499
+ /**
500
+ * Verdicts memoised by CONTENT, never by object identity: a section or definition changed in place must be
501
+ * judged again. Bounded so a long editing session cannot grow it without limit.
502
+ */
503
+ const verdicts = new Map();
504
+ const VERDICT_LIMIT = 512;
505
+
506
+ /**
507
+ * How a member's custom section stands. `null` when the member has no `customSectionId`.
508
+ *
509
+ * - `ok` — the definition is one this FloLess reads, both digests verify, and re-evaluating reproduces the
510
+ * stored result exactly.
511
+ * - `unknown-kind` — a kind, kind version or evaluator version this FloLess does not implement. The stored
512
+ * result may well be right; FloLess simply cannot vouch for it.
513
+ * - `unverified` — a digest does not match, or re-evaluating gives a different result.
514
+ * - `missing` — the id names nothing in this model (integrity rejects that on save; it can only reach a reader
515
+ * through a document that was never validated).
516
+ *
517
+ * `usable` is what quantities and exports gate on: `ok`, or anything else the person accepted as a stated
518
+ * assumption (`section.assumption`).
519
+ */
520
+ export function resolveCustomSection(doc, member) {
521
+ const id = member && typeof member.customSectionId === 'string' ? member.customSectionId : null;
522
+ if (!id) return null;
523
+ const sections = Array.isArray(doc?.custom_sections) ? doc.custom_sections : [];
524
+ const section = sections.find((s) => isObj(s) && s.sectionId === id);
525
+ if (!section) return { state: 'missing', usable: false, sectionId: id, section: null, definition: null, label: missingLabel() };
526
+ const definitions = Array.isArray(doc?.section_definitions) ? doc.section_definitions : [];
527
+ const definition = definitions.find((d) => isObj(d) && d.id === section.definitionId) || null;
528
+ let key;
529
+ try { key = `${JSON.stringify(section)}\u0000${JSON.stringify(definition)}`; } catch { key = null; }
530
+ const known = key !== null ? verdicts.get(key) : undefined;
531
+ const verdict = known ?? classify(section, definition);
532
+ if (key !== null && !known) {
533
+ if (verdicts.size >= VERDICT_LIMIT) verdicts.delete(verdicts.keys().next().value);
534
+ verdicts.set(key, verdict);
535
+ }
536
+ // The memo holds only the verdict; the caller gets the live objects it passed in.
537
+ return { ...verdict, section, definition };
538
+ }
539
+
540
+ function classify(section, definition) {
541
+ let assumed = false;
542
+ try { assumed = isObj(section.assumption) && section.assumption.resultDigest === resultDigest(section); } catch { assumed = false; }
543
+ // A version-2 result today's readers would misread is never usable, verified or assumed (see `v2NotYetUsable`).
544
+ // Judged by the section AND its definition: a version-1-shaped result stored against a version-2 definition is
545
+ // unverified, and an assumption on it must not carry a version-2 shape past readers that cannot read one.
546
+ const v2 = isV2Section(section) || (isObj(definition) && definition.kind === SECTION_PROFILE_KIND && definition.kindVersion === 2);
547
+ const blocked = v2 ? v2NotYetUsable(section) : incomplete(section);
548
+ const done = (state, label) => ({
549
+ state,
550
+ usable: !blocked && (state === 'ok' || assumed),
551
+ assumed: !blocked && state !== 'ok' && assumed,
552
+ // Whether proceeding on an assumption could make this section usable: never while it is blocked.
553
+ assumable: !blocked,
554
+ sectionId: section.sectionId, section, definition,
555
+ // Blocked, the state's own first sentence still says what FloLess found, and the reason replaces its offer to
556
+ // proceed on an assumption, which could not help.
557
+ label: !blocked ? label : state === 'ok' ? blocked : `${label.split(/(?<=\.) /)[0]} ${blocked}`,
558
+ });
559
+ if (!definition) return done('missing', missingLabel());
560
+ let digestOk = false, idOk = false;
561
+ try {
562
+ digestOk = definition.digest === definitionDigest(definition);
563
+ idOk = section.sectionId === sectionIdFor(section.definitionId, definition.digest, section.params, section.evaluatorVersion);
564
+ } catch { /* a non-finite value cannot be canonical: unverified below */ }
565
+ if (!digestOk || !idOk) return done('unverified', unverifiedLabel());
566
+ if (!kindIsKnown(definition) || !EVALUATOR_VERSIONS.includes(section.evaluatorVersion)) {
567
+ return done('unknown-kind', unknownLabel(definition, section));
568
+ }
569
+ // A section is verified with the evaluator it RECORDS, which must be the one its definition's kind version is
570
+ // made with: a version-1 definition never vouches for an evaluator-2 result, nor the reverse.
571
+ if (section.evaluatorVersion !== EVALUATOR_FOR_KIND_VERSION[definition.kindVersion]) return done('unverified', unverifiedLabel());
572
+ // A known kind whose payload no longer passes its own checker, or whose recipe no longer reproduces the
573
+ // stored result, is unverified — never an error that stops the model opening.
574
+ const again = evaluateSection(definition, section.params);
575
+ let same = false;
576
+ // A stored value no JSON can hold (NaN, Infinity, edited in memory) cannot be compared: unverified, never a throw.
577
+ try { same = !!again.section && reproduces(again.section, section); } catch { same = false; }
578
+ if (!same) return done('unverified', unverifiedLabel());
579
+ return done('ok', '');
580
+ }
581
+
582
+ function missingLabel() {
583
+ return 'This member names a custom section the model does not carry, so FloLess has no shape for it.';
584
+ }
585
+ function unknownLabel(definition, section) {
586
+ const what = kindIsKnown(definition)
587
+ ? `evaluator version ${section.evaluatorVersion}`
588
+ : `“${definition.kind}” version ${definition.kindVersion}`;
589
+ return `This section was made by a definition this FloLess cannot read (${what}), probably by a newer FloLess. `
590
+ + 'It is drawn as a placeholder and left out of quantities and exports until you proceed on its stored shape as an assumption, or ask the AI to fix it.';
591
+ }
592
+ function unverifiedLabel() {
593
+ return 'This section’s stored shape does not match its definition any more, so FloLess cannot vouch for it. '
594
+ + 'It is drawn as a placeholder and left out of quantities and exports until you proceed on its stored shape as an assumption, or ask the AI to fix it.';
595
+ }
596
+
597
+ // ---- kind version 2 (epic #3382 §4.1): parametric profiles ------------------------------------------------
598
+ // A version-2 definition is what every parametric section is stored as: a built-in shape (a plate, a welded I), a
599
+ // Tekla sketched shape, a hand-drawn or an AI-drafted one. It adds to version 1: case-sensitive sizes with a kind,
600
+ // a default and an advisory typical range; validity predicates; named expressions; a name grammar; trigonometry
601
+ // and square roots; a start and an optional end face, each an outer loop with holes; the definition's own origin as
602
+ // the reference point; canonical round shapes with an analytic area. Version 1 above is untouched.
603
+
604
+ const SYMBOL = /^[A-Za-z][A-Za-z0-9_]{0,31}$/;
605
+ /** Words a formula or a predicate reads as itself, so no size or expression may be called one of them. */
606
+ export const RESERVED_SYMBOLS = Object.freeze(['sin', 'cos', 'tan', 'atan', 'sqrt', 'min', 'max', 'PI', 'and']);
607
+ const RESERVED = new Set(RESERVED_SYMBOLS);
608
+ const FUNCTIONS_1 = new Set(['sin', 'cos', 'tan', 'atan', 'sqrt']);
609
+ const FUNCTIONS_2 = new Set(['min', 'max']);
610
+ const MAX_FORMULA_LENGTH_V2 = 400;
611
+ const MAX_EXPRESSIONS = 64;
612
+ const MAX_PREDICATES = 32;
613
+ const MAX_HOLES = 16;
614
+ const MAX_LOOP_VERTICES = 256;
615
+ /** The most corners one evaluated face may have in all its loops together, so the topology checks stay quick. */
616
+ const MAX_FACE_VERTICES = 1024;
617
+ const MAX_GRAMMAR_DEPTH = 4;
618
+ const MAX_GRAMMAR_TOKENS = 64;
619
+ const MAX_OPTIONAL_GROUPS = 8;
620
+ /** The longest a version-2 canonical name may ever be, at the widest value of every size (§4.4). */
621
+ export const MAX_NAME_LENGTH = 200;
622
+ /** The largest magnitude each kind of size may take. A section is never more than 100 m across. */
623
+ export const SIZE_LIMITS = Object.freeze({ length: 1e5, angle: 360, number: 1e5 });
624
+ const SIZE_UNITS = Object.freeze({ length: 'mm', angle: '°', number: '' });
625
+ const SEPARATOR = /^[-*/xX_]{1,3}$/;
626
+ const PREFIX = /^[A-Za-z_[\]](?:[A-Za-z0-9_[\]]{0,14}[A-Za-z_[\]])?$/;
627
+ /** How far the drawn polygon of a canonical curve may stray from the true curve, in mm (§9). */
628
+ export const CURVE_TOLERANCE_MM = 0.05;
629
+ const CURVE_MIN_SEGMENTS = 16;
630
+ const CURVE_MAX_SEGMENTS = 512;
631
+ /** The canonical shapes of the canonical scene (§5.2), with the descriptor fields AWARE's `XSection` names. */
632
+ export const CANONICAL_SHAPES = Object.freeze({
633
+ i: Object.freeze(['d', 'bf', 'tw', 'tf']),
634
+ channel: Object.freeze(['d', 'bf', 'tw', 'tf']),
635
+ tee: Object.freeze(['d', 'bf', 'tw', 'tf']),
636
+ angle: Object.freeze(['d', 'b', 't']),
637
+ rhs: Object.freeze(['d', 'b', 't']),
638
+ rect: Object.freeze(['w', 'd']),
639
+ chs: Object.freeze(['od', 't']),
640
+ 'solid-circle': Object.freeze(['diameter']),
641
+ });
642
+ const CURVE_SHAPES = new Set(['chs', 'solid-circle']);
643
+
644
+ // ---- formula language v2 -----------------------------------------------------------------------------------
645
+ // expr := term (('+'|'-') term)* ; term := unary (('*'|'/') unary)* ; unary := '-' unary | primary ;
646
+ // primary := number | 'PI' | symbol | f1 '(' expr ')' | f2 '(' expr ',' expr ')' | '(' expr ')',
647
+ // f1 ∈ sin cos tan atan sqrt (radians), f2 ∈ min max. Hand-written; nothing in it ever reaches `eval` or `Function`.
648
+ // Predicates: pred := cmp ('and' cmp)* ; cmp := expr ('<'|'<='|'>'|'>=') expr.
649
+
650
+ function tokensV2(text, comparisons) {
651
+ const tokens = [];
652
+ for (let i = 0; i < text.length;) {
653
+ const ch = text[i];
654
+ if (/\s/.test(ch)) { i++; continue; }
655
+ const number = /^(?:\d+(?:\.\d*)?|\.\d+)/.exec(text.slice(i));
656
+ if (number) { tokens.push({ t: 'num', v: Number(number[0]) }); i += number[0].length; continue; }
657
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(i));
658
+ if (word) { tokens.push({ t: 'id', v: word[0] }); i += word[0].length; continue; }
659
+ if (comparisons && (ch === '<' || ch === '>')) {
660
+ const op = text[i + 1] === '=' ? `${ch}=` : ch;
661
+ tokens.push({ t: 'cmp', v: op }); i += op.length; continue;
662
+ }
663
+ if ('+-*/(),'.includes(ch)) { tokens.push({ t: ch }); i++; continue; }
664
+ throw new FormulaError(`“${ch}” is not allowed in a ${comparisons ? 'condition' : 'formula'} (use numbers, size names, + - * /, brackets, min, max, sin, cos, tan, atan, sqrt and PI${comparisons ? ', the comparisons < <= > >= and “and”' : ''})`);
665
+ }
666
+ return tokens;
667
+ }
668
+
669
+ function formulaText(source, what) {
670
+ if (typeof source === 'number') {
671
+ if (!Number.isFinite(source)) throw new FormulaError(`a ${what} must be a finite number`);
672
+ return null;
673
+ }
674
+ if (typeof source !== 'string') throw new FormulaError(`a ${what} must be text or a number`);
675
+ if (!source.trim()) throw new FormulaError(`a ${what} is empty`);
676
+ if (source.length > MAX_FORMULA_LENGTH_V2) throw new FormulaError(`a ${what} is longer than ${MAX_FORMULA_LENGTH_V2} characters`);
677
+ return source;
678
+ }
679
+
680
+ function parserV2(text, tokens, symbols) {
681
+ let pos = 0;
682
+ const peek = () => tokens[pos];
683
+ const shown = (token) => (token ? String(token.v ?? token.t) : 'end');
684
+ const take = (type) => {
685
+ const token = tokens[pos];
686
+ if (!token || token.t !== type) throw new FormulaError(`“${text}” is not complete or has a misplaced “${shown(token)}”`);
687
+ pos++;
688
+ return token;
689
+ };
690
+ const expr = () => {
691
+ let node = term();
692
+ while (peek() && (peek().t === '+' || peek().t === '-')) node = { op: take(peek().t).t, a: node, b: term() };
693
+ return node;
694
+ };
695
+ const term = () => {
696
+ let node = unary();
697
+ while (peek() && (peek().t === '*' || peek().t === '/')) node = { op: take(peek().t).t, a: node, b: unary() };
698
+ return node;
699
+ };
700
+ const unary = () => {
701
+ if (peek() && peek().t === '-') { take('-'); return { op: 'neg', a: unary() }; }
702
+ return primary();
703
+ };
704
+ const primary = () => {
705
+ const token = peek();
706
+ if (!token) throw new FormulaError(`“${text}” ends too early`);
707
+ if (token.t === 'num') { pos++; return { num: token.v }; }
708
+ if (token.t === '(') { take('('); const node = expr(); take(')'); return node; }
709
+ if (token.t === 'id') {
710
+ pos++;
711
+ if (token.v === 'PI') return { num: Math.PI };
712
+ if (FUNCTIONS_1.has(token.v)) { take('('); const a = expr(); take(')'); return { fn: token.v, a }; }
713
+ if (FUNCTIONS_2.has(token.v)) { take('('); const a = expr(); take(','); const b = expr(); take(')'); return { op: token.v, a, b }; }
714
+ if (token.v === 'and') throw new FormulaError(`“${text}” uses “and” where a value belongs`);
715
+ if (!symbols.has(token.v)) throw new FormulaError(`“${text}” uses “${token.v}”, which is not a size or expression of this shape`);
716
+ return { sym: token.v };
717
+ }
718
+ throw new FormulaError(`“${text}” has a misplaced “${shown(token)}”`);
719
+ };
720
+ return { expr, peek, take, done: () => pos === tokens.length, shown };
721
+ }
722
+
723
+ /**
724
+ * Parse a formula-language-v2 formula. `symbols` holds the sizes and expressions it may use (case-sensitive).
725
+ * A plain finite number is a formula too.
726
+ * @param {string|number} source
727
+ * @param {Set<string>} symbols
728
+ */
729
+ export function parseFormulaV2(source, symbols) {
730
+ const text = formulaText(source, 'formula');
731
+ if (text === null) return { num: /** @type {number} */ (source) };
732
+ const p = parserV2(text, tokensV2(text, false), symbols);
733
+ const tree = p.expr();
734
+ if (!p.done()) throw new FormulaError(`“${text}” has something extra after its formula`);
735
+ return tree;
736
+ }
737
+
738
+ /** The value of a version-2 formula tree; NaN or ±Infinity when it has none (a division by zero, √ of a negative). */
739
+ export function evalFormulaV2(node, scope) {
740
+ if ('num' in node) return node.num;
741
+ if ('sym' in node) return Object.hasOwn(scope, node.sym) ? scope[node.sym] : NaN;
742
+ const a = evalFormulaV2(node.a, scope);
743
+ if ('fn' in node) {
744
+ switch (node.fn) {
745
+ case 'sin': return Math.sin(a);
746
+ case 'cos': return Math.cos(a);
747
+ case 'tan': return Math.tan(a);
748
+ case 'atan': return Math.atan(a);
749
+ case 'sqrt': return Math.sqrt(a);
750
+ default: throw new FormulaError(`unknown function ${node.fn}`);
751
+ }
752
+ }
753
+ if (node.op === 'neg') return -a;
754
+ const b = evalFormulaV2(node.b, scope);
755
+ switch (node.op) {
756
+ case '+': return a + b;
757
+ case '-': return a - b;
758
+ case '*': return a * b;
759
+ case '/': return a / b;
760
+ case 'min': return Math.min(a, b);
761
+ case 'max': return Math.max(a, b);
762
+ default: throw new FormulaError(`unknown operation ${node.op}`);
763
+ }
764
+ }
765
+
766
+ /** The symbols a formula tree reads. */
767
+ function symbolsOf(node, out = new Set()) {
768
+ if ('sym' in node) out.add(node.sym);
769
+ if (node.a) symbolsOf(node.a, out);
770
+ if (node.b) symbolsOf(node.b, out);
771
+ return out;
772
+ }
773
+
774
+ /**
775
+ * Parse a validity predicate: comparisons of two formulas joined by `and`, nothing else.
776
+ * @param {string} source
777
+ * @param {Set<string>} symbols
778
+ * @returns {{ a: any, cmp: string, b: any }[]}
779
+ */
780
+ export function parsePredicate(source, symbols) {
781
+ if (typeof source !== 'string') throw new FormulaError('a condition must be text');
782
+ const text = formulaText(source, 'condition');
783
+ const p = parserV2(text, tokensV2(text, true), symbols);
784
+ const parts = [];
785
+ for (;;) {
786
+ const a = p.expr();
787
+ const token = p.peek();
788
+ if (!token || token.t !== 'cmp') throw new FormulaError(`“${text}” needs a comparison (< <= > >=) between two values`);
789
+ p.take('cmp');
790
+ const b = p.expr();
791
+ parts.push({ a, cmp: token.v, b });
792
+ if (p.done()) break;
793
+ const next = p.peek();
794
+ if (next.t === 'id' && next.v === 'and') { p.take('id'); continue; }
795
+ throw new FormulaError(`“${text}” may only join comparisons with “and”; it has a misplaced “${p.shown(next)}”`);
796
+ }
797
+ return parts;
798
+ }
799
+
800
+ /**
801
+ * Whether a parsed predicate holds. A comparison that cannot be evaluated (either side not a finite number) is
802
+ * NOT met, and says so with `nonFinite`, so a shape is never assumed to exist where its own rule cannot be checked.
803
+ * @returns {{ met: boolean, nonFinite: boolean }}
804
+ */
805
+ export function evaluatePredicate(parts, scope) {
806
+ let met = true, nonFinite = false;
807
+ for (const { a, cmp, b } of parts) {
808
+ const x = evalFormulaV2(a, scope), y = evalFormulaV2(b, scope);
809
+ if (!Number.isFinite(x) || !Number.isFinite(y)) { met = false; nonFinite = true; continue; }
810
+ const ok = cmp === '<' ? x < y : cmp === '<=' ? x <= y : cmp === '>' ? x > y : x >= y;
811
+ if (!ok) met = false;
812
+ }
813
+ return { met, nonFinite };
814
+ }
815
+
816
+ // ---- sizes and names ----------------------------------------------------------------------------------------
817
+
818
+ /**
819
+ * A size printed the one way a version-2 canonical name prints it (§4.4): fixed-point, at most 6 decimals,
820
+ * trailing zeros removed, never an exponent, never `-0`.
821
+ * @param {number} value
822
+ * @returns {string}
823
+ */
824
+ export function formatSize(value) {
825
+ if (!Number.isFinite(value)) throw new RangeError('a size must be a finite number');
826
+ // `round` has already turned −0 into 0, and toFixed never writes an exponent below 1e21.
827
+ return round(value).toFixed(6).replace(/\.?0+$/, '');
828
+ }
829
+
830
+ /** The longest text `formatSize` can print for a size of this kind. */
831
+ function widestSize(kind) {
832
+ const limit = SIZE_LIMITS[kind];
833
+ return Math.max(formatSize(-limit).length, formatSize(-(limit - 1e-6)).length);
834
+ }
835
+
836
+ /** Every size the grammar names, with its optional group (null when mandatory), in grammar order. */
837
+ function grammarSizes(tokens, group = null, out = []) {
838
+ for (const token of tokens) {
839
+ if (!isObj(token)) continue;
840
+ if (typeof token.size === 'string') out.push({ symbol: token.size, group });
841
+ else if (Array.isArray(token.optional)) grammarSizes(token.optional, token, out);
842
+ }
843
+ return out;
844
+ }
845
+
846
+ /**
847
+ * The longest canonical name a version-2 payload can produce: the prefix, every literal, every optional group
848
+ * present, and every size at its widest printed form.
849
+ */
850
+ export function worstCaseNameLength(payload) {
851
+ const kinds = new Map((Array.isArray(payload?.parameters) ? payload.parameters : []).filter(isObj).map((p) => [p.symbol, p.kind]));
852
+ const walk = (tokens) => tokens.reduce((sum, token) => {
853
+ if (!isObj(token)) return sum;
854
+ if (typeof token.text === 'string') return sum + token.text.length;
855
+ if (typeof token.size === 'string') return sum + widestSize(SIZE_LIMITS[kinds.get(token.size)] ? kinds.get(token.size) : 'length');
856
+ if (Array.isArray(token.optional)) return sum + walk(token.optional);
857
+ return sum;
858
+ }, 0);
859
+ const grammar = payload?.grammar;
860
+ return String(grammar?.prefix ?? '').length + walk(Array.isArray(grammar?.tokens) ? grammar.tokens : []);
861
+ }
862
+
863
+ /**
864
+ * Every way the grammar can be written, as its pattern of separators and size slots (`#`), one per choice of which
865
+ * optional parts are present (a nested part only inside a present one). Two choices with the same pattern write
866
+ * different sizes as the same name; returns that pattern, or '' when every choice reads differently.
867
+ */
868
+ function grammarClash(tokens) {
869
+ const ways = (list) => list.reduce((acc, token) => {
870
+ if (typeof token.text === 'string') return acc.map((w) => w + token.text);
871
+ if (typeof token.size === 'string') return acc.map((w) => `${w}#`);
872
+ const inner = ways(token.optional);
873
+ return acc.flatMap((w) => [w, ...inner.map((x) => w + x)]);
874
+ }, ['']);
875
+ const seen = new Set();
876
+ for (const way of ways(tokens)) {
877
+ if (seen.has(way)) return way;
878
+ seen.add(way);
879
+ }
880
+ return '';
881
+ }
882
+
883
+ /** Problems with a grammar's token list; `ctx.seen` collects every size, `ctx.omitted` every optional part. */
884
+ function checkGrammarTokens(tokens, depth, where, ctx) {
885
+ if (!Array.isArray(tokens) || !tokens.length) { ctx.problems.push(`${where} needs at least one part`); return; }
886
+ if (depth > MAX_GRAMMAR_DEPTH) { ctx.problems.push(`${where} nests optional parts more than ${MAX_GRAMMAR_DEPTH} deep`); return; }
887
+ let previous = null;
888
+ tokens.forEach((token, i) => {
889
+ ctx.count++;
890
+ const at = `${where} part ${i + 1}`;
891
+ const keys = isObj(token) ? Object.keys(token) : [];
892
+ if (isObj(token) && typeof token.size === 'string' && keys.length === 1) {
893
+ if (previous === 'size' || previous === 'optional') ctx.problems.push(`${at}: a size must follow a separator, never another size or an optional part, or the name cannot be read back`);
894
+ if (!ctx.parameters.has(token.size)) ctx.problems.push(`${at} names the size “${token.size}”, which is not one of the shape's sizes`);
895
+ else if (ctx.seen.has(token.size)) ctx.problems.push(`${at}: the size “${token.size}” appears in the name twice`);
896
+ ctx.seen.add(token.size);
897
+ previous = 'size';
898
+ } else if (isObj(token) && typeof token.text === 'string' && keys.length === 1) {
899
+ if (!SEPARATOR.test(token.text)) ctx.problems.push(`${at}: a separator is 1 to 3 of - * / x X _`);
900
+ previous = 'text';
901
+ } else if (isObj(token) && Array.isArray(token.optional) && keys.every((k) => k === 'optional' || k === 'omitted')) {
902
+ if (!(isObj(token.optional[0]) && typeof token.optional[0].text === 'string')) ctx.problems.push(`${at}: an optional part must start with a separator`);
903
+ checkGrammarTokens(token.optional, depth + 1, `${at} (optional)`, ctx);
904
+ const direct = token.optional.filter((t) => isObj(t) && typeof t.size === 'string').map((t) => t.size);
905
+ const omitted = isObj(token.omitted) ? token.omitted : null;
906
+ if (!omitted) ctx.problems.push(`${at}: an optional part must say the value each of its sizes takes when it is left out (“omitted”)`);
907
+ else {
908
+ for (const symbol of direct) if (!Object.hasOwn(omitted, symbol)) ctx.problems.push(`${at}: the optional size “${symbol}” needs the value it takes when left out`);
909
+ for (const symbol of Object.keys(omitted)) if (!direct.includes(symbol)) ctx.problems.push(`${at}: “omitted” names “${symbol}”, which is not a size directly in this optional part`);
910
+ ctx.omitted.push({ group: token, direct, omitted, at });
911
+ }
912
+ previous = 'optional';
913
+ } else {
914
+ ctx.problems.push(`${at} must be a size {size}, a separator {text} or an optional part {optional, omitted}`);
915
+ previous = null;
916
+ }
917
+ });
918
+ }
919
+
920
+ /**
921
+ * Fill in the sizes a name left out: an optional part that is absent takes its `omitted` values, in grammar order,
922
+ * so an omitted value may use any size before it. `params` keeps every size it already has.
923
+ * @returns {{ params: Record<string, number> } | { problems: string[] }}
924
+ */
925
+ export function omittedValues(definition, params) {
926
+ const payload = definition?.payload;
927
+ const tokens = payload?.grammar?.tokens;
928
+ if (!Array.isArray(tokens) || !isObj(params)) return { problems: ['the definition has no name grammar, or the sizes are not an object of numbers'] };
929
+ const out = { ...params };
930
+ const problems = [];
931
+ const all = (group) => grammarSizes(group.optional).map((s) => s.symbol);
932
+ // Every token is visited at its own place in the name, nested parts included, so an omitted value can use any size
933
+ // before it — one inside a nested part that comes earlier too — exactly as the checker's "earlier in the name" allows.
934
+ const walk = (list, group) => {
935
+ for (const token of list) {
936
+ if (!isObj(token)) continue;
937
+ if (typeof token.size === 'string' && group) {
938
+ if (!group.leftOut) {
939
+ if (!Object.hasOwn(params, token.size)) problems.push(`the size “${token.size}” is missing`);
940
+ continue;
941
+ }
942
+ try {
943
+ const value = round(evalFormulaV2(parseFormulaV2(group.token.omitted[token.size], new Set(Object.keys(out))), out));
944
+ if (Number.isFinite(value)) out[token.size] = value;
945
+ else problems.push(`the value “${token.size}” takes when it is left out is not a finite number at these sizes (a division by zero?)`);
946
+ } catch (error) { problems.push(error.message); }
947
+ } else if (Array.isArray(token.optional)) {
948
+ const leftOut = (group?.leftOut ?? false) || all(token).every((s) => !Object.hasOwn(params, s));
949
+ walk(token.optional, { token, leftOut });
950
+ }
951
+ }
952
+ };
953
+ walk(tokens, null);
954
+ return problems.length ? { problems } : { params: out };
955
+ }
956
+
957
+ /**
958
+ * The canonical name of a version-2 shape at these sizes (§4.4): the grammar filled in. An optional part is
959
+ * printed when a size directly in it differs from the value it takes when left out, or a part nested in it is.
960
+ */
961
+ export function canonicalName(definition, params) {
962
+ const grammar = definition.payload.grammar;
963
+ const scope = { ...params };
964
+ const print = (tokens) => tokens.map((token) => {
965
+ if (typeof token.text === 'string') return token.text;
966
+ if (typeof token.size === 'string') return formatSize(scope[token.size]);
967
+ const inner = print(token.optional);
968
+ const differs = token.optional.some((t) => typeof t.size === 'string'
969
+ && round(evalFormulaV2(parseFormulaV2(token.omitted[t.size], new Set(Object.keys(scope))), scope)) !== round(scope[t.size]));
970
+ const nested = token.optional.some((t) => Array.isArray(t.optional) && print([t]) !== '');
971
+ return differs || nested ? inner : '';
972
+ }).join('');
973
+ return `${grammar.prefix}${print(grammar.tokens)}`;
974
+ }
975
+
976
+ // ---- the version-2 checker ----------------------------------------------------------------------------------
977
+
978
+ const isFiniteNumber = (v) => typeof v === 'number' && Number.isFinite(v);
979
+ const environmentsAllowed = () => [...STEEL_ENVIRONMENT_IDS, 'all'];
980
+ const environmentSuffix = (environment) => `-${String(environment).toLowerCase()}`;
981
+ /**
982
+ * The id endings an `all`-environment built-in may not have. Frozen with evaluator 2 (not derived from the
983
+ * environment registry), so an environment added later can never turn an existing id invalid.
984
+ */
985
+ const BUILT_IN_ENVIRONMENT_SUFFIXES = Object.freeze(['-us', '-uk', '-eu']);
986
+
987
+ /**
988
+ * Plain-English problems with a `floless.section-profile` v2 payload; empty when it is readable. Checks the
989
+ * structure, every formula and condition, expression cycles, the name grammar and its worst-case length.
990
+ * Geometry that depends on sizes (a loop crossing itself, a hole touching the outer) is the evaluator's.
991
+ * @param {unknown} payload
992
+ * @returns {string[]}
993
+ */
994
+ export function checkSectionProfileV2(payload) {
995
+ const problems = [];
996
+ if (!isObj(payload)) return ['the definition has no content'];
997
+ const allowed = new Set(['name', 'description', 'source', 'parameters', 'expressions', 'predicates', 'grammar', 'start', 'end', 'export']);
998
+ for (const key of Object.keys(payload)) if (!allowed.has(key)) problems.push(`the definition has a field “${key}” this kind does not use`);
999
+ if (typeof payload.name !== 'string' || !payload.name.trim() || payload.name.length > 80) problems.push('the definition needs a name of 1 to 80 characters');
1000
+ if (payload.description !== undefined && (typeof payload.description !== 'string' || payload.description.length > 500)) problems.push('the description must be text of at most 500 characters');
1001
+ if (payload.source !== undefined) checkSourceV2(payload.source, problems);
1002
+
1003
+ const symbols = new Set();
1004
+ const parameters = new Set();
1005
+ const claim = (symbol, where) => {
1006
+ if (typeof symbol !== 'string' || !SYMBOL.test(symbol)) { problems.push(`${where} needs a name of letters, digits and underscores that starts with a letter (at most 32)`); return false; }
1007
+ if (RESERVED.has(symbol)) { problems.push(`“${symbol}” is a word formulas use, so it cannot name ${where}`); return false; }
1008
+ if (symbols.has(symbol)) { problems.push(`“${symbol}” names two things; sizes and expressions need different names (upper and lower case count as different)`); return false; }
1009
+ symbols.add(symbol);
1010
+ return true;
1011
+ };
1012
+ if (!Array.isArray(payload.parameters) || payload.parameters.length < 1 || payload.parameters.length > MAX_PARAMETERS) {
1013
+ problems.push(`the definition needs 1 to ${MAX_PARAMETERS} sizes`);
1014
+ } else {
1015
+ payload.parameters.forEach((param, i) => {
1016
+ if (!isObj(param)) { problems.push(`size ${i + 1} must be an object`); return; }
1017
+ if (!claim(param.symbol, `size ${i + 1}`)) return;
1018
+ parameters.add(param.symbol);
1019
+ const name = `size “${param.symbol}”`;
1020
+ for (const key of Object.keys(param)) if (!['symbol', 'label', 'kind', 'default', 'typical'].includes(key)) problems.push(`${name} has a field “${key}” this kind does not use`);
1021
+ if (typeof param.label !== 'string' || !param.label.trim() || param.label.length > 80) problems.push(`${name} needs a plain-English label of 1 to 80 characters`);
1022
+ if (!Object.hasOwn(SIZE_LIMITS, param.kind)) { problems.push(`${name} must be a length (mm), an angle (degrees) or a number`); return; }
1023
+ const limit = SIZE_LIMITS[param.kind];
1024
+ if (!isFiniteNumber(param.default) || Math.abs(param.default) > limit) problems.push(`${name} needs a default between −${limit} and ${limit}`);
1025
+ if (param.typical !== undefined) {
1026
+ const t = param.typical;
1027
+ if (!isObj(t) || Object.keys(t).some((k) => k !== 'min' && k !== 'max')
1028
+ || (t.min !== undefined && !isFiniteNumber(t.min)) || (t.max !== undefined && !isFiniteNumber(t.max))
1029
+ || (isFiniteNumber(t.min) && isFiniteNumber(t.max) && t.min > t.max)) {
1030
+ problems.push(`${name} has a typical range that is not {min, max} with min at most max`);
1031
+ }
1032
+ }
1033
+ });
1034
+ }
1035
+
1036
+ const formula = (source, where, scope = symbols) => {
1037
+ try { return parseFormulaV2(source, scope); } catch (error) { problems.push(`${where}: ${error.message}`); return null; }
1038
+ };
1039
+
1040
+ // Expressions: names first (any order may refer to any other), then formulas, then a cycle check.
1041
+ const expressions = [];
1042
+ if (payload.expressions !== undefined) {
1043
+ if (!Array.isArray(payload.expressions) || payload.expressions.length > MAX_EXPRESSIONS) problems.push(`the expressions must be a list of at most ${MAX_EXPRESSIONS}`);
1044
+ else {
1045
+ payload.expressions.forEach((e, i) => {
1046
+ if (!isObj(e) || Object.keys(e).some((k) => k !== 'symbol' && k !== 'formula')) { problems.push(`expression ${i + 1} must be {symbol, formula}`); return; }
1047
+ if (claim(e.symbol, `expression ${i + 1}`)) expressions.push(e);
1048
+ });
1049
+ const reads = new Map();
1050
+ for (const e of expressions) {
1051
+ const tree = formula(e.formula, `expression “${e.symbol}”`);
1052
+ if (tree) reads.set(e.symbol, [...symbolsOf(tree)].filter((s) => !parameters.has(s)));
1053
+ }
1054
+ const cycle = findCycle(reads);
1055
+ if (cycle) problems.push(`the expressions refer to each other in a circle (${cycle.join(' → ')}), so none of them has a value`);
1056
+ }
1057
+ }
1058
+
1059
+ if (payload.predicates !== undefined) {
1060
+ if (!Array.isArray(payload.predicates) || payload.predicates.length > MAX_PREDICATES) problems.push(`the conditions must be a list of at most ${MAX_PREDICATES}`);
1061
+ else payload.predicates.forEach((pr, i) => {
1062
+ if (!isObj(pr) || Object.keys(pr).some((k) => k !== 'when' && k !== 'reason')) { problems.push(`condition ${i + 1} must be {when, reason}`); return; }
1063
+ if (typeof pr.reason !== 'string' || !pr.reason.trim() || pr.reason.length > 200) problems.push(`condition ${i + 1} needs a plain-English reason of 1 to 200 characters`);
1064
+ try { parsePredicate(pr.when, symbols); } catch (error) { problems.push(`condition ${i + 1}: ${error.message}`); }
1065
+ });
1066
+ }
1067
+
1068
+ checkGrammarV2(payload, parameters, problems);
1069
+
1070
+ const canonical = isObj(payload.export) ? payload.export.canonical : undefined;
1071
+ if (payload.export !== undefined) {
1072
+ if (!isObj(payload.export) || Object.keys(payload.export).some((key) => key !== 'canonical')) problems.push('the export map may only hold “canonical”');
1073
+ else if (canonical !== undefined) {
1074
+ if (!isObj(canonical) || !Object.hasOwn(CANONICAL_SHAPES, canonical.shape)) problems.push(`the canonical export shape must be one of ${Object.keys(CANONICAL_SHAPES).join(', ')}`);
1075
+ else {
1076
+ const fields = CANONICAL_SHAPES[canonical.shape];
1077
+ for (const key of Object.keys(canonical)) if (key !== 'shape' && !fields.includes(key)) problems.push(`the canonical “${canonical.shape}” has a field “${key}” it does not use`);
1078
+ for (const key of fields) {
1079
+ if (canonical[key] === undefined) problems.push(`the canonical “${canonical.shape}” needs “${key}”`);
1080
+ else formula(canonical[key], `the canonical “${canonical.shape}” ${key}`);
1081
+ }
1082
+ }
1083
+ }
1084
+ }
1085
+ const curve = isObj(canonical) && CURVE_SHAPES.has(canonical.shape);
1086
+ if (curve) {
1087
+ if (payload.start !== undefined || payload.end !== undefined) problems.push(`a canonical “${canonical.shape}” is drawn from its own sizes, so the definition gives no faces`);
1088
+ } else if (payload.start === undefined) {
1089
+ problems.push('the definition needs a start face {outer, holes}, unless it is a canonical round shape (solid-circle, chs)');
1090
+ } else {
1091
+ checkFaceV2(payload.start, 'the start face', formula, problems);
1092
+ }
1093
+ if (!curve && payload.end !== undefined) checkFaceV2(payload.end, 'the end face', formula, problems);
1094
+ return problems;
1095
+ }
1096
+
1097
+ function checkSourceV2(source, problems) {
1098
+ const addOn = isObj(source) && Object.hasOwn(source, 'addOnId');
1099
+ if (addOn) {
1100
+ if (typeof source.addOnId !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(source.addOnId)
1101
+ || (source.addOnVersion !== undefined && (typeof source.addOnVersion !== 'string' || source.addOnVersion.length > 64))
1102
+ || Object.keys(source).some((key) => key !== 'addOnId' && key !== 'addOnVersion')) {
1103
+ problems.push('an add-on source must name the add-on id (lower-case letters, digits and dashes) and, optionally, its version');
1104
+ }
1105
+ return;
1106
+ }
1107
+ const b = isObj(source) && Object.keys(source).length === 1 ? source.builtIn : undefined;
1108
+ if (!isObj(b) || Object.keys(b).some((k) => !['library', 'libraryVersion', 'environment'].includes(k))
1109
+ || typeof b.library !== 'string' || !b.library.trim() || b.library.length > 64
1110
+ || typeof b.libraryVersion !== 'string' || !b.libraryVersion.trim() || b.libraryVersion.length > 64
1111
+ || !environmentsAllowed().includes(b.environment)) {
1112
+ problems.push(`the source must be {addOnId, addOnVersion} or {builtIn: {library, libraryVersion, environment}}, the environment one of ${environmentsAllowed().join(', ')}`);
1113
+ }
1114
+ }
1115
+
1116
+ function checkGrammarV2(payload, parameters, problems) {
1117
+ const grammar = payload.grammar;
1118
+ if (!isObj(grammar) || Object.keys(grammar).some((k) => k !== 'prefix' && k !== 'tokens')) { problems.push('the definition needs a name grammar {prefix, tokens}'); return; }
1119
+ if (typeof grammar.prefix !== 'string' || !PREFIX.test(grammar.prefix)) problems.push('the name prefix must be 1 to 16 letters, digits, underscores or [ ], and cannot end with a digit');
1120
+ const ctx = { problems, parameters, seen: new Set(), omitted: [], count: 0 };
1121
+ checkGrammarTokens(grammar.tokens, 0, 'the name grammar', ctx);
1122
+ if (ctx.count > MAX_GRAMMAR_TOKENS) problems.push(`the name grammar has more than ${MAX_GRAMMAR_TOKENS} parts`);
1123
+ if (ctx.omitted.length > MAX_OPTIONAL_GROUPS) problems.push(`the name grammar has more than ${MAX_OPTIONAL_GROUPS} optional parts`);
1124
+ else if (!problems.length) {
1125
+ const clash = grammarClash(grammar.tokens);
1126
+ if (clash) problems.push(`the name grammar can write two different sets of sizes the same way (${clash}); make the optional parts differ by their separators or by how many sizes they hold`);
1127
+ }
1128
+ for (const symbol of parameters) if (!ctx.seen.has(symbol)) problems.push(`the size “${symbol}” is not in the name, so the name would not say it`);
1129
+ if (!ctx.seen.size) return;
1130
+ // An omitted value may use only sizes that come EARLIER in the name, so the values can never refer in a circle.
1131
+ const order = grammarSizes(grammar.tokens).map((s) => s.symbol);
1132
+ for (const { omitted, at } of ctx.omitted) {
1133
+ for (const [symbol, source] of Object.entries(omitted)) {
1134
+ const earlier = new Set(order.slice(0, Math.max(0, order.indexOf(symbol))));
1135
+ try { parseFormulaV2(source, earlier); } catch (error) { problems.push(`${at}: the value “${symbol}” takes when left out may use only sizes earlier in the name: ${error.message}`); }
1136
+ }
1137
+ }
1138
+ const worst = worstCaseNameLength(payload);
1139
+ if (worst > MAX_NAME_LENGTH) problems.push(`at its widest sizes the name would be ${worst} characters, more than the ${MAX_NAME_LENGTH} a name may have`);
1140
+ }
1141
+
1142
+ function checkFaceV2(face, where, formula, problems) {
1143
+ if (!isObj(face) || Object.keys(face).some((k) => k !== 'outer' && k !== 'holes')) { problems.push(`${where} must be {outer, holes}`); return; }
1144
+ const loop = (points, name) => {
1145
+ if (!Array.isArray(points) || points.length < 3 || points.length > MAX_LOOP_VERTICES) { problems.push(`${name} needs 3 to ${MAX_LOOP_VERTICES} corners`); return 0; }
1146
+ points.forEach((p, i) => {
1147
+ if (!Array.isArray(p) || p.length !== 2) { problems.push(`${name} corner ${i + 1} must be a pair [x, y]`); return; }
1148
+ formula(p[0], `${name} corner ${i + 1} x`);
1149
+ formula(p[1], `${name} corner ${i + 1} y`);
1150
+ });
1151
+ return points.length;
1152
+ };
1153
+ let total = loop(face.outer, `${where} outer loop`);
1154
+ if (face.holes !== undefined) {
1155
+ if (!Array.isArray(face.holes) || face.holes.length > MAX_HOLES) problems.push(`${where} may have at most ${MAX_HOLES} holes`);
1156
+ else face.holes.forEach((h, i) => { total += loop(h, `${where} hole ${i + 1}`); });
1157
+ }
1158
+ if (total > MAX_FACE_VERTICES) problems.push(`${where} has more than ${MAX_FACE_VERTICES} corners in all`);
1159
+ }
1160
+
1161
+ /** The first circle of references in `reads` (symbol → symbols it reads), or null. */
1162
+ function findCycle(reads) {
1163
+ const state = new Map();
1164
+ const path = [];
1165
+ const visit = (symbol) => {
1166
+ if (state.get(symbol) === 'done') return null;
1167
+ if (state.get(symbol) === 'open') return [...path.slice(path.indexOf(symbol)), symbol];
1168
+ state.set(symbol, 'open');
1169
+ path.push(symbol);
1170
+ for (const next of reads.get(symbol) || []) {
1171
+ if (!reads.has(next)) continue;
1172
+ const found = visit(next);
1173
+ if (found) return found;
1174
+ }
1175
+ path.pop();
1176
+ state.set(symbol, 'done');
1177
+ return null;
1178
+ };
1179
+ for (const symbol of reads.keys()) {
1180
+ const found = visit(symbol);
1181
+ if (found) return found;
1182
+ }
1183
+ return null;
1184
+ }
1185
+
1186
+ /** Expressions in an order where each comes after every expression it reads (the checker has ruled out cycles). */
1187
+ function expressionOrder(expressions, parameters) {
1188
+ const trees = new Map(expressions.map((e) => [e.symbol, parseFormulaV2(e.formula, new Set([...parameters, ...expressions.map((x) => x.symbol)]))]));
1189
+ const order = [];
1190
+ const done = new Set();
1191
+ const visit = (symbol) => {
1192
+ if (done.has(symbol)) return;
1193
+ done.add(symbol);
1194
+ for (const s of symbolsOf(trees.get(symbol))) if (trees.has(s)) visit(s);
1195
+ order.push(symbol);
1196
+ };
1197
+ for (const e of expressions) visit(e.symbol);
1198
+ return order.map((symbol) => [symbol, trees.get(symbol)]);
1199
+ }
1200
+
1201
+ /**
1202
+ * Whether a definition id is a FloLess built-in (`floless/…`). That namespace is reserved for `source.builtIn`.
1203
+ * @param {unknown} id
1204
+ */
1205
+ export function isBuiltInDefinitionId(id) {
1206
+ return typeof id === 'string' && id.startsWith('floless/');
1207
+ }
1208
+
1209
+ /** Problems with a version-2 definition's id against its source (§4.3). */
1210
+ function checkIdV2(id, payload) {
1211
+ if (typeof id !== 'string' || !DEFINITION_ID_PATTERN.test(id)) return ['the definition id must look like “add-on-id/definition-name@1” (lower case, digits and dashes)'];
1212
+ const builtIn = isObj(payload.source) && isObj(payload.source.builtIn) ? payload.source.builtIn : null;
1213
+ if (isBuiltInDefinitionId(id) !== !!builtIn) {
1214
+ return [builtIn ? 'a built-in shape’s id must start with “floless/”' : 'the “floless/” id namespace is kept for FloLess’s built-in shapes'];
1215
+ }
1216
+ if (!builtIn) return [];
1217
+ const name = id.slice('floless/'.length, id.indexOf('@'));
1218
+ if (builtIn.environment === 'all') {
1219
+ return BUILT_IN_ENVIRONMENT_SUFFIXES.some((s) => name.endsWith(s)) ? ['a built-in shape every environment agrees on has no environment ending in its id (“floless/pl@1”)'] : [];
1220
+ }
1221
+ return name.endsWith(environmentSuffix(builtIn.environment)) && name.length > environmentSuffix(builtIn.environment).length
1222
+ ? [] : [`a built-in shape for the ${builtIn.environment} environment ends its id with “${environmentSuffix(builtIn.environment)}” (“floless/hi${environmentSuffix(builtIn.environment)}@1”)`];
1223
+ }
1224
+
1225
+ // ---- evaluator 2 --------------------------------------------------------------------------------------------
1226
+
1227
+ const MAX_TRUE_COORDINATE = MAX_COORDINATE_MM;
1228
+
1229
+ /** A loop evaluated, rounded and cleaned; or a plain-English problem. `ccw` sets the orientation it is stored in. */
1230
+ function loopV2(raw, name, ccw) {
1231
+ if (!raw.every(([x, y]) => Number.isFinite(x) && Number.isFinite(y))) return { problem: `at these sizes ${name} has a corner that is not a finite number (a division by zero?)` };
1232
+ if (!raw.every(([x, y]) => Math.abs(x) <= MAX_TRUE_COORDINATE && Math.abs(y) <= MAX_TRUE_COORDINATE)) {
1233
+ return { problem: `at these sizes ${name} reaches more than ${MAX_TRUE_COORDINATE / 1000} m from the shape's origin, which is not a section FloLess can store` };
1234
+ }
1235
+ const rounded = raw.map(([x, y]) => [round(x), round(y)]);
1236
+ let pts = rounded.filter((p, i) => vertexKey(p) !== vertexKey(rounded[(i + rounded.length - 1) % rounded.length]));
1237
+ if (pts.length < 3 || new Set(pts.map(vertexKey)).size !== pts.length) return { problem: `at these sizes ${name} has fewer than 3 distinct corners, or visits a corner twice` };
1238
+ if (notSimple(pts)) return { problem: `at these sizes ${name} touches or crosses itself` };
1239
+ const a = signedArea(pts);
1240
+ if (!(Math.abs(a) > 1e-6)) return { problem: `at these sizes ${name} has no area` };
1241
+ if ((a > 0) !== ccw) pts = pts.slice().reverse();
1242
+ return { pts };
1243
+ }
1244
+
1245
+ /** True when point p lies strictly inside the simple polygon (ray casting; the caller has ruled out p on an edge). */
1246
+ function insidePolygon(p, pts) {
1247
+ let inside = false;
1248
+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
1249
+ const [xi, yi] = pts[i], [xj, yj] = pts[j];
1250
+ if ((yi > p[1]) !== (yj > p[1]) && p[0] < ((xj - xi) * (p[1] - yi)) / (yj - yi) + xi) inside = !inside;
1251
+ }
1252
+ return inside;
1253
+ }
1254
+
1255
+ function loopsTouch(a, b) {
1256
+ for (let i = 0; i < a.length; i++) {
1257
+ for (let j = 0; j < b.length; j++) {
1258
+ if (segmentsTouch(a[i], a[(i + 1) % a.length], b[j], b[(j + 1) % b.length])) return true;
1259
+ }
1260
+ }
1261
+ return false;
1262
+ }
1263
+
1264
+ /** The holes' topology against the outer loop and one another: each strictly inside, none touching. */
1265
+ function holeProblem(outer, holes, name) {
1266
+ for (let i = 0; i < holes.length; i++) {
1267
+ if (loopsTouch(outer, holes[i])) return `at these sizes hole ${i + 1} of ${name} touches its outer loop`;
1268
+ if (!insidePolygon(holes[i][0], outer)) return `at these sizes hole ${i + 1} of ${name} is not inside its outer loop`;
1269
+ for (let j = 0; j < i; j++) {
1270
+ if (loopsTouch(holes[i], holes[j])) return `at these sizes holes ${j + 1} and ${i + 1} of ${name} touch`;
1271
+ if (insidePolygon(holes[i][0], holes[j]) || insidePolygon(holes[j][0], holes[i])) return `at these sizes hole ${i + 1} of ${name} lies inside hole ${j + 1}`;
1272
+ }
1273
+ }
1274
+ return '';
1275
+ }
1276
+
1277
+ function faceV2(face, scope, symbols, name) {
1278
+ const point = ([x, y]) => [evalFormulaV2(parseFormulaV2(x, symbols), scope), evalFormulaV2(parseFormulaV2(y, symbols), scope)];
1279
+ const outer = loopV2(face.outer.map(point), `the outer loop of ${name}`, true);
1280
+ if (outer.problem) return { problem: outer.problem };
1281
+ const holes = [];
1282
+ for (const [i, hole] of (face.holes ?? []).entries()) {
1283
+ const h = loopV2(hole.map(point), `hole ${i + 1} of ${name}`, false);
1284
+ if (h.problem) return { problem: h.problem };
1285
+ holes.push(h.pts);
1286
+ }
1287
+ const problem = holeProblem(outer.pts, holes, name);
1288
+ return problem ? { problem } : { face: { outer: outer.pts, holes } };
1289
+ }
1290
+
1291
+ /**
1292
+ * The segment count for a circle of radius r: the fewest, a multiple of 4 (so the bounds are exact), from 16 to 512,
1293
+ * that keeps the polygon within `CURVE_TOLERANCE_MM` of the true circle. Worked out with the bound
1294
+ * r·(1 − cos(π/n)) ≤ r·(π/n)²/2 and a square root only, which IEEE 754 rounds the same way on every platform, so
1295
+ * the count can never differ between the browser and the server.
1296
+ */
1297
+ export function curveSegments(r) {
1298
+ const n = Math.ceil(Math.PI * Math.sqrt(r / (2 * CURVE_TOLERANCE_MM)));
1299
+ return Math.min(CURVE_MAX_SEGMENTS, Math.max(CURVE_MIN_SEGMENTS, Math.ceil(n / 4) * 4));
1300
+ }
1301
+
1302
+ /**
1303
+ * The most the drawn polygon of a circle of radius r with n segments can stray from the true circle, in mm (the same
1304
+ * bound, rounded up to a micrometre). Recorded with the result, so a very large round shape (past the 512-segment
1305
+ * cap, a radius over about 2.6 m) says how close its drawing is instead of claiming the usual tolerance.
1306
+ */
1307
+ export function curveDeviation(r, n) {
1308
+ // + 1e-6: each stored corner is rounded to a micrometre, which can move a chord out by up to √2/2 of that.
1309
+ return Math.ceil((r * (Math.PI / n) ** 2 / 2 + 1 / ROUND) * ROUND) / ROUND;
1310
+ }
1311
+
1312
+ /** n points on a circle of radius r about the origin, the first at angle 0; counter-clockwise or clockwise. */
1313
+ function circleLoop(r, n, ccw) {
1314
+ const pts = [];
1315
+ for (let k = 0; k < n; k++) {
1316
+ const t = (2 * Math.PI * k) / n;
1317
+ pts.push([round(r * Math.cos(t)), round(r * Math.sin(t))]);
1318
+ }
1319
+ return ccw ? pts : [pts[0], ...pts.slice(1).reverse()];
1320
+ }
1321
+
1322
+ const loopArea = (pts) => Math.abs(signedArea(pts));
1323
+
1324
+ const cyclicSame = (a, b) => {
1325
+ if (a.length !== b.length) return false;
1326
+ const ka = a.map(vertexKey), kb = b.map(vertexKey);
1327
+ const start = kb.indexOf(ka[0]);
1328
+ return start >= 0 && ka.every((key, i) => kb[(start + i) % kb.length] === key);
1329
+ };
1330
+ const facesSame = (a, b) => cyclicSame(a.outer, b.outer) && a.holes.length === b.holes.length && a.holes.every((h, i) => cyclicSame(h, b.holes[i]));
1331
+
1332
+ /** The loops of a canonical polygonal shape centred on its bounding box, outer counter-clockwise, holes clockwise. */
1333
+ export function canonicalLoops(canonical) {
1334
+ const s = canonical.shape;
1335
+ if (s === 'i') return { outer: canonicalIOutline(canonical), holes: [] };
1336
+ if (s === 'rect') {
1337
+ const hw = canonical.w / 2, hd = canonical.d / 2;
1338
+ return { outer: [[-hw, -hd], [hw, -hd], [hw, hd], [-hw, hd]], holes: [] };
1339
+ }
1340
+ if (s === 'rhs') {
1341
+ const hb = canonical.b / 2, hd = canonical.d / 2, ib = hb - canonical.t, id = hd - canonical.t;
1342
+ return { outer: [[-hb, -hd], [hb, -hd], [hb, hd], [-hb, hd]], holes: [[[-ib, -id], [-ib, id], [ib, id], [ib, -id]]] };
1343
+ }
1344
+ if (s === 'channel') {
1345
+ // IFC's U: the web on the −x side, the flanges reaching towards +x.
1346
+ const { d, bf, tw, tf } = canonical, hb = bf / 2, hd = d / 2;
1347
+ return { outer: [[-hb, -hd], [hb, -hd], [hb, -hd + tf], [-hb + tw, -hd + tf], [-hb + tw, hd - tf], [hb, hd - tf], [hb, hd], [-hb, hd]], holes: [] };
1348
+ }
1349
+ if (s === 'tee') {
1350
+ // IFC's T: the flange on the +y side, the stem centred below it.
1351
+ const { d, bf, tw, tf } = canonical, hb = bf / 2, hd = d / 2, hw = tw / 2;
1352
+ return { outer: [[-hw, -hd], [hw, -hd], [hw, hd - tf], [hb, hd - tf], [hb, hd], [-hb, hd], [-hb, hd - tf], [-hw, hd - tf]], holes: [] };
1353
+ }
1354
+ if (s === 'angle') {
1355
+ // IFC's L: the legs along the −x and −y sides, `d` up and `b` across.
1356
+ const { d, b, t } = canonical, hb = b / 2, hd = d / 2;
1357
+ return { outer: [[-hb, -hd], [hb, -hd], [hb, -hd + t], [-hb + t, -hd + t], [-hb + t, hd], [-hb, hd]], holes: [] };
1358
+ }
1359
+ return null;
1360
+ }
1361
+
1362
+ /** Whether a canonical descriptor's own sizes make that shape at all (positive, thin enough to leave a web). */
1363
+ function canonicalDimsValid(c) {
1364
+ const fields = CANONICAL_SHAPES[c.shape];
1365
+ if (!fields.every((k) => Number.isFinite(c[k]) && c[k] > 0)) return false;
1366
+ switch (c.shape) {
1367
+ case 'i': case 'channel': return c.tw < c.bf && 2 * c.tf < c.d;
1368
+ case 'tee': return c.tw < c.bf && c.tf < c.d;
1369
+ case 'angle': return c.t < c.b && c.t < c.d;
1370
+ case 'rhs': return 2 * c.t < c.b && 2 * c.t < c.d;
1371
+ case 'chs': return 2 * c.t < c.od;
1372
+ default: return true;
1373
+ }
1374
+ }
1375
+
1376
+ /** True when a face IS the canonical polygonal shape: the same loops corner after corner, wherever it sits. */
1377
+ export function faceIsCanonical(face, canonical) {
1378
+ if (!canonicalDimsValid(canonical)) return false;
1379
+ const expected = canonicalLoops(canonical);
1380
+ if (!expected) return false;
1381
+ let loX = Infinity, loY = Infinity, hiX = -Infinity, hiY = -Infinity;
1382
+ for (const [x, y] of face.outer) { loX = Math.min(loX, x); hiX = Math.max(hiX, x); loY = Math.min(loY, y); hiY = Math.max(hiY, y); }
1383
+ const cx = (loX + hiX) / 2, cy = (loY + hiY) / 2;
1384
+ const centre = (pts) => pts.map(([x, y]) => [round(x - cx), round(y - cy)]);
1385
+ const tidy = (pts) => pts.map(([x, y]) => [round(x), round(y)]);
1386
+ return facesSame({ outer: centre(face.outer), holes: face.holes.map(centre) }, { outer: tidy(expected.outer), holes: expected.holes.map(tidy) });
1387
+ }
1388
+
1389
+ /**
1390
+ * Evaluate a version-2 definition at one set of sizes into its materialized `custom_sections` entry (§4.1).
1391
+ * `params` holds every size (fill a name's left-out sizes with `omittedValues` first). Sizes outside their
1392
+ * typical range evaluate, with an advisory. An unmet validity condition means no section exists at these sizes:
1393
+ * `unmet` lists each one, so the person can be offered their choices.
1394
+ * @returns {{ section: any, advisories: string[] } | { problems: string[], unmet?: { index: number, reason: string, nonFinite: boolean }[] }}
1395
+ */
1396
+ export function evaluateSectionV2(definition, params) {
1397
+ if (!isObj(definition) || definition.kind !== SECTION_PROFILE_KIND || definition.kindVersion !== 2) {
1398
+ return { problems: [`this FloLess cannot evaluate a definition of kind “${definition?.kind}” version ${definition?.kindVersion} as version 2`] };
1399
+ }
1400
+ const payloadProblems = checkSectionProfileV2(definition.payload);
1401
+ if (payloadProblems.length) return { problems: payloadProblems };
1402
+ const payload = definition.payload;
1403
+ const idProblems = checkIdV2(definition.id, payload);
1404
+ if (idProblems.length) return { problems: idProblems };
1405
+ if (!isObj(params)) return { problems: ['the sizes must be an object of numbers'] };
1406
+ const problems = [];
1407
+ const advisories = [];
1408
+ const parameters = payload.parameters;
1409
+ const known = new Set(parameters.map((p) => p.symbol));
1410
+ for (const key of Object.keys(params)) if (!known.has(key)) problems.push(`“${key}” is not a size of ${payload.name}`);
1411
+ for (const p of parameters) {
1412
+ const value = params[p.symbol];
1413
+ const unit = SIZE_UNITS[p.kind];
1414
+ const limit = SIZE_LIMITS[p.kind];
1415
+ if (!isFiniteNumber(value)) { problems.push(`${p.label} (${p.symbol}) needs a value${unit ? ` in ${unit}` : ''}`); continue; }
1416
+ if (Math.abs(value) > limit) { problems.push(`${p.label} (${p.symbol}) is ${formatSize(value)}${unit}, beyond the ${limit}${unit} a size may be`); continue; }
1417
+ const t = p.typical;
1418
+ if (t && ((isFiniteNumber(t.min) && value < t.min) || (isFiniteNumber(t.max) && value > t.max))) {
1419
+ advisories.push(`${p.label} (${p.symbol}) is ${formatSize(value)}${unit}, outside its usual ${isFiniteNumber(t.min) ? formatSize(t.min) : '…'} to ${isFiniteNumber(t.max) ? formatSize(t.max) : '…'}${unit}`);
1420
+ }
1421
+ }
1422
+ if (problems.length) return { problems };
1423
+ // Stored at full precision, as given: a size is the person's, never rounded on the way in (§2.2).
1424
+ const clean = Object.fromEntries(parameters.map((p) => [p.symbol, params[p.symbol]]));
1425
+ const scope = { ...clean };
1426
+ const expressions = payload.expressions ?? [];
1427
+ const symbols = new Set([...known, ...expressions.map((e) => e.symbol)]);
1428
+ try {
1429
+ for (const [symbol, tree] of expressionOrder(expressions, known)) scope[symbol] = evalFormulaV2(tree, scope);
1430
+ } catch (error) {
1431
+ return { problems: [error.message] };
1432
+ }
1433
+
1434
+ const unmet = [];
1435
+ (payload.predicates ?? []).forEach((pr, index) => {
1436
+ const { met, nonFinite } = evaluatePredicate(parsePredicate(pr.when, symbols), scope);
1437
+ if (!met) unmet.push({ index, reason: pr.reason, nonFinite });
1438
+ });
1439
+ if (unmet.length) {
1440
+ return {
1441
+ problems: unmet.map((u) => (u.nonFinite
1442
+ ? `no section at these sizes: ${u.reason} (it could not be checked — a value in it is not a finite number)`
1443
+ : `no section at these sizes: ${u.reason}`)),
1444
+ unmet,
1445
+ };
1446
+ }
1447
+
1448
+ const map = isObj(payload.export) ? payload.export.canonical : undefined;
1449
+ let dims = null;
1450
+ if (map) {
1451
+ dims = { shape: map.shape };
1452
+ try {
1453
+ for (const key of CANONICAL_SHAPES[map.shape]) dims[key] = round(evalFormulaV2(parseFormulaV2(map[key], symbols), scope));
1454
+ } catch (error) {
1455
+ return { problems: [error.message] };
1456
+ }
1457
+ // A descriptor with no value is a broken definition, never a shape quietly left unexported.
1458
+ const missing = CANONICAL_SHAPES[map.shape].filter((key) => !Number.isFinite(dims[key]));
1459
+ if (missing.length) return { problems: [`at these sizes the canonical “${map.shape}” has no value for ${missing.join(', ')} (a division by zero, or the square root of a negative number?)`] };
1460
+ }
1461
+
1462
+ let start, end, area, tessellation, canonical;
1463
+ if (map && CURVE_SHAPES.has(map.shape)) {
1464
+ if (!canonicalDimsValid(dims)) {
1465
+ return { problems: [map.shape === 'chs'
1466
+ ? 'at these sizes the round tube has no wall: its outside diameter and wall thickness must be positive, and the wall less than half the diameter'
1467
+ : 'at these sizes the round bar has no positive diameter'] };
1468
+ }
1469
+ const r = (map.shape === 'chs' ? dims.od : dims.diameter) / 2;
1470
+ if (r > MAX_TRUE_COORDINATE) return { problems: [`at these sizes the round shape reaches more than ${MAX_TRUE_COORDINATE / 1000} m from its centre`] };
1471
+ const n = curveSegments(r);
1472
+ start = { outer: circleLoop(r, n, true), holes: map.shape === 'chs' ? [circleLoop(r - dims.t, n, false)] : [] };
1473
+ // The drawn loops are held to the same rules as any face: a wall thinner than a micrometre at this size would
1474
+ // round its hole onto the outer loop.
1475
+ for (const [i, loop] of [start.outer, ...start.holes].entries()) {
1476
+ if (new Set(loop.map(vertexKey)).size !== loop.length || notSimple(loop)) return { problems: [`at these sizes the drawn ${i ? 'inside' : 'outside'} of the round shape folds onto itself`] };
1477
+ }
1478
+ const touching = holeProblem(start.outer, start.holes, 'the round tube');
1479
+ if (touching) return { problems: [`${touching}: its wall is too thin to draw at this size`] };
1480
+ area = round(map.shape === 'chs' ? (Math.PI * (dims.od ** 2 - (dims.od - 2 * dims.t) ** 2)) / 4 : (Math.PI * dims.diameter ** 2) / 4);
1481
+ tessellation = { segments: n, maxDeviation: curveDeviation(r, n) };
1482
+ canonical = dims;
1483
+ } else {
1484
+ let a;
1485
+ try {
1486
+ a = faceV2(payload.start, scope, symbols, 'the start face');
1487
+ if (a.problem) return { problems: [a.problem] };
1488
+ start = a.face;
1489
+ if (payload.end) {
1490
+ const b = faceV2(payload.end, scope, symbols, 'the end face');
1491
+ if (b.problem) return { problems: [b.problem] };
1492
+ end = b.face;
1493
+ }
1494
+ } catch (error) {
1495
+ return { problems: [error.message] };
1496
+ }
1497
+ }
1498
+ const tapered = !!end && !facesSame(start, end);
1499
+ if (!tessellation) {
1500
+ if (!tapered) area = round(loopArea(start.outer) - start.holes.reduce((sum, h) => sum + loopArea(h), 0));
1501
+ if (!tapered && dims && faceIsCanonical(start, dims)) canonical = dims;
1502
+ else if (dims) {
1503
+ advisories.push(tapered
1504
+ ? `the definition says it is a canonical “${dims.shape}”, but at these sizes it tapers, so it is not exported as one`
1505
+ : `the definition says it is a canonical “${dims.shape}”, but at these sizes its outline is not that shape, so it is not exported as one`);
1506
+ }
1507
+ }
1508
+ // Bounds of the material, over both faces of a tapered section (the drawn outline of a curve is on the circle at
1509
+ // 0, 90, 180 and 270 degrees, so its bounds are exact).
1510
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1511
+ for (const face of end ? [start, end] : [start]) {
1512
+ for (const [x, y] of face.outer) { minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); }
1513
+ }
1514
+ let designation;
1515
+ try { designation = canonicalName(definition, clean); } catch (error) { return { problems: [`the name cannot be written at these sizes: ${error.message}`] }; }
1516
+ const section = {
1517
+ sectionId: sectionIdFor(definition.id, definitionDigest(definition), clean, 2),
1518
+ definitionId: definition.id,
1519
+ params: clean,
1520
+ evaluatorVersion: 2,
1521
+ units: 'mm',
1522
+ designation,
1523
+ // The outer loop of the start face, under the name every version-1 reader already reads. In the definition's
1524
+ // coordinates, like `start`: the reference point is the origin, never the bounding-box centre.
1525
+ outline: start.outer,
1526
+ start,
1527
+ ...(end ? { end } : {}),
1528
+ tapered,
1529
+ reference: [0, 0],
1530
+ bounds: { minX: round(minX), minY: round(minY), maxX: round(maxX), maxY: round(maxY) },
1531
+ ...(area !== undefined ? { area } : {}),
1532
+ width: round(maxX - minX),
1533
+ depth: round(maxY - minY),
1534
+ ...(canonical ? { canonical } : {}),
1535
+ ...(tessellation ? { tessellation } : {}),
1536
+ };
1537
+ // Defensive: the face checks above (every hole inside its outer loop, no loop without area) already rule these out.
1538
+ if (area !== undefined && !(area > 0)) return { problems: ['at these sizes the section has no area once its holes are taken out'] };
1539
+ if (![section.width, section.depth, ...Object.values(clean)].every(Number.isFinite) || !(section.width > 0 && section.depth > 0)) {
1540
+ return { problems: ['at these sizes the section has a size that is not a finite, positive number'] };
1541
+ }
1542
+ return { section, advisories };
1543
+ }
1544
+
1545
+ /**
1546
+ * Whether a re-evaluation reproduces a stored result. Exact for everything, except a canonical curve's drawn
1547
+ * loops: those are a drawing of an analytic shape, so each corner may differ by up to 1e-4 mm (a last-digit
1548
+ * difference in a platform's cosine), while its descriptor, area, bounds and segment count must match exactly.
1549
+ */
1550
+ function reproduces(again, stored) {
1551
+ if (!isV2Section(stored) || !stored.tessellation) return materialized(again) === materialized(stored);
1552
+ const strip = (s) => ({ ...s, outline: undefined, start: undefined, end: undefined });
1553
+ if (materialized(strip(again)) !== materialized(strip(stored))) return false;
1554
+ const near = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length
1555
+ && a.every((p, i) => Array.isArray(b[i]) && Math.abs(p[0] - b[i][0]) <= 1e-4 && Math.abs(p[1] - b[i][1]) <= 1e-4);
1556
+ const sf = stored.start;
1557
+ return isObj(sf) && near(again.start.outer, sf.outer) && near(stored.outline, sf.outer)
1558
+ && Array.isArray(sf.holes) && sf.holes.length === again.start.holes.length && again.start.holes.every((h, i) => near(h, sf.holes[i]))
1559
+ && stored.end === undefined;
1560
+ }
1561
+
1562
+ /**
1563
+ * Why the readers of this build cannot use a version-2 section, or '' when they can. In P0 none of them reads
1564
+ * version 2: they place an outline centred on its bounding box, while a version-2 outline sits on its reference
1565
+ * point, and they know neither holes nor the newer canonical shapes. So every version-2 section is verified and
1566
+ * labelled but never usable yet, assumed or not; the readers are taught version 2 in P1 (epic #3382 §4.1).
1567
+ */
1568
+ function v2NotYetUsable(section) {
1569
+ if (section.tapered !== false) return 'This section tapers along the member, so FloLess has no single shape or weight for it yet. It is drawn as a placeholder and left out of quantities and exports. To include it now, ask the AI for a section that does not taper.';
1570
+ return 'This section uses FloLess’s parametric section format, which this version checks but cannot draw, weigh or export yet. It is drawn as a placeholder and left out of quantities and exports. To include it now, ask the AI to rebuild it as a version 1 custom section.';
1571
+ }
1572
+
1573
+ /**
1574
+ * Why a stored section of ANY version cannot be read by today's readers however it is judged: it lacks one of the
1575
+ * values they read (the schema no longer requires `area`, because a tapered version-2 result has none). '' when
1576
+ * it has them all. An incomplete section stays in the model, labelled, and is never an error that stops it opening.
1577
+ */
1578
+ function incomplete(section) {
1579
+ const positive = (v) => typeof v === 'number' && Number.isFinite(v) && v > 0;
1580
+ const outlineOk = Array.isArray(section.outline) && section.outline.length >= 3
1581
+ && section.outline.every((p) => Array.isArray(p) && p.length === 2 && p.every(Number.isFinite));
1582
+ return positive(section.area) && positive(section.width) && positive(section.depth) && outlineOk ? ''
1583
+ : 'This section’s stored shape is missing its outline, area or extents, so FloLess cannot draw or count it. It is drawn as a placeholder and left out of quantities and exports. To use it, ask the AI to fix this section.';
1584
+ }
1585
+
1586
+ // ---- integrity -----------------------------------------------------------------------------------------
1587
+
1588
+ /**
1589
+ * Structural problems with the custom-section entries of a model: duplicate ids and references that do not
1590
+ * resolve. Digest mismatches and unknown kinds are NOT problems — they are states that relabel and gate (see
1591
+ * `resolveCustomSection`), so a model from a newer FloLess still opens.
1592
+ * @returns {{path:string, code:string, message:string}[]}
1593
+ */
1594
+ export function customSectionIssues(doc) {
1595
+ const issues = [];
1596
+ const add = (path, code, message) => issues.push({ path, code, message });
1597
+ if (!isObj(doc)) return issues;
1598
+ const definitions = Array.isArray(doc.section_definitions) ? doc.section_definitions : [];
1599
+ const sections = Array.isArray(doc.custom_sections) ? doc.custom_sections : [];
1600
+ const members = Array.isArray(doc.members) ? doc.members : [];
1601
+ // JSON.parse reads `1e400` as Infinity, which JSON then writes back as `null`: an opaque payload holding one
1602
+ // could not be preserved as the same value. Checked for every entry without interpreting it.
1603
+ // Iterative, with no depth limit: an unknown kind's payload may be shaped any way at all and is preserved.
1604
+ const nonFinite = (root, rootPath) => {
1605
+ const stack = [[root, rootPath]];
1606
+ while (stack.length) {
1607
+ const [value, path] = stack.pop();
1608
+ if (typeof value === 'number') {
1609
+ if (!Number.isFinite(value)) { add(path, 'custom-section-number-not-finite', 'a number here is too large to store'); return true; }
1610
+ } else if (Array.isArray(value)) {
1611
+ for (let i = value.length - 1; i >= 0; i--) stack.push([value[i], `${path}[${i}]`]);
1612
+ } else if (isObj(value)) {
1613
+ for (const key of Object.keys(value)) stack.push([value[key], `${path}.${key}`]);
1614
+ }
1615
+ }
1616
+ return false;
1617
+ };
1618
+ definitions.forEach((definition, i) => nonFinite(definition, `$.section_definitions[${i}]`));
1619
+ sections.forEach((section, i) => nonFinite(section, `$.custom_sections[${i}]`));
1620
+ const definitionIds = new Map();
1621
+ definitions.forEach((definition, i) => {
1622
+ if (!isObj(definition) || typeof definition.id !== 'string') return;
1623
+ if (definitionIds.has(definition.id)) add(`$.section_definitions[${i}].id`, 'section-definition-id-duplicate', `definition id "${definition.id}" occurs more than once; an id names exactly one definition`);
1624
+ else definitionIds.set(definition.id, definition);
1625
+ });
1626
+ const sectionIds = new Set();
1627
+ sections.forEach((section, i) => {
1628
+ if (!isObj(section)) return;
1629
+ if (sectionIds.has(section.sectionId)) add(`$.custom_sections[${i}].sectionId`, 'custom-section-id-duplicate', `custom section "${section.sectionId}" occurs more than once`);
1630
+ sectionIds.add(section.sectionId);
1631
+ if (!definitionIds.has(section.definitionId)) add(`$.custom_sections[${i}].definitionId`, 'custom-section-definition-missing', `"${section.definitionId}" does not name a definition in section_definitions`);
1632
+ });
1633
+ members.forEach((member, i) => {
1634
+ if (!isObj(member) || member.customSectionId === undefined) return;
1635
+ if (!sectionIds.has(member.customSectionId)) add(`$.members[${i}].customSectionId`, 'custom-section-missing', `"${member.customSectionId}" does not name a section in custom_sections`);
1636
+ });
1637
+ return issues;
1638
+ }
1639
+
1640
+ // ---- unique labels -------------------------------------------------------------------------------------
1641
+
1642
+ /** A section name compared the way a detailer reads it: case, spaces and the × sign do not make it different. */
1643
+ const nameKey = (name) => String(name).toUpperCase().replace(/[×✕✖]/g, 'X').replace(/\s+/g, '');
1644
+
1645
+ /**
1646
+ * A label for each custom section that no other section, and no catalogue profile a member of the model
1647
+ * spells, shares: the designation; then with its parameter values; then with a short form of its id. Two
1648
+ * different sections can therefore never land in one BOM line, scene group or legend row, however they are
1649
+ * named. `variant(sectionId)` may add a further distinction (the BOM adds the density) — it is applied before
1650
+ * the id fallback, so labels stay readable whenever they can.
1651
+ * @param {any} doc
1652
+ * @param {{ extraKeys?: Iterable<[string, string]>, reserved?: Iterable<string> }} [options] extra (sectionId, variant)
1653
+ * pairs to keep apart, and names no custom label may take (e.g. resolved catalogue designations)
1654
+ * @returns {Map<string, string>} key → label, where key is `sectionId` or `sectionId\u0000variant`
1655
+ */
1656
+ export function customSectionLabels(doc, options = {}) {
1657
+ const sections = (Array.isArray(doc?.custom_sections) ? doc.custom_sections : []).filter((s) => isObj(s) && typeof s.sectionId === 'string');
1658
+ // Compared spelling-blind (case, spaces, the × sign), because a catalogue member spelled `W16 X 26` is grouped
1659
+ // and billed as `W16X26`. `reserved` adds names a caller resolved itself, such as a catalogue row's own
1660
+ // designation, which this module cannot look up.
1661
+ const catalogue = new Set([
1662
+ ...(Array.isArray(doc?.members) ? doc.members : [])
1663
+ .filter((m) => isObj(m) && m.customSectionId === undefined && typeof m.profile === 'string')
1664
+ .map((m) => m.profile),
1665
+ ...(options.reserved ?? []),
1666
+ ].filter((name) => typeof name === 'string' && name.trim()).map(nameKey));
1667
+ const byId = new Map(sections.map((s) => [s.sectionId, s]));
1668
+ /** @type {[string, string, string][]} key, sectionId, variant */
1669
+ const keys = sections.map((s) => [s.sectionId, s.sectionId, '']);
1670
+ for (const [sectionId, variant] of options.extraKeys ?? []) {
1671
+ if (byId.has(sectionId) && variant) keys.push([`${sectionId}\u0000${variant}`, sectionId, variant]);
1672
+ }
1673
+ const values = (s) => Object.keys(s.params || {}).sort().map((k) => `${k} ${formatValue(s.params[k])}`).join(', ');
1674
+ const tiers = [
1675
+ (s) => String(s.designation || 'Custom section'),
1676
+ (s) => `${s.designation || 'Custom section'} (${values(s)})`,
1677
+ ];
1678
+ const labels = new Map();
1679
+ const pending = keys.slice();
1680
+ for (let tier = 0; tier <= tiers.length && pending.length; tier++) {
1681
+ const proposed = pending.map(([key, sectionId, variant]) => {
1682
+ const s = byId.get(sectionId);
1683
+ const base = tier < tiers.length ? tiers[tier](s) : `${tiers[1](s)} #${sectionId.slice(7, 15)}`;
1684
+ return [key, variant ? `${base} · ${variant}` : base];
1685
+ });
1686
+ const count = new Map();
1687
+ for (const [, label] of proposed) count.set(nameKey(label), (count.get(nameKey(label)) || 0) + 1);
1688
+ for (const label of labels.values()) count.set(nameKey(label), (count.get(nameKey(label)) || 0) + 1);
1689
+ const still = [];
1690
+ proposed.forEach(([key, label], i) => {
1691
+ const clash = count.get(nameKey(label)) > 1 || catalogue.has(nameKey(label));
1692
+ if (!clash || tier === tiers.length) labels.set(key, label);
1693
+ else still.push(pending[i]);
1694
+ });
1695
+ pending.length = 0;
1696
+ pending.push(...still);
1697
+ }
1698
+ return labels;
1699
+ }
1700
+
1701
+ /**
1702
+ * Every name a catalogue member of this model can be read by: what it carries, and each spelling its catalogue
1703
+ * row knows (`spellingsOf`, the same function the colour rank uses). Passed as `reserved` to `customSectionLabels`
1704
+ * by EVERY consumer — scene, bill and editor — so they all give a custom section the same label, and none of them
1705
+ * can resolve that label to a catalogue section (`UC305*305*97` beside a member spelled `UC305X97`).
1706
+ * @param {any} doc
1707
+ * @param {(profile: string) => string[]} [spellingsOf]
1708
+ * @returns {string[]}
1709
+ */
1710
+ export function catalogueNames(doc, spellingsOf) {
1711
+ const out = [];
1712
+ for (const m of Array.isArray(doc?.members) ? doc.members : []) {
1713
+ if (!isObj(m) || m.customSectionId !== undefined || typeof m.profile !== 'string' || !m.profile.trim()) continue;
1714
+ out.push(m.profile);
1715
+ if (typeof spellingsOf === 'function') {
1716
+ const spellings = spellingsOf(m.profile);
1717
+ if (Array.isArray(spellings)) out.push(...spellings.filter((s) => typeof s === 'string'));
1718
+ }
1719
+ }
1720
+ return out;
1721
+ }
1722
+
1723
+ /**
1724
+ * The catalogue spellings the colour rank may use, with every custom-section label kept out of them in BOTH
1725
+ * directions: a label has no catalogue spellings of its own (it names a custom section, never a catalogue row, even
1726
+ * when a catalogue would read it as an alias), and no catalogue section lists a label among its spellings. Without
1727
+ * this a label such as `HSS20.000X0.500` beside a catalogue member `HSS20X.500` would share that member's colour,
1728
+ * and recolouring either would delete the other's override.
1729
+ * @param {Map<string, string>} labels from the server's labels
1730
+ * @param {(profile: string) => string[]} spellingsOf
1731
+ * @returns {(profile: string) => string[]}
1732
+ */
1733
+ export function labelSafeSpellings(labels, spellingsOf) {
1734
+ const own = new Set([...(labels?.values?.() ?? [])].filter((l) => typeof l === 'string').map(nameKey));
1735
+ if (!own.size) return spellingsOf;
1736
+ return (profile) => {
1737
+ if (own.has(nameKey(profile))) return [];
1738
+ const out = typeof spellingsOf === 'function' ? spellingsOf(profile) : [];
1739
+ return Array.isArray(out) ? out.filter((s) => typeof s !== 'string' || !own.has(nameKey(s))) : out;
1740
+ };
1741
+ }
1742
+
1743
+ /**
1744
+ * The model as the colour rank reads it: each custom member under its unique label instead of its designation,
1745
+ * so two same-name sections take two palette slots, and the 2D plan (keyed by member) and the 3D groups (keyed
1746
+ * by label) agree. Returns `doc` itself when it holds no custom member.
1747
+ * @param {any} doc
1748
+ * @param {Map<string, string>} [labels] from `customSectionLabels(doc, …)`
1749
+ */
1750
+ export function colourModel(doc, labels = customSectionLabels(doc)) {
1751
+ const members = Array.isArray(doc?.members) ? doc.members : [];
1752
+ if (!members.some((m) => isObj(m) && typeof m.customSectionId === 'string')) return doc;
1753
+ return {
1754
+ ...doc,
1755
+ members: members.map((m) => (isObj(m) && typeof m.customSectionId === 'string' && labels.has(m.customSectionId)
1756
+ ? { ...m, profile: labels.get(m.customSectionId) } : m)),
1757
+ };
1758
+ }
1759
+
1760
+ // ---- mass ----------------------------------------------------------------------------------------------
1761
+
1762
+ const STEEL = { kgPerM3: 7850, basis: 'structural steel, 7850 kg/m³ (EN 1991-1-1 Table A.4)' };
1763
+
1764
+ /**
1765
+ * The density a member's mass is computed with, from its material, and the basis that says where it came
1766
+ * from. Every structural steel grade weighs the same per volume; stainless and aluminium do not.
1767
+ * @param {string|undefined|null} material
1768
+ * @returns {{kgPerM3:number, basis:string, assumed:boolean}}
1769
+ */
1770
+ export function densityFor(material) {
1771
+ const m = String(material ?? '').trim();
1772
+ // An empty material is the model's default structural grade (the same default the rest of FloLess infers).
1773
+ if (!m) return { ...STEEL, assumed: false };
1774
+ // The standard's name in front says nothing about the alloy, so it is taken off first: `ASTM A240 304`,
1775
+ // `EN 10025 S355`, `BS EN AW-6063`.
1776
+ const u = m.toUpperCase().replace(/\s+/g, ' ')
1777
+ .replace(/^(ASTM|ASME|BS EN|EN|BS|DIN EN|DIN|ISO|JIS|CSA|AS\/NZS|AS|GB\/T|GB)\s*[-:]?\s*/, '')
1778
+ .replace(/^\d{4,5}(-\d)?\s+(?=[A-Z0-9])/, '');
1779
+ // Stainless and aluminium are asked FIRST: their specification numbers look like a carbon-steel grade.
1780
+ if (/STAINLESS|\bA(240|276|312|479|554|1053)\b|\b(20[12]|30[1-9]|31[0-9]|32[01]|34[07]|409|410|430|904|2205|2507)(L|H|LN)?\b|\b1\.4\d{3}\b|DUPLEX/.test(u)) {
1781
+ return { kgPerM3: 8000, basis: 'stainless steel, 8000 kg/m³ (EN 1993-1-4)', assumed: false };
1782
+ }
1783
+ if (/ALUMIN|\bAW-|\bB(209|221|308|429)\b|\b(1100|3003|5052|5083|6005A?|6061|6063|6082|7020|7075)(-T\d+)?\b/.test(u)) {
1784
+ return { kgPerM3: 2700, basis: 'aluminium, 2700 kg/m³ (EN 1999-1-1)', assumed: false };
1785
+ }
1786
+ if (/^(A(36|53|500|501|529|572|588|618|709|847|913|992|1011|1085)\b|S\d{3}|SS\d{3}|E\d{3}\b|Q\d{3}|ST ?\d{2}|SM\d{3}|G40|GR(ADE)?\.? ?\d{2}|\d{2}W\b|\d{3}W\b|\d{3}WT?\b)/.test(u)
1787
+ || /\bSTEEL\b/.test(u)) {
1788
+ return { ...STEEL, assumed: false };
1789
+ }
1790
+ return { kgPerM3: STEEL.kgPerM3, basis: `assumed structural steel, 7850 kg/m³ — the material “${m}” is not one FloLess recognises`, assumed: true };
1791
+ }
1792
+
1793
+ /** kg per metre of a section of `area` mm² at `kgPerM3`. */
1794
+ export function customKgPerM(section, density) {
1795
+ return round((section.area * density.kgPerM3) / 1e6);
1796
+ }