@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/motors.mjs CHANGED
@@ -8,10 +8,10 @@ import { stageEfficiency } from '@rulecad/gears';
8
8
  import { screwGroup } from '@rulecad/fixings';
9
9
  import { named } from './parts.mjs';
10
10
  import { referenceBuilt } from './bought.mjs';
11
- import crypto from 'node:crypto';
12
11
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
13
12
  import { threadsBackend } from '@rulecad/fea/threads';
14
- import { host, cached } from './host.mjs';
13
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
14
+ import { feKey } from './fe-key.mjs';
15
15
  import { paths, printerOf } from './workspace.mjs';
16
16
  import { peekRuleSet } from './rules.mjs';
17
17
  import { isPlainName } from './names.mjs';
@@ -828,32 +828,12 @@ export function mountFE({
828
828
  nu,
829
829
  budget = 9000,
830
830
  }) {
831
- const key = crypto
832
- .createHash('sha256')
833
- .update(
834
- JSON.stringify([
835
- 4,
836
- tris,
837
- holes,
838
- hole,
839
- plate,
840
- side,
841
- held,
842
- down,
843
- weight,
844
- centre,
845
- torque,
846
- tip,
847
- ref,
848
- E,
849
- nu,
850
- budget,
851
- ]),
852
- )
853
- .digest('hex')
854
- .slice(0, 24),
855
- file = paths.cache('mount', `${key}.json`);
856
- if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
831
+ const file = paths.cache(
832
+ 'mount',
833
+ `${feKey('mount', [tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref, E, nu, budget])}.json`,
834
+ );
835
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
836
+ if (kept) return kept;
857
837
  const { lo, hi } = box3(tris.flat()),
858
838
  span = sub3(hi, lo);
859
839
  let cell = Math.max(0.4, plate / 2);
@@ -988,7 +968,7 @@ export function mountFE({
988
968
  atHoles = holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip + cell);
989
969
  }
990
970
  const out = { deflection, relative: !!base, stress, atHoles, cell, across, held: heldBy, cells: g.cells };
991
- host.writeText(file, JSON.stringify(out));
971
+ writeCacheFile(file, JSON.stringify(out));
992
972
  return out;
993
973
  }
994
974
 
package/lib/names.mjs CHANGED
@@ -39,3 +39,18 @@ export function isObjectRefName(ref) {
39
39
  const m = typeof ref === 'string' && OBJECT_REF.exec(ref);
40
40
  return !!m && isPlainName(m[1]) && isPlainName(m[2]);
41
41
  }
42
+
43
+ /**
44
+ * Whether `f` is a path to a file inside a workspace as the tool writes one down (a build's imports, a release's
45
+ * list of what it read): relative, with forward slashes, never climbing out (..), never absolute or with a drive
46
+ * letter, and never into a node_modules folder. Such lists can come from a workspace's own .cache/ or a release's tag,
47
+ * which a cloned workspace brings, so a path that is not like this is never read.
48
+ * @param {unknown} f
49
+ * @returns {boolean}
50
+ */
51
+ export const isWorkspacePath = (f) =>
52
+ typeof f === 'string' &&
53
+ f !== '' &&
54
+ !f.startsWith('/') &&
55
+ !/^[a-zA-Z]:|\\/.test(f) &&
56
+ f.split('/').every((s) => s !== '' && s !== '.' && s !== '..' && s.toLowerCase() !== 'node_modules');
package/lib/optimise.mjs CHANGED
@@ -8,7 +8,8 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
10
  import { AsyncLocalStorage } from 'node:async_hooks';
11
- import { host, readJson, cached } from './host.mjs';
11
+ import { host, readJson } from './host.mjs';
12
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
12
13
  import { paths, printerOf, noLinksOut } from './workspace.mjs';
13
14
  import { plainName } from './names.mjs';
14
15
  import { resolve, evaluate, fmt } from './rules.mjs';
@@ -35,6 +36,7 @@ import {
35
36
  import { islands } from '@rulecad/printcheck';
36
37
  import { turn, mul, inv, placeItems, jointValues } from '@rulecad/model-link';
37
38
  import { section, loops, slabLevels } from './mesh.mjs';
39
+ import { codeOnly } from './code-text.mjs';
38
40
  import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
39
41
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
40
42
 
@@ -688,24 +690,30 @@ function made(r, spec, density) {
688
690
  return out;
689
691
  }
690
692
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
691
- /**
692
- * The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
693
- * up to its shapes from results), the FE's code and its threads backend (the solver's products), and cad's own code
694
- * that readies the problem for the solver (holdEmpty). Drawing a shape from the densities is not in it.
695
- * @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
696
- */
697
693
  /**
698
694
  * Throws (code workspace.outside, naming the link) where the kept results optimised() reads (.cache/optimise,
699
695
  * .cache/densities) hold a link out of the workspace: a cloned workspace may carry a .cache/ of its own. Called before
700
696
  * optimised(), as its own text is part of the densities key (densityCode).
701
697
  */
702
698
  export const ownResults = () => noLinksOut([paths.cache('optimise'), paths.cache('densities')]);
703
- export const densityCode = () => ({
699
+ // The solver's share of topopt's file: the code above this line, which decides the densities (all model() calls, the
700
+ // virtual temperature among them: cache-salts.test.mjs holds it so); below it, only how a shape is drawn from them
701
+ const SHAPES_FROM_RESULTS = '// ---------- shapes from results ----------';
702
+ /**
703
+ * The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
704
+ * up to its shapes from results), the FE's code and its threads backend (the solver's products), and cad's own code
705
+ * that readies the problem for the solver (holdEmpty, and optimised, which calls it). Drawing a shape from the
706
+ * densities is not in it. Each is the code without its comment lines and blank lines (codeOnly), so rewording a
707
+ * comment keeps the densities, and any change to the code optimises again.
708
+ * @param {(module: string) => string} [read] reads a module's text by its name (tests read an edited copy)
709
+ * @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
710
+ */
711
+ export const densityCode = (read = source) => ({
704
712
  version: VERSION,
705
- solver: source('@rulecad/topopt').split('// ---------- shapes from results ----------')[0],
706
- fea: source('@rulecad/fea'),
707
- threads: source('@rulecad/fea/threads'),
708
- cad: `${holdEmpty.toString()}\n${optimised.toString()}`,
713
+ solver: codeOnly(read('@rulecad/topopt').split(SHAPES_FROM_RESULTS)[0]),
714
+ fea: codeOnly(read('@rulecad/fea')),
715
+ threads: codeOnly(read('@rulecad/fea/threads')),
716
+ cad: codeOnly(`${holdEmpty.toString()}\n${optimised.toString()}`),
709
717
  });
710
718
  /**
711
719
  * The key an optimisation's densities are kept by (.cache/densities/<key>.json): the problem and every piece of
@@ -732,21 +740,21 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
732
740
  fs.readFileSync(new URL(import.meta.url), 'utf8'),
733
741
  ]),
734
742
  file = paths.cache('optimise', `${hash}.json`);
735
- if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file))
736
- return { ...JSON.parse(host.readText(file)), cached: true };
743
+ const shapeKept = !fresh && !process.env.CAD_NO_CACHE && readCacheJson(file); // (one cut short or spoiled: a miss)
744
+ if (shapeKept) return { ...shapeKept, cached: true };
737
745
  const spec = holdEmpty(discretise(r.problem)),
738
746
  densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
739
747
  // A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
740
748
  const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
741
- if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities))
749
+ const densitiesKept = !fresh && !process.env.CAD_NO_CACHE ? readCacheJson(densities) : undefined;
750
+ if (!fresh && !process.env.CAD_NO_CACHE && !densitiesKept)
742
751
  onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
743
752
  else if (fresh) onRun?.('asked to run afresh');
744
- const o =
745
- !fresh && !process.env.CAD_NO_CACHE && host.exists(densities)
746
- ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(JSON.parse(host.readText(densities)))
747
- : optimise(spec, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
748
- if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
749
- if (!host.exists(seen)) host.writeText(seen, '');
753
+ const o = densitiesKept
754
+ ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(densitiesKept)
755
+ : optimise(spec, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
756
+ if (!host.exists(densities)) writeCacheFile(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
757
+ if (!host.exists(seen)) writeCacheFile(seen, '');
750
758
  // Regions as data: a part's triangles are named, not copied
751
759
  const named = (list) => list.map(({ triangles, ...x }) => x);
752
760
  const shape =
@@ -920,7 +928,7 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
920
928
  supports: named(r.problem.supports),
921
929
  loads: named(r.problem.loads),
922
930
  };
923
- host.writeText(file, JSON.stringify(result));
931
+ writeCacheFile(file, JSON.stringify(result));
924
932
  return result;
925
933
  }
926
934
 
@@ -980,12 +988,13 @@ export async function analysePart(triangles, project, ref, { cell } = {}) {
980
988
  )
981
989
  .digest('hex')}.json`,
982
990
  );
983
- if (!process.env.CAD_NO_CACHE && cached(file)) {
984
- const { density, ...x } = JSON.parse(host.readText(file));
991
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
992
+ if (kept) {
993
+ const { density, ...x } = kept;
985
994
  return { ...x, density: Float64Array.from(density) };
986
995
  }
987
996
  const out = analyseSolid(triangles, r, h);
988
- host.writeText(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
997
+ writeCacheFile(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
989
998
  return out;
990
999
  }
991
1000
  // The grid covers the part and the problem's space
package/lib/order.mjs CHANGED
@@ -6,10 +6,8 @@
6
6
  // tool comes from (its anchor's z points out along the screw): whatever stands on that line must go on after it.
7
7
  // Works on the assembly's top-level items; a component (an assembly used as an item) is one step.
8
8
  import crypto from 'node:crypto';
9
- import path from 'node:path';
10
- import fs from 'node:fs';
11
9
  import { placeItems, jointValues, mul } from '@rulecad/model-link';
12
- import { host, cached } from './host.mjs';
10
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
13
11
  import { paths } from './workspace.mjs';
14
12
  import { motorScrews } from './motors.mjs';
15
13
  import jscad from '@jscad/modeling';
@@ -605,14 +603,10 @@ function orderFile(s) {
605
603
  export function orderOf(s) {
606
604
  if (s.orderSteps) return s.orderSteps;
607
605
  const file = orderFile(s);
608
- if (!process.env.CAD_NO_CACHE && cached(file)) return (s.orderSteps = JSON.parse(host.readText(file)));
606
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
607
+ if (kept) return (s.orderSteps = kept);
609
608
  const r = assemblyOrder(s);
610
- try {
611
- fs.mkdirSync(path.dirname(file), { recursive: true });
612
- host.writeText(file, JSON.stringify(r));
613
- } catch {
614
- // (a cache that can't be written is only slower)
615
- }
609
+ writeCacheFile(file, JSON.stringify(r)); // (one that can't be written is only slower)
616
610
  return (s.orderSteps = r);
617
611
  }
618
612
 
package/lib/parts.mjs CHANGED
@@ -29,6 +29,8 @@ export function unpack(made) {
29
29
  // (v.mx.housing_top) are noted in `read`, so estimates a design relies on get flagged. A name that isn't there is
30
30
  // refused: a misspelt v.widht would otherwise come through as undefined, and quietly draw another shape. `optional`
31
31
  // names may be absent: the display's own inputs, and what only some designs get (layouts, problems, the board engine).
32
+ // A helper the design reached for is noted as `:<name>` (':frames'): no rule's name holds a colon. A release records
33
+ // the rule sets v.frames reads only for a design that used it.
32
34
  export function watch(values, extras = {}, optional = []) {
33
35
  const read = new Set(),
34
36
  may = new Set([...optional, 'layouts', 'problems', 'pcb', 'then', 'toJSON']);
@@ -50,6 +52,7 @@ export function watch(values, extras = {}, optional = []) {
50
52
  };
51
53
  const v = new Proxy(given, {
52
54
  get: (t, r) => {
55
+ if (typeof r === 'string' && Object.hasOwn(extras, r)) read.add(`:${r}`);
53
56
  if (typeof r !== 'string' || r in t || may.has(r)) return t[r];
54
57
  const guess = near(r, Object.keys(t));
55
58
  throw new CadError(
package/lib/rules.mjs CHANGED
@@ -24,7 +24,8 @@ export function loadRuleSet(name, dir) {
24
24
  host.writeText(own, readOwnText(file));
25
25
  console.error(`copied the ${name} rule set into rules/${name}.json: yours to keep and edit`);
26
26
  }
27
- return readJson(own);
27
+ // (a release's own rules are read from its folder: the workspace's copy may have been measured again since)
28
+ return readJson(dir ? file : own);
28
29
  }
29
30
  /**
30
31
  * `file` (a rule set about to be written into the workspace's rules/) if no folder or file on its way down from the
@@ -1,5 +1,12 @@
1
- // The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors, @rulecad/frames, @rulecad/fixings and files of
2
- // its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
1
+ // The sandbox's import hook: code in the design's project may import the packages in ALLOWED (below: the one list,
2
+ // which the README, AGENTS.md and sandbox.mjs follow, and test/sandbox-docs.test.mjs holds them to) and files of its
3
+ // own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
4
+ // Where Node has module.registerHooks (22.15 on) the hook runs in the design's own thread and sees require() as well as
5
+ // import; before that it runs in a worker and sees only import. A CommonJS file has the CommonJS loader itself to hand
6
+ // (module.constructor, require.cache), which can load Node's own modules past any hook: so no file of the project is
7
+ // loaded as CommonJS (.cjs, or a .js file Node reads as CommonJS), on every Node. A design and its files are ES modules
8
+ // (import and export), as the README says. The runner (sandbox-run.mjs) shuts the CommonJS loader to Node's own
9
+ // modules as well, before the design loads, for any other way to it (test/sandbox-loader.test.mjs tries them).
3
10
  // An allowed package is named plainly and must lead inside that package: '@jscad/modeling/../../graceful-fs' would
4
11
  // otherwise climb out of it to any file of the workspace, and a file outside the project isn't held to these rules.
5
12
  import fs from 'node:fs';
@@ -10,7 +17,40 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
10
17
  // (Not @rulecad/pcb: a board design reaches the board engine as v.pcb, which the runner loads as the tool's own
11
18
  // module. The engine imports Node's modules, which a package a design may import may not, and the permission model
12
19
  // holds it to reads only.)
13
- const ALLOWED = [
20
+ /**
21
+ * The only modules of Node's own the sandbox loads, for the tool's code (a design gets none): what the tool's packages
22
+ * use as they run (Manifold's loader asks for fs, path and url; a board's engine for crypto) and others like them,
23
+ * none of which reaches the network, another program, a worker or another loader. Every other module of Node's (net,
24
+ * http, dns, tls, tty, child_process, worker_threads, vm, inspector and the rest) is refused to every caller, by this
25
+ * hook and by the runner's lock on the CommonJS loader (sandbox-lock.mjs): before Node 25 that is what keeps the
26
+ * network shut, whatever way round the rest a design finds.
27
+ */
28
+ export const QUIET = new Set(
29
+ (
30
+ 'assert assert/strict buffer console constants crypto events fs fs/promises os path path/posix path/win32 ' +
31
+ 'perf_hooks process punycode querystring readline readline/promises stream stream/consumers stream/promises ' +
32
+ 'stream/web string_decoder timers timers/promises url util util/types zlib'
33
+ ).split(' '),
34
+ );
35
+ // Where these hooks run in the design's own thread (module.registerHooks), the design can change String.prototype,
36
+ // Set.prototype and the like for everyone: what decides which of Node's modules load, and whether code is the
37
+ // design's, uses functions taken here, before any design runs, and lists of its own.
38
+ const call = Reflect.apply,
39
+ startsWith = String.prototype.startsWith,
40
+ slice = String.prototype.slice,
41
+ has = Set.prototype.has,
42
+ QUIET_NOW = new Set(QUIET),
43
+ NODES = new Set(builtinModules);
44
+ const bare = (spec) => (call(startsWith, spec, ['node:']) ? call(slice, spec, [5]) : spec);
45
+ /** Whether spec names a module of Node's own (with or without "node:"). @param {string} spec */
46
+ export const isNodes = (spec) =>
47
+ typeof spec === 'string' && (call(startsWith, spec, ['node:']) || call(has, NODES, [spec]));
48
+ /** Whether spec names one of Node's own modules the sandbox loads for the tool (QUIET). @param {string} spec */
49
+ export const quiet = (spec) => typeof spec === 'string' && call(has, QUIET_NOW, [bare(spec)]);
50
+ const within = (url, folder) => typeof url === 'string' && !!folder && call(startsWith, url, [folder]);
51
+
52
+ /** The packages a design may import, by name (a file inside one too): the hook's one list, as the documents give it. */
53
+ export const ALLOWED = [
14
54
  '@jscad/modeling',
15
55
  '@rulecad/shapes',
16
56
  '@rulecad/flexures',
@@ -59,6 +99,12 @@ export const homesOf = () => Object.fromEntries(ALLOWED.map((a) => [a, home(a)])
59
99
  let project = '',
60
100
  homes = {},
61
101
  deps = {};
102
+ // The files of its own project the design imported (file: URLs, without a query), for the build's cache: a kept build
103
+ // holds while each of them reads as it did (design.mjs). The runner asks for them by importing IMPORTED, a module these
104
+ // hooks make up, which works the same whether they run in the runner's thread or in a worker of their own (older Node).
105
+ const imported = new Set();
106
+ /** The name the runner imports to learn which of its project's files the design imported (a list of file: URLs). */
107
+ export const IMPORTED = 'rulecad-imports:list';
62
108
  /**
63
109
  * Set the hooks up: the design's project (a file: URL ending in a slash) and, from the preload, the packages' folders.
64
110
  * @param {{ project?: string, homes?: Record<string, string | null> }} [data]
@@ -72,16 +118,58 @@ export async function initialize(data) {
72
118
  const deny = (spec, why) =>
73
119
  Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
74
120
 
75
- // The same check, for in-thread hooks (synchronous) and worker hooks (async)
121
+ // The same check, for in-thread hooks (synchronous) and worker hooks (async). (IMPORTED only after the check: a design
122
+ // that imports it by name is refused, as any name that isn't an allowed package is.)
76
123
  export function resolveHook(spec, context, next) {
77
- const fromDesign = check(spec, context),
78
- r = next(spec, context);
79
- return fromDesign ? after(spec, r) : inPackage(spec, context, r);
124
+ const fromDesign = check(spec, context);
125
+ if (spec === IMPORTED) return { url: IMPORTED, shortCircuit: true };
126
+ const r = next(spec, context);
127
+ return fromDesign ? noted(spec, after(spec, r)) : inPackage(spec, context, r);
80
128
  }
81
129
  export async function resolve(spec, context, next) {
82
- const fromDesign = check(spec, context),
83
- r = await next(spec, context);
84
- return fromDesign ? after(spec, r) : inPackage(spec, context, r);
130
+ const fromDesign = check(spec, context);
131
+ if (spec === IMPORTED) return { url: IMPORTED, shortCircuit: true };
132
+ const r = await next(spec, context);
133
+ return fromDesign ? noted(spec, after(spec, r)) : inPackage(spec, context, r);
134
+ }
135
+ /** The import hook's load, in this thread: IMPORTED's text, the list as it stands (the runner imports it once, after
136
+ * the design's main has run); any other module as Node loads it, but a file of the project that is CommonJS. */
137
+ export function loadHook(url, context, next) {
138
+ return url === IMPORTED
139
+ ? { format: 'module', source: `export default ${JSON.stringify([...imported])};`, shortCircuit: true }
140
+ : notCommonJS(url, next(url, context));
141
+ }
142
+ /** The import hook's load, in a worker (older Node): as loadHook. */
143
+ export async function load(url, context, next) {
144
+ return url === IMPORTED ? loadHook(url, context) : notCommonJS(url, await next(url, context));
145
+ }
146
+ // A file of the project that Node would run as CommonJS (format 'commonjs', or 'commonjs-typescript' for a .cts) is
147
+ // refused before it runs: it would have module.constructor, the CommonJS loader, which hands out Node's own modules
148
+ // whatever this hook says. (A package kept in the project's node_modules is the project's too, and held the same.)
149
+ function notCommonJS(url, r) {
150
+ if (within(url, project) && typeof r?.format === 'string' && call(startsWith, r.format, ['commonjs'])) {
151
+ const file = fileURLToPath(url.replace(/[?#].*$/, ''));
152
+ throw Object.assign(
153
+ new Error(
154
+ `designs can't load ${file}: it is a CommonJS file (require and module.exports), and a design's files are ES modules (import and export). In the sandbox a CommonJS file could reach Node's own modules, so none is loaded. Write it with import and export (a .js file in a workspace whose package.json says "type": "module", or a .mjs file)`,
155
+ ),
156
+ { code: 'design.sandbox' },
157
+ );
158
+ }
159
+ return r;
160
+ }
161
+ // A file of the project the design reached by a relative path is noted (a package's copy kept in the project's
162
+ // node_modules is not the design's own code: it changes with an install, as the tool's packages do)
163
+ function noted(spec, r) {
164
+ if (isRelative(spec) && r.url.startsWith(project)) {
165
+ const u = new URL(r.url);
166
+ if (!u.pathname.split('/').some((s) => s.toLowerCase() === 'node_modules')) {
167
+ u.search = '';
168
+ u.hash = '';
169
+ imported.add(u.href);
170
+ }
171
+ }
172
+ return r;
85
173
  }
86
174
  // A design may reach any file of an allowed package, and such a file isn't the design's, so it is free of the rules
87
175
  // above: one that imports something the package doesn't depend on would hand that to the design. @jscad/modeling's
@@ -127,12 +215,12 @@ const packageOf = (spec) => ALLOWED.find((a) => spec === a || spec.startsWith(`$
127
215
  // uses, or a copy in the project: not through a link out of the project to some other folder of the same name.
128
216
  const after = (spec, r) => {
129
217
  if (isRelative(spec)) {
130
- if (!r.url.startsWith(project)) throw deny(spec, 'it is outside the project');
218
+ if (!within(r.url, project)) throw deny(spec, 'it is outside the project');
131
219
  return r;
132
220
  }
133
221
  const name = packageOf(spec),
134
222
  inside = homes[name];
135
- if (!r.url.startsWith(project) && !(inside && r.url.startsWith(inside))) {
223
+ if (!within(r.url, project) && !within(r.url, inside)) {
136
224
  const to = r.url.startsWith('file:') ? fileURLToPath(r.url) : r.url;
137
225
  const own = inside ? ` (${fileURLToPath(inside)})` : '';
138
226
  throw deny(
@@ -158,11 +246,17 @@ const climbs = (spec, name) =>
158
246
  .some(odd));
159
247
  // Everything under the project is the design's code, a node_modules folder there included
160
248
  function check(spec, context) {
161
- const fromDesign = project && context.parentURL?.startsWith(project);
249
+ const fromDesign = within(context.parentURL, project);
250
+ // (whoever imports it: code of the design's that has worked its way to the CommonJS loader can make a module that
251
+ // says it is a file of the tool's, sandbox-lock.mjs says how, so the tool's own code is held to the same list)
252
+ if (!fromDesign && isNodes(spec) && !quiet(spec) && bare(spec) !== 'module')
253
+ throw deny(
254
+ spec,
255
+ "in the sandbox none of Node's own modules that reach the network, other programs or workers is loaded",
256
+ );
162
257
  if (!fromDesign) packageCheck(spec, context);
163
258
  if (fromDesign) {
164
- if (spec.startsWith('node:') || builtinModules.includes(spec))
165
- throw deny(spec, 'a design only makes shapes (no files, network or programs)');
259
+ if (isNodes(spec)) throw deny(spec, 'a design only makes shapes (no files, network or programs)');
166
260
  if (!isRelative(spec)) {
167
261
  const name = packageOf(spec);
168
262
  if (!name) throw deny(spec, `only ${ALLOWED.join(', ')} and files in its project`);