@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/versions.mjs CHANGED
@@ -11,11 +11,13 @@ import { fileURLToPath } from 'node:url';
11
11
  import crypto from 'node:crypto';
12
12
  import { resolve, loadRuleSet } from './rules.mjs';
13
13
  import { WS, paths } from './workspace.mjs';
14
- import { plainName, isPlainName } from './names.mjs';
14
+ import { readJson, readOwnText } from './host.mjs';
15
+ import { plainName, isPlainName, isWorkspacePath } from './names.mjs';
15
16
  import { readLayout, hasLayout } from './layout.mjs';
16
17
  import { newer } from '@rulecad/versions';
17
18
 
18
- export const git = (...args) => execFileSync('git', args, { cwd: WS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trimEnd();
19
+ export const git = (...args) =>
20
+ execFileSync('git', args, { cwd: WS, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trimEnd();
19
21
 
20
22
  // ---------- semver: @rulecad/versions ----------
21
23
  export { parse, bump, newer, bigger, compare } from '@rulecad/versions';
@@ -25,47 +27,251 @@ export { parse, bump, newer, bigger, compare } from '@rulecad/versions';
25
27
  export function tags(project, name) {
26
28
  const prefix = name ? `${project}/${name}@` : `${project}@`;
27
29
  let out;
28
- try { out = git('for-each-ref', `refs/tags/${prefix}*`, '--format=%(refname:strip=2)%09%(creatordate:short)%09%(contents:subject)'); }
29
- catch (e) { if (/not a git repository/.test(e.stderr || e.message)) return []; throw e; } // a workspace outside git: no releases yet
30
- return out.split('\n').filter(Boolean).map((l) => {
31
- const [tag, date, subject = ''] = l.split('\t'), [, kind, message] = subject.match(/^(major|minor|patch|first): (.*)$/) || [, '', subject];
32
- return { tag, version: tag.slice(prefix.length), date, kind, message };
33
- }).filter((t) => /^\d+\.\d+\.\d+$/.test(t.version)).sort((a, b) => (newer(a.version, b.version) ? 1 : -1));
30
+ try {
31
+ out = git(
32
+ 'for-each-ref',
33
+ `refs/tags/${prefix}*`,
34
+ '--format=%(refname:strip=2)%09%(creatordate:short)%09%(contents:subject)',
35
+ );
36
+ } catch (e) {
37
+ if (/not a git repository/.test(e.stderr || e.message)) return [];
38
+ throw e;
39
+ } // a workspace outside git: no releases yet
40
+ return out
41
+ .split('\n')
42
+ .filter(Boolean)
43
+ .map((l) => {
44
+ const [tag, date, subject = ''] = l.split('\t'),
45
+ [, kind, message] = subject.match(/^(major|minor|patch|first): (.*)$/) || [, '', subject];
46
+ return { tag, version: tag.slice(prefix.length), date, kind, message };
47
+ })
48
+ .filter((t) => /^\d+\.\d+\.\d+$/.test(t.version))
49
+ .sort((a, b) => (newer(a.version, b.version) ? 1 : -1));
34
50
  }
35
51
 
36
52
  // The layout files an object can pick (its layout variables' choices that are files), by name
37
- const layoutNames = (d, object) => Object.values(object.variables || {}).filter((v) => v.type === 'layout')
38
- .flatMap((v) => v.choice || [v.value]).filter((n) => hasLayout(d.project, n, d.layoutsDir));
53
+ const layoutNames = (d, object) =>
54
+ Object.values(object.variables || {})
55
+ .filter((v) => v.type === 'layout')
56
+ .flatMap((v) => v.choice || [v.value])
57
+ .filter((n) => hasLayout(d.project, n, d.layoutsDir));
39
58
 
40
59
  // A file's path in git's terms: relative to the workspace, forward slashes on every system (git show tag:path needs them)
41
60
  const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
42
61
 
43
- // The files a design depends on, relative to the workspace (its git repo): its .js and .json, the rule sets and the layouts it uses.
62
+ // The files a design depends on, relative to the workspace (its git repo): its .js and .json, the rule sets and the
63
+ // layouts it uses, and, given its build (b), everything else the build read (design.mjs readsOf): the files its design
64
+ // imported, the rule sets v.fixings and v.frames read, and the files of the objects it reads through "uses". A release
65
+ // commits them all, so its tag holds every file it was built from.
44
66
  // (A board's engine is the tool's code, not the workspace's: its release records engineId() instead.)
45
- export function files(d, object) {
46
- return [rel(d.js), rel(d.json), ...(object.uses || []).filter((u) => !u.includes('/')).map((u) => `rules/${u}.json`),
47
- ...layoutNames(d, object).map((n) => `projects/${d.project}/layouts/${n}.json`)];
67
+ export function files(d, object, b) {
68
+ const own = [
69
+ rel(d.js),
70
+ rel(d.json),
71
+ ...(object.uses || []).filter((u) => !u.includes('/')).map((u) => `rules/${u}.json`),
72
+ ...layoutNames(d, object).map((n) => `projects/${d.project}/layouts/${n}.json`),
73
+ ];
74
+ const r = b?.reads;
75
+ if (!r) return own;
76
+ // (only the workspace's own files: never a release's copy in .versions/, nor the cache)
77
+ const more = [...r.files, ...r.sets, ...r.also].filter((f) => isWorkspacePath(f) && !f.startsWith('.'));
78
+ return [...new Set([...own, ...more])];
79
+ }
80
+
81
+ // What a release records of its build's reads, in its tag's message (a line "reads: {…}"): the files its design
82
+ // imported, whether it called v.fixings and v.frames, and the files of the objects it reads. Its rule sets aren't
83
+ // listed: a release is rebuilt with every rule set its tag holds.
84
+ export const READS = 'reads: ';
85
+ export const readsLine = (b) =>
86
+ b?.reads
87
+ ? `${READS}${JSON.stringify({
88
+ files: b.reads.files.filter((f) => !f.startsWith('.')),
89
+ fixings: b.reads.fixings,
90
+ frames: b.reads.frames,
91
+ also: b.reads.also.filter((f) => !f.startsWith('.')),
92
+ })}`
93
+ : '';
94
+ // A tag's record of what its release read, or null for a release made before releases recorded it (or a line that is
95
+ // not one the tool writes: a tag comes with a cloned workspace, so its paths are taken only where they are plain paths
96
+ // inside the workspace)
97
+ function recorded(tag) {
98
+ let text;
99
+ try {
100
+ text = git('tag', '-l', '--format=%(contents)', tag);
101
+ } catch {
102
+ return null;
103
+ }
104
+ const line = text.split('\n').findLast((l) => l.startsWith(READS)); // (the tool's line comes after the message)
105
+ if (!line) return null;
106
+ let r;
107
+ try {
108
+ r = JSON.parse(line.slice(READS.length));
109
+ } catch {
110
+ return null;
111
+ }
112
+ const list = (x) => (Array.isArray(x) ? x.filter((f) => isWorkspacePath(f) && !f.startsWith('.')) : []);
113
+ return r && typeof r === 'object'
114
+ ? { files: list(r.files), fixings: r.fixings === true, frames: r.frames === true, also: list(r.also) }
115
+ : null;
116
+ }
117
+
118
+ // The files a .js imports by a path ('./box.js', '../shared/x.mjs'), as written in it: a release made before releases
119
+ // recorded what they read is rebuilt with these (and what they import in turn). Paths inside the workspace, from the
120
+ // file's own (`from`, a path inside the workspace).
121
+ const IMPORTED = /(?:\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.\.?\/[^'"\n]+)\1/g;
122
+ const importedBy = (from, text) =>
123
+ [...String(text).matchAll(IMPORTED)]
124
+ .map((m) => path.posix.join(path.posix.dirname(from), m[2]))
125
+ .filter((f) => isWorkspacePath(f) && /\.(m?js|json)$/.test(f));
126
+
127
+ // A release's folder holds its files at the paths they have in the workspace (.versions/<project>/<object>@<version>/
128
+ // projects/<project>/objects/<object>.js, …/rules/x1c.json), so that what the design imports by a path is found there
129
+ // as it was, and what it imports from a package is found in the workspace's node_modules, above.
130
+ // put: a file of the release written there from its tag (false when the tag has no such file)
131
+ function treeOf(tag, base) {
132
+ const show = (f) => git('show', `${tag}:./${f}`); // (./: from the workspace, which may be below the repository's root)
133
+ const put = (f) => {
134
+ if (!isWorkspacePath(f)) return false;
135
+ const to = path.join(base, ...f.split('/'));
136
+ if (fs.existsSync(to)) return true;
137
+ let text;
138
+ try {
139
+ text = show(f);
140
+ } catch {
141
+ return false;
142
+ }
143
+ fs.mkdirSync(path.dirname(to), { recursive: true });
144
+ fs.writeFileSync(to, text);
145
+ return true;
146
+ };
147
+ // A design's file, and those it imports by a path, in turn (as written: what it imports as it runs is in the record)
148
+ const withImports = (f) => {
149
+ const seen = new Set();
150
+ for (let todo = [f]; todo.length && seen.size < 1000;) {
151
+ const x = todo.pop();
152
+ if (seen.has(x) || !put(x)) continue;
153
+ seen.add(x);
154
+ if (/\.m?js$/.test(x)) todo.push(...importedBy(x, fs.readFileSync(path.join(base, ...x.split('/')), 'utf8')));
155
+ }
156
+ seen.delete(f);
157
+ return [...seen].sort();
158
+ };
159
+ return { show, put, withImports };
160
+ }
161
+
162
+ // An object's files from a release's tag, into the release's folder: its .js and what that imports, its .json and the
163
+ // layouts it can pick. -> its .json, parsed, and the files its .js imports
164
+ function objectFrom(t, project, name, where) {
165
+ const json = `projects/${project}/objects/${name}.json`,
166
+ js = `projects/${project}/objects/${name}.js`;
167
+ let object;
168
+ try {
169
+ object = JSON.parse(t.show(json));
170
+ } catch {
171
+ throw new Error(`${where} has no ${project}/${name} that can be read (${json})`);
172
+ }
173
+ t.put(json);
174
+ if (!t.put(js)) throw new Error(`${where} has no ${js}`);
175
+ const imports = t.withImports(js);
176
+ for (const v of Object.values(object.variables || {}))
177
+ if (v.type === 'layout')
178
+ for (const n of (v.choice || [v.value]).filter(isPlainName)) t.put(`projects/${project}/layouts/${n}.json`); // (another name is refused where the layout is read; a built-in (grid) has no file)
179
+ return { object, imports };
180
+ }
181
+
182
+ // The rule sets a release holds, all of them, into its folder: what its "uses" names, and what v.fixings and v.frames
183
+ // read (thread, material, profile sets and the printer's, with rules/outlines/), as its tag has them
184
+ function rulesFrom(tag, t) {
185
+ let names = [];
186
+ try {
187
+ // (--full-tree: below the repository's root, ls-tree would list only what is under the same folder of the tree)
188
+ names = git('ls-tree', '-r', '--name-only', '--full-tree', `${tag}:./rules`).split('\n');
189
+ } catch {
190
+ // (no rules/ in the release)
191
+ }
192
+ for (const n of names) if (/^(outlines\/)?[^/]+\.json$/.test(n)) t.put(`rules/${n}`);
48
193
  }
49
194
 
50
195
  // A released version's files, written under .versions/ so its imports still find node_modules. -> a design to build
51
196
  export function materialise(d, version) {
52
197
  const tag = `${d.project}/${d.name}@${version}`;
53
- try { git('rev-parse', '--verify', `refs/tags/${tag}`); } catch { throw new Error(`no release ${tag} (releases: ${tags(d.project, d.name).map((t) => t.version).join(', ') || 'none'})`); }
198
+ let id;
199
+ try {
200
+ id = git('rev-parse', '--verify', `refs/tags/${tag}`);
201
+ } catch {
202
+ throw new Error(
203
+ `no release ${tag} (releases: ${
204
+ tags(d.project, d.name)
205
+ .map((t) => t.version)
206
+ .join(', ') || 'none'
207
+ })`,
208
+ );
209
+ }
54
210
  const base = paths.versions(d.project, `${d.name}@${version}`);
55
- const show = (rel) => git('show', `${tag}:${rel}`);
56
- const object = JSON.parse(show(rel(d.json)));
57
- fs.mkdirSync(path.join(base, 'rules'), { recursive: true });
58
- const js = path.join(base, `${d.name}.js`), json = path.join(base, `${d.name}.json`);
59
- fs.writeFileSync(js, show(rel(d.js)));
60
- fs.writeFileSync(json, JSON.stringify(object, null, 2));
211
+ // A file already in the folder is used as it is (treeOf), so the folder is made afresh when it was written from
212
+ // another tag of the same name (one deleted and made again) or by an earlier version of the tool (another layout)
213
+ const stamp = path.join(base, '.tag');
214
+ if (fs.existsSync(base) && (!fs.existsSync(stamp) || fs.readFileSync(stamp, 'utf8') !== id))
215
+ fs.rmSync(base, { recursive: true, force: true });
216
+ fs.mkdirSync(base, { recursive: true });
217
+ fs.writeFileSync(stamp, id);
218
+ const t = treeOf(tag, base);
61
219
  // (names from the release's own file, each written as a file here: plain names only, never ../)
62
- for (const u of (object.uses || []).filter((x) => !x.includes('/'))) fs.writeFileSync(path.join(base, 'rules', `${plainName(u, 'rule set name', `${tag}'s ${d.name}.json, in its "uses"`)}.json`), show(`rules/${u}.json`)); // objects it reads are released on their own
63
- // The layouts it could pick, as they were then (only files that existed in that release)
64
- fs.mkdirSync(path.join(base, 'layouts'), { recursive: true });
65
- for (const v of Object.values(object.variables || {})) if (v.type === 'layout') for (const n of (v.choice || [v.value]).filter(isPlainName)) { // (another name is refused where the layout is read)
66
- try { fs.writeFileSync(path.join(base, 'layouts', `${n}.json`), show(`projects/${d.project}/layouts/${n}.json`)); } catch {} // a built-in (grid)
220
+ const object = JSON.parse(t.show(rel(d.json)));
221
+ for (const u of (object.uses || []).filter((x) => !x.includes('/')))
222
+ plainName(u, 'rule set name', `${tag}'s ${d.name}.json, in its "uses"`);
223
+ const { imports } = objectFrom(t, d.project, d.name, tag);
224
+ rulesFrom(tag, t);
225
+ t.put(`projects/${d.project}/project.json`); // (the material v.fixings draws for, as it was)
226
+ // What the release read, as its tag records it; for one made before tags recorded it, the files its .js imports by
227
+ // a path, and v.fixings and v.frames where its code names them
228
+ let reads = recorded(tag);
229
+ if (reads) for (const f of [...reads.files, ...reads.also]) t.put(f);
230
+ else {
231
+ const code = [rel(d.js), ...imports]
232
+ .map((f) => fs.readFileSync(path.join(base, ...f.split('/')), 'utf8'))
233
+ .join('\n');
234
+ reads = { files: imports, fixings: /\bfixings\b/.test(code), frames: /\bframes\b/.test(code), also: [] };
67
235
  }
68
- return { ...d, js, json, rulesDir: path.join(base, 'rules'), layoutsDir: path.join(base, 'layouts'), version, tag };
236
+ const at = (f) => path.join(base, ...rel(f).split('/'));
237
+ return {
238
+ ...d,
239
+ js: at(d.js),
240
+ json: at(d.json),
241
+ rulesDir: path.join(base, 'rules'),
242
+ layoutsDir: path.join(base, 'projects', d.project, 'layouts'),
243
+ version,
244
+ tag,
245
+ tree: base,
246
+ reads,
247
+ };
248
+ }
249
+
250
+ /**
251
+ * Another object as a release has it (its files at the release's tag), for a release that reads it through "uses"
252
+ * without naming a version: rebuilt from the same tag as the release, so with the numbers it had then.
253
+ * @param {{ tag: string, tree: string, rulesDir: string, project: string }} d the release (materialise's)
254
+ * @param {string} project @param {string} name the object, plain names (design.mjs objectSets has checked them)
255
+ */
256
+ export function inRelease(d, project, name) {
257
+ const [plain, variant] = String(name).split(':');
258
+ plainName(project, 'project name');
259
+ plainName(plain, 'object name');
260
+ const t = treeOf(d.tag, d.tree);
261
+ objectFrom(t, project, plain, d.tag);
262
+ const at = (f) => path.join(d.tree, 'projects', project, f);
263
+ return {
264
+ project,
265
+ name: plain,
266
+ js: at(`objects/${plain}.js`),
267
+ json: at(`objects/${plain}.json`),
268
+ dir: paths.project(project),
269
+ rulesDir: d.rulesDir,
270
+ layoutsDir: at('layouts'),
271
+ tag: d.tag,
272
+ tree: d.tree,
273
+ ...(variant ? { variant } : {}),
274
+ };
69
275
  }
70
276
 
71
277
  // ---------- what changed: compare() is @rulecad/versions' (exported above) ----------
@@ -77,18 +283,35 @@ export function materialise(d, version) {
77
283
  export function packageVersion(name, from = import.meta.url) {
78
284
  for (let dir = path.dirname(createRequire(from).resolve(name)); dir !== path.dirname(dir); dir = path.dirname(dir)) {
79
285
  const f = path.join(dir, 'package.json');
80
- if (fs.existsSync(f)) { const pj = JSON.parse(fs.readFileSync(f, 'utf8')); if (pj.name === name) return pj.version; }
286
+ if (fs.existsSync(f)) {
287
+ const pj = JSON.parse(fs.readFileSync(f, 'utf8'));
288
+ if (pj.name === name) return pj.version;
289
+ }
81
290
  }
82
291
  return '';
83
292
  }
84
- const ENGINE_LIBS = ['@tscircuit/capacity-autorouter', '@tscircuit/footprinter', '@tscircuit/checks', 'schematic-symbols'];
85
- const engineLibs = () => ENGINE_LIBS.map((n) => `${n}@${packageVersion(n, import.meta.resolve('@rulecad/pcb'))}`).join(' ');
86
- const engineHash = (code) => crypto.createHash('sha256').update(`${code.trimEnd()}\n${engineLibs()}`).digest('hex').slice(0, 16);
293
+ const ENGINE_LIBS = [
294
+ '@tscircuit/capacity-autorouter',
295
+ '@tscircuit/footprinter',
296
+ '@tscircuit/checks',
297
+ 'schematic-symbols',
298
+ ];
299
+ const engineLibs = () =>
300
+ ENGINE_LIBS.map((n) => `${n}@${packageVersion(n, import.meta.resolve('@rulecad/pcb'))}`).join(' ');
301
+ const engineHash = (code) =>
302
+ crypto.createHash('sha256').update(`${code.trimEnd()}\n${engineLibs()}`).digest('hex').slice(0, 16);
87
303
  // The board engine's code: @rulecad/pcb's modules, and @rulecad/smooth's, which a board's build runs too (smoothing its
88
304
  // tracks, finishing them): a change to either is a change to what a board builds, so it must miss the cache
89
- const sources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.')).sort().map((f) => fs.readFileSync(path.join(dir, f), 'utf8')).join('\n');
305
+ const sources = (dir) =>
306
+ fs
307
+ .readdirSync(dir)
308
+ .filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.'))
309
+ .sort()
310
+ .map((f) => fs.readFileSync(path.join(dir, f), 'utf8'))
311
+ .join('\n');
90
312
  export const engineId = () => {
91
- const pcb = import.meta.resolve('@rulecad/pcb'), dir = path.dirname(fileURLToPath(pcb));
313
+ const pcb = import.meta.resolve('@rulecad/pcb'),
314
+ dir = path.dirname(fileURLToPath(pcb));
92
315
  const smooth = path.dirname(createRequire(pcb).resolve('@rulecad/smooth'));
93
316
  return engineHash(`${sources(dir)}\n${sources(smooth)}`);
94
317
  };
@@ -96,18 +319,37 @@ export const engineId = () => {
96
319
  function taggedEngine(tag) {
97
320
  const m = git('tag', '-l', '--format=%(contents)', tag).match(/^engine: (\w+)$/m);
98
321
  if (m) return m[1];
99
- try { return engineHash(git('show', `${tag}:lib/pcb.mjs`)); } catch { return ''; } // (the engine once lived in the workspace)
322
+ try {
323
+ return engineHash(git('show', `${tag}:./lib/pcb.mjs`));
324
+ } catch {
325
+ return '';
326
+ } // (the engine once lived in the workspace)
100
327
  }
101
328
 
102
329
  // Resolve a design as it is on disk, or as materialised from a release.
103
330
  // refs: the numbers of objects it reads (design.mjs objectSets), which a snapshot can't build itself.
104
- export function snapshot(d, refs = {}) {
105
- const object = JSON.parse(fs.readFileSync(d.json, 'utf8'));
106
- const sets = { ...(d.rulesDir ? Object.fromEntries((object.uses || []).filter((u) => !u.includes('/')).map((u) => [u, loadRuleSet(u, d.rulesDir)])) : {}), ...refs };
331
+ // reads: the text of each file it read besides its own (design.mjs readTexts), compared file by file by compare()
332
+ export function snapshot(d, refs = {}, reads = null) {
333
+ const object = readJson(d.json); // (the workspace's own files only where they really are inside it: host.mjs)
334
+ const sets = {
335
+ ...(d.rulesDir
336
+ ? Object.fromEntries(
337
+ (object.uses || []).filter((u) => !u.includes('/')).map((u) => [u, loadRuleSet(u, d.rulesDir)]),
338
+ )
339
+ : {}),
340
+ ...refs,
341
+ };
107
342
  const layouts = Object.fromEntries(layoutNames(d, object).map((n) => [n, readLayout(d.project, n, d.layoutsDir)]));
108
343
  // A board is also made by the board engine (footprints, the router): which engine, as recorded at the release
109
344
  const engine = object.engine === 'pcb' ? (d.tag ? taggedEngine(d.tag) : engineId()) : null;
110
- return { object, entries: resolve(object, { sets }).entries, js: fs.readFileSync(d.js, 'utf8'), layouts, ...(engine != null ? { engine } : {}) };
345
+ return {
346
+ object,
347
+ entries: resolve(object, { sets }).entries,
348
+ js: readOwnText(d.js).replace(/\r\n/g, '\n'), // (git keeps \n; a Windows checkout may write \r\n)
349
+ layouts,
350
+ ...(engine != null ? { engine } : {}),
351
+ ...(reads ? { reads } : {}),
352
+ };
111
353
  }
112
354
 
113
355
  // ---------- prints log ----------
@@ -116,5 +358,9 @@ export const printsFile = (d) => path.join(d.dir, 'prints.jsonl');
116
358
  export function prints(d) {
117
359
  const f = printsFile(d);
118
360
  if (!fs.existsSync(f)) return [];
119
- return fs.readFileSync(f, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).filter((p) => !d.name || p.object === d.name);
361
+ return readOwnText(f)
362
+ .split('\n')
363
+ .filter(Boolean)
364
+ .map((l) => JSON.parse(l))
365
+ .filter((p) => !d.name || p.object === d.name);
120
366
  }