@huaqiu/hardware-artifacts 0.7.18 → 0.7.20

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