@huaqiu/hardware-artifacts 0.7.12 → 0.7.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/service.ts CHANGED
@@ -3,15 +3,26 @@
3
3
  *
4
4
  * This module deliberately has no Cordis dependency: it is the testable core
5
5
  * behind `hardwareArtifacts`. Native project files remain authoritative; the
6
- * objects here are path pointers and verified installation facts, never a
7
- * shadow project database.
6
+ * objects here are path pointers, verified installation facts and disposable
7
+ * derived outputs, never a shadow project database.
8
8
  */
9
- import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
10
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
9
+ import { execFile, execFileSync, spawn, type ChildProcess } from 'node:child_process'
10
+ import { createHash } from 'node:crypto'
11
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from 'node:fs'
12
+ import { readFile } from 'node:fs/promises'
11
13
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
14
+ import { tmpdir } from 'node:os'
15
+ import {
16
+ DEFAULT_ORDER_BASE_URL, DEFAULT_ORDER_PAGE_BASE, multipartBody,
17
+ ORDER_PATHS, orderBomCsv, orderBomRows, orderIdsFromUrl, packageName, parsePositions,
18
+ pcbOrderForm, pcbOrderUrl, positionsCsv, readBoardFacts, readExportDirectory, smtOrderForm,
19
+ smtOrderUrl, smtOrderUrlFromBackend, zipPackage,
20
+ type BoardFacts,
21
+ } from './order.js'
12
22
 
13
23
  export type ArtifactKind = 'schematic' | 'pcb' | 'pcb-3d' | 'bom' | 'mechanical-3d'
14
- export type NativeApplication = 'kicad' | 'solidcraft'
24
+ /** Native handoff is KiCad-only in this POC; SolidCraft stays agent context. */
25
+ export type NativeApplication = 'kicad'
15
26
 
16
27
  export interface HardwareArtifact {
17
28
  readonly id: string
@@ -22,16 +33,22 @@ export interface HardwareArtifact {
22
33
  readonly sourcePath?: string
23
34
  readonly title: string
24
35
  readonly format: string
36
+ /** Content hash of the saved source, filled when the source is read. */
37
+ readonly revision?: string
25
38
  }
26
39
 
27
40
  export interface HardwareProject {
28
41
  readonly path: string
29
42
  readonly name: string
43
+ /** Root schematic: the authoritative project entry point. */
44
+ readonly rootSheet?: HardwareArtifact
30
45
  readonly schematic?: HardwareArtifact
31
46
  /** Semantic views; both keep the identity of their source artifact. */
32
47
  readonly bom?: HardwareArtifact
33
48
  readonly pcb3d?: HardwareArtifact
34
49
  readonly sheets: readonly HardwareArtifact[]
50
+ /** Deterministic default board, only when ownership is unambiguous. */
51
+ readonly defaultBoard?: string
35
52
  readonly boards: readonly HardwareArtifact[]
36
53
  readonly mechanical: readonly HardwareArtifact[]
37
54
  readonly selectionRequired: boolean
@@ -77,15 +94,178 @@ export interface OpenArtifactResult {
77
94
  readonly pid?: number
78
95
  }
79
96
 
97
+ export interface SourceRequest {
98
+ readonly artifactPath: string
99
+ readonly expectedRevision?: string
100
+ /**
101
+ * Roots the caller names. They are *added* to the roots the host resolved
102
+ * for {@link sessionId}; naming one never revokes another.
103
+ */
104
+ readonly roots?: readonly string[]
105
+ /** DSH session the read belongs to; its workspace is the authorization base. */
106
+ readonly sessionId?: string
107
+ }
108
+
109
+ export interface SourceResult {
110
+ readonly path: string
111
+ readonly kind: 'schematic' | 'pcb'
112
+ readonly revision: string
113
+ readonly bytes: number
114
+ readonly mtimeMs: number
115
+ readonly text: string
116
+ }
117
+
118
+ export interface GlbRequest {
119
+ readonly artifactPath: string
120
+ readonly roots?: readonly string[]
121
+ readonly sessionId?: string
122
+ readonly signal?: AbortSignal
123
+ }
124
+
125
+ export interface GlbResult {
126
+ readonly path: string
127
+ readonly revision: string
128
+ readonly bytes: number
129
+ readonly generatedAt: string
130
+ readonly cached: boolean
131
+ readonly file: string
132
+ }
133
+
134
+ /** One grouped BOM line, as KiCad's own BOM export groups it. */
135
+ export interface BomRow {
136
+ readonly references: readonly string[]
137
+ readonly quantity: number
138
+ readonly value: string
139
+ readonly footprint: string
140
+ readonly dnp: boolean
141
+ readonly fields: Readonly<Record<string, string>>
142
+ }
143
+
144
+ export interface BomResult {
145
+ readonly path: string
146
+ readonly revision: string
147
+ readonly generatedAt: string
148
+ readonly cached: boolean
149
+ readonly rows: readonly BomRow[]
150
+ readonly source: 'kicad-cli-bom'
151
+ }
152
+
153
+ export interface OrderPackageSummary {
154
+ readonly zipName: string
155
+ readonly zipBytes: number
156
+ readonly files: readonly { readonly name: string; readonly bytes: number }[]
157
+ }
158
+
159
+ /** A prepared fabrication package: what would be uploaded, nothing sent yet. */
160
+ export interface FabricationResult {
161
+ readonly boardPath: string
162
+ readonly revision: string
163
+ readonly generatedAt: string
164
+ readonly facts: BoardFacts
165
+ readonly archive: OrderPackageSummary
166
+ /** Assembly inputs, present when a schematic was supplied. */
167
+ readonly assembly?: {
168
+ readonly positions: number
169
+ readonly bomLines: number
170
+ readonly positionsBytes: number
171
+ readonly bomBytes: number
172
+ }
173
+ }
174
+
175
+ export interface OrderConfigInfo {
176
+ readonly configured: boolean
177
+ readonly baseUrl: string
178
+ /** True when a signed-in session or a configured token can sign the page. */
179
+ readonly hasToken: boolean
180
+ readonly provider: 'huaqiu'
181
+ }
182
+
183
+ export interface PlaceOrderRequest {
184
+ readonly kind: 'pcb' | 'smt'
185
+ readonly boardPath: string
186
+ readonly schematicPath?: string
187
+ readonly roots?: readonly string[]
188
+ readonly sessionId?: string
189
+ readonly quantity?: number
190
+ readonly signal?: AbortSignal
191
+ /** Open the resulting page in the default browser; defaults to true. */
192
+ readonly launch?: boolean
193
+ }
194
+
195
+ export interface PlaceOrderResult {
196
+ readonly kind: 'pcb' | 'smt'
197
+ /** The exact URL KiCad's own action loads into its order webview. */
198
+ readonly orderUrl: string
199
+ /** The backend's raw URL, before KiCad's own query parameters were added. */
200
+ readonly responseUrl: string
201
+ /** True when the host handed `orderUrl` to the OS default browser. */
202
+ readonly launched: boolean
203
+ readonly launcher?: string
204
+ readonly status: 'launched' | 'ready'
205
+ readonly message: string
206
+ readonly endpoint: string
207
+ readonly facts: BoardFacts
208
+ readonly archive: OrderPackageSummary
209
+ readonly assembly?: FabricationResult['assembly']
210
+ }
211
+
80
212
  export interface HardwareArtifactsOptions {
81
213
  readonly kicadRoot?: string
82
214
  readonly solidcraftRoot?: string
215
+ /** Origin for the place-order endpoints; defaults to the Huaqiu host. */
216
+ readonly orderBaseUrl?: string
217
+ readonly orderPageBase?: string
218
+ /** Huaqiu access token; only ever sent to the order endpoint. */
219
+ readonly accessToken?: string
220
+ /**
221
+ * Resolves the signed-in Huaqiu token when no explicit token is configured.
222
+ *
223
+ * hqpcb is a Huaqiu business, so the login that feeds the eda.cn API is also
224
+ * the token the order page expects — there is no second credential.
225
+ */
226
+ readonly authToken?: () => Promise<string | null>
227
+ /** Injectable transport for tests; defaults to global fetch. */
228
+ readonly postOrder?: (url: string, init: {
229
+ readonly body: Buffer
230
+ readonly contentType: string
231
+ readonly headers?: Readonly<Record<string, string>>
232
+ readonly signal?: AbortSignal
233
+ }) => Promise<{ readonly status: number; readonly text: string }>
234
+ /**
235
+ * Live accessor for the user-configured roots.
236
+ *
237
+ * The plugin passes the profile config reference, so a settings write that
238
+ * replaces a volatile field is visible on the next validation without the
239
+ * service caching a start-time snapshot.
240
+ */
241
+ readonly settings?: () => {
242
+ readonly kicadRoot?: string
243
+ readonly solidcraftRoot?: string
244
+ readonly orderBaseUrl?: string
245
+ readonly accessToken?: string
246
+ }
83
247
  readonly probeVersion?: (executable: string) => string | undefined
84
248
  readonly spawnProcess?: (
85
249
  command: string,
86
250
  args: readonly string[],
87
251
  options: { cwd: string; detached: boolean; stdio: 'ignore'; windowsHide: boolean; shell: false },
88
252
  ) => Pick<ChildProcess, 'pid'>
253
+ /**
254
+ * Command used to hand a URL to the OS. Defaults to `open` on macOS,
255
+ * `rundll32 url.dll,FileProtocolHandler` on Windows and `xdg-open` elsewhere.
256
+ */
257
+ readonly openExternal?: (url: string) => { readonly command: string; readonly args: readonly string[] }
258
+ /** Runs one short-lived CLI command and returns its exit facts. */
259
+ readonly runCommand?: (
260
+ command: string,
261
+ args: readonly string[],
262
+ options: { cwd: string; timeoutMs: number; signal?: AbortSignal },
263
+ ) => Promise<{ exitCode: number | null; stdout: string; stderr: string; timedOut: boolean }>
264
+ /** Cache directory for derived outputs; defaults to a temp subdirectory. */
265
+ readonly cacheRoot?: string
266
+ readonly glbTimeoutMs?: number
267
+ /** Source text limit; protects the host from pathological files. */
268
+ readonly maxSourceBytes?: number
89
269
  }
90
270
 
91
271
  interface ProjectManifest {
@@ -100,7 +280,13 @@ const EXCLUDED_DIRS = new Set([
100
280
  'archive', 'archives', 'backup', 'backups', 'export', 'exports',
101
281
  ])
102
282
  const MECHANICAL_EXTENSIONS = new Set(['.step', '.stp', '.glb'])
283
+ const SOURCE_EXTENSIONS: Readonly<Record<string, 'schematic' | 'pcb'>> = {
284
+ '.kicad_sch': 'schematic',
285
+ '.kicad_pcb': 'pcb',
286
+ }
103
287
  const MAX_DEPTH = 5
288
+ /** KiCad writes each child sheet as `(property "Sheetfile" "child.kicad_sch")`. */
289
+ const SHEET_FILE_PATTERN = /\(property\s+"Sheetfile"\s+"((?:[^"\\]|\\.)*)"/gu
104
290
 
105
291
  function canonical(path: string): string {
106
292
  return resolve(path)
@@ -115,6 +301,146 @@ function isExcluded(name: string): boolean {
115
301
  return EXCLUDED_DIRS.has(name.toLowerCase())
116
302
  }
117
303
 
304
+ function realOrUndefined(path: string): string | undefined {
305
+ try {
306
+ return realpathSync(path)
307
+ } catch {
308
+ return undefined
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Identity of one authorization scope. DSH sessions are the scope; an embed
314
+ * without sessions (tests, a bare host) shares the default entry.
315
+ */
316
+ function scopeKey(sessionId?: string): string {
317
+ return sessionId === undefined || sessionId === '' ? '' : sessionId
318
+ }
319
+
320
+ /**
321
+ * A caller-named root, read as "the workspace this artifact belongs to".
322
+ *
323
+ * Callers may name a project file by mistake (the project `.kicad_pro` is the
324
+ * path the panel holds), and a file path authorizes nothing: no artifact is
325
+ * inside another file's path. Resolving to the containing directory keeps the
326
+ * caller's intent without widening beyond it.
327
+ */
328
+ function rootOf(root: string): string {
329
+ const real = realOrUndefined(root) ?? canonical(root)
330
+ try {
331
+ return statSync(real).isDirectory() ? real : dirname(real)
332
+ } catch {
333
+ return real
334
+ }
335
+ }
336
+
337
+ /** Roots a discovery proved reachable: the workspace and every adopted project. */
338
+ function discoveredRoots(discovery: DiscoveryResult | undefined): string[] {
339
+ if (discovery === undefined) return []
340
+ const roots = new Set<string>([discovery.cwd])
341
+ for (const project of discovery.projects) roots.add(dirname(project.path))
342
+ return [...roots]
343
+ }
344
+
345
+ function errorWithCode(message: string, code: string, status: number): Error {
346
+ return Object.assign(new Error(message), { code, status })
347
+ }
348
+
349
+ /**
350
+ * POST one multipart order payload.
351
+ *
352
+ * Kept out of the class so tests can inject their own transport; the default
353
+ * has a hard timeout and never logs the body (it carries the access token).
354
+ */
355
+ async function defaultPostOrder(url: string, init: {
356
+ readonly body: Buffer
357
+ readonly contentType: string
358
+ readonly headers?: Readonly<Record<string, string>>
359
+ readonly signal?: AbortSignal
360
+ }): Promise<{ readonly status: number; readonly text: string }> {
361
+ const controller = new AbortController()
362
+ const timer = setTimeout(() => { controller.abort() }, 90_000)
363
+ const forward = (): void => { controller.abort() }
364
+ init.signal?.addEventListener('abort', forward, { once: true })
365
+ try {
366
+ const response = await fetch(url, {
367
+ method: 'POST',
368
+ headers: {
369
+ ...init.headers,
370
+ 'content-type': init.contentType,
371
+ 'content-length': String(init.body.byteLength),
372
+ },
373
+ // Node's fetch accepts a Buffer body; the DOM lib's BodyInit typing only
374
+ // names ArrayBuffer views backed by a non-shared buffer.
375
+ body: init.body as unknown as BodyInit,
376
+ signal: controller.signal,
377
+ })
378
+ return { status: response.status, text: await response.text() }
379
+ } finally {
380
+ clearTimeout(timer)
381
+ init.signal?.removeEventListener('abort', forward)
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Command that opens one URL in the OS default browser.
387
+ *
388
+ * A URL argument is passed to a fixed executable with `shell: false`, so the
389
+ * page can never become a shell command.
390
+ */
391
+ function defaultOpenExternal(url: string): { command: string; args: readonly string[] } {
392
+ if (process.platform === 'darwin') return { command: 'open', args: [url] }
393
+ if (process.platform === 'win32') return { command: 'rundll32', args: ['url.dll,FileProtocolHandler', url] }
394
+ return { command: 'xdg-open', args: [url] }
395
+ }
396
+
397
+ /**
398
+ * Validate an order page URL before handing it to the OS.
399
+ *
400
+ * The backend owns this URL, so the check is deliberately about *shape*, not
401
+ * about a specific host: HTTPS anywhere, plain HTTP only on loopback (local
402
+ * stubs), and never a URL with embedded credentials or a non-web scheme.
403
+ */
404
+ function externalUrlTarget(raw: string): string {
405
+ if (raw.length === 0 || raw.length > 4096) {
406
+ throw errorWithCode('the order URL is empty or too long', 'invalid-order-url', 400)
407
+ }
408
+ let parsed: URL
409
+ try {
410
+ parsed = new URL(raw)
411
+ } catch {
412
+ throw errorWithCode('the order URL is not a valid absolute URL', 'invalid-order-url', 400)
413
+ }
414
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
415
+ throw errorWithCode(`refusing to open a ${parsed.protocol} URL`, 'invalid-order-url', 400)
416
+ }
417
+ if (parsed.username !== '' || parsed.password !== '') {
418
+ throw errorWithCode('refusing to open a URL with embedded credentials', 'invalid-order-url', 400)
419
+ }
420
+ const host = parsed.hostname.replace(/^\[|\]$/gu, '')
421
+ const loopback = host === 'localhost' || host === '::1' || host === '127.0.0.1' || host.startsWith('127.')
422
+ if (parsed.protocol === 'http:' && !loopback) {
423
+ throw errorWithCode('refusing to open a plain-HTTP order URL outside loopback', 'invalid-order-url', 400)
424
+ }
425
+ return parsed.toString()
426
+ }
427
+
428
+ /** First backend-owned order URL in a place-order response. */
429
+ function orderUrlOf(body: unknown): string | undefined {
430
+ if (body === null || typeof body !== 'object') return undefined
431
+ const record = body as Record<string, unknown>
432
+ for (const key of ['url', 'redirect', 'data']) {
433
+ const value = record[key]
434
+ if (typeof value === 'string' && value !== '') return value
435
+ if (value !== null && typeof value === 'object') {
436
+ const nested = orderUrlOf(value)
437
+ if (nested !== undefined) return nested
438
+ }
439
+ }
440
+ const result = record.result
441
+ return result === undefined ? undefined : orderUrlOf(result)
442
+ }
443
+
118
444
  function walkFiles(root: string, predicate: (name: string) => boolean): string[] {
119
445
  const found: string[] = []
120
446
  const visit = (dir: string, depth: number): void => {
@@ -138,6 +464,26 @@ function walkFiles(root: string, predicate: (name: string) => boolean): string[]
138
464
  return found.sort()
139
465
  }
140
466
 
467
+ /** Child schematics declared by sheet references in one saved schematic. */
468
+ function childSheetFiles(path: string): string[] {
469
+ let text: string
470
+ try {
471
+ text = readFileSync(path, 'utf8')
472
+ } catch {
473
+ return []
474
+ }
475
+ const dir = dirname(path)
476
+ const children: string[] = []
477
+ for (const match of text.matchAll(SHEET_FILE_PATTERN)) {
478
+ const raw = match[1]
479
+ if (raw === undefined || raw === '') continue
480
+ const declared = raw.replace(/\\(["\\])/gu, '$1')
481
+ const target = isAbsolute(declared) ? canonical(declared) : resolve(dir, declared)
482
+ children.push(target)
483
+ }
484
+ return children.sort()
485
+ }
486
+
141
487
  function artifact(kind: ArtifactKind, path: string, projectPath?: string, sourcePath?: string): HardwareArtifact {
142
488
  const full = canonical(path)
143
489
  return {
@@ -164,6 +510,41 @@ function defaultVersionProbe(executable: string): string | undefined {
164
510
  }
165
511
  }
166
512
 
513
+ function defaultRunCommand(
514
+ command: string,
515
+ args: readonly string[],
516
+ options: { cwd: string; timeoutMs: number; signal?: AbortSignal },
517
+ ): Promise<{ exitCode: number | null; stdout: string; stderr: string; timedOut: boolean }> {
518
+ return new Promise((resolvePromise, reject) => {
519
+ execFile(command, [...args], {
520
+ cwd: options.cwd,
521
+ timeout: options.timeoutMs,
522
+ encoding: 'utf8',
523
+ windowsHide: true,
524
+ shell: false,
525
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
526
+ maxBuffer: 8 * 1024 * 1024,
527
+ }, (error, stdout, stderr) => {
528
+ if (error === null) {
529
+ resolvePromise({ exitCode: 0, stdout: String(stdout), stderr: String(stderr), timedOut: false })
530
+ return
531
+ }
532
+ const killed = (error as { killed?: boolean }).killed === true
533
+ const signal = (error as { signal?: string | null }).signal
534
+ if (killed || signal !== null && signal !== undefined) {
535
+ resolvePromise({ exitCode: null, stdout: String(stdout), stderr: String(stderr), timedOut: true })
536
+ return
537
+ }
538
+ const code = typeof (error as { code?: unknown }).code === 'number' ? Number((error as { code: number }).code) : null
539
+ if (code === null) {
540
+ reject(error)
541
+ return
542
+ }
543
+ resolvePromise({ exitCode: code, stdout: String(stdout), stderr: String(stderr), timedOut: false })
544
+ })
545
+ })
546
+ }
547
+
167
548
  function existing(paths: readonly string[]): string | undefined {
168
549
  return paths.find((candidate) => {
169
550
  try {
@@ -195,6 +576,15 @@ function kicadCandidates(root: string): { cli: string[]; kicad: string[]; eesche
195
576
  }
196
577
  }
197
578
 
579
+ /** Install root that owns one resolved `kicad-cli`, per layout convention. */
580
+ function installRootFromCli(cli: string): string {
581
+ const segments = cli.split(sep)
582
+ const macIndex = segments.indexOf('Contents')
583
+ if (macIndex > 0) return segments.slice(0, macIndex).join(sep) || sep
584
+ if (segments[segments.length - 2]?.toLowerCase() === 'bin') return segments.slice(0, -2).join(sep) || sep
585
+ return dirname(cli)
586
+ }
587
+
198
588
  function solidcraftCandidates(root: string): string[] {
199
589
  const exe = process.platform === 'win32' ? '.exe' : ''
200
590
  const app = basename(root).toLowerCase().endsWith('.app')
@@ -216,18 +606,62 @@ function solidcraftCandidates(root: string): string[] {
216
606
 
217
607
  /** Small, immutable host capability implementation. */
218
608
  export class HardwareArtifactService {
219
- private readonly options: Required<Pick<HardwareArtifactsOptions, 'spawnProcess' | 'probeVersion'>>
609
+ private readonly options: Required<Pick<
610
+ HardwareArtifactsOptions,
611
+ 'spawnProcess' | 'probeVersion' | 'runCommand' | 'openExternal'
612
+ >>
613
+ private readonly cacheRoot: string
614
+ private readonly glbTimeoutMs: number
615
+ private readonly maxSourceBytes: number
616
+ /**
617
+ * Last discovery per scope — one entry per DSH session, plus the unscoped
618
+ * default used by tests and non-DSH embeds.
619
+ *
620
+ * It is a map rather than one field on purpose: a single "most recent
621
+ * discovery" is shared by every open viewer, so switching to a session in
622
+ * another workspace silently revoked the authorization of the viewer that
623
+ * stayed open. Authorization must never depend on who asked last.
624
+ */
625
+ private readonly discoveries = new Map<string, DiscoveryResult>()
626
+ /** Completed GLB exports keyed by `sourcePath:revision`. */
627
+ private readonly glbCache = new Map<string, GlbResult>()
628
+ /** In-flight GLB exports keyed by the same key, so concurrent callers share one run. */
629
+ private readonly glbPending = new Map<string, Promise<GlbResult>>()
630
+ /** BOM projections keyed by `sourcePath:revision`. */
631
+ private readonly bomCache = new Map<string, BomResult>()
632
+ /** Prepared fabrication packages keyed by board, revision and schematic. */
633
+ private readonly packageCache = new Map<string, FabricationResult & {
634
+ readonly archiveData: Uint8Array
635
+ readonly assemblyFiles?: { readonly positions: string; readonly bom: string }
636
+ }>()
220
637
 
221
638
  constructor(private readonly config: HardwareArtifactsOptions = {}) {
222
639
  this.options = {
223
640
  probeVersion: config.probeVersion ?? defaultVersionProbe,
224
641
  spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
642
+ runCommand: config.runCommand ?? defaultRunCommand,
643
+ openExternal: config.openExternal ?? defaultOpenExternal,
644
+ }
645
+ this.cacheRoot = canonical(config.cacheRoot ?? join(tmpdir(), 'huaqiu-hardware-artifacts'))
646
+ this.glbTimeoutMs = config.glbTimeoutMs ?? 120_000
647
+ this.maxSourceBytes = config.maxSourceBytes ?? 32 * 1024 * 1024
648
+ }
649
+
650
+ /** Configured roots, read live so a settings write is visible immediately. */
651
+ private roots(): { kicadRoot?: string; solidcraftRoot?: string } {
652
+ const live = this.config.settings?.()
653
+ const kicadRoot = live?.kicadRoot ?? this.config.kicadRoot
654
+ const solidcraftRoot = live?.solidcraftRoot ?? this.config.solidcraftRoot
655
+ return {
656
+ ...(kicadRoot === undefined ? {} : { kicadRoot }),
657
+ ...(solidcraftRoot === undefined ? {} : { solidcraftRoot }),
225
658
  }
226
659
  }
227
660
 
228
661
  /** Resolve configured installations from validated absolute paths only. */
229
662
  installations(): Installations {
230
- const kicadRoot = this.config.kicadRoot ? canonical(this.config.kicadRoot) : undefined
663
+ const roots = this.roots()
664
+ const kicadRoot = roots.kicadRoot ? canonical(roots.kicadRoot) : undefined
231
665
  let kicadCli: string | undefined
232
666
  if (kicadRoot !== undefined) {
233
667
  const cliPaths = basename(kicadRoot).toLowerCase().startsWith('kicad-cli')
@@ -237,23 +671,26 @@ export class HardwareArtifactService {
237
671
  }
238
672
  const candidates = kicadRoot === undefined
239
673
  ? { cli: [], kicad: [], eeschema: [], pcbnew: [] }
240
- : kicadCandidates(kicadCli && basename(kicadCli).toLowerCase().startsWith('kicad-cli') ? dirname(dirname(dirname(kicadCli))) : kicadRoot)
674
+ : kicadCandidates(kicadCli === undefined ? kicadRoot : installRootFromCli(kicadCli))
241
675
  const pcbEditor = existing(candidates.pcbnew)
242
676
  const schematicEditor = existing(candidates.eeschema)
243
677
  const projectManager = existing(candidates.kicad)
678
+ const version = kicadCli === undefined ? undefined : this.options.probeVersion(kicadCli)
244
679
  const kicad: InstallationInfo = kicadCli === undefined
245
680
  ? { configured: false, error: 'KiCad installation is not configured' }
246
- : {
247
- configured: true,
248
- root: kicadRoot,
249
- cli: kicadCli,
250
- ...(projectManager === undefined ? {} : { projectManager }),
251
- ...(pcbEditor === undefined ? {} : { pcbEditor }),
252
- ...(schematicEditor === undefined ? {} : { schematicEditor }),
253
- ...(this.options.probeVersion(kicadCli) === undefined ? {} : { version: this.options.probeVersion(kicadCli) }),
254
- }
681
+ : version === undefined
682
+ ? { configured: false, root: kicadRoot, cli: kicadCli, error: `${kicadCli} did not answer a version probe` }
683
+ : {
684
+ configured: true,
685
+ root: kicadRoot,
686
+ cli: kicadCli,
687
+ version,
688
+ ...(projectManager === undefined ? {} : { projectManager }),
689
+ ...(pcbEditor === undefined ? {} : { pcbEditor }),
690
+ ...(schematicEditor === undefined ? {} : { schematicEditor }),
691
+ }
255
692
 
256
- const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : undefined
693
+ const solidRoot = roots.solidcraftRoot ? canonical(roots.solidcraftRoot) : undefined
257
694
  const solidExecutable = solidRoot === undefined ? undefined : existing(solidcraftCandidates(solidRoot))
258
695
  const solidcraft: InstallationInfo = solidExecutable === undefined
259
696
  ? { configured: false, error: 'SolidCraft installation is not configured' }
@@ -275,6 +712,10 @@ export class HardwareArtifactService {
275
712
  /** Compact agent context: validated paths only, no project inventory dump. */
276
713
  environmentText(current?: DiscoveryResult): string {
277
714
  const installed = this.installations()
715
+ // The prompt has no session of its own; speaking for the only scope that
716
+ // ever discovered is honest, and with several open workspaces it says
717
+ // nothing rather than naming another session's project.
718
+ const scope = current ?? this.soleDiscovery()
278
719
  const lines = ['<hardware_environment>']
279
720
  lines.push('KiCad:')
280
721
  lines.push(` configured: ${String(installed.kicad.configured)}`)
@@ -287,12 +728,12 @@ export class HardwareArtifactService {
287
728
  lines.push(` configured: ${String(installed.solidcraft.configured)}`)
288
729
  if (installed.solidcraft.executable !== undefined) lines.push(` executable: ${installed.solidcraft.executable}`)
289
730
  if (installed.solidcraft.error !== undefined) lines.push(` error: ${installed.solidcraft.error}`)
290
- if (current?.selected !== undefined) {
731
+ if (scope?.selected !== undefined) {
291
732
  lines.push('Current project:')
292
- lines.push(` root: ${current.cwd}`)
293
- lines.push(` project: ${current.selected.path}`)
294
- if (current.selected.schematic !== undefined) lines.push(` schematic: ${current.selected.schematic.path}`)
295
- const board = current.selected.boards[0]
733
+ lines.push(` root: ${scope.cwd}`)
734
+ lines.push(` project: ${scope.selected.path}`)
735
+ if (scope.selected.schematic !== undefined) lines.push(` schematic: ${scope.selected.schematic.path}`)
736
+ const board = scope.selected.boards[0]
296
737
  if (board !== undefined) lines.push(` selected_pcb: ${board.path}`)
297
738
  }
298
739
  lines.push('</hardware_environment>')
@@ -303,8 +744,13 @@ export class HardwareArtifactService {
303
744
  * Deterministic discovery. An explicit project or manifest wins; otherwise
304
745
  * exactly one `.kicad_pro` may be selected automatically. Ambiguity is
305
746
  * returned as a selection requirement, never resolved by taking the first.
747
+ *
748
+ * @param cwdInput - workspace directory to walk.
749
+ * @param explicitProject - project chosen by the user, absolute or cwd-relative.
750
+ * @param sessionId - DSH session the discovery belongs to. Recording it per
751
+ * session is what keeps one open viewer from revoking another's roots.
306
752
  */
307
- discover(cwdInput: string, explicitProject?: string): DiscoveryResult {
753
+ discover(cwdInput: string, explicitProject?: string, sessionId?: string): DiscoveryResult {
308
754
  const cwd = canonical(cwdInput)
309
755
  const manifestPath = join(cwd, '.hardware-engineering.json')
310
756
  let manifest: ProjectManifest | undefined
@@ -312,7 +758,12 @@ export class HardwareArtifactService {
312
758
  try {
313
759
  manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as ProjectManifest
314
760
  } catch (error) {
315
- return { cwd, manifestPath, projects: [], issue: { code: 'bad-manifest', message: `invalid .hardware-engineering.json: ${String(error)}` } }
761
+ return this.remember({
762
+ cwd,
763
+ manifestPath,
764
+ projects: [],
765
+ issue: { code: 'bad-manifest', message: `invalid .hardware-engineering.json: ${String(error)}` },
766
+ }, sessionId)
316
767
  }
317
768
  }
318
769
 
@@ -320,7 +771,12 @@ export class HardwareArtifactService {
320
771
  if (explicitProject !== undefined && explicitProject.trim() !== '') {
321
772
  const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject)
322
773
  if (!existsSync(requested)) {
323
- return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects: [], issue: { code: 'missing-project', message: `${requested} does not exist` } }
774
+ return this.remember({
775
+ cwd,
776
+ ...(manifest === undefined ? {} : { manifestPath }),
777
+ projects: [],
778
+ issue: { code: 'missing-project', message: `${requested} does not exist` },
779
+ }, sessionId)
324
780
  }
325
781
  projectPaths.add(requested)
326
782
  } else if (manifest?.project !== undefined && manifest.project.trim() !== '') {
@@ -331,13 +787,23 @@ export class HardwareArtifactService {
331
787
 
332
788
  const projects: HardwareProject[] = [...projectPaths].sort().map(path => this.projectFrom(path, cwd, manifest))
333
789
  if (projects.length === 0) {
334
- return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'no-project', message: `no .kicad_pro found under ${cwd}` } }
790
+ return this.remember({
791
+ cwd,
792
+ ...(manifest === undefined ? {} : { manifestPath }),
793
+ projects,
794
+ issue: { code: 'no-project', message: `no .kicad_pro found under ${cwd}` },
795
+ }, sessionId)
335
796
  }
336
797
  if (projects.length > 1) {
337
- return { cwd, ...(manifest === undefined ? {} : { manifestPath }), projects, issue: { code: 'selection-required', message: `${projects.length} projects found; select one explicitly` } }
798
+ return this.remember({
799
+ cwd,
800
+ ...(manifest === undefined ? {} : { manifestPath }),
801
+ projects,
802
+ issue: { code: 'selection-required', message: `${projects.length} projects found; select one explicitly` },
803
+ }, sessionId)
338
804
  }
339
805
  const selected = projects[0] as HardwareProject
340
- return {
806
+ return this.remember({
341
807
  cwd,
342
808
  ...(manifest === undefined ? {} : { manifestPath }),
343
809
  projects,
@@ -345,7 +811,23 @@ export class HardwareArtifactService {
345
811
  ...(selected.selectionRequired
346
812
  ? { issue: { code: 'selection-required', message: 'select an artifact explicitly' } }
347
813
  : {}),
348
- }
814
+ }, sessionId)
815
+ }
816
+
817
+ /** Last discovery for one scope, never another session's. */
818
+ discovery(sessionId?: string): DiscoveryResult | undefined {
819
+ return this.discoveries.get(scopeKey(sessionId))
820
+ }
821
+
822
+ /** The only discovery the host can speak for without being told a session. */
823
+ private soleDiscovery(): DiscoveryResult | undefined {
824
+ if (this.discoveries.size !== 1) return undefined
825
+ return [...this.discoveries.values()][0]
826
+ }
827
+
828
+ private remember(result: DiscoveryResult, sessionId?: string): DiscoveryResult {
829
+ this.discoveries.set(scopeKey(sessionId), result)
830
+ return result
349
831
  }
350
832
 
351
833
  private projectFrom(projectPath: string, cwd: string, manifest?: ProjectManifest): HardwareProject {
@@ -354,38 +836,78 @@ export class HardwareArtifactService {
354
836
  const resolvePath = (value: string): string =>
355
837
  isAbsolute(value) ? canonical(value) : resolve(dir, value)
356
838
 
357
- const schematicPath = manifest?.schematic !== undefined
358
- ? resolvePath(manifest.schematic)
359
- : existing([join(dir, `${name}.kicad_sch`), ...walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_sch'))])
360
- const boards = manifest?.boards !== undefined
361
- ? manifest.boards.map(board => artifact('pcb', resolvePath(board.path), projectPath))
362
- : walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_pcb')).map(path => artifact('pcb', path, projectPath))
839
+ // The root schematic is authoritative: an explicit manifest entry, then the
840
+ // project-named file, then a single unambiguous candidate. Unrelated
841
+ // sibling `.kicad_sch` files are never promoted to sheets.
842
+ const explicitSchematic = manifest?.schematic === undefined ? undefined : resolvePath(manifest.schematic)
843
+ let schematicPath = explicitSchematic !== undefined && existsSync(explicitSchematic) ? explicitSchematic : undefined
844
+ if (schematicPath === undefined) {
845
+ const named = join(dir, `${name}.kicad_sch`)
846
+ if (existsSync(named)) schematicPath = named
847
+ else {
848
+ const candidates = readdirSync(dir, { withFileTypes: true })
849
+ .filter(entry => entry.isFile() && entry.name.toLowerCase().endsWith('.kicad_sch'))
850
+ .map(entry => join(dir, entry.name))
851
+ .sort()
852
+ if (candidates.length === 1) schematicPath = candidates[0]
853
+ }
854
+ }
855
+
856
+ // Hierarchy comes from sheet references only, resolved recursively with a
857
+ // cycle guard: parsing the root must never advertise unrelated files.
858
+ const sheets: HardwareArtifact[] = []
859
+ if (schematicPath !== undefined) {
860
+ const visited = new Set<string>([canonical(schematicPath)])
861
+ const queue = childSheetFiles(canonical(schematicPath))
862
+ while (queue.length > 0) {
863
+ const next = queue.shift() as string
864
+ const canonicalNext = canonical(next)
865
+ if (visited.has(canonicalNext)) continue
866
+ visited.add(canonicalNext)
867
+ if (!existsSync(canonicalNext) || extname(canonicalNext).toLowerCase() !== '.kicad_sch') continue
868
+ sheets.push(artifact('schematic', canonicalNext, projectPath, canonical(schematicPath)))
869
+ queue.push(...childSheetFiles(canonicalNext))
870
+ }
871
+ }
872
+
873
+ // Board ranking: manifest ownership first, then the project-named board, then
874
+ // the only candidate. Multiple unowned boards stay ambiguous on purpose.
875
+ const manifestBoards = manifest?.boards === undefined
876
+ ? []
877
+ : manifest.boards
878
+ .filter(entry => existsSync(resolvePath(entry.path)))
879
+ .map(entry => artifact('pcb', resolvePath(entry.path), projectPath))
880
+ const scannedBoards = walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_pcb'))
881
+ .map(path => artifact('pcb', path, projectPath))
882
+ const boards = manifestBoards.length > 0
883
+ ? manifestBoards
884
+ : [...scannedBoards].sort((left, right) => boardRank(left, right, name))
885
+ const owned = boards.find(board => basename(board.path, '.kicad_pcb') === name) ?? boards[0]
886
+ const ownershipAmbiguous = manifestBoards.length === 0 && boards.length > 1
887
+ && basename(owned?.path ?? '', '.kicad_pcb') !== name
888
+
363
889
  const mechanical = manifest?.mechanical !== undefined
364
890
  ? manifest.mechanical.map(model => artifact('mechanical-3d', resolvePath(model.path), projectPath))
365
891
  : walkFiles(dir, file => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase()))
366
892
  .map(path => artifact('mechanical-3d', path, projectPath))
367
- const sheets = schematicPath === undefined
368
- ? []
369
- : walkFiles(dir, file => file.toLowerCase().endsWith('.kicad_sch'))
370
- .filter(path => path !== schematicPath && isInside(path, dir))
371
- .map(path => artifact('schematic', path, projectPath, schematicPath))
372
893
 
373
894
  const sourceSchematic = schematicPath === undefined ? undefined : artifact('schematic', schematicPath, projectPath)
374
- const sourceBoard = boards[0]
895
+ const sourceBoard = ownershipAmbiguous ? undefined : owned
375
896
  return {
376
897
  path: projectPath,
377
898
  name,
378
- ...(sourceSchematic === undefined ? {} : { schematic: sourceSchematic }),
899
+ ...(sourceSchematic === undefined ? {} : { rootSheet: sourceSchematic, schematic: sourceSchematic }),
379
900
  ...(sourceSchematic === undefined ? {} : {
380
901
  bom: { ...artifact('bom', sourceSchematic.path, projectPath, sourceSchematic.path), title: `BOM — ${sourceSchematic.title}` },
381
902
  }),
382
903
  ...(sourceBoard === undefined ? {} : {
383
904
  pcb3d: { ...artifact('pcb-3d', sourceBoard.path, projectPath, sourceBoard.path), title: `3D — ${sourceBoard.title}` },
905
+ defaultBoard: sourceBoard.path,
384
906
  }),
385
907
  sheets,
386
908
  boards,
387
909
  mechanical,
388
- selectionRequired: boards.length > 1 || sheets.length > 1,
910
+ selectionRequired: boards.length > 1 && ownershipAmbiguous,
389
911
  }
390
912
  }
391
913
 
@@ -393,31 +915,737 @@ export class HardwareArtifactService {
393
915
  open(request: OpenArtifactRequest): OpenArtifactResult {
394
916
  const path = canonical(request.artifactPath)
395
917
  if (!existsSync(path)) {
396
- throw Object.assign(new Error(`artifact does not exist: ${path}`), { code: 'missing-artifact', status: 404 })
918
+ throw errorWithCode(`artifact does not exist: ${path}`, 'missing-artifact', 404)
397
919
  }
398
920
  const installed = this.installations()
399
- const isKicad = request.application === 'kicad'
921
+ const ext = extname(path).toLowerCase()
400
922
  let command: string | undefined
401
- if (isKicad) {
402
- const ext = extname(path).toLowerCase()
403
- if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
404
- else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
405
- else if (ext === '.kicad_pro') command = installed.kicad.projectManager
406
- else throw Object.assign(new Error(`unsupported KiCad artifact: ${ext}`), { code: 'unsupported-artifact', status: 415 })
407
- if (command === undefined) {
408
- throw Object.assign(new Error('the configured KiCad installation has no editor for this artifact'), { code: 'missing-executable', status: 412 })
923
+ if (ext === '.kicad_sch') command = installed.kicad.schematicEditor
924
+ else if (ext === '.kicad_pcb') command = installed.kicad.pcbEditor
925
+ else if (ext === '.kicad_pro') command = installed.kicad.projectManager
926
+ else throw errorWithCode(`unsupported KiCad artifact: ${ext}`, 'unsupported-artifact', 415)
927
+ if (command === undefined) {
928
+ throw errorWithCode('the configured KiCad installation has no editor for this artifact', 'missing-executable', 412)
929
+ }
930
+ const settings = { cwd: dirname(path), detached: true, stdio: 'ignore' as const, windowsHide: true, shell: false as const }
931
+ const child = this.options.spawnProcess(command, [path], settings)
932
+ return { launched: true, command, args: [path], cwd: settings.cwd, ...(child.pid === undefined ? {} : { pid: child.pid }) }
933
+ }
934
+
935
+ /**
936
+ * Workspace roots a read may target: what this scope discovered, plus what
937
+ * the caller named.
938
+ *
939
+ * Additive on purpose. The previous shape unioned the caller's roots with one
940
+ * process-wide "last discovery", so any other session's discovery — a
941
+ * workspace switch is exactly that — replaced the root the open viewer was
942
+ * authorized by, and its next read failed with "artifact is outside the
943
+ * authorized workspace". Roots now only ever accumulate within their scope.
944
+ */
945
+ private authorizedRoots(roots?: readonly string[], sessionId?: string): string[] {
946
+ const candidates = new Set<string>()
947
+ for (const root of discoveredRoots(this.discovery(sessionId))) candidates.add(canonical(root))
948
+ for (const root of roots ?? []) {
949
+ if (root === undefined || root.trim() === '') continue
950
+ candidates.add(rootOf(root))
951
+ }
952
+ return [...candidates]
953
+ }
954
+
955
+ /**
956
+ * Authorize one artifact path: canonical, realpath-checked, inside a
957
+ * workspace root, and of an expected type. A browser request cannot turn
958
+ * this into an arbitrary filesystem read, even from loopback.
959
+ */
960
+ private authorize(
961
+ artifactPath: string,
962
+ roots: readonly string[] | undefined,
963
+ sessionId?: string,
964
+ ): { path: string; kind: 'schematic' | 'pcb' } {
965
+ if (!isAbsolute(artifactPath)) {
966
+ throw errorWithCode('artifact identity must be an absolute path', 'invalid-identity', 400)
967
+ }
968
+ const requested = canonical(artifactPath)
969
+ const kind = SOURCE_EXTENSIONS[extname(requested).toLowerCase()]
970
+ if (kind === undefined) {
971
+ throw errorWithCode(`unsupported artifact type: ${extname(requested)}`, 'unsupported-artifact', 415)
972
+ }
973
+ const authorized = this.authorizedRoots(roots, sessionId)
974
+ if (authorized.length === 0) {
975
+ throw errorWithCode('no authorized workspace is known to the host', 'unauthorized', 403)
976
+ }
977
+ // Boundary check before existence: a path outside the workspace is refused
978
+ // whether or not it exists, so the route cannot probe the filesystem.
979
+ const permittedLexically = authorized.some((root) => isInside(requested, canonical(root)))
980
+ if (!permittedLexically) {
981
+ throw errorWithCode('artifact is outside the authorized workspace', 'unauthorized', 403)
982
+ }
983
+ if (!existsSync(requested)) {
984
+ throw errorWithCode(`artifact does not exist: ${requested}`, 'missing-artifact', 404)
985
+ }
986
+ const real = realOrUndefined(requested)
987
+ if (real === undefined) {
988
+ throw errorWithCode(`artifact cannot be resolved: ${requested}`, 'invalid-identity', 400)
989
+ }
990
+ const permitted = authorized.some((root) => {
991
+ const realRoot = realOrUndefined(root) ?? root
992
+ return isInside(real, realRoot)
993
+ })
994
+ if (!permitted) {
995
+ throw errorWithCode('artifact is outside the authorized workspace', 'unauthorized', 403)
996
+ }
997
+ const info = statSync(real)
998
+ if (!info.isFile()) {
999
+ throw errorWithCode(`artifact is not a regular file: ${requested}`, 'invalid-identity', 400)
1000
+ }
1001
+ if ((SOURCE_EXTENSIONS[extname(real).toLowerCase()]) === undefined) {
1002
+ throw errorWithCode('artifact type changed during resolution', 'unsupported-artifact', 415)
1003
+ }
1004
+ return { path: real, kind: SOURCE_EXTENSIONS[extname(real).toLowerCase()] as 'schematic' | 'pcb' }
1005
+ }
1006
+
1007
+ /** Saved source text plus a content-addressed revision. */
1008
+ async readSource(request: SourceRequest): Promise<SourceResult> {
1009
+ const { path, kind } = this.authorize(request.artifactPath, request.roots, request.sessionId)
1010
+ const info = statSync(path)
1011
+ if (info.size > this.maxSourceBytes) {
1012
+ throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, 'too-large', 413)
1013
+ }
1014
+ const body = await readFile(path)
1015
+ const revision = createHash('sha256').update(body).digest('hex')
1016
+ if (request.expectedRevision !== undefined && request.expectedRevision !== ''
1017
+ && request.expectedRevision !== revision) {
1018
+ throw errorWithCode(
1019
+ `source changed since it was selected (expected ${request.expectedRevision}, found ${revision})`,
1020
+ 'stale-revision',
1021
+ 409,
1022
+ )
1023
+ }
1024
+ return {
1025
+ path,
1026
+ kind,
1027
+ revision,
1028
+ bytes: body.byteLength,
1029
+ mtimeMs: info.mtimeMs,
1030
+ text: body.toString('utf8'),
1031
+ }
1032
+ }
1033
+
1034
+ private sourceRevision(path: string): string {
1035
+ const info = statSync(path)
1036
+ if (info.size > this.maxSourceBytes) {
1037
+ throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, 'too-large', 413)
1038
+ }
1039
+ return createHash('sha256').update(readFileSync(path)).digest('hex')
1040
+ }
1041
+
1042
+ /** Cache directory for one board's derived outputs. */
1043
+ private glbDirectory(boardPath: string): string {
1044
+ const digest = createHash('sha256').update(boardPath).digest('hex').slice(0, 16)
1045
+ return join(this.cacheRoot, 'glb', digest)
1046
+ }
1047
+
1048
+ /**
1049
+ * Generate (or reuse) the GLB for one board.
1050
+ *
1051
+ * - cache key includes the source content hash, so same-size/same-mtime edits invalidate
1052
+ * - one in-flight export is shared by concurrent callers for the same revision
1053
+ * - output is written to a temp file and renamed only after it validates
1054
+ * - a timeout or abort leaves no partial file behind
1055
+ */
1056
+ async exportGlb(request: GlbRequest): Promise<GlbResult> {
1057
+ const { path } = this.authorize(request.artifactPath, request.roots, request.sessionId)
1058
+ if (extname(path).toLowerCase() !== '.kicad_pcb') {
1059
+ throw errorWithCode('GLB export requires a .kicad_pcb artifact', 'unsupported-artifact', 415)
1060
+ }
1061
+ const installed = this.installations()
1062
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
1063
+ throw errorWithCode(
1064
+ installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli',
1065
+ 'not-configured',
1066
+ 412,
1067
+ )
1068
+ }
1069
+ const cli = installed.kicad.cli
1070
+ const revision = this.sourceRevision(path)
1071
+ const key = `${path}:${revision}`
1072
+ const cached = this.glbCache.get(key)
1073
+ if (cached !== undefined && existsSync(cached.file)) {
1074
+ const info = statSync(cached.file)
1075
+ return { ...cached, bytes: info.size, cached: true }
1076
+ }
1077
+ const pending = this.glbPending.get(key)
1078
+ if (pending !== undefined) return pending
1079
+
1080
+ const directory = this.glbDirectory(path)
1081
+ const target = join(directory, `board-${revision.slice(0, 16)}.glb`)
1082
+ const running = (async (): Promise<GlbResult> => {
1083
+ mkdirSync(directory, { recursive: true })
1084
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
1085
+ mkdirSync(tempDirectory, { recursive: true })
1086
+ const tempFile = join(tempDirectory, 'board.glb')
1087
+ try {
1088
+ const result = await this.options.runCommand(
1089
+ cli,
1090
+ ['pcb', 'export', 'glb', '--output', tempFile, path],
1091
+ { cwd: dirname(path), timeoutMs: this.glbTimeoutMs, ...(request.signal === undefined ? {} : { signal: request.signal }) },
1092
+ )
1093
+ if (result.timedOut) {
1094
+ throw errorWithCode(`kicad-cli pcb export glb timed out after ${this.glbTimeoutMs} ms`, 'export-timeout', 504)
1095
+ }
1096
+ if (result.exitCode !== 0) {
1097
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
1098
+ throw errorWithCode(`kicad-cli pcb export glb failed: ${detail}`, 'export-failed', 502)
1099
+ }
1100
+ if (!existsSync(tempFile)) {
1101
+ throw errorWithCode('kicad-cli pcb export glb produced no output', 'export-failed', 502)
1102
+ }
1103
+ const bytes = statSync(tempFile).size
1104
+ if (bytes === 0 || readFileSync(tempFile).subarray(0, 4).toString('ascii') !== 'glTF') {
1105
+ throw errorWithCode('kicad-cli wrote an invalid GLB', 'export-failed', 502)
1106
+ }
1107
+ renameSync(tempFile, target)
1108
+ const generated = {
1109
+ path,
1110
+ revision,
1111
+ bytes,
1112
+ generatedAt: new Date().toISOString(),
1113
+ cached: false,
1114
+ file: target,
1115
+ } satisfies GlbResult
1116
+ this.glbCache.set(key, generated)
1117
+ return generated
1118
+ } finally {
1119
+ rmSync(tempDirectory, { recursive: true, force: true })
1120
+ }
1121
+ })()
1122
+
1123
+ this.glbPending.set(key, running)
1124
+ try {
1125
+ return await running
1126
+ } finally {
1127
+ this.glbPending.delete(key)
1128
+ }
1129
+ }
1130
+
1131
+ /**
1132
+ * Grouped BOM for one saved root schematic.
1133
+ *
1134
+ * Reuses KiCad's own BOM extraction (`kicad-cli sch export bom`), the same
1135
+ * authoritative source `analyze_kicad_module` consumes, rather than building a
1136
+ * second component analyser. Grouping key is every non-reference column, so
1137
+ * different MPNs never merge and DNP stays explicit.
1138
+ */
1139
+ async exportBom(request: {
1140
+ readonly artifactPath: string
1141
+ readonly roots?: readonly string[]
1142
+ readonly sessionId?: string
1143
+ readonly signal?: AbortSignal
1144
+ }): Promise<BomResult> {
1145
+ const { path, kind } = this.authorize(request.artifactPath, request.roots, request.sessionId)
1146
+ if (kind !== 'schematic') {
1147
+ throw errorWithCode('BOM export requires a .kicad_sch artifact', 'unsupported-artifact', 415)
1148
+ }
1149
+ const installed = this.installations()
1150
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
1151
+ throw errorWithCode(installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli', 'not-configured', 412)
1152
+ }
1153
+ const revision = this.sourceRevision(path)
1154
+ const key = `${path}:${revision}`
1155
+ const cached = this.bomCache.get(key)
1156
+ if (cached !== undefined) return { ...cached, cached: true }
1157
+
1158
+ const directory = join(this.cacheRoot, 'bom', createHash('sha256').update(path).digest('hex').slice(0, 16))
1159
+ const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
1160
+ mkdirSync(tempDirectory, { recursive: true })
1161
+ const tempFile = join(tempDirectory, 'bom.csv')
1162
+ try {
1163
+ const result = await this.options.runCommand(
1164
+ installed.kicad.cli,
1165
+ ['sch', 'export', 'bom', '--output', tempFile, path],
1166
+ { cwd: dirname(path), timeoutMs: 60_000, ...(request.signal === undefined ? {} : { signal: request.signal }) },
1167
+ )
1168
+ if (result.timedOut) throw errorWithCode('kicad-cli sch export bom timed out', 'export-timeout', 504)
1169
+ if (result.exitCode !== 0) {
1170
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
1171
+ throw errorWithCode(`kicad-cli sch export bom failed: ${detail}`, 'export-failed', 502)
1172
+ }
1173
+ if (!existsSync(tempFile)) throw errorWithCode('kicad-cli produced no BOM output', 'export-failed', 502)
1174
+ const rows = groupBomRows(parseCsv(readFileSync(tempFile, 'utf8')))
1175
+ const generated: BomResult = {
1176
+ path,
1177
+ revision,
1178
+ generatedAt: new Date().toISOString(),
1179
+ cached: false,
1180
+ rows,
1181
+ source: 'kicad-cli-bom',
1182
+ }
1183
+ this.bomCache.set(key, generated)
1184
+ return generated
1185
+ } finally {
1186
+ rmSync(tempDirectory, { recursive: true, force: true })
1187
+ }
1188
+ }
1189
+
1190
+ // -------------------------------------------------------------------------
1191
+ // Fabrication packaging and order submission
1192
+ // -------------------------------------------------------------------------
1193
+
1194
+ /** Live order settings, read at call time so a settings write is immediate. */
1195
+ private orderSettings(): { baseUrl: string; pageBase: string; accessToken?: string } {
1196
+ const live = this.config.settings?.()
1197
+ const configured = [live?.orderBaseUrl, this.config.orderBaseUrl, process.env.HUAQIU_ORDER_BASE_URL]
1198
+ .find(value => value !== undefined && value.trim() !== '')
1199
+ const baseUrl = (configured ?? DEFAULT_ORDER_BASE_URL).replace(/\/+$/u, '')
1200
+ const pageBase = (this.config.orderPageBase ?? DEFAULT_ORDER_PAGE_BASE).replace(/\/+$/u, '')
1201
+ const token = live?.accessToken ?? this.config.accessToken ?? process.env.HUAQIU_ACCESS_TOKEN
1202
+ return {
1203
+ baseUrl,
1204
+ pageBase,
1205
+ ...(token === undefined || token.trim() === '' ? {} : { accessToken: token.trim() }),
1206
+ }
1207
+ }
1208
+
1209
+ /** What the Order destination may do right now, without contacting anything. */
1210
+ async orderConfig(): Promise<OrderConfigInfo> {
1211
+ const installed = this.installations()
1212
+ const settings = this.orderSettings()
1213
+ return {
1214
+ configured: installed.kicad.configured,
1215
+ baseUrl: settings.baseUrl,
1216
+ hasToken: (await this.orderToken()) !== undefined,
1217
+ provider: 'huaqiu',
1218
+ }
1219
+ }
1220
+
1221
+ /**
1222
+ * The token the order page must carry.
1223
+ *
1224
+ * An explicitly configured token wins (it makes a scripted run possible);
1225
+ * otherwise the signed-in Huaqiu session is used, which is the same token the
1226
+ * eda.cn API accepts. Absent both, ordering is refused before anything is
1227
+ * uploaded — the page would render signed out otherwise.
1228
+ */
1229
+ private async orderToken(): Promise<string | undefined> {
1230
+ const settings = this.orderSettings()
1231
+ if (settings.accessToken !== undefined) return settings.accessToken
1232
+ if (this.config.authToken === undefined) return undefined
1233
+ try {
1234
+ const token = await this.config.authToken()
1235
+ return token === null || token.trim() === '' ? undefined : token.trim()
1236
+ } catch {
1237
+ return undefined
1238
+ }
1239
+ }
1240
+
1241
+ /**
1242
+ * Build the fabrication archive and the assembly inputs for one board.
1243
+ *
1244
+ * The gerber/drill export is `kicad-cli`'s own plotter, so the archive is the
1245
+ * same set of files a KiCad "Place order" would upload. Cached by source
1246
+ * revision: reopening the panel must not re-run the exporter.
1247
+ */
1248
+ async fabricate(request: {
1249
+ readonly boardPath: string
1250
+ readonly schematicPath?: string
1251
+ readonly roots?: readonly string[]
1252
+ readonly sessionId?: string
1253
+ readonly signal?: AbortSignal
1254
+ }): Promise<FabricationResult & { readonly archiveData: Uint8Array; readonly assemblyFiles?: {
1255
+ readonly positions: string
1256
+ readonly bom: string
1257
+ } }> {
1258
+ const { path } = this.authorize(request.boardPath, request.roots, request.sessionId)
1259
+ if (extname(path).toLowerCase() !== '.kicad_pcb') {
1260
+ throw errorWithCode('Fabrication packaging requires a .kicad_pcb artifact', 'unsupported-artifact', 415)
1261
+ }
1262
+ const installed = this.installations()
1263
+ if (!installed.kicad.configured || installed.kicad.cli === undefined) {
1264
+ throw errorWithCode(installed.kicad.error ?? 'the configured KiCad installation has no kicad-cli', 'not-configured', 412)
1265
+ }
1266
+ const cli = installed.kicad.cli
1267
+ const revision = this.sourceRevision(path)
1268
+ const schematicPath = request.schematicPath === undefined
1269
+ ? undefined
1270
+ : this.authorize(request.schematicPath, request.roots, request.sessionId).path
1271
+ const key = `${path}:${revision}:${schematicPath ?? ''}`
1272
+ const cached = this.packageCache.get(key)
1273
+ if (cached !== undefined) return cached
1274
+
1275
+ const directory = join(this.cacheRoot, 'fabrication', createHash('sha256').update(path).digest('hex').slice(0, 16))
1276
+ const work = join(directory, `tmp-${process.pid}-${String(Date.now())}`)
1277
+ const plots = join(work, 'plots')
1278
+ const positionsFile = join(work, 'positions.raw.csv')
1279
+ mkdirSync(plots, { recursive: true })
1280
+
1281
+ const signal = request.signal
1282
+ const run = async (args: readonly string[], what: string, timeoutMs = 120_000): Promise<void> => {
1283
+ const result = await this.options.runCommand(cli, args, {
1284
+ cwd: dirname(path),
1285
+ timeoutMs,
1286
+ ...(signal === undefined ? {} : { signal }),
1287
+ })
1288
+ if (result.timedOut) throw errorWithCode(`kicad-cli ${what} timed out`, 'export-timeout', 504)
1289
+ if (result.exitCode !== 0) {
1290
+ const detail = (result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)
1291
+ throw errorWithCode(`kicad-cli ${what} failed: ${detail}`, 'export-failed', 502)
1292
+ }
1293
+ }
1294
+
1295
+ try {
1296
+ await run(['pcb', 'export', 'gerbers', '--output', plots, path], 'pcb export gerbers')
1297
+ await run(['pcb', 'export', 'drill', '--output', plots, '--format', 'excellon',
1298
+ '--excellon-units', 'mm', '--drill-origin', 'absolute', path], 'pcb export drill')
1299
+ const plotNames = readdirSync(plots).filter(name => statSync(join(plots, name)).isFile()).sort()
1300
+ if (plotNames.length === 0) throw errorWithCode('kicad-cli wrote no fabrication files', 'export-failed', 502)
1301
+ const plotted = readExportDirectory(plots, plotNames)
1302
+ const archiveData = zipPackage(plotted)
1303
+ const facts = readBoardFacts(readFileSync(path, 'utf8'))
1304
+
1305
+ let assembly: FabricationResult['assembly']
1306
+ let assemblyFiles: { positions: string; bom: string } | undefined
1307
+ if (schematicPath !== undefined) {
1308
+ await run(['pcb', 'export', 'pos', '--format', 'csv', '--units', 'mm', '--side', 'both',
1309
+ '--output', positionsFile, path], 'pcb export pos')
1310
+ const positions = parsePositions(readFileSync(positionsFile, 'utf8'))
1311
+ const bom = await this.exportBom({
1312
+ artifactPath: schematicPath,
1313
+ ...(request.roots === undefined ? {} : { roots: request.roots }),
1314
+ ...(signal === undefined ? {} : { signal }),
1315
+ })
1316
+ const bomRows = orderBomRows(positions, bom.rows)
1317
+ const positionsText = positionsCsv(positions)
1318
+ const bomText = orderBomCsv(bomRows)
1319
+ assemblyFiles = { positions: positionsText, bom: bomText }
1320
+ assembly = {
1321
+ positions: positions.length,
1322
+ bomLines: bomRows.length,
1323
+ positionsBytes: Buffer.byteLength(positionsText, 'utf8'),
1324
+ bomBytes: Buffer.byteLength(bomText, 'utf8'),
1325
+ }
1326
+ }
1327
+
1328
+ const result: FabricationResult & { archiveData: Uint8Array; assemblyFiles?: { positions: string; bom: string } } = {
1329
+ boardPath: path,
1330
+ revision,
1331
+ generatedAt: new Date().toISOString(),
1332
+ facts,
1333
+ archive: {
1334
+ zipName: `${packageName(path)}.zip`,
1335
+ zipBytes: archiveData.byteLength,
1336
+ files: plotted.map(file => ({ name: file.name, bytes: file.data.byteLength })),
1337
+ },
1338
+ archiveData,
1339
+ ...(assembly === undefined ? {} : { assembly }),
1340
+ ...(assemblyFiles === undefined ? {} : { assemblyFiles }),
409
1341
  }
1342
+ this.packageCache.set(key, result)
1343
+ return result
1344
+ } finally {
1345
+ rmSync(work, { recursive: true, force: true })
1346
+ }
1347
+ }
1348
+
1349
+ /**
1350
+ * Submit one order to the Huaqiu openapi, exactly as the KiCad action does.
1351
+ *
1352
+ * PCB: every `PCB_FORM` field plus the gerber/drill archive as `file`.
1353
+ * SMT: `pcbFile` + `coordFile` + `bomFile` and `reqParseVO`, with the caller's
1354
+ * access token in `authorization`. The backend owns the order; this method
1355
+ * forwards the files and composes the final page URL from the returned id the
1356
+ * way the reference does.
1357
+ */
1358
+ async placeOrder(request: PlaceOrderRequest): Promise<PlaceOrderResult> {
1359
+ const settings = this.orderSettings()
1360
+ const bundle = await this.fabricate({
1361
+ boardPath: request.boardPath,
1362
+ ...(request.schematicPath === undefined ? {} : { schematicPath: request.schematicPath }),
1363
+ ...(request.roots === undefined ? {} : { roots: request.roots }),
1364
+ ...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
1365
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
1366
+ })
1367
+ // Checked after the install gate so a missing KiCad is reported as such,
1368
+ // but before any upload: the page would open signed out without a token.
1369
+ const token = await this.orderToken()
1370
+ if (token === undefined) {
1371
+ throw errorWithCode(
1372
+ 'placing an order requires a signed-in Huaqiu account (or HUAQIU_ACCESS_TOKEN)',
1373
+ 'unauthorized',
1374
+ 401,
1375
+ )
1376
+ }
1377
+ const facts = bundle.facts
1378
+ const endpoint = `${settings.baseUrl}${ORDER_PATHS[request.kind]}`
1379
+
1380
+ let parts: { name: string; value: string }[]
1381
+ let files: { field: string; name: string; type: string; data: Uint8Array }[]
1382
+ let headers: Record<string, string> | undefined
1383
+
1384
+ if (request.kind === 'pcb') {
1385
+ const form = pcbOrderForm(facts, request.quantity === undefined ? {} : { quantity: request.quantity })
1386
+ parts = Object.entries(form).map(([name, value]) => ({ name, value }))
1387
+ files = [{ field: 'file', name: bundle.archive.zipName, type: 'application/zip', data: bundle.archiveData }]
410
1388
  } else {
411
- command = installed.solidcraft.executable
412
- if (command === undefined) {
413
- throw Object.assign(new Error('SolidCraft is not configured'), { code: 'not-configured', status: 412 })
1389
+ if (bundle.assemblyFiles === undefined) {
1390
+ throw errorWithCode('SMT order placement requires the project root schematic', 'invalid-request', 400)
414
1391
  }
415
- if (!MECHANICAL_EXTENSIONS.has(extname(path).toLowerCase())) {
416
- throw Object.assign(new Error(`unsupported SolidCraft artifact: ${extname(path)}`), { code: 'unsupported-artifact', status: 415 })
1392
+ const smt = smtOrderForm(facts, {
1393
+ bomFileName: `${packageName(bundle.boardPath)}-bom.csv`,
1394
+ coordFileName: `${packageName(bundle.boardPath)}-positions.csv`,
1395
+ materialTypes: bundle.assembly?.bomLines ?? 0,
1396
+ ...(request.quantity === undefined ? {} : { quantity: request.quantity }),
1397
+ })
1398
+ parts = [{
1399
+ name: 'reqParseVO',
1400
+ value: JSON.stringify({
1401
+ pcb_order: pcbOrderForm(facts, request.quantity === undefined ? {} : { quantity: request.quantity }),
1402
+ smt_order: smt,
1403
+ }),
1404
+ }]
1405
+ files = [
1406
+ { field: 'pcbFile', name: bundle.archive.zipName, type: 'application/zip', data: bundle.archiveData },
1407
+ {
1408
+ field: 'coordFile', name: String(smt.coord_file_name), type: 'application/octet-stream',
1409
+ data: new TextEncoder().encode(bundle.assemblyFiles.positions),
1410
+ },
1411
+ {
1412
+ field: 'bomFile', name: String(smt.bom_file_name), type: 'application/octet-stream',
1413
+ data: new TextEncoder().encode(bundle.assemblyFiles.bom),
1414
+ },
1415
+ ]
1416
+ headers = { authorization: token }
1417
+ }
1418
+
1419
+ const boundary = `----huaqiu${createHash('sha256').update(`${endpoint}:${String(Date.now())}`).digest('hex').slice(0, 24)}`
1420
+ const payload = multipartBody(parts, files, boundary)
1421
+ const post = this.config.postOrder ?? defaultPostOrder
1422
+
1423
+ let response: { status: number; text: string }
1424
+ try {
1425
+ response = await post(endpoint, {
1426
+ body: payload.body,
1427
+ contentType: payload.contentType,
1428
+ ...(headers === undefined ? {} : { headers }),
1429
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
1430
+ })
1431
+ } catch (error) {
1432
+ const detail = error instanceof Error ? error.message : String(error)
1433
+ throw errorWithCode(`the order endpoint could not be reached: ${detail}`, 'order-unreachable', 502)
1434
+ }
1435
+ if (response.status < 200 || response.status >= 300) {
1436
+ throw errorWithCode(
1437
+ `the order endpoint rejected the request (HTTP ${String(response.status)}): ${response.text.slice(0, 400)}`,
1438
+ 'order-rejected',
1439
+ 502,
1440
+ )
1441
+ }
1442
+
1443
+ let json: unknown
1444
+ try {
1445
+ json = JSON.parse(response.text)
1446
+ } catch {
1447
+ throw errorWithCode('the order endpoint returned an unreadable response', 'order-rejected', 502)
1448
+ }
1449
+ const responseUrl = orderUrlOf(json)
1450
+ if (responseUrl === undefined) {
1451
+ throw errorWithCode('the order endpoint returned no order URL', 'order-rejected', 502)
1452
+ }
1453
+
1454
+ // Reproduce the URL KiCad's own action loads in its webview, including the
1455
+ // exact query the hqpcb page expects. For PCB that is a page composed
1456
+ // around the returned id/guid; for assembly the same kind of page, composed
1457
+ // from the returned id with `source=bom` (BOM matching). The backend's own
1458
+ // string is kept as `responseUrl` for diagnostics.
1459
+ const ids = orderIdsFromUrl(responseUrl)
1460
+ const orderUrl = request.kind === 'pcb'
1461
+ ? pcbOrderUrl(settings.pageBase, ids, token)
1462
+ : smtOrderUrl(settings.pageBase, ids, token) ?? smtOrderUrlFromBackend(responseUrl, token)
1463
+ if (orderUrl === undefined) {
1464
+ throw errorWithCode('the order endpoint returned an order id that cannot form a page URL', 'order-rejected', 502)
1465
+ }
1466
+
1467
+ // Opening the page is the whole point of the action, but a browser that
1468
+ // will not start must never discard a successfully created order.
1469
+ const launch = request.launch !== false
1470
+ let opened: { launched: boolean; launcher?: string } = { launched: false }
1471
+ if (launch) {
1472
+ try {
1473
+ const result = this.openOrderUrl(orderUrl)
1474
+ opened = { launched: true, launcher: result.command }
1475
+ } catch {
1476
+ opened = { launched: false }
417
1477
  }
418
1478
  }
419
- const settings = { cwd: dirname(path), detached: true, stdio: 'ignore' as const, windowsHide: true, shell: false as const }
420
- const child = this.options.spawnProcess(command, [path], settings)
421
- return { launched: true, command, args: [path], cwd: settings.cwd, ...(child.pid === undefined ? {} : { pid: child.pid }) }
1479
+
1480
+ return {
1481
+ kind: request.kind,
1482
+ orderUrl,
1483
+ responseUrl,
1484
+ ...opened,
1485
+ status: opened.launched ? 'launched' : 'ready',
1486
+ message: opened.launched
1487
+ ? `Opened the ${request.kind === 'pcb' ? 'PCB' : 'assembly'} order page in your default browser.`
1488
+ : `The ${request.kind === 'pcb' ? 'PCB' : 'assembly'} order page is ready; open the URL to continue.`,
1489
+ endpoint,
1490
+ facts,
1491
+ archive: bundle.archive,
1492
+ ...(bundle.assembly === undefined ? {} : { assembly: bundle.assembly }),
1493
+ }
1494
+ }
1495
+
1496
+ /**
1497
+ * Open one order page in the OS default browser.
1498
+ *
1499
+ * This is the only place a URL reaches an external program; the URL is
1500
+ * validated by shape first and passed as a plain argument.
1501
+ */
1502
+ openOrderUrl(raw: string): { launched: true; command: string; url: string } {
1503
+ const url = externalUrlTarget(raw)
1504
+ const spec = this.options.openExternal(url)
1505
+ this.options.spawnProcess(spec.command, spec.args, {
1506
+ cwd: tmpdir(), detached: true, stdio: 'ignore', windowsHide: true, shell: false,
1507
+ })
1508
+ return { launched: true, command: spec.command, url }
1509
+ }
1510
+
1511
+ /** Serve a generated GLB file, re-validating the cache entry first. */
1512
+ glbFile(boardPath: string, revision: string): string {
1513
+ const key = `${canonical(boardPath)}:${revision}`
1514
+ const entry = this.glbCache.get(key)
1515
+ if (entry === undefined || !existsSync(entry.file)) {
1516
+ throw errorWithCode('generated GLB is not available for this revision', 'stale-revision', 409)
1517
+ }
1518
+ return entry.file
1519
+ }
1520
+
1521
+ /** Drop cached derived outputs for one board (or all of them). */
1522
+ clearCache(boardPath?: string): void {
1523
+ this.packageCache.clear()
1524
+ if (boardPath === undefined) {
1525
+ this.glbCache.clear()
1526
+ rmSync(this.cacheRoot, { recursive: true, force: true })
1527
+ return
1528
+ }
1529
+ const prefix = `${canonical(boardPath)}:`
1530
+ for (const key of [...this.glbCache.keys()]) {
1531
+ if (key.startsWith(prefix)) this.glbCache.delete(key)
1532
+ }
1533
+ rmSync(this.glbDirectory(canonical(boardPath)), { recursive: true, force: true })
1534
+ }
1535
+ }
1536
+
1537
+ /** Ownership order: project-named board first, then shallower, then alphabetical. */
1538
+ function boardRank(left: HardwareArtifact, right: HardwareArtifact, projectName: string): number { const leftNamed = basename(left.path, '.kicad_pcb') === projectName ? 0 : 1
1539
+ const rightNamed = basename(right.path, '.kicad_pcb') === projectName ? 0 : 1
1540
+ if (leftNamed !== rightNamed) return leftNamed - rightNamed
1541
+ const leftDepth = left.path.split(sep).length
1542
+ const rightDepth = right.path.split(sep).length
1543
+ if (leftDepth !== rightDepth) return leftDepth - rightDepth
1544
+ return left.path.localeCompare(right.path)
1545
+ }
1546
+
1547
+ /** RFC4180-style CSV reader: quoted fields, doubled quotes, CRLF rows. */
1548
+ export function parseCsv(text: string): string[][] {
1549
+ const rows: string[][] = []
1550
+ let row: string[] = []
1551
+ let field = ''
1552
+ let quoted = false
1553
+ const source = text.replace(/^\uFEFF/u, '')
1554
+ for (let index = 0; index < source.length; index += 1) {
1555
+ const char = source[index]
1556
+ if (quoted) {
1557
+ if (char === '"') {
1558
+ if (source[index + 1] === '"') {
1559
+ field += '"'
1560
+ index += 1
1561
+ } else {
1562
+ quoted = false
1563
+ }
1564
+ } else {
1565
+ field += char
1566
+ }
1567
+ continue
1568
+ }
1569
+ if (char === '"') {
1570
+ quoted = true
1571
+ } else if (char === ',') {
1572
+ row.push(field)
1573
+ field = ''
1574
+ } else if (char === '\r') {
1575
+ continue
1576
+ } else if (char === '\n') {
1577
+ row.push(field)
1578
+ rows.push(row)
1579
+ row = []
1580
+ field = ''
1581
+ } else {
1582
+ field += char
1583
+ }
1584
+ }
1585
+ if (field !== '' || row.length > 0) {
1586
+ row.push(field)
1587
+ rows.push(row)
1588
+ }
1589
+ return rows.filter(cells => cells.some(cell => cell.trim() !== ''))
1590
+ }
1591
+
1592
+ /**
1593
+ * Group KiCad's per-reference BOM rows.
1594
+ *
1595
+ * Identity is every column except the reference and quantity columns, so a
1596
+ * different MPN or a DNP flag always produces a separate line; ordering follows
1597
+ * the first reference seen, which keeps the table stable between reads.
1598
+ *
1599
+ * Column names follow `kicad-cli sch export bom`'s default field set, which is
1600
+ * `Refs,Value,Footprint,Qty,DNP`; a customized `--fields` header may spell the
1601
+ * same columns out in full, and a grouped export may pack several references
1602
+ * into one cell, so both spellings and both shapes are accepted.
1603
+ */
1604
+ export function groupBomRows(table: readonly string[][]): BomRow[] {
1605
+ const [header, ...body] = table
1606
+ if (header === undefined) return []
1607
+ const columns = header.map(cell => cell.trim())
1608
+ const find = (...aliases: readonly RegExp[]): number =>
1609
+ columns.findIndex(cell => aliases.some(alias => alias.test(cell)))
1610
+ const referenceIndex = find(/^refs?$/iu, /^references?$/iu)
1611
+ const quantityIndex = find(/^qty$/iu, /^quantity$/iu)
1612
+ const valueIndex = find(/^value$/iu)
1613
+ const footprintIndex = find(/^footprint$/iu)
1614
+ const dnpIndex = find(/^dnp$/iu)
1615
+ const groups = new Map<string, { references: string[]; fields: Record<string, string>; dnp: boolean }>()
1616
+ for (const cells of body) {
1617
+ const references = referenceIndex === -1
1618
+ ? []
1619
+ : (cells[referenceIndex] ?? '').split(/[,;\s]+/u).map(reference => reference.trim()).filter(reference => reference !== '')
1620
+ if (references.length === 0) continue
1621
+ const fields: Record<string, string> = {}
1622
+ columns.forEach((column, index) => {
1623
+ if (index === referenceIndex || index === quantityIndex || index === valueIndex
1624
+ || index === footprintIndex || index === dnpIndex) return
1625
+ const text = (cells[index] ?? '').trim()
1626
+ if (text !== '') fields[column] = text
1627
+ })
1628
+ const dnpText = dnpIndex === -1 ? '' : (cells[dnpIndex] ?? '').trim()
1629
+ const dnp = /^(1|true|yes|dnp|x)$/iu.test(dnpText)
1630
+ const identity = JSON.stringify([
1631
+ valueIndex === -1 ? '' : (cells[valueIndex] ?? '').trim(),
1632
+ footprintIndex === -1 ? '' : (cells[footprintIndex] ?? '').trim(),
1633
+ dnp,
1634
+ Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b))),
1635
+ ])
1636
+ const group = groups.get(identity) ?? { references: [], fields, dnp }
1637
+ group.references.push(...references)
1638
+ groups.set(identity, group)
422
1639
  }
1640
+ return [...groups.entries()].map(([identity, group]) => {
1641
+ const [value, footprint, dnp] = JSON.parse(identity) as [string, string, boolean]
1642
+ return {
1643
+ references: group.references,
1644
+ quantity: group.references.length,
1645
+ value,
1646
+ footprint,
1647
+ dnp,
1648
+ fields: group.fields,
1649
+ } satisfies BomRow
1650
+ })
423
1651
  }