@rulecad/cad 0.7.12 → 0.7.26
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.
- package/AGENTS.md +6 -1
- package/EXAMPLES.md +386 -0
- package/README.md +73 -15
- package/TUTORIAL.md +226 -0
- package/bin/cad.mjs +97 -31
- package/lib/animate.mjs +71 -0
- package/lib/assembly.mjs +31 -5
- package/lib/clone.mjs +150 -0
- package/lib/design.mjs +75 -33
- package/lib/errors.mjs +20 -2
- package/lib/host.mjs +7 -0
- package/lib/jsonedit.mjs +17 -11
- package/lib/layout.mjs +2 -2
- package/lib/links.mjs +23 -7
- package/lib/live-shape.mjs +131 -0
- package/lib/live.mjs +2 -2
- package/lib/optimise.mjs +87 -23
- package/lib/parts.mjs +26 -0
- package/lib/player.mjs +225 -0
- package/lib/preview.mjs +3 -1
- package/lib/rules.mjs +2 -2
- package/lib/sandbox-hooks.mjs +9 -6
- package/lib/sandbox-run.mjs +24 -10
- package/lib/sandbox.mjs +27 -15
- package/lib/schema.mjs +1 -7
- package/lib/workspace.mjs +8 -3
- package/package.json +17 -7
- package/schemas/assembly.schema.json +1 -1
- package/schemas/object.schema.json +1 -1
- package/schemas/problem.schema.json +106 -4
- package/schemas/rules.schema.json +3 -1
package/lib/assembly.mjs
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
// { "holes": "pcb.board", "into": "case.body", "depth": "m2.insert_length", "label": "Screws find their inserts" }
|
|
17
17
|
// The path must be clear for depth mm (it lands in a hole) and solid within "ring" mm of it (default: the hole's
|
|
18
18
|
// diameter) half way down, so the screw has something to grip. "direction": "up" for screws from below.
|
|
19
|
-
import { host } from './host.mjs';
|
|
19
|
+
import { host, readJson } from './host.mjs';
|
|
20
20
|
import fs from 'node:fs';
|
|
21
21
|
import crypto from 'node:crypto';
|
|
22
22
|
import path from 'node:path';
|
|
@@ -56,9 +56,16 @@ export { satisfies }; // from @rulecad/versions
|
|
|
56
56
|
// overrides: { itemId: { variable: value } }, set on this assembly's items by the assembly that uses it.
|
|
57
57
|
// opts: { mirror: true } builds each object with its mirror settings (cad show).
|
|
58
58
|
export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
|
|
59
|
+
const outer = overrides;
|
|
59
60
|
const [project, name] = ref.split('/');
|
|
60
61
|
if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
|
|
61
|
-
const a =
|
|
62
|
+
const a = readJson(assemblyPath(ref));
|
|
63
|
+
// A pose may set items' variables as well as joints ("cocked": { "run": -30, "action.travel": 25 }): a flexure bent
|
|
64
|
+
// as the pose bends it, while the part itself is printed as drawn. The pose being built sets them on its items.
|
|
65
|
+
const itemSets = (name) => { const out = {}; for (const [k, v] of Object.entries(a.poses?.[name] || {})) if (k.includes('.')) { const [item, ...rest] = k.split('.'); (out[item] ||= {})[rest.join('.')] = v; } return out; };
|
|
66
|
+
const builtPose = opts.pose ?? a.pose ?? Object.keys(a.poses || {})[0];
|
|
67
|
+
const ownSets = typeof builtPose === 'string' ? itemSets(builtPose) : {};
|
|
68
|
+
overrides = { ...overrides };
|
|
62
69
|
const printer = printerOf(project);
|
|
63
70
|
if (a.kind === 'plate' && !(a.uses || []).includes(printer)) a.uses = [...(a.uses || []), printer]; // a plate is checked as a print
|
|
64
71
|
const values = Object.fromEntries((a.uses || []).map((u) => { const s = loadRuleSet(u); return [u, Object.fromEntries(Object.entries(s.rules).map(([k, r]) => [k, r.value]))]; }));
|
|
@@ -86,7 +93,20 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
86
93
|
// from: inputs worked out from items built before this one ({ "usb_y": "board.pcb.pico_y" }): numbers, in this
|
|
87
94
|
// assembly's names, so a part can take a value only another part knows once it's built
|
|
88
95
|
const from = Object.fromEntries(Object.entries(it.from || {}).map(([k, x]) => [k, num(x)]));
|
|
89
|
-
|
|
96
|
+
// The pose's settings for this item: expressions in the assembly's names (launcher.travel), which may name the item's
|
|
97
|
+
// own variables (magazine.preload: the item is built once as drawn to read them), or a choice as it is
|
|
98
|
+
const base = { ...(it.set || {}), ...from, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
|
|
99
|
+
let own = null;
|
|
100
|
+
const ownValue = async (x) => {
|
|
101
|
+
if (typeof x !== 'string') return x;
|
|
102
|
+
try { return num(x); } catch {}
|
|
103
|
+
if (!it.object || !new RegExp(`\\b${it.id}\\.`).test(x)) return x;
|
|
104
|
+
if (!own) { const [r, named] = String(it.object).split(':'), [objName, pin] = r.split('@'), d = locate(`${project}/${objName}`); own = (await build({ ...(pin ? materialise(d, pin) : d), ...((named || it.variant) ? { variant: named || it.variant } : {}) }, base, opts)).values; }
|
|
105
|
+
return evaluate(x, (n) => { if (n.startsWith(`${it.id}.`)) { const v = own[n.slice(it.id.length + 1)]; if (typeof v === 'number') return v; } return lookup(n); });
|
|
106
|
+
};
|
|
107
|
+
const posed = {};
|
|
108
|
+
for (const [k, x] of Object.entries(ownSets[it.id] || {})) posed[k] = await ownValue(x);
|
|
109
|
+
const set = { ...(it.set || {}), ...from, ...posed, ...(overrides[it.id] || {}), ...(it.assembly ? {} : extra) };
|
|
90
110
|
// Built for the mirror, an object's mirror settings win (no legends), so copies that differ only there are one shape
|
|
91
111
|
if (opts.mirror && it.object) for (const k of Object.keys(readObject(locate(`${project}/${String(it.object).split(/[:@]/)[0]}`)).mirror || {})) delete set[k];
|
|
92
112
|
const sub = it.assembly ? extra : {}; // a component's values go to its items: { cap: { units: 1.5 } }
|
|
@@ -221,7 +241,11 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
221
241
|
for (const id of copies) { const swap = (n) => (n === star ? at(id, n) : n); fits.push({ ...x, a: swap(x.a), b: swap(x.b), num }); }
|
|
222
242
|
}
|
|
223
243
|
// at(pose): the same assembly in another pose (a name, or { joint: values }), nothing built again
|
|
244
|
+
const same = (x, y) => JSON.stringify(x) === JSON.stringify(y);
|
|
245
|
+
const others = {};
|
|
246
|
+
if (!opts.onePose) for (const n of Object.keys(a.poses || {})) if (n !== builtPose && !same(itemSets(n), ownSets)) others[n] = await buildAssembly(ref, stack, outer, { ...opts, pose: n, onePose: true });
|
|
224
247
|
const at = (p) => {
|
|
248
|
+
if (typeof p === 'string' && others[p]) return others[p];
|
|
225
249
|
const v = jointValues(motion, p), moved = partsAt(placeItems(motion, v));
|
|
226
250
|
return { ...s, parts: moved, pose: typeof p === 'string' ? p : null, jointValues: v, polygons: moved.flatMap((x) => x.polygons), triangles: moved.flatMap((x) => x.triangles) };
|
|
227
251
|
};
|
|
@@ -247,7 +271,9 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
|
|
|
247
271
|
// another's values (times "ratio", plus "offset"): the second hinge of a pair, gears. Items joined in a ring (two links
|
|
248
272
|
// between the same two parts) can't all be joints: join the ring's last pair with "loops" instead, which the check
|
|
249
273
|
// measures in every pose: [{ "a": "link_l.top", "b": "mount_l.axis", "label": "Left pivot lines up" }].
|
|
250
|
-
// "poses": { "open": { "hinge": 90 } } names sets of values, "pose" the one shown (default: the first);
|
|
274
|
+
// "poses": { "open": { "hinge": 90 } } names sets of values, "pose" the one shown (default: the first); a pose can set an
|
|
275
|
+
// item's variables too ("cocked": { "run": -30, "action.travel": 25 }), so a flexure is drawn bent in that pose and
|
|
276
|
+
// straight as printed (each such pose is built on its own; at(pose) returns it); check checks
|
|
251
277
|
// every pose, and --sweep moves each joint through its range, looking for parts that collide.
|
|
252
278
|
const rows = (m) => [m[0], m[4], m[8], m[12], m[1], m[5], m[9], m[13], m[2], m[6], m[10], m[14]]; // JSCAD's mat4 is column-major
|
|
253
279
|
const toMat4 = (r) => [r[0], r[4], r[8], 0, r[1], r[5], r[9], 0, r[2], r[6], r[10], 0, r[3], r[7], r[11], 1];
|
|
@@ -321,7 +347,7 @@ function motionOf(a, placed, num, ref) {
|
|
|
321
347
|
// A repeated item turns as a whole about its at: each copy's offset turns with it (keys on a tilted plate)
|
|
322
348
|
return [c.id, ...rows(translate(base, rotate(rot, translate([c.offset[0], c.offset[1], 0], jscad.geometries.geom3.create()))).transforms)];
|
|
323
349
|
});
|
|
324
|
-
const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).map(([id, v]) => {
|
|
350
|
+
const poses = Object.fromEntries(Object.entries(a.poses || {}).map(([n, set]) => [n, Object.fromEntries(Object.entries(set).filter(([id]) => !id.includes('.')).map(([id, v]) => {
|
|
325
351
|
if (!joints.some((j) => j.id === id)) throw new Error(`pose ${n}: no joint "${id}"`);
|
|
326
352
|
return [id, Array.isArray(v) ? v.map(num) : num(v)];
|
|
327
353
|
}))]));
|
package/lib/clone.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// cad clone: a published circuit board (a KiCad .kicad_pcb, a file or a GitHub link) into a rule set, so designs can
|
|
2
|
+
// redraw it by rules. The rule set keeps the circuit (parts, pads, nets, planes, outline) with where it came from and
|
|
3
|
+
// its licence, and a few numbers designs start from (size, thickness, copper layers), each traced to the source.
|
|
4
|
+
// Nothing from the file is ever run: it is read as data.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
const nodePath = path;
|
|
8
|
+
import { WS } from './workspace.mjs';
|
|
9
|
+
import { pcbEngine } from './design.mjs';
|
|
10
|
+
|
|
11
|
+
const today = () => new Date().toISOString().slice(0, 10);
|
|
12
|
+
// Licences that ask boards made from the source to stay under them (or forbid that use): said when cloning
|
|
13
|
+
export const reciprocal = (s) => /CERN-OHL-S|CERN Open Hardware Licence Version 2 - Strongly|GPL|share-?alike|\bSA\b/i.test(String(s || ''));
|
|
14
|
+
export const limiting = (s) => /\b(NC|ND)\b|non-?commercial|no-?deriv/i.test(String(s || ''));
|
|
15
|
+
|
|
16
|
+
// A GitHub file link (github.com/<owner>/<repo>/blob/<ref>/<path>) -> { owner, repo, ref, file }, else null
|
|
17
|
+
export function githubFile(link) {
|
|
18
|
+
const m = String(link).match(/^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/(?:blob|raw)\/([^/]+)\/(.+\.kicad_pcb)$/);
|
|
19
|
+
return m ? { owner: m[1], repo: m[2], ref: m[3], file: decodeURIComponent(m[4]) } : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function getJSON(url) {
|
|
23
|
+
const r = await fetch(url, { headers: { accept: 'application/vnd.github+json', 'user-agent': 'rulecad' } });
|
|
24
|
+
if (!r.ok) throw new Error(`GitHub said ${r.status} for ${url}`);
|
|
25
|
+
return r.json();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// The board's text and what to record about it: from a GitHub link, pinned to the commit the link names (a branch is
|
|
29
|
+
// looked up), with the repository's licence; from a file, what --source and --licence say
|
|
30
|
+
async function fetchBoard(ref, o) {
|
|
31
|
+
const gh = githubFile(ref);
|
|
32
|
+
if (!gh) {
|
|
33
|
+
if (!fs.existsSync(ref)) throw new Error(`no file ${ref}: give a .kicad_pcb file, or a GitHub link to one (https://github.com/<owner>/<repo>/blob/<branch>/<path>.kicad_pcb)`);
|
|
34
|
+
return { text: fs.readFileSync(ref, 'utf8'), source: o.source || path.basename(ref), licence: o.licence || null, dir: path.dirname(path.resolve(ref)) };
|
|
35
|
+
}
|
|
36
|
+
const base = `https://api.github.com/repos/${gh.owner}/${gh.repo}`;
|
|
37
|
+
const commit = (await getJSON(`${base}/commits/${encodeURIComponent(gh.ref)}`)).sha;
|
|
38
|
+
const raw = await fetch(`https://raw.githubusercontent.com/${gh.owner}/${gh.repo}/${commit}/${gh.file.split('/').map(encodeURIComponent).join('/')}`);
|
|
39
|
+
if (!raw.ok) throw new Error(`couldn't download ${gh.file} at ${commit.slice(0, 7)} (${raw.status})`);
|
|
40
|
+
let licence = o.licence || null;
|
|
41
|
+
if (!licence) {
|
|
42
|
+
const l = await getJSON(`${base}/license?ref=${commit}`).catch(() => null);
|
|
43
|
+
const first = l?.content ? Buffer.from(l.content, 'base64').toString('utf8').split('\n').map((s) => s.trim()).find(Boolean) : null;
|
|
44
|
+
licence = l?.license?.spdx_id && l.license.spdx_id !== 'NOASSERTION' ? l.license.spdx_id : first;
|
|
45
|
+
}
|
|
46
|
+
return { text: await raw.text(), source: `https://github.com/${gh.owner}/${gh.repo}/blob/${commit}/${gh.file}`, licence, commit, github: { ...gh, commit } };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ---- the parts' 3D models ----
|
|
50
|
+
// KiCad's own library, by the version its path variable names (6 and later name it; older boards say KISYS3DMOD)
|
|
51
|
+
const KICAD = { 6: '6.0.11', 7: '7.0.11', 8: '8.0.8' };
|
|
52
|
+
const KICAD_LICENCE = 'CC-BY-SA-4.0 with the KiCad libraries exception (designs using the models aren\'t bound by it)';
|
|
53
|
+
const fetchText = async (url) => { const r = await fetch(url); if (!r.ok) throw new Error(`${r.status} for ${url}`); return r.text(); };
|
|
54
|
+
|
|
55
|
+
// Where a model's file comes from: { url, licence } (or { file } for a board read from a file), or null
|
|
56
|
+
async function modelSource(path, got) {
|
|
57
|
+
const kicad = path.match(/^\$\{(?:KICAD(\d+)_3DMODEL_DIR|KISYS3DMOD)\}\/(.+)$/);
|
|
58
|
+
if (kicad) return { url: `https://gitlab.com/kicad/libraries/kicad-packages3D/-/raw/${KICAD[kicad[1]] ?? KICAD[6]}/${kicad[2]}`, licence: KICAD_LICENCE, kicad: true };
|
|
59
|
+
const own = path.match(/^\$\{KIPRJMOD\}\/(.+)$/);
|
|
60
|
+
if (!own) return null;
|
|
61
|
+
if (!got.github) return got.dir ? { file: nodePath.resolve(got.dir, own[1]) } : null;
|
|
62
|
+
// In the source's repository, next to its board; a path into a submodule goes on in the submodule's repository
|
|
63
|
+
const { owner, repo, commit, file } = got.github, parts = nodePath.posix.normalize(nodePath.posix.join(nodePath.posix.dirname(file), own[1])).split('/');
|
|
64
|
+
const api = (o, r, x) => getJSON(`https://api.github.com/repos/${o}/${r}/${x}`);
|
|
65
|
+
const top = await api(owner, repo, `contents/${encodeURIComponent(parts[0])}?ref=${commit}`).catch(() => null);
|
|
66
|
+
const licenceOf = async (o, r) => (await api(o, r, 'license').catch(() => null))?.license?.spdx_id;
|
|
67
|
+
if (top?.type === 'submodule') {
|
|
68
|
+
const m = top.submodule_git_url.match(/github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/);
|
|
69
|
+
if (!m) return null;
|
|
70
|
+
const lic = await licenceOf(m[1], m[2]);
|
|
71
|
+
return { url: `https://raw.githubusercontent.com/${m[1]}/${m[2]}/${top.sha}/${parts.slice(1).join('/')}`, licence: lic && lic !== 'NOASSERTION' ? lic : null };
|
|
72
|
+
}
|
|
73
|
+
return { url: `https://raw.githubusercontent.com/${owner}/${repo}/${commit}/${parts.join('/')}`, licence: got.licence };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Each model the circuit's parts name, fetched once into the workspace's models/ (a mesh, where its licence lets it be
|
|
77
|
+
// shared and it comes as VRML) or kept as its size (a STEP file, or a shape with no licence): circuit.models[path]
|
|
78
|
+
async function fetchModels(circuit, got, { wrlMesh, stepBounds }, notes) {
|
|
79
|
+
const out = {}, paths = [...new Set(circuit.parts.filter((p) => p.model).map((p) => p.model.path))];
|
|
80
|
+
for (const path of paths) {
|
|
81
|
+
try {
|
|
82
|
+
const src = await modelSource(path, got);
|
|
83
|
+
if (!src) { notes.push(`no 3D model for ${path}: its path isn't one cad clone can follow`); continue; }
|
|
84
|
+
const name = path.split('/').pop().replace(/\.(step|stp|wrl)$/i, ''), dir = src.kicad ? `kicad/${path.split('/').slice(-2, -1)[0]}` : 'source';
|
|
85
|
+
const read = (ext) => (src.file ? fs.promises.readFile(src.file.replace(/\.[^.]+$/, ext), 'utf8') : fetchText(src.url.replace(/\.[^./]+$/, ext)));
|
|
86
|
+
if (src.licence || src.file) { // VRML where there is one (KiCad's library has both): a mesh
|
|
87
|
+
const wrl = /\.wrl$/i.test(path) || src.kicad ? await read('.wrl').catch(() => null) : null;
|
|
88
|
+
if (wrl) {
|
|
89
|
+
const triangles = wrlMesh(wrl).map((t) => t.map((v) => v.map((n) => Math.round(n * 1e3) / 1e3)));
|
|
90
|
+
const file = `models/${dir}/${name}.json`;
|
|
91
|
+
fs.mkdirSync(nodePath.join(WS, nodePath.dirname(file)), { recursive: true });
|
|
92
|
+
fs.writeFileSync(nodePath.join(WS, file), JSON.stringify({ source: src.url || src.file, licence: src.licence, triangles }));
|
|
93
|
+
out[path] = { mesh: file, licence: src.licence };
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const step = await read(nodePath.extname(path) || '.step').catch(() => read('.step'));
|
|
98
|
+
const box = stepBounds(step);
|
|
99
|
+
if (!box) { notes.push(`no 3D model for ${name}: its file has no points to measure`); continue; }
|
|
100
|
+
out[path] = { box, ...(src.licence ? { licence: src.licence } : {}), size_only: src.licence ? 'a STEP model: drawn as the box round it' : 'no licence: only its size is used, drawn as a box' };
|
|
101
|
+
} catch (e) { notes.push(`no 3D model for ${path.split('/').pop()}: ${e.message}`); }
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* cad clone <board.kicad_pcb | GitHub link> <name>: writes rules/<name>.json and prints what it found, what boards here
|
|
108
|
+
* can't carry yet, and what the licence asks. o: { source, licence, force }.
|
|
109
|
+
*/
|
|
110
|
+
export async function cloneBoard(ref, name, o = {}) {
|
|
111
|
+
if (!ref || !/^[a-z][a-z0-9_]*$/.test(name || '')) throw new Error('usage: cad clone <board.kicad_pcb | GitHub link> <name> [--source <link>] [--licence <licence>] [--force] (name: lower case, digits and _)');
|
|
112
|
+
const to = path.join(WS, 'rules', `${name}.json`);
|
|
113
|
+
if (fs.existsSync(to) && !o.force) throw new Error(`rules/${name}.json already exists (--force to replace it)`);
|
|
114
|
+
const { fromKicadPcb, clone, learnPlacement, wrlMesh, stepBounds } = await pcbEngine();
|
|
115
|
+
if (!learnPlacement) throw new Error('cad clone needs @rulecad/pcb 0.3.8 or later: npm install @rulecad/pcb@latest');
|
|
116
|
+
const got = await fetchBoard(ref, o);
|
|
117
|
+
const circuit = fromKicadPcb(got.text);
|
|
118
|
+
circuit.source = { ...circuit.source, from: got.source, ...(got.commit ? { commit: got.commit } : {}), read: today() };
|
|
119
|
+
circuit.placement = learnPlacement(circuit); // which small parts stay by which pins: edit max to be stricter or freer
|
|
120
|
+
const modelNotes = [];
|
|
121
|
+
if (!o.noModels && wrlMesh) circuit.models = await fetchModels(circuit, got, { wrlMesh, stepBounds }, modelNotes);
|
|
122
|
+
const extra = { kind: 'derived', source: got.source, ...(got.licence ? { licence: got.licence } : {}), checked: today() };
|
|
123
|
+
const rule = (value, unit, text) => ({ value, ...(unit ? { unit } : {}), rule: text, ...extra });
|
|
124
|
+
const rules = {
|
|
125
|
+
width: rule(circuit.width, 'mm', 'The source board\'s width, across its outline'),
|
|
126
|
+
height: rule(circuit.height, 'mm', 'The source board\'s height, across its outline'),
|
|
127
|
+
layers: rule(circuit.layers, null, `Copper layers on the source board (${circuit.copper.join(', ')})`)
|
|
128
|
+
};
|
|
129
|
+
if (circuit.thickness) rules.thickness = rule(circuit.thickness, 'mm', 'The source board\'s thickness');
|
|
130
|
+
const doc = `Cloned from ${got.source} by cad clone: the circuit of a published board (its parts, pads, nets, planes and outline), for @rulecad/pcb's clone() to redraw by rules.${got.licence ? ` Licence: ${got.licence}.` : ' Licence unknown: find it before sharing anything made from this.'}${reciprocal(got.licence) ? ' Boards made from it must be shared under the same licence, with their design files.' : ''}`;
|
|
131
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
132
|
+
fs.writeFileSync(to, `${JSON.stringify({ _doc: doc, name, ...(got.licence ? { licence: got.licence } : {}), rules, circuit }, null, 1)}\n`);
|
|
133
|
+
|
|
134
|
+
const nets = Object.keys(circuit.nets).length, planes = Object.keys(circuit.planes);
|
|
135
|
+
console.log(`made ${path.relative(process.cwd(), to)}: ${circuit.parts.length} parts, ${nets} nets, ${circuit.width} × ${circuit.height} mm, ${circuit.layers} copper layers${planes.length ? `, planes ${planes.join(' ')}` : ''}`);
|
|
136
|
+
console.log(` from ${got.source}`);
|
|
137
|
+
console.log(` placement: ${circuit.placement.length} small parts kept near the pins they serve (circuit.placement: edit max to change how near)`);
|
|
138
|
+
if (circuit.models) {
|
|
139
|
+
const all = Object.values(circuit.models), boxes = all.filter((m) => m.box).length;
|
|
140
|
+
console.log(` 3D models: ${all.length - boxes} as meshes (in models/), ${boxes} as boxes the size of the part${all.some((m) => /no licence/.test(m.size_only || '')) ? ' (some have no licence: only their size is used)' : ''}`);
|
|
141
|
+
}
|
|
142
|
+
for (const n of modelNotes) console.log(` note: ${n}`);
|
|
143
|
+
if (!circuit.outline) console.log(' note: the outline isn\'t one closed shape: designs get its bounds');
|
|
144
|
+
for (const n of clone(circuit).notes) console.log(` note: ${n}`);
|
|
145
|
+
if (!got.licence) console.log(' ! no licence given (--licence): find the source\'s licence before sharing anything made from it');
|
|
146
|
+
else if (limiting(got.licence)) console.log(` ! licence "${got.licence}" limits what you may make from this: read it before using the circuit`);
|
|
147
|
+
else if (reciprocal(got.licence)) console.log(` ! licence "${got.licence}" is reciprocal: boards made from this must be shared under it too, with their design files. Keep this rule set apart from rules under other licences`);
|
|
148
|
+
console.log(` use it in a board: clone(v.${name}.circuit) from @rulecad/pcb gives the parts and nets, each where the source put it`);
|
|
149
|
+
return { to, circuit };
|
|
150
|
+
}
|
package/lib/design.mjs
CHANGED
|
@@ -10,13 +10,15 @@
|
|
|
10
10
|
// keyboard/keycap:oem-r3. Versions are the design over time; variants are alternatives that exist side by side.
|
|
11
11
|
// Layouts: a "type": "layout" variable picks a file in the project's layouts/; the design gets every layout it can pick
|
|
12
12
|
// as v.layouts[name] = { …the file, keys (each key's centre and properties), width, depth } (lib/layout.mjs).
|
|
13
|
-
// Boards: "engine": "pcb" in the .json makes main(v) return a tscircuit board ({ board, matrix }, built with v.pcb, as
|
|
13
|
+
// Boards: "engine": "pcb" in the .json makes main(v) return a tscircuit board ({ board, matrix, clone }, built with v.pcb, as
|
|
14
14
|
// @rulecad/pcb describes); the build then carries its Circuit JSON (circuit) and matrix, and one part: the bare board
|
|
15
15
|
// (its copper is in the 2D views).
|
|
16
|
-
// Builds are cached in .cache/builds/, by everything they're made from (CAD_NO_CACHE=1 to skip)
|
|
17
|
-
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
16
|
+
// Builds are cached in .cache/builds/, by everything they're made from (CAD_NO_CACHE=1 to skip), and a lamina's slow
|
|
17
|
+
// stages apart in .cache/stages/ (see stageStore).
|
|
18
|
+
import { spawnSync } from 'node:child_process';
|
|
19
|
+
import { located, lineOf } from './errors.mjs';
|
|
20
|
+
import { host, readJson } from './host.mjs';
|
|
21
|
+
import { named, faces, fromFaces, polygons, unpack, watch } from './parts.mjs';
|
|
20
22
|
import { runSandboxed, sandboxed } from './sandbox.mjs';
|
|
21
23
|
export { polygons };
|
|
22
24
|
import fs from 'node:fs';
|
|
@@ -29,6 +31,7 @@ import { WS, paths, printerOf } from './workspace.mjs';
|
|
|
29
31
|
import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
|
|
30
32
|
import { optimised, forDesign } from './optimise.mjs';
|
|
31
33
|
import * as shapes from '@rulecad/shapes';
|
|
34
|
+
import * as flexures from '@rulecad/flexures';
|
|
32
35
|
import { engineId, packageVersion, materialise } from './versions.mjs';
|
|
33
36
|
import { satisfies } from '@rulecad/versions';
|
|
34
37
|
|
|
@@ -72,7 +75,7 @@ export async function objectSets(d, object) {
|
|
|
72
75
|
const units = Object.fromEntries(Object.entries(b.object.variables || {}).map(([k, x]) => [k, x.unit]));
|
|
73
76
|
const rules = {};
|
|
74
77
|
for (const [k, v] of Object.entries(b.values)) if (typeof v === 'number' && Number.isFinite(v)) {
|
|
75
|
-
rules[k] = { value: v, unit: units[k]
|
|
78
|
+
rules[k] = { value: v, ...(units[k] ? { unit: units[k] } : {}), rule: `${ref}'s ${k}`, kind: 'design', source: `${ref}@${version}` }; // no unit: a count (turns, segments), not a length
|
|
76
79
|
}
|
|
77
80
|
sets[u] = { name: base.name, rules };
|
|
78
81
|
if (b.circuit) { const e = await pcbEngine(), board = b.circuit.find((x) => x.type === 'pcb_board'); extra[base.name] = { board_holes: e.holes(b.circuit), board_parts: e.parts ? e.parts(b.circuit) : {}, ...(board.outline ? { board_outline: board.outline } : {}) }; }
|
|
@@ -95,8 +98,15 @@ export async function problemsOf(d, object, values) {
|
|
|
95
98
|
const out = {};
|
|
96
99
|
for (const [name, v] of Object.entries(object.variables || {})) if (v.type === 'problem') {
|
|
97
100
|
const ref = values[name];
|
|
101
|
+
if (!ref || ref === 'none') continue; // a variant that draws without the optimiser (a test rig, or the regions a problem reads)
|
|
98
102
|
if (!out[ref]) {
|
|
99
|
-
|
|
103
|
+
// Optimising here can take an hour on a big solid: say so, why, and (on a terminal) how far it's got
|
|
104
|
+
const live = process.stderr.isTTY;
|
|
105
|
+
const r = await optimised(d.project, ref, {
|
|
106
|
+
onRun: (why) => console.error(`optimising ${ref} (${why}; the result is kept until the problem or the solver changes)…`),
|
|
107
|
+
onStep: (s) => { if (live) process.stderr.write(`\r\x1b[Koptimising ${ref}: step ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm`); if (s.step === s.steps && live) process.stderr.write('\r\x1b[K'); },
|
|
108
|
+
});
|
|
109
|
+
if (live) process.stderr.write('\r\x1b[K');
|
|
100
110
|
out[ref] = forDesign(r);
|
|
101
111
|
}
|
|
102
112
|
}
|
|
@@ -111,12 +121,25 @@ export function variantSet(d, object, set = {}) {
|
|
|
111
121
|
return { ...v, ...set };
|
|
112
122
|
}
|
|
113
123
|
|
|
114
|
-
const CACHE = paths.cache('builds'), CACHE_VERSION =
|
|
124
|
+
const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
|
|
115
125
|
const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
|
|
116
126
|
// What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
|
|
117
127
|
// boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
|
|
118
|
-
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes')));
|
|
119
|
-
|
|
128
|
+
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures')));
|
|
129
|
+
// (every module of a helper package but its tests: they change nothing a design builds)
|
|
130
|
+
const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs').sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
|
|
131
|
+
const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
|
|
132
|
+
const own = source(import.meta.url) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(feaDir) + packageVersion('@jscad/modeling'); // every shapes module, not just its entry
|
|
133
|
+
// A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
|
|
134
|
+
// and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
|
|
135
|
+
// at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
|
|
136
|
+
const STAGES = paths.cache('stages'), stageSalt = crypto.createHash('sha256').update(helperSources(flexuresDir) + helperSources(feaDir)).digest('hex');
|
|
137
|
+
const stageStore = () => ({
|
|
138
|
+
salt: stageSalt,
|
|
139
|
+
get: (k) => { const f = path.join(STAGES, `${k}.json`); if (process.env.CAD_NO_CACHE || !host.exists(f)) return undefined; try { host.touch(f); } catch {} return host.readText(f); }, // (CAD_NO_CACHE: computed afresh, and kept)
|
|
140
|
+
put: (k, text) => { try { prune(STAGES, STAGES_KEEP); host.writeText(path.join(STAGES, `${k}.json`), text); } catch {} }, // (a cache that can't be written is only slower)
|
|
141
|
+
});
|
|
142
|
+
const STAGES_KEEP = 60; // (a launcher's physics is 5 MB, its probe 9)
|
|
120
143
|
export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
|
|
121
144
|
if (e.code === 'ERR_MODULE_NOT_FOUND' && /@rulecad\/pcb/.test(e.message)) throw new Error('boards need the board engine: npm install @rulecad/pcb');
|
|
122
145
|
throw e;
|
|
@@ -128,12 +151,22 @@ export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
|
|
|
128
151
|
export const booleans = (object) => (object.engine === 'manifold' ? 'manifold' : object.engine === 'pcb' ? 'jscad' : process.env.CAD_ENGINE || 'jscad');
|
|
129
152
|
|
|
130
153
|
export const readObject = (d) => {
|
|
131
|
-
const o =
|
|
154
|
+
const o = readJson(d.json);
|
|
132
155
|
if (o.display && !o.mirror) o.mirror = o.display;
|
|
133
156
|
for (const p of Object.values(o.parts || {})) if (p.display === false) p.mirror = false;
|
|
134
157
|
return o;
|
|
135
158
|
};
|
|
136
159
|
|
|
160
|
+
// A design that doesn't parse: JavaScript's own error says what it met but not where, so ask Node to check the file
|
|
161
|
+
// and add the line it stopped at
|
|
162
|
+
function syntaxAt(e, d) {
|
|
163
|
+
if (e?.name !== 'SyntaxError' || e.line || host.name !== 'node') return e;
|
|
164
|
+
const r = spawnSync(process.execPath, ['--check', d.js], { encoding: 'utf8' });
|
|
165
|
+
const m = r.status ? String(r.stderr).match(/^(?:file:\/\/)?.*?:(\d+)\r?\n(.*)\r?\n/) : null;
|
|
166
|
+
if (m) { e.line = Number(m[1]); e.message = `${e.message}: ${m[2].trim()}`; }
|
|
167
|
+
return e;
|
|
168
|
+
}
|
|
169
|
+
|
|
137
170
|
// build(design, set, { mirror }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export) }
|
|
138
171
|
// parts: [{ name, role, label, geometry, polygons, triangles }]; polygons and triangles: every part together
|
|
139
172
|
export async function build(d, set = {}, { mirror = false } = {}) {
|
|
@@ -154,9 +187,12 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
154
187
|
const problems = await problemsOf(d, object, values);
|
|
155
188
|
if (Object.keys(problems).length) values.problems = problems;
|
|
156
189
|
|
|
157
|
-
// The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether
|
|
190
|
+
// The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether.
|
|
191
|
+
// What the design reads of its .json is its values, resolved, and its parts' names and roles: a rule's words, a
|
|
192
|
+
// label, a note or the version change nothing it builds, so they aren't in the key
|
|
158
193
|
const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
|
|
159
|
-
const
|
|
194
|
+
const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
|
|
195
|
+
const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
|
|
160
196
|
const hit = path.join(CACHE, `${key}.json`);
|
|
161
197
|
if (!process.env.CAD_NO_CACHE && host.exists(hit)) {
|
|
162
198
|
const c = JSON.parse(host.readText(hit));
|
|
@@ -164,51 +200,57 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
164
200
|
for (const e of entries) if (c.used.includes(e.name)) e.used = true;
|
|
165
201
|
const parts = c.parts.map(({ solid: f, ...p }) => ({ ...p, geometry: fromFaces(f) }));
|
|
166
202
|
if (c.circuit) Object.assign(values, (await pcbEngine()).outputs(c.circuit, c.matrix));
|
|
167
|
-
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: key, ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix } : {}) };
|
|
203
|
+
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: key, ...(c.mechanism ? { mechanism: c.mechanism } : {}), ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}) };
|
|
168
204
|
}
|
|
169
205
|
|
|
170
206
|
// A JSCAD design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach
|
|
171
207
|
// the network) unless the workspace trusts its designs; a board design runs here, with the board engine
|
|
172
208
|
const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
|
|
173
|
-
let parts, board = null, read;
|
|
174
|
-
|
|
209
|
+
let parts, board = null, read, mechanism = null;
|
|
210
|
+
const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
|
|
211
|
+
const stages = stageStore();
|
|
212
|
+
if (!pcb && sandboxed() && host.name === 'node') ({ parts, read, mechanism } = await runSandboxed(d, values, object.parts || {}, booleans(object), optional, stages).catch((e) => { throw syntaxAt(e, d); }));
|
|
175
213
|
else {
|
|
214
|
+
flexures.laminaCache(stages);
|
|
176
215
|
const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
|
|
177
216
|
// Designs import JSCAD themselves, so it has to be installed where they are (it's the workspace's dependency)
|
|
178
217
|
if (e.code === 'ERR_MODULE_NOT_FOUND' && /@jscad\/modeling/.test(e.message)) throw new Error(`designs need JSCAD in the workspace: npm install @jscad/modeling (in ${WS})`);
|
|
179
218
|
if (/import statement outside a module/.test(e.message)) throw new Error(`designs are ES modules: set "type": "module" in ${path.join(WS, 'package.json')}`);
|
|
180
|
-
throw e;
|
|
219
|
+
throw syntaxAt(located(e, d.js, 'design.run'), d);
|
|
181
220
|
});
|
|
182
221
|
if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
|
|
183
|
-
|
|
184
|
-
read =
|
|
185
|
-
const watched = Object.fromEntries(Object.entries(values).map(([k, v]) => [k, v && typeof v === 'object'
|
|
186
|
-
? new Proxy(v, { get: (t, r) => { if (typeof r === 'string' && r in t) read.add(`${k}.${r}`); return t[r]; } }) : v]));
|
|
187
|
-
watched.shapes = shapes; watched.ops = await shapes.ops(booleans(object)); if (pcb) watched.pcb = pcb;
|
|
222
|
+
const w = watch(values, { shapes, flexures, ops: await shapes.ops(booleans(object)), ...(pcb ? { pcb } : {}) }, optional);
|
|
223
|
+
read = w.read;
|
|
188
224
|
let made;
|
|
189
|
-
try { made = await mod.main(
|
|
225
|
+
try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
|
|
190
226
|
if (object.engine === 'pcb') { // a circuit board: tscircuit builds it, and the bare board is its one part
|
|
191
|
-
const { board: b, matrix } = made && made.board ? made : { board: made };
|
|
192
|
-
board = { circuit: await pcb.render(b), ...(matrix ? { matrix } : {}) };
|
|
227
|
+
const { board: b, matrix, clone } = made && made.board ? made : { board: made }; // clone: a cloned board's { circuit, arranged }, for its checks
|
|
228
|
+
board = { circuit: await pcb.render(b), ...(matrix ? { matrix } : {}), ...(clone ? { source: clone } : {}) };
|
|
193
229
|
Object.assign(values, pcb.outputs(board.circuit, matrix)); // what it tells the parts around it: outline, Pico
|
|
194
|
-
|
|
230
|
+
// the parts' 3D models: meshes cad clone fetched into the workspace's models/ (a design never reads files; cad does)
|
|
231
|
+
const meshes = {};
|
|
232
|
+
for (const c of board.circuit.filter((e) => e.type === 'cad_component' && e.rulecad_model?.mesh)) {
|
|
233
|
+
const f = c.rulecad_model.mesh;
|
|
234
|
+
if (!(f in meshes)) meshes[f] = host.exists(path.join(WS, f)) ? JSON.parse(host.readText(path.join(WS, f))).triangles : null;
|
|
235
|
+
}
|
|
236
|
+
made = pcb.solids(board.circuit, { thickness: values.thickness, smooth: values.smooth, models: meshes });
|
|
195
237
|
}
|
|
196
|
-
parts = named(made, object.parts || {});
|
|
238
|
+
try { parts = named(made, object.parts || {}); } catch (e) { throw located(e, d.js, 'design.run'); }
|
|
197
239
|
}
|
|
198
240
|
for (const e of entries) if (read.has(e.name)) e.used = true;
|
|
199
241
|
try {
|
|
200
242
|
prune();
|
|
201
|
-
host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}) }));
|
|
243
|
+
host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}) }));
|
|
202
244
|
} catch {} // a cache that can't be written is only slower
|
|
203
|
-
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: key, ...(board || {}) };
|
|
245
|
+
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: key, ...(board || {}), ...(mechanism ? { mechanism } : {}) };
|
|
204
246
|
}
|
|
205
247
|
|
|
206
|
-
//
|
|
248
|
+
// A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
|
|
207
249
|
const CACHE_KEEP = 800;
|
|
208
|
-
function prune() {
|
|
250
|
+
function prune(dir = CACHE, keep = CACHE_KEEP) {
|
|
209
251
|
if (Math.random() > 0.05) return; // now and then is enough
|
|
210
|
-
const files = host.list(
|
|
211
|
-
for (const { p } of files.slice(
|
|
252
|
+
const files = host.list(dir).map((f) => { const p = path.join(dir, f); return { p, t: host.mtime(p) }; }).sort((a, b) => b.t - a.t);
|
|
253
|
+
for (const { p } of files.slice(keep)) host.remove(p);
|
|
212
254
|
}
|
|
213
255
|
|
|
214
256
|
// The rules of the printer a build is checked against (the project's, else the workspace's), resolved
|
package/lib/errors.mjs
CHANGED
|
@@ -21,5 +21,23 @@ export function located(e, file, code) {
|
|
|
21
21
|
return e;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
-
/** An error as plain data: { code, message, file?, path? }. @param {any} e */
|
|
25
|
-
export const errorData = (e) => ({ code: e?.code || 'error', message: e?.message || String(e), ...(e?.file ? { file: e.file } : {}), ...(e?.path ? { path: e.path } : {}) });
|
|
24
|
+
/** An error as plain data: { code, message, file?, line?, path? }. @param {any} e */
|
|
25
|
+
export const errorData = (e) => ({ code: e?.code || 'error', message: e?.message || String(e), ...(e?.file ? { file: e.file } : {}), ...(e?.line ? { line: e.line } : {}), ...(e?.path ? { path: e.path } : {}) });
|
|
26
|
+
|
|
27
|
+
/** The closest name to a typo, one or two letters out, or null. @param {string} word @param {string[]} names */
|
|
28
|
+
export function near(word, names) {
|
|
29
|
+
const d = (a, b) => { const m = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]); for (let j = 1; j <= b.length; j++) m[0][j] = j;
|
|
30
|
+
for (let i = 1; i <= a.length; i++) for (let j = 1; j <= b.length; j++) m[i][j] = Math.min(m[i - 1][j] + 1, m[i][j - 1] + 1, m[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)); return m[a.length][b.length]; };
|
|
31
|
+
const best = names.map((n) => [n, d(word, n)]).sort((x, y) => x[1] - y[1])[0];
|
|
32
|
+
return best && best[1] <= 2 ? best[0] : null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The line of a module an error was thrown from, read from its stack, or null. @param {any} e @param {string} href the module's file: URL */
|
|
36
|
+
export function lineOf(e, href) {
|
|
37
|
+
const at = href.split('?')[0];
|
|
38
|
+
for (const l of String(e?.stack || '').split('\n')) {
|
|
39
|
+
const m = l.match(/(file:\/\/[^\s)]+?)(?:\?[^\s:)]*)?:(\d+):\d+\)?$/);
|
|
40
|
+
if (m && m[1] === at) return Number(m[2]);
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
package/lib/host.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import fs from 'node:fs';
|
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { createRequire } from 'node:module';
|
|
10
10
|
import { pathToFileURL } from 'node:url';
|
|
11
|
+
import { CadError } from './errors.mjs';
|
|
11
12
|
|
|
12
13
|
/** Node's file system. */
|
|
13
14
|
export const nodeHost = {
|
|
@@ -28,6 +29,12 @@ export const host = new Proxy({}, { get: (_, k) => current[k] });
|
|
|
28
29
|
/** Use another host (until the returned function is called). @param {Partial<typeof nodeHost>} h @returns {() => void} */
|
|
29
30
|
export function useHost(h) { const before = current; current = { ...nodeHost, ...h }; return () => { current = before; }; }
|
|
30
31
|
|
|
32
|
+
/** A JSON file, read through the host. One that doesn't parse is named, with where it stops. @param {string} f */
|
|
33
|
+
export function readJson(f) {
|
|
34
|
+
const text = host.readText(f);
|
|
35
|
+
try { return JSON.parse(text); } catch (e) { throw new CadError('json', `not valid JSON: ${e.message}`, { file: f, cause: e }); }
|
|
36
|
+
}
|
|
37
|
+
|
|
31
38
|
/**
|
|
32
39
|
* A workspace in memory: { [path]: text } under root. Reads outside root come from disk (the tool, its rule sets);
|
|
33
40
|
* writes stay in memory. A design module is loaded from its text, its imports of @jscad/modeling and @rulecad/shapes
|
package/lib/jsonedit.mjs
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
// Where every value is: [{ path: ['variables', 'w', 'value'], start, end }], in the order they appear
|
|
6
6
|
function spans(text) {
|
|
7
|
+
// (the scanner below takes the text to be JSON: one that isn't would send it past the end, so that's settled first)
|
|
8
|
+
try { JSON.parse(text); } catch (e) { throw Object.assign(new Error(`not valid JSON, so it can't be edited: ${e.message}`), { code: 'json' }); }
|
|
7
9
|
const out = [];
|
|
8
10
|
let i = 0;
|
|
9
11
|
const ws = () => { while (i < text.length && /\s/.test(text[i])) i++; };
|
|
@@ -30,13 +32,16 @@ const same = (a, b) => a.length === b.length && a.every((x, k) => x === b[k]);
|
|
|
30
32
|
const find = (text, path) => spans(text).find((s) => same(s.path, path));
|
|
31
33
|
// The indentation of the line a position is on
|
|
32
34
|
const indentAt = (text, at) => { const line = text.lastIndexOf('\n', at - 1) + 1; return /^[ \t]*/.exec(text.slice(line))[0]; };
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
|
|
35
|
+
// How the file is laid out: its line ending, and what one level of indentation is (two spaces, unless its first
|
|
36
|
+
// indented line says otherwise: a tab, four spaces)
|
|
37
|
+
const styleOf = (text) => ({ eol: text.includes('\r\n') ? '\r\n' : '\n', unit: (/\n([ \t]+)\S/.exec(text) || [null, ' '])[1] });
|
|
38
|
+
// A value as JSON, laid out like the file (from the given indentation); short arrays of numbers and expressions stay
|
|
39
|
+
// on one line, as people write them
|
|
40
|
+
function render(v, indent, style) {
|
|
36
41
|
if (Array.isArray(v) && v.every((x) => typeof x !== 'object' || x === null) && JSON.stringify(v).length <= 80) return `[${v.map((x) => JSON.stringify(x)).join(', ')}]`;
|
|
37
|
-
const inner = `${indent}
|
|
38
|
-
if (Array.isArray(v)) return v.length ? `[
|
|
39
|
-
if (v && typeof v === 'object') { const e = Object.entries(v); return e.length ? `{
|
|
42
|
+
const inner = `${indent}${style.unit}`, { eol } = style;
|
|
43
|
+
if (Array.isArray(v)) return v.length ? `[${eol}${v.map((x) => `${inner}${render(x, inner, style)}`).join(`,${eol}`)}${eol}${indent}]` : '[]';
|
|
44
|
+
if (v && typeof v === 'object') { const e = Object.entries(v); return e.length ? `{${eol}${e.map(([k, x]) => `${inner}${JSON.stringify(k)}: ${render(x, inner, style)}`).join(`,${eol}`)}${eol}${indent}}` : '{}'; }
|
|
40
45
|
return JSON.stringify(v);
|
|
41
46
|
}
|
|
42
47
|
|
|
@@ -52,7 +57,7 @@ export function getAt(text, path) {
|
|
|
52
57
|
*/
|
|
53
58
|
export function setAt(text, path, value) {
|
|
54
59
|
const s = find(text, path);
|
|
55
|
-
if (s) return text.slice(0, s.start) + render(value, indentAt(text, s.start)) + text.slice(s.end);
|
|
60
|
+
if (s) return text.slice(0, s.start) + render(value, indentAt(text, s.start), styleOf(text)) + text.slice(s.end);
|
|
56
61
|
const parent = find(text, path.slice(0, -1));
|
|
57
62
|
if (!parent) throw Object.assign(new Error(`no ${path.slice(0, -1).join('.') || 'top level'} to add ${path.at(-1)} to`), { code: 'edit.path' });
|
|
58
63
|
const body = text.slice(parent.start, parent.end);
|
|
@@ -76,9 +81,10 @@ function insert(text, s, key, value) {
|
|
|
76
81
|
const members = spans(text).filter((x) => x.path.length === s.path.length + 1 && same(x.path.slice(0, -1), s.path)).sort((a, b) => a.start - b.start);
|
|
77
82
|
const last = members.at(-1), multi = empty || inner.includes('\n');
|
|
78
83
|
const first = members.length ? text.lastIndexOf('\n', members[0].start) : -1;
|
|
79
|
-
const
|
|
80
|
-
const
|
|
81
|
-
|
|
84
|
+
const style = styleOf(text), { eol } = style;
|
|
85
|
+
const indent = empty ? `${outer}${style.unit}` : multi ? /^[ \t]*/.exec(text.slice(first + 1))[0] : outer;
|
|
86
|
+
const piece = `${key}${render(value, indent, style)}`;
|
|
87
|
+
if (empty) return `${text.slice(0, s.start + 1)}${eol}${indent}${piece}${eol}${outer}${text.slice(close)}`;
|
|
82
88
|
const after = last.end;
|
|
83
|
-
return multi ? `${text.slice(0, after)}
|
|
89
|
+
return multi ? `${text.slice(0, after)},${eol}${indent}${piece}${text.slice(after)}` : `${text.slice(0, after)}, ${piece}${text.slice(after)}`;
|
|
84
90
|
}
|
package/lib/layout.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Layout files: projects/<project>/layouts/<name>.json, in the format @rulecad/keyboard-layout describes and reads.
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { host } from './host.mjs';
|
|
3
|
+
import { host, readJson } from './host.mjs';
|
|
4
4
|
import { WS, paths } from './workspace.mjs';
|
|
5
5
|
|
|
6
6
|
export const layoutPath = (project, name, dir) => path.join(dir || path.join(paths.project(project), 'layouts'), `${name}.json`);
|
|
@@ -8,7 +8,7 @@ export const hasLayout = (project, name, dir) => host.exists(layoutPath(project,
|
|
|
8
8
|
export function readLayout(project, name, dir) {
|
|
9
9
|
const f = layoutPath(project, name, dir);
|
|
10
10
|
if (!host.exists(f)) throw new Error(`no layout "${name}" (${path.relative(WS, f)})`);
|
|
11
|
-
return
|
|
11
|
+
return readJson(f);
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
export { keys, width, depth, project } from '@rulecad/keyboard-layout';
|