@rulecad/cad 0.7.48 → 0.7.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/design.mjs CHANGED
@@ -27,13 +27,15 @@ import { pathToFileURL, fileURLToPath } from 'node:url';
27
27
  import { createRequire } from 'node:module';
28
28
  import crypto from 'node:crypto';
29
29
  import { resolve, loadRuleSet } from './rules.mjs';
30
- import { WS, paths, printerOf } from './workspace.mjs';
30
+ import { WS, paths, printerOf, RULE_DIRS } from './workspace.mjs';
31
31
  import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
32
32
  import { optimised, forDesign } from './optimise.mjs';
33
33
  import * as shapes from '@rulecad/shapes';
34
34
  import * as flexures from '@rulecad/flexures';
35
35
  import * as gears from '@rulecad/gears';
36
36
  import * as motors from '@rulecad/motors';
37
+ import { designFrames, framesContext } from './frames.mjs';
38
+ import { resolve as resolveWith } from '@rulecad/variables';
37
39
  import { engineId, packageVersion, materialise } from './versions.mjs';
38
40
  import { satisfies } from '@rulecad/versions';
39
41
 
@@ -127,11 +129,12 @@ const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
127
129
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
128
130
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
129
131
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
130
- const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors')));
132
+ const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))), framesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/frames'))), fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
131
133
  // (every module of a helper package but its tests: they change nothing a design builds)
132
134
  const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
133
135
  const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
134
- const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
136
+ // (as one digest, so each build's key hashes a line and not a megabyte of source)
137
+ const own = crypto.createHash('sha256').update(source(import.meta.url) + source('./fixings.mjs') + source('./frames.mjs') + helperSources(framesDir) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(fixingsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling')).digest('hex'); // every shapes module, not just its entry
135
138
  // A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
136
139
  // and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
137
140
  // at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
@@ -147,6 +150,29 @@ export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
147
150
  throw e;
148
151
  });
149
152
 
153
+ // What v.fixings is bound to (lib/fixings.mjs): the workspace's own rule sets by name (a release's own, where it is one:
154
+ // its threads and materials are used before the kit's), the project's printer as a rule set with its values worked
155
+ // out, and the project's material. With a hash of all of it and of the kit's sets: a build that called v.fixings is
156
+ // made from these too, so its cache holds only while they stand.
157
+ let kitRules = null;
158
+ export function fixingsContext(d) {
159
+ const dir = d.rulesDir || RULE_DIRS[0], sets = {}, text = [];
160
+ for (const f of host.list(dir).filter((x) => x.endsWith('.json')).sort()) {
161
+ try { const raw = host.readText(path.join(dir, f)), s = JSON.parse(raw); if (s && s.rules && typeof s.rules === 'object') { sets[s.name ?? f.slice(0, -5)] = s; text.push(raw); } } catch {} // (a broken set is cad check's to name, where a design uses it)
162
+ }
163
+ const name = printerOf(d.project), peek = (n) => { const f = [dir, ...RULE_DIRS].map((x) => path.join(x, `${n}.json`)).find((x) => host.exists(x)); if (!f) throw new Error(`no rule set "${n}" (rules/${n}.json)`); return readJson(f); };
164
+ let printer = null;
165
+ try { // (a printer with no rule set is said where a print is checked; fixings then draws for the kit's)
166
+ const set = peek(name), values = resolveWith({ uses: [name] }, { load: peek }).values[name];
167
+ printer = { name: set.name ?? name, rules: Object.fromEntries(Object.entries(set.rules).map(([k, r]) => [k, typeof values[k] === 'number' ? { ...r, value: values[k] } : r])) };
168
+ } catch {}
169
+ let material = null;
170
+ try { const f = path.join(d.dir, 'project.json'); if (host.exists(f)) material = String(readJson(f).material || '').trim().toLowerCase().split(/\s/)[0] || null; } catch {}
171
+ kitRules ||= (() => { const k = RULE_DIRS.at(-1); return crypto.createHash('sha256').update(fs.readdirSync(k).filter((f) => f.endsWith('.json')).sort().map((f) => fs.readFileSync(path.join(k, f), 'utf8')).join('')).digest('hex'); })();
172
+ const context = { sets, printer, material };
173
+ return { context, hash: crypto.createHash('sha256').update(JSON.stringify([text, printer, material, kitRules])).digest('hex').slice(0, 24) };
174
+ }
175
+
150
176
  // An object's on-screen settings are "display" ({ "smooth": 24 }), and a part left off screen is "display": false.
151
177
  // Their first name, "mirror", still works: read here, the rest of the tool sees it as mirror either way.
152
178
  // Which engine a design's v.ops booleans use: the object's "engine": "manifold", or CAD_ENGINE=manifold for every design
@@ -169,7 +195,8 @@ function syntaxAt(e, d) {
169
195
  return e;
170
196
  }
171
197
 
172
- // build(design, set, { mirror }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export) }
198
+ // build(design, set, { mirror }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export), fixings? }
199
+ // fixings: what the design's calls to v.fixings found (each hole and seat, what it was drawn to and rests on), as findings
173
200
  // parts: [{ name, role, label, geometry, polygons, triangles }]; polygons and triangles: every part together
174
201
  export async function build(d, set = {}, { mirror = false } = {}) {
175
202
  const object = readObject(d);
@@ -194,24 +221,30 @@ export async function build(d, set = {}, { mirror = false } = {}) {
194
221
  // label, a note or the version change nothing it builds, so they aren't in the key
195
222
  const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
196
223
  const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
197
- const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
224
+ // (v.frames reads the workspace's own profile sets: a build is made from them too, lib/frames.mjs)
225
+ const framed = framesContext(RULE_DIRS[0]);
226
+ const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, framed.hash, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
198
227
  const hit = path.join(CACHE, `${key}.json`);
199
- if (!process.env.CAD_NO_CACHE && host.exists(hit)) {
200
- const c = JSON.parse(host.readText(hit));
228
+ // (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
229
+ // while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot)
230
+ let fx = null; const fixed = () => (fx ||= fixingsContext(d)), known = (f) => (f ? crypto.createHash('sha256').update(key + f).digest('hex') : key);
231
+ const kept = !process.env.CAD_NO_CACHE && host.exists(hit) ? JSON.parse(host.readText(hit)) : null;
232
+ if (kept && (!kept.fixed || kept.fixed === fixed().hash)) {
233
+ const c = kept;
201
234
  try { host.touch(hit); } catch {} // recently used: kept when the cache is pruned
202
235
  for (const e of entries) if (c.used.includes(e.name)) e.used = true;
203
236
  const parts = c.parts.map(({ solid: f, ...p }) => ({ ...p, geometry: fromFaces(f) }));
204
237
  if (c.circuit) Object.assign(values, (await pcbEngine()).outputs(c.circuit, c.matrix));
205
- return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: key, ...(c.mechanism ? { mechanism: c.mechanism } : {}), ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}) };
238
+ return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: known(c.fixed), ...(c.fixings ? { fixings: c.fixings } : {}), ...(c.mechanism ? { mechanism: c.mechanism } : {}), ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}) };
206
239
  }
207
240
 
208
241
  // A JSCAD design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach
209
242
  // the network) unless the workspace trusts its designs; a board design runs here, with the board engine
210
243
  const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
211
- let parts, board = null, read, mechanism = null;
244
+ let parts, board = null, read, mechanism = null, fixings = null;
212
245
  const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
213
246
  const stages = stageStore();
214
- if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages).catch((e) => { throw syntaxAt(e, d); }));
247
+ if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism, fixings } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages, { frames: framed, fixings: fixed().context }).catch((e) => { throw syntaxAt(e, d); }));
215
248
  else {
216
249
  flexures.laminaCache(stages);
217
250
  const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
@@ -221,7 +254,8 @@ export async function build(d, set = {}, { mirror = false } = {}) {
221
254
  throw syntaxAt(located(e, d.js, 'design.run'), d);
222
255
  });
223
256
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
224
- const w = watch(values, { shapes, flexures, gears, motors, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
257
+ const ops = await shapes.ops(booleans(object)), df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
258
+ const w = watch(values, { shapes, flexures, gears, motors, frames: designFrames(framed), fixings: df.fixings, ops, ...(pcb ? { pcb } : {}) }, optional);
225
259
  read = w.read;
226
260
  let made;
227
261
  try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
@@ -238,13 +272,14 @@ export async function build(d, set = {}, { mirror = false } = {}) {
238
272
  made = pcb.solids(board.circuit, { thickness: values.thickness, smooth: values.smooth, models: meshes });
239
273
  }
240
274
  try { parts = named(made, object.parts || {}); } catch (e) { throw located(e, d.js, 'design.run'); }
275
+ if (df.used()) fixings = df.found();
241
276
  }
242
277
  for (const e of entries) if (read.has(e.name)) e.used = true;
243
278
  try {
244
279
  prune();
245
- host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}) }));
280
+ host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}), ...(fixings ? { fixed: fixed().hash, fixings } : {}) }));
246
281
  } catch {} // a cache that can't be written is only slower
247
- return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: key, ...(board || {}), ...(mechanism ? { mechanism } : {}) };
282
+ return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
248
283
  }
249
284
 
250
285
  // A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
package/lib/edit.mjs CHANGED
@@ -58,18 +58,18 @@ const assemblyFile = (ref) => {
58
58
  };
59
59
 
60
60
  /**
61
- * Add to an assembly: a fit, a joint, an item or a loop (appended to its list), or a pose (by name).
62
- * @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'pose'} what @param {any} entry (a pose: { name, values })
61
+ * Add to an assembly: a fit, a joint, an item, a loop or a fasten (appended to its list), or a pose (by name).
62
+ * @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'fasten' | 'pose'} what @param {any} entry (a pose: { name, values })
63
63
  * @returns {{ file: string }}
64
64
  */
65
65
  export function addToAssembly(ref, what, entry) {
66
- const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops' }[what];
66
+ const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops', fasten: 'fasten' }[what];
67
67
  let text = before;
68
68
  if (what === 'pose') {
69
69
  if (getAt(text, ['poses']) === undefined) text = setAt(text, ['poses'], {});
70
70
  text = setAt(text, ['poses', entry.name], entry.values);
71
71
  } else {
72
- if (!list) throw new CadError('edit.what', `can't add a ${what} (fit, joint, item, loop or pose)`);
72
+ if (!list) throw new CadError('edit.what', `can't add a ${what} (fit, joint, item, loop, fasten or pose)`);
73
73
  if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
74
74
  const ids = (getAt(text, [list]) || []).map((x) => x.id).filter(Boolean);
75
75
  if (entry.id && ids.includes(entry.id)) throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
@@ -84,6 +84,14 @@ export function addToAssembly(ref, what, entry) {
84
84
  if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
85
85
  }
86
86
  }
87
+ // a fasten names the parts its screw passes and ends in, and where the screws go: each must be an item of the assembly
88
+ if (what === 'fasten') {
89
+ const items = (getAt(text, ['items']) || []).map((x) => x.id), has = (n) => items.includes(String(n).split(/[.@]/)[0]);
90
+ if (!entry.screw) throw new CadError('edit.incomplete', 'a fasten needs its screw, by thread and head: --screw "M3 cap"', { file });
91
+ if (!entry.into || !Array.isArray(entry.through)) throw new CadError('edit.incomplete', 'a fasten needs the parts the screw passes and the one it ends in: --through bracket --into base', { file });
92
+ if ((entry.at == null) === (entry.holes == null)) throw new CadError('edit.incomplete', 'a fasten needs where its screws go: --at bracket.h1,bracket.h2 (an anchor each) or --holes bracket.body (a part whose holes they use), one of the two', { file });
93
+ for (const n of [...entry.through, entry.into, ...(entry.holes ? [entry.holes] : []), ...(entry.at || []).filter((x) => typeof x === 'string')]) if (!has(n)) throw new CadError('edit.part', `fasten: no item "${String(n).split(/[.@]/)[0]}" in ${ref} (items: ${items.join(', ') || 'none'})`, { file });
94
+ }
87
95
  text = appendAt(text, [list], entry);
88
96
  }
89
97
  write(file, text, 'assembly');