Compiler and canonical model
Why pcbjs is built the way it is: SVG as vocabulary, JSX without React, the schematic layer, the compile stages, and how a board is checked. Advanced. Read it before changing the compiler; the user reference is the other topic files.
// what jsx() returns: a plain node, no React, no reconciler
const node = { $$: 'pcb', type: 'rect', props: { layer: 'Edge.Cuts', w: 40, h: 12 }, children: [] }SVG is the vocabulary, not the model
- pcbjs borrows SVG's words,
dpath data,<g>,<rect>,<circle>,<line>and nested transforms, which many people read. - SVG has no nets, pads, drills, stack or rules, and a flip to the back swaps every
F.*layer for itsB.*twin, which no transform expresses. - The canonical model is the compiled
Boardinpackages/core/src/model.ts: flat pads, tracks, vias, zones, graphics and text in absolute mm, each with layer, net and footprint. Every exporter reads it;<name>.pcb.svgis one export, never parsed back.
JSX without React
jsx()returns a node{ $$: 'pcb', type, props, children }. A component is a pure function called once in flatten; the board recompiles on each change.- The JSX types come from
types.ts, so a misspelled prop fails in the editor;jsxDEVrecords where each element starts.
The schematic layer
- Nets are values, because a string
GDNis quietly a new net.nets()hands outNetobjects through a proxy, a factory with a value gives aPart, and.connect({ … })checks pin names in TypeScript and at runtime. There are no string nets. - A part's ref is its binding name, captured by
scope.tsat the top level and in a circuit's build; a loop part takes{ ref }, and a placed part with no name is a compile error. Parts render with a placeholder ref rewritten once every part is known. - A project's parts, defaults, KiCad config, model resolver and source mapper are one realm on
globalThis, swapped byinRealm; parts and nets are known by their$$brand, as the CLI's pcbjs compiles what Vite's copy made. The compile takes the default layer as an option its key hashes. A re-evaluated module replaces its parts; a module-level part declared in the relevant design scope but never placed is a compile error; isolated library previews can retain unplaced template members. - A circuit is a build function from ports to parts by key, typed so
Buck1.R1checks. Private nets are scoped to the instance, named from its path. Ports are the only way across, enforced atconnect. Refs stay flat for fabs and silk; the hierarchy ispathandlocalin the netlist. - A layout wraps its output in a marked group, so one circuit can have several, two layouts of one instance are rejected, and an instance never placed is one compile error, not one per part.
Sourcing
A part carries MPN and MPN:<tag>; a board or fab target has an ordered tag list resolved like any setting, and each BOM row takes the first tag it has, else MPN. .source() on the part is the one place for its keys, inline or in a sourcing module that calls it on imported parts.
The stage graph
pcb.config.ts and the entry load through Vite's SSR loader, which adds source ranges and transforms TSX with esbuild; entries share only the module graph. That load, evaluateEntry over a ModuleLoader in Node and in the browser worker, is the evaluate stage passed to compileLoaded, so one runner times, cancels and reports every stage. STAGE_DEFS in compile/stages.ts declares each stage once: what it runs after, the facets it reads and writes, the views it emits. The runner in compile/runner.ts runs the stages the wanted views need, with before and after hooks and two plugin slots:
| Stage | Reads | Writes | Code |
|---|---|---|---|
evaluate | the root, its targets checked, the plugins | stages.ts, pipeline.ts | |
manual | flattened declarations | a separate solver-free projection of fixed placements and resolvable authored copper for live meta, layers and shapes | explicit-geometry.ts, autoroute.ts |
place | parts, pads, nets, netlist and its ERC, jobs, outline, references, patches, the dependency graph; unit placer, keyed on what it places | flatten.ts, placer.ts, reference.ts, deps.ts | |
schematic | meta, parts, pads, nets, netlist, rest, jobs.sch | the drawing, sch-* findings | sch.ts |
manualCopper | as autoroute | each route's manual copper, planRoutes | autoroute.ts |
autoroute, placeFollowers, routeFollowers | meta, rules, stackup, outline, keepouts, parts, pads, copper, frame, nets, netlist, routes, rest, jobs; drawings with followers or a shared group | legs, pairs, failures, the at:follow parts | autoroute.ts, follow.ts |
tune | as autoroute, and the drawings within reach of a tuned route | meanders, skew bumps, route records | tune.ts |
patches | copper patches, patch-stale | patches.ts | |
finish | unit pours: as autoroute but netlist, rest and jobs, with jobs.finish, and drawings when a stitch keeps off silk; unit silk: meta, rules, outline, parts, pads, drawings, frame, jobs.finish | teardrops, fills, stitching vias; silk refs | zones.ts, silk-refs.ts |
checks | a unit per CheckDef of checks.ts, then plugin checks | every finding by severity | drc.ts, connectivity.ts |
exports | every facet, the formats' keys and model files | the formats the caller passes | stages.ts, formats in cli/src/project/project.ts |
beforeRouteruns inside the routing unit beforeautoroute,beforeChecksbeforechecks, each of its stages a unit of its own.- Live PCB geometry: flatten all targets and emit
manualbefore any placement, reference child compilation, schematic solver or router. The projection shares the manual route command walker and leaves authoritative boards and stage outputs unchanged. Unresolved placements, endpoint-dependent commands, differential pairs and rounded corner jobs wait for their normal stages; early airwires are empty. Neck-down processing also waits, so early copper near narrow pads can appear wider than the finished route. Model assets update at place. Schematic-only demand keeps its existing plan. - Variants:
evaluateonce per entry;placeandschematicfor every target first;autorouteandtuneonce per routing group, its other targets copying the lead's tuned copper; later stages per target. - Flatten calls components, composes
atand side flips, resolves layers, maps nets to pads by number then pin name, and gives refs, the netlist and its ERC; errors carry the source. - The schematic places symbols, checks hand wires and wires the rest in the router's square mode,
sch-route.ts; see schematic-graphic.md. - Every
route()becomes jobs once the tree and outline are known; manual commands are placed first, then legs run bypriorityand document order through aRouteContext, withmaze,straightor a customRouteFn, each an obstacle for the next. - Zones fill after routing, by priority: clip to the outline inset by
edgeClearance, subtract other-net copper and holes, open byzoneMinWidth, drop islands; Clipper. - Connectivity is union-find per copper layer, each pour piece its own item, one pass over grid candidates feeding DRC; tests are on edges, Clipper builds. DRC is findings.md.
- A hook's delta applies to its stage's input for
before, its output forafter; plugins.md. wantlists views,meta,sch,layers,shapes,model,findings,fab; the plan is every stage whoseemitsmeets them and what they run after:schrunsevaluate,placeandschematic.CompileOptions.signalis read bypulse()in every stage and its loops, including pair layout candidates, sampled clearance checks, pair-segment comparisons and obstacle-grid updates: the compile throwsCancelledErrorwithin a few ms, its finished units cached. Pair layout fallbacks preserve cancellation instead of treating it as a geometry failure.sketch(), the keystroke tier, is the plan ofmetaandmanualCopperwith the cache, the placer and references off.- A stage that changes an item puts a new one in its place with its id and uid.
PCBJS_FREEZE=1, on in the tests, deep-freezes each item as it joins the board and each field once no later stage writes it, and throws when a stage changes a facet itswritesleaves out. board.timingskeeps five phases.
Routing details:
- A failed leg is a
route-failedfinding with its nearest obstacles, so it hides no other leg;<PCB strict>throws instead. - Pure maze searches are cached by request and validated search reads in
.pcbjs/cache/route/<board>.json; joins and negotiation still run against the current board. A hold patch freezes a route, patches.md. - A pair routes its centre line as one wide track, which
compile/pair.tsoffsets into two tracks with fans and via pairs;compile/tune.tsthen tunes skew,.length()and.match(). - autorouter.md has the rest.
Cycles
place builds the dependency graph: a route to the parts it ends on, a part to its grid, a grid to its anchor, a follower to its route, a solver to what it reads, a reference() to its entry across processes through PCBJS_REFERENCE_CHAIN. A cycle or a self edge is a compile error naming each member: grid-cycle, follow-cycle, solver-order or reference-cycle. Nets, pours and at:cost are no edges; nothing iterates to a fixpoint.
The stage cache
Explicit preview geometry uses a demand graph within the existing cache lifetime. Nodes hold immutable values, semantic identities and tracked reads. An input change marks consumers suspect; an unchanged result stops propagation. Failed or cancelled work cannot publish, and dependency records change only after successful evaluation. Graphs are isolated by project, entry and target and bounded in memory; source evaluation and flattening remain coarse inputs.
The manual stage materializes these products into a fresh board for streaming. Independent manual routes read their endpoint geometry; branches and route-point relationships stay coupled and use the same route interpreter. Transient item IDs belong to the materialized board, not cached products. Navigation metadata and shared routing declarations remain conservative dependencies, so some non-geometric edits also recompute products. Existing stage units remain responsible for coupled solvers, plugins, checks and exports.
.pcbjs/cacheholdsmeta.jsonwithformatandcompileId, Vite's cache invite/,index/<board>[~<slug>].json, outputs asobjects/<hh>/<sha1>.json.gzand binary exports as.bin, named by content and written by rename, the route memos inroute/<board>.jsonandreferences/.compileIdhashes@pcbjs/compileand@pcbjs/core, each with itsdisthash in a workspace link.- A unit is a stage, a run of stages stored as one such as routing, or a unit of a stage such as
checks:clearance. Its key is the sha1 of its name,compileId, its plugins, the hash of each facet it reads and its own inputs; a hook in it makes it read every facet. Its output is the board's delta, its findings and what it keeps, the zone state or the tuning hand-off.evaluate,placeandpatchesalways run. - A label edit misses the silk refs, the silk checks and the exports;
tunereads only the drawings within reach of a tuned route. - A plugin-free start whose listed files, environment digest, defaults and exporters all match serves the boards without evaluating. Plugin-bearing boards re-evaluate configuration before reusing individual stages. A missing object is a miss, a draft writes memory only, units done before a cancel are stored, and objects neither index names are pruned.
--freshismake -B;check --cacheprints each unit's hit or miss and key.
Hosts
Everything the compiler reaches outside JavaScript goes through the Platform of @pcbjs/core/platform on globalThis: files, sha1, paths, the environment and a store, the disk of the stage cache and route memos. Node's is the default; memoryPlatform keeps files in memory with no store, so its caches never meet Node's, browser.md.
Source ranges
packages/cli/src/project/source-ranges.ts, a Vite transform before esbuild, adds a __src prop with the full range to every JSX element and every route, pour and via call. Flatten keeps it as the item's src and the enclosing calls as chain, outermost first; sourceIndex in packages/export/src/site-data.ts nests ranges per file with their item uids and refs.
The 3D view
Item rows name each item by uid and compile-local id; the shapes facet holds its rings in board mm by id; packages/ui/src/scene/items.ts batches the extrusions by layer, a group per physical layer making explode a z offset.
The IDE bridge
Every client, the editor too, joins the session .pcbjs/dev.json names, ide-bridge.md.
The dev loop
- Vite's watcher sees a change outside
.pcbjsandnode_modules. - The session's Vite plugin suppresses design HMR and passes edits to each project's runtime. Its scheduler gathers disk writes for 60 ms, starts sketches immediately with a 30 ms minimum interval and compiles the demanded views after 300 ms of typing quiet; a query requests every view, session.md.
- Before the compile,
pcbjs:invalidatemarks what the edit makes stale; each stage's facet goes out aspcbjs:facetas it ends, thenpcbjs:boardswith per-entry errors; the viewer keeps zoom, hidden layers and selection, see viewer.md. - A failed compile sends
pcbjs:error. The session attempts a cache-free preview of the current source before the failing expression, with placements, schematic geometry and manual copper only.meta.haltedrecords the failed stage, ordered stages, completed stages and source location. The preview replaces all displayed facets, retains completed manual-route point provenance and current copper connectivity for endpoint assistance, clears check results and has no manufacturing artifacts. Failed entries remain absent from successful query snapshots. If recovery cannot construct a board, the last successful board is explicitly stale. A later edit of a failed entry runs every stage before clearing the error.
- Boards are keyed by
name:/__pcbjs/<name>/in dev,fab/<name>/andboards/<name>.jsonin the site. The fab zip is built on request.pcbjs buildruns the same compile, then writes fab sets,boards.jsonand the site. - The site is prerendered from
packages/viewer/src/entry-server.ts, each route anindex.htmlwith its facets, hydrated in place. State comes fromcreateViewer; 2D and 3D render after hydration. Prerendering needs an absolute base; a relative base builds a client-rendered site.
Validation plan
Port a fabricated two-layer KiCad board with a pour; compare each Gerber layer as geometry but fills, thermals, text and arcs; compare drills, the netlist and placement; check pcbjs DRC finds every KiCad error; load the Gerbers in a viewer and a fab's checker; order the board.