@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.
- package/AGENTS.md +45 -16
- package/CHANGELOG.md +724 -0
- package/EXAMPLES.md +61 -54
- package/README.md +376 -98
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2664 -541
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1883 -435
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/cache-file.mjs +105 -0
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/code-text.mjs +28 -0
- package/lib/design-imports.mjs +127 -0
- package/lib/design.mjs +871 -147
- package/lib/designshapes.mjs +142 -0
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +922 -192
- package/lib/errors.mjs +16 -3
- package/lib/estimates.mjs +51 -0
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2708 -507
- package/lib/fe-key.mjs +29 -0
- package/lib/fittings.mjs +721 -122
- package/lib/fixings.mjs +38 -13
- package/lib/framebuild.mjs +790 -175
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +108 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +86 -18
- package/lib/framesize.mjs +719 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +129 -23
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +439 -69
- package/lib/layout.mjs +2 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +334 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +597 -136
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +1080 -117
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1002 -214
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +18 -1
- package/lib/optimise.mjs +991 -287
- package/lib/order.mjs +515 -114
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +81 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +223 -35
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +17 -6
- package/lib/sandbox-hooks.mjs +179 -27
- package/lib/sandbox-lock.mjs +225 -0
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +122 -25
- package/lib/sandbox.mjs +667 -75
- package/lib/schema.mjs +42 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +963 -179
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +22 -4
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +285 -39
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +200 -14
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
- 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/wires.mjs
CHANGED
|
@@ -6,26 +6,61 @@ import { placeItems, jointValues, mul } from '@rulecad/model-link';
|
|
|
6
6
|
|
|
7
7
|
const n3 = (x, d = 1) => String(Number(x.toFixed(d)));
|
|
8
8
|
const GAUGE = /^awg(\d{1,2})$/i;
|
|
9
|
-
const areaOf = (gauge, base) => {
|
|
9
|
+
const areaOf = (gauge, base) => {
|
|
10
|
+
const d = base * Math.pow(92, (36 - gauge) / 39);
|
|
11
|
+
return (Math.PI * d * d) / 4;
|
|
12
|
+
};
|
|
10
13
|
|
|
11
14
|
// Anchors to world points at given joint values
|
|
12
|
-
function pointer(s, {
|
|
13
|
-
const motion = s.motion,
|
|
15
|
+
function pointer(s, { mul }) {
|
|
16
|
+
const motion = s.motion,
|
|
17
|
+
ids = motion.items.map((x) => x[0]);
|
|
14
18
|
const marks = (id, name) => motion.marks.find((m) => m.id === id && m.name === name);
|
|
15
19
|
return (ref, what) => {
|
|
16
|
-
const bits = String(ref).split('.'),
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
+
const bits = String(ref).split('.'),
|
|
21
|
+
name = bits.pop(),
|
|
22
|
+
id = bits.join('.'),
|
|
23
|
+
m = marks(id, name);
|
|
24
|
+
if (!m)
|
|
25
|
+
throw new Error(
|
|
26
|
+
`${what}: no anchor "${ref}" (give <item>.<anchor>${
|
|
27
|
+
ids.includes(id)
|
|
28
|
+
? `; ${id} has ${
|
|
29
|
+
motion.marks
|
|
30
|
+
.filter((x) => x.id === id)
|
|
31
|
+
.map((x) => x.name)
|
|
32
|
+
.join(', ') || 'none'
|
|
33
|
+
}`
|
|
34
|
+
: ''
|
|
35
|
+
})`,
|
|
36
|
+
);
|
|
37
|
+
const k = ids.indexOf(id),
|
|
38
|
+
F = m.frame;
|
|
39
|
+
return (worlds) => {
|
|
40
|
+
const W = mul(worlds[k], F);
|
|
41
|
+
return [W[3], W[7], W[11]];
|
|
42
|
+
};
|
|
20
43
|
};
|
|
21
44
|
}
|
|
22
45
|
// Joint values to try: each named pose, each moving joint at its ends and middle, all together when few enough
|
|
23
46
|
function samples(motion, jointValues) {
|
|
24
|
-
const base = jointValues(motion, motion.pose ?? undefined),
|
|
47
|
+
const base = jointValues(motion, motion.pose ?? undefined),
|
|
48
|
+
free = motion.joints.filter((j) => !j.follow && j.type !== 'fixed' && j.dofs.length === 1),
|
|
49
|
+
out = [base];
|
|
25
50
|
for (const p of Object.keys(motion.poses || {})) out.push(jointValues(motion, p));
|
|
26
|
-
const levels = (j) => {
|
|
51
|
+
const levels = (j) => {
|
|
52
|
+
const [lo, hi] = j.dofs[0];
|
|
53
|
+
return [lo, (lo + hi) / 2, hi];
|
|
54
|
+
},
|
|
55
|
+
leads = Object.fromEntries(Object.entries(base).filter(([id]) => !motion.joints.find((x) => x.id === id)?.follow));
|
|
27
56
|
if (free.length && free.length <= 5) {
|
|
28
|
-
const go = (i, set) => {
|
|
57
|
+
const go = (i, set) => {
|
|
58
|
+
if (i === free.length) {
|
|
59
|
+
out.push(jointValues(motion, set));
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
for (const v of levels(free[i])) go(i + 1, { ...set, [free[i].id]: [v] });
|
|
63
|
+
};
|
|
29
64
|
go(0, leads);
|
|
30
65
|
} else for (const j of free) for (const v of levels(j)) out.push(jointValues(motion, { ...leads, [j.id]: [v] }));
|
|
31
66
|
return out;
|
|
@@ -37,8 +72,11 @@ export function wiresOf(a, placed, joints) {
|
|
|
37
72
|
const what = `wire ${w.id || i + 1}`;
|
|
38
73
|
if (!w.from || !w.to) throw new Error(`${what}: give "from" and "to", anchors as <item>.<anchor>`);
|
|
39
74
|
const g = GAUGE.exec(String(w.gauge ?? ''));
|
|
40
|
-
if (w.gauge != null && !g)
|
|
41
|
-
|
|
75
|
+
if (w.gauge != null && !g)
|
|
76
|
+
throw new Error(`${what}: gauge is awg and a number (awg22), not ${JSON.stringify(w.gauge)}`);
|
|
77
|
+
for (const v of w.via ?? [])
|
|
78
|
+
if (typeof v === 'string' && !v.includes('.') && !joints.some((j) => j.id === v && j.type === 'path'))
|
|
79
|
+
throw new Error(`${what}: via "${v}" is neither an anchor (<item>.<anchor>) nor a path joint`);
|
|
42
80
|
return { ...w, id: w.id || `w${i + 1}` };
|
|
43
81
|
});
|
|
44
82
|
}
|
|
@@ -47,14 +85,19 @@ export function wiresOf(a, placed, joints) {
|
|
|
47
85
|
function currentOf(w, s, top, signal) {
|
|
48
86
|
if (w.current != null) return { current: Number(w.current), why: 'as given' };
|
|
49
87
|
const motors = s.motion.drives.filter((d) => [top(w.from), top(w.to)].includes(d.id));
|
|
50
|
-
for (const d of motors) {
|
|
88
|
+
for (const d of motors) {
|
|
89
|
+
const I = d.spec.current ?? d.model.figures.rated_current?.value;
|
|
90
|
+
if (I != null) return { current: I, why: `${d.id}'s rated current` };
|
|
91
|
+
}
|
|
51
92
|
return { current: signal, why: 'a signal' };
|
|
52
93
|
}
|
|
53
94
|
|
|
54
95
|
// A wire ending on a board's axis connector: the board's pins for that axis, from its rule set
|
|
55
96
|
export function pinsAt(w, s) {
|
|
56
97
|
for (const end of [w.from, w.to]) {
|
|
57
|
-
const [id, anchor] = String(end).split('.'),
|
|
98
|
+
const [id, anchor] = String(end).split('.'),
|
|
99
|
+
o = s.objects.find((x) => x.id === id && x.bought?.part === 'board'),
|
|
100
|
+
e = o?.built.entries;
|
|
58
101
|
if (!e || !/^[A-Z]\d?$/.test(anchor ?? '')) continue; // (a shield's X, Y, Z; a Mega's S0 to S7)
|
|
59
102
|
const pin = (k) => e.find((x) => x.name === `${o.bought.set}.${k}_pin_${anchor.toLowerCase()}`)?.value;
|
|
60
103
|
if (!pin('step')) continue;
|
|
@@ -68,64 +111,188 @@ export function pinsAt(w, s) {
|
|
|
68
111
|
}
|
|
69
112
|
|
|
70
113
|
export function wireRows(s, helpers) {
|
|
71
|
-
const motion = s.motion,
|
|
72
|
-
|
|
73
|
-
|
|
114
|
+
const motion = s.motion,
|
|
115
|
+
wires = s.wires;
|
|
116
|
+
if (!wires?.length) return [];
|
|
117
|
+
const rules = loadRuleSet('wire').rules,
|
|
118
|
+
density = rules.current_density.value,
|
|
119
|
+
loop = rules.service_loop.value,
|
|
120
|
+
base = rules.awg_base.value,
|
|
121
|
+
signal = rules.signal_current.value;
|
|
122
|
+
const point = pointer(s, helpers),
|
|
123
|
+
{ placeItems, jointValues } = helpers,
|
|
124
|
+
top = (n) => String(n).split('.')[0],
|
|
125
|
+
poses = samples(motion, jointValues).map((v) => placeItems(motion, v));
|
|
74
126
|
return wires.map((w) => {
|
|
75
|
-
const what = `wire ${w.id}`,
|
|
127
|
+
const what = `wire ${w.id}`,
|
|
128
|
+
chain = [w.from, ...(w.via ?? []), w.to];
|
|
76
129
|
const fns = chain.flatMap((v) => (typeof v === 'string' && !v.includes('.') ? [] : [point(v, what)]));
|
|
77
|
-
const pathLen = (w.via ?? []).reduce((t, v) => {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
130
|
+
const pathLen = (w.via ?? []).reduce((t, v) => {
|
|
131
|
+
const j = typeof v === 'string' && !v.includes('.') && motion.joints.find((x) => x.id === v);
|
|
132
|
+
if (!j) return t;
|
|
133
|
+
let l = 0;
|
|
134
|
+
for (let k = 1; k < j.path.length; k++) l += Math.hypot(...j.path[k].map((c, m) => c - j.path[k - 1][m]));
|
|
135
|
+
return t + l;
|
|
136
|
+
}, 0);
|
|
137
|
+
let longest = 0,
|
|
138
|
+
shortest = Infinity,
|
|
139
|
+
atLongest = null;
|
|
140
|
+
for (const W of poses) {
|
|
141
|
+
const P = fns.map((fn) => fn(W));
|
|
142
|
+
let l = pathLen;
|
|
143
|
+
for (let k = 1; k < P.length; k++)
|
|
144
|
+
l += Math.hypot(P[k][0] - P[k - 1][0], P[k][1] - P[k - 1][1], P[k][2] - P[k - 1][2]);
|
|
145
|
+
if (l > longest) {
|
|
146
|
+
longest = l;
|
|
147
|
+
atLongest = P;
|
|
148
|
+
}
|
|
149
|
+
shortest = Math.min(shortest, l);
|
|
150
|
+
}
|
|
151
|
+
const { current, why } = currentOf(w, s, top, signal),
|
|
152
|
+
gauge = w.gauge ? Number(GAUGE.exec(w.gauge)[1]) : null,
|
|
153
|
+
area = gauge != null ? areaOf(gauge, base) : null,
|
|
154
|
+
capacity = area != null ? area * density : null;
|
|
155
|
+
return {
|
|
156
|
+
id: w.id,
|
|
157
|
+
from: w.from,
|
|
158
|
+
to: w.to,
|
|
159
|
+
via: w.via ?? [],
|
|
160
|
+
pins: pinsAt(w, s),
|
|
161
|
+
gauge: w.gauge ?? null,
|
|
162
|
+
colour: w.colour ?? null,
|
|
163
|
+
conductors: w.conductors ?? (s.motion.drives.some((d) => [top(w.from), top(w.to)].includes(d.id)) ? 4 : 1),
|
|
164
|
+
connectors: w.connectors ?? null,
|
|
165
|
+
longest,
|
|
166
|
+
shortest,
|
|
167
|
+
length: Math.ceil(longest + loop),
|
|
168
|
+
loop,
|
|
169
|
+
current,
|
|
170
|
+
why,
|
|
171
|
+
area,
|
|
172
|
+
capacity,
|
|
173
|
+
route: atLongest,
|
|
174
|
+
};
|
|
83
175
|
});
|
|
84
176
|
}
|
|
85
177
|
|
|
86
178
|
export function wireChecks(s, f, helpers) {
|
|
87
179
|
for (const w of wireRows(s, helpers)) {
|
|
88
|
-
const refs = { wire: w.id, from: w.from, to: w.to },
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
180
|
+
const refs = { wire: w.id, from: w.from, to: w.to },
|
|
181
|
+
at = w.route?.[0],
|
|
182
|
+
values = { length: w.length, longest: w.longest, shortest: w.shortest, current: w.current, capacity: w.capacity };
|
|
183
|
+
const run = (s.runs ?? []).filter((r) => r.wire === w.id),
|
|
184
|
+
clips = run.reduce((t, r) => t + r.count, 0);
|
|
185
|
+
f(
|
|
186
|
+
'info',
|
|
187
|
+
`${w.id}: ${w.from} to ${w.to}, ${n3(w.length, 0)} mm with its ${w.loop} mm loop (${n3(w.shortest, 0)} to ${n3(w.longest, 0)} mm as the joints move)${run.length ? `; ${run.map((r) => `${n3(r.length, 0)} mm of it along ${r.along}`).join(', ')}, held by ${clips} cable clip${clips > 1 ? 's' : ''}` : ''}`,
|
|
188
|
+
null,
|
|
189
|
+
{
|
|
190
|
+
code: 'wire.length',
|
|
191
|
+
at,
|
|
192
|
+
refs,
|
|
193
|
+
values: { ...values, ...(run.length ? { along: run.reduce((t, r) => t + r.length, 0), clips } : {}) },
|
|
194
|
+
},
|
|
195
|
+
);
|
|
196
|
+
if (w.capacity == null) {
|
|
197
|
+
f(
|
|
198
|
+
'warn',
|
|
199
|
+
`${w.id}: no gauge given, so nothing checks it against ${n3(w.current, 2)} A (${w.why})`,
|
|
200
|
+
`${w.id}: no gauge`,
|
|
201
|
+
{ code: 'wire.gauge', at, refs, values },
|
|
202
|
+
);
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (w.current > w.capacity)
|
|
206
|
+
f(
|
|
207
|
+
'fail',
|
|
208
|
+
`${w.id}: ${w.gauge} carries ${n3(w.capacity, 2)} A at most, and this carries ${n3(w.current, 2)} A (${w.why}): a thicker wire`,
|
|
209
|
+
`${w.id}: too thin`,
|
|
210
|
+
{ code: 'wire.gauge', at, refs, values },
|
|
211
|
+
);
|
|
212
|
+
else
|
|
213
|
+
f('pass', `${w.id}: ${w.gauge} takes ${n3(w.current, 2)} A (${w.why}), up to ${n3(w.capacity, 2)} A`, null, {
|
|
214
|
+
code: 'wire.gauge',
|
|
215
|
+
at,
|
|
216
|
+
refs,
|
|
217
|
+
values,
|
|
218
|
+
});
|
|
94
219
|
}
|
|
95
220
|
}
|
|
96
221
|
|
|
97
222
|
// A route's stations: each anchor as [item, local point]; a path joint in the route is its whole polyline, on its parent
|
|
98
223
|
function stations(s, chain, mul) {
|
|
99
|
-
const motion = s.motion,
|
|
224
|
+
const motion = s.motion,
|
|
225
|
+
out = [],
|
|
226
|
+
ids = motion.items.map((x) => x[0]);
|
|
100
227
|
for (const v of chain) {
|
|
101
|
-
if (typeof v === 'string' && !v.includes('.')) {
|
|
102
|
-
|
|
228
|
+
if (typeof v === 'string' && !v.includes('.')) {
|
|
229
|
+
const j = motion.joints.find((x) => x.id === v);
|
|
230
|
+
if (j)
|
|
231
|
+
for (const p of j.path) {
|
|
232
|
+
const W = mul(j.a, [1, 0, 0, p[0], 0, 1, 0, p[1], 0, 0, 1, p[2]]);
|
|
233
|
+
out.push([j.parent, W[3], W[7], W[11]]);
|
|
234
|
+
}
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const bits = String(v).split('.'),
|
|
238
|
+
name = bits.pop(),
|
|
239
|
+
id = bits.join('.'),
|
|
240
|
+
m = motion.marks.find((x) => x.id === id && x.name === name);
|
|
103
241
|
if (m) out.push([ids.indexOf(id), m.frame[3], m.frame[7], m.frame[11]]);
|
|
104
242
|
}
|
|
105
243
|
return out;
|
|
106
244
|
}
|
|
107
|
-
const worldOf = (W, [, x, y, z]) => [
|
|
245
|
+
const worldOf = (W, [, x, y, z]) => [
|
|
246
|
+
W[0] * x + W[1] * y + W[2] * z + W[3],
|
|
247
|
+
W[4] * x + W[5] * y + W[6] * z + W[7],
|
|
248
|
+
W[8] * x + W[9] * y + W[10] * z + W[11],
|
|
249
|
+
];
|
|
108
250
|
const I = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
|
109
251
|
|
|
110
252
|
/** Each wire's route as stations a link carries: [[id, [[item, x, y, z], …]]], the item -1 (world) when nothing moves. */
|
|
111
253
|
export function wireRoutes(s, { placeItems, mul }) {
|
|
112
|
-
const hasJoints = s.motion.joints.length > 0,
|
|
113
|
-
|
|
254
|
+
const hasJoints = s.motion.joints.length > 0,
|
|
255
|
+
W = hasJoints ? null : placeItems(s.motion, s.jointValues);
|
|
256
|
+
return (s.wires || []).map((w) => [
|
|
257
|
+
w.id,
|
|
258
|
+
stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) =>
|
|
259
|
+
hasJoints ? p.map((v) => +v.toFixed(3)) : [-1, ...worldOf(p[0] < 0 ? I : W[p[0]], p).map((v) => +v.toFixed(3))],
|
|
260
|
+
),
|
|
261
|
+
]);
|
|
114
262
|
}
|
|
115
263
|
|
|
116
264
|
// A thin square tube along each wire at the assembly's pose, for previews: drawn faint, never a part, so no check sees it
|
|
117
265
|
export function wireTubes(s, { placeItems, mul }) {
|
|
118
|
-
const worlds = placeItems(s.motion, s.jointValues),
|
|
266
|
+
const worlds = placeItems(s.motion, s.jointValues),
|
|
267
|
+
r = 0.5,
|
|
268
|
+
out = [];
|
|
119
269
|
for (const w of s.wires || []) {
|
|
120
|
-
const pts = stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) => worldOf(p[0] < 0 ? I : worlds[p[0]], p)),
|
|
270
|
+
const pts = stations(s, [w.from, ...(w.via ?? []), w.to], mul).map((p) => worldOf(p[0] < 0 ? I : worlds[p[0]], p)),
|
|
271
|
+
tris = [];
|
|
121
272
|
for (let k = 1; k < pts.length; k++) {
|
|
122
|
-
const a = pts[k - 1],
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
273
|
+
const a = pts[k - 1],
|
|
274
|
+
b = pts[k],
|
|
275
|
+
d = b.map((c, i) => c - a[i]),
|
|
276
|
+
l = Math.hypot(...d);
|
|
277
|
+
if (l < 1e-6) continue;
|
|
278
|
+
const z = d.map((c) => c / l),
|
|
279
|
+
side = Math.abs(z[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0],
|
|
280
|
+
x0 = [z[1] * side[2] - z[2] * side[1], z[2] * side[0] - z[0] * side[2], z[0] * side[1] - z[1] * side[0]],
|
|
281
|
+
m = Math.hypot(...x0),
|
|
282
|
+
x = x0.map((c) => c / m),
|
|
283
|
+
y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]];
|
|
284
|
+
const corner = (o, sx, sy) => o.map((c, i) => c + (sx * x[i] + sy * y[i]) * r),
|
|
285
|
+
ring = (o) => [corner(o, 1, 1), corner(o, -1, 1), corner(o, -1, -1), corner(o, 1, -1)],
|
|
286
|
+
A = ring(a),
|
|
287
|
+
B = ring(b);
|
|
288
|
+
for (let q = 0; q < 4; q++) {
|
|
289
|
+
const n = (q + 1) % 4;
|
|
290
|
+
tris.push([A[q], A[n], B[n]], [A[q], B[n], B[q]]);
|
|
291
|
+
}
|
|
126
292
|
tris.push([A[0], A[2], A[1]], [A[0], A[3], A[2]], [B[0], B[1], B[2]], [B[0], B[2], B[3]]);
|
|
127
293
|
}
|
|
128
|
-
if (tris.length)
|
|
294
|
+
if (tris.length)
|
|
295
|
+
out.push({ name: `wire.${w.id}`, role: 'wire', label: `wire ${w.id}`, item: null, triangles: tris });
|
|
129
296
|
}
|
|
130
297
|
return out;
|
|
131
298
|
}
|
|
@@ -133,8 +300,24 @@ export function wireTubes(s, { placeItems, mul }) {
|
|
|
133
300
|
// The sheet: each wire, its length, gauge, colour and connectors, in Markdown
|
|
134
301
|
export function wiringSheet(rows) {
|
|
135
302
|
const line = (a) => `| ${a.join(' | ')} |`;
|
|
136
|
-
return [
|
|
137
|
-
|
|
303
|
+
return [
|
|
304
|
+
line(['Wire', 'From', 'To', 'Length (mm)', 'Gauge', 'Conductors', 'Colour', 'Connectors', 'Board pins', 'Carries']),
|
|
305
|
+
line(['---', '---', '---', '---:', '---', '---:', '---', '---', '---', '---']),
|
|
306
|
+
...rows.map((w) =>
|
|
307
|
+
line([
|
|
308
|
+
w.id,
|
|
309
|
+
w.from,
|
|
310
|
+
w.to,
|
|
311
|
+
w.length,
|
|
312
|
+
w.gauge ?? '',
|
|
313
|
+
w.conductors,
|
|
314
|
+
w.colour ?? '',
|
|
315
|
+
Array.isArray(w.connectors) ? w.connectors.join(' to ') : (w.connectors ?? ''),
|
|
316
|
+
w.pins ?? '',
|
|
317
|
+
`${n3(w.current, 2)} A, ${w.why}`,
|
|
318
|
+
]),
|
|
319
|
+
),
|
|
320
|
+
].join('\n');
|
|
138
321
|
}
|
|
139
322
|
|
|
140
323
|
// An assembly's wires with model-link's placing: their rows (lengths, gauges, pins), tubes to draw and routes. Here
|
package/lib/workspace.mjs
CHANGED
|
@@ -6,9 +6,11 @@
|
|
|
6
6
|
// printer the rule set a print is checked against (bed, overhang, bridges); a project.json's "printer" wins
|
|
7
7
|
// viewUrl the model page that links open (the public one by default: it reads links as data, nothing is uploaded)
|
|
8
8
|
// targets optional extras: show (put a model on display: a module of your own) and shorten (short links: "gist")
|
|
9
|
+
// designTimeout, designMemory how long a design may run in the sandbox (seconds) and the memory it may hold
|
|
10
|
+
// (megabytes): sandbox.mjs designLimits; above the defaults, only once the workspace is trusted
|
|
9
11
|
import fs from 'node:fs';
|
|
10
12
|
import path from 'node:path';
|
|
11
|
-
import { host, readJson } from './host.mjs';
|
|
13
|
+
import { host, readJson, guardReads, readOwnText } from './host.mjs';
|
|
12
14
|
import { fileURLToPath } from 'node:url';
|
|
13
15
|
import { plainName } from './names.mjs';
|
|
14
16
|
|
|
@@ -23,18 +25,158 @@ function find() {
|
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
export const WS = find();
|
|
28
|
+
|
|
29
|
+
// Links out of the workspace. A workspace can come from anyone, and git carries symbolic links: a rules/x.json, a
|
|
30
|
+
// design's .json or a folder of a project that is a link to a file of the user's elsewhere (a key in their home folder)
|
|
31
|
+
// would be read as the workspace's own, and what is read can end up in a model link or an exported file. So the
|
|
32
|
+
// workspace's own files are read only where they really are inside it: by the file's real path (every link on its way
|
|
33
|
+
// followed) against the workspace's real path. node_modules is left alone: packages are linked in from elsewhere as a
|
|
34
|
+
// matter of course (npm link, a workspace of packages), and the sandbox holds what a design may load of them.
|
|
35
|
+
let realWs = null;
|
|
36
|
+
const wsReal = () => {
|
|
37
|
+
if (realWs == null)
|
|
38
|
+
try {
|
|
39
|
+
realWs = fs.realpathSync(WS);
|
|
40
|
+
} catch {
|
|
41
|
+
realWs = path.resolve(WS);
|
|
42
|
+
}
|
|
43
|
+
return realWs;
|
|
44
|
+
};
|
|
45
|
+
const within = (dir, f) => {
|
|
46
|
+
const rel = path.relative(dir, f);
|
|
47
|
+
return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* The error for a link in the workspace that leads out of it: code workspace.outside, naming the link.
|
|
51
|
+
* @param {string} link the link, inside the workspace @param {string} to where it really leads
|
|
52
|
+
*/
|
|
53
|
+
export function outsideError(link, to) {
|
|
54
|
+
const name = path.relative(WS, link) || link;
|
|
55
|
+
return Object.assign(
|
|
56
|
+
new Error(
|
|
57
|
+
`${name} is a link to ${to}, outside this workspace (${WS}), so it isn't read: a workspace may read only its own files, and a link could hand a file of yours elsewhere to a design or a model link. To share a file between workspaces, copy it into the workspace, or put it in a package and install that`,
|
|
58
|
+
),
|
|
59
|
+
{ code: 'workspace.outside', file: link },
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* `file`, when it is not the workspace's (one of the kit's rule sets, a package), or when it really is inside the
|
|
64
|
+
* workspace; else an error (code workspace.outside) naming the link on its way that leads out. A file not there yet is
|
|
65
|
+
* returned as it is: reading it finds nothing, and says so.
|
|
66
|
+
* @param {string} file
|
|
67
|
+
* @returns {string}
|
|
68
|
+
*/
|
|
69
|
+
export function ownFile(file) {
|
|
70
|
+
if (host.name !== 'node') return file; // (a workspace in memory has no links)
|
|
71
|
+
const abs = path.resolve(file),
|
|
72
|
+
base = within(WS, abs) ? WS : within(wsReal(), abs) ? wsReal() : null;
|
|
73
|
+
if (!base) return file; // (not the workspace's)
|
|
74
|
+
// (the workspace's own node_modules only: a project, or any other folder, named node_modules is the workspace's)
|
|
75
|
+
if (path.relative(base, abs).split(path.sep)[0] === 'node_modules') return file;
|
|
76
|
+
let real;
|
|
77
|
+
try {
|
|
78
|
+
real = fs.realpathSync(abs);
|
|
79
|
+
} catch {
|
|
80
|
+
return file;
|
|
81
|
+
}
|
|
82
|
+
if (within(wsReal(), real)) return file;
|
|
83
|
+
// the link that leads out: the first on the way down from the workspace whose real path is outside it
|
|
84
|
+
const parts = path.relative(base, abs).split(path.sep);
|
|
85
|
+
for (let i = 1; i <= parts.length; i++) {
|
|
86
|
+
const p = path.join(base, ...parts.slice(0, i));
|
|
87
|
+
try {
|
|
88
|
+
if (fs.lstatSync(p).isSymbolicLink() && !within(wsReal(), fs.realpathSync(p)))
|
|
89
|
+
throw outsideError(path.join(WS, ...parts.slice(0, i)), fs.realpathSync(p));
|
|
90
|
+
} catch (e) {
|
|
91
|
+
if (e.code === 'workspace.outside') throw e;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
throw outsideError(path.join(WS, ...parts), real);
|
|
95
|
+
}
|
|
96
|
+
// The folders already looked through this run (by real path): a run builds many designs of one project, and its
|
|
97
|
+
// links don't change under it, so each folder is walked once
|
|
98
|
+
const walked = new Set();
|
|
99
|
+
/**
|
|
100
|
+
* Throws (code workspace.outside, naming the link) if any of these folders of the workspace, or a folder in them,
|
|
101
|
+
* holds a link whose real path is outside the workspace. The sandbox may read the whole workspace, and Node's
|
|
102
|
+
* permission model follows a link even to a place it was not allowed to read: so before a design runs there, the
|
|
103
|
+
* folders it may read (its project, the rule sets) are looked through. A link that stays inside the workspace is
|
|
104
|
+
* followed and its folder looked through too; node_modules is left to the sandbox's import hook (sandbox-hooks.mjs),
|
|
105
|
+
* and a folder outside the workspace (a design named by a path elsewhere) is not the workspace's to look through.
|
|
106
|
+
* @param {string[]} dirs
|
|
107
|
+
*/
|
|
108
|
+
export function noLinksOut(dirs) {
|
|
109
|
+
if (host.name !== 'node') return;
|
|
110
|
+
const look = (dir, shown) => {
|
|
111
|
+
let real;
|
|
112
|
+
try {
|
|
113
|
+
real = fs.realpathSync(dir);
|
|
114
|
+
} catch {
|
|
115
|
+
return; // (no such folder)
|
|
116
|
+
}
|
|
117
|
+
if (walked.has(real) || !within(wsReal(), real)) return;
|
|
118
|
+
walked.add(real);
|
|
119
|
+
let entries;
|
|
120
|
+
try {
|
|
121
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
122
|
+
} catch {
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
for (const e of entries) {
|
|
126
|
+
if (e.name === 'node_modules') continue;
|
|
127
|
+
const p = path.join(dir, e.name),
|
|
128
|
+
named = path.join(shown, e.name);
|
|
129
|
+
if (e.isSymbolicLink()) {
|
|
130
|
+
let to;
|
|
131
|
+
try {
|
|
132
|
+
to = fs.realpathSync(p);
|
|
133
|
+
} catch {
|
|
134
|
+
continue; // (a link to nothing: reading it finds nothing)
|
|
135
|
+
}
|
|
136
|
+
if (!within(wsReal(), to)) throw outsideError(named, to);
|
|
137
|
+
if (fs.statSync(p).isDirectory()) look(p, named);
|
|
138
|
+
} else if (e.isDirectory()) look(p, named);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
try {
|
|
142
|
+
for (const d of dirs) {
|
|
143
|
+
if (!d) continue;
|
|
144
|
+
const abs = path.resolve(d);
|
|
145
|
+
if (!within(WS, abs) && !within(wsReal(), abs)) continue;
|
|
146
|
+
ownFile(abs); // (the folder itself, or one on its way, a link out: projects/p or rules/ linked in from elsewhere)
|
|
147
|
+
look(abs, abs);
|
|
148
|
+
}
|
|
149
|
+
} catch (e) {
|
|
150
|
+
walked.clear(); // (looked through afresh next time: the link may be put right by then)
|
|
151
|
+
throw e;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// One of the workspace's text files, read only where it really is inside it (ownFile): host.mjs's, held to ownFile below
|
|
156
|
+
export { readOwnText };
|
|
157
|
+
// Every JSON file the tool reads (readJson) is held to this: the workspace's rule sets, projects, designs, assemblies
|
|
158
|
+
guardReads(ownFile);
|
|
159
|
+
|
|
26
160
|
// A cad.config.json that doesn't parse is kept as configError for the command to report in its own words: this runs
|
|
27
161
|
// as the tool is loaded, where an error would reach a person as a stack trace
|
|
28
162
|
export let configError = null;
|
|
163
|
+
/** The kit's own model page, which links open unless a workspace names another (viewUrl in cad.config.json). */
|
|
164
|
+
export const DEFAULT_VIEW = 'https://jonibach.github.io/rulecad/';
|
|
29
165
|
export const config = (() => {
|
|
30
166
|
const f = path.join(WS, 'cad.config.json');
|
|
31
167
|
let own = {};
|
|
32
|
-
try {
|
|
33
|
-
|
|
168
|
+
try {
|
|
169
|
+
if (host.exists(f)) own = readJson(f);
|
|
170
|
+
} catch (e) {
|
|
171
|
+
configError = e;
|
|
172
|
+
}
|
|
173
|
+
return { printer: 'x1c', viewUrl: DEFAULT_VIEW, targets: {}, ...own };
|
|
34
174
|
})();
|
|
35
175
|
|
|
36
176
|
// Rule sets: the workspace's own first (your copies, with your measurements), then the published ones (@rulecad/rules).
|
|
37
|
-
export const RULE_DIRS = [
|
|
177
|
+
export const RULE_DIRS = [
|
|
178
|
+
...new Set([path.join(WS, 'rules'), path.dirname(fileURLToPath(import.meta.resolve('@rulecad/rules/x1c.json')))]),
|
|
179
|
+
];
|
|
38
180
|
|
|
39
181
|
export const paths = {
|
|
40
182
|
projects: path.join(WS, 'projects'),
|
|
@@ -47,8 +189,9 @@ export const paths = {
|
|
|
47
189
|
|
|
48
190
|
// The printer a project's prints are checked against: project.json's "printer", else cad.config.json's. Either is a
|
|
49
191
|
// rule set's name, which becomes part of a path (rules/<printer>.json, and the kit's), so it must be a plain name.
|
|
50
|
-
|
|
51
|
-
|
|
192
|
+
// dir: the project's folder as a release has it (lib/versions.mjs materialise), so it draws for the printer it named then.
|
|
193
|
+
export const printerOf = (project, dir = project && paths.project(project)) => {
|
|
194
|
+
const f = dir && path.join(dir, 'project.json');
|
|
52
195
|
const own = f && host.exists(f) && readJson(f).printer;
|
|
53
196
|
if (own) return plainName(own, '"printer" field', path.relative(WS, f));
|
|
54
197
|
return plainName(config.printer, '"printer" field', 'cad.config.json');
|
|
@@ -64,24 +207,67 @@ const TRUSTED = () => process.env.CAD_TRUSTED || path.join(os.homedir(), '.confi
|
|
|
64
207
|
// The kit's own targets, by exact name. A target is the kit's own only if its name is a key here, never because of
|
|
65
208
|
// what its name looks like or because a file of that name happens to be in the kit: anything else in "targets" (a bare
|
|
66
209
|
// name, a path with / or \, a ../ name that reaches one of the kit's modules) is the workspace's code, and asked about.
|
|
67
|
-
export const OWN_TARGETS = Object.freeze(
|
|
210
|
+
export const OWN_TARGETS = Object.freeze(
|
|
211
|
+
Object.assign(Object.create(null), { gist: new URL('./targets/gist.mjs', import.meta.url).href }),
|
|
212
|
+
);
|
|
68
213
|
/** Whether a target name in cad.config.json is one of the kit's own (exactly a key of OWN_TARGETS). */
|
|
69
214
|
export const isOwnTarget = (name) => typeof name === 'string' && Object.hasOwn(OWN_TARGETS, name);
|
|
70
|
-
/**
|
|
215
|
+
/** The time a design may run in the sandbox unless the workspace says otherwise, in seconds (sandbox.mjs designLimits). */
|
|
216
|
+
export const DESIGN_TIMEOUT = 3600;
|
|
217
|
+
/** The memory a design's JavaScript may hold in the sandbox unless the workspace says otherwise, in megabytes. */
|
|
218
|
+
export const DESIGN_MEMORY = 4096;
|
|
219
|
+
// A design's limits raised above these by cad.config.json are asked about too: a workspace cloned from elsewhere could
|
|
220
|
+
// otherwise take the limits away (a month, a million megabytes) and have a design fill the machine on its first command
|
|
221
|
+
const above = (v, limit) => {
|
|
222
|
+
const n = typeof v === 'number' ? v : typeof v === 'string' && v.trim() ? Number(v) : NaN;
|
|
223
|
+
return Number.isFinite(n) && n > limit ? n : null;
|
|
224
|
+
};
|
|
225
|
+
/** What this workspace asks to run outside the sandbox, or past the sandbox's limits: [] when nothing. */
|
|
71
226
|
export function asks(cfg = config) {
|
|
72
|
-
const own = Object.entries(cfg.targets || {})
|
|
73
|
-
|
|
227
|
+
const own = Object.entries(cfg.targets || {})
|
|
228
|
+
.filter(([, v]) => v && !isOwnTarget(v))
|
|
229
|
+
.map(([k, v]) => `the ${k} target ${typeof v === 'string' ? v : JSON.stringify(v)}`);
|
|
230
|
+
const time = above(cfg.designTimeout, DESIGN_TIMEOUT),
|
|
231
|
+
memory = above(cfg.designMemory, DESIGN_MEMORY);
|
|
232
|
+
return [
|
|
233
|
+
...(cfg.sandbox === false ? ['designs run outside the sandbox'] : []),
|
|
234
|
+
...(time != null ? [`designs run for up to ${time} s`] : []),
|
|
235
|
+
...(memory != null ? [`designs use up to ${memory} MB`] : []),
|
|
236
|
+
...own,
|
|
237
|
+
].sort();
|
|
74
238
|
}
|
|
75
|
-
const trustList = () => {
|
|
239
|
+
const trustList = () => {
|
|
240
|
+
try {
|
|
241
|
+
return JSON.parse(fs.readFileSync(TRUSTED(), 'utf8'));
|
|
242
|
+
} catch {
|
|
243
|
+
return {};
|
|
244
|
+
}
|
|
245
|
+
};
|
|
76
246
|
/** Whether the user has trusted this workspace for all it asks. */
|
|
77
|
-
export const trusted = (cfg = config) => {
|
|
247
|
+
export const trusted = (cfg = config) => {
|
|
248
|
+
const a = asks(cfg);
|
|
249
|
+
if (!a.length || process.env.CAD_TRUST === '1') return true;
|
|
250
|
+
const t = trustList()[WS];
|
|
251
|
+
return !!t && a.every((x) => t.includes(x));
|
|
252
|
+
};
|
|
78
253
|
/** Trust this workspace for what it asks now. */
|
|
79
|
-
export function trust(cfg = config) {
|
|
254
|
+
export function trust(cfg = config) {
|
|
255
|
+
const list = trustList();
|
|
256
|
+
list[WS] = asks(cfg);
|
|
257
|
+
fs.mkdirSync(path.dirname(TRUSTED()), { recursive: true });
|
|
258
|
+
fs.writeFileSync(TRUSTED(), JSON.stringify(list, null, 2) + '\n');
|
|
259
|
+
return list[WS];
|
|
260
|
+
}
|
|
80
261
|
/**
|
|
81
262
|
* Throws, saying what it asks, where it asks it and how to allow it, when this workspace isn't trusted for what it asks.
|
|
82
263
|
* @param {object} [cfg]
|
|
83
264
|
*/
|
|
84
265
|
export function needTrust(cfg = config) {
|
|
85
266
|
if (trusted(cfg)) return;
|
|
86
|
-
throw Object.assign(
|
|
267
|
+
throw Object.assign(
|
|
268
|
+
new Error(
|
|
269
|
+
`this workspace asks for ${asks(cfg).join(' and ')} (cad.config.json). If you trust it, run cad trust once; until then, it isn't done`,
|
|
270
|
+
),
|
|
271
|
+
{ code: 'workspace.untrusted' },
|
|
272
|
+
);
|
|
87
273
|
}
|