@rulecad/cad 0.8.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 (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/lib/sandbox.mjs CHANGED
@@ -1,15 +1,19 @@
1
- // Designs are code. A JSCAD design runs in a sandbox: another Node process with the permission model on. What that
2
- // promises, whatever the design does: it can't write or delete files, start programs or workers, or load addons, and
3
- // it reads only the workspace and the packages designs use. That much is Node's own boundary.
4
- // On top of it, to keep a design to making shapes: an import hook (sandbox-hooks.mjs) lets it import only
5
- // @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors, @rulecad/frames, @rulecad/fixings and
6
- // files in its own project (no node: modules); the runner
7
- // takes away fetch and its kin and process's own ways to Node's modules; and it is started with none of this
8
- // process's environment (no tokens). Those close the ordinary roads to the network, not every one: before Node 25
9
- // the permission model doesn't cover the network, so a design written to get round them might still reach it, and
10
- // read the workspace as it does. So: run only designs you trust, as with any code.
1
+ // Designs are code. A JSCAD design runs in a sandbox: another Node process with Node's permission model on, started
2
+ // with no --allow-fs-write, --allow-child-process, --allow-addons, --allow-wasi or --allow-net, reads allowed only in
3
+ // the folders readable() lists (of the workspace, only the design's own project), and none of this process's environment (no tokens). On top of Node's boundary, to keep
4
+ // a design to making shapes: the import hook (sandbox-hooks.mjs) lets it import only the packages in ALLOWED there and
5
+ // files of its own project, and loads no CommonJS file of the project (which would have the CommonJS loader to hand);
6
+ // the runner (sandbox-run.mjs, with sandbox-lock.mjs) takes away fetch and its kin and process's own ways to Node's
7
+ // modules, shuts the CommonJS loader to Node's modules, and gives the design plain streams in place of the standard
8
+ // streams' sockets. What that leaves a design, Node version by Node version, is the table in the README's Sandbox
9
+ // paragraph (its rows tried by test/sandbox-docs.test.mjs, sandbox-loader.test.mjs and sandbox.test.mjs): it can never
10
+ // write files or start programs, reads only what its imports name (its project's files, the allowed packages), and
11
+ // reaches no socket by any way the tests know of. Before Node 25 that last rests on the runner alone, in the design's
12
+ // own process, as the permission model doesn't cover the network: cad says so once a run (networkWarning). From Node
13
+ // 25 the permission model shuts the network too.
14
+ // So: run only designs you trust, as with any code.
11
15
  // It gets its values as data and sends back its parts' faces. A workspace that trusts its designs sets
12
- // "sandbox": false in cad.config.json (or CAD_TRUST=1).
16
+ // "sandbox": false in cad.config.json (counted once the user has run cad trust there) or CAD_TRUST=1.
13
17
  // Board designs (engine pcb) run here too, with the board engine: the sandbox may then also read @rulecad/pcb and what
14
18
  // it loads (tscircuit's packages), the design gets v.pcb as it would in the tool's process (v.pcb.mount reads the
15
19
  // workspace's thread sets, handed in as data), the runner builds the board's Circuit JSON, and the reply carries it
@@ -17,16 +21,23 @@
17
21
  // from. The autorouter's results come back the same way as a lamina's stages, for the tool to keep.
18
22
  import fs from 'node:fs';
19
23
  import path from 'node:path';
20
- import { spawn } from 'node:child_process';
24
+ import { spawn, execFile } from 'node:child_process';
25
+ import { constants as bufferConstants } from 'node:buffer';
21
26
  import * as nodeModule from 'node:module';
22
27
  import { pathToFileURL, fileURLToPath } from 'node:url';
23
- import { WS, TOOL, config, paths, trusted } from './workspace.mjs';
28
+ import { WS, TOOL, config, trusted, DESIGN_TIMEOUT, DESIGN_MEMORY, ownFile } from './workspace.mjs';
24
29
  import { fromFaces } from './parts.mjs';
25
30
  import { located } from './errors.mjs';
31
+ import { STAGES_MOST, ROUTES_MOST } from './kept.mjs';
32
+ import { ALLOWED } from './sandbox-hooks.mjs';
26
33
 
27
34
  const flag = (() => {
28
35
  const f = process.allowedNodeEnvironmentFlags;
29
- return f.has('--permission') ? '--permission' : f.has('--experimental-permission') ? '--experimental-permission' : null;
36
+ return f.has('--permission')
37
+ ? '--permission'
38
+ : f.has('--experimental-permission')
39
+ ? '--experimental-permission'
40
+ : null;
30
41
  })();
31
42
 
32
43
  const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks in this thread; older Node needs a worker for them
@@ -35,19 +46,60 @@ const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks
35
46
  // (a workspace's "sandbox": false counts only once the user has trusted it: cad trust)
36
47
  export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && !(config.sandbox === false && trusted());
37
48
 
38
- // What the sandbox may read: the workspace, and the packages designs and the runner load (wherever npm put them), and
39
- // what those load in turn (@rulecad/frames sizes a beam's operations through @rulecad/fixings)
40
- function readable({ board = false, extra = [] } = {}) {
41
- const real = (p) => { try { return fs.realpathSync(p); } catch { return null; } };
42
- const pkgDir = (name, from) => { // the package's folder: from its entry up to its package.json (exports may hide that file)
43
- try { let d = path.dirname(nodeModule.createRequire(from).resolve(name)); while (!fs.existsSync(path.join(d, 'package.json')) && path.dirname(d) !== d) d = path.dirname(d); return d; } catch { return null; }
49
+ // What the sandbox may read: of the workspace, what `own` names (the design's project, the workspace's package.json and
50
+ // the design's own cache folders: runSandboxed), and the packages designs and the runner load (wherever npm put them), and
51
+ // what those load in turn (@rulecad/frames sizes a beam's operations through @rulecad/fixings). Node's permission
52
+ // model follows a link inside these folders wherever it leads, so a link in the design's project or rules/ that leads
53
+ // out of the workspace is refused before the sandbox starts (workspace.mjs noLinksOut, from design.mjs).
54
+ function readable({ board = false, extra = [], own = [WS] } = {}) {
55
+ const real = (p) => {
56
+ try {
57
+ return fs.realpathSync(p);
58
+ } catch {
59
+ return null;
60
+ }
44
61
  };
45
- const fromWs = path.join(WS, 'package.json'), fromTool = path.join(TOOL, 'package.json');
62
+ const pkgDir = (name, from) => {
63
+ // the package's folder: from its entry up to its package.json (exports may hide that file)
64
+ try {
65
+ let d = path.dirname(nodeModule.createRequire(from).resolve(name));
66
+ while (!fs.existsSync(path.join(d, 'package.json')) && path.dirname(d) !== d) d = path.dirname(d);
67
+ return d;
68
+ } catch {
69
+ return null;
70
+ }
71
+ };
72
+ const fromWs = path.join(WS, 'package.json'),
73
+ fromTool = path.join(TOOL, 'package.json');
46
74
  // Every node_modules above the workspace and the tool (package lookups read their links), and where links lead
47
- const up = (dir) => { const out = []; for (let d = dir; ; d = path.dirname(d)) { out.push(path.join(d, 'node_modules')); if (path.dirname(d) === d) return out; } };
48
- const dirs = [WS, TOOL, ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
49
- ...['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/frames', '@rulecad/fixings', '@rulecad/rules/x1c.json', '@rulecad/fea', '@rulecad/variables', 'manifold-3d'].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)]), ...extra];
50
- const out = [...new Set(dirs.filter(Boolean).flatMap((d) => [d, real(d)]).filter(Boolean))];
75
+ const up = (dir) => {
76
+ const out = [];
77
+ for (let d = dir; ; d = path.dirname(d)) {
78
+ out.push(path.join(d, 'node_modules'));
79
+ if (path.dirname(d) === d) return out;
80
+ }
81
+ };
82
+ const dirs = [
83
+ ...own,
84
+ TOOL,
85
+ ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
86
+ ...[
87
+ ...ALLOWED, // (what a design may import, and what the runner loads besides)
88
+ '@rulecad/rules/x1c.json',
89
+ '@rulecad/fea',
90
+ '@rulecad/variables',
91
+ 'manifold-3d',
92
+ ].flatMap((n) => [pkgDir(n, fromWs), pkgDir(n, fromTool)]),
93
+ ...extra,
94
+ ];
95
+ const out = [
96
+ ...new Set(
97
+ dirs
98
+ .filter(Boolean)
99
+ .flatMap((d) => [d, real(d), path.join(real(path.dirname(d)) || path.dirname(d), path.basename(d))]) // (and by its folder's real path: a link spelled from there)
100
+ .filter(Boolean),
101
+ ),
102
+ ];
51
103
  // A board's engine loads tscircuit's packages and @rulecad's own (smooth, rules, fixings): what it depends on, and
52
104
  // what they do in turn, wherever each really is. Most are in a node_modules listed above; a package linked in from
53
105
  // elsewhere (a workspace of packages, as rulecad's own repository is) is added by its real folder.
@@ -63,20 +115,52 @@ const PACKAGE_NAME = /^(@[a-z0-9][\w.~-]*\/)?[a-z0-9][\w.~-]*$/i;
63
115
  // "dependencies" that lead out of it (a link, a path) would have the sandbox read wherever they lead. Each dependency is
64
116
  // a package name, and its folder one whose package.json has that name.
65
117
  function engineFolders(out, real, pkgDir, from) {
66
- const found = [], seen = new Set(), under = (d) => out.some((o) => d === o || d.startsWith(o + path.sep));
67
- const named = (d, n) => { try { return JSON.parse(fs.readFileSync(path.join(d, 'package.json'), 'utf8')).name === n; } catch { return false; } };
118
+ const found = [],
119
+ seen = new Set(),
120
+ under = (d) => out.some((o) => d === o || d.startsWith(o + path.sep));
121
+ const named = (d, n) => {
122
+ try {
123
+ return JSON.parse(fs.readFileSync(path.join(d, 'package.json'), 'utf8')).name === n;
124
+ } catch {
125
+ return false;
126
+ }
127
+ };
68
128
  // (the folder found, or the one above it of that name: by its entry, a package's dist/package.json may be found first,
69
129
  // but never above the node_modules it is in)
70
- const own = (d, n) => { for (; d && path.basename(d) !== 'node_modules' && path.dirname(d) !== d; d = path.dirname(d)) if (named(d, n)) return d; return null; };
71
- const add = (d, n) => { d = d && own(d, n); if (!d || seen.has(d)) return; seen.add(d); if (!under(d)) found.push(d); walk(d); };
72
- const find = (n, dir) => { // (findPackageJSON where Node has it: exports that hide a package's entry from require don't hide this)
130
+ const own = (d, n) => {
131
+ for (; d && path.basename(d) !== 'node_modules' && path.dirname(d) !== d; d = path.dirname(d))
132
+ if (named(d, n)) return d;
133
+ return null;
134
+ };
135
+ const add = (d, n) => {
136
+ d = d && own(d, n);
137
+ if (!d || seen.has(d)) return;
138
+ seen.add(d);
139
+ if (!under(d)) found.push(d);
140
+ walk(d);
141
+ };
142
+ const find = (n, dir) => {
143
+ // (findPackageJSON where Node has it: exports that hide a package's entry from require don't hide this)
73
144
  const at = path.join(dir, 'package.json');
74
- try { if (nodeModule.findPackageJSON) { const f = nodeModule.findPackageJSON(n, pathToFileURL(at)); if (f) return real(path.dirname(f)); } } catch { /* by its entry, below */ }
145
+ try {
146
+ if (nodeModule.findPackageJSON) {
147
+ const f = nodeModule.findPackageJSON(n, pathToFileURL(at));
148
+ if (f) return real(path.dirname(f));
149
+ }
150
+ } catch {
151
+ /* by its entry, below */
152
+ }
75
153
  return real(pkgDir(n, at) || '');
76
154
  };
77
155
  function walk(dir) {
78
- let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')); } catch { return; }
79
- for (const n of Object.keys({ ...j.dependencies, ...j.optionalDependencies, ...j.peerDependencies })) if (PACKAGE_NAME.test(n)) add(find(n, dir), n);
156
+ let j;
157
+ try {
158
+ j = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
159
+ } catch {
160
+ return;
161
+ }
162
+ for (const n of Object.keys({ ...j.dependencies, ...j.optionalDependencies, ...j.peerDependencies }))
163
+ if (PACKAGE_NAME.test(n)) add(find(n, dir), n);
80
164
  }
81
165
  add(real(pkgDir('@rulecad/pcb', from) || ''), '@rulecad/pcb');
82
166
  return found;
@@ -87,7 +171,14 @@ function engineFolders(out, real, pkgDir, from) {
87
171
  // are reached through a node_modules link spelled through it, which the sandbox follows by its real path and may not.
88
172
  function refused(e) {
89
173
  if (e.code !== 'design.sandbox' || !e.resource) return e.message;
90
- const res = e.resource, to = (() => { try { return fs.lstatSync(res).isSymbolicLink() ? fs.realpathSync(res) : null; } catch { return null; } })();
174
+ const res = e.resource,
175
+ to = (() => {
176
+ try {
177
+ return fs.lstatSync(res).isSymbolicLink() ? fs.realpathSync(res) : null;
178
+ } catch {
179
+ return null;
180
+ }
181
+ })();
91
182
  const trust = 'or trust the workspace ("sandbox": false in cad.config.json, then cad trust)';
92
183
  return to
93
184
  ? `the design's sandbox was refused ${res}, a link to ${to}: something the design loads is reached through it (a node_modules link spelled through ${res}, most likely). Make that link with its real path (ln -s "$(pwd -P)/node_modules"), ${trust}`
@@ -98,27 +189,142 @@ function refused(e) {
98
189
  // stdout the reply is read from, and end the process before the runner prints the real one. So every field is checked
99
190
  // before it is used (checkReply), and the only thing written from it is a stage of the cache: under a key of the form
100
191
  // the stage cache makes (@rulecad/flexures cache.mjs: `${name}-${sha256 hex}`, a name such as "physics" or "flood
101
- // probe"), as a file directly in the stages folder (stageFile). A reply that is not one the runner makes is refused
192
+ // probe"), as a file directly in the design's own stages folder (stageFile), which only that design reads: a key is a
193
+ // hash anyone can work out, so a stage handed back under another design's key must never be read by that design. A
194
+ // reply that is not one the runner makes, or that hands back more stages than a build makes (STAGES_MOST), is refused
102
195
  // whole, with nothing written.
103
196
 
197
+ // A cache folder the sandbox reads (the stages, the routes): one of the workspace's only where it really is inside it.
198
+ // A cloned workspace's .cache/ that is a link to a folder elsewhere is not read from (null: every stage a miss), and the
199
+ // runner reads a file of the folder only where it really is in it (sandbox-run.mjs fromFolder).
200
+ const ownFolder = (dir) => {
201
+ try {
202
+ return ownFile(dir);
203
+ } catch (e) {
204
+ if (e.code === 'workspace.outside') return null;
205
+ throw e;
206
+ }
207
+ };
208
+
209
+ const isLink = (f) => {
210
+ try {
211
+ return fs.lstatSync(f).isSymbolicLink();
212
+ } catch {
213
+ return false;
214
+ }
215
+ };
216
+ // Whether a folder, or one inside it, holds a link
217
+ const holdsLink = (dir) => {
218
+ try {
219
+ return fs
220
+ .readdirSync(dir, { withFileTypes: true })
221
+ .some((e) => e.isSymbolicLink() || (e.isDirectory() && holdsLink(path.join(dir, e.name))));
222
+ } catch {
223
+ return false;
224
+ }
225
+ };
226
+ // The first link in a folder (its node_modules included) that leads anywhere but inside the folder itself or a folder
227
+ // the sandbox reads anyway (reads): { link, to }, or null. Each folder is looked through once, by its real path.
228
+ function linkOut(dir, reads) {
229
+ const inside = (f, d) => {
230
+ const rel = path.relative(d, f);
231
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
232
+ };
233
+ const top = fs.realpathSync(dir),
234
+ allowed = [top, ...reads.filter((r) => r !== dir)],
235
+ seen = new Set();
236
+ const look = (d) => {
237
+ let real;
238
+ try {
239
+ real = fs.realpathSync(d);
240
+ } catch {
241
+ return null;
242
+ }
243
+ if (seen.has(real)) return null;
244
+ seen.add(real);
245
+ let entries;
246
+ try {
247
+ entries = fs.readdirSync(d, { withFileTypes: true });
248
+ } catch {
249
+ return null;
250
+ }
251
+ for (const e of entries) {
252
+ const p = path.join(d, e.name);
253
+ if (e.isSymbolicLink()) {
254
+ let to;
255
+ try {
256
+ to = fs.realpathSync(p);
257
+ } catch {
258
+ continue; // (a link to nothing: reading it finds nothing)
259
+ }
260
+ if (!allowed.some((a) => inside(to, a))) return { link: p, to };
261
+ if (inside(to, top) && fs.statSync(p).isDirectory()) {
262
+ const found = look(p);
263
+ if (found) return found;
264
+ }
265
+ } else if (e.isDirectory()) {
266
+ const found = look(p);
267
+ if (found) return found;
268
+ }
269
+ }
270
+ return null;
271
+ };
272
+ return look(dir);
273
+ }
274
+
275
+ // The files a reply says the design imported, each by its path inside the project ('objects/box.js', with forward
276
+ // slashes): only files of the project are kept (the reply is untrusted, and the tool reads and hashes what is listed)
277
+ function inProject(urls, project) {
278
+ const top = fileURLToPath(project),
279
+ out = new Set();
280
+ for (const u of urls) {
281
+ let f;
282
+ try {
283
+ f = fileURLToPath(u);
284
+ } catch {
285
+ continue;
286
+ }
287
+ const rel = path.relative(top, f);
288
+ if (rel && !path.isAbsolute(rel) && !rel.split(path.sep).includes('..')) out.add(rel.split(path.sep).join('/'));
289
+ }
290
+ return [...out].sort();
291
+ }
292
+
104
293
  /** The form of a stage's key, as the stage cache makes it: a stage's name, a dash and the 64 hex digits of a SHA-256. */
105
294
  export const STAGE_KEY = /^[a-z][a-z0-9 _-]{0,39}-[0-9a-f]{64}$/;
106
295
 
296
+ // How many stages one reply may hand back, and how much text in all (kept.mjs, which the runner keeps to): a reply past
297
+ // either is refused whole, since it would fill the disk, or push the design's honest stages out of its folder of the
298
+ // cache. Routes likewise.
299
+ export { STAGES_MOST, ROUTES_MOST };
300
+ // What is wrong with a reply's stages or routes past its cap, or null
301
+ const overCap = (o, most, what) => {
302
+ const all = Object.values(o),
303
+ bytes = all.reduce((n, text) => n + Buffer.byteLength(text, 'utf8'), 0);
304
+ if (all.length > most.count) return `it hands back ${all.length} ${what}, more than the ${most.count} a build makes`;
305
+ if (bytes > most.bytes) return `it hands back ${bytes} bytes of ${what}, more than the ${most.bytes} a build makes`;
306
+ return null;
307
+ };
308
+
107
309
  /**
108
310
  * The file a stage of the cache is kept in, or null when its key would put it anywhere but directly in `dir`.
109
311
  * @param {string} dir the stages folder @param {unknown} key @returns {string | null}
110
312
  */
111
313
  export function stageFile(dir, key) {
112
314
  if (typeof key !== 'string' || !key) return null;
113
- const file = path.resolve(dir, `${key}.json`), rel = path.relative(path.resolve(dir), file);
315
+ const file = path.resolve(dir, `${key}.json`),
316
+ rel = path.relative(path.resolve(dir), file);
114
317
  return rel && !path.isAbsolute(rel) && !rel.split(/[\\/]/).includes('..') && path.basename(rel) === rel ? file : null;
115
318
  }
116
319
 
117
- const plain = (x) => x !== null && typeof x === 'object' && !Array.isArray(x) && Object.getPrototypeOf(x) === Object.prototype;
320
+ const plain = (x) =>
321
+ x !== null && typeof x === 'object' && !Array.isArray(x) && Object.getPrototypeOf(x) === Object.prototype;
118
322
  const point = (p) => Array.isArray(p) && p.length === 3 && p.every((n) => typeof n === 'number' && Number.isFinite(n));
119
323
  const faceList = (x) => Array.isArray(x) && x.every((f) => Array.isArray(f) && f.every(point));
120
- const PART = { name: 'string', role: 'string', label: 'string', filament: 'string', mirror: 'boolean' }, PART_FACES = ['solid', 'polygons', 'triangles'];
121
- const REPLY = ['parts', 'read', 'mechanism', 'fixings', 'stages', 'board', 'mounted', 'routes'], ERROR = { message: 'string', code: 'string', line: 'number', syntax: 'boolean', resource: 'string' };
324
+ const PART = { name: 'string', role: 'string', label: 'string', filament: 'string', mirror: 'boolean' },
325
+ PART_FACES = ['solid', 'polygons', 'triangles'];
326
+ const REPLY = ['parts', 'read', 'imports', 'mechanism', 'fixings', 'seats', 'stages', 'board', 'mounted', 'routes'],
327
+ ERROR = { message: 'string', code: 'string', line: 'number', syntax: 'boolean', resource: 'string' };
122
328
  const fields = (o, kinds) => Object.entries(o).find(([k, x]) => !(k in kinds) || typeof x !== kinds[k]);
123
329
 
124
330
  /** The form of a route's key, as @rulecad/pcb's route cache makes it: the 64 hex digits of a SHA-256. */
@@ -138,50 +344,80 @@ function checkBoard(b) {
138
344
  if (!plain(b)) return 'its board is not an object';
139
345
  const extra = Object.keys(b).find((k) => !['circuit', 'matrix', 'source'].includes(k));
140
346
  if (extra) return `its board has a field "${extra}" the runner doesn't send`;
141
- if (!Array.isArray(b.circuit) || !b.circuit.length || !b.circuit.every((e) => plain(e) && typeof e.type === 'string')) return 'its board\'s circuit is not a list of circuit elements';
142
- if (b.matrix != null && !(plain(b.matrix) || Array.isArray(b.matrix))) return 'its board\'s matrix is not an object';
143
- if (b.source != null && !plain(b.source)) return 'its board\'s source is not an object';
347
+ if (!Array.isArray(b.circuit) || !b.circuit.length || !b.circuit.every((e) => plain(e) && typeof e.type === 'string'))
348
+ return "its board's circuit is not a list of circuit elements";
349
+ if (b.matrix != null && !(plain(b.matrix) || Array.isArray(b.matrix))) return "its board's matrix is not an object";
350
+ if (b.source != null && !plain(b.source)) return "its board's source is not an object";
144
351
  if (polluting(b)) return 'its board has a field named __proto__';
145
352
  return null;
146
353
  }
147
354
 
148
355
  /**
149
356
  * What is wrong with a reply from the sandbox's runner, in a few words, or null when it is one the runner makes:
150
- * `{ parts, read, mechanism?, fixings?, stages? }`, a board design's `{ parts: [], read, board: { circuit, matrix?,
151
- * source? }, mounted?, fixings?, routes? }`, or `{ error }`.
152
- * @param {unknown} r the child's stdout, parsed @returns {string | null}
357
+ * `{ parts, read, imports?, mechanism?, fixings?, stages? }`, a board design's `{ parts: [], read, imports?, board: {
358
+ * circuit, matrix?, source? }, mounted?, fixings?, routes? }`, or `{ error }`. Its stages no more than `stagesMost` (STAGES_MOST), its
359
+ * routes no more than ROUTES_MOST.
360
+ * @param {unknown} r the child's stdout, parsed
361
+ * @param {{ count: number, bytes: number }} [stagesMost] @returns {string | null}
153
362
  */
154
- export function checkReply(r) {
363
+ export function checkReply(r, stagesMost = STAGES_MOST) {
155
364
  if (!plain(r)) return 'it is not an object';
156
365
  if ('error' in r) {
157
366
  if (Object.keys(r).length !== 1 || !plain(r.error)) return 'its error is not one the runner makes';
158
367
  const bad = fields(r.error, ERROR);
159
- return bad ? `its error's ${bad[0]} is not one the runner makes` : typeof r.error.message !== 'string' ? 'its error has no message' : null;
368
+ return bad
369
+ ? `its error's ${bad[0]} is not one the runner makes`
370
+ : typeof r.error.message !== 'string'
371
+ ? 'its error has no message'
372
+ : null;
160
373
  }
161
374
  const extra = Object.keys(r).find((k) => !REPLY.includes(k));
162
375
  if (extra) return `it has a field "${extra}" the runner doesn't send`;
163
376
  if (!Array.isArray(r.parts)) return 'it has no list of parts';
164
377
  for (const p of r.parts) {
165
378
  if (!plain(p)) return 'a part is not an object';
166
- const bad = Object.entries(p).find(([k, x]) => !(PART_FACES.includes(k) ? faceList(x) : k in PART && typeof x === PART[k]));
379
+ const bad = Object.entries(p).find(
380
+ ([k, x]) => !(PART_FACES.includes(k) ? faceList(x) : k in PART && typeof x === PART[k]),
381
+ );
167
382
  if (bad) return `a part's ${bad[0]} is not one the runner makes`;
168
383
  if (typeof p.name !== 'string' || PART_FACES.some((k) => !(k in p))) return 'a part has no name or no faces';
169
384
  }
170
- if (!Array.isArray(r.read) || !r.read.every((n) => typeof n === 'string')) return 'what it read is not a list of names';
385
+ if (!Array.isArray(r.read) || !r.read.every((n) => typeof n === 'string'))
386
+ return 'what it read is not a list of names';
387
+ if (r.imports != null && !(Array.isArray(r.imports) && r.imports.every((u) => typeof u === 'string')))
388
+ return 'what it imported is not a list of files';
171
389
  if (r.mechanism != null && !plain(r.mechanism)) return 'its mechanism is not an object';
172
- if (r.fixings != null && !(Array.isArray(r.fixings) && r.fixings.every(plain))) return 'its fixings are not a list of findings';
390
+ if (r.fixings != null && !(Array.isArray(r.fixings) && r.fixings.every(plain)))
391
+ return 'its fixings are not a list of findings';
392
+ // (what v.shapes' seat helpers drew, lib/designshapes.mjs: never more than an info finding of its one code)
393
+ if (
394
+ r.seats != null &&
395
+ !(
396
+ Array.isArray(r.seats) &&
397
+ r.seats.every((x) => plain(x) && x.level === 'info' && x.code === 'seat.drawn' && typeof x.text === 'string')
398
+ )
399
+ )
400
+ return 'its seats are not a list of seat.drawn findings';
173
401
  if (r.stages != null) {
174
402
  if (!plain(r.stages)) return 'its stages are not an object';
175
403
  const bad = Object.entries(r.stages).find(([k, text]) => !STAGE_KEY.test(k) || typeof text !== 'string');
176
- if (bad) return STAGE_KEY.test(bad[0]) ? 'a stage is not text' : 'a stage\'s key is not one the stage cache makes';
404
+ if (bad) return STAGE_KEY.test(bad[0]) ? 'a stage is not text' : "a stage's key is not one the stage cache makes";
405
+ const over = overCap(r.stages, stagesMost, 'slow stages');
406
+ if (over) return over;
407
+ }
408
+ if (r.board != null) {
409
+ const bad = checkBoard(r.board);
410
+ if (bad) return bad;
411
+ if (r.parts.length) return "a board's reply has parts of its own";
177
412
  }
178
- if (r.board != null) { const bad = checkBoard(r.board); if (bad) return bad; if (r.parts.length) return 'a board\'s reply has parts of its own'; }
179
413
  if (r.mounted != null && typeof r.mounted !== 'boolean') return 'its "mounted" is not true or false';
180
414
  if (r.routes != null) {
181
415
  if (r.board == null) return 'it has routes but no board';
182
416
  if (!plain(r.routes)) return 'its routes are not an object';
183
417
  const bad = Object.entries(r.routes).find(([k, text]) => !ROUTE_KEY.test(k) || typeof text !== 'string');
184
- if (bad) return ROUTE_KEY.test(bad[0]) ? 'a route is not text' : 'a route\'s key is not one the route cache makes';
418
+ if (bad) return ROUTE_KEY.test(bad[0]) ? 'a route is not text' : "a route's key is not one the route cache makes";
419
+ const over = overCap(r.routes, ROUTES_MOST, 'routes');
420
+ if (over) return over;
185
421
  }
186
422
  if (r.mechanism != null && polluting(r.mechanism)) return 'its mechanism has a field named __proto__';
187
423
  return null;
@@ -190,6 +426,160 @@ export function checkReply(r) {
190
426
  /** Whether designs can be sandboxed here at all: Node has the permission model. */
191
427
  export const canSandbox = () => !!flag;
192
428
 
429
+ /**
430
+ * What cad says before the first design it runs in the sandbox, where Node's permission model doesn't cover the
431
+ * network (before Node 25: no --allow-net to withhold) and only the runner's own locks keep a design off it
432
+ * (sandbox-lock.mjs), or null where Node's model does.
433
+ * @param {string} [version] Node's version, as process.version gives it @returns {string | null}
434
+ */
435
+ export function networkWarning(version = process.version) {
436
+ const major = Number(/^v?(\d+)/.exec(version)?.[1]);
437
+ return major < 25
438
+ ? `designs are kept off the network on Node ${major} by rulecad alone, not by Node itself: use Node 25 or above for designs you did not write`
439
+ : null;
440
+ }
441
+ let warned = false; // (said once a run)
442
+
443
+ // How long a design may run and how much memory it may use, in the sandbox. A design with an endless loop would
444
+ // otherwise hang every command that builds it, with no word said, and one that fills memory without end would grow
445
+ // until the system stopped it, taking other work with it. Past either limit the design's process is stopped, and the
446
+ // build fails with design.time or design.memory, naming the design. The time limit was set from the kit's slowest
447
+ // example built from nothing: the launcher's in-line action (examples/projects/launcher, its physics and flooded
448
+ // frame) took 2210 s, 1766 s of it working, on an 8 GB laptop shared with other work (November 2026), so an hour
449
+ // leaves room; the memory limit is the most the design's JavaScript may hold, and its process as a whole may hold
450
+ // MEMORY_ROOM more (Node itself, and what lies outside the JavaScript: typed arrays, WebAssembly memory, output not
451
+ // yet sent), watched from here. What the design sends back or prints is kept here only up to a bound, so it can't
452
+ // fill this process instead. A workspace's cad.config.json that raises a limit above the default is used once the
453
+ // workspace is trusted (cad trust), as "sandbox": false is: until then the default holds. A trusted workspace
454
+ // ("sandbox": false) runs its designs in the tool's own process, without either limit.
455
+ export { DESIGN_TIMEOUT, DESIGN_MEMORY };
456
+ /** How much more than the design's memory limit its process as a whole may hold, in megabytes. */
457
+ export const MEMORY_ROOM = 512;
458
+
459
+ /**
460
+ * The time and memory limits a design runs under in the sandbox: CAD_DESIGN_TIMEOUT (seconds) and CAD_DESIGN_MEMORY
461
+ * (megabytes) if set, else cad.config.json's "designTimeout" and "designMemory", else 3600 s and 4096 MB. A value that
462
+ * is not a number above nothing is refused, with what to write, rather than left to run without a limit. A value in
463
+ * cad.config.json above the default is used only once the workspace is trusted; until then the default is, and held
464
+ * says what the workspace asked for.
465
+ * @param {Record<string, string | undefined>} [env] @param {{ designTimeout?: unknown, designMemory?: unknown }} [cfg]
466
+ * @param {() => boolean} [ok] whether the workspace is trusted for what it asks
467
+ * @returns {{ timeout: number, memory: number, held?: { timeout?: number, memory?: number } }} timeout in seconds, memory in megabytes
468
+ */
469
+ export function designLimits(env = process.env, cfg = config, ok = () => trusted(cfg)) {
470
+ const held = {};
471
+ const one = (name, key, fallback, unit, least, which) => {
472
+ const fromEnv = env[name] != null && env[name] !== '';
473
+ const raw = fromEnv ? env[name] : cfg[key];
474
+ if (raw == null) return fallback;
475
+ const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() ? Number(raw) : NaN;
476
+ if (Number.isFinite(n) && n >= least) {
477
+ if (fromEnv || n <= fallback || ok()) return n;
478
+ held[which] = n; // (a cloned workspace can't take the limits away by itself: cad trust)
479
+ return fallback;
480
+ }
481
+ const where = fromEnv ? name : `"${key}" in cad.config.json`;
482
+ throw Object.assign(
483
+ new Error(
484
+ `${where} is ${JSON.stringify(raw)}: it should be a number of ${unit} (at least ${least}), as ${fallback}, the default`,
485
+ ),
486
+ { code: 'design.limit', ...(fromEnv ? {} : { file: 'cad.config.json', path: key }) },
487
+ );
488
+ };
489
+ const timeout = one('CAD_DESIGN_TIMEOUT', 'designTimeout', DESIGN_TIMEOUT, 'seconds', 0.1, 'timeout'),
490
+ memory = Math.round(one('CAD_DESIGN_MEMORY', 'designMemory', DESIGN_MEMORY, 'megabytes', 16, 'memory'));
491
+ return { timeout, memory, ...(Object.keys(held).length ? { held } : {}) };
492
+ }
493
+ // What a workspace's raised limit, held back until it is trusted, adds to the message of a design stopped at the limit
494
+ const heldBack = (n, unit) =>
495
+ n != null
496
+ ? ` (this workspace's cad.config.json asks for ${n} ${unit}: that is used once you trust it, with cad trust)`
497
+ : '';
498
+
499
+ /**
500
+ * The memory a process holds, in bytes (its resident set: what it has in the machine's memory), or null where that
501
+ * can't be told. Read from /proc on Linux, from ps on other Unix systems and from tasklist on Windows.
502
+ * @param {number} pid @returns {Promise<number | null>}
503
+ */
504
+ export function processMemory(pid) {
505
+ return new Promise((resolve) => {
506
+ if (process.platform === 'linux') {
507
+ try {
508
+ const m = /VmRSS:\s*(\d+)\s*kB/.exec(fs.readFileSync(`/proc/${pid}/status`, 'utf8'));
509
+ return resolve(m ? Number(m[1]) * 1024 : null);
510
+ } catch {
511
+ return resolve(null);
512
+ }
513
+ }
514
+ const [cmd, args, read] =
515
+ process.platform === 'win32'
516
+ ? [
517
+ 'tasklist',
518
+ ['/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'],
519
+ (t) => /"([\d.,\s\u00a0]+)\s*K"\s*$/m.exec(t)?.[1],
520
+ ]
521
+ : ['ps', ['-o', 'rss=', '-p', String(pid)], (t) => /^\s*(\d+)\s*$/.exec(t)?.[1]];
522
+ execFile(cmd, args, { windowsHide: true, timeout: 5000 }, (e, text) => {
523
+ const kb = e ? null : read(String(text));
524
+ resolve(kb ? Number(kb.replace(/\D/g, '')) * 1024 : null);
525
+ });
526
+ });
527
+ }
528
+ // How often the design's process's memory is looked at, in milliseconds
529
+ const WATCH_EVERY = 250;
530
+ // On a Mac, memory the system has squeezed (compressed) or set aside on disk leaves the resident set, so a process can
531
+ // hold far more than ps says once the machine is short of memory: footprint (the Mac's own tool) counts it, once a
532
+ // second as it runs
533
+ const FOOTPRINT = '/usr/bin/footprint';
534
+ /**
535
+ * Look at a process's memory until told to stop, and call over() once it holds more than most bytes.
536
+ * @param {number} pid @param {number} most @param {() => void} over @returns {() => void} stops looking
537
+ */
538
+ function watchMemory(pid, most, over) {
539
+ let looking = false,
540
+ ended = false;
541
+ const past = (held) => {
542
+ if (!ended && held != null && held > most) {
543
+ ended = true;
544
+ over();
545
+ }
546
+ };
547
+ const every = setInterval(() => {
548
+ if (looking || ended) return;
549
+ looking = true;
550
+ processMemory(pid).then((held) => {
551
+ looking = false;
552
+ past(held);
553
+ });
554
+ }, WATCH_EVERY);
555
+ every.unref();
556
+ let deep = null;
557
+ if (process.platform === 'darwin' && fs.existsSync(FOOTPRINT)) {
558
+ deep = spawn(FOOTPRINT, ['--sample', '1', '--noCategories', '-f', 'bytes', '-p', String(pid)], {
559
+ stdio: ['ignore', 'pipe', 'ignore'],
560
+ });
561
+ deep.on('error', () => {}); // (without it, ps alone)
562
+ let text = '';
563
+ deep.stdout.on('data', (b) => {
564
+ text += b;
565
+ const lines = text.split('\n');
566
+ text = lines.pop();
567
+ for (const l of lines) past(Number(/^\s*phys_footprint:\s*(\d+)\s*B/.exec(l)?.[1] ?? NaN) || null);
568
+ });
569
+ deep.unref();
570
+ deep.stdout.unref?.();
571
+ }
572
+ return () => {
573
+ ended = true;
574
+ clearInterval(every);
575
+ if (deep && deep.exitCode == null) deep.kill();
576
+ };
577
+ }
578
+ // The most of what the design prints that is kept, to pass on after it (its last lines: a crash's own words are there)
579
+ const PRINT_KEPT = 1 << 20;
580
+ // What Node prints as it stops a process whose JavaScript ran out of the memory it may hold (V8's own words)
581
+ const HEAP_DEATH = /JavaScript heap out of memory|Reached heap limit|Ineffective mark-compacts near heap limit/;
582
+
193
583
  /**
194
584
  * Run a design's main(values) in the sandbox: { parts, read, mechanism, fixings } as the build makes them, and for a
195
585
  * board design (board set) its { board: { circuit, matrix?, source? }, mounted } too, parts empty: the tool makes the
@@ -201,41 +591,243 @@ export const canSandbox = () => !!flag;
201
591
  * @param {object} request.values @param {object} request.meta the .json's parts
202
592
  * @param {'jscad' | 'manifold'} [request.engine] v.ops's booleans
203
593
  * @param {string[]} [request.optional] names main may read that aren't among the values (the display's own inputs)
204
- * @param {{ salt: string, get: (k: string) => string | undefined, put: (k: string, text: string) => void } | null} [request.stages] where a lamina's slow stages are kept: the child reads them from the cache (it may read the workspace) and hands back what it made, which is written here
594
+ * @param {{ dir: string, salt: string, get: (k: string) => string | undefined, put: (k: string, text: string) => void } | null} [request.stages] where a lamina's slow stages are kept: the child reads them from this design's own folder of the cache, dir (it may read the workspace), and hands back what it made, which is written there
205
595
  * @param {{ frames?: object, fixings?: { sets?: object, printer?: object, material?: string | null } | null }} [request.bound] what the design's helpers are bound to: frames, the workspace's profile sets (lib/frames.mjs framesContext); fixings, what v.fixings is bound to (design.mjs fixingsContext), whose calls come back as fixings. A board's v.pcb.mount reads fixings.sets too
206
- * @param {{ routes?: { dir: string, put: (k: string, text: string) => void } | null } | null} [request.board] set for a board design (engine pcb): routes, where the autorouter's results are kept (the child reads the folder; what it routes is handed back and put here)
596
+ * @param {{ routes?: { dir: string, shared?: string | null, put: (k: string, text: string) => void } | null } | null} [request.board] set for a board design (engine pcb): routes, where the autorouter's results are kept (the child reads this design's own folder, dir, then the route cache the tool's own process writes, shared; what it routes is handed back and put in dir only)
207
597
  * @param {string[]} [request.read] more folders the sandbox may read (a copy of a workspace held in memory)
208
- * @returns {Promise<{ parts: object[], read: Set<string>, mechanism: object | null, fixings: object[] | null, board?: { circuit: object[], matrix?: object, source?: object }, mounted?: boolean }>}
598
+ * @returns {Promise<{ parts: object[], read: Set<string>, imports: string[], mechanism: object | null, fixings: object[] | null, board?: { circuit: object[], matrix?: object, source?: object }, mounted?: boolean }>}
599
+ * imports: the files of its project the design imported, each by its path inside the project ('objects/box.js')
209
600
  */
210
- export function runSandboxed({ d, values, meta, engine = 'jscad', optional = [], stages = null, bound = {}, board = null, read: more = [] }) {
601
+ export function runSandboxed({
602
+ d,
603
+ values,
604
+ meta,
605
+ engine = 'jscad',
606
+ optional = [],
607
+ stages = null,
608
+ bound = {},
609
+ board = null,
610
+ read: more = [],
611
+ }) {
211
612
  const here = path.dirname(fileURLToPath(import.meta.url));
212
- const routes = board?.routes?.dir ? [path.resolve(board.routes.dir)] : []; // (a route cache the user put outside the workspace, RULECAD_ROUTE_CACHE: read there, or every build routes again)
213
- const args = [flag, ...readable({ board: !!board, extra: [...more, ...routes] }).map((p) => `--allow-fs-read=${p}`), ...(inThread ? [] : ['--allow-worker']), '--import', pathToFileURL(path.join(here, 'sandbox-preload.mjs')).href, path.join(here, 'sandbox-run.mjs')];
613
+ const routes = board?.routes?.shared ? [path.resolve(board.routes.shared)] : []; // (a route cache the user put outside the workspace, RULECAD_ROUTE_CACHE: read there, or every build routes again)
614
+ let limits;
615
+ try {
616
+ limits = designLimits();
617
+ } catch (e) {
618
+ return Promise.reject(located(e, d.js, 'design.limit'));
619
+ }
620
+ if (!warned) {
621
+ warned = true;
622
+ const w = networkWarning();
623
+ if (w) process.stderr.write(`Note: ${w}\n`);
624
+ }
214
625
  // (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
215
- const js = fs.realpathSync(d.js), project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href, stagesDir = paths.cache('stages');
626
+ const js = fs.realpathSync(d.js),
627
+ project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href;
628
+ // Of the workspace, the sandbox reads only the design's project, the package.json that says its files are ES
629
+ // modules, and the design's own folders of the caches: not the workspace's other projects
630
+ // Node's permission model follows a link wherever it leads, and a design can get Node's fs by way of a package's
631
+ // code (sandbox-lock.mjs): so a cache folder holding a link is not read at all (every stage a miss), the workspace's
632
+ // package.json only where it is no link, and a link anywhere in the project (its node_modules too) must lead to a
633
+ // folder the sandbox reads anyway, never to another project or out of the workspace (linksIn)
634
+ const projectDir = path.dirname(path.dirname(js));
635
+ const own = [
636
+ projectDir,
637
+ ...[path.join(WS, 'package.json')].filter((f) => !isLink(f)),
638
+ ...[stages?.dir, board?.routes?.dir]
639
+ .filter(Boolean)
640
+ .map((dir) => ownFolder(path.resolve(dir)))
641
+ .filter((dir) => dir && !holdsLink(dir)),
642
+ ].filter(Boolean);
643
+ const reads = readable({ board: !!board, extra: [...more, ...routes], own });
644
+ const leads = linkOut(projectDir, reads);
645
+ if (leads)
646
+ return Promise.reject(
647
+ Object.assign(
648
+ new Error(
649
+ `${leads.link} is a link to ${leads.to}, which a design of this project may not read, so the design isn't run: in the sandbox a design reads only its own project and the kit's packages, and a link would hand it a file of another project or of yours elsewhere. Copy the file into the project, or take the link out`,
650
+ ),
651
+ { code: 'workspace.outside', file: leads.link },
652
+ ),
653
+ );
654
+ const args = [
655
+ flag,
656
+ `--max-old-space-size=${limits.memory}`,
657
+ ...reads.map((p) => `--allow-fs-read=${p}`),
658
+ ...(inThread ? [] : ['--allow-worker']),
659
+ '--import',
660
+ pathToFileURL(path.join(here, 'sandbox-preload.mjs')).href,
661
+ path.join(here, 'sandbox-run.mjs'),
662
+ ];
216
663
  // The child gets none of this process's environment but what Node needs to start: tokens and keys stay out of it
217
- const env = Object.fromEntries(['PATH', 'SystemRoot', 'windir', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'PHYS_DEBUG', 'LAMINA_TIMES'].filter((k) => process.env[k] != null).map((k) => [k, process.env[k]]));
664
+ const env = Object.fromEntries(
665
+ ['PATH', 'SystemRoot', 'windir', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'PHYS_DEBUG', 'LAMINA_TIMES']
666
+ .filter((k) => process.env[k] != null)
667
+ .map((k) => [k, process.env[k]]),
668
+ );
218
669
  return new Promise((resolve, reject) => {
219
- const child = spawn(process.execPath, args, { stdio: ['pipe', 'pipe', 'pipe'], env: { ...env, CAD_SANDBOX_PROJECT: project, NODE_NO_WARNINGS: '1' } }); // (its stderr is passed on: what the design prints, not Node's notes on its own flags)
220
- const out = [], err = [];
221
- child.stdout.on('data', (b) => out.push(b));
222
- child.stderr.on('data', (b) => err.push(b));
223
- child.on('error', reject);
670
+ const child = spawn(process.execPath, args, {
671
+ stdio: ['pipe', 'pipe', 'pipe'],
672
+ env: { ...env, CAD_SANDBOX_PROJECT: project, NODE_NO_WARNINGS: '1' },
673
+ }); // (its stderr is passed on: what the design prints, not Node's notes on its own flags)
674
+ const MB = 1024 * 1024,
675
+ memoryMessage = (what) =>
676
+ `the design ${what}, so it was stopped: it may make shapes or lists without end. If it needs more, raise the limit: "designMemory" (megabytes) in cad.config.json, or CAD_DESIGN_MEMORY${heldBack(limits.held?.memory, 'MB')}`;
677
+ // What it sends back is kept up to what its JavaScript could hold (a reply is made there), and never past the
678
+ // longest text this process can read; what it prints, only its last PRINT_KEPT bytes
679
+ const replyMost = Math.min(limits.memory * MB, bufferConstants.MAX_STRING_LENGTH);
680
+ const out = [],
681
+ err = [];
682
+ let sent = 0,
683
+ kept = 0,
684
+ dropped = 0,
685
+ over = null; // (why the process was stopped: 'time', 'memory', 'reply')
686
+ const stop = (why) => {
687
+ if (over) return;
688
+ over = why;
689
+ child.kill('SIGKILL');
690
+ };
691
+ child.stdout.on('data', (b) => {
692
+ if (over) return;
693
+ sent += b.length;
694
+ if (sent > replyMost) return stop('reply');
695
+ out.push(b);
696
+ });
697
+ child.stderr.on('data', (b) => {
698
+ err.push(b);
699
+ kept += b.length;
700
+ while (kept - err[0].length >= PRINT_KEPT) {
701
+ kept -= err[0].length;
702
+ dropped += err.shift().length;
703
+ }
704
+ });
705
+ // The time limit: past it the process is stopped outright (a design can't catch SIGKILL, nor delay it with a loop)
706
+ // (a timer holds at most about 24 days: a longer limit would fire at once, so it waits that long instead)
707
+ const timer = setTimeout(() => stop('time'), Math.min(limits.timeout * 1000, 2 ** 31 - 1));
708
+ // The memory of the process as a whole, looked at from here (the design can't stop that)
709
+ const unwatch = watchMemory(child.pid, (limits.memory + MEMORY_ROOM) * MB, () => stop('memory'));
710
+ const done = () => {
711
+ clearTimeout(timer);
712
+ unwatch();
713
+ };
714
+ // Why the process was stopped from here, said as an error naming the design and the limit
715
+ const stopped = (why) =>
716
+ why === 'time'
717
+ ? located(
718
+ new Error(
719
+ `the design ran for longer than ${limits.timeout} s, so it was stopped: it may loop for ever. If it is only slow, raise the limit: "designTimeout" (seconds) in cad.config.json, or CAD_DESIGN_TIMEOUT${heldBack(limits.held?.timeout, 's')}`,
720
+ ),
721
+ d.js,
722
+ 'design.time',
723
+ )
724
+ : located(
725
+ new Error(
726
+ memoryMessage(
727
+ why === 'memory'
728
+ ? `held more than ${limits.memory + MEMORY_ROOM} MB in all (${limits.memory} MB for its JavaScript, and ${MEMORY_ROOM} MB more for the rest: typed arrays, WebAssembly memory, output)`
729
+ : `sent back more than ${Math.floor(replyMost / MB)} MB, more than a reply it could make`,
730
+ ),
731
+ ),
732
+ d.js,
733
+ 'design.memory',
734
+ );
735
+ child.on('error', (e) => {
736
+ done();
737
+ reject(e);
738
+ });
224
739
  child.on('close', () => {
740
+ done();
741
+ if (over) return reject(stopped(over));
225
742
  let r;
226
- try { r = JSON.parse(Buffer.concat(out).toString('utf8')); } catch {
227
- return reject(located(new Error(`the design's sandbox stopped: ${Buffer.concat(err).toString('utf8').trim().split('\n').slice(-3).join(' ') || 'no output'}`), d.js, 'design.sandbox'));
743
+ try {
744
+ r = JSON.parse(Buffer.concat(out).toString('utf8'));
745
+ } catch {
746
+ // No reply: the process stopped before it gave one. Node's own words say whether it ran out of memory
747
+ const said = Buffer.concat(err).toString('utf8');
748
+ if (HEAP_DEATH.test(said))
749
+ return reject(
750
+ located(
751
+ new Error(memoryMessage(`used more than the ${limits.memory} MB of memory it may`)),
752
+ d.js,
753
+ 'design.memory',
754
+ ),
755
+ );
756
+ return reject(
757
+ located(
758
+ new Error(`the design's sandbox stopped: ${said.trim().split('\n').slice(-3).join(' ') || 'no output'}`),
759
+ d.js,
760
+ 'design.sandbox',
761
+ ),
762
+ );
228
763
  }
764
+ if (dropped) process.stderr.write(`(the design printed ${dropped} bytes more before this, not kept)\n`);
229
765
  if (err.length) process.stderr.write(Buffer.concat(err)); // what the design printed
230
- const wrong = checkReply(r) || (!board && r.board != null ? 'it has a board, and the design is not one' : board && r.board == null && !r.error ? 'a board design\'s reply has no board' : null); // (every field is untrusted: see checkReply)
231
- if (wrong) return reject(located(new Error(`the design's reply was not one rulecad makes (${wrong}), so none of it was used and nothing it sent was written. A design gives back its shapes from main(v); one that writes to the process's output itself or ends the process is refused`), d.js, 'design.sandbox'));
232
- if (r.error) return reject(located(Object.assign(new Error(refused(r.error)), { code: r.error.code, ...(r.error.line ? { line: r.error.line } : {}), ...(r.error.syntax ? { name: 'SyntaxError' } : {}) }), d.js, r.error.code || 'design.run'));
766
+ const wrong =
767
+ checkReply(r) ||
768
+ (!board && r.board != null
769
+ ? 'it has a board, and the design is not one'
770
+ : board && r.board == null && !r.error
771
+ ? "a board design's reply has no board"
772
+ : null); // (every field is untrusted: see checkReply)
773
+ if (wrong)
774
+ return reject(
775
+ located(
776
+ new Error(
777
+ `the design's reply was not one rulecad makes (${wrong}), so none of it was used and nothing it sent was written. A design gives back its shapes from main(v); one that writes to the process's output itself or ends the process is refused`,
778
+ ),
779
+ d.js,
780
+ 'design.sandbox',
781
+ ),
782
+ );
783
+ if (r.error)
784
+ return reject(
785
+ located(
786
+ Object.assign(new Error(refused(r.error)), {
787
+ code: r.error.code,
788
+ ...(r.error.line ? { line: r.error.line } : {}),
789
+ ...(r.error.syntax ? { name: 'SyntaxError' } : {}),
790
+ }),
791
+ d.js,
792
+ r.error.code || 'design.run',
793
+ ),
794
+ );
233
795
  if (stages) for (const [k, text] of Object.entries(r.stages || {})) stages.put(k, text);
234
796
  if (board?.routes) for (const [k, text] of Object.entries(r.routes || {})) board.routes.put(k, text);
235
- resolve({ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })), read: new Set(r.read), mechanism: r.mechanism || null, fixings: r.fixings || null,
236
- ...(board ? { board: r.board, mounted: r.mounted === true } : {}) });
797
+ resolve({
798
+ parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })),
799
+ read: new Set(r.read),
800
+ imports: inProject(r.imports || [], project),
801
+ mechanism: r.mechanism || null,
802
+ fixings: r.fixings || null,
803
+ seats: r.seats || null,
804
+ ...(board ? { board: r.board, mounted: r.mounted === true } : {}),
805
+ });
237
806
  });
238
- child.stdin.end(JSON.stringify({ js: `${pathToFileURL(js).href}?t=${fs.statSync(js).mtimeMs}`, values, meta, engine, optional, ...(stages ? { stages: { dir: stagesDir, salt: stages.salt } } : {}), bound,
239
- ...(board ? { board: { ...(board.routes ? { routes: path.resolve(board.routes.dir) } : {}) } } : {}) }));
807
+ child.stdin.end(
808
+ JSON.stringify({
809
+ js: `${pathToFileURL(js).href}?t=${fs.statSync(js).mtimeMs}`,
810
+ values,
811
+ meta,
812
+ engine,
813
+ optional,
814
+ ...(stages ? { stages: { dir: ownFolder(path.resolve(stages.dir)), salt: stages.salt } } : {}),
815
+ bound,
816
+ ...(board
817
+ ? {
818
+ board: {
819
+ ...(board.routes
820
+ ? {
821
+ routes: [board.routes.dir, board.routes.shared]
822
+ .filter(Boolean)
823
+ .map((dir) => ownFolder(path.resolve(dir)))
824
+ .filter(Boolean),
825
+ }
826
+ : {}),
827
+ },
828
+ }
829
+ : {}),
830
+ }),
831
+ );
240
832
  });
241
833
  }