perfboard-designer-mcp 0.3.0 → 0.4.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 (3) hide show
  1. package/README.md +1 -1
  2. package/dist/server.js +283 -43
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -81,7 +81,7 @@ Point them at a local Worker with `http://localhost:8787/render.svg` and `http:/
81
81
  | `list_parts` | Lists the parts a project can place (79 today). Without a query, every part by category, one line each (its id, name and pin count). With words such as `"capacitor"` or `"555"`, the parts matching all of them, or the closest ones when none do. |
82
82
  | `get_part` | Parts in full, as many as you name in `ids`: which list each goes in, its pins and pin labels, polarity, value unit, holes its body covers, and an example entry to copy. |
83
83
  | `new_project` | Starts a project kept in memory and returns its `projectId`: a blank perfboard or stripboard of the size you give, or a copy of an example (`example: "555-led-blinker"`). |
84
- | `edit_project` | Changes a kept project with a list of ops, all or none: `add_part` (by part id, with `at`, or `from`/`to` for two-lead parts; refs are numbered if left out), `update_part` (move, turn, change value or ref), `remove_parts`, `add_wire` (`from`/`to`, with `via` for the holes it bends at, or a `path` of holes made into one wire per leg; any end can be a pin by name, e.g. `"U1.7"` or `"D1.K"`, for the hole it's in), `update_wire` (ends by hole or pin too, `via` to replace its bends), `remove_wires`, `set_board`, `add_cuts`/`remove_cuts`, `set_pad` (a note on a hole). Returns what changed, where the new or moved parts' pins landed, and the board checked as `validate_project` does; when it has no errors, also its nets. |
84
+ | `edit_project` | Changes a kept project with a list of ops, all or none: `add_part` (by part id, with `at`, or `from`/`to` for two-lead parts; refs are numbered if left out; or a part of the agent's own: `custom`, pins anywhere or a catalog part's package via `shape` with its own pin names, or `chip`, a dual-row chip or dev board, placed again later by name), `update_part` (move, turn, change value or ref), `remove_parts`, `add_wire` (`from`/`to`, with `via` for the holes it bends at, or a `path` of holes made into one wire per leg; any end can be a pin by name, e.g. `"U1.7"` or `"D1.K"`, for the hole it's in), `update_wire` (ends by hole or pin too, `via` to replace its bends), `remove_wires`, `set_board`, `add_cuts`/`remove_cuts`, `set_pad` (a note on a hole). Returns what changed, where the new or moved parts' pins landed, and the board checked as `validate_project` does; when it has no errors, also its nets. |
85
85
  | `get_project` | The whole project file of a kept project. |
86
86
  | `get_pin_positions` | Where every placed part's pins land on the board after rotation, e.g. `U1 pin 8 (VCC) at [9, 3]`, so wires can be routed to the right holes. |
87
87
  | `render_board` | Draws the board as text, one cell per hole with column and row numbers: pins by part key and number (`a1`), holes under a body, wire ends, holes a wire runs over without joining them, strip cuts and holes with notes, then which part each key is and every wire with its net. `area` draws only part of the board (needed above 6000 holes). `format: "png"` draws a picture instead, as the editor draws it (holes 50 px apart, scaled down to fit 1000 px; `area` crops it), for an agent to look at. |
package/dist/server.js CHANGED
@@ -38171,9 +38171,19 @@ A board that's right isn't done until it looks neat and someone can easily solde
38171
38171
  - On a stripboard, let the strips do the connecting: place parts so pins that share a net sit on one strip, and use wires and cuts only where strips can't.
38172
38172
  - Look at the board as you go: render_board shows free space as text; with format "png" you see it as the user will. Tidy it up before you give the user the link: fewer crossings, fewer bends, straighter rows. Never break a connection to make it look better.
38173
38173
 
38174
+ ## Parts the catalog doesn't have
38175
+
38176
+ When list_parts has nothing for a part, make it with add_part, then place more of it with \`part\` and its name (\`{"op": "add_part", "part": "BC337", "at": [8, 2]}\`). Don't stand in a catalog part with the wrong pinout. Three kinds:
38177
+
38178
+ - A part in a package the catalog has, with its own name and pinout: a BC337 or 2N3906 is a TO-92 transistor, an IRLZ44N or LM7812 a TO-220. \`custom\` with \`shape\`, the catalog part's id, and the pin names in its pin order (get_part gives the package's pins): \`{"op": "add_part", "custom": {"name": "BC337", "shape": "transistor", "pins": [{"label": "C"}, {"label": "B"}, {"label": "E"}]}, "at": [2, 2]}\`. Check the pinout in the part's datasheet: they differ from part to part. It's drawn as the package, and its refs follow it (Q1).
38179
+ - A module or anything else with pins anywhere: \`custom\` with every pin's hole \`at\` within its body, from the body's top-left hole, pin 1 first; \`cols\` and \`rows\` (the body's size, else just big enough for its pins), \`color\` and \`refPrefix\` (default M) are optional. An HC-SR04's four pins along the bottom of an 8\xD74 body: \`{"name": "HC-SR04", "cols": 8, "rows": 4, "pins": [{"at": [2, 3], "label": "VCC"}, {"at": [3, 3], "label": "TRIG"}, {"at": [4, 3], "label": "ECHO"}, {"at": [5, 3], "label": "GND"}]}\`. add_part's \`at\` is pin 1's hole on the board; the body reaches from there as the pins say.
38180
+ - A dual-row chip or dev board: \`chip\` with \`pinsPerSide\`, \`width\` (columns from one pin row to the other, both included: 4 for a narrow DIP), \`pins\` (names in DIP order: down the left row from pin 1 at the top left, then up the right row) and \`board: true\` for a dev board. add_part's \`at\` is its top-left pin.
38181
+
38182
+ Name pins: wires and expectNets can then use the names ("M1.VCC", "Q1.B"), and get_nets shows them. The project file keeps each custom part whole in its placed part's "custom" (version 6) and each chip in "customIcs", so the user's editor adds them to its parts list when they open the board. A name already in the catalog is refused: use the catalog's part.
38183
+
38174
38184
  ## More
38175
38185
 
38176
- get_project returns the whole file. Kept projects don't last forever (on your computer, only while the server runs; hosted, 30 days unused); a whole project file works in place of a projectId everywhere. To change a board the user shares with you, read it with read_share_link: it returns a projectId to edit. Such a board may hold the user's own parts, made in the editor: custom ICs and dev boards (the file's customIcs, placed as placedIcs) and custom modules (format version 6: a placedAdvancedComponents entry with definitionId "custom" carrying the whole part in "custom": its size, its pins' holes and names). Wire to their pins by name like any part's ("M1.VCC" or "M1.1") and keep them as they are; edit_project can remove them but not make new ones. The format is documented in the resource perfboard://docs/project-file, links in perfboard://docs/share-links, and the whole parts catalog is perfboard://parts.
38186
+ get_project returns the whole file. Kept projects don't last forever (on your computer, only while the server runs; hosted, 30 days unused); a whole project file works in place of a projectId everywhere. To change a board the user shares with you, read it with read_share_link: it returns a projectId to edit. Such a board may hold the user's own parts, made in the editor: custom ICs and dev boards (the file's customIcs, placed as placedIcs) and custom modules (format version 6: a placedAdvancedComponents entry with definitionId "custom" carrying the whole part in "custom": its size, its pins' holes and names, and with "shape" a built-in part's package it takes, such as "transistor" for a TO-92 BC337). Wire to their pins by name like any part's ("M1.VCC" or "M1.1"), place more of them by name, and keep them as they are (see Parts the catalog doesn't have). The format is documented in the resource perfboard://docs/project-file, links in perfboard://docs/share-links, and the whole parts catalog is perfboard://parts.
38177
38187
  `;
38178
38188
 
38179
38189
  // src/tools/catalog-tools.ts
@@ -39048,10 +39058,61 @@ var CUSTOM_PART_ID = "custom";
39048
39058
  var CUSTOM_REF_PREFIX = "M";
39049
39059
  var MAX_CUSTOM_PART_SIDE = 40;
39050
39060
  var BODY_MARGIN = 0.45;
39061
+ function isShapeable(def) {
39062
+ return !def.gridSizable && !def.perPinIcon;
39063
+ }
39064
+ var CUSTOM_PART_SHAPES = ADVANCED_COMPONENT_DEFINITIONS.filter(isShapeable);
39065
+ function customPartShape(id) {
39066
+ const def = id ? getAdvancedComponentDefinition(id) : void 0;
39067
+ return def && isShapeable(def) ? def : void 0;
39068
+ }
39069
+ function shapeHoles(shape) {
39070
+ const holes = [...shape.pinOffsets, ...shape.shadedOffsets ?? []];
39071
+ const left = Math.min(...holes.map((h2) => h2.dx)), top = Math.min(...holes.map((h2) => h2.dy));
39072
+ const right = Math.max(...holes.map((h2) => h2.dx)), bottom = Math.max(...holes.map((h2) => h2.dy));
39073
+ return {
39074
+ cols: right - left + 1,
39075
+ rows: bottom - top + 1,
39076
+ pins: shape.pinOffsets.map((pin) => [pin.dx - left, pin.dy - top])
39077
+ };
39078
+ }
39079
+ function shapedPartSpec(shape, fields) {
39080
+ const { cols, rows, pins } = shapeHoles(shape);
39081
+ return {
39082
+ ...fields.id ? { id: fields.id } : {},
39083
+ name: fields.name,
39084
+ ...fields.refPrefix ? { refPrefix: fields.refPrefix } : {},
39085
+ cols,
39086
+ rows,
39087
+ pins: pins.map((at, i) => {
39088
+ const label = fields.labels[i]?.trim();
39089
+ return { at, ...label ? { label } : {} };
39090
+ }),
39091
+ shape: shape.id
39092
+ };
39093
+ }
39051
39094
  var definitions = /* @__PURE__ */ new WeakMap();
39052
39095
  function customPartDefinition(spec) {
39053
39096
  const cached2 = definitions.get(spec);
39054
39097
  if (cached2) return cached2;
39098
+ const shape = customPartShape(spec.shape);
39099
+ const definition = shape ? shapedDefinition(spec, shape) : moduleDefinition(spec);
39100
+ definitions.set(spec, definition);
39101
+ return definition;
39102
+ }
39103
+ function shapedDefinition(spec, shape) {
39104
+ return {
39105
+ ...shape,
39106
+ id: CUSTOM_PART_ID,
39107
+ name: spec.name,
39108
+ keywords: void 0,
39109
+ refPrefix: spec.refPrefix || shape.refPrefix,
39110
+ // The package's artwork, which the shape names by its own id.
39111
+ iconFile: getIconFile(shape),
39112
+ pinLabels: shape.pinOffsets.map((_2, i) => spec.pins[i]?.label?.trim() ?? "")
39113
+ };
39114
+ }
39115
+ function moduleDefinition(spec) {
39055
39116
  const [ax, ay] = spec.pins[0]?.at ?? [0, 0];
39056
39117
  const offset2 = ([col, row]) => ({ dx: col - ax, dy: row - ay });
39057
39118
  const pinHoles = new Set(spec.pins.map((pin) => `${pin.at[0]},${pin.at[1]}`));
@@ -39063,7 +39124,7 @@ function customPartDefinition(spec) {
39063
39124
  }
39064
39125
  const left = -ax - BODY_MARGIN, top = -ay - BODY_MARGIN;
39065
39126
  const right = spec.cols - 1 - ax + BODY_MARGIN, bottom = spec.rows - 1 - ay + BODY_MARGIN;
39066
- const definition = {
39127
+ return {
39067
39128
  id: CUSTOM_PART_ID,
39068
39129
  category: "modules.custom",
39069
39130
  name: spec.name,
@@ -39079,8 +39140,6 @@ function customPartDefinition(spec) {
39079
39140
  noIcon: true,
39080
39141
  ...spec.color ? { bodyColor: spec.color } : {}
39081
39142
  };
39082
- definitions.set(spec, definition);
39083
- return definition;
39084
39143
  }
39085
39144
  function advancedDefinitionFor(part) {
39086
39145
  return part.custom ? customPartDefinition(part.custom) : getAdvancedComponentDefinition(part.definitionId);
@@ -39694,9 +39753,19 @@ var REF_PREFIX = /^[A-Za-z]{1,4}$/;
39694
39753
  var MAX_LABEL_LENGTH = 24;
39695
39754
  function readCustomPart(value) {
39696
39755
  const entry = asEntry(value);
39697
- const cols = entry && wholeCount(entry.cols);
39698
- const rows = entry && wholeCount(entry.rows);
39699
- if (!entry || !cols || !rows || cols > MAX_CUSTOM_PART_SIDE || rows > MAX_CUSTOM_PART_SIDE || !Array.isArray(entry.pins)) return void 0;
39756
+ if (!entry) return void 0;
39757
+ const refPrefix = typeof entry.refPrefix === "string" && REF_PREFIX.test(entry.refPrefix) ? entry.refPrefix.toUpperCase() : void 0;
39758
+ const id = text(entry.id)?.slice(0, 64);
39759
+ const name = text(entry.name)?.trim().slice(0, 60);
39760
+ const shapeId = text(entry.shape)?.trim().slice(0, 64);
39761
+ const shape = customPartShape(shapeId);
39762
+ if (shape) {
39763
+ const labels = Array.isArray(entry.pins) ? entry.pins.map((item) => text(asEntry(item)?.label)?.trim().slice(0, MAX_LABEL_LENGTH) ?? "") : [];
39764
+ return shapedPartSpec(shape, { ...id ? { id } : {}, name: name || shape.name, ...refPrefix ? { refPrefix } : {}, labels });
39765
+ }
39766
+ const cols = wholeCount(entry.cols);
39767
+ const rows = wholeCount(entry.rows);
39768
+ if (!cols || !rows || cols > MAX_CUSTOM_PART_SIDE || rows > MAX_CUSTOM_PART_SIDE || !Array.isArray(entry.pins)) return void 0;
39700
39769
  const pins = [];
39701
39770
  const taken = /* @__PURE__ */ new Set();
39702
39771
  for (const item of entry.pins) {
@@ -39710,17 +39779,17 @@ function readCustomPart(value) {
39710
39779
  pins.push({ at: [col, row], ...label ? { label } : {} });
39711
39780
  }
39712
39781
  if (!pins.length) return void 0;
39713
- const refPrefix = typeof entry.refPrefix === "string" && REF_PREFIX.test(entry.refPrefix) ? entry.refPrefix.toUpperCase() : void 0;
39714
39782
  const color = text(entry.color)?.trim().slice(0, 32);
39715
- const id = text(entry.id)?.slice(0, 64);
39716
39783
  return {
39717
39784
  ...id ? { id } : {},
39718
- name: text(entry.name)?.trim().slice(0, 60) || "Custom Module",
39785
+ name: name || "Custom Module",
39719
39786
  ...refPrefix ? { refPrefix } : {},
39720
39787
  cols,
39721
39788
  rows,
39722
39789
  pins,
39723
- ...color ? { color } : {}
39790
+ ...color ? { color } : {},
39791
+ // A package this build doesn't have: drawn as a plain module, and kept for one that has it.
39792
+ ...shapeId ? { shape: shapeId } : {}
39724
39793
  };
39725
39794
  }
39726
39795
  var Reader = class {
@@ -42519,10 +42588,31 @@ function expectedNets(given, held) {
42519
42588
  var wireEnd = union([array(number2().int()).length(2), string2()]).describe('A hole [column, row], or a pin by name: "U1.7", "U1.DISCH", "D1.K", "R2.1" (the hole that pin is in).');
42520
42589
  var rotation2 = union([literal(0), literal(90), literal(180), literal(270)]);
42521
42590
  var wireSelector = union([number2().int().min(0), array(holeInput).length(2)]).describe("A wire by its index in wires, or by its two end holes [[c, r], [c, r]] (either way round).");
42591
+ var customPart = object({
42592
+ name: string2().describe('What it is, e.g. "HC-SR04", "BC337". Later add_part ops can place more of it by this name.'),
42593
+ shape: string2().optional().describe(`The id of a fixed-pin part from list_parts whose package this part comes in, e.g. "transistor" (TO-92) for a BC337 or "mosfet" (TO-220) for an IRLZ44N: its pins, outline and look, with this part's name and pin names. Any fixed-pin part but header-pins. Leave out for a body of your own with pins anywhere.`),
42594
+ pins: array(object({
42595
+ at: holeInput.optional().describe("Without shape: the pin's hole [column, row] within the body, from its top-left hole. With shape: leave out, the package decides."),
42596
+ label: string2().optional().describe('Its name, e.g. "VCC", "TRIG", "B". Wire to it by name ("M1.VCC").')
42597
+ })).optional().describe("In pin order, pin 1 first; pin 1 is the hole add_part's `at` places it by. Without shape: every pin with its `at`. With shape: just their names, in the package's pin order (get_part gives it), as many as it has pins."),
42598
+ cols: number2().int().min(1).optional().describe("Without shape: the body's width in holes. Default: just wide enough for its pins."),
42599
+ rows: number2().int().min(1).optional().describe("Without shape: the body's height in holes. Default: just tall enough for its pins."),
42600
+ refPrefix: string2().optional().describe(`Letters of its refs: "Q" makes Q1, Q2. Default: the package's, else "M".`),
42601
+ color: string2().optional().describe(`Without shape: the body's colour, "#rrggbb", e.g. a blue module board "#1d4ed8".`)
42602
+ });
42603
+ var customChip = object({
42604
+ name: string2().describe('What it is, e.g. "LM358", "ESP32 DevKit". Later add_part ops can place more of it by this name.'),
42605
+ pinsPerSide: number2().int().min(2).describe("Pins in each of its two rows."),
42606
+ width: number2().int().min(2).describe(`Columns from one pin row to the other, both included: 4 for a narrow (0.3") DIP, 7 for a wide (0.6") one; a dev board's row spacing in holes plus one.`),
42607
+ pins: array(string2()).optional().describe('Pin names in DIP order: pin 1 at the top of the left row (at rotation 0), down the left row, then up the right row, so the last pin is at the top right. "" for a pin without a name.'),
42608
+ board: boolean2().optional().describe("true: a dev board or module (drawn as a board, listed under Modules); else a DIP chip.")
42609
+ });
42522
42610
  var editOp = discriminatedUnion("op", [
42523
42611
  object({
42524
42612
  op: literal("add_part"),
42525
- part: string2().describe(`The part's id from list_parts ("resistor", "ne555", "header-pins"), or the name of one of the project's customIcs.`),
42613
+ part: string2().optional().describe('The part\'s id from list_parts ("resistor", "ne555", "header-pins"), or the name of a custom part or chip the project already has. Give this, `custom` or `chip`.'),
42614
+ custom: customPart.optional().describe("Instead of `part`, a new part of your own for one the catalog doesn't have, placed by `at` and `rotation`."),
42615
+ chip: customChip.optional().describe("Instead of `part`, a new dual-row chip or dev board of your own, placed by `at` (its top-left pin) and `rotation`."),
42526
42616
  ref: string2().optional().describe("Its reference designator. The next free one (R1, R2...) when left out."),
42527
42617
  from: holeInput.optional().describe("Two-lead parts: the hole of lead 1. On a polarized part get_part's leadLabels say which that is: K for a diode or LED, - for an electrolytic."),
42528
42618
  to: holeInput.optional().describe("Two-lead parts: the hole of lead 2."),
@@ -42736,10 +42826,22 @@ function pinsOf(project, refs) {
42736
42826
  return result;
42737
42827
  }
42738
42828
  function addPart(project, op, placed) {
42739
- const part = findPart(op.part);
42740
- const custom2 = part ? void 0 : project.customIcs.find((ic) => ic.name.toLowerCase() === op.part.trim().toLowerCase());
42741
- if (!part && !custom2) throw new OpError(`${noSuchPart(op.part)} Use list_parts to find one.`);
42742
- if (part?.kind === "standard-component") {
42829
+ const given = [op.part, op.custom, op.chip].filter((field) => field !== void 0).length;
42830
+ if (given !== 1) {
42831
+ throw new OpError("Give one of `part` (a catalog id, or the name of a custom part or chip the project has), `custom` (a new part of your own) or `chip` (a new chip or dev board of your own).");
42832
+ }
42833
+ if (op.custom) return placeCustomPart(project, op, makeCustomPart(project, op.custom), true, placed);
42834
+ if (op.chip) return placeChip(project, op, makeChip(project, op.chip), true, placed);
42835
+ const name = op.part;
42836
+ const part = findPart(name);
42837
+ if (!part) {
42838
+ const chip = findCustomChip(project, name);
42839
+ if (chip) return placeChip(project, op, chip, false, placed);
42840
+ const custom2 = findCustomPart(project, name);
42841
+ if (custom2) return placeCustomPart(project, op, structuredClone(custom2), false, placed);
42842
+ throw new OpError(`${noSuchPart(name)} Use list_parts to find one, or make it with \`custom\` or \`chip\`.`);
42843
+ }
42844
+ if (part.kind === "standard-component") {
42743
42845
  notFor(`a two-lead part (${part.id})`, op, ["at", "rotation", "rows", "cols"]);
42744
42846
  if (!op.from || !op.to) throw new OpError(`${part.id} is a two-lead part: give \`from\` and \`to\`, the holes of its two leads.`);
42745
42847
  checkOnBoard(project, op.from, "`from`");
@@ -42756,20 +42858,15 @@ function addPart(project, op, placed) {
42756
42858
  placed.add(ref2);
42757
42859
  return `Added ${ref2} (${part.name}${op.value ? ` ${op.value}` : ""}) from ${showHole(op.from)} to ${showHole(op.to)}.`;
42758
42860
  }
42759
- notFor("a part placed by `at`", op, ["from", "to", "color"]);
42760
- if (!op.at) throw new OpError("Give `at`: the hole of pin 1 (a chip's or pin block's top-left pin).");
42761
- checkOnBoard(project, op.at, "`at`");
42762
- const at = toGridPos(op.at);
42763
- const rotation3 = op.rotation ?? 0;
42764
- const turned = rotation3 ? `, turned ${rotation3}\xB0` : "";
42765
- if (part?.kind === "advanced-component") {
42861
+ const { at, turned } = placedBy(project, op);
42862
+ if (part.kind === "advanced-component") {
42766
42863
  if (!part.sizable) notFor(`${part.id} (not a pin block)`, op, ["rows", "cols"]);
42767
42864
  const ref2 = claimRef(project, op.ref, part.refPrefix);
42768
42865
  project.placedAdvancedComponents.push({
42769
42866
  ref: ref2,
42770
42867
  definitionId: part.id,
42771
42868
  at,
42772
- rotation: rotation3,
42869
+ rotation: op.rotation ?? 0,
42773
42870
  rows: op.rows ?? 1,
42774
42871
  cols: op.cols ?? 1,
42775
42872
  ...op.value ? { value: op.value } : {}
@@ -42779,24 +42876,167 @@ function addPart(project, op, placed) {
42779
42876
  }
42780
42877
  notFor("a chip", op, ["rows", "cols", "value"]);
42781
42878
  const ref = claimRef(project, op.ref, "U");
42782
- if (part?.kind === "ic") {
42783
- project.placedIcs.push(icEntry(part, at, rotation3, ref));
42879
+ project.placedIcs.push(icEntry(part, at, op.rotation ?? 0, ref));
42880
+ placed.add(ref);
42881
+ return `Added ${ref} (${part.name}) with its top-left pin at ${showHole(at)}${turned}.`;
42882
+ }
42883
+ function placedBy(project, op) {
42884
+ notFor("a part placed by `at`", op, ["from", "to", "color"]);
42885
+ if (!op.at) throw new OpError("Give `at`: the hole of pin 1 (a chip's or pin block's top-left pin).");
42886
+ checkOnBoard(project, op.at, "`at`");
42887
+ return { at: toGridPos(op.at), turned: op.rotation ? `, turned ${op.rotation}\xB0` : "" };
42888
+ }
42889
+ var REF_LETTERS = /^[A-Z]{1,4}$/;
42890
+ var MAX_NAME = 60;
42891
+ var MAX_PIN_NAME = 24;
42892
+ function findCustomPart(project, name) {
42893
+ const wanted = name.trim().toLowerCase();
42894
+ return project.placedAdvancedComponents.find((part) => part.custom?.name.toLowerCase() === wanted)?.custom;
42895
+ }
42896
+ function findCustomChip(project, name) {
42897
+ const wanted = name.trim().toLowerCase();
42898
+ return project.customIcs.find((ic) => ic.name.toLowerCase() === wanted);
42899
+ }
42900
+ function newPartName(given, what) {
42901
+ const name = given.trim();
42902
+ if (!name) throw new OpError(`\`${what}.name\` is empty: name the part, e.g. "BC337".`);
42903
+ if (name.length > MAX_NAME) throw new OpError(`\`${what}.name\` is longer than ${MAX_NAME} characters.`);
42904
+ const catalog = findPart(name);
42905
+ if (catalog) throw new OpError(`"${name}" is already the catalog's ${catalog.name} (id ${catalog.id}): place that with \`part\`, or give yours another name.`);
42906
+ return name;
42907
+ }
42908
+ function checkedPinName(label, i, what) {
42909
+ const name = label?.trim() ?? "";
42910
+ if (name.length > MAX_PIN_NAME) throw new OpError(`${what} pin ${i + 1}'s name is longer than ${MAX_PIN_NAME} characters.`);
42911
+ return name;
42912
+ }
42913
+ function makeCustomPart(project, custom2) {
42914
+ const name = newPartName(custom2.name, "custom");
42915
+ if (findCustomChip(project, name)) throw new OpError(`The project already has a custom chip named "${name}": give this part another name.`);
42916
+ const existing = findCustomPart(project, name);
42917
+ const refPrefix = custom2.refPrefix?.trim().toUpperCase();
42918
+ if (refPrefix !== void 0 && !REF_LETTERS.test(refPrefix)) throw new OpError("`custom.refPrefix` is 1 to 4 letters, such as M or Q.");
42919
+ const pins = custom2.pins ?? [];
42920
+ const labels = pins.map((pin, i) => checkedPinName(pin.label, i, "`custom.pins`:"));
42921
+ let spec;
42922
+ if (custom2.shape !== void 0) {
42923
+ const shape = customPartShape(custom2.shape);
42924
+ if (!shape) {
42925
+ const part = findPart(custom2.shape);
42926
+ throw new OpError(part ? `${part.id} can't be a custom part's \`shape\`: give a fixed-pin part from list_parts other than header-pins, such as "transistor" (TO-92) or "mosfet" (TO-220).` : `${noSuchPart(custom2.shape)} \`custom.shape\` is the id of a fixed-pin part from list_parts, such as "transistor" (TO-92) or "mosfet" (TO-220).`);
42927
+ }
42928
+ const holes = ["cols", "rows", "color"].filter((field) => custom2[field] !== void 0);
42929
+ if (pins.some((pin) => pin.at)) holes.push("pins[].at");
42930
+ if (holes.length) throw new OpError(`With \`shape\` the package decides the part's holes and look: leave out ${holes.map((f2) => `\`custom.${f2}\``).join(", ")}.`);
42931
+ if (labels.length > shape.pinOffsets.length) {
42932
+ throw new OpError(`${shape.name} has ${plural2(shape.pinOffsets.length, "pin")}, but \`custom.pins\` names ${labels.length}.`);
42933
+ }
42934
+ spec = shapedPartSpec(shape, { name, ...refPrefix ? { refPrefix } : {}, labels });
42784
42935
  } else {
42785
- const ic = custom2;
42786
- const sideways = rotation3 === 90 || rotation3 === 270;
42787
- project.placedIcs.push({
42788
- ref,
42789
- name: ic.name,
42790
- at,
42791
- rotation: rotation3,
42792
- widthPin: sideways ? ic.heightPin : ic.widthPin,
42793
- heightPin: sideways ? ic.widthPin : ic.heightPin,
42794
- pinDescription: { ...ic.pinDescription },
42795
- ...ic.category ? { category: ic.category } : {}
42796
- });
42936
+ if (!pins.length) {
42937
+ throw new OpError("`custom.pins` needs every pin's hole `at` within the body, pin 1 first. Or give `custom.shape` to take a catalog part's package.");
42938
+ }
42939
+ const holes = pins.map((pin, i) => {
42940
+ if (!pin.at) throw new OpError(`\`custom.pins[${i}]\` has no \`at\`: without \`shape\`, give each pin's hole within the body.`);
42941
+ if (pin.at[0] < 0 || pin.at[1] < 0) throw new OpError(`\`custom.pins[${i}].at\` ${showHole(pin.at)} is outside the body: holes count from its top-left one, [0, 0].`);
42942
+ return toGridPos(pin.at);
42943
+ });
42944
+ const cols = custom2.cols ?? Math.max(...holes.map((at) => at[0])) + 1;
42945
+ const rows = custom2.rows ?? Math.max(...holes.map((at) => at[1])) + 1;
42946
+ if (cols > MAX_CUSTOM_PART_SIDE || rows > MAX_CUSTOM_PART_SIDE) {
42947
+ throw new OpError(`The body is ${cols}\xD7${rows} holes; a custom part is at most ${MAX_CUSTOM_PART_SIDE} holes a side.`);
42948
+ }
42949
+ holes.forEach((at, i) => {
42950
+ if (at[0] >= cols || at[1] >= rows) throw new OpError(`\`custom.pins[${i}].at\` ${showHole(at)} is outside a body of ${cols}\xD7${rows} holes.`);
42951
+ const first = holes.findIndex((other) => sameHole(other, at));
42952
+ if (first < i) throw new OpError(`Pins ${first + 1} and ${i + 1} are both at ${showHole(at)}: each pin needs its own hole.`);
42953
+ });
42954
+ const color = custom2.color?.trim();
42955
+ spec = {
42956
+ name,
42957
+ ...refPrefix ? { refPrefix } : {},
42958
+ cols,
42959
+ rows,
42960
+ pins: holes.map((at, i) => ({ at, ...labels[i] ? { label: labels[i] } : {} })),
42961
+ ...color ? { color } : {}
42962
+ };
42963
+ }
42964
+ const read = readCustomPart(spec);
42965
+ if (!read) throw new OpError("That custom part can't be saved: check its pins and size.");
42966
+ if (existing && JSON.stringify({ ...existing, id: void 0 }) !== JSON.stringify({ ...read, id: void 0 })) {
42967
+ throw new OpError(`The board already has a different custom part named "${name}": place that one with \`part\`, or give this one another name.`);
42797
42968
  }
42969
+ return read;
42970
+ }
42971
+ function placeCustomPart(project, op, spec, isNew, placed) {
42972
+ notFor("a custom part", op, ["rows", "cols"]);
42973
+ const { at, turned } = placedBy(project, op);
42974
+ const ref = claimRef(project, op.ref, customPartDefinition(spec).refPrefix);
42975
+ project.placedAdvancedComponents.push({
42976
+ ref,
42977
+ definitionId: CUSTOM_PART_ID,
42978
+ at,
42979
+ rotation: op.rotation ?? 0,
42980
+ rows: 1,
42981
+ cols: 1,
42982
+ ...op.value ? { value: op.value } : {},
42983
+ custom: spec
42984
+ });
42985
+ placed.add(ref);
42986
+ const shape = customPartShape(spec.shape);
42987
+ const what = shape ? `in the ${shape.name} package` : `${spec.cols}\xD7${spec.rows} holes, ${plural2(spec.pins.length, "pin")}`;
42988
+ return `Added ${ref} (${spec.name}, ${isNew ? "a new custom part" : "custom"}, ${what}) with pin 1 at ${showHole(at)}${turned}.`;
42989
+ }
42990
+ function makeChip(project, chip) {
42991
+ const name = newPartName(chip.name, "chip");
42992
+ if (findCustomPart(project, name)) throw new OpError(`The board already has a custom part named "${name}": give this chip another name.`);
42993
+ const total = chip.pinsPerSide * 2;
42994
+ const names = chip.pins ?? [];
42995
+ if (names.length > total) throw new OpError(`A chip with ${chip.pinsPerSide} pins a side has ${total} pins, but \`chip.pins\` names ${names.length}.`);
42996
+ const pinDescription = {};
42997
+ names.forEach((label, i) => {
42998
+ const pin = checkedPinName(label, i, "`chip.pins`:");
42999
+ if (pin) pinDescription[i + 1] = pin;
43000
+ });
43001
+ const entry = {
43002
+ name,
43003
+ widthPin: chip.width,
43004
+ heightPin: chip.pinsPerSide,
43005
+ pinDescription,
43006
+ category: chip.board ? "modules.custom" : "ics.custom"
43007
+ };
43008
+ const existing = findCustomChip(project, name);
43009
+ if (existing) {
43010
+ const same = existing.widthPin === entry.widthPin && existing.heightPin === entry.heightPin && JSON.stringify(existing.pinDescription) === JSON.stringify(entry.pinDescription) && (existing.category ?? "ics.custom") === entry.category;
43011
+ if (!same) throw new OpError(`The project already has a different custom chip named "${name}": place that one with \`part\`, or give this one another name.`);
43012
+ return existing;
43013
+ }
43014
+ project.customIcs.push({ id: 1e3 + hashOf(JSON.stringify(entry)), ...entry });
43015
+ return project.customIcs[project.customIcs.length - 1];
43016
+ }
43017
+ function placeChip(project, op, chip, isNew, placed) {
43018
+ notFor("a chip", op, ["rows", "cols", "value"]);
43019
+ const { at, turned } = placedBy(project, op);
43020
+ const rotation3 = op.rotation ?? 0;
43021
+ const ref = claimRef(project, op.ref, "U");
43022
+ const sideways = rotation3 === 90 || rotation3 === 270;
43023
+ project.placedIcs.push({
43024
+ ref,
43025
+ name: chip.name,
43026
+ at,
43027
+ rotation: rotation3,
43028
+ widthPin: sideways ? chip.heightPin : chip.widthPin,
43029
+ heightPin: sideways ? chip.widthPin : chip.heightPin,
43030
+ pinDescription: { ...chip.pinDescription },
43031
+ ...chip.category ? { category: chip.category } : {}
43032
+ });
42798
43033
  placed.add(ref);
42799
- return `Added ${ref} (${part?.name ?? custom2.name}) with its top-left pin at ${showHole(at)}${turned}.`;
43034
+ return `Added ${ref} (${chip.name}${isNew ? ", a new custom chip" : ""}) with its top-left pin at ${showHole(at)}${turned}.`;
43035
+ }
43036
+ function hashOf(text2) {
43037
+ let hash2 = 2166136261;
43038
+ for (let i = 0; i < text2.length; i++) hash2 = Math.imul(hash2 ^ text2.charCodeAt(i), 16777619);
43039
+ return (hash2 >>> 0) % 1e9;
42800
43040
  }
42801
43041
  function updatePart(project, op, placed) {
42802
43042
  const found = findRef(project, op.ref);
@@ -44678,7 +44918,7 @@ function registerShowBoardTool(server, DEFAULT_EDITOR_URL) {
44678
44918
  description: "The page show_board shows the board in.",
44679
44919
  // The picture is a data: image, and the page loads nothing else.
44680
44920
  _meta: { ui: { prefersBorder: false } }
44681
- }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: p, text: '<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>Perfboard board</title>\n<style>\n :root { color-scheme: light dark; font-family: system-ui, sans-serif; font-size: 14px; }\n body { margin: 0; background: transparent; color: CanvasText; }\n figure { margin: 0; display: flex; flex-direction: column; gap: 8px; }\n img { display: block; width: 100%; height: auto; border-radius: 6px; }\n img:not([src]) { display: none; }\n figcaption { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }\n #caption { opacity: 0.75; }\n button { font: inherit; padding: 6px 12px; border-radius: 6px; border: 1px solid #1f7a3a; background: #1f7a3a; color: #fff; cursor: pointer; }\n button:hover { background: #18602e; }\n button[hidden] { display: none; }\n</style>\n</head>\n<body>\n<figure>\n <img id="board" alt="">\n <figcaption>\n <span id="caption">Drawing the board\u2026</span>\n <button id="open" type="button" hidden>Open in Perfboard Designer</button>\n </figcaption>\n</figure>\n<script type="module">var f="2026-01-26",r=document.getElementById("board"),a=document.getElementById("caption"),u=document.getElementById("open"),i,g=1,s=new Map,o=t=>window.parent.postMessage({jsonrpc:"2.0",...t},"*");function m(t,e){let n=g++;return o({id:n,method:t,params:e}),new Promise(p=>s.set(n,p))}function h(t){let e=t._meta?.board;if(t.isError||!e){a.textContent=t.content?.find(n=>n.type==="text")?.text??"The board couldn\'t be shown.";return}r.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e.svg)}`,r.alt=e.caption,a.textContent=e.caption,i=e.link,u.hidden=!i}window.addEventListener("message",({source:t,data:e})=>{t!==window.parent||e?.jsonrpc!=="2.0"||(e.method===void 0?(s.get(e.id)?.(e.result),s.delete(e.id)):e.method==="ui/notifications/tool-result"?h(e.params??{}):e.id!==void 0&&o({id:e.id,result:{}}))});u.addEventListener("click",()=>{i&&m("ui/open-link",{url:i})});var c=0,l=0;function d(){let t=document.documentElement,e=Math.ceil(t.getBoundingClientRect().height),n=Math.ceil(window.innerWidth);n===c&&e===l||(c=n,l=e,o({method:"ui/notifications/size-changed",params:{width:n,height:e}}))}await m("ui/initialize",{protocolVersion:f,appInfo:{name:"Perfboard Designer board",version:"0.3.0"},appCapabilities:{}});o({method:"ui/notifications/initialized",params:{}});new ResizeObserver(()=>requestAnimationFrame(d)).observe(document.body);r.addEventListener("load",d);d();\n</script>\n</body>\n</html>\n', _meta: { ui: { prefersBorder: false } } }] }));
44921
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: p, text: '<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width, initial-scale=1">\n<title>Perfboard board</title>\n<style>\n :root { color-scheme: light dark; font-family: system-ui, sans-serif; font-size: 14px; }\n body { margin: 0; background: transparent; color: CanvasText; }\n figure { margin: 0; display: flex; flex-direction: column; gap: 8px; }\n img { display: block; width: 100%; height: auto; border-radius: 6px; }\n img:not([src]) { display: none; }\n figcaption { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }\n #caption { opacity: 0.75; }\n button { font: inherit; padding: 6px 12px; border-radius: 6px; border: 1px solid #1f7a3a; background: #1f7a3a; color: #fff; cursor: pointer; }\n button:hover { background: #18602e; }\n button[hidden] { display: none; }\n</style>\n</head>\n<body>\n<figure>\n <img id="board" alt="">\n <figcaption>\n <span id="caption">Drawing the board\u2026</span>\n <button id="open" type="button" hidden>Open in Perfboard Designer</button>\n </figcaption>\n</figure>\n<script type="module">var f="2026-01-26",r=document.getElementById("board"),a=document.getElementById("caption"),u=document.getElementById("open"),i,g=1,s=new Map,o=t=>window.parent.postMessage({jsonrpc:"2.0",...t},"*");function m(t,e){let n=g++;return o({id:n,method:t,params:e}),new Promise(p=>s.set(n,p))}function h(t){let e=t._meta?.board;if(t.isError||!e){a.textContent=t.content?.find(n=>n.type==="text")?.text??"The board couldn\'t be shown.";return}r.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(e.svg)}`,r.alt=e.caption,a.textContent=e.caption,i=e.link,u.hidden=!i}window.addEventListener("message",({source:t,data:e})=>{t!==window.parent||e?.jsonrpc!=="2.0"||(e.method===void 0?(s.get(e.id)?.(e.result),s.delete(e.id)):e.method==="ui/notifications/tool-result"?h(e.params??{}):e.id!==void 0&&o({id:e.id,result:{}}))});u.addEventListener("click",()=>{i&&m("ui/open-link",{url:i})});var c=0,l=0;function d(){let t=document.documentElement,e=Math.ceil(t.getBoundingClientRect().height),n=Math.ceil(window.innerWidth);n===c&&e===l||(c=n,l=e,o({method:"ui/notifications/size-changed",params:{width:n,height:e}}))}await m("ui/initialize",{protocolVersion:f,appInfo:{name:"Perfboard Designer board",version:"0.4.0"},appCapabilities:{}});o({method:"ui/notifications/initialized",params:{}});new ResizeObserver(()=>requestAnimationFrame(d)).observe(document.body);r.addEventListener("load",d);d();\n</script>\n</body>\n</html>\n', _meta: { ui: { prefersBorder: false } } }] }));
44682
44922
  K3(server, "show_board", {
44683
44923
  title: "Show board",
44684
44924
  description: "Shows the user a picture of the board right in the conversation, as the editor draws it, with a button that opens it in Perfboard Designer. Only in clients that show MCP Apps (e.g. Claude, ChatGPT); elsewhere the user sees nothing, so give them make_share_link's link too. The picture goes to the user, not to you: to look at the board yourself, use render_board.",
@@ -44721,12 +44961,12 @@ function registerResources(server) {
44721
44961
  title: "Project file format",
44722
44962
  description: "The project file format (version 8), including component identities and optional circuit requirements, as TypeScript types.",
44723
44963
  mimeType: "text/plain"
44724
- }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/plain", text: 'import {GridPos} from "./grid";\nimport type {CustomPartSpec} from "../parts/custom-parts";\nimport type {CircuitRequirements} from "./requirements";\n\n// The project file format, version 8. Positions are grid [column, row] pairs counted from the\n// top-left hole (column = left to right, row = top to bottom), not pixels, and only holes with a\n// note are listed. Older files are still read, see read-project-file.ts:\n// - version 7: the same, minus circuit requirements (`requirements`).\n// - version 6: the same as 7, minus part identities (a placed part\'s `instanceId`).\n// - version 5: the same as 6, minus custom parts (a fixed-pin part\'s `custom`).\n// - version 4: the same as 5, minus solder paths (a wire\'s `kind`).\n// - version 3: the same as 4, minus bent wires (a wire\'s `via`).\n// - version 2: the same as 3, minus the board type (always a perfboard) and part refs.\n// - version 1 (no `version` field): pixel coordinates, every hole listed, the whole IC catalog.\nexport const PROJECT_FILE_VERSION = 8;\n\n// A file says the oldest version that holds everything in it: 8 with requirements, else 6 with a\n// custom part, else 5 with a solder path, else 4 if a wire bends, else 3. So a board without them\n// still opens in editors and tools from before. Part identities (version 7) don\'t raise it: older\n// readers skip the field, and identities only matter to requirements, which are version 8.\nexport type FileVersion = 3 | 4 | 5 | 6 | typeof PROJECT_FILE_VERSION;\n\nexport function fileVersionFor(project: Pick<ProjectFile, "wires" | "placedAdvancedComponents" | "requirements">): FileVersion {\n if (project.requirements) return PROJECT_FILE_VERSION;\n if (project.placedAdvancedComponents.some(part => part.custom)) return 6;\n if (project.wires.some(wire => wire.kind === "solder")) return 5;\n return project.wires.some(wire => wire.via?.length) ? 4 : 3;\n}\n\nexport type Rotation = 0 | 90 | 180 | 270;\n\n// A perfboard has a separate copper pad around every hole: nothing is connected until it\'s wired.\n// A stripboard has long copper strips instead, each connecting a whole line of holes.\nexport type BoardType = "perfboard" | "stripboard";\n\n// Which way a stripboard\'s strips run. "horizontal": every hole in the same row is on one strip.\n// "vertical": every hole in the same column is.\nexport type StripDirection = "horizontal" | "vertical";\n\nexport interface SavedPerfboard {\n type: "perfboard";\n cols: number;\n rows: number;\n}\n\nexport interface SavedStripboard {\n type: "stripboard";\n cols: number;\n rows: number;\n strips: StripDirection;\n // Holes where the strip is cut (drilled through). A cut splits its strip in two, and the cut\n // hole itself connects to neither side: a lead in it is connected to nothing.\n cuts: GridPos[];\n}\n\nexport type SavedBoard = SavedPerfboard | SavedStripboard;\n\n// A hole with a note on it ("+9V", "GND", "to battery"). Purely a label: it says nothing about\n// what\'s connected. (Files from before notes were the only mark may give a hole a `color` too;\n// it\'s ignored.)\nexport interface SavedPad {\n at: GridPos;\n note: string;\n}\n\n// What a wire is made of (version 5):\n// - "jumper": an insulated jumper wire on the component side. It joins the holes at its two ends\n// and nothing else: not the holes it passes over, and not its corners.\n// - "solder": a solder path, a trail of solder bridging pad to pad on the copper side. Bare metal,\n// so it joins every hole it runs over: its ends, its corners and each hole along the way\n// (solderPathHoles() in wire-path.ts), and any solder path it touches. A cut hole on a\n// stripboard has no copper for it to join, so whatever is in one stays unconnected.\nexport type WireKind = "jumper" | "solder";\n\n// A wire: a jumper unless `kind` says otherwise.\nexport interface SavedWire {\n from: GridPos;\n to: GridPos;\n // Where it bends on its way from `from` to `to`, in order (version 4): it runs straight from\n // hole to hole through these. A jumper\'s corner is a bend over a hole, never a joint; a solder\n // path\'s joins that hole like the rest of its holes. Absent: straight.\n via?: GridPos[];\n // Absent: "jumper". Only solder paths say it.\n kind?: WireKind;\n // A jumper\'s insulation colour and thickness (drawing px). A solder path has neither.\n color?: string;\n width?: number;\n}\n\n// Every placed part has a `ref`: its reference designator (R1, C2, U1...), unique on the board\n// ignoring case. See part-refs.ts.\n\nexport interface SavedIc {\n instanceId?: string;\n ref: string;\n name: string;\n // Pin columns and rows as placed, i.e. already swapped by any 90/270 rotation.\n widthPin: number;\n heightPin: number;\n rotation: Rotation;\n pinDescription: Record<number, string>;\n // Top-left pin.\n at: GridPos;\n // The catalog category the chip was placed from; "modules\u2026" parts are drawn as boards. Absent in\n // files from before this was recorded.\n category?: string;\n}\n\nexport interface SavedStandardComponent {\n instanceId?: string;\n ref: string;\n definitionId: string;\n from: GridPos;\n to: GridPos;\n value?: string;\n color?: string;\n}\n\nexport interface SavedAdvancedComponent {\n instanceId?: string;\n ref: string;\n definitionId: string;\n // The anchor pin (the definition\'s pins[0]), or a grid-sizable block\'s top-left pin.\n at: GridPos;\n rotation: Rotation;\n rows: number;\n cols: number;\n value?: string;\n // A user-made part (version 6, definitionId "custom"): its whole definition, so the board needs\n // nothing else to draw it and know its pins (src/parts/custom-parts.ts): `name`, `cols` x `rows`\n // holes of body, its `pins` in order, each `at` a [column, row] within the body from its top-left\n // hole with an optional `label`, and optionally `refPrefix`, `color` (the body\'s) and `id` (its\n // entry in the editor\'s catalog). `at` above is pin 1\'s hole.\n custom?: CustomPartSpec;\n}\n\n// A user-made IC catalog entry. Loading a file adds these to the catalog (keyed by id) rather\n// than replacing it.\nexport interface SavedCustomIc {\n id?: number;\n name: string;\n widthPin: number;\n heightPin: number;\n pinDescription: Record<number, string>;\n // Where the part is listed in the Components panel; absent in files from before the catalog.\n category?: string;\n}\n\nexport interface ProjectFile {\n requirements?: CircuitRequirements;\n version: FileVersion;\n board: SavedBoard;\n pads: SavedPad[];\n wires: SavedWire[];\n // One array per kind, each in stacking order (see PartState.parts).\n placedIcs: SavedIc[];\n placedStandardComponents: SavedStandardComponent[];\n placedAdvancedComponents: SavedAdvancedComponent[];\n customIcs: SavedCustomIc[];\n}\n\nimport type { ProjectFile } from "./project-file";\nimport { partPins } from "./pin-positions";\nimport { computeNets, Net, NetPin } from "./nets";\n\nexport interface RequiredPin {\n componentId: string;\n pin: number;\n}\n\nexport interface RequiredComponent {\n id: string;\n ref: string;\n name: string;\n pins: { pin: number; label?: string }[];\n}\n\nexport interface RequiredNet {\n id: string;\n pins: RequiredPin[];\n}\n\nexport interface CircuitRequirements {\n validate: boolean;\n components: RequiredComponent[];\n nets: RequiredNet[];\n unused: RequiredPin[];\n}\n\nexport interface RequirementIssue {\n kind:\n | "missing-component"\n | "missing-pin"\n | "missing-connection"\n | "unexpected-connection";\n message: string;\n pins: RequiredPin[];\n}\n\nexport interface RequirementValidation {\n status: "disabled" | "incomplete" | "mismatch" | "match";\n issues: RequirementIssue[];\n unspecified: RequiredPin[];\n checked: number;\n total: number;\n}\n\n' }] }));
44964
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/plain", text: 'import {GridPos} from "./grid";\nimport type {CustomPartSpec} from "../parts/custom-parts";\nimport type {CircuitRequirements} from "./requirements";\n\n// The project file format, version 8. Positions are grid [column, row] pairs counted from the\n// top-left hole (column = left to right, row = top to bottom), not pixels, and only holes with a\n// note are listed. Older files are still read, see read-project-file.ts:\n// - version 7: the same, minus circuit requirements (`requirements`).\n// - version 6: the same as 7, minus part identities (a placed part\'s `instanceId`).\n// - version 5: the same as 6, minus custom parts (a fixed-pin part\'s `custom`).\n// - version 4: the same as 5, minus solder paths (a wire\'s `kind`).\n// - version 3: the same as 4, minus bent wires (a wire\'s `via`).\n// - version 2: the same as 3, minus the board type (always a perfboard) and part refs.\n// - version 1 (no `version` field): pixel coordinates, every hole listed, the whole IC catalog.\nexport const PROJECT_FILE_VERSION = 8;\n\n// A file says the oldest version that holds everything in it: 8 with requirements, else 6 with a\n// custom part, else 5 with a solder path, else 4 if a wire bends, else 3. So a board without them\n// still opens in editors and tools from before. Part identities (version 7) don\'t raise it: older\n// readers skip the field, and identities only matter to requirements, which are version 8.\nexport type FileVersion = 3 | 4 | 5 | 6 | typeof PROJECT_FILE_VERSION;\n\nexport function fileVersionFor(project: Pick<ProjectFile, "wires" | "placedAdvancedComponents" | "requirements">): FileVersion {\n if (project.requirements) return PROJECT_FILE_VERSION;\n if (project.placedAdvancedComponents.some(part => part.custom)) return 6;\n if (project.wires.some(wire => wire.kind === "solder")) return 5;\n return project.wires.some(wire => wire.via?.length) ? 4 : 3;\n}\n\nexport type Rotation = 0 | 90 | 180 | 270;\n\n// A perfboard has a separate copper pad around every hole: nothing is connected until it\'s wired.\n// A stripboard has long copper strips instead, each connecting a whole line of holes.\nexport type BoardType = "perfboard" | "stripboard";\n\n// Which way a stripboard\'s strips run. "horizontal": every hole in the same row is on one strip.\n// "vertical": every hole in the same column is.\nexport type StripDirection = "horizontal" | "vertical";\n\nexport interface SavedPerfboard {\n type: "perfboard";\n cols: number;\n rows: number;\n}\n\nexport interface SavedStripboard {\n type: "stripboard";\n cols: number;\n rows: number;\n strips: StripDirection;\n // Holes where the strip is cut (drilled through). A cut splits its strip in two, and the cut\n // hole itself connects to neither side: a lead in it is connected to nothing.\n cuts: GridPos[];\n}\n\nexport type SavedBoard = SavedPerfboard | SavedStripboard;\n\n// A hole with a note on it ("+9V", "GND", "to battery"). Purely a label: it says nothing about\n// what\'s connected. (Files from before notes were the only mark may give a hole a `color` too;\n// it\'s ignored.)\nexport interface SavedPad {\n at: GridPos;\n note: string;\n}\n\n// What a wire is made of (version 5):\n// - "jumper": an insulated jumper wire on the component side. It joins the holes at its two ends\n// and nothing else: not the holes it passes over, and not its corners.\n// - "solder": a solder path, a trail of solder bridging pad to pad on the copper side. Bare metal,\n// so it joins every hole it runs over: its ends, its corners and each hole along the way\n// (solderPathHoles() in wire-path.ts), and any solder path it touches. A cut hole on a\n// stripboard has no copper for it to join, so whatever is in one stays unconnected.\nexport type WireKind = "jumper" | "solder";\n\n// A wire: a jumper unless `kind` says otherwise.\nexport interface SavedWire {\n from: GridPos;\n to: GridPos;\n // Where it bends on its way from `from` to `to`, in order (version 4): it runs straight from\n // hole to hole through these. A jumper\'s corner is a bend over a hole, never a joint; a solder\n // path\'s joins that hole like the rest of its holes. Absent: straight.\n via?: GridPos[];\n // Absent: "jumper". Only solder paths say it.\n kind?: WireKind;\n // A jumper\'s insulation colour and thickness (drawing px). A solder path has neither.\n color?: string;\n width?: number;\n}\n\n// Every placed part has a `ref`: its reference designator (R1, C2, U1...), unique on the board\n// ignoring case. See part-refs.ts.\n\nexport interface SavedIc {\n instanceId?: string;\n ref: string;\n name: string;\n // Pin columns and rows as placed, i.e. already swapped by any 90/270 rotation.\n widthPin: number;\n heightPin: number;\n rotation: Rotation;\n pinDescription: Record<number, string>;\n // Top-left pin.\n at: GridPos;\n // The catalog category the chip was placed from; "modules\u2026" parts are drawn as boards. Absent in\n // files from before this was recorded.\n category?: string;\n}\n\nexport interface SavedStandardComponent {\n instanceId?: string;\n ref: string;\n definitionId: string;\n from: GridPos;\n to: GridPos;\n value?: string;\n color?: string;\n}\n\nexport interface SavedAdvancedComponent {\n instanceId?: string;\n ref: string;\n definitionId: string;\n // The anchor pin (the definition\'s pins[0]), or a grid-sizable block\'s top-left pin.\n at: GridPos;\n rotation: Rotation;\n rows: number;\n cols: number;\n value?: string;\n // A user-made part (version 6, definitionId "custom"): its whole definition, so the board needs\n // nothing else to draw it and know its pins (src/parts/custom-parts.ts): `name`, `cols` x `rows`\n // holes of body, its `pins` in order, each `at` a [column, row] within the body from its top-left\n // hole with an optional `label`, and optionally `refPrefix`, `color` (the body\'s) and `id` (its\n // entry in the editor\'s catalog). `at` above is pin 1\'s hole. With `shape`, the id of a built-in\n // fixed-pin part (e.g. "transistor", a TO-92), it\'s that part\'s package with its own name and pin\n // names: the package decides its pins\' holes (`cols`, `rows` and each `at` are written to match,\n // so a reader without shapes still finds the same pins) and how it\'s drawn; `color` is unused.\n custom?: CustomPartSpec;\n}\n\n// A user-made IC catalog entry. Loading a file adds these to the catalog (keyed by id) rather\n// than replacing it.\nexport interface SavedCustomIc {\n id?: number;\n name: string;\n widthPin: number;\n heightPin: number;\n pinDescription: Record<number, string>;\n // Where the part is listed in the Components panel; absent in files from before the catalog.\n category?: string;\n}\n\nexport interface ProjectFile {\n requirements?: CircuitRequirements;\n version: FileVersion;\n board: SavedBoard;\n pads: SavedPad[];\n wires: SavedWire[];\n // One array per kind, each in stacking order (see PartState.parts).\n placedIcs: SavedIc[];\n placedStandardComponents: SavedStandardComponent[];\n placedAdvancedComponents: SavedAdvancedComponent[];\n customIcs: SavedCustomIc[];\n}\n\nimport type { ProjectFile } from "./project-file";\nimport { partPins } from "./pin-positions";\nimport { computeNets, Net, NetPin } from "./nets";\n\nexport interface RequiredPin {\n componentId: string;\n pin: number;\n}\n\nexport interface RequiredComponent {\n id: string;\n ref: string;\n name: string;\n pins: { pin: number; label?: string }[];\n}\n\nexport interface RequiredNet {\n id: string;\n pins: RequiredPin[];\n}\n\nexport interface CircuitRequirements {\n validate: boolean;\n components: RequiredComponent[];\n nets: RequiredNet[];\n unused: RequiredPin[];\n}\n\nexport interface RequirementIssue {\n kind:\n | "missing-component"\n | "missing-pin"\n | "missing-connection"\n | "unexpected-connection";\n message: string;\n pins: RequiredPin[];\n}\n\nexport interface RequirementValidation {\n status: "disabled" | "incomplete" | "mismatch" | "match";\n issues: RequirementIssue[];\n unspecified: RequiredPin[];\n checked: number;\n total: number;\n}\n\n' }] }));
44725
44965
  server.registerResource("share-links", "perfboard://docs/share-links", {
44726
44966
  title: "Share links",
44727
44967
  description: "How a share link carries a project, and what happens when the user opens one.",
44728
44968
  mimeType: "text/markdown"
44729
- }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/markdown", text: '# Share links\n\nA share link opens a board in Perfboard Designer for whoever clicks it. The whole project travels\ninside the link itself, so there\'s no account, no upload and no server. In the editor, use\n**\u{1F517} Share** (or **File \u2192 Share Link...**) to make one. The same dialog can also make a **short\nlink** to a copy of the board stored on Perfboard Designer\'s server (`p`, below).\n\nThis page is the link format, written so that people and programs can make links too, including\nAI agents that design a board and hand the user a link to open it. The code is\n[`src/project-file/share-link.ts`](../src/project-file/share-link.ts). An agent that can use MCP\ncan skip most of this page: the [MCP server](../mcp/README.md) looks up parts, checks the project\nand makes the link for it.\n\n## What happens when a link is opened\n\n- The project is added to the receiver\'s projects (kept in their browser) as a **new project**,\n and opened. Whatever they had open stays as it was. The link is a snapshot: later changes by the\n sender aren\'t in it.\n- It\'s named after the link\'s `name`, or "Shared project". If a project with that name exists,\n the new one is numbered: "LED demo 2".\n- The link is then removed from the address bar, so reloading doesn\'t add the project again.\n- The project is checked like an imported file. Entries that can\'t be read are left out, and the\n user is told how many. A link that can\'t be read at all leaves everything untouched and says why.\n\n## Format\n\n```\nhttps://perfboarddesigner.com/app/#<fragment>\n```\n\nThe project goes in the URL **fragment** (after `#`), which browsers never send to a server. The\nfragment holds `key=value` parameters joined with `&`, like a query string:\n\n| Parameter | Value |\n| --- | --- |\n| `name` | Optional. The project\'s name, percent-encoded. |\n| `z` | The project file, compressed (see below). This is what the editor makes. |\n| `json` | The project file as plain JSON, percent-encoded. Must be the **last** parameter. |\n| `src` | The `https://` address of a project file hosted somewhere else, percent-encoded. |\n| `p` | The id of a project stored on Perfboard Designer\'s server: a short link. |\n\nUse exactly one of `z`, `json`, `src` and `p`. If several are present, `json` wins, then `z`, then\n`src`, then `p`.\n\n### `z`: compressed (shortest)\n\n1. Write the project file as JSON (minified is best).\n2. Compress its UTF-8 bytes with **raw DEFLATE** (no zlib or gzip header).\n3. Encode the result as **base64url** (`-` and `_` instead of `+` and `/`) with no `=` padding.\n\nThe reader is forgiving about what programs commonly produce instead. It also accepts zlib- or\ngzip-wrapped data, plain base64 with `+`, `/` and `=` padding, and line breaks in the base64 text.\n\nPython:\n\n```python\nimport base64, json, urllib.parse, zlib\n\ndef share_link(project: dict, name: str = "") -> str:\n data = json.dumps(project, separators=(",", ":")).encode("utf-8")\n deflate = zlib.compressobj(9, zlib.DEFLATED, -15) # -15: raw DEFLATE, no header\n z = base64.urlsafe_b64encode(deflate.compress(data) + deflate.flush()).rstrip(b"=").decode()\n name_param = f"name={urllib.parse.quote(name, safe=\'\')}&" if name else ""\n return f"https://perfboarddesigner.com/app/#{name_param}z={z}"\n```\n\nNode.js:\n\n```js\nconst zlib = require("zlib");\n\nfunction shareLink(project, name = "") {\n const z = zlib.deflateRawSync(Buffer.from(JSON.stringify(project))).toString("base64url");\n const nameParam = name ? `name=${encodeURIComponent(name)}&` : "";\n return `https://perfboarddesigner.com/app/#${nameParam}z=${z}`;\n}\n```\n\n### `json`: plain JSON (no tools needed)\n\n```\nhttps://perfboarddesigner.com/app/#name=LED%20demo&json=<percent-encoded project file JSON>\n```\n\nThis is for writers that can\'t compress, such as a language model writing the link directly.\nThese links are 3 to 7 times longer than `z` links. Rules:\n\n- `json` must be the **last parameter**: everything after `json=` is the project.\n- Percent-encode the JSON, as `encodeURIComponent` or Python\'s\n `urllib.parse.quote(text, safe="")` do. Encode at least spaces (`%20`), `#` (`%23`, which\n starts every color), `%` (`%25`) and `+` (`%2B`). A `+` is kept as a plus sign, never read as\n a space. Unencoded links may survive in a browser\'s address bar but are often broken by the chat\n apps and editors that turn text into links.\n- The reader tolerates a stray `%` that doesn\'t start an escape, such as a note saying `50%`.\n\n### `src`: a file hosted elsewhere\n\n```\nhttps://perfboarddesigner.com/app/#src=https%3A%2F%2Fexample.com%2Fmy-board.json\n```\n\n- The address must be `http://` or `https://`, and the site must allow other websites to read\n the file (CORS). Raw GitHub Gist and raw GitHub file addresses\n (`gist.githubusercontent.com`, `raw.githubusercontent.com`) do. A gist\'s normal page does not.\n- The user is asked before anything is downloaded, since fetching the file shows that site the\n visit.\n- Without a `name`, the project is named after the file (`my-board.json` \u2192 "my-board").\n- There\'s no size limit to worry about here, so this suits large boards and programs that can\n publish files.\n\n### `p`: a stored project (short link)\n\n```\nhttps://perfboarddesigner.com/app/#name=LED%20blinker&p=led-blinker\n```\n\n- The project is stored on Perfboard Designer\'s own server, `https://projects.perfboarddesigner.com`\n (below), and the link names it by its id. It\'s fetched without asking, since it\'s the site\'s own.\n- Without a `name`, the project is named after its id.\n- A stored project never changes, and it\'s deleted after a year unopened. Anyone with the link\n can open it. Unlike the other forms, it needs the server: the Share dialog offers the full link\n beside it, which works without one.\n\n### Stored projects\n\n`https://projects.perfboarddesigner.com` keeps projects for short links. Anyone can store one:\n\n| Request | Answer |\n| --- | --- |\n| `POST /projects` with `{"project": {\u2026}, "id": "led-blinker", "name": "LED blinker"}` (`id` and `name` optional) | `{id, link, file, image, png}`: the id it got, a short link, the file\'s address and its pictures\' |\n| `GET /<id>.json` | the project file |\n| `GET /<id>.png`, `GET /<id>.svg` | pictures of the board |\n\n- **Ids** are lowercase letters, digits and dashes, at most 40 characters, made from the wanted\n `id` or else the `name` (`"M\xE1gneses kapcsol\xF3!"` \u2192 `magneses-kapcsolo`). If another board has\n that id, a few characters of the board\'s SHA-256 are added (`led-blinker-08196a`); storing the\n same board under the same id again gives the same id back. With neither, the id is the hash.\n- Only valid project files are stored, as the editor reads them, up to 1 MB.\n- Every site may call it (CORS). There\'s no sign-in.\n- It\'s the [MCP server\'s](../mcp/README.md) Cloudflare Worker, which agents store through too.\n\n### Limits\n\n- The project file may be at most 5 MB once unpacked, and a board at most 500 holes on a side.\n- Links longer than about 8,000 characters may be cut off by some chat apps and mail clients; the\n Share dialog warns about these. For scale, the boards in [`examples/`](../examples) make `z`\n links of 0.8k to 2.7k characters.\n\n## The project file\n\nVersion 8 adds optional `requirements`: independent intended `nets` containing\n`{componentId, pin}` terminals, an explicit `unused` terminal list, component/pin snapshots\n(`components`) and an opt-in `validate` flag.\nAll terminals refer to stable component identities, not editable reference names. Snapshots\nkeep missing components/pins reportable; unspecified terminals are unchecked rather than unused.\nInvalid or overlapping requirement assignments reject the import instead of silently dropping\nconstraints. Board edits must preserve intended nets; adding a component extends the shared\ninventory without assigning new connections.\n\nVersion 7 adds a project-scoped `instanceId` to each placed part. Older readers skip it, so it\ndoesn\'t need a newer version on its own. A top-level `schematic` field, written by older editors,\nis ignored.\n\nA share link carries the same project file as **File \u2192 Save Project to File**. Every version\nopens, but write the oldest one that holds your board: version 8 with requirements,\nelse version 6 with a custom module, else 5\nwith a solder path, else 4 if a wire bends, else 3 (the same without any of them), which older\neditors open too. It\'s documented field by field in\n[`src/project-file/project-file.ts`](../src/project-file/project-file.ts). In short:\n\n- Positions are `[column, row]` grid holes counted from the **top-left hole**, both starting at 0.\n Neighbouring holes are 2.54 mm (0.1 in) apart.\n- `board`: `{"type": "perfboard", "cols": 12, "rows": 8}`, or a stripboard with\n `"strips": "horizontal" | "vertical"` and `"cuts": [[col, row], ...]`.\n- `pads`: holes with a `note` (like `+9V` or `GND`), as `{"at": [c, r], "note": "+9V"}`. Purely\n a label: it doesn\'t connect anything.\n- `wires`: `{"from": [c, r], "to": [c, r]}`, with optional `color` (`"#rrggbb"`) and `width`. A\n wire joins only its two end holes. With `"via": [[c, r], ...]` (version 4) it bends at those\n holes on its way, in order; a bend joins nothing. With `"kind": "solder"` (version 5) it\'s a\n solder path instead: a trail of solder on the copper side, with no `color` or `width`, that\n joins every hole it runs over (ends, bends and the holes between) and any solder path it\n touches.\n- `placedStandardComponents`: two-lead parts placed between two holes: `definitionId`, `from`,\n `to`, optional `value` (`"10k"`, `"100n"`) and `color` (LEDs). On polarized parts, `from` is\n an LED\'s cathode, a diode\'s anode and an electrolytic capacitor\'s \u2212 lead (`leadLabels` in the\n definitions).\n- `placedAdvancedComponents`: fixed-footprint parts: `definitionId`, the anchor pin `at`,\n `rotation` (0, 90, 180 or 270), `rows` and `cols` (1 except for sizable parts such as header\n pins), optional `value`. A user-made module has `"definitionId": "custom"` and carries the\n whole part in `custom` (version 6): `name`, optional `refPrefix`, its size in holes `cols` and\n `rows`, its `pins` in order as `{"at": [c, r], "label": "VCC"}` (holes within the body from its\n top-left hole; pin 1 is the anchor `at`) and an optional `color`.\n- `placedIcs`: DIP chips and dual-row modules: `name`, `at` (top-left pin), `widthPin` (columns\n including both pin rows, 4 for a 0.3" DIP), `heightPin` (pins per side), `rotation`, and\n `pinDescription` (`{"1": "GND", "2": "TRIG", ...}`, numbered counter-clockwise from pin 1).\n- `customIcs`: user-made catalog entries. `[]` is fine.\n- Every part should have a unique `ref` (R1, C2, U1...). Missing or duplicate refs are numbered\n automatically.\n\nThe reader is forgiving: empty lists can be left out, a file without `version` that has a `board`\nis read as version 8, and board entries it can\'t read are skipped (and counted) instead of failing the\nwhole project.\n\nThe `definitionId`s, with each part\'s pins, are in\n[`component-definitions.ts`](../src/parts/component-definitions.ts)\n(two-lead parts such as `resistor`, `ceramic-capacitor`, `electrolytic-capacitor`, `led` and\n`diode`) and\n[`advanced-component-definitions.ts`](../src/parts/advanced-component-definitions.ts)\n(fixed-footprint parts such as `transistor`, `potentiometer` and `header-pins`). Built-in chips are\nin [`ic-definitions.ts`](../src/parts/ic-definitions.ts), and footprints are described in\n[component-footprints.md](component-footprints.md). Check ids against these files: a part with an\nunknown `definitionId` isn\'t skipped, it stays on the board as an unrecognised part with an `X` ref.\n\n## Example\n\nA 9 V LED circuit on a 12 \xD7 8 perfboard:\n\n```json\n{\n "version": 3,\n "board": {"type": "perfboard", "cols": 12, "rows": 8},\n "pads": [{"at": [1, 1], "note": "+9V"}, {"at": [1, 6], "note": "GND"}],\n "wires": [\n {"from": [1, 1], "to": [3, 1], "color": "#ef4444"},\n {"from": [8, 4], "to": [8, 6]},\n {"from": [8, 6], "to": [1, 6]}\n ],\n "placedIcs": [],\n "placedStandardComponents": [\n {"ref": "R1", "definitionId": "resistor", "from": [3, 1], "to": [8, 1], "value": "470"},\n {"ref": "D1", "definitionId": "led", "from": [8, 2], "to": [8, 4], "color": "#22c55e"}\n ],\n "placedAdvancedComponents": [\n {"ref": "J1", "definitionId": "header-pins", "at": [0, 1], "rotation": 0, "rows": 6, "cols": 1}\n ],\n "customIcs": []\n}\n```\n\nAs a `json` link (the start of it):\n\n```\nhttps://perfboarddesigner.com/app/#name=LED%20demo&json=%7B%22version%22%3A3%2C%22board%22%3A%7B%22type%22%3A%22perfboard%22%2C...\n```\n' }] }));
44969
+ }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/markdown", text: '# Share links\n\nA share link opens a board in Perfboard Designer for whoever clicks it. The whole project travels\ninside the link itself, so there\'s no account, no upload and no server. In the editor, use\n**\u{1F517} Share** (or **File \u2192 Share Link...**) to make one. The same dialog can also make a **short\nlink** to a copy of the board stored on Perfboard Designer\'s server (`p`, below).\n\nThis page is the link format, written so that people and programs can make links too, including\nAI agents that design a board and hand the user a link to open it. The code is\n[`src/project-file/share-link.ts`](../src/project-file/share-link.ts). An agent that can use MCP\ncan skip most of this page: the [MCP server](../mcp/README.md) looks up parts, checks the project\nand makes the link for it.\n\n## What happens when a link is opened\n\n- The project is added to the receiver\'s projects (kept in their browser) as a **new project**,\n and opened. Whatever they had open stays as it was. The link is a snapshot: later changes by the\n sender aren\'t in it.\n- It\'s named after the link\'s `name`, or "Shared project". If a project with that name exists,\n the new one is numbered: "LED demo 2".\n- The link is then removed from the address bar, so reloading doesn\'t add the project again.\n- The project is checked like an imported file. Entries that can\'t be read are left out, and the\n user is told how many. A link that can\'t be read at all leaves everything untouched and says why.\n\n## Format\n\n```\nhttps://perfboarddesigner.com/app/#<fragment>\n```\n\nThe project goes in the URL **fragment** (after `#`), which browsers never send to a server. The\nfragment holds `key=value` parameters joined with `&`, like a query string:\n\n| Parameter | Value |\n| --- | --- |\n| `name` | Optional. The project\'s name, percent-encoded. |\n| `z` | The project file, compressed (see below). This is what the editor makes. |\n| `json` | The project file as plain JSON, percent-encoded. Must be the **last** parameter. |\n| `src` | The `https://` address of a project file hosted somewhere else, percent-encoded. |\n| `p` | The id of a project stored on Perfboard Designer\'s server: a short link. |\n\nUse exactly one of `z`, `json`, `src` and `p`. If several are present, `json` wins, then `z`, then\n`src`, then `p`.\n\n### `z`: compressed (shortest)\n\n1. Write the project file as JSON (minified is best).\n2. Compress its UTF-8 bytes with **raw DEFLATE** (no zlib or gzip header).\n3. Encode the result as **base64url** (`-` and `_` instead of `+` and `/`) with no `=` padding.\n\nThe reader is forgiving about what programs commonly produce instead. It also accepts zlib- or\ngzip-wrapped data, plain base64 with `+`, `/` and `=` padding, and line breaks in the base64 text.\n\nPython:\n\n```python\nimport base64, json, urllib.parse, zlib\n\ndef share_link(project: dict, name: str = "") -> str:\n data = json.dumps(project, separators=(",", ":")).encode("utf-8")\n deflate = zlib.compressobj(9, zlib.DEFLATED, -15) # -15: raw DEFLATE, no header\n z = base64.urlsafe_b64encode(deflate.compress(data) + deflate.flush()).rstrip(b"=").decode()\n name_param = f"name={urllib.parse.quote(name, safe=\'\')}&" if name else ""\n return f"https://perfboarddesigner.com/app/#{name_param}z={z}"\n```\n\nNode.js:\n\n```js\nconst zlib = require("zlib");\n\nfunction shareLink(project, name = "") {\n const z = zlib.deflateRawSync(Buffer.from(JSON.stringify(project))).toString("base64url");\n const nameParam = name ? `name=${encodeURIComponent(name)}&` : "";\n return `https://perfboarddesigner.com/app/#${nameParam}z=${z}`;\n}\n```\n\n### `json`: plain JSON (no tools needed)\n\n```\nhttps://perfboarddesigner.com/app/#name=LED%20demo&json=<percent-encoded project file JSON>\n```\n\nThis is for writers that can\'t compress, such as a language model writing the link directly.\nThese links are 3 to 7 times longer than `z` links. Rules:\n\n- `json` must be the **last parameter**: everything after `json=` is the project.\n- Percent-encode the JSON, as `encodeURIComponent` or Python\'s\n `urllib.parse.quote(text, safe="")` do. Encode at least spaces (`%20`), `#` (`%23`, which\n starts every color), `%` (`%25`) and `+` (`%2B`). A `+` is kept as a plus sign, never read as\n a space. Unencoded links may survive in a browser\'s address bar but are often broken by the chat\n apps and editors that turn text into links.\n- The reader tolerates a stray `%` that doesn\'t start an escape, such as a note saying `50%`.\n\n### `src`: a file hosted elsewhere\n\n```\nhttps://perfboarddesigner.com/app/#src=https%3A%2F%2Fexample.com%2Fmy-board.json\n```\n\n- The address must be `http://` or `https://`, and the site must allow other websites to read\n the file (CORS). Raw GitHub Gist and raw GitHub file addresses\n (`gist.githubusercontent.com`, `raw.githubusercontent.com`) do. A gist\'s normal page does not.\n- The user is asked before anything is downloaded, since fetching the file shows that site the\n visit.\n- Without a `name`, the project is named after the file (`my-board.json` \u2192 "my-board").\n- There\'s no size limit to worry about here, so this suits large boards and programs that can\n publish files.\n\n### `p`: a stored project (short link)\n\n```\nhttps://perfboarddesigner.com/app/#name=LED%20blinker&p=led-blinker\n```\n\n- The project is stored on Perfboard Designer\'s own server, `https://projects.perfboarddesigner.com`\n (below), and the link names it by its id. It\'s fetched without asking, since it\'s the site\'s own.\n- Without a `name`, the project is named after its id.\n- A stored project never changes, and it\'s deleted after a year unopened. Anyone with the link\n can open it. Unlike the other forms, it needs the server: the Share dialog offers the full link\n beside it, which works without one.\n\n### Stored projects\n\n`https://projects.perfboarddesigner.com` keeps projects for short links. Anyone can store one:\n\n| Request | Answer |\n| --- | --- |\n| `POST /projects` with `{"project": {\u2026}, "id": "led-blinker", "name": "LED blinker"}` (`id` and `name` optional) | `{id, link, file, image, png}`: the id it got, a short link, the file\'s address and its pictures\' |\n| `GET /<id>.json` | the project file |\n| `GET /<id>.png`, `GET /<id>.svg` | pictures of the board |\n\n- **Ids** are lowercase letters, digits and dashes, at most 40 characters, made from the wanted\n `id` or else the `name` (`"M\xE1gneses kapcsol\xF3!"` \u2192 `magneses-kapcsolo`). If another board has\n that id, a few characters of the board\'s SHA-256 are added (`led-blinker-08196a`); storing the\n same board under the same id again gives the same id back. With neither, the id is the hash.\n- Only valid project files are stored, as the editor reads them, up to 1 MB.\n- Every site may call it (CORS). There\'s no sign-in.\n- It\'s the [MCP server\'s](../mcp/README.md) Cloudflare Worker, which agents store through too.\n\n### Limits\n\n- The project file may be at most 5 MB once unpacked, and a board at most 500 holes on a side.\n- Links longer than about 8,000 characters may be cut off by some chat apps and mail clients; the\n Share dialog warns about these. For scale, the boards in [`examples/`](../examples) make `z`\n links of 0.8k to 2.7k characters.\n\n## The project file\n\nVersion 8 adds optional `requirements`: independent intended `nets` containing\n`{componentId, pin}` terminals, an explicit `unused` terminal list, component/pin snapshots\n(`components`) and an opt-in `validate` flag.\nAll terminals refer to stable component identities, not editable reference names. Snapshots\nkeep missing components/pins reportable; unspecified terminals are unchecked rather than unused.\nInvalid or overlapping requirement assignments reject the import instead of silently dropping\nconstraints. Board edits must preserve intended nets; adding a component extends the shared\ninventory without assigning new connections.\n\nVersion 7 adds a project-scoped `instanceId` to each placed part. Older readers skip it, so it\ndoesn\'t need a newer version on its own. A top-level `schematic` field, written by older editors,\nis ignored.\n\nA share link carries the same project file as **File \u2192 Save Project to File**. Every version\nopens, but write the oldest one that holds your board: version 8 with requirements,\nelse version 6 with a custom module, else 5\nwith a solder path, else 4 if a wire bends, else 3 (the same without any of them), which older\neditors open too. It\'s documented field by field in\n[`src/project-file/project-file.ts`](../src/project-file/project-file.ts). In short:\n\n- Positions are `[column, row]` grid holes counted from the **top-left hole**, both starting at 0.\n Neighbouring holes are 2.54 mm (0.1 in) apart.\n- `board`: `{"type": "perfboard", "cols": 12, "rows": 8}`, or a stripboard with\n `"strips": "horizontal" | "vertical"` and `"cuts": [[col, row], ...]`.\n- `pads`: holes with a `note` (like `+9V` or `GND`), as `{"at": [c, r], "note": "+9V"}`. Purely\n a label: it doesn\'t connect anything.\n- `wires`: `{"from": [c, r], "to": [c, r]}`, with optional `color` (`"#rrggbb"`) and `width`. A\n wire joins only its two end holes. With `"via": [[c, r], ...]` (version 4) it bends at those\n holes on its way, in order; a bend joins nothing. With `"kind": "solder"` (version 5) it\'s a\n solder path instead: a trail of solder on the copper side, with no `color` or `width`, that\n joins every hole it runs over (ends, bends and the holes between) and any solder path it\n touches.\n- `placedStandardComponents`: two-lead parts placed between two holes: `definitionId`, `from`,\n `to`, optional `value` (`"10k"`, `"100n"`) and `color` (LEDs). On polarized parts, `from` is\n an LED\'s cathode, a diode\'s anode and an electrolytic capacitor\'s \u2212 lead (`leadLabels` in the\n definitions).\n- `placedAdvancedComponents`: fixed-footprint parts: `definitionId`, the anchor pin `at`,\n `rotation` (0, 90, 180 or 270), `rows` and `cols` (1 except for sizable parts such as header\n pins), optional `value`. A user-made module has `"definitionId": "custom"` and carries the\n whole part in `custom` (version 6): `name`, optional `refPrefix`, its size in holes `cols` and\n `rows`, its `pins` in order as `{"at": [c, r], "label": "VCC"}` (holes within the body from its\n top-left hole; pin 1 is the anchor `at`) and an optional `color`. With `"shape"`, the id of a\n built-in fixed-pin part (e.g. `"transistor"` for a TO-92), it\'s that package with its own `name`\n and pin names (`pins` in the package\'s pin order, each `{"label": "B"}`): the package decides its\n holes, and `cols`, `rows` and each `at` are written to match it.\n- `placedIcs`: DIP chips and dual-row modules: `name`, `at` (top-left pin), `widthPin` (columns\n including both pin rows, 4 for a 0.3" DIP), `heightPin` (pins per side), `rotation`, and\n `pinDescription` (`{"1": "GND", "2": "TRIG", ...}`, numbered counter-clockwise from pin 1).\n- `customIcs`: user-made catalog entries. `[]` is fine.\n- Every part should have a unique `ref` (R1, C2, U1...). Missing or duplicate refs are numbered\n automatically.\n\nThe reader is forgiving: empty lists can be left out, a file without `version` that has a `board`\nis read as version 8, and board entries it can\'t read are skipped (and counted) instead of failing the\nwhole project.\n\nThe `definitionId`s, with each part\'s pins, are in\n[`component-definitions.ts`](../src/parts/component-definitions.ts)\n(two-lead parts such as `resistor`, `ceramic-capacitor`, `electrolytic-capacitor`, `led` and\n`diode`) and\n[`advanced-component-definitions.ts`](../src/parts/advanced-component-definitions.ts)\n(fixed-footprint parts such as `transistor`, `potentiometer` and `header-pins`). Built-in chips are\nin [`ic-definitions.ts`](../src/parts/ic-definitions.ts), and footprints are described in\n[component-footprints.md](component-footprints.md). Check ids against these files: a part with an\nunknown `definitionId` isn\'t skipped, it stays on the board as an unrecognised part with an `X` ref.\n\n## Example\n\nA 9 V LED circuit on a 12 \xD7 8 perfboard:\n\n```json\n{\n "version": 3,\n "board": {"type": "perfboard", "cols": 12, "rows": 8},\n "pads": [{"at": [1, 1], "note": "+9V"}, {"at": [1, 6], "note": "GND"}],\n "wires": [\n {"from": [1, 1], "to": [3, 1], "color": "#ef4444"},\n {"from": [8, 4], "to": [8, 6]},\n {"from": [8, 6], "to": [1, 6]}\n ],\n "placedIcs": [],\n "placedStandardComponents": [\n {"ref": "R1", "definitionId": "resistor", "from": [3, 1], "to": [8, 1], "value": "470"},\n {"ref": "D1", "definitionId": "led", "from": [8, 2], "to": [8, 4], "color": "#22c55e"}\n ],\n "placedAdvancedComponents": [\n {"ref": "J1", "definitionId": "header-pins", "at": [0, 1], "rotation": 0, "rows": 6, "cols": 1}\n ],\n "customIcs": []\n}\n```\n\nAs a `json` link (the start of it):\n\n```\nhttps://perfboarddesigner.com/app/#name=LED%20demo&json=%7B%22version%22%3A3%2C%22board%22%3A%7B%22type%22%3A%22perfboard%22%2C...\n```\n' }] }));
44730
44970
  server.registerResource("parts", "perfboard://parts", {
44731
44971
  title: "Parts catalog",
44732
44972
  description: "Every part a project can place, with pins and pin labels, as JSON.",
@@ -44743,7 +44983,7 @@ function registerResources(server) {
44743
44983
 
44744
44984
  // src/create-server.ts
44745
44985
  function createServer({ editorUrl, imageUrl: imageUrl2, storage }) {
44746
- const server = new McpServer({ name: "perfboard-designer", version: "0.3.0" }, { instructions: INSTRUCTIONS });
44986
+ const server = new McpServer({ name: "perfboard-designer", version: "0.4.0" }, { instructions: INSTRUCTIONS });
44747
44987
  registerCatalogTools(server);
44748
44988
  registerProjectTools(server);
44749
44989
  registerBoardTools(server);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "perfboard-designer-mcp",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "MCP server for Perfboard Designer: lets AI agents look up parts, check perfboard and stripboard layouts, and hand back a link that opens the board in the editor.",
5
5
  "license": "ISC",
6
6
  "mcpName": "com.perfboarddesigner/mcp",