@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.
- package/AGENTS.md +29 -10
- package/CHANGELOG.md +604 -0
- package/EXAMPLES.md +122 -105
- package/README.md +292 -63
- package/bin/cad.mjs +500 -87
- package/lib/assembly.mjs +486 -134
- package/lib/bays.mjs +124 -0
- package/lib/cache-file.mjs +148 -0
- package/lib/clone.mjs +93 -11
- package/lib/code-text.mjs +28 -0
- package/lib/design-imports.mjs +127 -0
- package/lib/design.mjs +291 -59
- package/lib/designshapes.mjs +142 -0
- package/lib/edit.mjs +29 -5
- package/lib/estimates.mjs +51 -0
- package/lib/fasten.mjs +11 -5
- package/lib/fe-key.mjs +29 -0
- package/lib/fittings.mjs +20 -15
- package/lib/fixings.mjs +17 -4
- package/lib/framebuild.mjs +73 -92
- package/lib/framecheck.mjs +154 -77
- package/lib/framegen.mjs +9 -1
- package/lib/frames.mjs +6 -2
- package/lib/framesize.mjs +45 -82
- package/lib/gait.mjs +17 -7
- package/lib/guides.mjs +84 -50
- package/lib/host.mjs +7 -3
- package/lib/kit.mjs +5 -5
- package/lib/list.mjs +29 -21
- package/lib/live-guard.mjs +18 -8
- package/lib/loads.mjs +35 -23
- package/lib/measured.mjs +740 -99
- package/lib/mesh.mjs +156 -56
- package/lib/motors.mjs +26 -33
- package/lib/names.mjs +15 -0
- package/lib/node-version.mjs +52 -0
- package/lib/optimise.mjs +34 -25
- package/lib/order.mjs +5 -12
- package/lib/parts.mjs +3 -0
- package/lib/picture-servers.mjs +66 -0
- package/lib/power.mjs +14 -7
- package/lib/preview.mjs +12 -25
- package/lib/programs.mjs +113 -0
- package/lib/rules.mjs +2 -1
- package/lib/sandbox-guard.mjs +43 -0
- package/lib/sandbox-hooks.mjs +109 -15
- package/lib/sandbox-lock.mjs +225 -0
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +22 -24
- package/lib/sandbox.mjs +345 -42
- package/lib/sheet.mjs +114 -3
- package/lib/targets/gist.mjs +9 -6
- package/lib/versions.mjs +294 -35
- package/lib/workspace.mjs +6 -3
- package/package.json +14 -14
- package/schemas/assembly.schema.json +6 -5
- package/schemas/object.schema.json +1 -1
- package/schemas/project.schema.json +6 -0
- package/templates/coupons/MEASURE.md +109 -0
- package/templates/coupons/assemblies/fixings-test.json +20 -0
- package/templates/coupons/assemblies/slot-test.json +11 -0
- package/templates/coupons/objects/fixings-coupon.js +88 -0
- package/templates/coupons/objects/fixings-coupon.json +26 -0
- package/templates/coupons/objects/holds-coupon.js +130 -0
- package/templates/coupons/objects/holds-coupon.json +42 -0
- package/templates/coupons/objects/slot-coupon.js +89 -0
- package/templates/coupons/objects/slot-coupon.json +29 -0
- package/templates/coupons/project.json +10 -0
package/lib/bays.mjs
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// The bays of a frame, found one way for every command that reads them: cad check (frame.square, the frame's solve,
|
|
2
|
+
// its panels as shear webs and frame.rack's braces and panels), cad order and the build page (each bay's diagonals) and
|
|
3
|
+
// cad kit (the diagonals table). It works from the beams' lines and the joins alone, so it needs no solve.
|
|
4
|
+
// A bay is four beams round a rectangle in one plane, two each way. Each neighbouring pair is joined to each other
|
|
5
|
+
// (a side of a box whose rails meet its posts), or both are joined to one other beam at one place (the top and bottom
|
|
6
|
+
// rings of a corner-post box: each rail's end meets a post, and the rails meet each other only through it). Each
|
|
7
|
+
// corner is where two neighbouring beams' axes cross, and lies within a profile's width of both beams' lengths, or of
|
|
8
|
+
// the beam both join there.
|
|
9
|
+
// lib/framecheck.mjs puts a node at each corner; lib/framebuild.mjs works out each bay's opening and its diagonals.
|
|
10
|
+
|
|
11
|
+
const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
12
|
+
const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
|
13
|
+
const add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
|
|
14
|
+
const scale = (a, k) => [a[0] * k, a[1] * k, a[2] * k];
|
|
15
|
+
const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
|
16
|
+
const unit = (a) => {
|
|
17
|
+
const l = Math.hypot(...a);
|
|
18
|
+
return a.map((x) => x / l);
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Where each join of beams meets them: a's end on b's axis, as stations along each beam (mm from its end a).
|
|
23
|
+
* @param {{ items: string[], end: string, model: { b: { end?: string, distance?: number } } }[]} joins the assembly's
|
|
24
|
+
* joins (s.joins)
|
|
25
|
+
* @param {(id: string) => number | undefined} lengthOf each beam's length, undefined for an item that is no beam
|
|
26
|
+
* @returns {{ a: string, b: string, za: number, zb: number, j: object }[]}
|
|
27
|
+
*/
|
|
28
|
+
export function joinStations(joins, lengthOf) {
|
|
29
|
+
const out = [];
|
|
30
|
+
for (const j of joins ?? []) {
|
|
31
|
+
const [a, b] = j.items,
|
|
32
|
+
La = lengthOf(a),
|
|
33
|
+
Lb = lengthOf(b);
|
|
34
|
+
if (La == null || Lb == null || a === b) continue;
|
|
35
|
+
const e = j.end?.[0] ?? 'a',
|
|
36
|
+
zb = j.model?.b?.end != null ? (j.model.b.end === 'a' ? 0 : Lb) : (j.model?.b?.distance ?? 0);
|
|
37
|
+
out.push({ a, b, za: e === 'a' ? 0 : La, zb, j });
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The bays of a frame: four beams round a rectangle in one plane, each neighbouring pair joined to each other or both
|
|
44
|
+
* joined to one beam at one place.
|
|
45
|
+
* @param {{ id: string, A: number[], u: number[], L: number, reach: number }[]} beams each beam's end a, its axis (a unit
|
|
46
|
+
* vector from a to b), its length and how far its section reaches from its axis (the larger of its width and height)
|
|
47
|
+
* @param {{ a: string, b: string, za: number, zb: number }[]} joins where each join meets its beams (joinStations)
|
|
48
|
+
* @returns {{ beams: string[], name: string, n: number[], corners: { at: number[], joined: boolean, through: string[] }[], through: string[] }[]}
|
|
49
|
+
* beams in order round the bay (the first and third parallel), n the bay's normal, each corner between beams i and i+1
|
|
50
|
+
* (its point, whether the two are joined to each other, and the beams both join there), and the beams the bay's
|
|
51
|
+
* corners are joined through (the posts of a corner-post box's ring; empty for a bay whose beams join each other)
|
|
52
|
+
*/
|
|
53
|
+
export function baysOf(beams, joins) {
|
|
54
|
+
const byId = new Map(beams.map((b) => [b.id, b])),
|
|
55
|
+
ids = beams.map((b) => b.id);
|
|
56
|
+
const pairs = new Set();
|
|
57
|
+
for (const x of joins) {
|
|
58
|
+
pairs.add(`${x.a}|${x.b}`);
|
|
59
|
+
pairs.add(`${x.b}|${x.a}`);
|
|
60
|
+
}
|
|
61
|
+
const direct = (p, q) => pairs.has(`${p}|${q}`);
|
|
62
|
+
// the beams p and q both join at one place: each end on that beam within a profile's width of the other's
|
|
63
|
+
const memo = new Map();
|
|
64
|
+
const via = (p, q) => {
|
|
65
|
+
const key = `${p}|${q}`;
|
|
66
|
+
if (memo.has(key)) return memo.get(key);
|
|
67
|
+
const at = (id) =>
|
|
68
|
+
joins.flatMap((x) => (x.a === id ? [[x.b, x.zb]] : x.b === id ? [[x.a, x.za]] : [])).filter(([r]) => byId.has(r));
|
|
69
|
+
const out = new Set();
|
|
70
|
+
for (const [r, z] of at(p))
|
|
71
|
+
for (const [r2, z2] of at(q))
|
|
72
|
+
if (r === r2 && r !== p && r !== q && Math.abs(z - z2) <= byId.get(r).reach) out.add(r);
|
|
73
|
+
memo.set(key, [...out]);
|
|
74
|
+
return memo.get(key);
|
|
75
|
+
};
|
|
76
|
+
const linked = (p, q) => direct(p, q) || via(p, q).length > 0;
|
|
77
|
+
const par = (p, q) => Math.abs(Math.abs(dot(p.u, q.u)) - 1) < 1e-3,
|
|
78
|
+
square = (p, q) => Math.abs(dot(p.u, q.u)) < 1e-3;
|
|
79
|
+
// how far a point lies past a beam's ends, along its axis (0 within its length)
|
|
80
|
+
const past = (b, X) => {
|
|
81
|
+
const t = dot(sub(X, b.A), b.u);
|
|
82
|
+
return t < 0 ? -t : t > b.L ? t - b.L : 0;
|
|
83
|
+
};
|
|
84
|
+
const out = [],
|
|
85
|
+
seen = new Set();
|
|
86
|
+
for (const a of ids)
|
|
87
|
+
for (const b of ids)
|
|
88
|
+
if (b !== a && linked(a, b))
|
|
89
|
+
for (const c of ids)
|
|
90
|
+
if (c !== a && c !== b && linked(b, c))
|
|
91
|
+
for (const d of ids) {
|
|
92
|
+
if ([a, b, c].includes(d) || !linked(c, d) || !linked(d, a)) continue;
|
|
93
|
+
const key = [a, b, c, d].sort().join(',');
|
|
94
|
+
if (seen.has(key)) continue;
|
|
95
|
+
const B = [a, b, c, d].map((id) => byId.get(id));
|
|
96
|
+
if (!(par(B[0], B[2]) && par(B[1], B[3]) && square(B[0], B[1]))) continue;
|
|
97
|
+
const n = unit(cross(B[0].u, B[1].u));
|
|
98
|
+
if (B.some((q) => Math.abs(dot(sub(q.A, B[0].A), n)) > 1)) continue;
|
|
99
|
+
const corners = B.map((p, i) => {
|
|
100
|
+
const q = B[(i + 1) % 4],
|
|
101
|
+
X = add(p.A, scale(p.u, dot(sub(q.A, p.A), p.u))),
|
|
102
|
+
joined = direct(p.id, q.id);
|
|
103
|
+
return { at: X, joined, through: via(p.id, q.id) };
|
|
104
|
+
});
|
|
105
|
+
// each corner on both its beams (within a profile's width of their lengths), or where both join a beam
|
|
106
|
+
const near = (cn, i) => {
|
|
107
|
+
const p = B[i],
|
|
108
|
+
q = B[(i + 1) % 4],
|
|
109
|
+
r = Math.max(p.reach, q.reach);
|
|
110
|
+
if (cn.joined && past(p, cn.at) <= r && past(q, cn.at) <= r) return true;
|
|
111
|
+
return cn.through.some((id) => past(byId.get(id), cn.at) <= r);
|
|
112
|
+
};
|
|
113
|
+
if (!corners.every(near)) continue;
|
|
114
|
+
seen.add(key);
|
|
115
|
+
out.push({
|
|
116
|
+
beams: [a, b, c, d],
|
|
117
|
+
name: [a, b, c, d].join('-'),
|
|
118
|
+
n,
|
|
119
|
+
corners,
|
|
120
|
+
through: [...new Set(corners.flatMap((x) => (x.joined ? [] : x.through)))],
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// The workspace's .cache/ folder, written and read one way (issue #633). Everything cad keeps there (builds, stages,
|
|
2
|
+
// routes, overlaps, the gears' contact, the finite elements' results, assembly orders, optimised shapes and their
|
|
3
|
+
// densities, recorded runs, links, the record of AGENTS.md) is written by writeCacheFile and, where it is JSON, read by
|
|
4
|
+
// readCacheJson. test/cache-writes.test.mjs holds every file of lib/ and bin/ to that.
|
|
5
|
+
//
|
|
6
|
+
// Two dangers. A workspace cloned from someone else may carry a .cache/ of its own, and a file there that is a link to a
|
|
7
|
+
// file elsewhere (the user's trust list, a file in their home) would be written through, overwritten with what the tool
|
|
8
|
+
// worked out: so a cache file is written only where it, and every folder between it and the workspace, is a plain file
|
|
9
|
+
// and plain folders, or not there yet (ownCacheFile); otherwise the result is simply not kept. And a run stopped part way
|
|
10
|
+
// through writing (Ctrl-C, a test's time running out, a full disc) would leave a file cut short that every later run
|
|
11
|
+
// failed to read: so a file is written whole beside its place and then renamed over it, which leaves either the old
|
|
12
|
+
// file or the new one, never part of one; and a kept file that does not read as JSON is a miss, removed and made again.
|
|
13
|
+
// The same guard (notOwn, writeOwnFile, removeOwnFolder) keeps the released versions lib/versions.mjs unpacks into the
|
|
14
|
+
// workspace's .versions/ folder (issue #696), where a link is refused aloud rather than passed over.
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import crypto from 'node:crypto';
|
|
18
|
+
import { host, nodeHost, cached } from './host.mjs';
|
|
19
|
+
import { WS } from './workspace.mjs';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The first thing on the way from the workspace (root) down to `file` that the tool must not write, read or remove
|
|
23
|
+
* through, or null when there is none: `file` itself when it is not inside root; else the first of it (a plain file,
|
|
24
|
+
* not a link and not hard-linked to another name; with `folder`, a plain folder) and the folders between it and root
|
|
25
|
+
* (plain folders) that is something else. What is not there yet is fine: it will be made as the tool's own. (A
|
|
26
|
+
* junction on Windows is a link here too: Node's lstat says so.) The one guard for .cache/ (ownCacheFile) and for the
|
|
27
|
+
* released versions in .versions/ (lib/versions.mjs), which a workspace cloned from someone else may both bring.
|
|
28
|
+
* @param {string} file @param {string} [root] the workspace @param {{ folder?: boolean }} [options]
|
|
29
|
+
* @returns {string | null}
|
|
30
|
+
*/
|
|
31
|
+
export function notOwn(file, root = WS, { folder = false } = {}) {
|
|
32
|
+
const top = path.resolve(root);
|
|
33
|
+
let p = path.resolve(file);
|
|
34
|
+
if (!p.startsWith(top + path.sep)) return p;
|
|
35
|
+
for (let first = true; p !== top; p = path.dirname(p), first = false) {
|
|
36
|
+
let st;
|
|
37
|
+
try {
|
|
38
|
+
st = fs.lstatSync(p);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
if (e.code === 'ENOENT') continue;
|
|
41
|
+
return p;
|
|
42
|
+
}
|
|
43
|
+
if (first && !folder ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return p;
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Whether the tool may write a cache file at `file`: it lies inside the workspace (root), and it and every folder on its
|
|
50
|
+
* way down from there are a plain file (not a link, and not hard-linked to another name) and plain folders, or are not
|
|
51
|
+
* there yet (notOwn). A workspace in memory has nothing on disk to follow, so any file of it is the tool's own.
|
|
52
|
+
* @param {string} file @param {string} [root] the workspace @returns {boolean}
|
|
53
|
+
*/
|
|
54
|
+
export function ownCacheFile(file, root = WS) {
|
|
55
|
+
if (host.name === 'memory') return true;
|
|
56
|
+
return notOwn(file, root) === null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Write `text` to `file` on disk, whole or not at all, never through a link: where notOwn finds something on its way,
|
|
61
|
+
* `refuse` is called with it (and throws) and nothing is written; else the folders are made, looked at again, and the
|
|
62
|
+
* text written to a new file beside it (never one already there, nor a link) that is then renamed over it, which leaves
|
|
63
|
+
* either the old file or the new one, never part of one.
|
|
64
|
+
* @param {string} file @param {string} text @param {(bad: string) => never} refuse @param {string} [root] the workspace
|
|
65
|
+
*/
|
|
66
|
+
export function writeOwnFile(file, text, refuse, root = WS) {
|
|
67
|
+
let bad = notOwn(file, root);
|
|
68
|
+
if (bad) refuse(bad);
|
|
69
|
+
const dir = path.dirname(file);
|
|
70
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
71
|
+
if ((bad = notOwn(file, root))) refuse(bad); // (the folders just made, looked at again)
|
|
72
|
+
const temp = path.join(dir, `.${path.basename(file)}.${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`);
|
|
73
|
+
try {
|
|
74
|
+
fs.writeFileSync(temp, text, { flag: 'wx' }); // (wx: a new file, never one that is there already, nor a link)
|
|
75
|
+
fs.renameSync(temp, file);
|
|
76
|
+
} catch (e) {
|
|
77
|
+
fs.rmSync(temp, { force: true });
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Remove the folder `dir` and all in it, only where it and the folders above it up to the workspace are plain folders
|
|
84
|
+
* (notOwn): else `refuse` is called with what was found (and throws) and nothing is removed. A link inside the folder
|
|
85
|
+
* is removed as a link, what it leads to left alone (Node's rm does not follow links).
|
|
86
|
+
* @param {string} dir @param {(bad: string) => never} refuse @param {string} [root] the workspace
|
|
87
|
+
*/
|
|
88
|
+
export function removeOwnFolder(dir, refuse, root = WS) {
|
|
89
|
+
const bad = notOwn(dir, root, { folder: true });
|
|
90
|
+
if (bad) refuse(bad);
|
|
91
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Keep `text` in the cache file `file`, whole or not at all: only where ownCacheFile allows (a link, or a folder that is
|
|
96
|
+
* a link, is left as it is and the text not kept), written by writeOwnFile. A cache that can't be written is only
|
|
97
|
+
* slower, so nothing is thrown.
|
|
98
|
+
* @param {string} file @param {string} text @returns {boolean} whether it was kept
|
|
99
|
+
*/
|
|
100
|
+
export function writeCacheFile(file, text) {
|
|
101
|
+
try {
|
|
102
|
+
if (!ownCacheFile(file)) return false;
|
|
103
|
+
if (host.writeText !== nodeHost.writeText) {
|
|
104
|
+
host.writeText(file, text); // (a host of another kind, a workspace in memory: what it writes is its own business)
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
writeOwnFile(file, text, () => {
|
|
108
|
+
throw new Error('not kept');
|
|
109
|
+
});
|
|
110
|
+
return true;
|
|
111
|
+
} catch {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Remove a cache file that is the tool's own (ownCacheFile): a link, or a file elsewhere, is left alone.
|
|
118
|
+
* @param {string} file
|
|
119
|
+
*/
|
|
120
|
+
export function dropCacheFile(file) {
|
|
121
|
+
try {
|
|
122
|
+
if (ownCacheFile(file)) host.remove(file);
|
|
123
|
+
} catch {
|
|
124
|
+
// (left for another run: it is a miss each time until then)
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* A kept JSON file of the cache, or undefined when there is none to read: not there, a link out of the workspace
|
|
130
|
+
* (host.mjs cached), or a file that does not read as JSON (cut short by a run that was stopped while writing it under an
|
|
131
|
+
* older version of the tool, or spoiled since), which is removed so that it is made again.
|
|
132
|
+
* @param {string} file @returns {any}
|
|
133
|
+
*/
|
|
134
|
+
export function readCacheJson(file) {
|
|
135
|
+
if (!cached(file)) return undefined;
|
|
136
|
+
let text;
|
|
137
|
+
try {
|
|
138
|
+
text = host.readText(file);
|
|
139
|
+
} catch {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(text);
|
|
144
|
+
} catch {
|
|
145
|
+
dropCacheFile(file);
|
|
146
|
+
return undefined;
|
|
147
|
+
}
|
|
148
|
+
}
|
package/lib/clone.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import path from 'node:path';
|
|
|
7
7
|
const nodePath = path;
|
|
8
8
|
import { WS } from './workspace.mjs';
|
|
9
9
|
import { pcbEngine } from './design.mjs';
|
|
10
|
+
import { MESH_LIMITS } from './mesh.mjs';
|
|
10
11
|
|
|
11
12
|
const today = () => new Date().toISOString().slice(0, 10);
|
|
12
13
|
// Licences that ask boards made from the source to stay under them (or forbid that use): said when cloning
|
|
@@ -26,6 +27,63 @@ async function getJSON(url) {
|
|
|
26
27
|
return r.json();
|
|
27
28
|
}
|
|
28
29
|
|
|
30
|
+
// What cad clone downloads or reads from a board's folder is at most MESH_LIMITS.download (64 MB) a file: a bigger one,
|
|
31
|
+
// from a repository nobody here checked, is refused with the limit named rather than read into memory whole. (said: a
|
|
32
|
+
// refusal that is told as it is, not passed over for another way to the same model.)
|
|
33
|
+
const said = (message) => Object.assign(new Error(message), { said: true });
|
|
34
|
+
const tooLarge = (what, max) => said(`${what} is more than the ${max / (1024 * 1024)} MB cad clone reads`);
|
|
35
|
+
const notFile = (what) =>
|
|
36
|
+
said(`${what} is not a file (it is a folder, a device or a pipe), so cad clone doesn't read it`);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A downloaded file's text, stopped at max bytes: refused at once if the server says it is bigger, else as soon as more
|
|
40
|
+
* than max has come.
|
|
41
|
+
* @param {Response} r the server's answer @param {string} what the file, for the message
|
|
42
|
+
* @param {number} [max] bytes (MESH_LIMITS.download) @returns {Promise<string>}
|
|
43
|
+
*/
|
|
44
|
+
export async function textOf(r, what, max = MESH_LIMITS.download) {
|
|
45
|
+
if (Number(r.headers?.get('content-length')) > max) {
|
|
46
|
+
await r.body?.cancel().catch(() => {});
|
|
47
|
+
throw tooLarge(what, max);
|
|
48
|
+
}
|
|
49
|
+
if (!r.body) return '';
|
|
50
|
+
const chunks = [];
|
|
51
|
+
let n = 0;
|
|
52
|
+
// (leaving the loop by throwing cancels the download)
|
|
53
|
+
for await (const c of r.body) {
|
|
54
|
+
if ((n += c.length) > max) throw tooLarge(what, max);
|
|
55
|
+
chunks.push(c);
|
|
56
|
+
}
|
|
57
|
+
// (read as the server's answer's own text() reads it: a byte order mark at the start is not part of the text)
|
|
58
|
+
return new TextDecoder().decode(Buffer.concat(chunks));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// A file of this computer's, read the same way: refused by its size before it is read, and counted as it is read.
|
|
62
|
+
// Only a plain file is read: a link to a device says it has no size and never ends (so it was read until the memory
|
|
63
|
+
// was full), and a pipe nobody writes to held cad clone for ever (so the file is opened without waiting for one).
|
|
64
|
+
async function readCapped(file, what, max = MESH_LIMITS.download) {
|
|
65
|
+
const fh = await fs.promises.open(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0)).catch((e) => {
|
|
66
|
+
// (where a folder can't be opened at all)
|
|
67
|
+
throw e.code === 'EISDIR' ? notFile(what) : e;
|
|
68
|
+
});
|
|
69
|
+
try {
|
|
70
|
+
const is = await fh.stat();
|
|
71
|
+
if (!is.isFile()) throw notFile(what);
|
|
72
|
+
if (is.size > max) throw tooLarge(what, max);
|
|
73
|
+
const chunks = [];
|
|
74
|
+
for (let n = 0; ;) {
|
|
75
|
+
const { bytesRead, buffer } = await fh.read(Buffer.allocUnsafe(1024 * 1024), 0, 1024 * 1024, null);
|
|
76
|
+
if (!bytesRead) break;
|
|
77
|
+
// (a file that grew since its size was asked)
|
|
78
|
+
if ((n += bytesRead) > max) throw tooLarge(what, max);
|
|
79
|
+
chunks.push(buffer.subarray(0, bytesRead));
|
|
80
|
+
}
|
|
81
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
82
|
+
} finally {
|
|
83
|
+
await fh.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
29
87
|
// The board's text and what to record about it: from a GitHub link, pinned to the commit the link names (a branch is
|
|
30
88
|
// looked up), with the repository's licence; from a file, what --source and --licence say
|
|
31
89
|
async function fetchBoard(ref, o) {
|
|
@@ -36,7 +94,7 @@ async function fetchBoard(ref, o) {
|
|
|
36
94
|
`no file ${ref}: give a .kicad_pcb file, or a GitHub link to one (https://github.com/<owner>/<repo>/blob/<branch>/<path>.kicad_pcb)`,
|
|
37
95
|
);
|
|
38
96
|
return {
|
|
39
|
-
text:
|
|
97
|
+
text: await readCapped(ref, `the board ${path.basename(ref)}`),
|
|
40
98
|
source: o.source || path.basename(ref),
|
|
41
99
|
licence: o.licence || null,
|
|
42
100
|
dir: path.dirname(path.resolve(ref)),
|
|
@@ -61,7 +119,7 @@ async function fetchBoard(ref, o) {
|
|
|
61
119
|
licence = l?.license?.spdx_id && l.license.spdx_id !== 'NOASSERTION' ? l.license.spdx_id : first;
|
|
62
120
|
}
|
|
63
121
|
return {
|
|
64
|
-
text: await raw.
|
|
122
|
+
text: await textOf(raw, `the board ${gh.file}`),
|
|
65
123
|
source: `https://github.com/${gh.owner}/${gh.repo}/blob/${commit}/${gh.file}`,
|
|
66
124
|
licence,
|
|
67
125
|
commit,
|
|
@@ -73,11 +131,28 @@ async function fetchBoard(ref, o) {
|
|
|
73
131
|
// KiCad's own library, by the version its path variable names (6 and later name it; older boards say KISYS3DMOD)
|
|
74
132
|
const KICAD = { 6: '6.0.11', 7: '7.0.11', 8: '8.0.8' };
|
|
75
133
|
const KICAD_LICENCE = "CC-BY-SA-4.0 with the KiCad libraries exception (designs using the models aren't bound by it)";
|
|
76
|
-
const fetchText = async (url) => {
|
|
134
|
+
const fetchText = async (url, what) => {
|
|
77
135
|
const r = await fetch(url);
|
|
78
136
|
if (!r.ok) throw new Error(`${r.status} for ${url}`);
|
|
79
|
-
return r
|
|
137
|
+
return textOf(r, what);
|
|
80
138
|
};
|
|
139
|
+
// A model as notes name it: one of the board's own by its path in the board's folder (a board read from a file) or in
|
|
140
|
+
// its repository (a board from GitHub), any other (one of KiCad's library, a path cad clone can't follow) as the board
|
|
141
|
+
// gives it. Never by its last part alone: two refused files of one name then read the same. The name is the board's
|
|
142
|
+
// text, so a character in it that would ring, move the cursor or hide what is written (a control character, a line or
|
|
143
|
+
// direction mark) is shown as its code, "\u{1b}": a board's model path could wipe its own note off the screen, and
|
|
144
|
+
// two names that differ only in such a character read the same. (A "\u{" written out in a name has its backslash
|
|
145
|
+
// shown as a code too, so no two names are shown alike.)
|
|
146
|
+
const shown = (name) =>
|
|
147
|
+
name
|
|
148
|
+
.replace(/\\(?=u\{)/g, '\\u{5c}')
|
|
149
|
+
.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (c) => `\\u{${c.codePointAt(0).toString(16)}}`);
|
|
150
|
+
function modelName(model, got) {
|
|
151
|
+
const own = model.match(/^\$\{KIPRJMOD\}\/(.+)$/);
|
|
152
|
+
if (!own) return shown(model);
|
|
153
|
+
const posix = nodePath.posix;
|
|
154
|
+
return shown(got.github ? posix.normalize(posix.join(posix.dirname(got.github.file), own[1])) : own[1]);
|
|
155
|
+
}
|
|
81
156
|
|
|
82
157
|
// Whether file is in the folder dir, or a folder in it (by its name, and by where a link in the way leads)
|
|
83
158
|
function inside(dir, file) {
|
|
@@ -174,7 +249,7 @@ async function fetchModels(circuit, got, { wrlMesh, stepBounds }, notes) {
|
|
|
174
249
|
try {
|
|
175
250
|
const src = await modelSource(path, got);
|
|
176
251
|
if (!src) {
|
|
177
|
-
notes.push(`no 3D model for ${path}: its path isn't one cad clone can follow`);
|
|
252
|
+
notes.push(`no 3D model for ${shown(path)}: its path isn't one cad clone can follow`);
|
|
178
253
|
continue;
|
|
179
254
|
}
|
|
180
255
|
const name = path
|
|
@@ -183,15 +258,19 @@ async function fetchModels(circuit, got, { wrlMesh, stepBounds }, notes) {
|
|
|
183
258
|
.replace(/\.(step|stp|wrl)$/i, ''),
|
|
184
259
|
dir = src.kicad ? `kicad/${path.split('/').slice(-2, -1)[0]}` : 'source';
|
|
185
260
|
const read = async (ext) => {
|
|
186
|
-
if (!src.file) return fetchText(src.url.replace(/\.[^./]+$/, ext));
|
|
261
|
+
if (!src.file) return fetchText(src.url.replace(/\.[^./]+$/, ext), `its ${ext} file`);
|
|
187
262
|
const f = src.file.replace(/\.[^.]+$/, ext);
|
|
188
263
|
// (and where a link in the board's folder leads: it must stay in the folder too)
|
|
189
264
|
if (!inside(src.dir, f)) throw new Error(`its path leaves the board's folder, so cad clone doesn't follow it`);
|
|
190
|
-
return
|
|
265
|
+
return readCapped(f, `its ${ext} file`);
|
|
266
|
+
};
|
|
267
|
+
// (a file too big to read, or one that is no file, is said, not passed over for the next way to the model)
|
|
268
|
+
const unlessSaid = (e) => {
|
|
269
|
+
if (e.said) throw e;
|
|
191
270
|
};
|
|
192
271
|
if (src.licence || src.file) {
|
|
193
272
|
// VRML where there is one (KiCad's library has both): a mesh
|
|
194
|
-
const wrl = /\.wrl$/i.test(path) || src.kicad ? await read('.wrl').catch(
|
|
273
|
+
const wrl = /\.wrl$/i.test(path) || src.kicad ? ((await read('.wrl').catch(unlessSaid)) ?? null) : null;
|
|
195
274
|
if (wrl) {
|
|
196
275
|
const triangles = wrlMesh(wrl).map((t) => t.map((v) => v.map((n) => Math.round(n * 1e3) / 1e3)));
|
|
197
276
|
const file = `models/${dir}/${name}.json`;
|
|
@@ -204,10 +283,13 @@ async function fetchModels(circuit, got, { wrlMesh, stepBounds }, notes) {
|
|
|
204
283
|
continue;
|
|
205
284
|
}
|
|
206
285
|
}
|
|
207
|
-
const step = await read(nodePath.extname(path) || '.step').catch(() =>
|
|
286
|
+
const step = await read(nodePath.extname(path) || '.step').catch((e) => {
|
|
287
|
+
unlessSaid(e);
|
|
288
|
+
return read('.step');
|
|
289
|
+
});
|
|
208
290
|
const box = stepBounds(step);
|
|
209
291
|
if (!box) {
|
|
210
|
-
notes.push(`no 3D model for ${
|
|
292
|
+
notes.push(`no 3D model for ${modelName(path, got)}: its file has no points to measure`);
|
|
211
293
|
continue;
|
|
212
294
|
}
|
|
213
295
|
out[path] = {
|
|
@@ -218,7 +300,7 @@ async function fetchModels(circuit, got, { wrlMesh, stepBounds }, notes) {
|
|
|
218
300
|
: 'no licence: only its size is used, drawn as a box',
|
|
219
301
|
};
|
|
220
302
|
} catch (e) {
|
|
221
|
-
notes.push(`no 3D model for ${path
|
|
303
|
+
notes.push(`no 3D model for ${modelName(path, got)}: ${e.message}`);
|
|
222
304
|
}
|
|
223
305
|
}
|
|
224
306
|
return out;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Code as it runs, for the keys of cad's slow caches (an optimisation's densities, a fitting's finite-element results):
|
|
2
|
+
// a module's text without its lines that are only a comment (// ..., or a /* ... */ or /** ... */ block) and without
|
|
3
|
+
// blank lines. Rewording a comment, or spacing the code out, then keeps a key and the minutes of work kept under it;
|
|
4
|
+
// any change to the code itself moves it. A comment after code on the same line stays in: telling it apart from a
|
|
5
|
+
// string that holds // would take a parser, and a key that moves now and then is only slower, never wrong.
|
|
6
|
+
// (@rulecad/frames has its own copy for fittingCode, as it runs in a browser and does not depend on cad.)
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A module's code without the lines that are only a comment and without blank lines.
|
|
10
|
+
* @param {string} text the module's text, or a function's (fn.toString())
|
|
11
|
+
* @returns {string}
|
|
12
|
+
*/
|
|
13
|
+
export function codeOnly(text) {
|
|
14
|
+
let inComment = false;
|
|
15
|
+
return String(text)
|
|
16
|
+
.split('\n')
|
|
17
|
+
.filter((line) => {
|
|
18
|
+
const t = line.trim();
|
|
19
|
+
// (a block comment's lines, kept only where code follows its end on the same line)
|
|
20
|
+
if (inComment || t.startsWith('/*')) {
|
|
21
|
+
const end = t.indexOf('*/', inComment ? 0 : 2);
|
|
22
|
+
inComment = end < 0;
|
|
23
|
+
return !inComment && t.slice(end + 2).trim() !== '';
|
|
24
|
+
}
|
|
25
|
+
return t !== '' && !t.startsWith('//');
|
|
26
|
+
})
|
|
27
|
+
.join('\n');
|
|
28
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// A design run in the tool's own process (a trusted workspace's), loaded so that the files it imports are known and
|
|
2
|
+
// never stale. Node keeps every module it has loaded for as long as the process runs, by its URL: a design is loaded
|
|
3
|
+
// by a URL that changes with its text, but a helper it imports ('./box.js') would be found by its plain URL and so kept
|
|
4
|
+
// as first loaded, however it is edited after (a live view runs for hours). So an import hook marks each file a design
|
|
5
|
+
// reaches by a path (not a package) with the design's load: `?rulecad-design=<token>`, the token a hash of the design's
|
|
6
|
+
// text and of the files it imported the last time. Edit a helper and the token changes, so the design and its helpers
|
|
7
|
+
// are loaded afresh. The hook notes those files too, for the build's cache (design.mjs): the tool learns them by
|
|
8
|
+
// importing a module the hook makes up, which works the same whether the hook runs in this thread or, on older Node,
|
|
9
|
+
// in a worker of its own.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import * as nodeModule from 'node:module';
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
14
|
+
|
|
15
|
+
const MARK = 'rulecad-design',
|
|
16
|
+
LIST = 'rulecad-imports:'; // `${LIST}${token}?n=<count>`: the files a load imported, as a module of the hook's making
|
|
17
|
+
|
|
18
|
+
// ---- the hook (in this thread, or in the hooks' worker on older Node) ----
|
|
19
|
+
const imported = new Map(); // token -> Set of file: URLs
|
|
20
|
+
const tokenOf = (url) => {
|
|
21
|
+
if (!url?.startsWith('file:')) return null;
|
|
22
|
+
return new URL(url).searchParams.get(MARK);
|
|
23
|
+
};
|
|
24
|
+
const byPath = (spec) =>
|
|
25
|
+
spec.startsWith('./') || spec.startsWith('../') || spec.startsWith('/') || spec.startsWith('file:');
|
|
26
|
+
function mark(spec, context, r) {
|
|
27
|
+
const token = tokenOf(context.parentURL);
|
|
28
|
+
if (!token || !byPath(spec) || !r.url.startsWith('file:')) return r;
|
|
29
|
+
const u = new URL(r.url);
|
|
30
|
+
if (u.pathname.split('/').some((s) => s.toLowerCase() === 'node_modules')) return r; // (a package's file: left as it is)
|
|
31
|
+
const plain = new URL(u.href);
|
|
32
|
+
plain.search = plain.hash = '';
|
|
33
|
+
if (!imported.has(token)) imported.set(token, new Set());
|
|
34
|
+
imported.get(token).add(plain.href);
|
|
35
|
+
u.searchParams.set(MARK, token);
|
|
36
|
+
return { ...r, url: u.href };
|
|
37
|
+
}
|
|
38
|
+
/** The import hook's resolve, in this thread (module.registerHooks). */
|
|
39
|
+
export function resolveHook(spec, context, next) {
|
|
40
|
+
if (spec.startsWith(LIST)) return { url: spec, shortCircuit: true };
|
|
41
|
+
return mark(spec, context, next(spec, context));
|
|
42
|
+
}
|
|
43
|
+
/** The import hook's resolve, in a worker (module.register). */
|
|
44
|
+
export async function resolve(spec, context, next) {
|
|
45
|
+
if (spec.startsWith(LIST)) return { url: spec, shortCircuit: true };
|
|
46
|
+
return mark(spec, context, await next(spec, context));
|
|
47
|
+
}
|
|
48
|
+
/** The import hook's load, in this thread: the made-up module that lists a load's files. */
|
|
49
|
+
export function loadHook(url, context, next) {
|
|
50
|
+
if (!url.startsWith(LIST)) return next(url, context);
|
|
51
|
+
const token = url.slice(LIST.length).split('?')[0];
|
|
52
|
+
return {
|
|
53
|
+
format: 'module',
|
|
54
|
+
source: `export default ${JSON.stringify([...(imported.get(token) || [])])};`,
|
|
55
|
+
shortCircuit: true,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/** The import hook's load, in a worker. */
|
|
59
|
+
export async function load(url, context, next) {
|
|
60
|
+
return loadHook(url, context, next);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---- the tool's side ----
|
|
64
|
+
let hooked = false;
|
|
65
|
+
function hook() {
|
|
66
|
+
if (hooked) return;
|
|
67
|
+
hooked = true;
|
|
68
|
+
if (nodeModule.registerHooks) nodeModule.registerHooks({ resolve: resolveHook, load: loadHook });
|
|
69
|
+
else nodeModule.register(import.meta.url);
|
|
70
|
+
}
|
|
71
|
+
// For each design file: the token it was last loaded by and the files that load imported (paths)
|
|
72
|
+
const loads = new Map();
|
|
73
|
+
let asked = 0;
|
|
74
|
+
const textOf = (f) => {
|
|
75
|
+
try {
|
|
76
|
+
return fs.readFileSync(f, 'utf8');
|
|
77
|
+
} catch {
|
|
78
|
+
return '\u0000missing';
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// The files a load has imported so far, as the hook noted them (absolute paths)
|
|
83
|
+
const listed = async (token) =>
|
|
84
|
+
(await import(`${LIST}${token}?n=${asked++}`)).default.map((u) => fileURLToPath(u)).sort();
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* A design's module, loaded afresh when it or a file it imports has changed since its last load here.
|
|
88
|
+
* @param {string} file the design's .js
|
|
89
|
+
* @returns {Promise<any>} the module
|
|
90
|
+
*/
|
|
91
|
+
export async function loadDesign(file) {
|
|
92
|
+
hook();
|
|
93
|
+
const last = loads.get(file);
|
|
94
|
+
// (after a load that failed, a fresh token whatever the files say: Node keeps a failed load's error by its URL too,
|
|
95
|
+
// and the fault may have been a file that wasn't there, which no text of the last load's files shows)
|
|
96
|
+
const token = crypto
|
|
97
|
+
.createHash('sha256')
|
|
98
|
+
.update(
|
|
99
|
+
JSON.stringify([textOf(file), ...(last?.imports || []).map((f) => [f, textOf(f)]), last?.failed ? asked : null]),
|
|
100
|
+
)
|
|
101
|
+
.digest('hex')
|
|
102
|
+
.slice(0, 32);
|
|
103
|
+
if (last?.token === token && !last.failed) return import(last.url);
|
|
104
|
+
const url = new URL(pathToFileURL(file).href);
|
|
105
|
+
url.searchParams.set(MARK, token);
|
|
106
|
+
try {
|
|
107
|
+
const module = await import(url.href);
|
|
108
|
+
loads.set(file, { token, url: url.href, imports: await listed(token) });
|
|
109
|
+
return module;
|
|
110
|
+
} catch (e) {
|
|
111
|
+
loads.set(file, { token, url: url.href, imports: await listed(token), failed: true });
|
|
112
|
+
throw e;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The files of its own (not a package's) a design has imported since it was loaded, its main's own imports included:
|
|
118
|
+
* absolute paths. Asked after main has run.
|
|
119
|
+
* @param {string} file the design's .js
|
|
120
|
+
* @returns {Promise<string[]>}
|
|
121
|
+
*/
|
|
122
|
+
export async function importsOf(file) {
|
|
123
|
+
const last = loads.get(file);
|
|
124
|
+
if (!last) return [];
|
|
125
|
+
last.imports = await listed(last.token);
|
|
126
|
+
return last.imports;
|
|
127
|
+
}
|