@rulecad/pcb 0.4.0 → 0.5.1

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 (3) hide show
  1. package/circuit.mjs +11 -4
  2. package/package.json +6 -2
  3. package/pcb.mjs +74 -26
package/circuit.mjs CHANGED
@@ -40,14 +40,16 @@ import { fp } from '@tscircuit/footprinter';
40
40
  import { symbols } from 'schematic-symbols';
41
41
 
42
42
  const SUB = 'subcircuit_source_group_0';
43
- const PASTE = 0.7;
43
+ // Solder paste: each side of an SMD pad's opening this share of the pad's (an aperture about 10% smaller than its pad, as
44
+ // stencil guides give for ordinary pads: 81% of the area; 0.7, tscircuit's, left 49%)
45
+ const PASTE = 0.9;
44
46
  // Quarter turns, counter-clockwise, as exact cosines and sines (no rounding error in pad positions)
45
47
  const QUARTER = { 0: [1, 0], 90: [0, 1], 180: [-1, 0], 270: [0, -1] };
46
48
  function quarter(r = 0) {
47
49
  const t = QUARTER[((r % 360) + 360) % 360];
48
50
  if (!t) throw new Error(`a part's rotation is ${r}°: boards take 0, 90, 180 or 270`);
49
51
  return t;
50
- } // solder paste, as a share of an SMD pad (what tscircuit uses)
52
+ }
51
53
  // The board's manufacturing minimums (mm): tscircuit's defaults, within what common fabs make. The router keeps to them.
52
54
  const FAB_MINIMUMS = { min_trace_width: 0.1, min_via_hole_diameter: 0.2, min_via_pad_diameter: 0.3, min_via_hole_edge_to_via_hole_edge_clearance: 0.1,
53
55
  min_trace_to_hole_edge_clearance: 0.2, min_trace_to_pad_edge_clearance: 0.1, min_pad_edge_to_pad_edge_clearance: 0.1,
@@ -112,7 +114,8 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
112
114
  for (const part of board.parts) {
113
115
  const comp = add('source_component', { ftype: part.ftype, name: part.name, manufacturer_part_number: part.mpn,
114
116
  ...(part.lcsc ? { supplier_part_numbers: { jlcpcb: [part.lcsc] } } : {}), ...(part.value ? { display_value: part.value } : {}), ...(part.bom === false ? { exclude_from_bom: true } : {}),
115
- are_pins_interchangeable: part.ftype === 'simple_switch', source_group_id: 'source_group_0', subcircuit_id: SUB });
117
+ are_pins_interchangeable: part.ftype === 'simple_switch', source_group_id: 'source_group_0', subcircuit_id: SUB,
118
+ ...(part.package || typeof part.footprint === 'string' ? { rulecad_package: part.package ?? part.footprint } : {}) }); // (for the BOM's footprint column)
116
119
  const fpEls = part.footprint ? fp.string(part.footprint).circuitJson() : [];
117
120
  const mirror = part.layer === 'bottom' ? -1 : 1;
118
121
  const [cos, sin] = quarter(part.rotation), swap = sin !== 0;
@@ -146,6 +149,7 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
146
149
  // (the vias the router may make: the board's sizes, else ones with the ring a fab recommends, 0.3 in 0.8)
147
150
  add('pcb_board', { source_board_id: sourceBoard.source_board_id, subcircuit_id: SUB, center: board.center, thickness: board.thickness, num_layers: copper.length,
148
151
  width: board.width, height: board.height, ...(board.outline ? { outline: board.outline.map(({ x, y }) => ({ x, y })) } : {}), material: 'fr4', ...FAB_MINIMUMS,
152
+ ...(board.fab ? { min_trace_width: board.fab.track_min, min_trace_to_pad_edge_clearance: board.fab.gap_min, min_pad_edge_to_pad_edge_clearance: board.fab.gap_min, min_via_hole_edge_to_via_hole_edge_clearance: board.fab.gap_min } : {}), // (the fab's own, when the board names its rules)
149
153
  min_via_hole_diameter: board.via_hole ?? 0.3, min_via_pad_diameter: board.via_pad ?? 0.8 });
150
154
 
151
155
  for (const { part, comp, pads, sourcePorts, fpEls, at, mirror, size } of placed) {
@@ -195,7 +199,10 @@ export async function circuitJson(board, { route = defaultRouter } = {}) {
195
199
  // ---- planes: each plane net's pads reach its inner layer, through their own holes or a via each ----
196
200
  if (board.planes && copper.length < 4) throw new Error('planes need a board of 4 layers or more (board.layers): the outer two carry the tracks');
197
201
  const netOf = new Map(); // `${part}.${pin}` -> net, for the pours
198
- for (const [net, spec] of Object.entries(board.nets || {})) for (const pin of Array.isArray(spec) ? spec : spec.pins) netOf.set(pin, net);
202
+ for (const [net, spec] of Object.entries(board.nets || {})) for (const pin of Array.isArray(spec) ? spec : spec.pins) {
203
+ if (netOf.has(pin) && netOf.get(pin) !== net) throw new Error(`${pin} is in two nets, ${netOf.get(pin)} and ${net}: a pin is on one net (join the nets, or take it out of one)`);
204
+ netOf.set(pin, net);
205
+ }
199
206
  for (const [net, spec] of Object.entries(board.planes || {})) for (const pin of spec.pins) netOf.set(pin, net);
200
207
  const { nets: planeNets = null, links = [] } = board.planes ? planeVias(out, add, board, copper) : {};
201
208
  if (board.copper) keptCopper(out, add, board, copper, planeNets || {});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rulecad/pcb",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Circuit boards from rules: parts from rule sets or any standard footprint, quarter-turn rotation, nets and autorouting; keyboards with every matrix track drawn by rule. Gerbers, KiCad files and a JLCPCB BOM. Circuit JSON written directly: no React.",
5
5
  "type": "module",
6
6
  "exports": "./pcb.mjs",
@@ -29,11 +29,15 @@
29
29
  "url": "git+https://github.com/JoniBach/rulecad.git",
30
30
  "directory": "packages/pcb"
31
31
  },
32
+ "homepage": "https://github.com/JoniBach/rulecad/tree/main/packages/pcb#readme",
33
+ "bugs": {
34
+ "url": "https://github.com/JoniBach/rulecad/issues"
35
+ },
32
36
  "dependencies": {
33
37
  "@flatten-js/core": "1.6.14",
34
38
  "@jscad/modeling": "^2.12.0",
39
+ "@rulecad/rules": "^0.3.4",
35
40
  "@resvg/resvg-js": "2.6.2",
36
- "@rulecad/cad": "^0.2.0 || ^0.3.0 || ^0.4.0 || ^0.5.0 || ^0.6.0 || ^0.7.0",
37
41
  "@rulecad/smooth": "^0.1.0",
38
42
  "@tscircuit/capacity-autorouter": "0.0.982",
39
43
  "@tscircuit/checks": "0.0.264",
package/pcb.mjs CHANGED
@@ -15,7 +15,11 @@ import fs from 'node:fs';
15
15
  import path from 'node:path';
16
16
  import { circuitJson, bounds, smtBounds, slideClear } from './circuit.mjs';
17
17
  export { bounds };
18
- import { loadRuleSet } from '@rulecad/cad/rules';
18
+ import { createRequire } from 'node:module';
19
+ // The published rule sets a footprint's pins come from (a Pico's GPIO, a XIAO's labels): read from @rulecad/rules as
20
+ // published, not through @rulecad/cad, which pcb would then depend on (and cad names pcb: a loop), and which copies a
21
+ // set into the current folder when it reads one
22
+ const loadRuleSet = (name) => createRequire(import.meta.url)(`@rulecad/rules/${name}.json`);
19
23
  import jscad from '@jscad/modeling';
20
24
 
21
25
  // A rows × cols grid of keys at the key pitch, centred on the origin: [{ r, c, x, y, n }], n counting from 1, row 0
@@ -32,7 +36,7 @@ const hole = (x, y, d) => ({ x, y, d });
32
36
 
33
37
  // An MX switch, PCB mount: two pins, the centre post and the two fixing pegs
34
38
  export function mx(name, x, y, m, sch = {}) {
35
- return { name, ftype: 'simple_switch', mpn: 'Cherry MX (PCB mount)', x, y, layer: 'top', sch,
39
+ return { name, ftype: 'simple_switch', mpn: 'Cherry MX (PCB mount)', package: 'Cherry MX, PCB mount', x, y, layer: 'top', sch,
36
40
  pads: [pad('pin1', m.pcb_pin1_x, m.pcb_pin1_y, m.pcb_pin_drill, m.pcb_pin_pad), pad('pin2', m.pcb_pin2_x, m.pcb_pin2_y, m.pcb_pin_drill, m.pcb_pin_pad)],
37
41
  holes: [hole(0, 0, m.pcb_centre_hole), hole(-m.pcb_peg_x, 0, m.pcb_peg_hole), hole(m.pcb_peg_x, 0, m.pcb_peg_hole)],
38
42
  courtyard: { w: m.pcb_body, h: m.pcb_body } }; // the housing's footprint on the board
@@ -45,7 +49,7 @@ export function pico(name, x, y, p, sch = {}) {
45
49
  const left = n <= 20, i = left ? n - 1 : 40 - n;
46
50
  pins.push(pad(`pin${n}`, (left ? -1 : 1) * p.pin_rows / 2, (19 / 2 - i) * p.pin_pitch, p.pin_hole, p.pin_pad));
47
51
  }
48
- return { name, ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', x, y, layer: 'top', sch, pads: pins, courtyard: { w: p.width, h: p.length } };
52
+ return { name, ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', package: 'Raspberry Pi Pico, 0.1 in header pins', x, y, layer: 'top', sch, pads: pins, courtyard: { w: p.width, h: p.length } };
49
53
  }
50
54
  // Where a Pico pin is, from its centre
51
55
  export const picoPin = (n, p) => { const left = n <= 20, i = left ? n - 1 : 40 - n; return { x: (left ? -1 : 1) * p.pin_rows / 2, y: (19 / 2 - i) * p.pin_pitch }; };
@@ -56,7 +60,7 @@ export const picoGpio = (side) => Object.entries(loadRuleSet('pico').rules[`gpio
56
60
  // Parts for any board, not only keyboards. Each returns a part as circuit.mjs describes it: put them in board.parts, join
57
61
  // their pins with board.nets, and set board.autoroute. o (all optional): { rotation: 0 | 90 | 180 | 270, layer,
58
62
  // mpn, labels: { pin1: 'GND', ... }, sch: { x, y } }. Pin labels name the pins in nets ('U1.GND') and on the schematic.
59
- const chip = (name, x, y, o, more) => ({ name, ftype: 'simple_chip', x, y, layer: o.layer ?? 'top', rotation: o.rotation ?? 0, mpn: o.mpn,
63
+ const chip = (name, x, y, o, more) => ({ name, ftype: 'simple_chip', x, y, layer: o.layer ?? 'top', rotation: o.rotation ?? 0, mpn: o.mpn, ...(o.package ? { package: o.package } : {}),
60
64
  courtyard: o.courtyard ?? null, sch: { x: o.sch?.x ?? x / 2, y: o.sch?.y ?? y / 2, pinLabels: o.labels ?? {} }, ...more });
61
65
  const pinNo = (p) => Number(p.pin.replace(/\D/g, ''));
62
66
  // A rule set's pin map ({ "1": "GND", ... }) as pin labels ({ pin1: 'GND', ... })
@@ -80,25 +84,25 @@ export function header(name, x, y, r, o = {}) {
80
84
  pads.push(pad(`pin${i + 1}`, two ? -r.row_spacing / 2 : 0, py, r.drill, r.pad));
81
85
  if (two) pads.push(pad(`pin${2 * n - i}`, r.row_spacing / 2, py, r.drill, r.pad));
82
86
  }
83
- return chip(name, x, y, o, { pads: pads.sort((a, b) => pinNo(a) - pinNo(b)) });
87
+ return chip(name, x, y, { package: `${two ? '2 × ' : ''}${n}-pin header, ${r.pitch} mm`, ...o }, { pads: pads.sort((a, b) => pinNo(a) - pinNo(b)) });
84
88
  }
85
89
 
86
90
  /** A Seeed Studio XIAO module (any of the family) on header pins, USB at +y, from the xiao rules; pins labelled D0..D10, 5V, GND, 3V3. */
87
91
  export const xiao = (name, x, y, r, o = {}) =>
88
- header(name, x, y, r, { pins: r.pins / 2, rows: 2, mpn: 'Seeed Studio XIAO', courtyard: { w: r.width, h: r.length }, labels: labelsFrom('xiao', 'pins'), ...o });
92
+ header(name, x, y, r, { pins: r.pins / 2, rows: 2, mpn: 'Seeed Studio XIAO', package: 'Seeed Studio XIAO, 0.1 in header pins', courtyard: { w: r.width, h: r.length }, labels: labelsFrom('xiao', 'pins'), ...o });
89
93
 
90
94
  /** A Qwiic / STEMMA QT socket (JST SH, 4 pins, side entry), from the qwiic rules: the plug goes in from +y, the tabs' side. */
91
95
  export function qwiic(name, x, y, r, o = {}) {
92
96
  const n = r.pins, smd = (k, x, y, w, h) => ({ pin: `pin${k}`, smd: true, hint: String(k), x, y, w, h });
93
97
  const pads = Array.from({ length: n }, (_, i) => smd(i + 1, (i - (n - 1) / 2) * r.pitch, r.pad_y, r.pad_w, r.pad_h))
94
98
  .concat([-1, 1].map((side, i) => smd(n + i + 1, side * r.tab_x, r.tab_y, r.tab_w, r.tab_h)));
95
- return chip(name, x, y, { mpn: 'JST SM04B-SRSS-TB', labels: { ...labelsFrom('qwiic', 'pins'), pin5: 'TAB1', pin6: 'TAB2' }, ...o }, { pads });
99
+ return chip(name, x, y, { mpn: 'JST SM04B-SRSS-TB', package: 'JST SH, 4 pins, side entry', labels: { ...labelsFrom('qwiic', 'pins'), pin5: 'TAB1', pin6: 'TAB2' }, ...o }, { pads });
96
100
  }
97
101
 
98
102
  /** A JST PH socket (2.0 mm, through-hole), from the jstph rules: o.pins pins in a row along x (default 2). */
99
103
  export function jstph(name, x, y, r, o = {}) {
100
104
  const n = o.pins ?? 2;
101
- return chip(name, x, y, { mpn: `JST B${n}B-PH-K-S`, ...o }, { pads: Array.from({ length: n }, (_, i) => pad(`pin${i + 1}`, (i - (n - 1) / 2) * r.pitch, 0, r.drill, r.pad)) });
105
+ return chip(name, x, y, { mpn: `JST B${n}B-PH-K-S`, package: `JST PH, ${n} pins`, ...o }, { pads: Array.from({ length: n }, (_, i) => pad(`pin${i + 1}`, (i - (n - 1) / 2) * r.pitch, 0, r.drill, r.pad)) });
102
106
  }
103
107
 
104
108
  // ---------- the keyboard ----------
@@ -203,7 +207,7 @@ export function keyboard(v, keys) {
203
207
  pico0 = { x: cx, y: cy };
204
208
  right = cx + p.width / 2 + v.margin;
205
209
  }
206
- const picoPart = { name: 'U1', ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', x: pico0.x, y: pico0.y, layer: 'top', sch,
210
+ const picoPart = { name: 'U1', ftype: 'simple_chip', mpn: 'Raspberry Pi Pico', package: 'Raspberry Pi Pico, 0.1 in header pins', x: pico0.x, y: pico0.y, layer: 'top', sch,
207
211
  pads: Array.from({ length: 40 }, (_, i) => { const q = pinAt(i + 1); return pad(`pin${i + 1}`, q.x - pico0.x, q.y - pico0.y, p.pin_hole, p.pin_pad); }),
208
212
  courtyard: under ? null : { w: p.width, h: p.length } };
209
213
 
@@ -211,7 +215,7 @@ export function keyboard(v, keys) {
211
215
  const pts = (list) => list.map(([x, y]) => ({ x, y })); // a track's corners between its two pads, on the board
212
216
  for (const k of keys) {
213
217
  parts.push(mx(`K${k.n}`, k.x, k.y, m, { x: k.c * SX, y: -k.r * SY }),
214
- { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
218
+ { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', package: 'SOD-123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
215
219
  traces.push({ from: [`D${k.n}`, 'anode'], to: [`K${k.n}`, 'pin1'], width: v.track, path: pts([[k.x + anodeX, k.y + m.pcb_pin1_y]]) });
216
220
  }
217
221
 
@@ -339,7 +343,7 @@ export function keyboard(v, keys) {
339
343
  ...keys.map((k) => rect(k.x + cathodeX + d.pad_w / 2 + silk * 2, k.y + diode.y, silk, d.pad_h, 'bottom')),
340
344
  ...(v.margin >= text * 2 ? [{ text: 'rulecad: diodes point to the rows', x: (keyBox.left + keyBox.right) / 2, y: bottom + v.margin / 2, size: text, layer: 'bottom' }] : [])];
341
345
  const board = { center: { x: cx, y: cy }, width: right - left, height: top - bottom, thickness: v.thickness, autoroute: under,
342
- silk_line: v.jlcpcb.silk_line, silk_text: v.jlcpcb.silk_text, via_hole: 0.3, via_pad: 0.3 + 2 * v.jlcpcb.annular, // (vias with the ring the fab recommends)
346
+ silk_line: v.jlcpcb.silk_line, silk_text: v.jlcpcb.silk_text, via_hole: 0.3, via_pad: 0.3 + 2 * v.jlcpcb.annular, fab: v.jlcpcb, // (vias with the ring the fab recommends; the fab's minimums for the router)
343
347
  parts, traces, silk: marks, holes: corners.map(([x, y]) => hole(x, y, v.m2.clearance)) };
344
348
  const matrix = {
345
349
  keys: keys.map((k) => ({ key: `K${k.n}`, ...(k.label ? { label: k.label } : {}), row: k.r, col: k.c })),
@@ -354,25 +358,37 @@ export function keyboard(v, keys) {
354
358
  * A KiCad footprint (.kicad_mod text) as pad data: { pads, courtyard: { w, h } }, in mm, y up (KiCad's y is down).
355
359
  * Keep the result in a rule set's "footprints" (with its source), and place it with footprint(): a design never
356
360
  * reads files. SMD pads: { pin, smd: true, x, y, w, h } (a turned pad's w and h swapped); plated holes: { pin, x, y,
357
- * hole, outer }. Pads named alike (several GND pads) keep their name; unnamed pads (mechanical) are left out.
358
- * @param {string} text @returns {{ pads: object[], courtyard: { w: number, h: number } | null }}
361
+ * hole, outer }, an oval one with rect: { w, h } (its copper) and slot: [w, h] (drilled round at the narrow width);
362
+ * unplated holes in holes: [{ x, y, d }]. Pads named alike (several GND pads) keep their name; unnamed plated pads
363
+ * (mechanical) are left out. Text that isn't a footprint, or one with nothing on it, is refused.
364
+ * @param {string} text @returns {{ pads: object[], holes?: object[], courtyard: { w: number, h: number } | null }}
359
365
  */
360
366
  export function fromKicad(text) {
361
- const num = (s) => Number(s), pads = [];
367
+ if (!/^\s*\((?:footprint|module)\s/.test(text)) throw new Error('fromKicad: not a KiCad footprint (a .kicad_mod starts with "(footprint")');
368
+ const num = (s) => Number(s), pads = [], holes = [];
362
369
  for (const m of text.matchAll(/\(pad\s+"([^"]*)"\s+(smd|thru_hole|np_thru_hole)\s+(\w+)([\s\S]*?)\(layers/g)) {
363
- const [, name, kind, , rest] = m;
364
- if (!name) continue;
370
+ const [, name, kind, shape, rest] = m;
365
371
  const at = rest.match(/\(at\s+([-\d.]+)\s+([-\d.]+)(?:\s+([-\d.]+))?\)/), sz = rest.match(/\(size\s+([-\d.]+)\s+([-\d.]+)\)/);
366
372
  if (!at || !sz) continue;
367
373
  const turn = ((num(at[3] || 0) % 180) + 180) % 180 === 90, w = num(turn ? sz[2] : sz[1]), h = num(turn ? sz[1] : sz[2]);
368
374
  const x = +num(at[1]).toFixed(4), y = +(-num(at[2])).toFixed(4);
375
+ const drill = rest.match(/\(drill\s+(oval\s+)?([-\d.]+)(?:\s+([-\d.]+))?/);
376
+ if (kind === 'np_thru_hole') { if (drill) holes.push({ x, y, d: num(drill[2]) }); continue; } // a locating peg's hole: unplated, nothing to connect
377
+ if (!name) continue; // (an unnamed plated pad: mechanical)
369
378
  if (kind === 'smd') pads.push({ pin: name, smd: true, x, y, w, h });
370
- else if (kind === 'thru_hole') { const d = rest.match(/\(drill\s+(?:oval\s+)?([-\d.]+)/); pads.push({ pin: name, x, y, hole: num(d[1]), outer: Math.max(w, h) }); }
379
+ else if (kind === 'thru_hole') {
380
+ // An oval pad keeps its oval copper; a slot is drilled round at its narrow width (boards here can't carry slots),
381
+ // and says so
382
+ const d = num(drill[2]), slot = drill[1] && drill[3] && num(drill[3]) !== d ? (turn ? [num(drill[3]), d] : [d, num(drill[3])]) : null;
383
+ const oval = shape === 'oval' || (shape === 'rect' || shape === 'roundrect') ? w !== h : false;
384
+ pads.push({ pin: name, x, y, hole: slot ? Math.min(...slot) : d, outer: Math.max(w, h), ...(oval ? { rect: { w, h } } : {}), ...(slot ? { slot } : {}) });
385
+ }
371
386
  }
387
+ if (!pads.length && !holes.length) throw new Error('fromKicad: the footprint has no pads');
372
388
  const pts = text.split(/\n\s*(?=\(fp_|\(pad|\(model|\(zone)/).filter((el) => /^\(fp_(?:line|rect|poly)/.test(el) && /\(layer\s+"F\.CrtYd"\)/.test(el)) // the courtyard's corners
373
389
  .flatMap((el) => [...el.matchAll(/\((?:start|end|xy)\s+([-\d.]+)\s+([-\d.]+)\)/g)].map((m) => [num(m[1]), num(m[2])]));
374
390
  const span = (k) => Math.max(...pts.map((p) => p[k])) - Math.min(...pts.map((p) => p[k]));
375
- return { pads, courtyard: pts.length ? { w: +span(0).toFixed(3), h: +span(1).toFixed(3) } : null };
391
+ return { pads, ...(holes.length ? { holes } : {}), courtyard: pts.length ? { w: +span(0).toFixed(3), h: +span(1).toFixed(3) } : null };
376
392
  }
377
393
 
378
394
  /**
@@ -381,8 +397,8 @@ export function fromKicad(text) {
381
397
  * layer, mpn, labels, sch).
382
398
  */
383
399
  export function footprint(name, data, x, y, o = {}) {
384
- const pads = data.pads.map((p, i) => p.smd ? { pin: `pin${p.pin}`, smd: true, hint: String(p.pin), x: p.x, y: p.y, w: p.w, h: p.h } : pad(`pin${p.pin}`, p.x, p.y, p.hole, p.outer));
385
- return chip(name, x, y, { courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o }, { pads });
400
+ const pads = data.pads.map((p, i) => p.smd ? { pin: `pin${p.pin}`, smd: true, hint: String(p.pin), x: p.x, y: p.y, w: p.w, h: p.h } : { ...pad(`pin${p.pin}`, p.x, p.y, p.hole, p.outer), ...(p.rect ? { rect: p.rect } : {}) });
401
+ return chip(name, x, y, { courtyard: data.courtyard, mpn: data.mpn, labels: data.labels, ...o }, { pads, ...(data.holes?.length ? { holes: data.holes.map((h) => hole(h.x, h.y, h.d)) } : {}) });
386
402
  }
387
403
 
388
404
  // ---------- whole boards from KiCad: clones ----------
@@ -1081,7 +1097,7 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1081
1097
  // part is checked here pad by pad against the outline instead (below)
1082
1098
  // Castellated pads sit on the edge by design: half holes the fab cuts through. They're checked against its rules for them below
1083
1099
  // (with the other pads of their pins: a header pad beside a half hole runs into it, as on a Pico)
1084
- const castellated = json.filter((e) => e.type === 'pcb_plated_hole' && e.port_hints?.includes('castellated'));
1100
+ const b = board, castellated = json.filter((e) => e.type === 'pcb_plated_hole' && e.port_hints?.includes('castellated'));
1085
1101
  const pinOf = (e) => `${e.pcb_component_id}:${e.port_hints?.[1]}`, edgePins = new Set(castellated.map(pinOf));
1086
1102
  const halves = new Set(json.filter((e) => e.type === 'pcb_plated_hole' && edgePins.has(pinOf(e))).map((e) => e.pcb_plated_hole_id));
1087
1103
  const padsOf = (id) => json.filter((e) => e.pcb_component_id === id && ['pcb_smtpad', 'pcb_plated_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id));
@@ -1133,8 +1149,39 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1133
1149
  out.push(moved.length || strays.length ? { level: 'fail', text: `${moved.length + strays.length} of the source's own tracks and vias aren't where the source has them` }
1134
1150
  : { level: 'pass', text: `the source's own routing as it was: ${laid.length - vias - short} tracks and ${vias} vias exactly where the source has them${cutBy.length ? `, but for ${escapes} escapes cut back where a routed track turned straight back on them (${gone.length} segments gone, ${short} shortened: ${mm(total)} mm of track in all)` : ''} (only the router's tracks are tidied)` });
1135
1151
  }
1136
- const thin = traces.flatMap((t) => t.route).filter((p) => p.width != null && p.width < j.track_min);
1137
- out.push(thin.length ? { level: 'fail', text: `tracks under JLCPCB's ${j.track_min} mm` } : { level: 'pass', text: `tracks ${mm(v.track ?? Math.min(...traces.flatMap((t) => t.route).map((p) => p.width).filter((w) => w != null)))} mm${v.clear != null ? `, gaps ${mm(v.clear)} mm` : ''}: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
1152
+ // Tracks and the gaps between them, measured from the board as drawn (not the design's variables): the narrowest
1153
+ // track, and the nearest two tracks of different connections come on one layer, edge to edge
1154
+ const segs = traces.flatMap((t) => t.route.slice(1).map((q, i) => ({ a: t.route[i], b: q, id: t.source_trace_id ?? t.pcb_trace_id, w: Math.max(t.route[i].width ?? 0, q.width ?? 0), layer: q.layer ?? t.route[i].layer })))
1155
+ .filter((g) => g.a.route_type !== 'via' && g.b.route_type !== 'via' && g.a.layer === g.b.layer);
1156
+ const widths = segs.map((g) => g.w).filter((w) => w > 0), narrow = widths.length ? Math.min(...widths) : null;
1157
+ let tight = null;
1158
+ const segGap = (g, h) => { const pts = [[g.a, h], [g.b, h], [h.a, g], [h.b, g]].map(([p, o]) => { const dx = o.b.x - o.a.x, dy = o.b.y - o.a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((p.x - o.a.x) * dx + (p.y - o.a.y) * dy) / l)) : 0; return Math.hypot(p.x - o.a.x - t * dx, p.y - o.a.y - t * dy); }); return Math.min(...pts) - (g.w + h.w) / 2; };
1159
+ const crosses = (g, h) => { const o = (p, q, r) => Math.sign((q.x - p.x) * (r.y - p.y) - (q.y - p.y) * (r.x - p.x)); return o(g.a, g.b, h.a) * o(g.a, g.b, h.b) < 0 && o(h.a, h.b, g.a) * o(h.a, h.b, g.b) < 0; };
1160
+ // (tracks of one net may run close or meet: connections are grouped into nets by the ports and nets they share)
1161
+ const parent = new Map(), root = (x) => { while (parent.get(x) !== x) x = parent.get(x); return x; }, join = (x, y) => { parent.set(root(x), root(y)); };
1162
+ for (const t of json.filter((e) => e.type === 'source_trace')) {
1163
+ const ends = [t.source_trace_id, ...(t.connected_source_port_ids || []), ...(t.connected_source_net_ids || [])];
1164
+ for (const e of ends) if (!parent.has(e)) parent.set(e, e);
1165
+ for (const e of ends.slice(1)) join(ends[0], e);
1166
+ }
1167
+ const netOf = (id) => (parent.has(id) ? root(id) : id);
1168
+ const byLayer = new Map(); for (const g of segs) byLayer.set(g.layer, [...(byLayer.get(g.layer) || []), g]);
1169
+ for (const list of byLayer.values()) for (let x = 0; x < list.length; x++) for (let y = x + 1; y < list.length; y++) {
1170
+ const g = list[x], h = list[y];
1171
+ if (g.id === h.id || netOf(g.id) === netOf(h.id)) continue;
1172
+ const d = crosses(g, h) ? -1 : segGap(g, h);
1173
+ if (d <= 1e-6) continue; // touching: two pieces of one net meeting at a pad (the design checks catch real shorts)
1174
+ if (!tight || d < tight.d) tight = { d, at: [(g.a.x + g.b.x) / 2, (g.a.y + g.b.y) / 2] };
1175
+ }
1176
+ const thinTrack = narrow != null && narrow < j.track_min - 1e-9, closeGap = tight && tight.d < j.gap_min - 1e-9;
1177
+ if (narrow != null) out.push(thinTrack || closeGap
1178
+ ? { level: 'fail', text: [thinTrack && `a track ${mm(narrow)} mm wide, under JLCPCB's ${j.track_min} mm`, closeGap && `two tracks ${mm(tight.d)} mm apart near (${mm(tight.at[0])}, ${mm(tight.at[1])}), under JLCPCB's ${j.gap_min} mm`].filter(Boolean).join('; ') }
1179
+ : { level: 'pass', text: `tracks ${mm(narrow)} mm or wider${tight ? `, ${mm(tight.d)} mm or more apart` : ''}, measured on the board: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
1180
+ // A board that can't be made: no size, a hole through its edge, two parts of one name, a pin in two nets
1181
+ const named = json.filter((e) => e.type === 'source_component').map((e) => e.name), twice = named.filter((n, i) => named.indexOf(n) !== i);
1182
+ const edgeHoles = b.outline ? [] : json.filter((e) => (e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') && !halves.has(e.pcb_plated_hole_id)).filter((e) => { const r = (e.outer_diameter ?? e.hole_diameter ?? e.hole_width ?? 0) / 2; return Math.abs(e.x - b.center.x) + r > b.width / 2 + 1e-6 || Math.abs(e.y - b.center.y) + r > b.height / 2 + 1e-6; });
1183
+ const broken = [!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`, edgeHoles.length && `${edgeHoles.length} holes break through the board's edge`, twice.length && `two parts named ${[...new Set(twice)].join(', ')}`].filter(Boolean); // (a pin in two nets is refused as the board is built)
1184
+ if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
1138
1185
  // Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
1139
1186
  // between them (under the recommended ring a warning, under the least a failure). A clone's vias as its source
1140
1187
  // has them are the source's design: said, not failed
@@ -1154,9 +1201,11 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1154
1201
  if (json.some((e) => /^pcb_silkscreen_/.test(e.type))) out.push(silkLines.length || silkTexts.length
1155
1202
  ? { level: 'fail', text: `silkscreen the fab can't print: ${[silkLines.length && `${silkLines.length} lines under ${j.silk_line} mm (${mm(Math.min(...silkLines.map((e) => e.stroke_width)))})`, silkTexts.length && `${silkTexts.length} texts under ${j.silk_text} mm high (${mm(Math.min(...silkTexts.map((e) => e.font_size)))})`].filter(Boolean).join(', ')}` }
1156
1203
  : { level: 'pass', text: `silkscreen: lines ${j.silk_line} mm or wider, text ${j.silk_text} mm or taller (JLCPCB's least)` });
1204
+ const unplated = json.filter((e) => e.type === 'pcb_hole').map((e) => e.hole_diameter ?? e.hole_width), npth = j.npth_min ?? 0.5;
1205
+ if (unplated.length && Math.min(...unplated) < npth - 1e-9) out.push({ level: 'fail', text: `an unplated hole of ${mm(Math.min(...unplated))} mm, under JLCPCB's ${npth} mm for unplated holes` });
1157
1206
  const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width);
1158
1207
  if (drills.length) out.push(Math.min(...drills) < j.drill_min ? { level: 'fail', text: `a hole under JLCPCB's ${j.drill_min} mm` } : { level: 'pass', text: `${drills.length} holes, smallest ${Math.min(...drills)} mm (JLCPCB: ${j.drill_min} mm)` });
1159
- const b = json.find((e) => e.type === 'pcb_board'), size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
1208
+ const size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
1160
1209
  if (b.outline) { // a shaped board: every pad and hole inside it
1161
1210
  const reaching = same ? same.reaching : new Set();
1162
1211
  const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
@@ -1258,12 +1307,11 @@ export async function fabFiles(json, name) {
1258
1307
  // The BOM in JLCPCB's columns (Comment, Designator, Footprint, LCSC Part #), one line per kind of part. A part's LCSC
1259
1308
  // number comes with it when it has one (a clone's parts keep the source's); otherwise it's blank until parts are chosen
1260
1309
  // for assembly, and a hand-soldered board doesn't need them.
1261
- const FOOTPRINT = { K: 'Cherry MX, PCB mount', U: 'Raspberry Pi Pico, 0.1 in header pins', D: 'SOD-123' };
1262
1310
  function bom(json) {
1263
1311
  const lines = new Map(), q = (x) => `"${String(x).replace(/"/g, '""')}"`;
1264
1312
  for (const c of json.filter((e) => e.type === 'source_component' && !e.exclude_from_bom)) {
1265
1313
  const lcsc = c.supplier_part_numbers?.jlcpcb?.[0] ?? '', comment = c.display_value || c.manufacturer_part_number || c.name;
1266
- const footprint = lcsc ? '' : FOOTPRINT[c.name[0]] || ''; // a keyboard's parts by their letter; a part with an LCSC number is known by that
1314
+ const footprint = lcsc ? '' : c.rulecad_package || ''; // the part's own package (a part with an LCSC number is known by that)
1267
1315
  const key = `${comment}|${footprint}|${lcsc}`;
1268
1316
  if (!lines.has(key)) lines.set(key, { comment, footprint, lcsc, refs: [] });
1269
1317
  lines.get(key).refs.push(c.name);