@huaqiu/hardware-artifacts 0.7.12 → 0.7.13
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/lib/routes.mjs +150 -20
- package/lib/service.d.mts +129 -2
- package/lib/service.mjs +538 -77
- package/package.json +1 -1
- package/src/index.ts +1 -1
- package/src/routes.ts +108 -9
- package/src/service.ts +639 -54
package/lib/service.mjs
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
|
|
2
|
+
import { execFile, execFileSync, spawn } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
4
7
|
//#region src/service.ts
|
|
5
8
|
/**
|
|
6
9
|
* Hardware Engineering artifact model and host operations.
|
|
7
10
|
*
|
|
8
11
|
* This module deliberately has no Cordis dependency: it is the testable core
|
|
9
12
|
* behind `hardwareArtifacts`. Native project files remain authoritative; the
|
|
10
|
-
* objects here are path pointers
|
|
11
|
-
* shadow project database.
|
|
13
|
+
* objects here are path pointers, verified installation facts and disposable
|
|
14
|
+
* derived outputs, never a shadow project database.
|
|
12
15
|
*/
|
|
13
16
|
const EXCLUDED_DIRS = /* @__PURE__ */ new Set([
|
|
14
17
|
".git",
|
|
@@ -31,7 +34,13 @@ const MECHANICAL_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
31
34
|
".stp",
|
|
32
35
|
".glb"
|
|
33
36
|
]);
|
|
37
|
+
const SOURCE_EXTENSIONS = {
|
|
38
|
+
".kicad_sch": "schematic",
|
|
39
|
+
".kicad_pcb": "pcb"
|
|
40
|
+
};
|
|
34
41
|
const MAX_DEPTH = 5;
|
|
42
|
+
/** KiCad writes each child sheet as `(property "Sheetfile" "child.kicad_sch")`. */
|
|
43
|
+
const SHEET_FILE_PATTERN = /\(property\s+"Sheetfile"\s+"((?:[^"\\]|\\.)*)"/gu;
|
|
35
44
|
function canonical(path) {
|
|
36
45
|
return resolve(path);
|
|
37
46
|
}
|
|
@@ -42,6 +51,19 @@ function isInside(child, parent) {
|
|
|
42
51
|
function isExcluded(name) {
|
|
43
52
|
return EXCLUDED_DIRS.has(name.toLowerCase());
|
|
44
53
|
}
|
|
54
|
+
function realOrUndefined(path) {
|
|
55
|
+
try {
|
|
56
|
+
return realpathSync(path);
|
|
57
|
+
} catch {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function errorWithCode(message, code, status) {
|
|
62
|
+
return Object.assign(new Error(message), {
|
|
63
|
+
code,
|
|
64
|
+
status
|
|
65
|
+
});
|
|
66
|
+
}
|
|
45
67
|
function walkFiles(root, predicate) {
|
|
46
68
|
const found = [];
|
|
47
69
|
const visit = (dir, depth) => {
|
|
@@ -62,6 +84,25 @@ function walkFiles(root, predicate) {
|
|
|
62
84
|
visit(root, 0);
|
|
63
85
|
return found.sort();
|
|
64
86
|
}
|
|
87
|
+
/** Child schematics declared by sheet references in one saved schematic. */
|
|
88
|
+
function childSheetFiles(path) {
|
|
89
|
+
let text;
|
|
90
|
+
try {
|
|
91
|
+
text = readFileSync(path, "utf8");
|
|
92
|
+
} catch {
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
const dir = dirname(path);
|
|
96
|
+
const children = [];
|
|
97
|
+
for (const match of text.matchAll(SHEET_FILE_PATTERN)) {
|
|
98
|
+
const raw = match[1];
|
|
99
|
+
if (raw === void 0 || raw === "") continue;
|
|
100
|
+
const declared = raw.replace(/\\(["\\])/gu, "$1");
|
|
101
|
+
const target = isAbsolute(declared) ? canonical(declared) : resolve(dir, declared);
|
|
102
|
+
children.push(target);
|
|
103
|
+
}
|
|
104
|
+
return children.sort();
|
|
105
|
+
}
|
|
65
106
|
function artifact(kind, path, projectPath, sourcePath) {
|
|
66
107
|
const full = canonical(path);
|
|
67
108
|
return {
|
|
@@ -90,6 +131,51 @@ function defaultVersionProbe(executable) {
|
|
|
90
131
|
return;
|
|
91
132
|
}
|
|
92
133
|
}
|
|
134
|
+
function defaultRunCommand(command, args, options) {
|
|
135
|
+
return new Promise((resolvePromise, reject) => {
|
|
136
|
+
execFile(command, [...args], {
|
|
137
|
+
cwd: options.cwd,
|
|
138
|
+
timeout: options.timeoutMs,
|
|
139
|
+
encoding: "utf8",
|
|
140
|
+
windowsHide: true,
|
|
141
|
+
shell: false,
|
|
142
|
+
...options.signal === void 0 ? {} : { signal: options.signal },
|
|
143
|
+
maxBuffer: 8388608
|
|
144
|
+
}, (error, stdout, stderr) => {
|
|
145
|
+
if (error === null) {
|
|
146
|
+
resolvePromise({
|
|
147
|
+
exitCode: 0,
|
|
148
|
+
stdout: String(stdout),
|
|
149
|
+
stderr: String(stderr),
|
|
150
|
+
timedOut: false
|
|
151
|
+
});
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const killed = error.killed === true;
|
|
155
|
+
const signal = error.signal;
|
|
156
|
+
if (killed || signal !== null && signal !== void 0) {
|
|
157
|
+
resolvePromise({
|
|
158
|
+
exitCode: null,
|
|
159
|
+
stdout: String(stdout),
|
|
160
|
+
stderr: String(stderr),
|
|
161
|
+
timedOut: true
|
|
162
|
+
});
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
const code = typeof error.code === "number" ? Number(error.code) : null;
|
|
166
|
+
if (code === null) {
|
|
167
|
+
reject(error);
|
|
168
|
+
return;
|
|
169
|
+
}
|
|
170
|
+
resolvePromise({
|
|
171
|
+
exitCode: code,
|
|
172
|
+
stdout: String(stdout),
|
|
173
|
+
stderr: String(stderr),
|
|
174
|
+
timedOut: false
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
}
|
|
93
179
|
function existing(paths) {
|
|
94
180
|
return paths.find((candidate) => {
|
|
95
181
|
try {
|
|
@@ -119,6 +205,14 @@ function kicadCandidates(root) {
|
|
|
119
205
|
pcbnew: [join(bin, `pcbnew${exe}`)]
|
|
120
206
|
};
|
|
121
207
|
}
|
|
208
|
+
/** Install root that owns one resolved `kicad-cli`, per layout convention. */
|
|
209
|
+
function installRootFromCli(cli) {
|
|
210
|
+
const segments = cli.split(sep);
|
|
211
|
+
const macIndex = segments.indexOf("Contents");
|
|
212
|
+
if (macIndex > 0) return segments.slice(0, macIndex).join(sep) || sep;
|
|
213
|
+
if (segments[segments.length - 2]?.toLowerCase() === "bin") return segments.slice(0, -2).join(sep) || sep;
|
|
214
|
+
return dirname(cli);
|
|
215
|
+
}
|
|
122
216
|
function solidcraftCandidates(root) {
|
|
123
217
|
const exe = process.platform === "win32" ? ".exe" : "";
|
|
124
218
|
const app = basename(root).toLowerCase().endsWith(".app");
|
|
@@ -138,12 +232,26 @@ function solidcraftCandidates(root) {
|
|
|
138
232
|
var HardwareArtifactService = class {
|
|
139
233
|
config;
|
|
140
234
|
options;
|
|
235
|
+
cacheRoot;
|
|
236
|
+
glbTimeoutMs;
|
|
237
|
+
maxSourceBytes;
|
|
238
|
+
lastDiscovery;
|
|
239
|
+
/** Completed GLB exports keyed by `sourcePath:revision`. */
|
|
240
|
+
glbCache = /* @__PURE__ */ new Map();
|
|
241
|
+
/** In-flight GLB exports keyed by the same key, so concurrent callers share one run. */
|
|
242
|
+
glbPending = /* @__PURE__ */ new Map();
|
|
243
|
+
/** BOM projections keyed by `sourcePath:revision`. */
|
|
244
|
+
bomCache = /* @__PURE__ */ new Map();
|
|
141
245
|
constructor(config = {}) {
|
|
142
246
|
this.config = config;
|
|
143
247
|
this.options = {
|
|
144
248
|
probeVersion: config.probeVersion ?? defaultVersionProbe,
|
|
145
|
-
spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings))
|
|
249
|
+
spawnProcess: config.spawnProcess ?? ((command, args, settings) => spawn(command, [...args], settings)),
|
|
250
|
+
runCommand: config.runCommand ?? defaultRunCommand
|
|
146
251
|
};
|
|
252
|
+
this.cacheRoot = canonical(config.cacheRoot ?? join(tmpdir(), "huaqiu-hardware-artifacts"));
|
|
253
|
+
this.glbTimeoutMs = config.glbTimeoutMs ?? 12e4;
|
|
254
|
+
this.maxSourceBytes = config.maxSourceBytes ?? 33554432;
|
|
147
255
|
}
|
|
148
256
|
/** Resolve configured installations from validated absolute paths only. */
|
|
149
257
|
installations() {
|
|
@@ -155,21 +263,27 @@ var HardwareArtifactService = class {
|
|
|
155
263
|
kicad: [],
|
|
156
264
|
eeschema: [],
|
|
157
265
|
pcbnew: []
|
|
158
|
-
} : kicadCandidates(kicadCli
|
|
266
|
+
} : kicadCandidates(kicadCli === void 0 ? kicadRoot : installRootFromCli(kicadCli));
|
|
159
267
|
const pcbEditor = existing(candidates.pcbnew);
|
|
160
268
|
const schematicEditor = existing(candidates.eeschema);
|
|
161
269
|
const projectManager = existing(candidates.kicad);
|
|
270
|
+
const version = kicadCli === void 0 ? void 0 : this.options.probeVersion(kicadCli);
|
|
162
271
|
const kicad = kicadCli === void 0 ? {
|
|
163
272
|
configured: false,
|
|
164
273
|
error: "KiCad installation is not configured"
|
|
274
|
+
} : version === void 0 ? {
|
|
275
|
+
configured: false,
|
|
276
|
+
root: kicadRoot,
|
|
277
|
+
cli: kicadCli,
|
|
278
|
+
error: `${kicadCli} did not answer a version probe`
|
|
165
279
|
} : {
|
|
166
280
|
configured: true,
|
|
167
281
|
root: kicadRoot,
|
|
168
282
|
cli: kicadCli,
|
|
283
|
+
version,
|
|
169
284
|
...projectManager === void 0 ? {} : { projectManager },
|
|
170
285
|
...pcbEditor === void 0 ? {} : { pcbEditor },
|
|
171
|
-
...schematicEditor === void 0 ? {} : { schematicEditor }
|
|
172
|
-
...this.options.probeVersion(kicadCli) === void 0 ? {} : { version: this.options.probeVersion(kicadCli) }
|
|
286
|
+
...schematicEditor === void 0 ? {} : { schematicEditor }
|
|
173
287
|
};
|
|
174
288
|
const solidRoot = this.config.solidcraftRoot ? canonical(this.config.solidcraftRoot) : void 0;
|
|
175
289
|
const solidExecutable = solidRoot === void 0 ? void 0 : existing(solidcraftCandidates(solidRoot));
|
|
@@ -238,7 +352,7 @@ var HardwareArtifactService = class {
|
|
|
238
352
|
if (existsSync(manifestPath)) try {
|
|
239
353
|
manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
240
354
|
} catch (error) {
|
|
241
|
-
|
|
355
|
+
const result = {
|
|
242
356
|
cwd,
|
|
243
357
|
manifestPath,
|
|
244
358
|
projects: [],
|
|
@@ -247,43 +361,57 @@ var HardwareArtifactService = class {
|
|
|
247
361
|
message: `invalid .hardware-engineering.json: ${String(error)}`
|
|
248
362
|
}
|
|
249
363
|
};
|
|
364
|
+
this.lastDiscovery = result;
|
|
365
|
+
return result;
|
|
250
366
|
}
|
|
251
367
|
const projectPaths = /* @__PURE__ */ new Set();
|
|
252
368
|
if (explicitProject !== void 0 && explicitProject.trim() !== "") {
|
|
253
369
|
const requested = isAbsolute(explicitProject) ? canonical(explicitProject) : resolve(cwd, explicitProject);
|
|
254
|
-
if (!existsSync(requested))
|
|
370
|
+
if (!existsSync(requested)) {
|
|
371
|
+
const result = {
|
|
372
|
+
cwd,
|
|
373
|
+
...manifest === void 0 ? {} : { manifestPath },
|
|
374
|
+
projects: [],
|
|
375
|
+
issue: {
|
|
376
|
+
code: "missing-project",
|
|
377
|
+
message: `${requested} does not exist`
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
this.lastDiscovery = result;
|
|
381
|
+
return result;
|
|
382
|
+
}
|
|
383
|
+
projectPaths.add(requested);
|
|
384
|
+
} else if (manifest?.project !== void 0 && manifest.project.trim() !== "") projectPaths.add(isAbsolute(manifest.project) ? canonical(manifest.project) : resolve(cwd, manifest.project));
|
|
385
|
+
else for (const path of walkFiles(cwd, (name) => name.toLowerCase().endsWith(".kicad_pro"))) projectPaths.add(path);
|
|
386
|
+
const projects = [...projectPaths].sort().map((path) => this.projectFrom(path, cwd, manifest));
|
|
387
|
+
if (projects.length === 0) {
|
|
388
|
+
const result = {
|
|
255
389
|
cwd,
|
|
256
390
|
...manifest === void 0 ? {} : { manifestPath },
|
|
257
|
-
projects
|
|
391
|
+
projects,
|
|
258
392
|
issue: {
|
|
259
|
-
code: "
|
|
260
|
-
message:
|
|
393
|
+
code: "no-project",
|
|
394
|
+
message: `no .kicad_pro found under ${cwd}`
|
|
261
395
|
}
|
|
262
396
|
};
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
projects,
|
|
280
|
-
issue: {
|
|
281
|
-
code: "selection-required",
|
|
282
|
-
message: `${projects.length} projects found; select one explicitly`
|
|
283
|
-
}
|
|
284
|
-
};
|
|
397
|
+
this.lastDiscovery = result;
|
|
398
|
+
return result;
|
|
399
|
+
}
|
|
400
|
+
if (projects.length > 1) {
|
|
401
|
+
const result = {
|
|
402
|
+
cwd,
|
|
403
|
+
...manifest === void 0 ? {} : { manifestPath },
|
|
404
|
+
projects,
|
|
405
|
+
issue: {
|
|
406
|
+
code: "selection-required",
|
|
407
|
+
message: `${projects.length} projects found; select one explicitly`
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
this.lastDiscovery = result;
|
|
411
|
+
return result;
|
|
412
|
+
}
|
|
285
413
|
const selected = projects[0];
|
|
286
|
-
|
|
414
|
+
const result = {
|
|
287
415
|
cwd,
|
|
288
416
|
...manifest === void 0 ? {} : { manifestPath },
|
|
289
417
|
projects,
|
|
@@ -293,69 +421,84 @@ var HardwareArtifactService = class {
|
|
|
293
421
|
message: "select an artifact explicitly"
|
|
294
422
|
} } : {}
|
|
295
423
|
};
|
|
424
|
+
this.lastDiscovery = result;
|
|
425
|
+
return result;
|
|
426
|
+
}
|
|
427
|
+
/** The most recent discovery, used to authorize source reads. */
|
|
428
|
+
discovery() {
|
|
429
|
+
return this.lastDiscovery;
|
|
296
430
|
}
|
|
297
431
|
projectFrom(projectPath, cwd, manifest) {
|
|
298
432
|
const dir = dirname(projectPath);
|
|
299
433
|
const name = basename(projectPath, extname(projectPath));
|
|
300
434
|
const resolvePath = (value) => isAbsolute(value) ? canonical(value) : resolve(dir, value);
|
|
301
|
-
const
|
|
302
|
-
|
|
435
|
+
const explicitSchematic = manifest?.schematic === void 0 ? void 0 : resolvePath(manifest.schematic);
|
|
436
|
+
let schematicPath = explicitSchematic !== void 0 && existsSync(explicitSchematic) ? explicitSchematic : void 0;
|
|
437
|
+
if (schematicPath === void 0) {
|
|
438
|
+
const named = join(dir, `${name}.kicad_sch`);
|
|
439
|
+
if (existsSync(named)) schematicPath = named;
|
|
440
|
+
else {
|
|
441
|
+
const candidates = readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(".kicad_sch")).map((entry) => join(dir, entry.name)).sort();
|
|
442
|
+
if (candidates.length === 1) schematicPath = candidates[0];
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
const sheets = [];
|
|
446
|
+
if (schematicPath !== void 0) {
|
|
447
|
+
const visited = /* @__PURE__ */ new Set([canonical(schematicPath)]);
|
|
448
|
+
const queue = childSheetFiles(canonical(schematicPath));
|
|
449
|
+
while (queue.length > 0) {
|
|
450
|
+
const canonicalNext = canonical(queue.shift());
|
|
451
|
+
if (visited.has(canonicalNext)) continue;
|
|
452
|
+
visited.add(canonicalNext);
|
|
453
|
+
if (!existsSync(canonicalNext) || extname(canonicalNext).toLowerCase() !== ".kicad_sch") continue;
|
|
454
|
+
sheets.push(artifact("schematic", canonicalNext, projectPath, canonical(schematicPath)));
|
|
455
|
+
queue.push(...childSheetFiles(canonicalNext));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
const manifestBoards = manifest?.boards === void 0 ? [] : manifest.boards.filter((entry) => existsSync(resolvePath(entry.path))).map((entry) => artifact("pcb", resolvePath(entry.path), projectPath));
|
|
459
|
+
const scannedBoards = walkFiles(dir, (file) => file.toLowerCase().endsWith(".kicad_pcb")).map((path) => artifact("pcb", path, projectPath));
|
|
460
|
+
const boards = manifestBoards.length > 0 ? manifestBoards : [...scannedBoards].sort((left, right) => boardRank(left, right, name));
|
|
461
|
+
const owned = boards.find((board) => basename(board.path, ".kicad_pcb") === name) ?? boards[0];
|
|
462
|
+
const ownershipAmbiguous = manifestBoards.length === 0 && boards.length > 1 && basename(owned?.path ?? "", ".kicad_pcb") !== name;
|
|
303
463
|
const mechanical = manifest?.mechanical !== void 0 ? manifest.mechanical.map((model) => artifact("mechanical-3d", resolvePath(model.path), projectPath)) : walkFiles(dir, (file) => MECHANICAL_EXTENSIONS.has(extname(file).toLowerCase())).map((path) => artifact("mechanical-3d", path, projectPath));
|
|
304
|
-
const sheets = schematicPath === void 0 ? [] : walkFiles(dir, (file) => file.toLowerCase().endsWith(".kicad_sch")).filter((path) => path !== schematicPath && isInside(path, dir)).map((path) => artifact("schematic", path, projectPath, schematicPath));
|
|
305
464
|
const sourceSchematic = schematicPath === void 0 ? void 0 : artifact("schematic", schematicPath, projectPath);
|
|
306
|
-
const sourceBoard =
|
|
465
|
+
const sourceBoard = ownershipAmbiguous ? void 0 : owned;
|
|
307
466
|
return {
|
|
308
467
|
path: projectPath,
|
|
309
468
|
name,
|
|
310
|
-
...sourceSchematic === void 0 ? {} : {
|
|
469
|
+
...sourceSchematic === void 0 ? {} : {
|
|
470
|
+
rootSheet: sourceSchematic,
|
|
471
|
+
schematic: sourceSchematic
|
|
472
|
+
},
|
|
311
473
|
...sourceSchematic === void 0 ? {} : { bom: {
|
|
312
474
|
...artifact("bom", sourceSchematic.path, projectPath, sourceSchematic.path),
|
|
313
475
|
title: `BOM — ${sourceSchematic.title}`
|
|
314
476
|
} },
|
|
315
|
-
...sourceBoard === void 0 ? {} : {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
477
|
+
...sourceBoard === void 0 ? {} : {
|
|
478
|
+
pcb3d: {
|
|
479
|
+
...artifact("pcb-3d", sourceBoard.path, projectPath, sourceBoard.path),
|
|
480
|
+
title: `3D — ${sourceBoard.title}`
|
|
481
|
+
},
|
|
482
|
+
defaultBoard: sourceBoard.path
|
|
483
|
+
},
|
|
319
484
|
sheets,
|
|
320
485
|
boards,
|
|
321
486
|
mechanical,
|
|
322
|
-
selectionRequired: boards.length > 1
|
|
487
|
+
selectionRequired: boards.length > 1 && ownershipAmbiguous
|
|
323
488
|
};
|
|
324
489
|
}
|
|
325
490
|
/** Validate and launch a native application without a shell. */
|
|
326
491
|
open(request) {
|
|
327
492
|
const path = canonical(request.artifactPath);
|
|
328
|
-
if (!existsSync(path)) throw
|
|
329
|
-
code: "missing-artifact",
|
|
330
|
-
status: 404
|
|
331
|
-
});
|
|
493
|
+
if (!existsSync(path)) throw errorWithCode(`artifact does not exist: ${path}`, "missing-artifact", 404);
|
|
332
494
|
const installed = this.installations();
|
|
333
|
-
const
|
|
495
|
+
const ext = extname(path).toLowerCase();
|
|
334
496
|
let command;
|
|
335
|
-
if (
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
else throw Object.assign(/* @__PURE__ */ new Error(`unsupported KiCad artifact: ${ext}`), {
|
|
341
|
-
code: "unsupported-artifact",
|
|
342
|
-
status: 415
|
|
343
|
-
});
|
|
344
|
-
if (command === void 0) throw Object.assign(/* @__PURE__ */ new Error("the configured KiCad installation has no editor for this artifact"), {
|
|
345
|
-
code: "missing-executable",
|
|
346
|
-
status: 412
|
|
347
|
-
});
|
|
348
|
-
} else {
|
|
349
|
-
command = installed.solidcraft.executable;
|
|
350
|
-
if (command === void 0) throw Object.assign(/* @__PURE__ */ new Error("SolidCraft is not configured"), {
|
|
351
|
-
code: "not-configured",
|
|
352
|
-
status: 412
|
|
353
|
-
});
|
|
354
|
-
if (!MECHANICAL_EXTENSIONS.has(extname(path).toLowerCase())) throw Object.assign(/* @__PURE__ */ new Error(`unsupported SolidCraft artifact: ${extname(path)}`), {
|
|
355
|
-
code: "unsupported-artifact",
|
|
356
|
-
status: 415
|
|
357
|
-
});
|
|
358
|
-
}
|
|
497
|
+
if (ext === ".kicad_sch") command = installed.kicad.schematicEditor;
|
|
498
|
+
else if (ext === ".kicad_pcb") command = installed.kicad.pcbEditor;
|
|
499
|
+
else if (ext === ".kicad_pro") command = installed.kicad.projectManager;
|
|
500
|
+
else throw errorWithCode(`unsupported KiCad artifact: ${ext}`, "unsupported-artifact", 415);
|
|
501
|
+
if (command === void 0) throw errorWithCode("the configured KiCad installation has no editor for this artifact", "missing-executable", 412);
|
|
359
502
|
const settings = {
|
|
360
503
|
cwd: dirname(path),
|
|
361
504
|
detached: true,
|
|
@@ -372,6 +515,324 @@ var HardwareArtifactService = class {
|
|
|
372
515
|
...child.pid === void 0 ? {} : { pid: child.pid }
|
|
373
516
|
};
|
|
374
517
|
}
|
|
518
|
+
/** Workspace roots a read may target: explicit request, last discovery, config. */
|
|
519
|
+
authorizedRoots(roots) {
|
|
520
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
521
|
+
for (const root of roots ?? []) if (root !== void 0 && root.trim() !== "") candidates.add(canonical(root));
|
|
522
|
+
const discovered = this.lastDiscovery?.cwd;
|
|
523
|
+
if (discovered !== void 0) candidates.add(canonical(discovered));
|
|
524
|
+
return [...candidates];
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Authorize one artifact path: canonical, realpath-checked, inside a
|
|
528
|
+
* workspace root, and of an expected type. A browser request cannot turn
|
|
529
|
+
* this into an arbitrary filesystem read, even from loopback.
|
|
530
|
+
*/
|
|
531
|
+
authorize(artifactPath, roots) {
|
|
532
|
+
if (!isAbsolute(artifactPath)) throw errorWithCode("artifact identity must be an absolute path", "invalid-identity", 400);
|
|
533
|
+
const requested = canonical(artifactPath);
|
|
534
|
+
if (SOURCE_EXTENSIONS[extname(requested).toLowerCase()] === void 0) throw errorWithCode(`unsupported artifact type: ${extname(requested)}`, "unsupported-artifact", 415);
|
|
535
|
+
const authorized = this.authorizedRoots(roots);
|
|
536
|
+
if (authorized.length === 0) throw errorWithCode("no authorized workspace is known to the host", "unauthorized", 403);
|
|
537
|
+
if (!authorized.some((root) => isInside(requested, canonical(root)))) throw errorWithCode("artifact is outside the authorized workspace", "unauthorized", 403);
|
|
538
|
+
if (!existsSync(requested)) throw errorWithCode(`artifact does not exist: ${requested}`, "missing-artifact", 404);
|
|
539
|
+
const real = realOrUndefined(requested);
|
|
540
|
+
if (real === void 0) throw errorWithCode(`artifact cannot be resolved: ${requested}`, "invalid-identity", 400);
|
|
541
|
+
if (!authorized.some((root) => {
|
|
542
|
+
const realRoot = realOrUndefined(root) ?? root;
|
|
543
|
+
return isInside(real, realRoot);
|
|
544
|
+
})) throw errorWithCode("artifact is outside the authorized workspace", "unauthorized", 403);
|
|
545
|
+
if (!statSync(real).isFile()) throw errorWithCode(`artifact is not a regular file: ${requested}`, "invalid-identity", 400);
|
|
546
|
+
if (SOURCE_EXTENSIONS[extname(real).toLowerCase()] === void 0) throw errorWithCode("artifact type changed during resolution", "unsupported-artifact", 415);
|
|
547
|
+
return {
|
|
548
|
+
path: real,
|
|
549
|
+
kind: SOURCE_EXTENSIONS[extname(real).toLowerCase()]
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
/** Saved source text plus a content-addressed revision. */
|
|
553
|
+
async readSource(request) {
|
|
554
|
+
const { path, kind } = this.authorize(request.artifactPath, request.roots);
|
|
555
|
+
const info = statSync(path);
|
|
556
|
+
if (info.size > this.maxSourceBytes) throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, "too-large", 413);
|
|
557
|
+
const body = await readFile(path);
|
|
558
|
+
const revision = createHash("sha256").update(body).digest("hex");
|
|
559
|
+
if (request.expectedRevision !== void 0 && request.expectedRevision !== "" && request.expectedRevision !== revision) throw errorWithCode(`source changed since it was selected (expected ${request.expectedRevision}, found ${revision})`, "stale-revision", 409);
|
|
560
|
+
return {
|
|
561
|
+
path,
|
|
562
|
+
kind,
|
|
563
|
+
revision,
|
|
564
|
+
bytes: body.byteLength,
|
|
565
|
+
mtimeMs: info.mtimeMs,
|
|
566
|
+
text: body.toString("utf8")
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
sourceRevision(path) {
|
|
570
|
+
if (statSync(path).size > this.maxSourceBytes) throw errorWithCode(`artifact is larger than ${this.maxSourceBytes} bytes`, "too-large", 413);
|
|
571
|
+
return createHash("sha256").update(readFileSync(path)).digest("hex");
|
|
572
|
+
}
|
|
573
|
+
/** Cache directory for one board's derived outputs. */
|
|
574
|
+
glbDirectory(boardPath) {
|
|
575
|
+
const digest = createHash("sha256").update(boardPath).digest("hex").slice(0, 16);
|
|
576
|
+
return join(this.cacheRoot, "glb", digest);
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Generate (or reuse) the GLB for one board.
|
|
580
|
+
*
|
|
581
|
+
* - cache key includes the source content hash, so same-size/same-mtime edits invalidate
|
|
582
|
+
* - one in-flight export is shared by concurrent callers for the same revision
|
|
583
|
+
* - output is written to a temp file and renamed only after it validates
|
|
584
|
+
* - a timeout or abort leaves no partial file behind
|
|
585
|
+
*/
|
|
586
|
+
async exportGlb(request) {
|
|
587
|
+
const { path } = this.authorize(request.artifactPath, request.roots);
|
|
588
|
+
if (extname(path).toLowerCase() !== ".kicad_pcb") throw errorWithCode("GLB export requires a .kicad_pcb artifact", "unsupported-artifact", 415);
|
|
589
|
+
const installed = this.installations();
|
|
590
|
+
if (!installed.kicad.configured || installed.kicad.cli === void 0) throw errorWithCode(installed.kicad.error ?? "the configured KiCad installation has no kicad-cli", "not-configured", 412);
|
|
591
|
+
const cli = installed.kicad.cli;
|
|
592
|
+
const revision = this.sourceRevision(path);
|
|
593
|
+
const key = `${path}:${revision}`;
|
|
594
|
+
const cached = this.glbCache.get(key);
|
|
595
|
+
if (cached !== void 0 && existsSync(cached.file)) {
|
|
596
|
+
const info = statSync(cached.file);
|
|
597
|
+
return {
|
|
598
|
+
...cached,
|
|
599
|
+
bytes: info.size,
|
|
600
|
+
cached: true
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
const pending = this.glbPending.get(key);
|
|
604
|
+
if (pending !== void 0) return pending;
|
|
605
|
+
const directory = this.glbDirectory(path);
|
|
606
|
+
const target = join(directory, `board-${revision.slice(0, 16)}.glb`);
|
|
607
|
+
const running = (async () => {
|
|
608
|
+
mkdirSync(directory, { recursive: true });
|
|
609
|
+
const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`);
|
|
610
|
+
mkdirSync(tempDirectory, { recursive: true });
|
|
611
|
+
const tempFile = join(tempDirectory, "board.glb");
|
|
612
|
+
try {
|
|
613
|
+
const result = await this.options.runCommand(cli, [
|
|
614
|
+
"pcb",
|
|
615
|
+
"export",
|
|
616
|
+
"glb",
|
|
617
|
+
"--output",
|
|
618
|
+
tempFile,
|
|
619
|
+
path
|
|
620
|
+
], {
|
|
621
|
+
cwd: dirname(path),
|
|
622
|
+
timeoutMs: this.glbTimeoutMs,
|
|
623
|
+
...request.signal === void 0 ? {} : { signal: request.signal }
|
|
624
|
+
});
|
|
625
|
+
if (result.timedOut) throw errorWithCode(`kicad-cli pcb export glb timed out after ${this.glbTimeoutMs} ms`, "export-timeout", 504);
|
|
626
|
+
if (result.exitCode !== 0) throw errorWithCode(`kicad-cli pcb export glb failed: ${(result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)}`, "export-failed", 502);
|
|
627
|
+
if (!existsSync(tempFile)) throw errorWithCode("kicad-cli pcb export glb produced no output", "export-failed", 502);
|
|
628
|
+
const bytes = statSync(tempFile).size;
|
|
629
|
+
if (bytes === 0 || readFileSync(tempFile).subarray(0, 4).toString("ascii") !== "glTF") throw errorWithCode("kicad-cli wrote an invalid GLB", "export-failed", 502);
|
|
630
|
+
renameSync(tempFile, target);
|
|
631
|
+
const generated = {
|
|
632
|
+
path,
|
|
633
|
+
revision,
|
|
634
|
+
bytes,
|
|
635
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
636
|
+
cached: false,
|
|
637
|
+
file: target
|
|
638
|
+
};
|
|
639
|
+
this.glbCache.set(key, generated);
|
|
640
|
+
return generated;
|
|
641
|
+
} finally {
|
|
642
|
+
rmSync(tempDirectory, {
|
|
643
|
+
recursive: true,
|
|
644
|
+
force: true
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
})();
|
|
648
|
+
this.glbPending.set(key, running);
|
|
649
|
+
try {
|
|
650
|
+
return await running;
|
|
651
|
+
} finally {
|
|
652
|
+
this.glbPending.delete(key);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Grouped BOM for one saved root schematic.
|
|
657
|
+
*
|
|
658
|
+
* Reuses KiCad's own BOM extraction (`kicad-cli sch export bom`), the same
|
|
659
|
+
* authoritative source `analyze_kicad_module` consumes, rather than building a
|
|
660
|
+
* second component analyser. Grouping key is every non-reference column, so
|
|
661
|
+
* different MPNs never merge and DNP stays explicit.
|
|
662
|
+
*/
|
|
663
|
+
async exportBom(request) {
|
|
664
|
+
const { path, kind } = this.authorize(request.artifactPath, request.roots);
|
|
665
|
+
if (kind !== "schematic") throw errorWithCode("BOM export requires a .kicad_sch artifact", "unsupported-artifact", 415);
|
|
666
|
+
const installed = this.installations();
|
|
667
|
+
if (!installed.kicad.configured || installed.kicad.cli === void 0) throw errorWithCode(installed.kicad.error ?? "the configured KiCad installation has no kicad-cli", "not-configured", 412);
|
|
668
|
+
const revision = this.sourceRevision(path);
|
|
669
|
+
const key = `${path}:${revision}`;
|
|
670
|
+
const cached = this.bomCache.get(key);
|
|
671
|
+
if (cached !== void 0) return {
|
|
672
|
+
...cached,
|
|
673
|
+
cached: true
|
|
674
|
+
};
|
|
675
|
+
const directory = join(this.cacheRoot, "bom", createHash("sha256").update(path).digest("hex").slice(0, 16));
|
|
676
|
+
const tempDirectory = join(directory, `tmp-${process.pid}-${String(Date.now())}`);
|
|
677
|
+
mkdirSync(tempDirectory, { recursive: true });
|
|
678
|
+
const tempFile = join(tempDirectory, "bom.csv");
|
|
679
|
+
try {
|
|
680
|
+
const result = await this.options.runCommand(installed.kicad.cli, [
|
|
681
|
+
"sch",
|
|
682
|
+
"export",
|
|
683
|
+
"bom",
|
|
684
|
+
"--output",
|
|
685
|
+
tempFile,
|
|
686
|
+
path
|
|
687
|
+
], {
|
|
688
|
+
cwd: dirname(path),
|
|
689
|
+
timeoutMs: 6e4,
|
|
690
|
+
...request.signal === void 0 ? {} : { signal: request.signal }
|
|
691
|
+
});
|
|
692
|
+
if (result.timedOut) throw errorWithCode("kicad-cli sch export bom timed out", "export-timeout", 504);
|
|
693
|
+
if (result.exitCode !== 0) throw errorWithCode(`kicad-cli sch export bom failed: ${(result.stderr.trim() || result.stdout.trim() || `exit ${String(result.exitCode)}`).slice(0, 800)}`, "export-failed", 502);
|
|
694
|
+
if (!existsSync(tempFile)) throw errorWithCode("kicad-cli produced no BOM output", "export-failed", 502);
|
|
695
|
+
const rows = groupBomRows(parseCsv(readFileSync(tempFile, "utf8")));
|
|
696
|
+
const generated = {
|
|
697
|
+
path,
|
|
698
|
+
revision,
|
|
699
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
700
|
+
cached: false,
|
|
701
|
+
rows,
|
|
702
|
+
source: "kicad-cli-bom"
|
|
703
|
+
};
|
|
704
|
+
this.bomCache.set(key, generated);
|
|
705
|
+
return generated;
|
|
706
|
+
} finally {
|
|
707
|
+
rmSync(tempDirectory, {
|
|
708
|
+
recursive: true,
|
|
709
|
+
force: true
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
/** Serve a generated GLB file, re-validating the cache entry first. */ glbFile(boardPath, revision) {
|
|
714
|
+
const key = `${canonical(boardPath)}:${revision}`;
|
|
715
|
+
const entry = this.glbCache.get(key);
|
|
716
|
+
if (entry === void 0 || !existsSync(entry.file)) throw errorWithCode("generated GLB is not available for this revision", "stale-revision", 409);
|
|
717
|
+
return entry.file;
|
|
718
|
+
}
|
|
719
|
+
/** Drop cached derived outputs for one board (or all of them). */
|
|
720
|
+
clearCache(boardPath) {
|
|
721
|
+
if (boardPath === void 0) {
|
|
722
|
+
this.glbCache.clear();
|
|
723
|
+
rmSync(this.cacheRoot, {
|
|
724
|
+
recursive: true,
|
|
725
|
+
force: true
|
|
726
|
+
});
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
const prefix = `${canonical(boardPath)}:`;
|
|
730
|
+
for (const key of [...this.glbCache.keys()]) if (key.startsWith(prefix)) this.glbCache.delete(key);
|
|
731
|
+
rmSync(this.glbDirectory(canonical(boardPath)), {
|
|
732
|
+
recursive: true,
|
|
733
|
+
force: true
|
|
734
|
+
});
|
|
735
|
+
}
|
|
375
736
|
};
|
|
737
|
+
/** Ownership order: project-named board first, then shallower, then alphabetical. */
|
|
738
|
+
function boardRank(left, right, projectName) {
|
|
739
|
+
const leftNamed = basename(left.path, ".kicad_pcb") === projectName ? 0 : 1;
|
|
740
|
+
const rightNamed = basename(right.path, ".kicad_pcb") === projectName ? 0 : 1;
|
|
741
|
+
if (leftNamed !== rightNamed) return leftNamed - rightNamed;
|
|
742
|
+
const leftDepth = left.path.split(sep).length;
|
|
743
|
+
const rightDepth = right.path.split(sep).length;
|
|
744
|
+
if (leftDepth !== rightDepth) return leftDepth - rightDepth;
|
|
745
|
+
return left.path.localeCompare(right.path);
|
|
746
|
+
}
|
|
747
|
+
/** RFC4180-style CSV reader: quoted fields, doubled quotes, CRLF rows. */
|
|
748
|
+
function parseCsv(text) {
|
|
749
|
+
const rows = [];
|
|
750
|
+
let row = [];
|
|
751
|
+
let field = "";
|
|
752
|
+
let quoted = false;
|
|
753
|
+
const source = text.replace(/^\uFEFF/u, "");
|
|
754
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
755
|
+
const char = source[index];
|
|
756
|
+
if (quoted) {
|
|
757
|
+
if (char === "\"") {
|
|
758
|
+
if (source[index + 1] === "\"") {
|
|
759
|
+
field += "\"";
|
|
760
|
+
index += 1;
|
|
761
|
+
} else quoted = false;
|
|
762
|
+
} else field += char;
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
765
|
+
if (char === "\"") quoted = true;
|
|
766
|
+
else if (char === ",") {
|
|
767
|
+
row.push(field);
|
|
768
|
+
field = "";
|
|
769
|
+
} else if (char === "\r") continue;
|
|
770
|
+
else if (char === "\n") {
|
|
771
|
+
row.push(field);
|
|
772
|
+
rows.push(row);
|
|
773
|
+
row = [];
|
|
774
|
+
field = "";
|
|
775
|
+
} else field += char;
|
|
776
|
+
}
|
|
777
|
+
if (field !== "" || row.length > 0) {
|
|
778
|
+
row.push(field);
|
|
779
|
+
rows.push(row);
|
|
780
|
+
}
|
|
781
|
+
return rows.filter((cells) => cells.some((cell) => cell.trim() !== ""));
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Group KiCad's per-reference BOM rows.
|
|
785
|
+
*
|
|
786
|
+
* Identity is every column except the reference and quantity columns, so a
|
|
787
|
+
* different MPN or a DNP flag always produces a separate line; ordering follows
|
|
788
|
+
* the first reference seen, which keeps the table stable between reads.
|
|
789
|
+
*/
|
|
790
|
+
function groupBomRows(table) {
|
|
791
|
+
const [header, ...body] = table;
|
|
792
|
+
if (header === void 0) return [];
|
|
793
|
+
const columns = header.map((cell) => cell.trim());
|
|
794
|
+
const referenceIndex = columns.findIndex((cell) => /^reference$/iu.test(cell));
|
|
795
|
+
const quantityIndex = columns.findIndex((cell) => /^quantity$/iu.test(cell));
|
|
796
|
+
const valueIndex = columns.findIndex((cell) => /^value$/iu.test(cell));
|
|
797
|
+
const footprintIndex = columns.findIndex((cell) => /^footprint$/iu.test(cell));
|
|
798
|
+
const dnpIndex = columns.findIndex((cell) => /^dnp$/iu.test(cell));
|
|
799
|
+
const groups = /* @__PURE__ */ new Map();
|
|
800
|
+
for (const cells of body) {
|
|
801
|
+
const reference = referenceIndex === -1 ? "" : (cells[referenceIndex] ?? "").trim();
|
|
802
|
+
if (reference === "") continue;
|
|
803
|
+
const fields = {};
|
|
804
|
+
columns.forEach((column, index) => {
|
|
805
|
+
if (index === referenceIndex || index === quantityIndex || index === valueIndex || index === footprintIndex || index === dnpIndex) return;
|
|
806
|
+
const text = (cells[index] ?? "").trim();
|
|
807
|
+
if (text !== "") fields[column] = text;
|
|
808
|
+
});
|
|
809
|
+
const dnpText = dnpIndex === -1 ? "" : (cells[dnpIndex] ?? "").trim();
|
|
810
|
+
const dnp = /^(1|true|yes|dnp|x)$/iu.test(dnpText);
|
|
811
|
+
const identity = JSON.stringify([
|
|
812
|
+
valueIndex === -1 ? "" : (cells[valueIndex] ?? "").trim(),
|
|
813
|
+
footprintIndex === -1 ? "" : (cells[footprintIndex] ?? "").trim(),
|
|
814
|
+
dnp,
|
|
815
|
+
Object.fromEntries(Object.entries(fields).sort(([a], [b]) => a.localeCompare(b)))
|
|
816
|
+
]);
|
|
817
|
+
const group = groups.get(identity) ?? {
|
|
818
|
+
references: [],
|
|
819
|
+
fields,
|
|
820
|
+
dnp
|
|
821
|
+
};
|
|
822
|
+
group.references.push(reference);
|
|
823
|
+
groups.set(identity, group);
|
|
824
|
+
}
|
|
825
|
+
return [...groups.entries()].map(([identity, group]) => {
|
|
826
|
+
const [value, footprint, dnp] = JSON.parse(identity);
|
|
827
|
+
return {
|
|
828
|
+
references: group.references,
|
|
829
|
+
quantity: group.references.length,
|
|
830
|
+
value,
|
|
831
|
+
footprint,
|
|
832
|
+
dnp,
|
|
833
|
+
fields: group.fields
|
|
834
|
+
};
|
|
835
|
+
});
|
|
836
|
+
}
|
|
376
837
|
//#endregion
|
|
377
|
-
export { HardwareArtifactService };
|
|
838
|
+
export { HardwareArtifactService, groupBomRows, parseCsv };
|