@rulecad/cad 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/links.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  // Model links: a design or an assembly as the model page's data (@rulecad/model-link): its parts (each on its filament
2
2
  // slot), the rules card and sheet, a board's 2D views, an assembly's joints. Used by cad link and cad show.
3
3
  import path from 'node:path';
4
- import { fromParts, fromShapes, encode, check as checkLink, expand } from '@rulecad/model-link';
4
+ import { fromParts, fromShapes, encode } from '@rulecad/model-link';
5
5
  import { fmt } from './rules.mjs';
6
- import { paths, config } from './workspace.mjs';
7
- import { host, readJson } from './host.mjs';
6
+ import { paths, config, DEFAULT_VIEW } from './workspace.mjs';
7
+ import { readJson } from './host.mjs';
8
8
  import { pcbEngine } from './design.mjs';
9
9
  import { shapes, motionData, checkAssembly, wireRoutesOf } from './assembly.mjs';
10
10
  import { slotOf } from './threemf.mjs';
@@ -15,29 +15,68 @@ import { cutListOf } from './beams.mjs';
15
15
  /** The project's filaments: { base: { slot: 1, … }, legend: { slot: 2, … } } in project.json. @param {string} project */
16
16
  export const filaments = (project) => readJson(path.join(paths.project(project), 'project.json')).filaments || {};
17
17
  /** The filaments in AMS slot order, for the print file: [{ colour }, …], slot 1 first. */
18
- export const slots = (fil) => { const out = []; for (const f of Object.values(fil)) out[(f.slot || 1) - 1] = f; return Array.from(out, (f) => f || {}); };
18
+ export const slots = (fil) => {
19
+ const out = [];
20
+ for (const f of Object.values(fil)) out[(f.slot || 1) - 1] = f;
21
+ return Array.from(out, (f) => f || {});
22
+ };
19
23
 
20
24
  export const VIEW = process.env.CAD_VIEW_URL || config.viewUrl;
25
+ /**
26
+ * A line to print with links when they open a model page other than the kit's own: a workspace from elsewhere can
27
+ * name any site in its cad.config.json, and the person sharing a link should see where it leads. Null for the kit's.
28
+ * @param {string} [view] the page the links open
29
+ * @returns {string | null}
30
+ */
31
+ export function viewNote(view = VIEW) {
32
+ if (view === DEFAULT_VIEW) return null;
33
+ const from = view === process.env.CAD_VIEW_URL ? 'CAD_VIEW_URL' : `"viewUrl" in cad.config.json`;
34
+ return `note: these links open ${view}, the model page ${from} names, not the kit's own (${DEFAULT_VIEW})`;
35
+ }
21
36
  /** A link to the model page; one the page would turn away is an error here, not when someone opens it. */
22
37
  export async function linkTo(model) {
23
- const errors = checkLink(model.shapes ? expand(model) : model);
24
- if (errors.length) throw new Error(`no link: ${errors[0].text}`);
25
- return `${VIEW}#m=${await encode(model)}`;
38
+ let token;
39
+ try {
40
+ token = await encode(model); // (encode() checks the model as the page will)
41
+ } catch (e) {
42
+ throw new Error(`no link: ${e.message}`);
43
+ }
44
+ return `${VIEW}#m=${token}`;
26
45
  }
27
46
 
28
47
  // The rules sheet: each object's variables, then the rules they use (once each)
29
48
  export function sheet(objects, { noRules = false } = {}) {
30
49
  if (noRules) return {};
31
- const rows = [], seen = new Set(), trim = (r) => { while (r.length && (r[r.length - 1] === '' || r[r.length - 1] == null)) r.pop(); return r; };
32
- for (const [obj, entries] of objects) for (const e of entries) {
33
- if (!e.name.includes('.')) rows.push(trim([obj, e.label || e.name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '']));
34
- }
35
- for (const [, entries] of objects) for (const e of entries) {
36
- if (!e.name.includes('.') || !e.used || e.private || seen.has(e.name)) continue;
37
- seen.add(e.name);
38
- const [set, name] = e.name.split('.');
39
- rows.push(trim([set, name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '', e.kind || '', e.source || '', e.checked || '']));
40
- }
50
+ const rows = [],
51
+ seen = new Set(),
52
+ trim = (r) => {
53
+ while (r.length && (r[r.length - 1] === '' || r[r.length - 1] == null)) r.pop();
54
+ return r;
55
+ };
56
+ for (const [obj, entries] of objects)
57
+ for (const e of entries) {
58
+ if (!e.name.includes('.'))
59
+ rows.push(trim([obj, e.label || e.name, fmt(e.value), e.unit || '', e.rule || '', e.expr || '']));
60
+ }
61
+ for (const [, entries] of objects)
62
+ for (const e of entries) {
63
+ if (!e.name.includes('.') || !e.used || e.private || seen.has(e.name)) continue;
64
+ seen.add(e.name);
65
+ const [set, name] = e.name.split('.');
66
+ rows.push(
67
+ trim([
68
+ set,
69
+ name,
70
+ fmt(e.value),
71
+ e.unit || '',
72
+ e.rule || '',
73
+ e.expr || '',
74
+ e.kind || '',
75
+ e.source || '',
76
+ e.checked || '',
77
+ ]),
78
+ );
79
+ }
41
80
  return rows.length ? { sheet: rows } : {};
42
81
  }
43
82
 
@@ -46,25 +85,44 @@ const triangles = (polys) => polys.flatMap((t) => t.slice(1, -1).map((_, i) => [
46
85
  /** A built design as a model: full print precision (triangles), the rules card and sheet, exactly which version it is. */
47
86
  export async function objectModel(b, { title, version, src, set, filaments: fil = {}, noRules = false }) {
48
87
  return {
49
- title, version, src, ...(set ? { set } : {}),
50
- material: b.object.material, orientation: b.object.orientation,
88
+ title,
89
+ version,
90
+ src,
91
+ ...(set ? { set } : {}),
92
+ material: b.object.material,
93
+ orientation: b.object.orientation,
51
94
  rules: b.entries.filter((e) => e.show).map((e) => [e.label || e.name, fmt(e.value), e.unit || '']),
52
95
  ...sheet([[b.object.name, b.entries]], { noRules }),
53
96
  ...(b.circuit ? { views: await (await pcbEngine()).views(b.circuit) } : {}), // boards: the 2D board and schematic
54
97
  ...(b.circuit ? await fabOf([[b.object.name, version, b]]) : {}), // and the zip to order it with
55
- ...fromParts(b.parts.map((p) => ({ name: p.name, role: p.role, label: p.label, slot: slotOf(fil, p.filament), triangles: triangles(p.triangles) }))),
98
+ ...fromParts(
99
+ b.parts.map((p) => ({
100
+ name: p.name,
101
+ role: p.role,
102
+ label: p.label,
103
+ slot: slotOf(fil, p.filament),
104
+ triangles: triangles(p.triangles),
105
+ })),
106
+ ),
56
107
  };
57
108
  }
58
109
 
59
110
  // Each board's fab zip (cad export's: Gerbers, drill files, BOM, placement), for the page to offer as a download. A
60
111
  // board whose files can't be made here (one that needs KiCad, without it) goes without, and says why
61
112
  async function fabOf(boards) {
62
- const pcb = await pcbEngine(), { zip, fabName } = await import('@rulecad/model-link'), fab = [];
113
+ const pcb = await pcbEngine(),
114
+ { zip, fabName } = await import('@rulecad/model-link'),
115
+ fab = [];
63
116
  for (const [name, version, b] of boards) {
64
117
  try {
65
118
  const files = await pcb.fabFiles(b.circuit, name, { source: b.source });
66
- fab.push({ name: fabName(`${name}${version ? `@${version}` : ''}-fab`), zip: Buffer.from(await zip(Object.entries(files))).toString('base64') });
67
- } catch (e) { console.error(` ${name}: no fab zip in the link (${String(e.message || e).split('\n')[0]})`); }
119
+ fab.push({
120
+ name: fabName(`${name}${version ? `@${version}` : ''}-fab`),
121
+ zip: Buffer.from(await zip(Object.entries(files))).toString('base64'),
122
+ });
123
+ } catch (e) {
124
+ console.error(` ${name}: no fab zip in the link (${String(e.message || e).split('\n')[0]})`);
125
+ }
68
126
  }
69
127
  return fab.length ? { fab } : {};
70
128
  }
@@ -73,40 +131,82 @@ async function fabOf(boards) {
73
131
  export async function assemblyModel(s, { title, versions, filaments: fil = {}, noRules = false, steps }) {
74
132
  // a beam is labelled by its mark (beams that are the same share one, as the cut list and the sheets name them), so the
75
133
  // parts list groups them and a beam picked shows its mark
76
- const marks = new Map(s.objects.filter((o) => o.mark).map((o) => [o.id, o.mark])), labelOf = (q, p) => (marks.has(q.item) ? `mark ${marks.get(q.item)}: ${String(q.label).replace(/^[^:]*: mark \w+, /, '')}` : p.object || p.label);
77
- const placed = shapes(s.parts), list = placed.shapes.length ? placed.place.map(([i, ...m], n) => { const p = placed.shapes[i].part; return { shape: i, role: p.role, label: labelOf(s.parts[n], p), slot: slotOf(fil, p.filament), triangles: triangles(placed.shapes[i].triangles), matrix: m, name: s.parts[n].name }; }) : [];
134
+ const marks = new Map(s.objects.filter((o) => o.mark).map((o) => [o.id, o.mark])),
135
+ labelOf = (q, p) =>
136
+ marks.has(q.item)
137
+ ? `mark ${marks.get(q.item)}: ${String(q.label).replace(/^[^:]*: mark \w+, /, '')}`
138
+ : p.object || p.label;
139
+ const placed = shapes(s.parts),
140
+ list = placed.shapes.length
141
+ ? placed.place.map(([i, ...m], n) => {
142
+ const p = placed.shapes[i].part;
143
+ return {
144
+ shape: i,
145
+ role: p.role,
146
+ label: labelOf(s.parts[n], p),
147
+ slot: slotOf(fil, p.filament),
148
+ triangles: triangles(placed.shapes[i].triangles),
149
+ matrix: m,
150
+ name: s.parts[n].name,
151
+ };
152
+ })
153
+ : [];
78
154
  // A pose that sets items' variables draws some parts differently (a flexure bent): each such part's shape in that
79
155
  // pose goes in the link as a "pose" part, placed as the part is, to be swapped in when the page shows the pose
80
156
  const alts = [];
81
- if (list.length) for (const pose of Object.keys(s.motion?.poses || {})) {
82
- const t = s.at(pose);
83
- t.parts.forEach((q, n) => {
84
- const p = s.parts[n];
85
- if (!p || !q || q.name !== p.name || q.hash === p.hash) return;
86
- alts.push({ of: n, pose });
87
- list.push({ shape: `${q.hash}@pose`, role: 'pose', label: list[n].label, triangles: triangles(q.localTriangles), matrix: list[n].matrix, name: `${p.name}@${pose}` });
88
- });
89
- }
157
+ if (list.length)
158
+ for (const pose of Object.keys(s.motion?.poses || {})) {
159
+ const t = s.at(pose);
160
+ t.parts.forEach((q, n) => {
161
+ const p = s.parts[n];
162
+ if (!p || !q || q.name !== p.name || q.hash === p.hash) return;
163
+ alts.push({ of: n, pose });
164
+ list.push({
165
+ shape: `${q.hash}@pose`,
166
+ role: 'pose',
167
+ label: list[n].label,
168
+ triangles: triangles(q.localTriangles),
169
+ matrix: list[n].matrix,
170
+ name: `${p.name}@${pose}`,
171
+ });
172
+ });
173
+ }
90
174
  const model = {
91
- title, version: versions, src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short
175
+ title,
176
+ version: versions,
177
+ src: `${s.project}/${s.name}`, // object versions are in version: the file name stays short
92
178
  ...(s.a?.show === 'built' ? { show: 'built' } : {}), // its references drawn solid on the page
93
179
  rules: [],
94
- ...sheet([...new Map(s.objects.filter((o) => o.built?.entries).map((o) => [o.objName, o.built.entries])).entries()], { noRules }),
180
+ ...sheet(
181
+ [...new Map(s.objects.filter((o) => o.built?.entries).map((o) => [o.objName, o.built.entries])).entries()],
182
+ { noRules },
183
+ ),
95
184
  // Its boards' 2D views (copper, schematic), so one link holds the whole build: tabs over the 3D model
96
185
  ...(await (async () => {
97
186
  const boards = [...new Map(s.objects.filter((o) => o.built?.circuit).map((o) => [o.objName, o])).values()];
98
187
  if (!boards.length) return {};
99
- const pcb = await pcbEngine(), views = [];
100
- for (const o of boards) for (const [n, svg] of await pcb.views(o.built.circuit)) views.push([boards.length > 1 ? `${o.objName} ${n}` : n, svg]);
188
+ const pcb = await pcbEngine(),
189
+ views = [];
190
+ for (const o of boards)
191
+ for (const [n, svg] of await pcb.views(o.built.circuit))
192
+ views.push([boards.length > 1 ? `${o.objName} ${n}` : n, svg]);
101
193
  return { views, ...(await fabOf(boards.map((o) => [o.objName, o.version || o.built.object?.version, o.built]))) };
102
194
  })()),
103
195
  ...fromShapes(list),
104
196
  };
105
197
  // each mark's cut-and-drill sheet, as a 2D view (Beams: A, B ..): a beam picked in the model opens its own
106
198
  const cut = marks.size ? cutListOf(s) : null;
107
- if (cut) model.views = [...(model.views ?? []), ...cut.marks.map((m) => [`Beams: ${m.mark}`, beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }).svg])];
199
+ if (cut)
200
+ model.views = [
201
+ ...(model.views ?? []),
202
+ ...cut.marks.map((m) => [
203
+ `Beams: ${m.mark}`,
204
+ beamSheet(m.beam, { mark: m.mark, items: m.items, grams: m.grams }).svg,
205
+ ]),
206
+ ];
108
207
  Object.assign(model, motionData(s));
109
- if (alts.length) { // the shapes parts take in other poses, on the same items, and which pose shows which
208
+ if (alts.length) {
209
+ // the shapes parts take in other poses, on the same items, and which pose shows which
110
210
  model.motion.part.push(...alts.map((x) => model.motion.part[x.of]));
111
211
  model.motion.swap = {};
112
212
  alts.forEach((x, i) => (model.motion.swap[x.pose] ||= []).push([x.of, list.length - alts.length + i]));
@@ -116,9 +216,16 @@ export async function assemblyModel(s, { title, versions, filaments: fil = {}, n
116
216
  if (s.wires?.length) model.wires = wireRoutesOf(s);
117
217
  if (s.task || s.wires?.length || s.a.fasten?.length || s.objects.some((o) => o.bought || o.motor)) {
118
218
  const findings = s.task ? checkAssembly(s) : [];
119
- if (s.task && model.motion) { model.task = taskData(s, findings); const carried = stepsData(s, steps); if (carried) model.steps = carried; }
219
+ if (s.task && model.motion) {
220
+ model.task = taskData(s, findings);
221
+ const carried = stepsData(s, steps);
222
+ if (carried) model.steps = carried;
223
+ }
120
224
  Object.assign(model, await buildData(s));
121
- if (!noRules && s.task) { const rows = ledgerRows(s, findings); if (rows.length) model.sheet = [...rows, ...(model.sheet ?? [])]; }
225
+ if (!noRules && s.task) {
226
+ const rows = ledgerRows(s, findings);
227
+ if (rows.length) model.sheet = [...rows, ...(model.sheet ?? [])];
228
+ }
122
229
  }
123
230
  return model;
124
231
  }