@rulecad/cad 0.9.0 → 0.11.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 (68) hide show
  1. package/AGENTS.md +29 -10
  2. package/CHANGELOG.md +604 -0
  3. package/EXAMPLES.md +122 -105
  4. package/README.md +292 -63
  5. package/bin/cad.mjs +500 -87
  6. package/lib/assembly.mjs +486 -134
  7. package/lib/bays.mjs +124 -0
  8. package/lib/cache-file.mjs +148 -0
  9. package/lib/clone.mjs +93 -11
  10. package/lib/code-text.mjs +28 -0
  11. package/lib/design-imports.mjs +127 -0
  12. package/lib/design.mjs +291 -59
  13. package/lib/designshapes.mjs +142 -0
  14. package/lib/edit.mjs +29 -5
  15. package/lib/estimates.mjs +51 -0
  16. package/lib/fasten.mjs +11 -5
  17. package/lib/fe-key.mjs +29 -0
  18. package/lib/fittings.mjs +20 -15
  19. package/lib/fixings.mjs +17 -4
  20. package/lib/framebuild.mjs +73 -92
  21. package/lib/framecheck.mjs +154 -77
  22. package/lib/framegen.mjs +9 -1
  23. package/lib/frames.mjs +6 -2
  24. package/lib/framesize.mjs +45 -82
  25. package/lib/gait.mjs +17 -7
  26. package/lib/guides.mjs +84 -50
  27. package/lib/host.mjs +7 -3
  28. package/lib/kit.mjs +5 -5
  29. package/lib/list.mjs +29 -21
  30. package/lib/live-guard.mjs +18 -8
  31. package/lib/loads.mjs +35 -23
  32. package/lib/measured.mjs +740 -99
  33. package/lib/mesh.mjs +156 -56
  34. package/lib/motors.mjs +26 -33
  35. package/lib/names.mjs +15 -0
  36. package/lib/node-version.mjs +52 -0
  37. package/lib/optimise.mjs +34 -25
  38. package/lib/order.mjs +5 -12
  39. package/lib/parts.mjs +3 -0
  40. package/lib/picture-servers.mjs +66 -0
  41. package/lib/power.mjs +14 -7
  42. package/lib/preview.mjs +12 -25
  43. package/lib/programs.mjs +113 -0
  44. package/lib/rules.mjs +2 -1
  45. package/lib/sandbox-guard.mjs +43 -0
  46. package/lib/sandbox-hooks.mjs +109 -15
  47. package/lib/sandbox-lock.mjs +225 -0
  48. package/lib/sandbox-preload.mjs +2 -2
  49. package/lib/sandbox-run.mjs +22 -24
  50. package/lib/sandbox.mjs +345 -42
  51. package/lib/sheet.mjs +114 -3
  52. package/lib/targets/gist.mjs +9 -6
  53. package/lib/versions.mjs +294 -35
  54. package/lib/workspace.mjs +6 -3
  55. package/package.json +14 -14
  56. package/schemas/assembly.schema.json +6 -5
  57. package/schemas/object.schema.json +1 -1
  58. package/schemas/project.schema.json +6 -0
  59. package/templates/coupons/MEASURE.md +109 -0
  60. package/templates/coupons/assemblies/fixings-test.json +20 -0
  61. package/templates/coupons/assemblies/slot-test.json +11 -0
  62. package/templates/coupons/objects/fixings-coupon.js +88 -0
  63. package/templates/coupons/objects/fixings-coupon.json +26 -0
  64. package/templates/coupons/objects/holds-coupon.js +130 -0
  65. package/templates/coupons/objects/holds-coupon.json +42 -0
  66. package/templates/coupons/objects/slot-coupon.js +89 -0
  67. package/templates/coupons/objects/slot-coupon.json +29 -0
  68. 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
@@ -25,6 +29,8 @@ import { WS, TOOL, config, trusted, DESIGN_TIMEOUT, DESIGN_MEMORY, ownFile } fro
25
29
  import { fromFaces } from './parts.mjs';
26
30
  import { located } from './errors.mjs';
27
31
  import { STAGES_MOST, ROUTES_MOST } from './kept.mjs';
32
+ import { ALLOWED } from './sandbox-hooks.mjs';
33
+ import { whereIs } from './programs.mjs';
28
34
 
29
35
  const flag = (() => {
30
36
  const f = process.allowedNodeEnvironmentFlags;
@@ -41,11 +47,12 @@ const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks
41
47
  // (a workspace's "sandbox": false counts only once the user has trusted it: cad trust)
42
48
  export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && !(config.sandbox === false && trusted());
43
49
 
44
- // What the sandbox may read: the workspace, and the packages designs and the runner load (wherever npm put them), and
50
+ // What the sandbox may read: of the workspace, what `own` names (the design's project, the workspace's package.json and
51
+ // the design's own cache folders: runSandboxed), and the packages designs and the runner load (wherever npm put them), and
45
52
  // what those load in turn (@rulecad/frames sizes a beam's operations through @rulecad/fixings). Node's permission
46
53
  // model follows a link inside these folders wherever it leads, so a link in the design's project or rules/ that leads
47
54
  // out of the workspace is refused before the sandbox starts (workspace.mjs noLinksOut, from design.mjs).
48
- function readable({ board = false, extra = [] } = {}) {
55
+ function readable({ board = false, extra = [], own = [WS] } = {}) {
49
56
  const real = (p) => {
50
57
  try {
51
58
  return fs.realpathSync(p);
@@ -74,17 +81,11 @@ function readable({ board = false, extra = [] } = {}) {
74
81
  }
75
82
  };
76
83
  const dirs = [
77
- WS,
84
+ ...own,
78
85
  TOOL,
79
86
  ...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
80
87
  ...[
81
- '@jscad/modeling',
82
- '@rulecad/shapes',
83
- '@rulecad/flexures',
84
- '@rulecad/gears',
85
- '@rulecad/motors',
86
- '@rulecad/frames',
87
- '@rulecad/fixings',
88
+ ...ALLOWED, // (what a design may import, and what the runner loads besides)
88
89
  '@rulecad/rules/x1c.json',
89
90
  '@rulecad/fea',
90
91
  '@rulecad/variables',
@@ -96,7 +97,7 @@ function readable({ board = false, extra = [] } = {}) {
96
97
  ...new Set(
97
98
  dirs
98
99
  .filter(Boolean)
99
- .flatMap((d) => [d, real(d)])
100
+ .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
101
  .filter(Boolean),
101
102
  ),
102
103
  ];
@@ -206,6 +207,90 @@ const ownFolder = (dir) => {
206
207
  }
207
208
  };
208
209
 
210
+ const isLink = (f) => {
211
+ try {
212
+ return fs.lstatSync(f).isSymbolicLink();
213
+ } catch {
214
+ return false;
215
+ }
216
+ };
217
+ // Whether a folder, or one inside it, holds a link
218
+ const holdsLink = (dir) => {
219
+ try {
220
+ return fs
221
+ .readdirSync(dir, { withFileTypes: true })
222
+ .some((e) => e.isSymbolicLink() || (e.isDirectory() && holdsLink(path.join(dir, e.name))));
223
+ } catch {
224
+ return false;
225
+ }
226
+ };
227
+ // The first link in a folder (its node_modules included) that leads anywhere but inside the folder itself or a folder
228
+ // the sandbox reads anyway (reads): { link, to }, or null. Each folder is looked through once, by its real path.
229
+ function linkOut(dir, reads) {
230
+ const inside = (f, d) => {
231
+ const rel = path.relative(d, f);
232
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
233
+ };
234
+ const top = fs.realpathSync(dir),
235
+ allowed = [top, ...reads.filter((r) => r !== dir)],
236
+ seen = new Set();
237
+ const look = (d) => {
238
+ let real;
239
+ try {
240
+ real = fs.realpathSync(d);
241
+ } catch {
242
+ return null;
243
+ }
244
+ if (seen.has(real)) return null;
245
+ seen.add(real);
246
+ let entries;
247
+ try {
248
+ entries = fs.readdirSync(d, { withFileTypes: true });
249
+ } catch {
250
+ return null;
251
+ }
252
+ for (const e of entries) {
253
+ const p = path.join(d, e.name);
254
+ if (e.isSymbolicLink()) {
255
+ let to;
256
+ try {
257
+ to = fs.realpathSync(p);
258
+ } catch {
259
+ continue; // (a link to nothing: reading it finds nothing)
260
+ }
261
+ if (!allowed.some((a) => inside(to, a))) return { link: p, to };
262
+ if (inside(to, top) && fs.statSync(p).isDirectory()) {
263
+ const found = look(p);
264
+ if (found) return found;
265
+ }
266
+ } else if (e.isDirectory()) {
267
+ const found = look(p);
268
+ if (found) return found;
269
+ }
270
+ }
271
+ return null;
272
+ };
273
+ return look(dir);
274
+ }
275
+
276
+ // The files a reply says the design imported, each by its path inside the project ('objects/box.js', with forward
277
+ // slashes): only files of the project are kept (the reply is untrusted, and the tool reads and hashes what is listed)
278
+ function inProject(urls, project) {
279
+ const top = fileURLToPath(project),
280
+ out = new Set();
281
+ for (const u of urls) {
282
+ let f;
283
+ try {
284
+ f = fileURLToPath(u);
285
+ } catch {
286
+ continue;
287
+ }
288
+ const rel = path.relative(top, f);
289
+ if (rel && !path.isAbsolute(rel) && !rel.split(path.sep).includes('..')) out.add(rel.split(path.sep).join('/'));
290
+ }
291
+ return [...out].sort();
292
+ }
293
+
209
294
  /** 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. */
210
295
  export const STAGE_KEY = /^[a-z][a-z0-9 _-]{0,39}-[0-9a-f]{64}$/;
211
296
 
@@ -239,7 +324,7 @@ const point = (p) => Array.isArray(p) && p.length === 3 && p.every((n) => typeof
239
324
  const faceList = (x) => Array.isArray(x) && x.every((f) => Array.isArray(f) && f.every(point));
240
325
  const PART = { name: 'string', role: 'string', label: 'string', filament: 'string', mirror: 'boolean' },
241
326
  PART_FACES = ['solid', 'polygons', 'triangles'];
242
- const REPLY = ['parts', 'read', 'mechanism', 'fixings', 'stages', 'board', 'mounted', 'routes'],
327
+ const REPLY = ['parts', 'read', 'imports', 'mechanism', 'fixings', 'seats', 'stages', 'board', 'mounted', 'routes'],
243
328
  ERROR = { message: 'string', code: 'string', line: 'number', syntax: 'boolean', resource: 'string' };
244
329
  const fields = (o, kinds) => Object.entries(o).find(([k, x]) => !(k in kinds) || typeof x !== kinds[k]);
245
330
 
@@ -270,8 +355,8 @@ function checkBoard(b) {
270
355
 
271
356
  /**
272
357
  * What is wrong with a reply from the sandbox's runner, in a few words, or null when it is one the runner makes:
273
- * `{ parts, read, mechanism?, fixings?, stages? }`, a board design's `{ parts: [], read, board: { circuit, matrix?,
274
- * source? }, mounted?, fixings?, routes? }`, or `{ error }`. Its stages no more than `stagesMost` (STAGES_MOST), its
358
+ * `{ parts, read, imports?, mechanism?, fixings?, stages? }`, a board design's `{ parts: [], read, imports?, board: {
359
+ * circuit, matrix?, source? }, mounted?, fixings?, routes? }`, or `{ error }`. Its stages no more than `stagesMost` (STAGES_MOST), its
275
360
  * routes no more than ROUTES_MOST.
276
361
  * @param {unknown} r the child's stdout, parsed
277
362
  * @param {{ count: number, bytes: number }} [stagesMost] @returns {string | null}
@@ -300,9 +385,20 @@ export function checkReply(r, stagesMost = STAGES_MOST) {
300
385
  }
301
386
  if (!Array.isArray(r.read) || !r.read.every((n) => typeof n === 'string'))
302
387
  return 'what it read is not a list of names';
388
+ if (r.imports != null && !(Array.isArray(r.imports) && r.imports.every((u) => typeof u === 'string')))
389
+ return 'what it imported is not a list of files';
303
390
  if (r.mechanism != null && !plain(r.mechanism)) return 'its mechanism is not an object';
304
391
  if (r.fixings != null && !(Array.isArray(r.fixings) && r.fixings.every(plain)))
305
392
  return 'its fixings are not a list of findings';
393
+ // (what v.shapes' seat helpers drew, lib/designshapes.mjs: never more than an info finding of its one code)
394
+ if (
395
+ r.seats != null &&
396
+ !(
397
+ Array.isArray(r.seats) &&
398
+ r.seats.every((x) => plain(x) && x.level === 'info' && x.code === 'seat.drawn' && typeof x.text === 'string')
399
+ )
400
+ )
401
+ return 'its seats are not a list of seat.drawn findings';
306
402
  if (r.stages != null) {
307
403
  if (!plain(r.stages)) return 'its stages are not an object';
308
404
  const bad = Object.entries(r.stages).find(([k, text]) => !STAGE_KEY.test(k) || typeof text !== 'string');
@@ -331,6 +427,155 @@ export function checkReply(r, stagesMost = STAGES_MOST) {
331
427
  /** Whether designs can be sandboxed here at all: Node has the permission model. */
332
428
  export const canSandbox = () => !!flag;
333
429
 
430
+ /**
431
+ * What cad says before the first design it runs in the sandbox, where Node's permission model doesn't cover the
432
+ * network (before Node 25: no --allow-net to withhold) and only the runner's own locks keep a design off it
433
+ * (sandbox-lock.mjs), or null where Node's model does.
434
+ * @param {string} [version] Node's version, as process.version gives it @returns {string | null}
435
+ */
436
+ export function networkWarning(version = process.version) {
437
+ const major = Number(/^v?(\d+)/.exec(version)?.[1]);
438
+ return major < 25
439
+ ? `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`
440
+ : null;
441
+ }
442
+ let warned = false; // (said once a run)
443
+
444
+ // What a sandbox that stopped without a reply printed, in a few words: Node's own error line where it printed one (its
445
+ // stack dump ends in a brace and Node's version), else its last three lines
446
+ function lastWords(said) {
447
+ const lines = said.trim().split('\n');
448
+ return (
449
+ lines.find((l) => /^\s*(?:[A-Z]\w*)?Error\b.*:/.test(l))?.trim() ||
450
+ lines.slice(-3).join(' ') ||
451
+ 'it printed nothing'
452
+ );
453
+ }
454
+
455
+ // Every process started from here that this command has not yet seen end: a design's sandboxed process, the guard
456
+ // (below), a look at the design's memory (processMemory, watchMemory). A command that returned while one of them was
457
+ // still running left it behind for a moment in the folder the command ran in, the workspace, and Windows will not move
458
+ // or remove a folder a live process sits in: a script that ran `cad check` and removed the folder straight after was
459
+ // refused now and then (EPERM, issue #687). The design's own process was always waited for (runSandboxed settles when
460
+ // it has closed); the guard and a look in flight were not. So before this command returns it ends each one and waits
461
+ // until it has gone (endSandbox): when Node has nothing left to do ('beforeExit', in whatever script uses this
462
+ // library), and from the command itself before it exits on an error (bin/cad.mjs), which 'beforeExit' never sees.
463
+ // A command killed from outside can do none of this: there the guard ends the design's process, as before.
464
+ const ours = new Map(); // (each with how it is asked to end: 'kill', or 'close' for one that ends when its input closes)
465
+ function ourOwn(child, how = 'kill') {
466
+ if (child.pid == null) return child; // (it never started, as its 'error' says: nothing to wait for)
467
+ ours.set(child, how);
468
+ child.once('exit', () => ours.delete(child));
469
+ return child;
470
+ }
471
+ // How long a process that ends when its input closes has to go before it is stopped outright, and how long one stopped
472
+ // outright is waited for before the command returns without it (rather than never return), in milliseconds
473
+ const END_GRACE = 2000,
474
+ END_WAIT = 5000;
475
+ // The helpers started from here (the guard, the looks at memory) sit in a folder outside any workspace, never the one
476
+ // the command runs in: Node's own, which is there for as long as this command runs and which a running Node holds in
477
+ // place anyway. So even where the guard outlives the command (one killed from outside), it holds nothing of the
478
+ // workspace. And a program named without its folder (ps, tasklist) is looked for, on Windows, in the working folder it
479
+ // is given before the PATH: Node's own, then, not a workspace's, where a file of that name could be waiting. (They are
480
+ // started by the full path programs.mjs finds on PATH all the same, which passes over PATH's folders in the workspace.)
481
+ const AWAY = path.dirname(process.execPath);
482
+
483
+ /**
484
+ * End every process the sandbox has started that is still running, and wait until each has gone: a design still
485
+ * running and a look at its memory are stopped outright; the guard is ended by closing its input, and stopped outright
486
+ * if it has not gone within two seconds. A command calls this before it returns, so that nothing of it is left in the
487
+ * workspace's folder, which can then be moved or removed at once (Windows refuses while a process sits in it). Node
488
+ * calls it by itself when a script that used the sandbox has nothing left to do; a command that exits by
489
+ * process.exit() awaits it first. It never rejects, and gives up on a process that will not end after five seconds
490
+ * more.
491
+ * @returns {Promise<void>}
492
+ */
493
+ export function endSandbox() {
494
+ const gone = [...ours].map(
495
+ ([child, how]) =>
496
+ new Promise((resolve) => {
497
+ if (child.exitCode != null || child.signalCode != null) return resolve();
498
+ let timer = null;
499
+ const ended = () => {
500
+ clearTimeout(timer);
501
+ resolve();
502
+ };
503
+ const stop = () => {
504
+ try {
505
+ child.kill('SIGKILL');
506
+ } catch {
507
+ // (it has gone already)
508
+ }
509
+ timer = setTimeout(() => {
510
+ ours.delete(child); // (it will not end: left, rather than have the command never return)
511
+ child.removeListener('exit', ended);
512
+ child.unref();
513
+ resolve();
514
+ }, END_WAIT);
515
+ };
516
+ child.once('exit', ended);
517
+ child.ref(); // (the guard doesn't keep the command running: the command waits for it now all the same)
518
+ if (how === 'close' && child.stdin?.writable) {
519
+ if (guard === child) guard = null; // (a design run after this starts a guard of its own)
520
+ child.stdin.end();
521
+ timer = setTimeout(stop, END_GRACE);
522
+ } else stop();
523
+ }),
524
+ );
525
+ return Promise.all(gone).then(() => {});
526
+ }
527
+ process.on('beforeExit', () => {
528
+ if (ours.size) endSandbox(); // (Node goes on until each has gone, then comes back here with nothing left)
529
+ });
530
+
531
+ // The guard (sandbox-guard.mjs): one small process a command, started with the first design it runs sandboxed, that
532
+ // ends every sandboxed process still running when this command ends, however it ends. The time and memory limits are
533
+ // kept from here, so a command killed from outside (a closed terminal, a test or CI job stopped) would otherwise leave
534
+ // a design that loops for ever running, on a processor core, until someone killed it by hand. It is told of each
535
+ // process as it starts and ends, and holds the other end of a pipe from here: when the pipe closes, it ends them.
536
+ // Neither it nor its pipe keeps this command running; a command that comes to its own end closes the pipe and waits
537
+ // for the guard to go before it returns (endSandbox).
538
+ let guard = null;
539
+ function guardChild(pid) {
540
+ if (!guard) {
541
+ try {
542
+ guard = spawn(process.execPath, [fileURLToPath(new URL('./sandbox-guard.mjs', import.meta.url))], {
543
+ cwd: AWAY,
544
+ stdio: ['pipe', 'ignore', 'ignore'],
545
+ env: Object.fromEntries(
546
+ ['PATH', 'SystemRoot', 'windir'].filter((k) => process.env[k] != null).map((k) => [k, process.env[k]]),
547
+ ),
548
+ windowsHide: true,
549
+ });
550
+ } catch {
551
+ guard = null;
552
+ return () => {}; // (no guard: the run goes on as before, its limits kept from here)
553
+ }
554
+ const g = ourOwn(guard, 'close');
555
+ g.on('error', () => {
556
+ if (guard === g) guard = null; // (it couldn't start, or has gone: the next run starts another)
557
+ });
558
+ g.on('exit', () => {
559
+ if (guard === g) guard = null;
560
+ });
561
+ g.stdin.on('error', () => {
562
+ if (guard === g) guard = null;
563
+ });
564
+ g.unref();
565
+ g.stdin.unref?.();
566
+ }
567
+ const g = guard,
568
+ say = (line) => {
569
+ try {
570
+ if (g.stdin.writable) g.stdin.write(`${line}\n`);
571
+ } catch {
572
+ // (the guard has gone: nothing to tell it)
573
+ }
574
+ };
575
+ say(`+${pid}`);
576
+ return () => say(`-${pid}`);
577
+ }
578
+
334
579
  // How long a design may run and how much memory it may use, in the sandbox. A design with an endless loop would
335
580
  // otherwise hang every command that builds it, with no word said, and one that fills memory without end would grow
336
581
  // until the system stopped it, taking other work with it. Past either limit the design's process is stopped, and the
@@ -390,9 +635,12 @@ const heldBack = (n, unit) =>
390
635
  /**
391
636
  * The memory a process holds, in bytes (its resident set: what it has in the machine's memory), or null where that
392
637
  * can't be told. Read from /proc on Linux, from ps on other Unix systems and from tasklist on Windows.
393
- * @param {number} pid @returns {Promise<number | null>}
638
+ * @param {number} pid
639
+ * @param {(look: import('node:child_process').ChildProcess) => void} [started] given the process that looks, where
640
+ * one is started (ps, tasklist), for a caller that may want to end it before it answers
641
+ * @returns {Promise<number | null>}
394
642
  */
395
- export function processMemory(pid) {
643
+ export function processMemory(pid, started) {
396
644
  return new Promise((resolve) => {
397
645
  if (process.platform === 'linux') {
398
646
  try {
@@ -410,10 +658,13 @@ export function processMemory(pid) {
410
658
  (t) => /"([\d.,\s\u00a0]+)\s*K"\s*$/m.exec(t)?.[1],
411
659
  ]
412
660
  : ['ps', ['-o', 'rss=', '-p', String(pid)], (t) => /^\s*(\d+)\s*$/.exec(t)?.[1]];
413
- execFile(cmd, args, { windowsHide: true, timeout: 5000 }, (e, text) => {
661
+ const exe = whereIs(cmd); // (by its full path on PATH, never one in the workspace: programs.mjs)
662
+ if (!exe) return resolve(null);
663
+ const look = execFile(exe, args, { cwd: AWAY, windowsHide: true, timeout: 5000 }, (e, text) => {
414
664
  const kb = e ? null : read(String(text));
415
665
  resolve(kb ? Number(kb.replace(/\D/g, '')) * 1024 : null);
416
666
  });
667
+ started?.(ourOwn(look));
417
668
  });
418
669
  }
419
670
  // How often the design's process's memory is looked at, in milliseconds
@@ -428,7 +679,8 @@ const FOOTPRINT = '/usr/bin/footprint';
428
679
  */
429
680
  function watchMemory(pid, most, over) {
430
681
  let looking = false,
431
- ended = false;
682
+ ended = false,
683
+ look = null; // (the look in flight, where it is a process)
432
684
  const past = (held) => {
433
685
  if (!ended && held != null && held > most) {
434
686
  ended = true;
@@ -438,8 +690,11 @@ function watchMemory(pid, most, over) {
438
690
  const every = setInterval(() => {
439
691
  if (looking || ended) return;
440
692
  looking = true;
441
- processMemory(pid).then((held) => {
693
+ processMemory(pid, (p) => {
694
+ look = p;
695
+ }).then((held) => {
442
696
  looking = false;
697
+ look = null;
443
698
  past(held);
444
699
  });
445
700
  }, WATCH_EVERY);
@@ -447,9 +702,11 @@ function watchMemory(pid, most, over) {
447
702
  let deep = null;
448
703
  if (process.platform === 'darwin' && fs.existsSync(FOOTPRINT)) {
449
704
  deep = spawn(FOOTPRINT, ['--sample', '1', '--noCategories', '-f', 'bytes', '-p', String(pid)], {
705
+ cwd: AWAY,
450
706
  stdio: ['ignore', 'pipe', 'ignore'],
451
707
  });
452
708
  deep.on('error', () => {}); // (without it, ps alone)
709
+ ourOwn(deep);
453
710
  let text = '';
454
711
  deep.stdout.on('data', (b) => {
455
712
  text += b;
@@ -463,6 +720,7 @@ function watchMemory(pid, most, over) {
463
720
  return () => {
464
721
  ended = true;
465
722
  clearInterval(every);
723
+ look?.kill(); // (its answer is no longer wanted, and the command waits for every process it started: endSandbox)
466
724
  if (deep && deep.exitCode == null) deep.kill();
467
725
  };
468
726
  }
@@ -486,7 +744,9 @@ const HEAP_DEATH = /JavaScript heap out of memory|Reached heap limit|Ineffective
486
744
  * @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
487
745
  * @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)
488
746
  * @param {string[]} [request.read] more folders the sandbox may read (a copy of a workspace held in memory)
489
- * @returns {Promise<{ parts: object[], read: Set<string>, mechanism: object | null, fixings: object[] | null, board?: { circuit: object[], matrix?: object, source?: object }, mounted?: boolean }>}
747
+ * @param {string | null} [request.runner] the script the sandbox runs in place of sandbox-run.mjs (tests: a runner that fails), a file the sandbox may read
748
+ * @returns {Promise<{ parts: object[], read: Set<string>, imports: string[], mechanism: object | null, fixings: object[] | null, board?: { circuit: object[], matrix?: object, source?: object }, mounted?: boolean }>}
749
+ * imports: the files of its project the design imported, each by its path inside the project ('objects/box.js')
490
750
  */
491
751
  export function runSandboxed({
492
752
  d,
@@ -498,6 +758,7 @@ export function runSandboxed({
498
758
  bound = {},
499
759
  board = null,
500
760
  read: more = [],
761
+ runner = null,
501
762
  }) {
502
763
  const here = path.dirname(fileURLToPath(import.meta.url));
503
764
  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)
@@ -507,18 +768,49 @@ export function runSandboxed({
507
768
  } catch (e) {
508
769
  return Promise.reject(located(e, d.js, 'design.limit'));
509
770
  }
771
+ if (!warned) {
772
+ warned = true;
773
+ const w = networkWarning();
774
+ if (w) process.stderr.write(`Note: ${w}\n`);
775
+ }
776
+ // (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
777
+ const js = fs.realpathSync(d.js),
778
+ project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href;
779
+ // Of the workspace, the sandbox reads only the design's project, the package.json that says its files are ES
780
+ // modules, and the design's own folders of the caches: not the workspace's other projects
781
+ // Node's permission model follows a link wherever it leads, and a design can get Node's fs by way of a package's
782
+ // code (sandbox-lock.mjs): so a cache folder holding a link is not read at all (every stage a miss), the workspace's
783
+ // package.json only where it is no link, and a link anywhere in the project (its node_modules too) must lead to a
784
+ // folder the sandbox reads anyway, never to another project or out of the workspace (linksIn)
785
+ const projectDir = path.dirname(path.dirname(js));
786
+ const own = [
787
+ projectDir,
788
+ ...[path.join(WS, 'package.json')].filter((f) => !isLink(f)),
789
+ ...[stages?.dir, board?.routes?.dir]
790
+ .filter(Boolean)
791
+ .map((dir) => ownFolder(path.resolve(dir)))
792
+ .filter((dir) => dir && !holdsLink(dir)),
793
+ ].filter(Boolean);
794
+ const reads = readable({ board: !!board, extra: [...more, ...routes], own });
795
+ const leads = linkOut(projectDir, reads);
796
+ if (leads)
797
+ return Promise.reject(
798
+ Object.assign(
799
+ new Error(
800
+ `${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`,
801
+ ),
802
+ { code: 'workspace.outside', file: leads.link },
803
+ ),
804
+ );
510
805
  const args = [
511
806
  flag,
512
807
  `--max-old-space-size=${limits.memory}`,
513
- ...readable({ board: !!board, extra: [...more, ...routes] }).map((p) => `--allow-fs-read=${p}`),
808
+ ...reads.map((p) => `--allow-fs-read=${p}`),
514
809
  ...(inThread ? [] : ['--allow-worker']),
515
810
  '--import',
516
811
  pathToFileURL(path.join(here, 'sandbox-preload.mjs')).href,
517
- path.join(here, 'sandbox-run.mjs'),
812
+ runner || path.join(here, 'sandbox-run.mjs'),
518
813
  ];
519
- // (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
520
- const js = fs.realpathSync(d.js),
521
- project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href;
522
814
  // The child gets none of this process's environment but what Node needs to start: tokens and keys stay out of it
523
815
  const env = Object.fromEntries(
524
816
  ['PATH', 'SystemRoot', 'windir', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'PHYS_DEBUG', 'LAMINA_TIMES']
@@ -526,10 +818,13 @@ export function runSandboxed({
526
818
  .map((k) => [k, process.env[k]]),
527
819
  );
528
820
  return new Promise((resolve, reject) => {
529
- const child = spawn(process.execPath, args, {
530
- stdio: ['pipe', 'pipe', 'pipe'],
531
- env: { ...env, CAD_SANDBOX_PROJECT: project, NODE_NO_WARNINGS: '1' },
532
- }); // (its stderr is passed on: what the design prints, not Node's notes on its own flags)
821
+ const child = ourOwn(
822
+ spawn(process.execPath, args, {
823
+ stdio: ['pipe', 'pipe', 'pipe'],
824
+ env: { ...env, CAD_SANDBOX_PROJECT: project, NODE_NO_WARNINGS: '1' },
825
+ }),
826
+ ); // (its stderr is passed on: what the design prints, not Node's notes on its own flags)
827
+ const unguard = child.pid ? guardChild(child.pid) : () => {}; // (it ends when this command does)
533
828
  const MB = 1024 * 1024,
534
829
  memoryMessage = (what) =>
535
830
  `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')}`;
@@ -569,6 +864,7 @@ export function runSandboxed({
569
864
  const done = () => {
570
865
  clearTimeout(timer);
571
866
  unwatch();
867
+ unguard();
572
868
  };
573
869
  // Why the process was stopped from here, said as an error naming the design and the limit
574
870
  const stopped = (why) =>
@@ -595,7 +891,10 @@ export function runSandboxed({
595
891
  done();
596
892
  reject(e);
597
893
  });
598
- child.on('close', () => {
894
+ // A process that ends before it has read its request (it couldn't start, or this Node can't run it) closes the
895
+ // pipe the request goes down, and the write fails: that is said, as any other end without a reply is, when it closes
896
+ child.stdin.on('error', () => {});
897
+ child.on('close', (status, signal) => {
599
898
  done();
600
899
  if (over) return reject(stopped(over));
601
900
  let r;
@@ -614,7 +913,9 @@ export function runSandboxed({
614
913
  );
615
914
  return reject(
616
915
  located(
617
- new Error(`the design's sandbox stopped: ${said.trim().split('\n').slice(-3).join(' ') || 'no output'}`),
916
+ new Error(
917
+ `the design's sandbox stopped (${status != null ? `exit code ${status}` : `signal ${signal}`}) before it sent back the design's shapes: ${lastWords(said)}`,
918
+ ),
618
919
  d.js,
619
920
  'design.sandbox',
620
921
  ),
@@ -656,8 +957,10 @@ export function runSandboxed({
656
957
  resolve({
657
958
  parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })),
658
959
  read: new Set(r.read),
960
+ imports: inProject(r.imports || [], project),
659
961
  mechanism: r.mechanism || null,
660
962
  fixings: r.fixings || null,
963
+ seats: r.seats || null,
661
964
  ...(board ? { board: r.board, mounted: r.mounted === true } : {}),
662
965
  });
663
966
  });