@rulecad/cad 0.9.0 → 0.10.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/AGENTS.md +21 -6
  2. package/CHANGELOG.md +320 -0
  3. package/EXAMPLES.md +22 -17
  4. package/README.md +192 -40
  5. package/bin/cad.mjs +465 -80
  6. package/lib/assembly.mjs +68 -33
  7. package/lib/cache-file.mjs +105 -0
  8. package/lib/code-text.mjs +28 -0
  9. package/lib/design-imports.mjs +127 -0
  10. package/lib/design.mjs +251 -55
  11. package/lib/designshapes.mjs +142 -0
  12. package/lib/edit.mjs +24 -2
  13. package/lib/estimates.mjs +51 -0
  14. package/lib/fasten.mjs +11 -5
  15. package/lib/fe-key.mjs +29 -0
  16. package/lib/fittings.mjs +20 -15
  17. package/lib/fixings.mjs +17 -4
  18. package/lib/framebuild.mjs +1 -1
  19. package/lib/framegen.mjs +9 -1
  20. package/lib/frames.mjs +6 -2
  21. package/lib/framesize.mjs +8 -81
  22. package/lib/host.mjs +7 -3
  23. package/lib/kit.mjs +5 -5
  24. package/lib/list.mjs +29 -21
  25. package/lib/loads.mjs +35 -23
  26. package/lib/measured.mjs +738 -98
  27. package/lib/motors.mjs +9 -29
  28. package/lib/names.mjs +15 -0
  29. package/lib/optimise.mjs +34 -25
  30. package/lib/order.mjs +4 -10
  31. package/lib/parts.mjs +3 -0
  32. package/lib/rules.mjs +2 -1
  33. package/lib/sandbox-hooks.mjs +109 -15
  34. package/lib/sandbox-lock.mjs +225 -0
  35. package/lib/sandbox-preload.mjs +2 -2
  36. package/lib/sandbox-run.mjs +22 -24
  37. package/lib/sandbox.mjs +173 -30
  38. package/lib/sheet.mjs +114 -3
  39. package/lib/versions.mjs +195 -32
  40. package/lib/workspace.mjs +3 -2
  41. package/package.json +11 -11
  42. package/schemas/assembly.schema.json +1 -1
  43. package/schemas/project.schema.json +6 -0
  44. package/templates/coupons/MEASURE.md +109 -0
  45. package/templates/coupons/assemblies/fixings-test.json +20 -0
  46. package/templates/coupons/assemblies/slot-test.json +11 -0
  47. package/templates/coupons/objects/fixings-coupon.js +88 -0
  48. package/templates/coupons/objects/fixings-coupon.json +26 -0
  49. package/templates/coupons/objects/holds-coupon.js +130 -0
  50. package/templates/coupons/objects/holds-coupon.json +42 -0
  51. package/templates/coupons/objects/slot-coupon.js +89 -0
  52. package/templates/coupons/objects/slot-coupon.json +29 -0
  53. package/templates/coupons/project.json +10 -0
package/lib/design.mjs CHANGED
@@ -22,6 +22,7 @@ import { host, readJson, cached } from './host.mjs';
22
22
  import { named, faces, fromFaces, polygons, unpack, watch } from './parts.mjs';
23
23
  import { sandboxed, canSandbox, stageFile, ROUTE_KEY, designLimits } from './sandbox.mjs';
24
24
  import { roomFor, STAGES_HELD, ROUTES_HELD } from './kept.mjs';
25
+ import { ownCacheFile, writeCacheFile, readCacheJson } from './cache-file.mjs';
25
26
  import { Worker } from 'node:worker_threads';
26
27
  export { polygons };
27
28
  import fs from 'node:fs';
@@ -34,14 +35,15 @@ import { WS, paths, printerOf, RULE_DIRS, readOwnText, noLinksOut } from './work
34
35
  import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
35
36
  import { optimised, forDesign, ownResults } from './optimise.mjs';
36
37
  import * as shapes from '@rulecad/shapes';
38
+ import { designShapes } from './designshapes.mjs';
37
39
  import * as flexures from '@rulecad/flexures';
38
40
  import * as gears from '@rulecad/gears';
39
41
  import * as motors from '@rulecad/motors';
40
42
  import { designFrames, framesContext } from './frames.mjs';
41
43
  import { resolve as resolveWith } from '@rulecad/variables';
42
- import { engineId, packageVersion, materialise } from './versions.mjs';
44
+ import { engineId, packageVersion, materialise, files as filesOf, inRelease } from './versions.mjs';
43
45
  import { satisfies } from '@rulecad/versions';
44
- import { plainName, isObjectRefName } from './names.mjs';
46
+ import { plainName, isObjectRefName, isWorkspacePath } from './names.mjs';
45
47
 
46
48
  const require = createRequire(import.meta.url);
47
49
  const jscad = require('@jscad/modeling');
@@ -93,11 +95,12 @@ const building = new Set();
93
95
  export async function objectSets(d, object, { trusted = false } = {}) {
94
96
  const refs = (object.uses || []).filter(isObjectRef),
95
97
  sets = {},
96
- extra = {};
98
+ extra = {},
99
+ files = []; // the files of the objects it reads as they are now (not a release of theirs): their own and what they read
97
100
  // Its rule sets (the entries without a slash) become paths, rules/<name>.json: plain names only, said with the file they're in
98
101
  for (const u of object.uses || [])
99
102
  if (!isObjectRef(u)) plainName(u, 'rule set name', `${path.relative(WS, d.json)}, in its "uses"`);
100
- if (!refs.length) return { sets, extra };
103
+ if (!refs.length) return { sets, extra, files };
101
104
  const self = `${d.project}/${d.name}`;
102
105
  building.add(self);
103
106
  try {
@@ -113,9 +116,11 @@ export async function objectSets(d, object, { trusted = false } = {}) {
113
116
  throw new Error(
114
117
  `${self} and ${ref} read each other's numbers: one of them has to give its numbers to the other, not both`,
115
118
  );
116
- const base = locateIn(...ref.split('/')),
119
+ // (read by a release: as that release has it, from its tag, where it isn't pinned to a release of its own)
120
+ const base = d.tree && !exact ? inRelease(d, ...ref.split('/')) : locateIn(...ref.split('/')),
117
121
  b = await build(exact ? materialise(base, want) : base, {}, { trusted }),
118
122
  version = b.object.version;
123
+ if (!exact) files.push(...filesOf(base, b.object, b));
119
124
  if (want && !exact && !satisfies(version, want))
120
125
  throw new Error(
121
126
  `${self} uses ${ref} ${want}, but ${ref} is ${version}: change the range, or the design to suit ${version}`,
@@ -146,7 +151,7 @@ export async function objectSets(d, object, { trusted = false } = {}) {
146
151
  } finally {
147
152
  building.delete(self);
148
153
  }
149
- return { sets, extra };
154
+ return { sets, extra, files: [...new Set(files)].sort() };
150
155
  }
151
156
 
152
157
  // The layouts an object can pick, by name, from its layout variables' choices (built-ins like grid have no file)
@@ -201,7 +206,8 @@ export function variantSet(d, object, set = {}) {
201
206
  }
202
207
 
203
208
  const CACHE = paths.cache('builds'),
204
- CACHE_VERSION = 3;
209
+ CACHE_VERSION = 6; // (4: a kept build lists the files its design imported, and holds only while they read the same;
210
+ // 5: and says whether the design used v.frames, which a release records; 6: and holds what v.shapes' seats were drawn to)
205
211
  // The autorouter's results too, by its exact input (@rulecad/pcb reads RULECAD_ROUTE_CACHE): a board rebuilt for anything
206
212
  // but its routing (a change to the library, its finish, its checks) reuses its route instead of searching again
207
213
  if (!process.env.CAD_NO_CACHE) process.env.RULECAD_ROUTE_CACHE ||= paths.cache('routes');
@@ -250,32 +256,89 @@ const own = crypto
250
256
  // name, its inputs and the library's code, which anyone can work out, so a design that came with a cloned workspace
251
257
  // could otherwise hand back a false result under the key another design (the user's own) reads, and pass a mechanism
252
258
  // that would fail.
259
+ // A stage's salt is everything a lamina's stages run besides their inputs: flexures' code and the code it calls
260
+ // (@rulecad/fea, @rulecad/fixings and @rulecad/gears, and @rulecad/shapes, which fixings calls), each as flexures
261
+ // finds it, and the versions of the geometry libraries it measures with (manifold-3d: every clash, offset and area;
262
+ // @jscad/modeling: the shapes). A change to any of them works the stages out again.
263
+ const nextTo = (name, dir) =>
264
+ path.dirname(createRequire(pathToFileURL(path.join(dir, 'package.json')).href).resolve(name));
265
+ // (a package's version as installed where `dir` finds it, by its package.json, which manifold-3d does not export;
266
+ // 'none' where it is not installed)
267
+ function installedVersion(name, dir) {
268
+ for (const at of createRequire(pathToFileURL(path.join(dir, 'package.json')).href).resolve.paths(name) ?? []) {
269
+ const f = path.join(at, name, 'package.json');
270
+ if (fs.existsSync(f)) return JSON.parse(fs.readFileSync(f, 'utf8')).version;
271
+ }
272
+ return 'none';
273
+ }
274
+ /**
275
+ * What a lamina's slow stages are worked out with, besides their own inputs: the code of flexures and of the packages
276
+ * it calls (fea, fixings, gears, and shapes through fixings), and the versions of manifold-3d and @jscad/modeling.
277
+ * @returns {{ sources: string[], versions: Record<string, string> }}
278
+ */
279
+ export function stageInputs() {
280
+ const fixings = nextTo('@rulecad/fixings', flexuresDir);
281
+ return {
282
+ sources: [
283
+ flexuresDir,
284
+ feaDir,
285
+ fixings,
286
+ nextTo('@rulecad/gears', flexuresDir),
287
+ nextTo('@rulecad/shapes', fixings),
288
+ ].map(helperSources),
289
+ versions: Object.fromEntries(['manifold-3d', '@jscad/modeling'].map((n) => [n, installedVersion(n, flexuresDir)])),
290
+ };
291
+ }
292
+ /**
293
+ * The salt a lamina's stages are kept under (.cache/stages): a hash of stageInputs.
294
+ * @param {ReturnType<typeof stageInputs>} inputs @returns {string}
295
+ */
296
+ export const stageSaltOf = (inputs) => crypto.createHash('sha256').update(JSON.stringify(inputs)).digest('hex');
253
297
  const STAGES = paths.cache('stages'),
254
- stageSalt = crypto
255
- .createHash('sha256')
256
- .update(helperSources(flexuresDir) + helperSources(feaDir))
257
- .digest('hex');
258
- // A workspace cloned from elsewhere may hold links of its own in .cache/: a cache file that is a link to a file outside
259
- // (the trust list, say) would have the tool write what a sandboxed design handed back through it, and a cache folder
260
- // that is a link would have cache files written, and pruned, somewhere else. So a cache file is written only when it
261
- // and every folder between it and the workspace are a plain file and plain folders, or not there yet.
262
- function ownCacheFile(file, root = WS) {
263
- if (host.name === 'memory') return true; // (held in memory: nothing on disk to follow)
264
- const top = path.resolve(root);
265
- let p = path.resolve(file);
266
- if (!p.startsWith(top + path.sep)) return false;
267
- for (let first = true; p !== top; p = path.dirname(p), first = false) {
268
- let st;
298
+ stageSalt = stageSaltOf(stageInputs());
299
+ // (a cache file is written only where it and every folder between it and the workspace are a plain file and plain
300
+ // folders, or not there yet, and whole: cache-file.mjs ownCacheFile and writeCacheFile)
301
+ // The files of the workspace a design imported (its project's helpers: lid.js's ./box.js), as each reads now: { path in
302
+ // the workspace, with forward slashes: its SHA-256 }. A kept build was made from them as much as from the design's own
303
+ // text, so it holds only while each reads as it did when the build was made. Null when one of them can't be read
304
+ // as a file of the workspace (gone, outside it, in its node_modules, or reached through a link out of it): such a build
305
+ // is never kept, nor a kept one used. (A kept build's list comes from .cache/, which a cloned workspace may bring: a
306
+ // path that climbs out, or names a file elsewhere, is never read, whatever it hashed to.)
307
+ const ownPath = (f) => isWorkspacePath(f) && !path.isAbsolute(f);
308
+ function importHashes(files) {
309
+ const out = {};
310
+ for (const f of files) {
311
+ if (!ownPath(f)) return null;
269
312
  try {
270
- st = fs.lstatSync(p);
271
- } catch (e) {
272
- if (e.code === 'ENOENT') continue;
273
- return false;
313
+ out[f] = crypto
314
+ .createHash('sha256')
315
+ .update(readOwnText(path.resolve(WS, f)))
316
+ .digest('hex');
317
+ } catch {
318
+ return null;
274
319
  }
275
- if (first ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return false;
276
320
  }
277
- return true;
321
+ return out;
322
+ }
323
+ const sameHashes = (a, b) =>
324
+ !!a && !!b && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((f) => a[f] === b[f]);
325
+ // (a path inside the workspace, with forward slashes, as importHashes takes them: Node names an imported file by its
326
+ // real path, so a workspace reached through a link, /var for /private/var, is matched by its real path too)
327
+ let realWS = null;
328
+ function inWorkspace(f) {
329
+ const leaves = (rel) => rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel);
330
+ let rel = path.relative(WS, f);
331
+ if (leaves(rel)) {
332
+ try {
333
+ realWS ||= fs.realpathSync(WS);
334
+ } catch {
335
+ realWS = WS;
336
+ }
337
+ if (!leaves(path.relative(realWS, f))) rel = path.relative(realWS, f);
338
+ }
339
+ return rel.split(path.sep).join('/');
278
340
  }
341
+
279
342
  // A design's own folder of a cache: named by a hash of its file's path in the workspace, so it stays the same when the
280
343
  // workspace moves, and one design's results are never read by another
281
344
  const designFolder = (dir, d) =>
@@ -357,7 +420,7 @@ function stageStore(d) {
357
420
  try {
358
421
  clearOldStages();
359
422
  prune(dir, STAGES_KEEP);
360
- if (makeRoom(STAGES, dir, Buffer.byteLength(text, 'utf8'), STAGES_HELD)) host.writeText(f, text);
423
+ if (makeRoom(STAGES, dir, Buffer.byteLength(text, 'utf8'), STAGES_HELD)) writeCacheFile(f, text);
361
424
  } catch {
362
425
  // (a cache that can't be written is only slower)
363
426
  }
@@ -384,7 +447,7 @@ const routeStore = (d) => {
384
447
  if (!f || !ownCacheFile(f)) return;
385
448
  try {
386
449
  prune(dir, ROUTES_KEEP);
387
- if (makeRoom(paths.cache('routes'), dir, Buffer.byteLength(text, 'utf8'), ROUTES_HELD)) host.writeText(f, text);
450
+ if (makeRoom(paths.cache('routes'), dir, Buffer.byteLength(text, 'utf8'), ROUTES_HELD)) writeCacheFile(f, text);
388
451
  } catch {
389
452
  // (a cache that can't be written is only slower)
390
453
  }
@@ -398,15 +461,21 @@ export const pcbEngine = () =>
398
461
  throw e;
399
462
  });
400
463
 
401
- // 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:
402
- // its threads and materials are used before the kit's), the project's printer as a rule set with its values worked
403
- // 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
404
- // made from these too, so its cache holds only while they stand.
405
464
  let kitRules = null;
465
+ /**
466
+ * What v.fixings is bound to (lib/fixings.mjs): the workspace's own rule sets by name (a release's own, where it is
467
+ * one: its threads and materials are used before the kit's), the project's printer as a rule set with its values
468
+ * worked out, and the project's material (a release's, as it was then). With a hash of all of it and of the kit's
469
+ * sets: a build that called v.fixings is made from these too, so its cache holds only while they stand. And the files
470
+ * it read them from: a release records those of the workspace, so a changed thread set counts as a change.
471
+ * @param {{ project: string, dir: string, rulesDir?: string, tree?: string }} d the design (a release's, materialised)
472
+ * @returns {{ context: { sets: object, printer: object | null, material: string | null }, hash: string, files: string[] }}
473
+ */
406
474
  export function fixingsContext(d) {
407
475
  const dir = d.rulesDir || RULE_DIRS[0],
408
476
  sets = {},
409
- text = [];
477
+ text = [],
478
+ files = [];
410
479
  for (const f of host
411
480
  .list(dir)
412
481
  .filter((x) => x.endsWith('.json'))
@@ -417,16 +486,19 @@ export function fixingsContext(d) {
417
486
  if (s && s.rules && typeof s.rules === 'object') {
418
487
  sets[s.name ?? f.slice(0, -5)] = s;
419
488
  text.push(raw);
489
+ files.push(path.join(dir, f));
420
490
  }
421
491
  } catch {
422
492
  // (a broken set is cad check's to name, where a design uses it)
423
493
  }
424
494
  }
425
- const name = printerOf(d.project),
495
+ const projectDir = d.tree ? path.join(d.tree, 'projects', d.project) : d.dir; // (a release's: its project.json as it was)
496
+ const name = printerOf(d.project, projectDir),
426
497
  peek = (n) => {
427
498
  plainName(n, 'rule set name');
428
499
  const f = [dir, ...RULE_DIRS].map((x) => path.join(x, `${n}.json`)).find((x) => host.exists(x));
429
500
  if (!f) throw new Error(`no rule set "${n}" (rules/${n}.json)`);
501
+ files.push(f);
430
502
  return readJson(f);
431
503
  };
432
504
  let printer = null;
@@ -445,7 +517,7 @@ export function fixingsContext(d) {
445
517
  }
446
518
  let material = null;
447
519
  try {
448
- const f = path.join(d.dir, 'project.json');
520
+ const f = path.join(projectDir, 'project.json');
449
521
  if (host.exists(f))
450
522
  material =
451
523
  String(readJson(f).material || '')
@@ -472,6 +544,7 @@ export function fixingsContext(d) {
472
544
  const context = { sets, printer, material };
473
545
  return {
474
546
  context,
547
+ files: [...new Set(files)].sort(),
475
548
  hash: crypto
476
549
  .createHash('sha256')
477
550
  .update(JSON.stringify([text, printer, material, kitRules]))
@@ -660,10 +733,82 @@ export async function boardChecks(b, d) {
660
733
  return boardWork('checks', args, d, until);
661
734
  }
662
735
 
736
+ // What a build read besides its own .js and .json, its "uses" rule sets and its layouts, as a release records it (lib/
737
+ // versions.mjs): files, the workspace's files its design imported (lid.js's ./box.js); fixings and frames, whether it
738
+ // called v.fixings or v.frames, which read the rule sets of rules/ (thread, material, profile sets, the printer's);
739
+ // sets, those rule sets' files as they are now (the workspace's own only: the kit's come with the kit), and the
740
+ // project's project.json where v.fixings drew (its material); also, the files
741
+ // of the objects it reads through "uses", so that the release holds them as they were. Paths inside the workspace (or
742
+ // the release), with forward slashes.
743
+ // (a file's path inside the workspace, or inside the release a design was materialised from, else null: the kit's own)
744
+ const inside = (d, f) => {
745
+ const r = path
746
+ .relative(d.tree || WS, f)
747
+ .split(path.sep)
748
+ .join('/');
749
+ return isWorkspacePath(r) ? r : null;
750
+ };
751
+ function readsOf(d, { imports, fixings, frames, also, framed, fixed }) {
752
+ const js = inside(d, d.js);
753
+ // (with the project's project.json where v.fixings drew: the material it drew for is the project's)
754
+ const pj = path.join(d.tree ? path.join(d.tree, 'projects', d.project) : d.dir, 'project.json');
755
+ const sets = [
756
+ ...(fixings ? fixed().files : []),
757
+ ...(fixings && host.exists(pj) ? [pj] : []),
758
+ ...(frames ? framed.files || [] : []),
759
+ ]
760
+ .map((f) => inside(d, f))
761
+ .filter(Boolean);
762
+ return {
763
+ files: imports.filter((f) => f !== js),
764
+ fixings,
765
+ frames,
766
+ sets: [...new Set(sets)].sort(),
767
+ also,
768
+ };
769
+ }
770
+
771
+ /**
772
+ * The text of each file a design read besides its own, as a release's record names them (lib/versions.mjs: the files
773
+ * its design imported, and, where it called v.fixings or v.frames, the rule sets those read and the project's material),
774
+ * read from the release's folder for a release, else from the workspace: compared file by file between a release and
775
+ * the design now, so an edited helper or thread set counts as a change. A file that isn't there is null.
776
+ * @param {{ project: string, dir: string, js: string, rulesDir?: string, tree?: string }} d the design, or a release (materialise's)
777
+ * @param {{ files: string[], fixings: boolean, frames: boolean }} reads a release's record
778
+ * @returns {Record<string, string | null>} by path inside the workspace
779
+ */
780
+ export function readTexts(d, reads) {
781
+ const top = d.tree || WS,
782
+ out = {};
783
+ const text = (f) => {
784
+ try {
785
+ return readOwnText(path.join(top, ...f.split('/'))).replace(/\r\n/g, '\n'); // (a Windows checkout may write \r\n)
786
+ } catch {
787
+ return null;
788
+ }
789
+ };
790
+ for (const f of reads.files) out[f] = text(f);
791
+ const fx = reads.fixings ? fixingsContext(d) : null;
792
+ const sets = [...(fx ? fx.files : []), ...(reads.frames ? framesContext(d.rulesDir || RULE_DIRS[0]).files : [])]
793
+ .map((f) => inside(d, f))
794
+ .filter(Boolean);
795
+ for (const f of sets.sort()) out[f] = text(f);
796
+ if (fx) {
797
+ // (the project's material and printer, which v.fixings draws for: a project.json with another printer is a change)
798
+ out[`projects/${d.project}/project.json: material`] = fx.context.material;
799
+ out[`projects/${d.project}/project.json: printer`] = fx.context.printer?.name ?? null;
800
+ }
801
+ return out;
802
+ }
803
+
663
804
  // build(design, set, { mirror, trusted }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export), fixings? }
664
805
  // trusted: the caller trusts the design, for a host other than Node's file system (memoryHost): run it in this process, not the sandbox (runsHere)
665
806
  // fixings: what the design's calls to v.fixings found (each hole and seat, what it was drawn to and rests on), as findings
807
+ // seats: what v.shapes' seat helpers drew (shaftBore, bearingSeat, plainBearing, pulleyBore), as 'seat.drawn' findings
666
808
  // parts: [{ name, role, label, geometry, polygons, triangles }]; polygons and triangles: every part together
809
+ // imports: the files of the workspace the design imported (its project's helpers), paths inside the workspace with
810
+ // forward slashes: the build is made from them too, and its kept copy holds only while they read the same
811
+ // reads: what it read besides its own files, as a release records it (readsOf)
667
812
  export async function build(d, set = {}, { mirror = false, trusted = false } = {}) {
668
813
  const object = readObject(d);
669
814
  set = variantSet(d, object, set);
@@ -703,9 +848,18 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
703
848
  ...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))),
704
849
  JSON.stringify(refs.extra),
705
850
  ];
706
- const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
707
- // (v.frames reads the workspace's own profile sets: a build is made from them too, lib/frames.mjs)
708
- const framed = framesContext(RULE_DIRS[0]);
851
+ // (and whether it is printed: a reference's holes, or a board's, made by its fab, are drawn with no hole
852
+ // compensation, lib/fixings.mjs)
853
+ const reference = ['reference', 'board'].includes(object.role),
854
+ reads = {
855
+ values,
856
+ parts: object.parts,
857
+ engine: object.engine,
858
+ mirror: object.mirror,
859
+ ...(reference ? { reference } : {}),
860
+ };
861
+ // (v.frames reads the workspace's own profile sets, or a release's own: a build is made from them too, lib/frames.mjs)
862
+ const framed = framesContext(d.rulesDir || RULE_DIRS[0]);
709
863
  const key = crypto
710
864
  .createHash('sha256')
711
865
  .update(
@@ -726,18 +880,27 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
726
880
  .digest('hex');
727
881
  const hit = path.join(CACHE, `${key}.json`);
728
882
  // (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
729
- // while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot)
883
+ // while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot.
884
+ // Likewise the files the design imported: a kept build holds while they read the same, and is known by them)
730
885
  let fx = null;
731
886
  const fixed = () => (fx ||= fixingsContext(d)),
732
- known = (f) =>
733
- f
887
+ // (v.fixings as this object has it: a reference is not printed)
888
+ bound = () => ({ ...fixed().context, ...(reference ? { printed: false } : {}) }),
889
+ known = (f, imported) => {
890
+ const more = (f || '') + (imported && Object.keys(imported).length ? JSON.stringify(imported) : '');
891
+ return more
734
892
  ? crypto
735
893
  .createHash('sha256')
736
- .update(key + f)
894
+ .update(key + more)
737
895
  .digest('hex')
738
896
  : key;
739
- const kept = !process.env.CAD_NO_CACHE && cached(hit) ? JSON.parse(host.readText(hit)) : null;
740
- if (kept && (!kept.fixed || kept.fixed === fixed().hash)) {
897
+ };
898
+ const kept = (!process.env.CAD_NO_CACHE && readCacheJson(hit)) || null; // (one cut short or spoiled: a miss, made again)
899
+ const keptImports =
900
+ kept && kept.imports && typeof kept.imports === 'object' && !Array.isArray(kept.imports)
901
+ ? importHashes(Object.keys(kept.imports))
902
+ : null;
903
+ if (kept && sameHashes(keptImports, kept.imports) && (!kept.fixed || kept.fixed === fixed().hash)) {
741
904
  const c = kept;
742
905
  try {
743
906
  host.touch(hit);
@@ -757,8 +920,18 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
757
920
  polygons: parts.flatMap((p) => p.polygons),
758
921
  triangles: parts.flatMap((p) => p.triangles),
759
922
  cached: true,
760
- hash: known(c.fixed),
923
+ hash: known(c.fixed, keptImports),
924
+ imports: Object.keys(keptImports),
925
+ reads: readsOf(d, {
926
+ imports: Object.keys(keptImports),
927
+ fixings: !!c.fixed,
928
+ frames: !!c.frames,
929
+ also: refs.files,
930
+ framed,
931
+ fixed,
932
+ }),
761
933
  ...(c.fixings ? { fixings: c.fixings } : {}),
934
+ ...(Array.isArray(c.seats) ? { seats: c.seats } : {}),
762
935
  ...(c.mechanism ? { mechanism: c.mechanism } : {}),
763
936
  ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}),
764
937
  };
@@ -770,8 +943,10 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
770
943
  let parts,
771
944
  board = null,
772
945
  read,
946
+ imported = [], // the files of the workspace the design imported (paths inside it, forward slashes)
773
947
  mechanism = null,
774
948
  fixings = null,
949
+ seats = null, // what v.shapes' seat helpers drew (lib/designshapes.mjs), as findings
775
950
  mounted = false;
776
951
  const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
777
952
  const stages = stageStore(d);
@@ -793,13 +968,15 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
793
968
  engine: booleans(object),
794
969
  optional,
795
970
  stages,
796
- bound: { frames: framed, fixings: fixed().context },
971
+ bound: { frames: framed, fixings: bound() },
797
972
  board: pcb ? { routes: routeStore(d) } : null,
798
973
  })
799
974
  .catch((e) => {
800
975
  throw syntaxAt(e, d);
801
976
  });
802
- ({ parts, read, mechanism, fixings } = r);
977
+ ({ parts, read, mechanism, fixings, seats } = r);
978
+ const project = path.dirname(path.dirname(path.resolve(d.js)));
979
+ imported = (r.imports || []).map((f) => inWorkspace(path.resolve(project, f)));
803
980
  if (pcb) {
804
981
  board = r.board;
805
982
  mounted = r.mounted;
@@ -819,7 +996,8 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
819
996
  });
820
997
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
821
998
  const ops = await shapes.ops(booleans(object)),
822
- df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
999
+ df = (await import('./fixings.mjs')).designFixings({ ...bound(), ops }), // (loaded when a design is run here: the sandbox's runner has its own)
1000
+ ds = designShapes(shapes, { printer: fixed().context.printer });
823
1001
  // v.pcb.mount('M2', ...) reads the workspace's thread sets, as v.fixings does: such a build is known by them too
824
1002
  const engine = pcb
825
1003
  ? {
@@ -833,7 +1011,7 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
833
1011
  const w = watch(
834
1012
  values,
835
1013
  {
836
- shapes,
1014
+ shapes: ds.shapes,
837
1015
  flexures,
838
1016
  gears,
839
1017
  motors,
@@ -863,20 +1041,28 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
863
1041
  throw located(e, d.js, 'design.run');
864
1042
  }
865
1043
  if (df.used()) fixings = df.found();
1044
+ if (ds.used()) seats = ds.found();
1045
+ imported = ((await host.importsOf?.(d.js)) || []).map(inWorkspace); // (after main: it may import as it runs)
866
1046
  }
867
1047
  for (const e of entries) if (read.has(e.name)) e.used = true;
868
- if (ownCacheFile(hit))
1048
+ // (read after the run: a helper saved while the design ran is then read as it is now, and the build kept under it,
1049
+ // until the next edit; a window of the run's length, against a cache that otherwise never sees the helper at all)
1050
+ const importsNow = importHashes([...new Set(imported)].sort());
1051
+ if (importsNow && ownCacheFile(hit))
869
1052
  try {
870
1053
  prune();
871
- host.writeText(
1054
+ writeCacheFile(
872
1055
  hit,
873
1056
  JSON.stringify({
874
1057
  used: entries.filter((e) => e.used).map((e) => e.name),
1058
+ imports: importsNow,
875
1059
  parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })),
876
1060
  ...(board || {}),
877
1061
  ...(mechanism ? { mechanism } : {}),
878
- ...(fixings || mounted ? { fixed: fixed().hash } : {}),
1062
+ ...(fixings || seats || mounted ? { fixed: fixed().hash } : {}),
879
1063
  ...(fixings ? { fixings } : {}),
1064
+ ...(seats ? { seats } : {}),
1065
+ ...(read.has(':frames') ? { frames: true } : {}),
880
1066
  }),
881
1067
  );
882
1068
  } catch {
@@ -891,8 +1077,18 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
891
1077
  parts,
892
1078
  polygons: parts.flatMap((p) => p.polygons),
893
1079
  triangles: parts.flatMap((p) => p.triangles),
894
- hash: known(fixings || mounted ? fixed().hash : null),
1080
+ hash: known(fixings || seats || mounted ? fixed().hash : null, importsNow || { [crypto.randomUUID()]: 'unread' }), // (one not read: known by no other build)
1081
+ imports: [...new Set(imported)].sort(),
1082
+ reads: readsOf(d, {
1083
+ imports: [...new Set(imported)].sort(),
1084
+ fixings: !!(fixings || seats || mounted),
1085
+ frames: read.has(':frames'),
1086
+ also: refs.files,
1087
+ framed,
1088
+ fixed,
1089
+ }),
895
1090
  ...(fixings ? { fixings } : {}),
1091
+ ...(seats ? { seats } : {}),
896
1092
  ...(board || {}),
897
1093
  ...(mechanism ? { mechanism } : {}),
898
1094
  };