@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/lib/index.d.mts +61 -8
- package/lib/index.mjs +2610 -6
- package/lib/routes-D78ML_ef.d.mts +438 -0
- package/lib/routes.d.mts +2 -18
- package/lib/routes.mjs +156 -41
- package/lib/{service-CtVn7z8b.d.mts → service-BGecln85.d.mts} +119 -28
- package/lib/{service-Yrc2C_eo.mjs → service-Bo58tzXv.mjs} +570 -167
- package/lib/service.d.mts +1 -1
- package/lib/service.mjs +1 -1
- package/package.json +2 -1
- package/src/index.ts +124 -5
- package/src/order.ts +22 -0
- package/src/package.ts +282 -0
- package/src/routes.ts +127 -48
- package/src/service.ts +1635 -1651
- package/src/toolchain/dialog.ts +240 -0
- package/src/toolchain/discovery.ts +266 -0
- package/src/toolchain/index.ts +36 -0
- package/src/toolchain/install.ts +430 -0
- package/src/toolchain/lzma.ts +384 -0
- package/src/toolchain/manager.ts +596 -0
- package/src/toolchain/manifest.ts +234 -0
- package/src/toolchain/resolve.ts +325 -0
- package/src/toolchain/zip.ts +495 -0
- package/src/tools.ts +470 -0
package/lib/index.mjs
CHANGED
|
@@ -1,6 +1,2520 @@
|
|
|
1
|
-
import { HARDWARE_ROUTE_PREFIX, createHardwareHandler } from "./routes.mjs";
|
|
2
|
-
import {
|
|
1
|
+
import { HARDWARE_ROUTE_PREFIX, TOOLCHAIN_ROUTE_PREFIX, createHardwareHandler } from "./routes.mjs";
|
|
2
|
+
import { A as snapTraceTier, C as positionsCsv, D as smtOrderUrlFromBackend, E as smtOrderUrl, O as snapHoleTier, S as pcbOrderUrl, T as smtOrderForm, _ as orderBomCsv, a as installRootFromExecutable, b as parsePositions, c as normalizeVersion, d as validateFabricationPackage, f as validationSummary, g as ORDER_SOURCE_TID, h as ORDER_PATHS, i as canonicalPath, k as snapThickness, l as resolveToolchain, m as DEFAULT_ORDER_PAGE_BASE, o as installationRootOf, p as DEFAULT_ORDER_BASE_URL, s as label, t as HardwareArtifactService, u as expectedCopperLayers, v as orderBomRows, w as readBoardFacts, x as pcbOrderForm, y as orderIdsFromUrl } from "./service-Bo58tzXv.mjs";
|
|
3
3
|
import Schema from "@deepseek-ai/schemastery";
|
|
4
|
+
import { createReadStream, createWriteStream, existsSync, readdirSync, statSync } from "node:fs";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
11
|
+
import { Readable, Transform } from "node:stream";
|
|
12
|
+
import { pipeline } from "node:stream/promises";
|
|
13
|
+
import { createInflateRaw } from "node:zlib";
|
|
14
|
+
//#region src/tools.ts
|
|
15
|
+
/**
|
|
16
|
+
* Agent tools for `@huaqiu/hardware-artifacts`.
|
|
17
|
+
*
|
|
18
|
+
* hardware_projects which projects/boards this workspace has, and
|
|
19
|
+
* whether a `kicad-cli` can export from them
|
|
20
|
+
* hardware_bom the grouped BOM of one root schematic
|
|
21
|
+
* hardware_fabricate gerber + drill (+ assembly inputs), validated
|
|
22
|
+
* hardware_place_pcb_order upload the package and enter the hqpcb order flow
|
|
23
|
+
* hardware_place_smt_order the same for assembly (board zip + BOM + positions)
|
|
24
|
+
*
|
|
25
|
+
* These are the file-based path to fabrication. They take a path — absolute
|
|
26
|
+
* anywhere on this machine, or relative to the session workspace — and run
|
|
27
|
+
* `kicad-cli` in the board's own directory — no HQ Edge, no open PCB editor, no
|
|
28
|
+
* live KiCad IPC, and no workspace authorization step: the user is the owner of
|
|
29
|
+
* the machine, and making them prove which directory their own board is in is
|
|
30
|
+
* how a working order turned into `403 artifact is outside the authorized
|
|
31
|
+
* workspace`.
|
|
32
|
+
*
|
|
33
|
+
* Every name is prefixed with this plugin's own `hardware_` namespace. The
|
|
34
|
+
* order tools deliberately do not reuse `@huaqiu/dsh-tool-quote`'s bare
|
|
35
|
+
* `place_pcb_order`/`place_smt_order`: that plugin drives the EDA host's own
|
|
36
|
+
* action, this one runs the file-based path, and two plugins registering one
|
|
37
|
+
* name would collide in the tool registry if a profile ever mounted both.
|
|
38
|
+
*
|
|
39
|
+
* The two order tools call the same `service.placeOrder` the panel's
|
|
40
|
+
* `/hardware/order/*` routes call, so this one package owns both the route and
|
|
41
|
+
* the agent tool for the same action instead of splitting the order backend
|
|
42
|
+
* across two plugins. Creating a purchase is a human decision, so the tools
|
|
43
|
+
* carry the route's own guard — a required `confirm: true` — and the service
|
|
44
|
+
* refuses a package that failed validation before anything is uploaded.
|
|
45
|
+
*
|
|
46
|
+
* Every tool answers with one `{ ok, ... }` JSON value. A prepared package that
|
|
47
|
+
* fails validation is still a successful call with `ok: false` and the issues:
|
|
48
|
+
* the export ran, the judgement is the finding, and the agent has to relay it
|
|
49
|
+
* rather than retry.
|
|
50
|
+
*
|
|
51
|
+
* @module
|
|
52
|
+
*/
|
|
53
|
+
function asJson(value) {
|
|
54
|
+
return JSON.parse(JSON.stringify(value));
|
|
55
|
+
}
|
|
56
|
+
/** The DSH session one execution belongs to, spelled however the host spells it. */
|
|
57
|
+
function sessionIdOf(exec) {
|
|
58
|
+
const e = exec;
|
|
59
|
+
return e?.sessionId ?? e?.session?.id ?? e?.context?.sessionId;
|
|
60
|
+
}
|
|
61
|
+
/** Resolve the scan root: the session workspace, then the process directory. */
|
|
62
|
+
async function workspaceOf(env, exec) {
|
|
63
|
+
const sessionId = sessionIdOf(exec);
|
|
64
|
+
const declared = await env.workspaceOf(sessionId);
|
|
65
|
+
if (declared !== void 0 && declared.trim() !== "") return resolve(declared);
|
|
66
|
+
return resolve(env.defaultCwd?.() ?? process.cwd());
|
|
67
|
+
}
|
|
68
|
+
/** Resolve a caller-supplied path: absolute as given, relative against the workspace. */
|
|
69
|
+
function resolveUnder(cwd, input) {
|
|
70
|
+
const text = typeof input === "string" ? input.trim() : "";
|
|
71
|
+
if (text === "") throw new Error("path is required");
|
|
72
|
+
return isAbsolute(text) ? resolve(text) : resolve(cwd, text);
|
|
73
|
+
}
|
|
74
|
+
/** Compact one project for the model: identity and paths, no per-artifact noise. */
|
|
75
|
+
function projectJson(project, limit = 20) {
|
|
76
|
+
return {
|
|
77
|
+
name: project.name,
|
|
78
|
+
path: project.path,
|
|
79
|
+
...project.defaultBoard === void 0 ? {} : { defaultBoard: project.defaultBoard },
|
|
80
|
+
...project.rootSheet === void 0 ? {} : { rootSheet: project.rootSheet.path },
|
|
81
|
+
...project.schematic === void 0 ? {} : { schematic: project.schematic.path },
|
|
82
|
+
boards: project.boards.slice(0, limit).map((board) => board.path),
|
|
83
|
+
...project.boards.length > limit ? { boardsTruncated: project.boards.length } : {},
|
|
84
|
+
selectionRequired: project.selectionRequired
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function failure$1(error) {
|
|
88
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
89
|
+
const code = typeof error.code === "string" ? String(error.code) : "internal";
|
|
90
|
+
const status = error.status;
|
|
91
|
+
return {
|
|
92
|
+
ok: false,
|
|
93
|
+
error: {
|
|
94
|
+
code,
|
|
95
|
+
message,
|
|
96
|
+
...typeof status === "number" ? { status } : {}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** The refusal the order routes and the order tools share. */
|
|
101
|
+
function confirmationRequired(kind) {
|
|
102
|
+
return {
|
|
103
|
+
ok: false,
|
|
104
|
+
error: {
|
|
105
|
+
code: "confirmation-required",
|
|
106
|
+
message: kind === "pcb" ? "placing an order uploads the board files and requires explicit confirmation" : "placing an assembly order uploads the board, BOM and positions and requires explicit confirmation"
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Compact one placed order for the model: the flow's outcome, not the upload. */
|
|
111
|
+
function placedOrderJson(placed) {
|
|
112
|
+
return asJson({
|
|
113
|
+
ok: true,
|
|
114
|
+
kind: placed.kind,
|
|
115
|
+
orderUrl: placed.orderUrl,
|
|
116
|
+
status: placed.status,
|
|
117
|
+
message: placed.message,
|
|
118
|
+
launched: placed.launched,
|
|
119
|
+
endpoint: placed.endpoint,
|
|
120
|
+
facts: placed.facts,
|
|
121
|
+
archive: placed.archive,
|
|
122
|
+
validation: placed.validation,
|
|
123
|
+
...placed.assembly === void 0 ? {} : { assembly: placed.assembly }
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
function createHardwareTools(env) {
|
|
127
|
+
const { service } = env;
|
|
128
|
+
return [
|
|
129
|
+
defineTool({
|
|
130
|
+
name: "hardware_projects",
|
|
131
|
+
description: "List the hardware projects and boards a directory contains, and whether a KiCad CLI is available to export from them. Convenience only: every other tool takes a path directly, so this is never a required first step. Use it when the user asks what can be manufactured, and before hardware_fabricate when the board path is not already known. Reads the workspace only — no KiCad process is started. Returns project paths, their boards, the deterministic default board (only when ownership is unambiguous), and the resolved kicad-cli path/version. An `issue.code` of \"selection-required\" means the workspace holds several projects and the user must choose one; never pick for them.",
|
|
132
|
+
parameters: {
|
|
133
|
+
project: {
|
|
134
|
+
type: "string",
|
|
135
|
+
description: "Project (.kicad_pro) path, absolute or relative to the workspace. Omit to discover every project in the workspace."
|
|
136
|
+
},
|
|
137
|
+
path: {
|
|
138
|
+
type: "string",
|
|
139
|
+
description: "Workspace directory to scan. Defaults to the session working directory."
|
|
140
|
+
}
|
|
141
|
+
},
|
|
142
|
+
output: {
|
|
143
|
+
schema: { type: "json" },
|
|
144
|
+
render: renderJson
|
|
145
|
+
},
|
|
146
|
+
async execute(args, exec) {
|
|
147
|
+
const a = args ?? {};
|
|
148
|
+
try {
|
|
149
|
+
const cwd = await workspaceOf(env, exec);
|
|
150
|
+
const base = a.path === void 0 ? cwd : resolveUnder(cwd, a.path);
|
|
151
|
+
const sessionId = sessionIdOf(exec);
|
|
152
|
+
const discovery = service.discover(base, typeof a.project === "string" ? a.project : void 0, sessionId);
|
|
153
|
+
const installed = service.installations().kicad;
|
|
154
|
+
return asJson({
|
|
155
|
+
ok: true,
|
|
156
|
+
cwd: discovery.cwd,
|
|
157
|
+
...discovery.issue === void 0 ? {} : { issue: discovery.issue },
|
|
158
|
+
projects: discovery.projects.slice(0, 20).map((project) => projectJson(project)),
|
|
159
|
+
...discovery.projects.length > 20 ? { projectsTruncated: discovery.projects.length } : {},
|
|
160
|
+
...discovery.selected === void 0 ? {} : { selected: projectJson(discovery.selected) },
|
|
161
|
+
kicad: {
|
|
162
|
+
configured: installed.configured,
|
|
163
|
+
...installed.cli === void 0 ? {} : { cli: installed.cli },
|
|
164
|
+
...installed.version === void 0 ? {} : { version: installed.version },
|
|
165
|
+
...installed.error === void 0 ? {} : { error: installed.error }
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
} catch (error) {
|
|
169
|
+
return failure$1(error);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}),
|
|
173
|
+
defineTool({
|
|
174
|
+
name: "hardware_bom",
|
|
175
|
+
description: "Read the bill of materials of one KiCad root schematic, grouped by part. Uses KiCad's own `kicad-cli sch export bom`, so the rows are what KiCad itself reports — references, value, footprint, quantity and DNP, plus any custom fields (MPN, Manufacturer). Use when the user asks what parts a board needs, for a cost estimate, or to sanity-check assembly. Requires a configured KiCad CLI; returns its error otherwise.",
|
|
176
|
+
parameters: { path: {
|
|
177
|
+
type: "string",
|
|
178
|
+
required: true,
|
|
179
|
+
description: "Root schematic (.kicad_sch) path, absolute or relative to the workspace. A child sheet returns that sheet only."
|
|
180
|
+
} },
|
|
181
|
+
output: {
|
|
182
|
+
schema: { type: "json" },
|
|
183
|
+
render: renderJson
|
|
184
|
+
},
|
|
185
|
+
async execute(args, exec) {
|
|
186
|
+
try {
|
|
187
|
+
const artifactPath = resolveUnder(await workspaceOf(env, exec), args?.path);
|
|
188
|
+
const sessionId = sessionIdOf(exec);
|
|
189
|
+
const bom = await service.exportBom({
|
|
190
|
+
artifactPath,
|
|
191
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
192
|
+
...exec.signal === void 0 ? {} : { signal: exec.signal }
|
|
193
|
+
});
|
|
194
|
+
return asJson({
|
|
195
|
+
ok: true,
|
|
196
|
+
path: bom.path,
|
|
197
|
+
revision: bom.revision,
|
|
198
|
+
cached: bom.cached,
|
|
199
|
+
source: bom.source,
|
|
200
|
+
lines: bom.rows.length,
|
|
201
|
+
parts: bom.rows.reduce((total, row) => total + row.quantity, 0),
|
|
202
|
+
rows: bom.rows.map((row) => ({
|
|
203
|
+
references: row.references,
|
|
204
|
+
quantity: row.quantity,
|
|
205
|
+
value: row.value,
|
|
206
|
+
footprint: row.footprint,
|
|
207
|
+
dnp: row.dnp,
|
|
208
|
+
fields: row.fields
|
|
209
|
+
}))
|
|
210
|
+
});
|
|
211
|
+
} catch (error) {
|
|
212
|
+
return failure$1(error);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}),
|
|
216
|
+
defineTool({
|
|
217
|
+
name: "hardware_fabricate",
|
|
218
|
+
description: "Export and validate the fabrication package for one .kicad_pcb: gerbers, Excellon drill, and — when a schematic is given — the assembly inputs (positions CSV + grouped BOM). Runs `kicad-cli` in the board directory; no PCB editor needs to be open and no HQ Edge service is involved. Returns the board facts read from the file (layers, outline size, thickness, min track/hole, copper weight), the archive manifest, and a `validation` with `ok` plus `errors`/`warnings`. `ok: false` means the package must not be ordered (for example a copper layer that was not plotted, or no board outline): report the issues instead of retrying. Pass `output_dir` when the user wants the files on disk.",
|
|
219
|
+
parameters: {
|
|
220
|
+
path: {
|
|
221
|
+
type: "string",
|
|
222
|
+
required: true,
|
|
223
|
+
description: "Board (.kicad_pcb) path, absolute or relative to the workspace."
|
|
224
|
+
},
|
|
225
|
+
schematic: {
|
|
226
|
+
type: "string",
|
|
227
|
+
description: "Root schematic (.kicad_sch) to add assembly inputs (positions + BOM). Required for an SMT order; omit for fabrication only."
|
|
228
|
+
},
|
|
229
|
+
output_dir: {
|
|
230
|
+
type: "string",
|
|
231
|
+
description: "Directory to write the package into (created when missing): `<board>.zip`, plus positions/BOM CSVs when assembly inputs were produced. Omit to export and validate without writing files."
|
|
232
|
+
}
|
|
233
|
+
},
|
|
234
|
+
output: {
|
|
235
|
+
schema: { type: "json" },
|
|
236
|
+
render: renderJson
|
|
237
|
+
},
|
|
238
|
+
async execute(args, exec) {
|
|
239
|
+
const a = args ?? {};
|
|
240
|
+
try {
|
|
241
|
+
const cwd = await workspaceOf(env, exec);
|
|
242
|
+
const boardPath = resolveUnder(cwd, a.path);
|
|
243
|
+
const sessionId = sessionIdOf(exec);
|
|
244
|
+
const directory = a.output_dir === void 0 ? void 0 : resolveUnder(cwd, a.output_dir);
|
|
245
|
+
const prepared = await service.fabricate({
|
|
246
|
+
boardPath,
|
|
247
|
+
...typeof a.schematic === "string" ? { schematicPath: resolveUnder(cwd, a.schematic) } : {},
|
|
248
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
249
|
+
...exec.signal === void 0 ? {} : { signal: exec.signal }
|
|
250
|
+
});
|
|
251
|
+
const written = directory === void 0 ? void 0 : service.writePackage(prepared, directory);
|
|
252
|
+
return asJson({
|
|
253
|
+
ok: prepared.validation.ok,
|
|
254
|
+
boardPath: prepared.boardPath,
|
|
255
|
+
revision: prepared.revision,
|
|
256
|
+
generatedAt: prepared.generatedAt,
|
|
257
|
+
facts: prepared.facts,
|
|
258
|
+
archive: prepared.archive,
|
|
259
|
+
validation: prepared.validation,
|
|
260
|
+
...prepared.assembly === void 0 ? {} : { assembly: prepared.assembly },
|
|
261
|
+
...written === void 0 ? {} : { written }
|
|
262
|
+
});
|
|
263
|
+
} catch (error) {
|
|
264
|
+
return failure$1(error);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}),
|
|
268
|
+
defineTool({
|
|
269
|
+
name: "hardware_place_pcb_order",
|
|
270
|
+
description: "Place a bare-PCB (fabrication-only) order: fabricate and validate the package from one .kicad_pcb, upload it to the configured Huaqiu order endpoint, and return the order page URL — the same flow the Hardware panel's order action runs, through the same service. Use only when the user has clearly asked to order/prototype this board (\"下单\", \"place order\", \"打样\"): this uploads the board files and creates a real purchase, so `confirm` must be true. Refused before any upload when the user is not signed in to Huaqiu (error code \"unauthorized\") or when the package fails validation (error code \"package-invalid\"); relay either instead of retrying. The order origin is this plugin's configured setting (default eda.cn) — there is no region parameter. The PCB order uploads the gerber/drill archive only; use hardware_place_smt_order when assembly inputs matter. Returns { orderUrl, status, message, facts, archive, validation }. The DSH client opens orderUrl in its own Browser tab as soon as this result arrives; do not paste the URL or ask the user to click it. `status` is \"ready\" — the page is prepared, and nothing is bought until the user finishes there.",
|
|
271
|
+
parameters: {
|
|
272
|
+
path: {
|
|
273
|
+
type: "string",
|
|
274
|
+
required: true,
|
|
275
|
+
description: "Board (.kicad_pcb) path, absolute or relative to the workspace."
|
|
276
|
+
},
|
|
277
|
+
confirm: {
|
|
278
|
+
type: "boolean",
|
|
279
|
+
required: true,
|
|
280
|
+
description: "Must be true. The user's explicit request to order this board is the confirmation; passing false (or omitting it) refuses the call without uploading anything."
|
|
281
|
+
},
|
|
282
|
+
quantity: {
|
|
283
|
+
type: "number",
|
|
284
|
+
description: "Board quantity for the order form. Omit to let the endpoint use its default."
|
|
285
|
+
}
|
|
286
|
+
},
|
|
287
|
+
output: {
|
|
288
|
+
schema: { type: "json" },
|
|
289
|
+
render: renderJson
|
|
290
|
+
},
|
|
291
|
+
async execute(args, exec) {
|
|
292
|
+
const a = args ?? {};
|
|
293
|
+
try {
|
|
294
|
+
if (a.confirm !== true) return confirmationRequired("pcb");
|
|
295
|
+
const cwd = await workspaceOf(env, exec);
|
|
296
|
+
const sessionId = sessionIdOf(exec);
|
|
297
|
+
return placedOrderJson(await service.placeOrder({
|
|
298
|
+
kind: "pcb",
|
|
299
|
+
boardPath: resolveUnder(cwd, a.path),
|
|
300
|
+
...typeof a.quantity === "number" ? { quantity: a.quantity } : {},
|
|
301
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
302
|
+
...exec.signal === void 0 ? {} : { signal: exec.signal }
|
|
303
|
+
}));
|
|
304
|
+
} catch (error) {
|
|
305
|
+
return failure$1(error);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}),
|
|
309
|
+
defineTool({
|
|
310
|
+
name: "hardware_place_smt_order",
|
|
311
|
+
description: "Place an SMT assembly order: fabricate the package plus the assembly inputs (board zip, component positions and BOM from the root schematic), upload them to the configured Huaqiu order endpoint, and return the order page URL. Same flow, service and guards as hardware_place_pcb_order, but `schematic` is required — without it there is nothing to assemble from. Requires the user's explicit request to order assembly for this board, so `confirm` must be true. Refused before any upload when the user is not signed in to Huaqiu (error code \"unauthorized\") or when the package fails validation (error code \"package-invalid\"). The order origin is this plugin's configured setting (default eda.cn) — there is no region parameter.",
|
|
312
|
+
parameters: {
|
|
313
|
+
path: {
|
|
314
|
+
type: "string",
|
|
315
|
+
required: true,
|
|
316
|
+
description: "Board (.kicad_pcb) path, absolute or relative to the workspace."
|
|
317
|
+
},
|
|
318
|
+
schematic: {
|
|
319
|
+
type: "string",
|
|
320
|
+
required: true,
|
|
321
|
+
description: "Root schematic (.kicad_sch) path for the BOM. Required: the assembly endpoint needs the grouped BOM alongside the positions."
|
|
322
|
+
},
|
|
323
|
+
confirm: {
|
|
324
|
+
type: "boolean",
|
|
325
|
+
required: true,
|
|
326
|
+
description: "Must be true. The user's explicit request to order assembly for this board is the confirmation; passing false (or omitting it) refuses the call without uploading anything."
|
|
327
|
+
},
|
|
328
|
+
quantity: {
|
|
329
|
+
type: "number",
|
|
330
|
+
description: "Assembled quantity for the order form. Omit to let the endpoint use its default."
|
|
331
|
+
}
|
|
332
|
+
},
|
|
333
|
+
output: {
|
|
334
|
+
schema: { type: "json" },
|
|
335
|
+
render: renderJson
|
|
336
|
+
},
|
|
337
|
+
async execute(args, exec) {
|
|
338
|
+
const a = args ?? {};
|
|
339
|
+
try {
|
|
340
|
+
if (a.confirm !== true) return confirmationRequired("assembly");
|
|
341
|
+
const cwd = await workspaceOf(env, exec);
|
|
342
|
+
const sessionId = sessionIdOf(exec);
|
|
343
|
+
return placedOrderJson(await service.placeOrder({
|
|
344
|
+
kind: "smt",
|
|
345
|
+
boardPath: resolveUnder(cwd, a.path),
|
|
346
|
+
schematicPath: resolveUnder(cwd, a.schematic),
|
|
347
|
+
...typeof a.quantity === "number" ? { quantity: a.quantity } : {},
|
|
348
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
349
|
+
...exec.signal === void 0 ? {} : { signal: exec.signal }
|
|
350
|
+
}));
|
|
351
|
+
} catch (error) {
|
|
352
|
+
return failure$1(error);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
})
|
|
356
|
+
];
|
|
357
|
+
}
|
|
358
|
+
/** The tool names this package registers; the bundle test asserts them. */
|
|
359
|
+
function hardwareToolNames() {
|
|
360
|
+
return [
|
|
361
|
+
"hardware_projects",
|
|
362
|
+
"hardware_bom",
|
|
363
|
+
"hardware_fabricate",
|
|
364
|
+
"hardware_place_pcb_order",
|
|
365
|
+
"hardware_place_smt_order"
|
|
366
|
+
];
|
|
367
|
+
}
|
|
368
|
+
function renderJson(_args, value) {
|
|
369
|
+
return [{
|
|
370
|
+
type: "text",
|
|
371
|
+
text: JSON.stringify(value)
|
|
372
|
+
}];
|
|
373
|
+
}
|
|
374
|
+
//#endregion
|
|
375
|
+
//#region src/toolchain/dialog.ts
|
|
376
|
+
/**
|
|
377
|
+
* A real native file chooser, owned by this plugin.
|
|
378
|
+
*
|
|
379
|
+
* The spec requires an actual OS dialog, not a simulated one (§4.5/§6.2), and
|
|
380
|
+
* the Host's own `directoryPicker` seam can only choose *directories* while this
|
|
381
|
+
* feature must also accept an executable. Rather than change a shared Host
|
|
382
|
+
* capability for one caller, the plugin drives the platform's own dialog in a
|
|
383
|
+
* child process: `IFileOpenDialog` through the Windows PowerShell host, an
|
|
384
|
+
* `NSOpenPanel` through the system JXA host, and `zenity`/`kdialog` on Linux.
|
|
385
|
+
* Nothing is rendered by the browser, and nothing is fabricated: a cancelled
|
|
386
|
+
* dialog reports cancellation.
|
|
387
|
+
*
|
|
388
|
+
* The directory-only case stays on the Host's seam (see the plugin's
|
|
389
|
+
* `browse` route), so a machine where this picker is unavailable still offers a
|
|
390
|
+
* native chooser backed by DSH itself.
|
|
391
|
+
*
|
|
392
|
+
* @module @huaqiu/hardware-artifacts/toolchain/dialog
|
|
393
|
+
*/
|
|
394
|
+
/** Default runner: a child process, never a shell (§6.2 of the runtime constraints). */
|
|
395
|
+
const defaultRunner = (command, args, options) => new Promise((resolvePromise, reject) => {
|
|
396
|
+
execFile(command, [...args], {
|
|
397
|
+
timeout: options.timeoutMs,
|
|
398
|
+
encoding: "utf8",
|
|
399
|
+
windowsHide: true,
|
|
400
|
+
shell: false,
|
|
401
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
402
|
+
}, (error, stdout, stderr) => {
|
|
403
|
+
if (error === null) {
|
|
404
|
+
resolvePromise({
|
|
405
|
+
stdout: String(stdout),
|
|
406
|
+
stderr: String(stderr),
|
|
407
|
+
exitCode: 0
|
|
408
|
+
});
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const code = error.code;
|
|
412
|
+
if (typeof code === "number") {
|
|
413
|
+
resolvePromise({
|
|
414
|
+
stdout: String(stdout),
|
|
415
|
+
stderr: String(stderr),
|
|
416
|
+
exitCode: code
|
|
417
|
+
});
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
reject(error);
|
|
421
|
+
});
|
|
422
|
+
});
|
|
423
|
+
/** PowerShell single-quoted literal: only `'` needs doubling. */
|
|
424
|
+
function quotePowerShell(value) {
|
|
425
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
426
|
+
}
|
|
427
|
+
/** One platform's filter string (`Windows` requires `name|pattern|name|pattern`). */
|
|
428
|
+
function windowsFilter(filters) {
|
|
429
|
+
const rows = filters.map((filter) => `${filter.name}|${filter.patterns.join(";")}`);
|
|
430
|
+
rows.push("All files (*.*)|*.*");
|
|
431
|
+
return rows.join("|");
|
|
432
|
+
}
|
|
433
|
+
/** Windows dialog script; the whole conversation runs in one child process. */
|
|
434
|
+
function windowsScript(request) {
|
|
435
|
+
return [
|
|
436
|
+
"$ErrorActionPreference = \"Stop\"",
|
|
437
|
+
"Add-Type -AssemblyName System.Windows.Forms",
|
|
438
|
+
"$dialog = New-Object System.Windows.Forms.OpenFileDialog",
|
|
439
|
+
`$dialog.Title = ${quotePowerShell(request.title)}`,
|
|
440
|
+
`$dialog.Filter = ${quotePowerShell(windowsFilter(request.filters ?? []))}`,
|
|
441
|
+
"$dialog.CheckFileExists = $true",
|
|
442
|
+
"$dialog.Multiselect = $false",
|
|
443
|
+
...request.initialDirectory === void 0 || request.initialDirectory === "" ? [] : [
|
|
444
|
+
"try {",
|
|
445
|
+
` $dialog.InitialDirectory = ${quotePowerShell(request.initialDirectory)}`,
|
|
446
|
+
"} catch { }"
|
|
447
|
+
],
|
|
448
|
+
"$owner = New-Object System.Windows.Forms.Form",
|
|
449
|
+
"$owner.TopMost = $true",
|
|
450
|
+
"$owner.ShowInTaskbar = $false",
|
|
451
|
+
"$owner.WindowState = [System.Windows.Forms.FormWindowState]::Minimized",
|
|
452
|
+
"$owner.Opacity = 0",
|
|
453
|
+
"try {",
|
|
454
|
+
" if ($dialog.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) {",
|
|
455
|
+
" [Console]::Out.WriteLine($dialog.FileName)",
|
|
456
|
+
" } else {",
|
|
457
|
+
" exit 2",
|
|
458
|
+
" }",
|
|
459
|
+
"} finally {",
|
|
460
|
+
" $owner.Dispose()",
|
|
461
|
+
"}"
|
|
462
|
+
].join("\n");
|
|
463
|
+
}
|
|
464
|
+
/** macOS `NSOpenPanel` source (JXA), with the copy encoded as JSON literals. */
|
|
465
|
+
function macPanelScript(request) {
|
|
466
|
+
return `ObjC.import('AppKit');
|
|
467
|
+
function run() {
|
|
468
|
+
var app = $.NSApplication.sharedApplication;
|
|
469
|
+
app.setActivationPolicy($.NSApplicationActivationPolicyAccessory);
|
|
470
|
+
var panel = $.NSOpenPanel.openPanel;
|
|
471
|
+
panel.canChooseFiles = true;
|
|
472
|
+
panel.canChooseDirectories = false;
|
|
473
|
+
panel.allowsMultipleSelection = false;
|
|
474
|
+
panel.message = ${JSON.stringify(request.title)};
|
|
475
|
+
var start = ${JSON.stringify(request.initialDirectory ?? "")};
|
|
476
|
+
if (start !== '') panel.directoryURL = $.NSURL.fileURLWithPath(start);
|
|
477
|
+
$.NSOperationQueue.mainQueue.addOperationWithBlock(function() {
|
|
478
|
+
app.activateIgnoringOtherApps(true);
|
|
479
|
+
});
|
|
480
|
+
if (panel.runModal !== $.NSModalResponseOK) return '';
|
|
481
|
+
var urls = panel.URLs;
|
|
482
|
+
if (urls.count < 1) return '';
|
|
483
|
+
return ObjC.unwrap(urls.objectAtIndex(0).path);
|
|
484
|
+
}`;
|
|
485
|
+
}
|
|
486
|
+
function firstLine(text) {
|
|
487
|
+
return text.replace(/[\r\n]+$/u, "").split(/\r?\n/u)[0] ?? "";
|
|
488
|
+
}
|
|
489
|
+
/** Map a missing binary into the "unsupported" verdict instead of a crash. */
|
|
490
|
+
function isMissingBinary(error) {
|
|
491
|
+
return error?.code === "ENOENT";
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Show the platform's file chooser and wait for the operator.
|
|
495
|
+
* @param request - title, filters and starting directory.
|
|
496
|
+
* @param internals - platform/runner/timeout injection.
|
|
497
|
+
* @returns the picked path, a cancellation, or an unsupported-platform notice.
|
|
498
|
+
*/
|
|
499
|
+
async function pickFile(request, internals = {}) {
|
|
500
|
+
const platform = internals.platform ?? process.platform;
|
|
501
|
+
const run = internals.run ?? defaultRunner;
|
|
502
|
+
const options = {
|
|
503
|
+
timeoutMs: internals.timeoutMs ?? 9e5,
|
|
504
|
+
...internals.signal === void 0 ? {} : { signal: internals.signal }
|
|
505
|
+
};
|
|
506
|
+
if (platform === "win32") {
|
|
507
|
+
const result = await run("powershell.exe", [
|
|
508
|
+
"-NoProfile",
|
|
509
|
+
"-NonInteractive",
|
|
510
|
+
"-STA",
|
|
511
|
+
"-WindowStyle",
|
|
512
|
+
"Hidden",
|
|
513
|
+
"-ExecutionPolicy",
|
|
514
|
+
"Bypass",
|
|
515
|
+
"-EncodedCommand",
|
|
516
|
+
Buffer.from(windowsScript(request), "utf16le").toString("base64")
|
|
517
|
+
], options);
|
|
518
|
+
if (result.exitCode === 2) return {
|
|
519
|
+
kind: "cancelled",
|
|
520
|
+
mechanism: "win32"
|
|
521
|
+
};
|
|
522
|
+
if (result.exitCode !== 0) return {
|
|
523
|
+
kind: "unsupported",
|
|
524
|
+
message: result.stderr.trim() === "" ? `dialog exited with ${String(result.exitCode)}` : result.stderr.trim()
|
|
525
|
+
};
|
|
526
|
+
const path = firstLine(result.stdout);
|
|
527
|
+
return path === "" ? {
|
|
528
|
+
kind: "cancelled",
|
|
529
|
+
mechanism: "win32"
|
|
530
|
+
} : {
|
|
531
|
+
kind: "picked",
|
|
532
|
+
path,
|
|
533
|
+
mechanism: "win32"
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
if (platform === "darwin") try {
|
|
537
|
+
const path = firstLine((await run("osascript", [
|
|
538
|
+
"-l",
|
|
539
|
+
"JavaScript",
|
|
540
|
+
"-e",
|
|
541
|
+
macPanelScript(request)
|
|
542
|
+
], options)).stdout);
|
|
543
|
+
return path === "" ? {
|
|
544
|
+
kind: "cancelled",
|
|
545
|
+
mechanism: "darwin"
|
|
546
|
+
} : {
|
|
547
|
+
kind: "picked",
|
|
548
|
+
path,
|
|
549
|
+
mechanism: "darwin"
|
|
550
|
+
};
|
|
551
|
+
} catch (error) {
|
|
552
|
+
if (isMissingBinary(error)) return {
|
|
553
|
+
kind: "unsupported",
|
|
554
|
+
message: "osascript is unavailable"
|
|
555
|
+
};
|
|
556
|
+
throw error;
|
|
557
|
+
}
|
|
558
|
+
if (platform === "linux") {
|
|
559
|
+
const filters = (request.filters ?? []).flatMap((filter) => filter.patterns.map((pattern) => `--file-filter=${filter.name} | ${pattern}`));
|
|
560
|
+
try {
|
|
561
|
+
const result = await run("zenity", [
|
|
562
|
+
"--file-selection",
|
|
563
|
+
`--title=${request.title}`,
|
|
564
|
+
...request.initialDirectory === void 0 || request.initialDirectory === "" ? [] : [`--filename=${request.initialDirectory}`],
|
|
565
|
+
...filters
|
|
566
|
+
], options);
|
|
567
|
+
if (result.exitCode === 1) return {
|
|
568
|
+
kind: "cancelled",
|
|
569
|
+
mechanism: "zenity"
|
|
570
|
+
};
|
|
571
|
+
const path = firstLine(result.stdout);
|
|
572
|
+
return path === "" ? {
|
|
573
|
+
kind: "cancelled",
|
|
574
|
+
mechanism: "zenity"
|
|
575
|
+
} : {
|
|
576
|
+
kind: "picked",
|
|
577
|
+
path,
|
|
578
|
+
mechanism: "zenity"
|
|
579
|
+
};
|
|
580
|
+
} catch (error) {
|
|
581
|
+
if (!isMissingBinary(error)) throw error;
|
|
582
|
+
}
|
|
583
|
+
try {
|
|
584
|
+
const result = await run("kdialog", [
|
|
585
|
+
"--title",
|
|
586
|
+
request.title,
|
|
587
|
+
...request.initialDirectory === void 0 || request.initialDirectory === "" ? [] : [request.initialDirectory],
|
|
588
|
+
...(request.filters ?? []).flatMap((filter) => filter.patterns)
|
|
589
|
+
], options);
|
|
590
|
+
if (result.exitCode === 1) return {
|
|
591
|
+
kind: "cancelled",
|
|
592
|
+
mechanism: "kdialog"
|
|
593
|
+
};
|
|
594
|
+
const path = firstLine(result.stdout);
|
|
595
|
+
return path === "" ? {
|
|
596
|
+
kind: "cancelled",
|
|
597
|
+
mechanism: "kdialog"
|
|
598
|
+
} : {
|
|
599
|
+
kind: "picked",
|
|
600
|
+
path,
|
|
601
|
+
mechanism: "kdialog"
|
|
602
|
+
};
|
|
603
|
+
} catch (error) {
|
|
604
|
+
if (isMissingBinary(error)) return {
|
|
605
|
+
kind: "unsupported",
|
|
606
|
+
message: "no native file chooser is installed (zenity or kdialog)"
|
|
607
|
+
};
|
|
608
|
+
throw error;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return {
|
|
612
|
+
kind: "unsupported",
|
|
613
|
+
message: `no native file chooser on ${platform}`
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
/** Filters the two toolchains accept, per §6.2's suggested list. */
|
|
617
|
+
const TOOLCHAIN_FILTERS = Object.freeze({
|
|
618
|
+
kicad: Object.freeze([{
|
|
619
|
+
name: "KiCad CLI (kicad-cli.exe)",
|
|
620
|
+
patterns: Object.freeze(["kicad-cli.exe", "kicad-cli"])
|
|
621
|
+
}]),
|
|
622
|
+
solidcraft: Object.freeze([{
|
|
623
|
+
name: "SolidCraft (solidcraft*.exe)",
|
|
624
|
+
patterns: Object.freeze([
|
|
625
|
+
"solidcraft.exe",
|
|
626
|
+
"solidcraft-cli.exe",
|
|
627
|
+
"solidcraft"
|
|
628
|
+
])
|
|
629
|
+
}])
|
|
630
|
+
});
|
|
631
|
+
//#endregion
|
|
632
|
+
//#region src/toolchain/discovery.ts
|
|
633
|
+
/**
|
|
634
|
+
* Bounded background discovery of already-installed toolchains.
|
|
635
|
+
*
|
|
636
|
+
* Discovery exists so a user who already has KiCad is never asked where it is,
|
|
637
|
+
* and it must not cost anything if it finds nothing: the candidate set is a
|
|
638
|
+
* short list of installation conventions (§5.1), each candidate is one `stat`
|
|
639
|
+
* plus at most one version probe, and the whole run happens off the request
|
|
640
|
+
* that started it (§4.2/§5.2). Nothing here recurses a drive.
|
|
641
|
+
*
|
|
642
|
+
* @module @huaqiu/hardware-artifacts/toolchain/discovery
|
|
643
|
+
*/
|
|
644
|
+
/** How many version-suffixed subdirectories one install prefix may contribute. */
|
|
645
|
+
const MAX_VERSIONED_DIRECTORIES = 3;
|
|
646
|
+
function isDirectory(path, internals) {
|
|
647
|
+
if (internals.exists !== void 0) return internals.exists(path);
|
|
648
|
+
try {
|
|
649
|
+
return statSync(path).isDirectory();
|
|
650
|
+
} catch {
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
function listDirectories(path, internals) {
|
|
655
|
+
if (internals.readdir !== void 0) return [...internals.readdir(path)];
|
|
656
|
+
try {
|
|
657
|
+
return readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
658
|
+
} catch {
|
|
659
|
+
return [];
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
/** Version-ordered directory names, newest first, capped. */
|
|
663
|
+
function versionedDirectories(path, internals) {
|
|
664
|
+
const names = listDirectories(path, internals).filter((name) => /^\d/u.test(name));
|
|
665
|
+
names.sort((left, right) => compareVersions$1(right, left));
|
|
666
|
+
return names.slice(0, MAX_VERSIONED_DIRECTORIES);
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Installation roots discovery should look at, most specific first.
|
|
670
|
+
*
|
|
671
|
+
* The managed root comes first because a distribution the product itself
|
|
672
|
+
* installed is the one it can reason about; system and user-local conventions
|
|
673
|
+
* follow, and only their version-suffixed children are considered (§5.1). This
|
|
674
|
+
* is a fixed, documented list — not a scan (§5.2).
|
|
675
|
+
* @param tool - which toolchain.
|
|
676
|
+
* @param environment - platform/env/managed root/home.
|
|
677
|
+
* @param internals - filesystem injection.
|
|
678
|
+
* @returns candidate roots in precedence order, de-duplicated.
|
|
679
|
+
*/
|
|
680
|
+
function candidateRoots(tool, environment, internals = {}) {
|
|
681
|
+
const platform = environment.platform ?? process.platform;
|
|
682
|
+
const env = environment.env ?? process.env;
|
|
683
|
+
const roots = [];
|
|
684
|
+
const push = (path, origin) => {
|
|
685
|
+
roots.push({
|
|
686
|
+
path: resolve(path),
|
|
687
|
+
origin
|
|
688
|
+
});
|
|
689
|
+
};
|
|
690
|
+
const managed = join(environment.managedRoot, tool);
|
|
691
|
+
for (const version of versionedDirectories(managed, internals)) push(join(managed, version), "managed");
|
|
692
|
+
if (isDirectory(managed, internals)) push(managed, "managed");
|
|
693
|
+
const toolDirectory = tool === "kicad" ? "KiCad" : "SolidCraft";
|
|
694
|
+
if (platform === "win32") {
|
|
695
|
+
for (const prefix of [env.ProgramFiles, env["ProgramFiles(x86)"]]) {
|
|
696
|
+
if (prefix === void 0 || prefix === "") continue;
|
|
697
|
+
const base = join(prefix, toolDirectory);
|
|
698
|
+
for (const version of versionedDirectories(base, internals)) push(join(base, version), "system");
|
|
699
|
+
if (tool === "solidcraft" && isDirectory(base, internals)) push(base, "system");
|
|
700
|
+
}
|
|
701
|
+
const local = env.LOCALAPPDATA;
|
|
702
|
+
if (local !== void 0 && local !== "") {
|
|
703
|
+
const base = join(local, "Programs", toolDirectory);
|
|
704
|
+
for (const version of versionedDirectories(base, internals)) push(join(base, version), "user-local");
|
|
705
|
+
if (tool === "solidcraft" && isDirectory(base, internals)) push(base, "user-local");
|
|
706
|
+
}
|
|
707
|
+
} else if (platform === "darwin") for (const base of ["/Applications", join(environment.home, "Applications")]) {
|
|
708
|
+
const origin = base.startsWith("/Applications") ? "system" : "user-local";
|
|
709
|
+
push(join(base, toolDirectory), origin);
|
|
710
|
+
push(join(base, `${toolDirectory}.app`), origin);
|
|
711
|
+
}
|
|
712
|
+
else {
|
|
713
|
+
const bases = [
|
|
714
|
+
{
|
|
715
|
+
base: "/usr/local",
|
|
716
|
+
origin: "system"
|
|
717
|
+
},
|
|
718
|
+
{
|
|
719
|
+
base: "/usr",
|
|
720
|
+
origin: "system"
|
|
721
|
+
},
|
|
722
|
+
{
|
|
723
|
+
base: join(environment.home, ".local"),
|
|
724
|
+
origin: "user-local"
|
|
725
|
+
}
|
|
726
|
+
];
|
|
727
|
+
for (const { base, origin } of bases) {
|
|
728
|
+
push(join(base, "bin"), origin);
|
|
729
|
+
push(join(base, tool === "kicad" ? "kicad" : "solidcraft"), origin);
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
const unique = [];
|
|
733
|
+
const seen = /* @__PURE__ */ new Set();
|
|
734
|
+
for (const root of roots) {
|
|
735
|
+
const key = root.path.toLowerCase();
|
|
736
|
+
if (seen.has(key)) continue;
|
|
737
|
+
seen.add(key);
|
|
738
|
+
unique.push(root);
|
|
739
|
+
}
|
|
740
|
+
return unique;
|
|
741
|
+
}
|
|
742
|
+
/**
|
|
743
|
+
* Validate candidates and choose one deterministically.
|
|
744
|
+
*
|
|
745
|
+
* Policy (§5.4/§5.2): a managed installation outranks a system one, then the
|
|
746
|
+
* highest reported version wins, then candidate order. A candidate is valid
|
|
747
|
+
* only when its executable answered a version probe, so a stale directory that
|
|
748
|
+
* merely exists never wins.
|
|
749
|
+
* @param tool - which toolchain.
|
|
750
|
+
* @param roots - candidate roots in precedence order.
|
|
751
|
+
* @param internals - probe/fs injection.
|
|
752
|
+
* @returns every candidate's verdict, plus the one discovery would configure.
|
|
753
|
+
*/
|
|
754
|
+
function validateCandidates(tool, roots, internals = {}) {
|
|
755
|
+
const candidates = [];
|
|
756
|
+
for (const root of roots) {
|
|
757
|
+
const resolution = resolveToolchain(tool, root.path, {
|
|
758
|
+
...internals.exists === void 0 ? {} : { exists: internals.exists },
|
|
759
|
+
...internals.probeVersion === void 0 ? {} : { probeVersion: (executable) => internals.probeVersion?.(executable, tool) }
|
|
760
|
+
});
|
|
761
|
+
const executable = resolution.cli ?? resolution.app;
|
|
762
|
+
const effective = executable === void 0 ? root.path : installRootFromExecutable(executable);
|
|
763
|
+
candidates.push({
|
|
764
|
+
path: effective,
|
|
765
|
+
origin: root.origin,
|
|
766
|
+
valid: resolution.configured,
|
|
767
|
+
...resolution.version === void 0 ? {} : { version: resolution.version },
|
|
768
|
+
...resolution.cli === void 0 ? {} : { cli: resolution.cli },
|
|
769
|
+
...resolution.error === void 0 ? {} : { error: resolution.error }
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
const selected = [...candidates.filter((candidate) => candidate.valid)].sort((left, right) => {
|
|
773
|
+
if (left.origin !== right.origin) {
|
|
774
|
+
const weight = (origin) => origin === "managed" ? 0 : origin === "system" ? 1 : 2;
|
|
775
|
+
return weight(left.origin) - weight(right.origin);
|
|
776
|
+
}
|
|
777
|
+
const byVersion = compareVersions$1(right.version, left.version);
|
|
778
|
+
return byVersion !== 0 ? byVersion : candidates.indexOf(left) - candidates.indexOf(right);
|
|
779
|
+
})[0];
|
|
780
|
+
return {
|
|
781
|
+
candidates,
|
|
782
|
+
...selected === void 0 ? {} : { selected }
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
/** Compare two version strings, tolerant of packaging suffixes. */
|
|
786
|
+
function compareVersions$1(left, right) {
|
|
787
|
+
if (left === void 0 || right === void 0) return left === right ? 0 : left === void 0 ? -1 : 1;
|
|
788
|
+
const split = (value) => value.split(/[.+-]/u).map((part) => /^\d+$/u.test(part) ? Number(part) : part);
|
|
789
|
+
const a = split(left);
|
|
790
|
+
const b = split(right);
|
|
791
|
+
for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
|
|
792
|
+
const x = a[index];
|
|
793
|
+
const y = b[index];
|
|
794
|
+
if (x === void 0) return -1;
|
|
795
|
+
if (y === void 0) return 1;
|
|
796
|
+
if (typeof x === "number" && typeof y === "number") {
|
|
797
|
+
if (x !== y) return x - y;
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
const sx = String(x);
|
|
801
|
+
const sy = String(y);
|
|
802
|
+
if (sx !== sy) return sx < sy ? -1 : 1;
|
|
803
|
+
}
|
|
804
|
+
return 0;
|
|
805
|
+
}
|
|
806
|
+
/**
|
|
807
|
+
* Probe one directory the user named or a dialog returned.
|
|
808
|
+
* @param tool - which toolchain.
|
|
809
|
+
* @param root - installation root to probe.
|
|
810
|
+
* @param internals - probe injection.
|
|
811
|
+
* @returns validity with the reason, for the "Validate and save" error path.
|
|
812
|
+
*/
|
|
813
|
+
function probeInstallation(tool, root, internals = {}) {
|
|
814
|
+
const resolution = resolveToolchain(tool, root, {
|
|
815
|
+
...internals.exists === void 0 ? {} : { exists: internals.exists },
|
|
816
|
+
...internals.probeVersion === void 0 ? {} : { probeVersion: (executable) => internals.probeVersion?.(executable, tool) }
|
|
817
|
+
});
|
|
818
|
+
return {
|
|
819
|
+
ok: resolution.configured,
|
|
820
|
+
...resolution.version === void 0 ? {} : { version: resolution.version },
|
|
821
|
+
...resolution.cli === void 0 ? {} : { cli: resolution.cli },
|
|
822
|
+
...resolution.app === void 0 ? {} : { app: resolution.app },
|
|
823
|
+
...resolution.error === void 0 ? {} : { error: resolution.error }
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
//#endregion
|
|
827
|
+
//#region src/toolchain/lzma.ts
|
|
828
|
+
/**
|
|
829
|
+
* LZMA (ZIP compression method 14) decoder.
|
|
830
|
+
*
|
|
831
|
+
* The HuaQiu KiCad distribution is ~84 % LZMA: 83 548 of its 99 460 entries use
|
|
832
|
+
* method 14. Node's zlib has no LZMA, and the alternative — a native addon —
|
|
833
|
+
* cannot be rebuilt for every Electron target the desktop app ships. So the
|
|
834
|
+
* archive format the product actually serves decides this: without a decoder
|
|
835
|
+
* here, the primary download button could never finish (§8.5 steps 3–4).
|
|
836
|
+
*
|
|
837
|
+
* This is the LZMA SDK algorithm (the `LzmaDecode` state machine) specialised to
|
|
838
|
+
* what ZIP needs: raw LZMA1, properties from the entry header, and a known
|
|
839
|
+
* output length. Only the decoder is implemented — the product never writes
|
|
840
|
+
* archives.
|
|
841
|
+
*
|
|
842
|
+
* @module @huaqiu/hardware-artifacts/toolchain/lzma
|
|
843
|
+
*/
|
|
844
|
+
/** Probability model size (11-bit probabilities). */
|
|
845
|
+
const BIT_MODEL_TOTAL = 2048;
|
|
846
|
+
const MOVE_BITS = 5;
|
|
847
|
+
const TOP_VALUE = 4294967295;
|
|
848
|
+
const NORMALIZE_THRESHOLD = 16777216;
|
|
849
|
+
const NUM_STATES = 12;
|
|
850
|
+
const NUM_POS_STATES_MAX = 16;
|
|
851
|
+
const NUM_LEN_TO_POS_STATES = 4;
|
|
852
|
+
const NUM_ALIGN_BITS = 4;
|
|
853
|
+
const ALIGN_TABLE_SIZE = 16;
|
|
854
|
+
const START_POS_MODEL_INDEX = 4;
|
|
855
|
+
const END_POS_MODEL_INDEX = 14;
|
|
856
|
+
const MATCH_MIN_LEN = 2;
|
|
857
|
+
/** A stream this decoder cannot read; never repaired, always refused. */
|
|
858
|
+
var LzmaError = class extends Error {
|
|
859
|
+
code;
|
|
860
|
+
constructor(code, message) {
|
|
861
|
+
super(message);
|
|
862
|
+
this.code = code;
|
|
863
|
+
this.name = "LzmaError";
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
/**
|
|
867
|
+
* Parse the 5-byte LZMA1 property block ZIP stores after its 4-byte method
|
|
868
|
+
* header.
|
|
869
|
+
* @param bytes - property bytes (usually five).
|
|
870
|
+
* @returns the decoded properties.
|
|
871
|
+
*/
|
|
872
|
+
function parseLzmaProperties(bytes) {
|
|
873
|
+
if (bytes.length < 5) throw new LzmaError("invalid-properties", "LZMA properties are truncated");
|
|
874
|
+
const first = bytes[0];
|
|
875
|
+
const lc = first % 9;
|
|
876
|
+
const lp = Math.floor(first / 9) % 5;
|
|
877
|
+
const pb = Math.floor(first / 45);
|
|
878
|
+
if (pb >= 5 || lp > 4 || lc > 8) throw new LzmaError("invalid-properties", `unsupported LZMA properties (lc=${String(lc)}, lp=${String(lp)}, pb=${String(pb)})`);
|
|
879
|
+
return {
|
|
880
|
+
lc,
|
|
881
|
+
lp,
|
|
882
|
+
pb,
|
|
883
|
+
dictSize: bytes.readUInt32LE(1)
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
/** Range decoder over the compressed bytes. */
|
|
887
|
+
var RangeDecoder = class {
|
|
888
|
+
input;
|
|
889
|
+
range = TOP_VALUE;
|
|
890
|
+
code = 0;
|
|
891
|
+
cursor = 0;
|
|
892
|
+
constructor(input) {
|
|
893
|
+
this.input = input;
|
|
894
|
+
if (input.length === 0 || input[0] !== 0) throw new LzmaError("invalid-stream", "LZMA stream does not begin with a zero byte");
|
|
895
|
+
for (let index = 0; index < 5; index += 1) {
|
|
896
|
+
const byte = this.readByte();
|
|
897
|
+
this.code = (this.code * 256 + byte) % 4294967296;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
readByte() {
|
|
901
|
+
const value = this.input[this.cursor];
|
|
902
|
+
if (value === void 0) {
|
|
903
|
+
this.cursor += 1;
|
|
904
|
+
return 0;
|
|
905
|
+
}
|
|
906
|
+
this.cursor += 1;
|
|
907
|
+
return value;
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Normalise the range at the *end* of a decode step.
|
|
911
|
+
*
|
|
912
|
+
* The timing matters: `LzmaDecode` scales right after the range update, so
|
|
913
|
+
* the next step always starts with a range of at least 2^24. Normalising at
|
|
914
|
+
* the start instead leaves the *previous* step's value in place, and the
|
|
915
|
+
* `range / 2` of an unmodelled bit then rounds away half a bit that the
|
|
916
|
+
* reference implementation would have kept. That single rounding is enough to
|
|
917
|
+
* desynchronise a real stream after a few hundred symbols — this decoder did
|
|
918
|
+
* exactly that until the normalisation moved here.
|
|
919
|
+
*/
|
|
920
|
+
normalize() {
|
|
921
|
+
if (this.range < NORMALIZE_THRESHOLD) {
|
|
922
|
+
this.range = this.range * 256 % 4294967296;
|
|
923
|
+
this.code = (this.code * 256 + this.readByte()) % 4294967296;
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
/** Decode one modelled bit. */
|
|
927
|
+
decodeBit(probs, index) {
|
|
928
|
+
const prob = probs[index];
|
|
929
|
+
const bound = Math.floor(this.range / 2048) * prob;
|
|
930
|
+
let bit;
|
|
931
|
+
if (this.code < bound) {
|
|
932
|
+
this.range = bound;
|
|
933
|
+
probs[index] = prob + (BIT_MODEL_TOTAL - prob >> MOVE_BITS);
|
|
934
|
+
bit = 0;
|
|
935
|
+
} else {
|
|
936
|
+
this.range -= bound;
|
|
937
|
+
this.code -= bound;
|
|
938
|
+
probs[index] = prob - (prob >> MOVE_BITS);
|
|
939
|
+
bit = 1;
|
|
940
|
+
}
|
|
941
|
+
this.normalize();
|
|
942
|
+
return bit;
|
|
943
|
+
}
|
|
944
|
+
/** Decode one unmodelled bit. */
|
|
945
|
+
decodeDirectBit() {
|
|
946
|
+
this.range = Math.floor(this.range / 2);
|
|
947
|
+
let bit = 0;
|
|
948
|
+
if (this.code >= this.range) {
|
|
949
|
+
this.code -= this.range;
|
|
950
|
+
bit = 1;
|
|
951
|
+
}
|
|
952
|
+
this.normalize();
|
|
953
|
+
return bit;
|
|
954
|
+
}
|
|
955
|
+
/** Decode `count` unmodelled bits, most significant first. */
|
|
956
|
+
decodeDirectBits(count) {
|
|
957
|
+
let result = 0;
|
|
958
|
+
for (let index = 0; index < count; index += 1) result = result * 2 + this.decodeDirectBit();
|
|
959
|
+
return result;
|
|
960
|
+
}
|
|
961
|
+
};
|
|
962
|
+
/** One length-coder triple (low/mid/high trees behind two choices). */
|
|
963
|
+
var LengthDecoder = class {
|
|
964
|
+
choice = /* @__PURE__ */ new Uint16Array(1);
|
|
965
|
+
choice2 = /* @__PURE__ */ new Uint16Array(1);
|
|
966
|
+
low = /* @__PURE__ */ new Uint16Array(128);
|
|
967
|
+
mid = /* @__PURE__ */ new Uint16Array(128);
|
|
968
|
+
high = /* @__PURE__ */ new Uint16Array(256);
|
|
969
|
+
constructor() {
|
|
970
|
+
this.reset();
|
|
971
|
+
}
|
|
972
|
+
reset() {
|
|
973
|
+
for (const table of [
|
|
974
|
+
this.choice,
|
|
975
|
+
this.choice2,
|
|
976
|
+
this.low,
|
|
977
|
+
this.mid,
|
|
978
|
+
this.high
|
|
979
|
+
]) table.fill(1024);
|
|
980
|
+
}
|
|
981
|
+
/** Decode one length symbol (0…273). */
|
|
982
|
+
decode(decoder, posState) {
|
|
983
|
+
if (decoder.decodeBit(this.choice, 0) === 0) return this.tree(decoder, this.low, posState * 8, 3);
|
|
984
|
+
if (decoder.decodeBit(this.choice2, 0) === 0) return 8 + this.tree(decoder, this.mid, posState * 8, 3);
|
|
985
|
+
return 16 + this.tree(decoder, this.high, 0, 8);
|
|
986
|
+
}
|
|
987
|
+
tree(decoder, probs, base, bits) {
|
|
988
|
+
let m = 1;
|
|
989
|
+
for (let index = 0; index < bits; index += 1) m = (m << 1) + decoder.decodeBit(probs, base + m);
|
|
990
|
+
return m - (1 << bits);
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
/**
|
|
994
|
+
* Decode one raw LZMA1 stream into exactly `outputSize` bytes.
|
|
995
|
+
* @param compressed - stream bytes after the ZIP method header and properties.
|
|
996
|
+
* @param properties - parsed LZMA1 properties.
|
|
997
|
+
* @param outputSize - uncompressed length the central directory declared.
|
|
998
|
+
* @returns the decompressed bytes.
|
|
999
|
+
*/
|
|
1000
|
+
function decodeLzma(compressed, properties, outputSize) {
|
|
1001
|
+
const { lc, lp, pb } = properties;
|
|
1002
|
+
const decoder = new RangeDecoder(compressed);
|
|
1003
|
+
const literalProbs = new Uint16Array(768 * (1 << lc + lp));
|
|
1004
|
+
const isMatch = /* @__PURE__ */ new Uint16Array(192);
|
|
1005
|
+
const isRep = new Uint16Array(NUM_STATES);
|
|
1006
|
+
const isRepG0 = new Uint16Array(NUM_STATES);
|
|
1007
|
+
const isRepG1 = new Uint16Array(NUM_STATES);
|
|
1008
|
+
const isRepG2 = new Uint16Array(NUM_STATES);
|
|
1009
|
+
const isRep0Long = /* @__PURE__ */ new Uint16Array(192);
|
|
1010
|
+
const posSlot = /* @__PURE__ */ new Uint16Array(256);
|
|
1011
|
+
const specPos = /* @__PURE__ */ new Uint16Array(114);
|
|
1012
|
+
const align = new Uint16Array(ALIGN_TABLE_SIZE);
|
|
1013
|
+
for (const table of [
|
|
1014
|
+
literalProbs,
|
|
1015
|
+
isMatch,
|
|
1016
|
+
isRep,
|
|
1017
|
+
isRepG0,
|
|
1018
|
+
isRepG1,
|
|
1019
|
+
isRepG2,
|
|
1020
|
+
isRep0Long,
|
|
1021
|
+
posSlot,
|
|
1022
|
+
specPos,
|
|
1023
|
+
align
|
|
1024
|
+
]) table.fill(1024);
|
|
1025
|
+
const lenDecoder = new LengthDecoder();
|
|
1026
|
+
const repLenDecoder = new LengthDecoder();
|
|
1027
|
+
const output = Buffer.alloc(outputSize);
|
|
1028
|
+
const posStateMask = (1 << pb) - 1;
|
|
1029
|
+
const literalPosMask = (1 << lp) - 1;
|
|
1030
|
+
let state = 0;
|
|
1031
|
+
let rep0 = 0;
|
|
1032
|
+
let rep1 = 0;
|
|
1033
|
+
let rep2 = 0;
|
|
1034
|
+
let rep3 = 0;
|
|
1035
|
+
let pos = 0;
|
|
1036
|
+
const isMatchIndex = (state_, posState) => state_ * NUM_POS_STATES_MAX + posState;
|
|
1037
|
+
const decodeLiteral = () => {
|
|
1038
|
+
const prevByte = pos > 0 ? output[pos - 1] : 0;
|
|
1039
|
+
const literalState = (((pos & literalPosMask) << lc) + (prevByte >> 8 - lc)) * 768;
|
|
1040
|
+
let symbol = 1;
|
|
1041
|
+
if (state >= 7) {
|
|
1042
|
+
const matchByte = output[pos - rep0 - 1];
|
|
1043
|
+
if (matchByte === void 0) throw new LzmaError("invalid-stream", `literal match distance is out of range at pos ${String(pos)}`);
|
|
1044
|
+
let match = matchByte;
|
|
1045
|
+
do {
|
|
1046
|
+
const matchBit = match >> 7 & 1;
|
|
1047
|
+
match = match << 1 & 255;
|
|
1048
|
+
const bit = decoder.decodeBit(literalProbs, literalState + (1 + matchBit << 8) + symbol);
|
|
1049
|
+
symbol = symbol << 1 | bit;
|
|
1050
|
+
if (matchBit !== bit) break;
|
|
1051
|
+
} while (symbol < 256);
|
|
1052
|
+
}
|
|
1053
|
+
while (symbol < 256) symbol = symbol << 1 | decoder.decodeBit(literalProbs, literalState + symbol);
|
|
1054
|
+
output[pos] = symbol & 255;
|
|
1055
|
+
pos += 1;
|
|
1056
|
+
state = state < 4 ? 0 : state < 10 ? state - 3 : state - 6;
|
|
1057
|
+
};
|
|
1058
|
+
/**
|
|
1059
|
+
* Decode the distance of a new match.
|
|
1060
|
+
*
|
|
1061
|
+
* Distances are coded in three bands: slots 0–3 are the distance itself,
|
|
1062
|
+
* slots 4–13 use a reverse bit tree whose base depends on the slot, and
|
|
1063
|
+
* slots 14+ use unmodelled "direct" bits plus the 4-bit align tree. The align
|
|
1064
|
+
* tree is reverse-decoded from index 1 — starting at 16 reads a probability
|
|
1065
|
+
* that belongs to another model.
|
|
1066
|
+
*/
|
|
1067
|
+
const decodeDistance = (length) => {
|
|
1068
|
+
const base = (length - MATCH_MIN_LEN < NUM_LEN_TO_POS_STATES ? length - MATCH_MIN_LEN : 3) * 64;
|
|
1069
|
+
let m = 1;
|
|
1070
|
+
for (let index = 0; index < 6; index += 1) m = (m << 1) + decoder.decodeBit(posSlot, base + m);
|
|
1071
|
+
const slot = m - 64;
|
|
1072
|
+
if (slot < START_POS_MODEL_INDEX) return slot;
|
|
1073
|
+
const directBits = (slot >> 1) - 1;
|
|
1074
|
+
let distance = (2 | slot & 1) * (1 << directBits);
|
|
1075
|
+
if (slot < END_POS_MODEL_INDEX) return distance + reverseTree(specPos, distance - slot - 1, directBits);
|
|
1076
|
+
distance += decoder.decodeDirectBits(directBits - NUM_ALIGN_BITS) * ALIGN_TABLE_SIZE;
|
|
1077
|
+
return distance + reverseTree(align, 0, NUM_ALIGN_BITS);
|
|
1078
|
+
};
|
|
1079
|
+
/** Reverse bit-tree decode: the first decoded bit is the least significant. */
|
|
1080
|
+
const reverseTree = (probs, base, bits) => {
|
|
1081
|
+
let m = 1;
|
|
1082
|
+
let symbol = 0;
|
|
1083
|
+
for (let index = 0; index < bits; index += 1) {
|
|
1084
|
+
const bit = decoder.decodeBit(probs, base + m);
|
|
1085
|
+
m = m << 1 | bit;
|
|
1086
|
+
symbol |= bit << index;
|
|
1087
|
+
}
|
|
1088
|
+
return symbol;
|
|
1089
|
+
};
|
|
1090
|
+
while (pos < outputSize) {
|
|
1091
|
+
const posState = pos & posStateMask;
|
|
1092
|
+
if (decoder.decodeBit(isMatch, isMatchIndex(state, posState)) === 0) {
|
|
1093
|
+
decodeLiteral();
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
let length;
|
|
1097
|
+
if (decoder.decodeBit(isRep, state) === 0) {
|
|
1098
|
+
rep3 = rep2;
|
|
1099
|
+
rep2 = rep1;
|
|
1100
|
+
rep1 = rep0;
|
|
1101
|
+
length = lenDecoder.decode(decoder, posState) + MATCH_MIN_LEN;
|
|
1102
|
+
state = state < 7 ? 7 : 10;
|
|
1103
|
+
rep0 = decodeDistance(length);
|
|
1104
|
+
} else {
|
|
1105
|
+
if (decoder.decodeBit(isRepG0, state) === 0) {
|
|
1106
|
+
if (decoder.decodeBit(isRep0Long, isMatchIndex(state, posState)) === 0) {
|
|
1107
|
+
state = state < 7 ? 9 : 11;
|
|
1108
|
+
const source = output[pos - rep0 - 1];
|
|
1109
|
+
if (source === void 0) throw new LzmaError("invalid-stream", `short rep distance is out of range at pos ${String(pos)}`);
|
|
1110
|
+
output[pos] = source;
|
|
1111
|
+
pos += 1;
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
} else {
|
|
1115
|
+
let distance;
|
|
1116
|
+
if (decoder.decodeBit(isRepG1, state) === 0) distance = rep1;
|
|
1117
|
+
else {
|
|
1118
|
+
if (decoder.decodeBit(isRepG2, state) === 0) distance = rep2;
|
|
1119
|
+
else {
|
|
1120
|
+
distance = rep3;
|
|
1121
|
+
rep3 = rep2;
|
|
1122
|
+
}
|
|
1123
|
+
rep2 = rep1;
|
|
1124
|
+
}
|
|
1125
|
+
rep1 = rep0;
|
|
1126
|
+
rep0 = distance;
|
|
1127
|
+
}
|
|
1128
|
+
length = repLenDecoder.decode(decoder, posState) + MATCH_MIN_LEN;
|
|
1129
|
+
state = state < 7 ? 8 : 11;
|
|
1130
|
+
}
|
|
1131
|
+
for (let index = 0; index < length && pos < outputSize; index += 1) {
|
|
1132
|
+
const source = output[pos - rep0 - 1];
|
|
1133
|
+
if (source === void 0) throw new LzmaError("invalid-stream", `match distance is out of range at pos ${String(pos)} (rep0 ${String(rep0)})`);
|
|
1134
|
+
output[pos] = source;
|
|
1135
|
+
pos += 1;
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
return output;
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Read an entry's LZMA properties out of its data header.
|
|
1142
|
+
* @param header - the first bytes of the entry data.
|
|
1143
|
+
* @returns the properties and the number of bytes the header consumed.
|
|
1144
|
+
*/
|
|
1145
|
+
function readZipLzmaHeader(header) {
|
|
1146
|
+
if (header.length < 9) throw new LzmaError("invalid-stream", "LZMA entry header is truncated");
|
|
1147
|
+
const propertiesSize = header.readUInt16LE(2);
|
|
1148
|
+
if (propertiesSize < 5 || propertiesSize > 64) throw new LzmaError("invalid-stream", `LZMA properties size ${String(propertiesSize)} is not supported`);
|
|
1149
|
+
if (header.length < 4 + propertiesSize) throw new LzmaError("invalid-stream", "LZMA properties are truncated");
|
|
1150
|
+
return {
|
|
1151
|
+
properties: parseLzmaProperties(header.subarray(4, 4 + propertiesSize)),
|
|
1152
|
+
consumed: 4 + propertiesSize
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
//#endregion
|
|
1156
|
+
//#region src/toolchain/zip.ts
|
|
1157
|
+
/**
|
|
1158
|
+
* Minimal, safe, streaming ZIP reader — the installer's only archive code.
|
|
1159
|
+
*
|
|
1160
|
+
* Three reasons this is not a dependency: the archive is ~840 MB, so a
|
|
1161
|
+
* load-into-memory unzip is not acceptable (§7.5); extraction must be able to
|
|
1162
|
+
* *refuse* an entry rather than sanitize it afterwards (§8.4); and every byte it
|
|
1163
|
+
* writes has to be observable so the UI can show extraction progress (§7.4).
|
|
1164
|
+
* Node ships the two primitives the format needs (`inflateRaw` and file
|
|
1165
|
+
* streams), so the reader is a small amount of code instead of a package.
|
|
1166
|
+
*
|
|
1167
|
+
* Supported: stored (method 0) and deflated (method 8) entries from a classic
|
|
1168
|
+
* (non-ZIP64) central directory — what the HuaQiu portable distributions are.
|
|
1169
|
+
* Everything else is refused rather than guessed at.
|
|
1170
|
+
*
|
|
1171
|
+
* @module @huaqiu/hardware-artifacts/toolchain/zip
|
|
1172
|
+
*
|
|
1173
|
+
* @example
|
|
1174
|
+
* const directory = await readZipDirectory('kicad.zip')
|
|
1175
|
+
* await extractZip('kicad.zip', staging, { directory, stripPrefix: commonDirectory(directory) })
|
|
1176
|
+
*/
|
|
1177
|
+
const EOCD_SIGNATURE = 101010256;
|
|
1178
|
+
const ZIP64_LOCATOR_SIGNATURE = 117853008;
|
|
1179
|
+
const ZIP64_EOCD_SIGNATURE = 101075792;
|
|
1180
|
+
const CENTRAL_SIGNATURE = 33639248;
|
|
1181
|
+
const LOCAL_SIGNATURE = 67324752;
|
|
1182
|
+
/** ZIP compression method 14 (LZMA) — the KiCad distribution's dominant method. */
|
|
1183
|
+
const LZMA_METHOD = 14;
|
|
1184
|
+
const EOCD_SEARCH_BYTES = 66e3;
|
|
1185
|
+
const MAX_CENTRAL_DIRECTORY_BYTES = 67108864;
|
|
1186
|
+
/** Defaults sized for the real distributions (~840 MB archive, ~2 GiB extracted). */
|
|
1187
|
+
const DEFAULT_ZIP_LIMITS = Object.freeze({
|
|
1188
|
+
maxEntryBytes: 3221225472,
|
|
1189
|
+
maxTotalBytes: 17179869184,
|
|
1190
|
+
maxEntries: 4e5
|
|
1191
|
+
});
|
|
1192
|
+
/** A structural problem with the archive; never repaired, always refused. */
|
|
1193
|
+
var ZipError = class extends Error {
|
|
1194
|
+
code;
|
|
1195
|
+
constructor(code, message) {
|
|
1196
|
+
super(message);
|
|
1197
|
+
this.code = code;
|
|
1198
|
+
this.name = "ZipError";
|
|
1199
|
+
}
|
|
1200
|
+
};
|
|
1201
|
+
/**
|
|
1202
|
+
* Normalise and validate one archive path.
|
|
1203
|
+
*
|
|
1204
|
+
* Absolute paths, drive letters, `..` segments, NUL bytes, Windows alternate
|
|
1205
|
+
* data streams and reserved device names are all rejected: the first three
|
|
1206
|
+
* escape the target directory (§8.4), the rest cannot be safely created on the
|
|
1207
|
+
* target platform.
|
|
1208
|
+
* @param raw - entry name as the archive stores it.
|
|
1209
|
+
* @returns the safe relative path segments.
|
|
1210
|
+
*/
|
|
1211
|
+
function safeEntrySegments(raw) {
|
|
1212
|
+
const name = raw.replaceAll("\\", "/");
|
|
1213
|
+
if (name.includes("\0")) throw new ZipError("unsafe-entry", `archive entry contains NUL: ${raw}`);
|
|
1214
|
+
if (name.startsWith("/")) throw new ZipError("unsafe-entry", `archive entry is absolute: ${raw}`);
|
|
1215
|
+
if (/^[A-Za-z]:/u.test(name)) throw new ZipError("unsafe-entry", `archive entry has a drive prefix: ${raw}`);
|
|
1216
|
+
const segments = name.split("/").filter((segment) => segment !== "" && segment !== ".");
|
|
1217
|
+
if (segments.some((segment) => segment === "..")) throw new ZipError("unsafe-entry", `archive entry traverses upwards: ${raw}`);
|
|
1218
|
+
if (segments.length === 0) throw new ZipError("unsafe-entry", `archive entry has no name: ${raw}`);
|
|
1219
|
+
for (const segment of segments) {
|
|
1220
|
+
if (segment.includes(":")) throw new ZipError("unsafe-entry", `archive entry has a stream separator: ${raw}`);
|
|
1221
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/iu.test(segment)) throw new ZipError("unsafe-entry", `archive entry is a reserved device name: ${raw}`);
|
|
1222
|
+
}
|
|
1223
|
+
return segments;
|
|
1224
|
+
}
|
|
1225
|
+
/** Read exactly `length` bytes at `start` into `target`. */
|
|
1226
|
+
async function readRange(archivePath, start, length, target) {
|
|
1227
|
+
if (length === 0) return;
|
|
1228
|
+
await new Promise((resolvePromise, rejectPromise) => {
|
|
1229
|
+
const stream = createReadStream(archivePath, {
|
|
1230
|
+
start,
|
|
1231
|
+
end: start + length - 1
|
|
1232
|
+
});
|
|
1233
|
+
let filled = 0;
|
|
1234
|
+
stream.on("data", (chunk) => {
|
|
1235
|
+
const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
|
|
1236
|
+
filled += buffer.copy(target, filled);
|
|
1237
|
+
});
|
|
1238
|
+
stream.on("end", () => {
|
|
1239
|
+
if (filled === length) resolvePromise();
|
|
1240
|
+
else rejectPromise(new ZipError("invalid-zip", `short read at ${String(start)}`));
|
|
1241
|
+
});
|
|
1242
|
+
stream.on("error", rejectPromise);
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
/** Read an unsigned 64-bit little-endian field as a JS number (exact below 2^53). */
|
|
1246
|
+
function u64(buffer, offset) {
|
|
1247
|
+
const value = buffer.readBigUInt64LE(offset);
|
|
1248
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new ZipError("archive-too-large", "archive declares an unsupported size");
|
|
1249
|
+
return Number(value);
|
|
1250
|
+
}
|
|
1251
|
+
/**
|
|
1252
|
+
* Resolve the end-of-central-directory values, following the ZIP64 record when
|
|
1253
|
+
* the classic fields are saturated.
|
|
1254
|
+
*
|
|
1255
|
+
* The HuaQiu KiCad archive is genuinely ZIP64 (its contents exceed the classic
|
|
1256
|
+
* 4 GiB uncompressed limit), so this is a real requirement, not a defensive
|
|
1257
|
+
* branch: refusing ZIP64 would refuse the primary download (§8.5).
|
|
1258
|
+
* @param archivePath - archive being read.
|
|
1259
|
+
* @param eocd - tail window containing the classic record.
|
|
1260
|
+
* @param eocdOffset - index of the classic record inside `eocd`.
|
|
1261
|
+
* @returns the entry count, directory size and directory offset.
|
|
1262
|
+
*/
|
|
1263
|
+
async function directoryLocation(archivePath, eocd, eocdOffset) {
|
|
1264
|
+
const entryCount = eocd.readUInt16LE(eocdOffset + 10);
|
|
1265
|
+
const directorySize = eocd.readUInt32LE(eocdOffset + 12);
|
|
1266
|
+
const directoryOffset = eocd.readUInt32LE(eocdOffset + 16);
|
|
1267
|
+
if (!(entryCount === 65535 || directorySize === 4294967295 || directoryOffset === 4294967295)) return {
|
|
1268
|
+
entryCount,
|
|
1269
|
+
directorySize,
|
|
1270
|
+
directoryOffset
|
|
1271
|
+
};
|
|
1272
|
+
const locatorOffset = eocdOffset - 20;
|
|
1273
|
+
if (locatorOffset < 0 || eocd.readUInt32LE(locatorOffset) !== ZIP64_LOCATOR_SIGNATURE) throw new ZipError("invalid-zip", "ZIP64 archive without a ZIP64 locator");
|
|
1274
|
+
const recordOffset = u64(eocd, locatorOffset + 8);
|
|
1275
|
+
const record = Buffer.alloc(56);
|
|
1276
|
+
await readRange(archivePath, recordOffset, 56, record);
|
|
1277
|
+
if (record.readUInt32LE(0) !== ZIP64_EOCD_SIGNATURE) throw new ZipError("invalid-zip", "ZIP64 end-of-central-directory record is missing");
|
|
1278
|
+
return {
|
|
1279
|
+
entryCount: u64(record, 32),
|
|
1280
|
+
directorySize: u64(record, 40),
|
|
1281
|
+
directoryOffset: u64(record, 48)
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
/**
|
|
1285
|
+
* Read one central-directory entry's ZIP64 extended sizes from its extra field.
|
|
1286
|
+
*
|
|
1287
|
+
* The extra block only carries the values the classic header saturated, in
|
|
1288
|
+
* declaration order (uncompressed, compressed, offset) — reading them positionally
|
|
1289
|
+
* is what the specification requires.
|
|
1290
|
+
* @param extra - the entry's extra-field bytes.
|
|
1291
|
+
* @param needs - which classic fields were saturated.
|
|
1292
|
+
* @returns the saturated values as numbers.
|
|
1293
|
+
*/
|
|
1294
|
+
function zip64Sizes(extra, needs) {
|
|
1295
|
+
if (!needs.uncompressed && !needs.compressed && !needs.offset) return {};
|
|
1296
|
+
let cursor = 0;
|
|
1297
|
+
while (cursor + 4 <= extra.length) {
|
|
1298
|
+
const id = extra.readUInt16LE(cursor);
|
|
1299
|
+
const size = extra.readUInt16LE(cursor + 2);
|
|
1300
|
+
const body = extra.subarray(cursor + 4, cursor + 4 + size);
|
|
1301
|
+
cursor += 4 + size + size % 2;
|
|
1302
|
+
if (id !== 1) continue;
|
|
1303
|
+
let at = 0;
|
|
1304
|
+
const result = {};
|
|
1305
|
+
const next = () => {
|
|
1306
|
+
const value = u64(body, at);
|
|
1307
|
+
at += 8;
|
|
1308
|
+
return value;
|
|
1309
|
+
};
|
|
1310
|
+
if (needs.uncompressed) result.uncompressedSize = next();
|
|
1311
|
+
if (needs.compressed) result.compressedSize = next();
|
|
1312
|
+
if (needs.offset) result.headerOffset = next();
|
|
1313
|
+
return result;
|
|
1314
|
+
}
|
|
1315
|
+
throw new ZipError("invalid-zip", "ZIP64 entry is missing its extended size field");
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* Locate and parse the central directory.
|
|
1319
|
+
* @param archivePath - archive to read.
|
|
1320
|
+
* @returns the table of contents.
|
|
1321
|
+
*/
|
|
1322
|
+
async function readZipDirectory(archivePath) {
|
|
1323
|
+
const size = (await stat(archivePath)).size;
|
|
1324
|
+
const eocdLength = Math.min(size, EOCD_SEARCH_BYTES);
|
|
1325
|
+
const eocd = Buffer.alloc(eocdLength);
|
|
1326
|
+
await readRange(archivePath, size - eocdLength, eocdLength, eocd);
|
|
1327
|
+
let eocdOffset = -1;
|
|
1328
|
+
for (let index = eocdLength - 22; index >= 0; index -= 1) if (eocd.readUInt32LE(index) === EOCD_SIGNATURE) {
|
|
1329
|
+
eocdOffset = index;
|
|
1330
|
+
break;
|
|
1331
|
+
}
|
|
1332
|
+
if (eocdOffset < 0) throw new ZipError("invalid-zip", "no end-of-central-directory record");
|
|
1333
|
+
const { entryCount, directorySize, directoryOffset } = await directoryLocation(archivePath, eocd, eocdOffset);
|
|
1334
|
+
if (directorySize > MAX_CENTRAL_DIRECTORY_BYTES) throw new ZipError("invalid-zip", `central directory is implausibly large (${String(directorySize)} bytes)`);
|
|
1335
|
+
const directory = Buffer.alloc(directorySize);
|
|
1336
|
+
await readRange(archivePath, directoryOffset, directorySize, directory);
|
|
1337
|
+
const entries = [];
|
|
1338
|
+
let cursor = 0;
|
|
1339
|
+
let totalUncompressed = 0;
|
|
1340
|
+
for (let index = 0; index < entryCount; index += 1) {
|
|
1341
|
+
if (cursor + 46 > directory.length || directory.readUInt32LE(cursor) !== CENTRAL_SIGNATURE) throw new ZipError("invalid-zip", `central directory entry ${String(index)} is malformed`);
|
|
1342
|
+
const method = directory.readUInt16LE(cursor + 10);
|
|
1343
|
+
const compressedField = directory.readUInt32LE(cursor + 20);
|
|
1344
|
+
const uncompressedField = directory.readUInt32LE(cursor + 24);
|
|
1345
|
+
const nameLength = directory.readUInt16LE(cursor + 28);
|
|
1346
|
+
const extraLength = directory.readUInt16LE(cursor + 30);
|
|
1347
|
+
const commentLength = directory.readUInt16LE(cursor + 32);
|
|
1348
|
+
const offsetField = directory.readUInt32LE(cursor + 42);
|
|
1349
|
+
const name = directory.toString("utf8", cursor + 46, cursor + 46 + nameLength);
|
|
1350
|
+
const extra = directory.subarray(cursor + 46 + nameLength, cursor + 46 + nameLength + extraLength);
|
|
1351
|
+
cursor += 46 + nameLength + extraLength + commentLength;
|
|
1352
|
+
const extended = zip64Sizes(extra, {
|
|
1353
|
+
uncompressed: uncompressedField === 4294967295,
|
|
1354
|
+
compressed: compressedField === 4294967295,
|
|
1355
|
+
offset: offsetField === 4294967295
|
|
1356
|
+
});
|
|
1357
|
+
const compressedSize = extended.compressedSize ?? compressedField;
|
|
1358
|
+
const uncompressedSize = extended.uncompressedSize ?? uncompressedField;
|
|
1359
|
+
const headerOffset = extended.headerOffset ?? offsetField;
|
|
1360
|
+
entries.push({
|
|
1361
|
+
name: name.replaceAll("\\", "/"),
|
|
1362
|
+
compressedSize,
|
|
1363
|
+
uncompressedSize,
|
|
1364
|
+
method,
|
|
1365
|
+
headerOffset,
|
|
1366
|
+
directory: name.replaceAll("\\", "/").endsWith("/")
|
|
1367
|
+
});
|
|
1368
|
+
totalUncompressed += uncompressedSize;
|
|
1369
|
+
}
|
|
1370
|
+
return {
|
|
1371
|
+
entries,
|
|
1372
|
+
totalUncompressed,
|
|
1373
|
+
archiveBytes: size
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* The single wrapper directory an archive extracts into, when it has one.
|
|
1378
|
+
*
|
|
1379
|
+
* Both HuaQiu distributions ship one (`kicad-huaqiu-…/`, `solidcraft-…/`), and
|
|
1380
|
+
* the spec installs the *contents* into a versioned directory (§8.2/§8.3). Only
|
|
1381
|
+
* a genuine single root qualifies; an archive with two top-level names keeps
|
|
1382
|
+
* its own layout, because guessing would lose files.
|
|
1383
|
+
* @param directory - the archive's table of contents.
|
|
1384
|
+
* @returns the prefix to strip (with its trailing `/`), or undefined.
|
|
1385
|
+
*/
|
|
1386
|
+
function commonDirectory(directory) {
|
|
1387
|
+
const prefixes = /* @__PURE__ */ new Set();
|
|
1388
|
+
for (const entry of directory.entries) {
|
|
1389
|
+
const first = entry.name.split("/")[0];
|
|
1390
|
+
if (first === void 0 || first === "") return void 0;
|
|
1391
|
+
prefixes.add(first);
|
|
1392
|
+
if (prefixes.size > 1) return void 0;
|
|
1393
|
+
}
|
|
1394
|
+
const [prefix] = [...prefixes];
|
|
1395
|
+
return prefix === void 0 ? void 0 : `${prefix}/`;
|
|
1396
|
+
}
|
|
1397
|
+
/** Resolve one entry's data offset by reading its local header. */
|
|
1398
|
+
async function dataOffsetOf(archivePath, entry) {
|
|
1399
|
+
const header = Buffer.alloc(30);
|
|
1400
|
+
await readRange(archivePath, entry.headerOffset, 30, header);
|
|
1401
|
+
if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) throw new ZipError("invalid-zip", `local header missing for ${entry.name}`);
|
|
1402
|
+
const nameLength = header.readUInt16LE(26);
|
|
1403
|
+
const extraLength = header.readUInt16LE(28);
|
|
1404
|
+
return entry.headerOffset + 30 + nameLength + extraLength;
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Extract one archive into a directory that must already be staging.
|
|
1408
|
+
*
|
|
1409
|
+
* Every entry is validated before its file is created, so a refused archive
|
|
1410
|
+
* never leaves a tree that could be mistaken for an installation (§8.4). Writes
|
|
1411
|
+
* are streamed, so memory stays bounded regardless of entry size.
|
|
1412
|
+
* @param archivePath - archive to read.
|
|
1413
|
+
* @param targetDir - staging directory to fill; the caller owns its lifetime.
|
|
1414
|
+
* @param options - progress/cancellation/prefix/limits.
|
|
1415
|
+
* @returns counts of what was written.
|
|
1416
|
+
*/
|
|
1417
|
+
async function extractZip(archivePath, targetDir, options = {}) {
|
|
1418
|
+
const directory = options.directory ?? await readZipDirectory(archivePath);
|
|
1419
|
+
const limits = {
|
|
1420
|
+
...DEFAULT_ZIP_LIMITS,
|
|
1421
|
+
...options.limits
|
|
1422
|
+
};
|
|
1423
|
+
const total = directory.totalUncompressed;
|
|
1424
|
+
if (directory.entries.length > limits.maxEntries) throw new ZipError("archive-too-large", `archive declares ${String(directory.entries.length)} entries`);
|
|
1425
|
+
if (total > limits.maxTotalBytes) throw new ZipError("archive-too-large", `archive expands to ${String(total)} bytes`);
|
|
1426
|
+
const prefix = options.stripPrefix ?? "";
|
|
1427
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1428
|
+
const root = resolve(targetDir);
|
|
1429
|
+
let written = 0;
|
|
1430
|
+
let files = 0;
|
|
1431
|
+
let directories = 0;
|
|
1432
|
+
let completed = 0;
|
|
1433
|
+
for (const entry of directory.entries) {
|
|
1434
|
+
if (options.signal?.aborted === true) throw new ZipError("cancelled", "extraction was cancelled");
|
|
1435
|
+
const raw = prefix !== "" && entry.name.startsWith(prefix) ? entry.name.slice(prefix.length) : entry.name;
|
|
1436
|
+
if (raw === "") continue;
|
|
1437
|
+
if (entry.uncompressedSize > limits.maxEntryBytes) throw new ZipError("archive-too-large", `archive entry ${entry.name} expands to ${String(entry.uncompressedSize)} bytes`);
|
|
1438
|
+
const relative = safeEntrySegments(raw).join(sep);
|
|
1439
|
+
if (seen.has(relative)) throw new ZipError("duplicate-entry", `archive repeats the entry ${raw}`);
|
|
1440
|
+
seen.add(relative);
|
|
1441
|
+
const destination = join(root, relative);
|
|
1442
|
+
if (!destination.startsWith(`${root}${sep}`)) throw new ZipError("unsafe-entry", `archive entry escapes the target directory: ${raw}`);
|
|
1443
|
+
if (entry.directory) {
|
|
1444
|
+
await mkdir(destination, { recursive: true });
|
|
1445
|
+
directories += 1;
|
|
1446
|
+
completed += 1;
|
|
1447
|
+
continue;
|
|
1448
|
+
}
|
|
1449
|
+
if (entry.method !== 0 && entry.method !== 8 && entry.method !== LZMA_METHOD) throw new ZipError("unsupported-compression", `archive entry ${entry.name} uses compression method ${String(entry.method)}`);
|
|
1450
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
1451
|
+
const offset = await dataOffsetOf(archivePath, entry);
|
|
1452
|
+
if (entry.method === LZMA_METHOD) {
|
|
1453
|
+
const raw = Buffer.alloc(entry.compressedSize);
|
|
1454
|
+
await readRange(archivePath, offset, entry.compressedSize, raw);
|
|
1455
|
+
const { properties, consumed } = readZipLzmaHeader(raw);
|
|
1456
|
+
const expanded = decodeLzma(raw.subarray(consumed), properties, entry.uncompressedSize);
|
|
1457
|
+
await writeFile(destination, expanded);
|
|
1458
|
+
written += expanded.length;
|
|
1459
|
+
options.onProgress?.({
|
|
1460
|
+
written,
|
|
1461
|
+
total,
|
|
1462
|
+
entries: completed,
|
|
1463
|
+
totalEntries: directory.entries.length,
|
|
1464
|
+
current: entry.name
|
|
1465
|
+
});
|
|
1466
|
+
} else if (entry.compressedSize === 0) await writeFile(destination, "");
|
|
1467
|
+
else {
|
|
1468
|
+
const counter = new Transform({ transform: (chunk, _encoding, callback) => {
|
|
1469
|
+
written += chunk.length;
|
|
1470
|
+
options.onProgress?.({
|
|
1471
|
+
written,
|
|
1472
|
+
total,
|
|
1473
|
+
entries: completed,
|
|
1474
|
+
totalEntries: directory.entries.length,
|
|
1475
|
+
current: entry.name
|
|
1476
|
+
});
|
|
1477
|
+
callback(null, chunk);
|
|
1478
|
+
} });
|
|
1479
|
+
const source = createReadStream(archivePath, {
|
|
1480
|
+
start: offset,
|
|
1481
|
+
end: offset + entry.compressedSize - 1
|
|
1482
|
+
});
|
|
1483
|
+
const sink = createWriteStream(destination);
|
|
1484
|
+
const abort = () => {
|
|
1485
|
+
source.destroy(new ZipError("cancelled", "extraction was cancelled"));
|
|
1486
|
+
};
|
|
1487
|
+
options.signal?.addEventListener("abort", abort);
|
|
1488
|
+
try {
|
|
1489
|
+
if (entry.method === 8) await pipeline(source, createInflateRaw(), counter, sink);
|
|
1490
|
+
else await pipeline(source, counter, sink);
|
|
1491
|
+
} finally {
|
|
1492
|
+
options.signal?.removeEventListener("abort", abort);
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
const writtenBytes = await stat(destination).then((value) => value.size).catch(() => -1);
|
|
1496
|
+
if (writtenBytes !== entry.uncompressedSize) throw new ZipError("invalid-zip", `archive entry ${entry.name} expanded to ${String(writtenBytes)} bytes, expected ${String(entry.uncompressedSize)}`);
|
|
1497
|
+
files += 1;
|
|
1498
|
+
completed += 1;
|
|
1499
|
+
}
|
|
1500
|
+
options.onProgress?.({
|
|
1501
|
+
written,
|
|
1502
|
+
total,
|
|
1503
|
+
entries: completed,
|
|
1504
|
+
totalEntries: directory.entries.length,
|
|
1505
|
+
current: ""
|
|
1506
|
+
});
|
|
1507
|
+
return {
|
|
1508
|
+
files,
|
|
1509
|
+
directories,
|
|
1510
|
+
bytes: written
|
|
1511
|
+
};
|
|
1512
|
+
}
|
|
1513
|
+
//#endregion
|
|
1514
|
+
//#region src/toolchain/install.ts
|
|
1515
|
+
/**
|
|
1516
|
+
* Download → verify → extract → validate → promote, as one cancellable job.
|
|
1517
|
+
*
|
|
1518
|
+
* The order of the stages *is* the safety property (§8.5): nothing is reported
|
|
1519
|
+
* installed until a checksum matched the manifest entry and the extracted
|
|
1520
|
+
* executables answered a version probe, and a failure at any stage removes what
|
|
1521
|
+
* that stage wrote. Every stage is host-side and asynchronous, so the browser
|
|
1522
|
+
* only ever polls progress (§7.5).
|
|
1523
|
+
*
|
|
1524
|
+
* @module @huaqiu/hardware-artifacts/toolchain/install
|
|
1525
|
+
*/
|
|
1526
|
+
/** The primary file an installation must contain, per distribution (§8.2/§8.3). */
|
|
1527
|
+
function expectedLayout(tool, platform = process.platform) {
|
|
1528
|
+
const exe = platform === "win32" ? ".exe" : "";
|
|
1529
|
+
if (tool === "kicad") return platform === "darwin" ? ["KiCad.app/Contents/MacOS/kicad-cli"] : [join("bin", `kicad-cli${exe}`)];
|
|
1530
|
+
return [`solidcraft${exe}`];
|
|
1531
|
+
}
|
|
1532
|
+
/** The stable vocabulary, as a runtime list so a thrown code can be recognised. */
|
|
1533
|
+
const INSTALL_ERROR_CODES = [
|
|
1534
|
+
"http",
|
|
1535
|
+
"network",
|
|
1536
|
+
"checksum-mismatch",
|
|
1537
|
+
"invalid-zip",
|
|
1538
|
+
"unsafe-entry",
|
|
1539
|
+
"archive-too-large",
|
|
1540
|
+
"unsupported-compression",
|
|
1541
|
+
"unsupported-zip64",
|
|
1542
|
+
"duplicate-entry",
|
|
1543
|
+
"layout",
|
|
1544
|
+
"validation",
|
|
1545
|
+
"disk",
|
|
1546
|
+
"cancelled",
|
|
1547
|
+
"internal"
|
|
1548
|
+
];
|
|
1549
|
+
/** Wrap a Node/unknown failure into the job's stable vocabulary. */
|
|
1550
|
+
function classify(error) {
|
|
1551
|
+
const declared = error?.code;
|
|
1552
|
+
if (typeof declared === "string" && INSTALL_ERROR_CODES.includes(declared)) return {
|
|
1553
|
+
code: declared,
|
|
1554
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1555
|
+
};
|
|
1556
|
+
if (error instanceof ZipError) return {
|
|
1557
|
+
code: "invalid-zip",
|
|
1558
|
+
message: error.message
|
|
1559
|
+
};
|
|
1560
|
+
if (typeof declared === "string") {
|
|
1561
|
+
if (declared === "ENOSPC" || declared === "EDQUOT") return {
|
|
1562
|
+
code: "disk",
|
|
1563
|
+
message: "not enough free disk space"
|
|
1564
|
+
};
|
|
1565
|
+
if (declared === "ABORT_ERR") return {
|
|
1566
|
+
code: "cancelled",
|
|
1567
|
+
message: "the download was cancelled"
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
return {
|
|
1571
|
+
code: "internal",
|
|
1572
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
/**
|
|
1576
|
+
* Runs one download/install at a time per tool, and reports it as a snapshot.
|
|
1577
|
+
*
|
|
1578
|
+
* Job identity is the tool: a second request while one is running joins the
|
|
1579
|
+
* running job instead of starting a competing one (§14.4).
|
|
1580
|
+
*/
|
|
1581
|
+
var ToolchainInstaller = class {
|
|
1582
|
+
options;
|
|
1583
|
+
jobs = /* @__PURE__ */ new Map();
|
|
1584
|
+
running = /* @__PURE__ */ new Map();
|
|
1585
|
+
root;
|
|
1586
|
+
fetchImpl;
|
|
1587
|
+
idleTimeoutMs;
|
|
1588
|
+
now;
|
|
1589
|
+
sequence = 0;
|
|
1590
|
+
constructor(options) {
|
|
1591
|
+
this.options = options;
|
|
1592
|
+
this.root = options.root;
|
|
1593
|
+
this.fetchImpl = options.fetchImpl ?? fetch;
|
|
1594
|
+
this.idleTimeoutMs = options.idleTimeoutMs ?? 3e4;
|
|
1595
|
+
this.now = options.now ?? (() => Date.now());
|
|
1596
|
+
}
|
|
1597
|
+
/** One job's current snapshot. */
|
|
1598
|
+
snapshot(id) {
|
|
1599
|
+
return this.jobs.get(id);
|
|
1600
|
+
}
|
|
1601
|
+
/** The job currently running for one tool, if any. */
|
|
1602
|
+
activeFor(tool) {
|
|
1603
|
+
const entry = this.running.get(tool);
|
|
1604
|
+
return entry === void 0 ? void 0 : this.jobs.get(entry.id);
|
|
1605
|
+
}
|
|
1606
|
+
/**
|
|
1607
|
+
* Cancel one job.
|
|
1608
|
+
* @param id - job to cancel.
|
|
1609
|
+
* @returns true when a running job was signalled.
|
|
1610
|
+
*/
|
|
1611
|
+
cancel(id) {
|
|
1612
|
+
for (const [tool, entry] of this.running) {
|
|
1613
|
+
if (entry.id !== id) continue;
|
|
1614
|
+
entry.controller.abort();
|
|
1615
|
+
this.running.delete(tool);
|
|
1616
|
+
return true;
|
|
1617
|
+
}
|
|
1618
|
+
return false;
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* Start (or join) the install of one manifest entry.
|
|
1622
|
+
* @param tool - which toolchain.
|
|
1623
|
+
* @param entry - validated manifest entry to install.
|
|
1624
|
+
* @param hooks - validation and progress callbacks.
|
|
1625
|
+
* @returns the job's initial snapshot and the promise that settles it.
|
|
1626
|
+
*/
|
|
1627
|
+
start(tool, entry, hooks) {
|
|
1628
|
+
const active = this.running.get(tool);
|
|
1629
|
+
if (active !== void 0) {
|
|
1630
|
+
const snapshot = this.jobs.get(active.id);
|
|
1631
|
+
return {
|
|
1632
|
+
snapshot,
|
|
1633
|
+
done: Promise.resolve({
|
|
1634
|
+
ok: false,
|
|
1635
|
+
version: snapshot.version,
|
|
1636
|
+
reused: false,
|
|
1637
|
+
errorCode: "internal",
|
|
1638
|
+
error: "another installation is already running"
|
|
1639
|
+
})
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
this.sequence += 1;
|
|
1643
|
+
const id = `${tool}-${this.now()}-${this.sequence}`;
|
|
1644
|
+
const controller = new AbortController();
|
|
1645
|
+
this.running.set(tool, {
|
|
1646
|
+
id,
|
|
1647
|
+
controller
|
|
1648
|
+
});
|
|
1649
|
+
const initial = {
|
|
1650
|
+
id,
|
|
1651
|
+
tool,
|
|
1652
|
+
version: entry.version,
|
|
1653
|
+
phase: "download",
|
|
1654
|
+
received: 0,
|
|
1655
|
+
message: `Downloading ${label(tool)} ${entry.version}`,
|
|
1656
|
+
startedAt: this.now()
|
|
1657
|
+
};
|
|
1658
|
+
this.jobs.set(id, initial);
|
|
1659
|
+
const done = this.run(id, tool, entry, controller, hooks);
|
|
1660
|
+
return {
|
|
1661
|
+
snapshot: this.jobs.get(id),
|
|
1662
|
+
done
|
|
1663
|
+
};
|
|
1664
|
+
}
|
|
1665
|
+
/** Emit one snapshot and keep it as the job's latest state. */
|
|
1666
|
+
publish(snapshot, hooks) {
|
|
1667
|
+
this.jobs.set(snapshot.id, snapshot);
|
|
1668
|
+
hooks.onProgress?.(snapshot);
|
|
1669
|
+
}
|
|
1670
|
+
/** Advance one job to a transient stage. */
|
|
1671
|
+
stage(id, tool, version, phase, message, progress = {}, hooks) {
|
|
1672
|
+
const startedAt = this.jobs.get(id)?.startedAt ?? this.now();
|
|
1673
|
+
const received = progress.received ?? 0;
|
|
1674
|
+
const total = progress.total;
|
|
1675
|
+
const snapshot = {
|
|
1676
|
+
id,
|
|
1677
|
+
tool,
|
|
1678
|
+
version,
|
|
1679
|
+
phase,
|
|
1680
|
+
received,
|
|
1681
|
+
message,
|
|
1682
|
+
startedAt,
|
|
1683
|
+
...total === void 0 ? {} : {
|
|
1684
|
+
total,
|
|
1685
|
+
percent: total === 0 ? 100 : Math.min(100, Math.round(received / total * 100))
|
|
1686
|
+
}
|
|
1687
|
+
};
|
|
1688
|
+
this.jobs.set(id, snapshot);
|
|
1689
|
+
if (hooks !== void 0) hooks.onProgress?.(snapshot);
|
|
1690
|
+
return snapshot;
|
|
1691
|
+
}
|
|
1692
|
+
/** The whole stage machine for one job. */
|
|
1693
|
+
async run(id, tool, entry, controller, hooks) {
|
|
1694
|
+
const tempRoot = join(this.root, ".tmp");
|
|
1695
|
+
const stagingRoot = join(this.root, ".staging");
|
|
1696
|
+
const trashRoot = join(this.root, ".trash");
|
|
1697
|
+
const archivePath = join(tempRoot, `${tool}-${entry.version}-${id}.zip`);
|
|
1698
|
+
const stagingPath = join(stagingRoot, `${tool}-${entry.version}-${id}`);
|
|
1699
|
+
const finalPath = join(this.root, tool, entry.version);
|
|
1700
|
+
let promoted = false;
|
|
1701
|
+
try {
|
|
1702
|
+
await mkdir(tempRoot, { recursive: true });
|
|
1703
|
+
await mkdir(stagingRoot, { recursive: true });
|
|
1704
|
+
await mkdir(join(this.root, tool), { recursive: true });
|
|
1705
|
+
if (existsSync(finalPath) && (await hooks.validate(finalPath)).ok) {
|
|
1706
|
+
this.stage(id, tool, entry.version, "done", `${label(tool)} ${entry.version} is already installed`, {}, hooks);
|
|
1707
|
+
this.jobs.set(id, {
|
|
1708
|
+
...this.jobs.get(id),
|
|
1709
|
+
installPath: finalPath
|
|
1710
|
+
});
|
|
1711
|
+
return {
|
|
1712
|
+
ok: true,
|
|
1713
|
+
installPath: finalPath,
|
|
1714
|
+
version: entry.version,
|
|
1715
|
+
reused: true
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
this.stage(id, tool, entry.version, "download", `Downloading ${label(tool)} ${entry.version}`, {}, hooks);
|
|
1719
|
+
const digest = await this.download(id, tool, entry, archivePath, controller, hooks);
|
|
1720
|
+
this.stage(id, tool, entry.version, "verify", "Verifying the download", {}, hooks);
|
|
1721
|
+
if (digest !== entry.sha256.toLowerCase()) throw Object.assign(/* @__PURE__ */ new Error("the download does not match the published SHA-256"), { code: "checksum-mismatch" });
|
|
1722
|
+
if ((await stat(archivePath)).size === 0) throw Object.assign(/* @__PURE__ */ new Error("the downloaded archive is empty"), { code: "invalid-zip" });
|
|
1723
|
+
this.stage(id, tool, entry.version, "extract", "Extracting", { received: 0 }, hooks);
|
|
1724
|
+
const directory = await readZipDirectory(archivePath);
|
|
1725
|
+
await rm(stagingPath, {
|
|
1726
|
+
recursive: true,
|
|
1727
|
+
force: true
|
|
1728
|
+
});
|
|
1729
|
+
await mkdir(stagingPath, { recursive: true });
|
|
1730
|
+
const prefix = commonDirectory(directory);
|
|
1731
|
+
await extractZip(archivePath, stagingPath, {
|
|
1732
|
+
...prefix === void 0 ? {} : { stripPrefix: prefix },
|
|
1733
|
+
directory,
|
|
1734
|
+
signal: controller.signal,
|
|
1735
|
+
...hooks.onProgress === void 0 ? {} : { onProgress: (progress) => {
|
|
1736
|
+
this.stage(id, tool, entry.version, "extract", `Extracting ${String(progress.entries)}/${String(progress.totalEntries)} files`, {
|
|
1737
|
+
received: progress.written,
|
|
1738
|
+
total: directory.totalUncompressed
|
|
1739
|
+
}, hooks);
|
|
1740
|
+
} }
|
|
1741
|
+
});
|
|
1742
|
+
this.stage(id, tool, entry.version, "layout", "Checking the installation layout", {}, hooks);
|
|
1743
|
+
for (const relative of expectedLayout(tool)) if (!existsSync(join(stagingPath, relative))) throw Object.assign(/* @__PURE__ */ new Error(`the archive is missing ${relative}`), { code: "layout" });
|
|
1744
|
+
this.stage(id, tool, entry.version, "promote", "Installing", {}, hooks);
|
|
1745
|
+
if (existsSync(finalPath)) {
|
|
1746
|
+
await mkdir(trashRoot, { recursive: true });
|
|
1747
|
+
await rename(finalPath, join(trashRoot, `${tool}-${entry.version}-${id}`));
|
|
1748
|
+
}
|
|
1749
|
+
await rename(stagingPath, finalPath);
|
|
1750
|
+
promoted = true;
|
|
1751
|
+
const validation = await hooks.validate(finalPath);
|
|
1752
|
+
if (!validation.ok) throw Object.assign(new Error(validation.error ?? "the installed executables did not validate"), { code: "validation" });
|
|
1753
|
+
await rm(archivePath, { force: true }).catch(() => {});
|
|
1754
|
+
this.jobs.set(id, {
|
|
1755
|
+
...this.jobs.get(id),
|
|
1756
|
+
phase: "done",
|
|
1757
|
+
message: `${label(tool)} ${entry.version} installed`,
|
|
1758
|
+
installPath: finalPath,
|
|
1759
|
+
received: 1,
|
|
1760
|
+
total: 1
|
|
1761
|
+
});
|
|
1762
|
+
hooks.onProgress?.(this.jobs.get(id));
|
|
1763
|
+
return {
|
|
1764
|
+
ok: true,
|
|
1765
|
+
installPath: finalPath,
|
|
1766
|
+
version: entry.version,
|
|
1767
|
+
reused: false
|
|
1768
|
+
};
|
|
1769
|
+
} catch (error) {
|
|
1770
|
+
const cancelled = controller.signal.aborted || error?.code === "cancelled";
|
|
1771
|
+
const failure = classify(error);
|
|
1772
|
+
if (promoted) {
|
|
1773
|
+
await mkdir(trashRoot, { recursive: true }).catch(() => {});
|
|
1774
|
+
await rename(finalPath, join(trashRoot, `${tool}-${entry.version}-${id}-rejected`)).catch(() => {});
|
|
1775
|
+
}
|
|
1776
|
+
await rm(stagingPath, {
|
|
1777
|
+
recursive: true,
|
|
1778
|
+
force: true
|
|
1779
|
+
}).catch(() => {});
|
|
1780
|
+
await rm(archivePath, {
|
|
1781
|
+
force: true,
|
|
1782
|
+
maxRetries: 2
|
|
1783
|
+
}).catch(() => {});
|
|
1784
|
+
const phase = cancelled ? "cancelled" : "failed";
|
|
1785
|
+
const message = cancelled ? "Installation cancelled" : `${label(tool)} could not be installed: ${failure.message}`;
|
|
1786
|
+
this.jobs.set(id, {
|
|
1787
|
+
id,
|
|
1788
|
+
tool,
|
|
1789
|
+
version: entry.version,
|
|
1790
|
+
phase,
|
|
1791
|
+
received: 0,
|
|
1792
|
+
message,
|
|
1793
|
+
errorCode: cancelled ? "cancelled" : failure.code,
|
|
1794
|
+
error: message,
|
|
1795
|
+
startedAt: this.jobs.get(id)?.startedAt ?? this.now(),
|
|
1796
|
+
finishedAt: this.now()
|
|
1797
|
+
});
|
|
1798
|
+
hooks.onProgress?.(this.jobs.get(id));
|
|
1799
|
+
return {
|
|
1800
|
+
ok: false,
|
|
1801
|
+
version: entry.version,
|
|
1802
|
+
reused: false,
|
|
1803
|
+
errorCode: cancelled ? "cancelled" : failure.code,
|
|
1804
|
+
error: message
|
|
1805
|
+
};
|
|
1806
|
+
} finally {
|
|
1807
|
+
this.running.delete(tool);
|
|
1808
|
+
const snapshot = this.jobs.get(id);
|
|
1809
|
+
if (snapshot !== void 0 && (snapshot.phase === "done" || snapshot.phase === "failed" || snapshot.phase === "cancelled")) this.jobs.set(id, {
|
|
1810
|
+
...snapshot,
|
|
1811
|
+
finishedAt: snapshot.finishedAt ?? this.now()
|
|
1812
|
+
});
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
/** Stream one archive to disk, hashing as it arrives. */
|
|
1816
|
+
async download(id, tool, entry, archivePath, controller, hooks) {
|
|
1817
|
+
const signal = controller.signal;
|
|
1818
|
+
let response;
|
|
1819
|
+
try {
|
|
1820
|
+
response = await this.fetchImpl(entry.url, {
|
|
1821
|
+
signal,
|
|
1822
|
+
redirect: "follow"
|
|
1823
|
+
});
|
|
1824
|
+
} catch (error) {
|
|
1825
|
+
throw Object.assign(/* @__PURE__ */ new Error(`the download could not start: ${error instanceof Error ? error.message : String(error)}`), { code: "network" });
|
|
1826
|
+
}
|
|
1827
|
+
if (!response.ok || response.body === null) throw Object.assign(/* @__PURE__ */ new Error(`the download answered HTTP ${String(response.status)}`), { code: "http" });
|
|
1828
|
+
const declared = Number(response.headers.get("content-length") ?? "");
|
|
1829
|
+
const total = Number.isFinite(declared) && declared > 0 ? declared : void 0;
|
|
1830
|
+
const digest = createHash("sha256");
|
|
1831
|
+
let received = 0;
|
|
1832
|
+
let lastEmit = 0;
|
|
1833
|
+
let idle = setTimeout(() => {
|
|
1834
|
+
controller.abort();
|
|
1835
|
+
}, this.idleTimeoutMs);
|
|
1836
|
+
idle.unref?.();
|
|
1837
|
+
const counter = new Transform({ transform: (chunk, _encoding, callback) => {
|
|
1838
|
+
received += chunk.length;
|
|
1839
|
+
digest.update(chunk);
|
|
1840
|
+
clearTimeout(idle);
|
|
1841
|
+
idle = setTimeout(() => {
|
|
1842
|
+
controller.abort();
|
|
1843
|
+
}, this.idleTimeoutMs);
|
|
1844
|
+
idle.unref?.();
|
|
1845
|
+
const now = this.now();
|
|
1846
|
+
const percent = total === void 0 ? 0 : Math.round(received / total * 100);
|
|
1847
|
+
if (now - lastEmit >= 250 || percent === 100) {
|
|
1848
|
+
lastEmit = now;
|
|
1849
|
+
this.stage(id, tool, entry.version, "download", total === void 0 ? `Downloading (${String(received)} bytes)` : `Downloading ${String(percent)}%`, {
|
|
1850
|
+
received,
|
|
1851
|
+
...total === void 0 ? {} : { total }
|
|
1852
|
+
}, hooks);
|
|
1853
|
+
}
|
|
1854
|
+
callback(null, chunk);
|
|
1855
|
+
} });
|
|
1856
|
+
const source = Readable.fromWeb(response.body);
|
|
1857
|
+
const sink = createWriteStream(archivePath);
|
|
1858
|
+
try {
|
|
1859
|
+
await pipeline(source, counter, sink);
|
|
1860
|
+
} finally {
|
|
1861
|
+
clearTimeout(idle);
|
|
1862
|
+
}
|
|
1863
|
+
if (total !== void 0 && received !== total) throw Object.assign(/* @__PURE__ */ new Error(`the download stopped at ${String(received)} of ${String(total)} bytes`), { code: "network" });
|
|
1864
|
+
return digest.digest("hex");
|
|
1865
|
+
}
|
|
1866
|
+
};
|
|
1867
|
+
/** Manifest platform token for the host platform, or undefined when unsupported. */
|
|
1868
|
+
function manifestPlatformOf(platform) {
|
|
1869
|
+
if (platform === "win32") return "win";
|
|
1870
|
+
if (platform === "darwin") return "darwin";
|
|
1871
|
+
if (platform === "linux") return "linux";
|
|
1872
|
+
}
|
|
1873
|
+
/** Manifest architecture token for the host architecture. */
|
|
1874
|
+
function manifestArchOf(arch) {
|
|
1875
|
+
if (arch === "arm64") return "arm64";
|
|
1876
|
+
if (arch === "ia32" || arch === "x64") return "x64";
|
|
1877
|
+
return arch;
|
|
1878
|
+
}
|
|
1879
|
+
const TOOLCHAIN_IDS = ["kicad", "solidcraft"];
|
|
1880
|
+
const VERSION_PATTERN = /^[0-9A-Za-z][0-9A-Za-z.+_-]{0,63}$/u;
|
|
1881
|
+
const SHA256_PATTERN = /^[0-9a-f]{64}$/u;
|
|
1882
|
+
function failure(code, message) {
|
|
1883
|
+
return {
|
|
1884
|
+
ok: false,
|
|
1885
|
+
code,
|
|
1886
|
+
message
|
|
1887
|
+
};
|
|
1888
|
+
}
|
|
1889
|
+
function isRecord(value) {
|
|
1890
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1891
|
+
}
|
|
1892
|
+
/** Validate one entry against the manifest contract; the reason on refusal. */
|
|
1893
|
+
function readEntry(tool, value) {
|
|
1894
|
+
if (!isRecord(value)) return `${tool}: entry is not an object`;
|
|
1895
|
+
const { version, sha256, platform, arch, url } = value;
|
|
1896
|
+
if (typeof version !== "string" || !VERSION_PATTERN.test(version)) return `${tool}: invalid version`;
|
|
1897
|
+
if (typeof sha256 !== "string" || !SHA256_PATTERN.test(sha256)) return `${tool}: invalid sha256`;
|
|
1898
|
+
if (typeof platform !== "string" || platform === "") return `${tool}: invalid platform`;
|
|
1899
|
+
if (typeof arch !== "string" || arch === "") return `${tool}: invalid arch`;
|
|
1900
|
+
if (typeof url !== "string" || !url.startsWith("https://")) return `${tool}: download url must be https`;
|
|
1901
|
+
return {
|
|
1902
|
+
version,
|
|
1903
|
+
sha256,
|
|
1904
|
+
platform,
|
|
1905
|
+
arch,
|
|
1906
|
+
url
|
|
1907
|
+
};
|
|
1908
|
+
}
|
|
1909
|
+
/** Version ordering used to pick the newest entry deterministically. */
|
|
1910
|
+
function compareVersions(left, right) {
|
|
1911
|
+
const segments = (value) => value.split(/[.+-]/u).map((part) => /^\d+$/u.test(part) ? Number(part) : part);
|
|
1912
|
+
const a = segments(left);
|
|
1913
|
+
const b = segments(right);
|
|
1914
|
+
for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
|
|
1915
|
+
const x = a[index];
|
|
1916
|
+
const y = b[index];
|
|
1917
|
+
if (x === void 0) return -1;
|
|
1918
|
+
if (y === void 0) return 1;
|
|
1919
|
+
if (typeof x === "number" && typeof y === "number") {
|
|
1920
|
+
if (x !== y) return x - y;
|
|
1921
|
+
continue;
|
|
1922
|
+
}
|
|
1923
|
+
const sx = String(x);
|
|
1924
|
+
const sy = String(y);
|
|
1925
|
+
if (sx !== sy) return sx < sy ? -1 : 1;
|
|
1926
|
+
}
|
|
1927
|
+
return 0;
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Parse and validate one manifest document for this host.
|
|
1931
|
+
*
|
|
1932
|
+
* Malformed or unsupported entries are rejected as a whole entry (§7.3): an
|
|
1933
|
+
* entry with a bad checksum is not "probably fine", because a download it
|
|
1934
|
+
* authorised could never be verified. Entries for other platforms/architectures
|
|
1935
|
+
* are kept in `entries` (so the UI can explain the mismatch) but never selected.
|
|
1936
|
+
* @param text - raw manifest body.
|
|
1937
|
+
* @param options - host platform/architecture to select for.
|
|
1938
|
+
* @returns the validated manifest, or the reason it cannot be used.
|
|
1939
|
+
*/
|
|
1940
|
+
function parseManifest(text, options = {}) {
|
|
1941
|
+
let document;
|
|
1942
|
+
try {
|
|
1943
|
+
document = JSON.parse(text);
|
|
1944
|
+
} catch {
|
|
1945
|
+
return failure("invalid-json", "the toolchain manifest is not valid JSON");
|
|
1946
|
+
}
|
|
1947
|
+
if (!isRecord(document)) return failure("invalid-json", "the toolchain manifest is not an object");
|
|
1948
|
+
if (document.schemaVersion !== 1) return failure("unsupported-schema", `unsupported toolchain manifest schemaVersion ${String(document.schemaVersion)}`);
|
|
1949
|
+
const platform = manifestPlatformOf(options.platform ?? process.platform);
|
|
1950
|
+
if (platform === void 0) return failure("unsupported-platform", `toolchain downloads are not available on ${options.platform ?? process.platform}`);
|
|
1951
|
+
const arch = manifestArchOf(options.arch ?? process.arch);
|
|
1952
|
+
const entries = {
|
|
1953
|
+
kicad: [],
|
|
1954
|
+
solidcraft: []
|
|
1955
|
+
};
|
|
1956
|
+
const selected = {};
|
|
1957
|
+
for (const tool of TOOLCHAIN_IDS) {
|
|
1958
|
+
const list = document[tool];
|
|
1959
|
+
if (list === void 0) continue;
|
|
1960
|
+
if (!Array.isArray(list)) return failure("invalid-entry", `${tool}: entries are not an array`);
|
|
1961
|
+
const validated = [];
|
|
1962
|
+
for (const raw of list) {
|
|
1963
|
+
const entry = readEntry(tool, raw);
|
|
1964
|
+
if (typeof entry === "string") return failure("invalid-entry", entry);
|
|
1965
|
+
validated.push(entry);
|
|
1966
|
+
}
|
|
1967
|
+
entries[tool] = validated;
|
|
1968
|
+
const newest = validated.filter((entry) => entry.platform === platform && entry.arch === arch).sort((left, right) => compareVersions(right.version, left.version))[0];
|
|
1969
|
+
if (newest !== void 0) selected[tool] = newest;
|
|
1970
|
+
}
|
|
1971
|
+
if (selected.kicad === void 0 && selected.solidcraft === void 0) return failure("no-entry", `the toolchain manifest offers no ${platform}-${arch} distribution`);
|
|
1972
|
+
return {
|
|
1973
|
+
ok: true,
|
|
1974
|
+
manifest: {
|
|
1975
|
+
schemaVersion: 1,
|
|
1976
|
+
entries,
|
|
1977
|
+
selected,
|
|
1978
|
+
target: {
|
|
1979
|
+
platform,
|
|
1980
|
+
arch
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
};
|
|
1984
|
+
}
|
|
1985
|
+
/**
|
|
1986
|
+
* Fetch and validate the manifest.
|
|
1987
|
+
*
|
|
1988
|
+
* A network or HTTP failure is a *download-unavailable* state, not a setup
|
|
1989
|
+
* error: manual configuration and browsing stay available (§14.2), so the
|
|
1990
|
+
* failure is reported as data rather than thrown.
|
|
1991
|
+
* @param options - URL/transport/timeout and the target platform.
|
|
1992
|
+
* @returns the validated manifest or the reason it is unavailable.
|
|
1993
|
+
*/
|
|
1994
|
+
async function fetchManifest(options = {}) {
|
|
1995
|
+
const url = options.url ?? "https://kicad.eda.cn/agent-toolchains.json";
|
|
1996
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
1997
|
+
const controller = new AbortController();
|
|
1998
|
+
const timeout = setTimeout(() => {
|
|
1999
|
+
controller.abort();
|
|
2000
|
+
}, options.timeoutMs ?? 2e4);
|
|
2001
|
+
const abort = () => {
|
|
2002
|
+
controller.abort();
|
|
2003
|
+
};
|
|
2004
|
+
options.signal?.addEventListener("abort", abort);
|
|
2005
|
+
try {
|
|
2006
|
+
const response = await fetchImpl(url, {
|
|
2007
|
+
signal: controller.signal,
|
|
2008
|
+
redirect: "follow"
|
|
2009
|
+
});
|
|
2010
|
+
if (!response.ok) return failure("http", `the toolchain manifest answered HTTP ${String(response.status)}`);
|
|
2011
|
+
return parseManifest(await response.text(), {
|
|
2012
|
+
...options.platform === void 0 ? {} : { platform: options.platform },
|
|
2013
|
+
...options.arch === void 0 ? {} : { arch: options.arch }
|
|
2014
|
+
});
|
|
2015
|
+
} catch (error) {
|
|
2016
|
+
return failure("network", `the toolchain manifest could not be fetched: ${error instanceof Error ? error.message : String(error)}`);
|
|
2017
|
+
} finally {
|
|
2018
|
+
clearTimeout(timeout);
|
|
2019
|
+
options.signal?.removeEventListener("abort", abort);
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
//#endregion
|
|
2023
|
+
//#region src/toolchain/manager.ts
|
|
2024
|
+
/**
|
|
2025
|
+
* The toolchain capability: status, validation, discovery, download and
|
|
2026
|
+
* configuration for KiCad and SolidCraft.
|
|
2027
|
+
*
|
|
2028
|
+
* One object owns the whole lifecycle so the wizard, the Settings panel, the
|
|
2029
|
+
* installer and the agent prompt read the same facts (§10.5). It never writes
|
|
2030
|
+
* UI state and never invents a download: everything it reports comes from a
|
|
2031
|
+
* resolution of the configured path, a validated manifest entry, or a job it is
|
|
2032
|
+
* running right now.
|
|
2033
|
+
*
|
|
2034
|
+
* @module @huaqiu/hardware-artifacts/toolchain/manager
|
|
2035
|
+
*/
|
|
2036
|
+
/** The fallback download pages offered when the HuaQiu manifest is unusable (§9.2). */
|
|
2037
|
+
const OFFICIAL_DOWNLOAD_PAGES = Object.freeze({
|
|
2038
|
+
kicad: "https://www.kicad.org/download/",
|
|
2039
|
+
solidcraft: "https://github.com/tangency-labs/solidcraft/releases/"
|
|
2040
|
+
});
|
|
2041
|
+
/** Version probes cost a process; cache them briefly per executable. */
|
|
2042
|
+
const PROBE_CACHE_MS = 3e4;
|
|
2043
|
+
/** Dispatch one version command per tool — the interfaces are not identical (§5.3). */
|
|
2044
|
+
function versionCommand(tool, executable) {
|
|
2045
|
+
return tool === "kicad" ? {
|
|
2046
|
+
command: executable,
|
|
2047
|
+
args: ["version"]
|
|
2048
|
+
} : {
|
|
2049
|
+
command: executable,
|
|
2050
|
+
args: ["--version"]
|
|
2051
|
+
};
|
|
2052
|
+
}
|
|
2053
|
+
/** Default probe: one short-lived process, no shell. */
|
|
2054
|
+
async function defaultVersionProbe(executable, tool) {
|
|
2055
|
+
const { command, args } = versionCommand(tool, executable);
|
|
2056
|
+
return new Promise((resolvePromise) => {
|
|
2057
|
+
execFile(command, args, {
|
|
2058
|
+
timeout: 15e3,
|
|
2059
|
+
encoding: "utf8",
|
|
2060
|
+
windowsHide: true,
|
|
2061
|
+
shell: false,
|
|
2062
|
+
maxBuffer: 4194304
|
|
2063
|
+
}, (error, stdout) => {
|
|
2064
|
+
if (error !== null) {
|
|
2065
|
+
resolvePromise(void 0);
|
|
2066
|
+
return;
|
|
2067
|
+
}
|
|
2068
|
+
resolvePromise(normalizeVersion(String(stdout)) ?? String(stdout).trim());
|
|
2069
|
+
});
|
|
2070
|
+
});
|
|
2071
|
+
}
|
|
2072
|
+
/** The per-user toolchain root, following the harness-home convention (§8.1). */
|
|
2073
|
+
function defaultManagedRoot(env = process.env) {
|
|
2074
|
+
const home = env.DSH_HOME !== void 0 && env.DSH_HOME !== "" ? resolve(env.DSH_HOME) : join(homedir(), ".huaqiu-eda");
|
|
2075
|
+
return join(home, "toolchains");
|
|
2076
|
+
}
|
|
2077
|
+
/**
|
|
2078
|
+
* Discovery is asynchronous by construction: `state: 'running'` is answered
|
|
2079
|
+
* immediately, and the verdicts arrive through {@link ToolchainManager.status}.
|
|
2080
|
+
*/
|
|
2081
|
+
var ToolchainManager = class {
|
|
2082
|
+
options;
|
|
2083
|
+
installer;
|
|
2084
|
+
managedRoot;
|
|
2085
|
+
platform;
|
|
2086
|
+
arch;
|
|
2087
|
+
env;
|
|
2088
|
+
home;
|
|
2089
|
+
now;
|
|
2090
|
+
probeCache = /* @__PURE__ */ new Map();
|
|
2091
|
+
discovery;
|
|
2092
|
+
discovering = /* @__PURE__ */ new Set();
|
|
2093
|
+
manifestCache;
|
|
2094
|
+
manifestPending;
|
|
2095
|
+
constructor(options) {
|
|
2096
|
+
this.options = options;
|
|
2097
|
+
this.managedRoot = options.managedRoot ?? defaultManagedRoot(options.env ?? process.env);
|
|
2098
|
+
this.platform = options.platform ?? process.platform;
|
|
2099
|
+
this.arch = options.arch ?? process.arch;
|
|
2100
|
+
this.env = options.env ?? process.env;
|
|
2101
|
+
this.home = options.home ?? homedir();
|
|
2102
|
+
this.now = options.now ?? (() => Date.now());
|
|
2103
|
+
this.installer = new ToolchainInstaller({
|
|
2104
|
+
root: this.managedRoot,
|
|
2105
|
+
...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl },
|
|
2106
|
+
now: this.now
|
|
2107
|
+
});
|
|
2108
|
+
this.discovery = {
|
|
2109
|
+
kicad: {
|
|
2110
|
+
tool: "kicad",
|
|
2111
|
+
state: "idle",
|
|
2112
|
+
candidates: []
|
|
2113
|
+
},
|
|
2114
|
+
solidcraft: {
|
|
2115
|
+
tool: "solidcraft",
|
|
2116
|
+
state: "idle",
|
|
2117
|
+
candidates: []
|
|
2118
|
+
}
|
|
2119
|
+
};
|
|
2120
|
+
}
|
|
2121
|
+
/** The per-user root this capability installs into, for diagnostics. */
|
|
2122
|
+
get toolchainRoot() {
|
|
2123
|
+
return this.managedRoot;
|
|
2124
|
+
}
|
|
2125
|
+
/** Probe one executable, memoised briefly; an install invalidates it. */
|
|
2126
|
+
async versionOf(tool, executable) {
|
|
2127
|
+
const key = `${tool}:${executable}`;
|
|
2128
|
+
const cached = this.probeCache.get(key);
|
|
2129
|
+
if (cached !== void 0 && this.now() - cached.at < PROBE_CACHE_MS) return cached.version;
|
|
2130
|
+
const report = await (this.options.versionProbe ?? defaultVersionProbe)(executable, tool);
|
|
2131
|
+
const version = report === void 0 ? void 0 : normalizeVersion(report) ?? report;
|
|
2132
|
+
this.probeCache.set(key, {
|
|
2133
|
+
at: this.now(),
|
|
2134
|
+
...version === void 0 ? {} : { version }
|
|
2135
|
+
});
|
|
2136
|
+
return version;
|
|
2137
|
+
}
|
|
2138
|
+
/** Resolve one configured path into its executables and validated state. */
|
|
2139
|
+
async resolve(tool, root) {
|
|
2140
|
+
if (root === void 0 || root.trim() === "") return resolveToolchain(tool, root);
|
|
2141
|
+
const layout = resolveToolchain(tool, root, { platform: this.platform });
|
|
2142
|
+
const executable = layout.cli ?? layout.app;
|
|
2143
|
+
const version = executable === void 0 ? void 0 : await this.versionOf(tool, executable);
|
|
2144
|
+
return resolveToolchain(tool, root, {
|
|
2145
|
+
platform: this.platform,
|
|
2146
|
+
probeVersion: () => version
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
/** The persisted path for one tool, as the settings service holds it. */
|
|
2150
|
+
roots() {
|
|
2151
|
+
return this.options.settings();
|
|
2152
|
+
}
|
|
2153
|
+
/** Status of one tool, from its configured path. */
|
|
2154
|
+
async toolStatus(tool) {
|
|
2155
|
+
const settings = this.roots();
|
|
2156
|
+
const root = tool === "kicad" ? settings.kicadRoot : settings.solidcraftRoot;
|
|
2157
|
+
const persistedVersion = tool === "kicad" ? settings.kicadVersion : settings.solidcraftVersion;
|
|
2158
|
+
const persistedSource = tool === "kicad" ? settings.kicadSource : settings.solidcraftSource;
|
|
2159
|
+
const validatedAt = tool === "kicad" ? settings.kicadValidatedAt : settings.solidcraftValidatedAt;
|
|
2160
|
+
const resolution = await this.resolve(tool, root);
|
|
2161
|
+
const source = persistedSource === "manual" || persistedSource === "browse" || persistedSource === "download" || persistedSource === "detected" ? persistedSource : void 0;
|
|
2162
|
+
const entry = await this.selectedEntry(tool);
|
|
2163
|
+
const base = {
|
|
2164
|
+
tool,
|
|
2165
|
+
discovery: this.discovery[tool],
|
|
2166
|
+
...entry === void 0 ? {} : { download: {
|
|
2167
|
+
version: entry.version,
|
|
2168
|
+
url: entry.url
|
|
2169
|
+
} }
|
|
2170
|
+
};
|
|
2171
|
+
if (resolution.configured) return {
|
|
2172
|
+
...base,
|
|
2173
|
+
state: "configured",
|
|
2174
|
+
installPath: resolution.installPath,
|
|
2175
|
+
...resolution.cli === void 0 ? {} : { cliPath: resolution.cli },
|
|
2176
|
+
...resolution.app === void 0 ? {} : { appPath: resolution.app },
|
|
2177
|
+
...resolution.version === void 0 ? {} : { version: resolution.version },
|
|
2178
|
+
...source === void 0 ? {} : { source },
|
|
2179
|
+
...validatedAt === void 0 || validatedAt === 0 ? {} : { validatedAt }
|
|
2180
|
+
};
|
|
2181
|
+
if (root === void 0 || root.trim() === "") return {
|
|
2182
|
+
...base,
|
|
2183
|
+
state: "unconfigured"
|
|
2184
|
+
};
|
|
2185
|
+
return {
|
|
2186
|
+
...base,
|
|
2187
|
+
state: "invalid",
|
|
2188
|
+
installPath: resolution.installPath,
|
|
2189
|
+
...resolution.cli === void 0 ? {} : { cliPath: resolution.cli },
|
|
2190
|
+
...resolution.app === void 0 ? {} : { appPath: resolution.app },
|
|
2191
|
+
...persistedVersion === void 0 || persistedVersion === "" ? {} : { version: persistedVersion },
|
|
2192
|
+
...source === void 0 ? {} : { source },
|
|
2193
|
+
...validatedAt === void 0 || validatedAt === 0 ? {} : { validatedAt },
|
|
2194
|
+
...resolution.error === void 0 ? {} : { error: resolution.error }
|
|
2195
|
+
};
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Full status for the settings/wizard surfaces.
|
|
2199
|
+
* @param jobIds - optional jobs whose progress the caller wants included. Both
|
|
2200
|
+
* tools can be downloading at once, so this is a list: asking for one id at a
|
|
2201
|
+
* time is exactly how the second download used to erase the first one's bar.
|
|
2202
|
+
* @returns both tools plus the manifest and target facts.
|
|
2203
|
+
*/
|
|
2204
|
+
async status(jobIds) {
|
|
2205
|
+
const [kicad, solidcraft] = await Promise.all([this.toolStatus("kicad"), this.toolStatus("solidcraft")]);
|
|
2206
|
+
const manifest = await this.manifestState();
|
|
2207
|
+
const jobs = (jobIds ?? []).map((id) => this.installer.snapshot(id)).filter((job) => job !== void 0);
|
|
2208
|
+
const downloadsSupported = this.platform === "win32" || this.platform === "darwin" || this.platform === "linux";
|
|
2209
|
+
return {
|
|
2210
|
+
kicad,
|
|
2211
|
+
solidcraft,
|
|
2212
|
+
manifest,
|
|
2213
|
+
target: {
|
|
2214
|
+
platform: this.platform,
|
|
2215
|
+
arch: this.arch,
|
|
2216
|
+
downloadsSupported
|
|
2217
|
+
},
|
|
2218
|
+
official: OFFICIAL_DOWNLOAD_PAGES,
|
|
2219
|
+
...jobs.length === 0 ? {} : { jobs },
|
|
2220
|
+
...jobs.length === 0 ? {} : { job: jobs[0] }
|
|
2221
|
+
};
|
|
2222
|
+
}
|
|
2223
|
+
/** Manifest projection for the status poll. */
|
|
2224
|
+
async manifestState() {
|
|
2225
|
+
if (this.manifestCache !== void 0 && this.now() - this.manifestCache.at < 6e5) return this.manifestProjection(this.manifestCache.result);
|
|
2226
|
+
const pending = this.loadManifest();
|
|
2227
|
+
if (pending === void 0) return { state: "unknown" };
|
|
2228
|
+
return this.manifestProjection(await pending);
|
|
2229
|
+
}
|
|
2230
|
+
manifestProjection(result) {
|
|
2231
|
+
if (result.ok) return {
|
|
2232
|
+
state: "ready",
|
|
2233
|
+
schemaVersion: result.manifest.schemaVersion,
|
|
2234
|
+
url: this.options.manifestUrl ?? "https://kicad.eda.cn/agent-toolchains.json"
|
|
2235
|
+
};
|
|
2236
|
+
return {
|
|
2237
|
+
state: "unavailable",
|
|
2238
|
+
code: result.code,
|
|
2239
|
+
message: result.message
|
|
2240
|
+
};
|
|
2241
|
+
}
|
|
2242
|
+
/** Fetch the manifest once; concurrent callers share one request. */
|
|
2243
|
+
loadManifest(force = false) {
|
|
2244
|
+
if (!force && this.manifestCache !== void 0 && this.now() - this.manifestCache.at < 6e5) return Promise.resolve(this.manifestCache.result);
|
|
2245
|
+
if (this.manifestPending !== void 0) return this.manifestPending;
|
|
2246
|
+
if (this.platform !== "win32" && this.platform !== "darwin" && this.platform !== "linux") return void 0;
|
|
2247
|
+
this.manifestPending = fetchManifest({
|
|
2248
|
+
...this.options.manifestUrl === void 0 ? {} : { url: this.options.manifestUrl },
|
|
2249
|
+
...this.options.fetchImpl === void 0 ? {} : { fetchImpl: this.options.fetchImpl },
|
|
2250
|
+
platform: this.platform,
|
|
2251
|
+
arch: this.arch
|
|
2252
|
+
}).then((result) => {
|
|
2253
|
+
this.manifestCache = {
|
|
2254
|
+
at: this.now(),
|
|
2255
|
+
result
|
|
2256
|
+
};
|
|
2257
|
+
this.manifestPending = void 0;
|
|
2258
|
+
return result;
|
|
2259
|
+
});
|
|
2260
|
+
return this.manifestPending;
|
|
2261
|
+
}
|
|
2262
|
+
/** The validated manifest entry for one tool, when the manifest answered. */
|
|
2263
|
+
async selectedEntry(tool) {
|
|
2264
|
+
const result = await this.loadManifest();
|
|
2265
|
+
if (result === void 0 || !result.ok) return void 0;
|
|
2266
|
+
return result.manifest.selected[tool];
|
|
2267
|
+
}
|
|
2268
|
+
/** Validated manifest for the installer; a refusal keeps manual paths usable. */
|
|
2269
|
+
async manifest() {
|
|
2270
|
+
return await this.loadManifest(true) ?? {
|
|
2271
|
+
ok: false,
|
|
2272
|
+
code: "network",
|
|
2273
|
+
message: "the toolchain manifest is unavailable on this platform"
|
|
2274
|
+
};
|
|
2275
|
+
}
|
|
2276
|
+
/**
|
|
2277
|
+
* Validate one user-supplied path without persisting anything (§6.3).
|
|
2278
|
+
* @param tool - which toolchain.
|
|
2279
|
+
* @param input - installation root, `bin` directory or executable path.
|
|
2280
|
+
* @returns resolution verdict with the normalised root to persist on success.
|
|
2281
|
+
*/
|
|
2282
|
+
async validate(tool, input) {
|
|
2283
|
+
const root = installationRootOf(tool, input);
|
|
2284
|
+
if (root === void 0) return {
|
|
2285
|
+
ok: false,
|
|
2286
|
+
error: "a path is required"
|
|
2287
|
+
};
|
|
2288
|
+
const resolution = await this.resolve(tool, root);
|
|
2289
|
+
return {
|
|
2290
|
+
ok: resolution.configured,
|
|
2291
|
+
installPath: resolution.installPath,
|
|
2292
|
+
...resolution.cli === void 0 ? {} : { cliPath: resolution.cli },
|
|
2293
|
+
...resolution.app === void 0 ? {} : { appPath: resolution.app },
|
|
2294
|
+
...resolution.version === void 0 ? {} : { version: resolution.version },
|
|
2295
|
+
...resolution.error === void 0 ? {} : { error: resolution.error }
|
|
2296
|
+
};
|
|
2297
|
+
}
|
|
2298
|
+
/** Persist a validated configuration; the host settings service stays authoritative. */
|
|
2299
|
+
async save(tool, input, source) {
|
|
2300
|
+
const outcome = await this.validate(tool, input);
|
|
2301
|
+
if (!outcome.ok || outcome.installPath === void 0) return outcome;
|
|
2302
|
+
const patch = tool === "kicad" ? {
|
|
2303
|
+
kicadRoot: outcome.installPath,
|
|
2304
|
+
kicadVersion: outcome.version ?? "",
|
|
2305
|
+
kicadSource: source,
|
|
2306
|
+
kicadValidatedAt: this.now()
|
|
2307
|
+
} : {
|
|
2308
|
+
solidcraftRoot: outcome.installPath,
|
|
2309
|
+
solidcraftVersion: outcome.version ?? "",
|
|
2310
|
+
solidcraftSource: source,
|
|
2311
|
+
solidcraftValidatedAt: this.now()
|
|
2312
|
+
};
|
|
2313
|
+
if (!(await this.options.persist?.(patch) ?? false)) return {
|
|
2314
|
+
...outcome,
|
|
2315
|
+
ok: false,
|
|
2316
|
+
error: "the Host refused the configuration write"
|
|
2317
|
+
};
|
|
2318
|
+
this.probeCache.clear();
|
|
2319
|
+
return outcome;
|
|
2320
|
+
}
|
|
2321
|
+
/**
|
|
2322
|
+
* Start background discovery for one tool (or both).
|
|
2323
|
+
*
|
|
2324
|
+
* Returns the current discovery state immediately: the run continues off-request
|
|
2325
|
+
* and the UI polls {@link ToolchainManager.status} (§4.2/§5.5).
|
|
2326
|
+
* @param tool - tool to discover; both when omitted.
|
|
2327
|
+
* @returns the discovery state at the moment the request was answered.
|
|
2328
|
+
*/
|
|
2329
|
+
startDiscovery(tool) {
|
|
2330
|
+
for (const candidate of tool === void 0 ? ["kicad", "solidcraft"] : [tool]) {
|
|
2331
|
+
if (this.discovering.has(candidate)) continue;
|
|
2332
|
+
this.discovering.add(candidate);
|
|
2333
|
+
this.discovery[candidate] = {
|
|
2334
|
+
...this.discovery[candidate],
|
|
2335
|
+
state: "running"
|
|
2336
|
+
};
|
|
2337
|
+
this.runDiscovery(candidate);
|
|
2338
|
+
}
|
|
2339
|
+
return {
|
|
2340
|
+
kicad: this.discovery.kicad,
|
|
2341
|
+
solidcraft: this.discovery.solidcraft
|
|
2342
|
+
};
|
|
2343
|
+
}
|
|
2344
|
+
/** One bounded discovery run; a failure is recorded, never thrown at the UI. */
|
|
2345
|
+
async runDiscovery(tool) {
|
|
2346
|
+
try {
|
|
2347
|
+
const roots = candidateRoots(tool, {
|
|
2348
|
+
platform: this.platform,
|
|
2349
|
+
env: this.env,
|
|
2350
|
+
managedRoot: this.managedRoot,
|
|
2351
|
+
home: this.home
|
|
2352
|
+
}, this.options.discoveryInternals ?? {});
|
|
2353
|
+
const validated = await this.validateDiscoveryCandidates(tool, roots);
|
|
2354
|
+
this.discovery[tool] = {
|
|
2355
|
+
tool,
|
|
2356
|
+
state: "done",
|
|
2357
|
+
candidates: validated.candidates,
|
|
2358
|
+
...validated.selected === void 0 ? {} : { selected: validated.selected },
|
|
2359
|
+
finishedAt: this.now()
|
|
2360
|
+
};
|
|
2361
|
+
} catch (error) {
|
|
2362
|
+
this.discovery[tool] = {
|
|
2363
|
+
tool,
|
|
2364
|
+
state: "failed",
|
|
2365
|
+
candidates: [],
|
|
2366
|
+
error: error instanceof Error ? error.message : String(error),
|
|
2367
|
+
finishedAt: this.now()
|
|
2368
|
+
};
|
|
2369
|
+
} finally {
|
|
2370
|
+
this.discovering.delete(tool);
|
|
2371
|
+
}
|
|
2372
|
+
}
|
|
2373
|
+
/**
|
|
2374
|
+
* Probe candidates asynchronously, then rank them with the shared policy.
|
|
2375
|
+
*
|
|
2376
|
+
* The ranking stays in {@link validateCandidates}; this method only supplies
|
|
2377
|
+
* the asynchronous probes it needs, keyed by the executable the resolver will
|
|
2378
|
+
* actually ask about, so discovery and manual validation cannot disagree about
|
|
2379
|
+
* what counts as valid.
|
|
2380
|
+
*/
|
|
2381
|
+
async validateDiscoveryCandidates(tool, roots) {
|
|
2382
|
+
const versions = /* @__PURE__ */ new Map();
|
|
2383
|
+
for (const root of roots) {
|
|
2384
|
+
const layout = resolveToolchain(tool, root.path, { platform: this.platform });
|
|
2385
|
+
const executable = layout.cli ?? layout.app;
|
|
2386
|
+
if (executable === void 0) continue;
|
|
2387
|
+
versions.set(executable, await this.versionOf(tool, executable));
|
|
2388
|
+
}
|
|
2389
|
+
return validateCandidates(tool, roots, {
|
|
2390
|
+
...this.options.discoveryInternals ?? {},
|
|
2391
|
+
probeVersion: (executable) => versions.get(executable)
|
|
2392
|
+
});
|
|
2393
|
+
}
|
|
2394
|
+
/** One directory probe for a diagnostics path (no version process). */
|
|
2395
|
+
probeDirectory(tool, root) {
|
|
2396
|
+
return probeInstallation(tool, root, this.options.discoveryInternals ?? {});
|
|
2397
|
+
}
|
|
2398
|
+
/** Install the manifest entry for one tool; the job reports progress. */
|
|
2399
|
+
async install(tool) {
|
|
2400
|
+
const running = this.installer.activeFor(tool);
|
|
2401
|
+
if (running !== void 0) return { snapshot: running };
|
|
2402
|
+
const result = await this.manifest();
|
|
2403
|
+
if (!result.ok) return { error: result };
|
|
2404
|
+
const entry = result.manifest.selected[tool];
|
|
2405
|
+
if (entry === void 0) return { error: {
|
|
2406
|
+
ok: false,
|
|
2407
|
+
code: "no-entry",
|
|
2408
|
+
message: `the toolchain manifest offers no ${label(tool)} build for this platform`
|
|
2409
|
+
} };
|
|
2410
|
+
const { snapshot, done } = this.installer.start(tool, entry, {
|
|
2411
|
+
validate: async (installPath) => {
|
|
2412
|
+
this.probeCache.clear();
|
|
2413
|
+
const resolution = await this.resolve(tool, installPath);
|
|
2414
|
+
return resolution.configured ? { ok: true } : {
|
|
2415
|
+
ok: false,
|
|
2416
|
+
error: resolution.error ?? "the installation did not validate"
|
|
2417
|
+
};
|
|
2418
|
+
},
|
|
2419
|
+
onProgress: () => {}
|
|
2420
|
+
});
|
|
2421
|
+
done.then(async (outcome) => {
|
|
2422
|
+
await this.afterInstall(tool, entry, outcome);
|
|
2423
|
+
});
|
|
2424
|
+
return { snapshot };
|
|
2425
|
+
}
|
|
2426
|
+
/** Persist the completed installation and drop stale probes (§8.5). */
|
|
2427
|
+
async afterInstall(tool, entry, outcome) {
|
|
2428
|
+
if (!outcome.ok || outcome.installPath === void 0) return;
|
|
2429
|
+
this.probeCache.clear();
|
|
2430
|
+
const probe = await this.resolve(tool, outcome.installPath);
|
|
2431
|
+
if (!probe.configured) return;
|
|
2432
|
+
const patch = tool === "kicad" ? {
|
|
2433
|
+
kicadRoot: canonicalPath(outcome.installPath),
|
|
2434
|
+
kicadVersion: probe.version ?? entry.version,
|
|
2435
|
+
kicadSource: "download",
|
|
2436
|
+
kicadValidatedAt: this.now()
|
|
2437
|
+
} : {
|
|
2438
|
+
solidcraftRoot: canonicalPath(outcome.installPath),
|
|
2439
|
+
solidcraftVersion: probe.version ?? entry.version,
|
|
2440
|
+
solidcraftSource: "download",
|
|
2441
|
+
solidcraftValidatedAt: this.now()
|
|
2442
|
+
};
|
|
2443
|
+
await this.options.persist?.(patch);
|
|
2444
|
+
}
|
|
2445
|
+
/** One job's snapshot. */
|
|
2446
|
+
job(id) {
|
|
2447
|
+
return this.installer.snapshot(id);
|
|
2448
|
+
}
|
|
2449
|
+
/** Cancel one running job. */
|
|
2450
|
+
cancel(id) {
|
|
2451
|
+
return this.installer.cancel(id);
|
|
2452
|
+
}
|
|
2453
|
+
/**
|
|
2454
|
+
* Open the native chooser for one tool.
|
|
2455
|
+
*
|
|
2456
|
+
* The plugin-owned file dialog answers first (it can filter to the expected
|
|
2457
|
+
* executable); when it is unavailable the Host's own native folder chooser
|
|
2458
|
+
* answers instead, so a native picker exists on every supported desktop.
|
|
2459
|
+
* @param tool - which toolchain the choice is for.
|
|
2460
|
+
* @param signal - request lifetime; abort dismisses the chooser.
|
|
2461
|
+
* @returns the picked path, a cancellation, or an unsupported notice.
|
|
2462
|
+
*/
|
|
2463
|
+
async browse(tool, signal) {
|
|
2464
|
+
const request = {
|
|
2465
|
+
title: tool === "kicad" ? "Select kicad-cli" : "Select SolidCraft",
|
|
2466
|
+
filters: TOOLCHAIN_FILTERS[tool]
|
|
2467
|
+
};
|
|
2468
|
+
const outcome = await (this.options.pickFile ?? pickFile)(request, { ...signal === void 0 ? {} : { signal } });
|
|
2469
|
+
if (outcome.kind === "picked") return {
|
|
2470
|
+
kind: "picked",
|
|
2471
|
+
path: outcome.path,
|
|
2472
|
+
mechanism: outcome.mechanism
|
|
2473
|
+
};
|
|
2474
|
+
if (outcome.kind === "cancelled") return {
|
|
2475
|
+
kind: "cancelled",
|
|
2476
|
+
mechanism: outcome.mechanism
|
|
2477
|
+
};
|
|
2478
|
+
if (this.options.pickFolder !== void 0) {
|
|
2479
|
+
const folder = await this.options.pickFolder(request.title);
|
|
2480
|
+
if (folder !== null) return {
|
|
2481
|
+
kind: "picked",
|
|
2482
|
+
path: folder,
|
|
2483
|
+
mechanism: "dsh-directory-picker"
|
|
2484
|
+
};
|
|
2485
|
+
return {
|
|
2486
|
+
kind: "cancelled",
|
|
2487
|
+
mechanism: "dsh-directory-picker"
|
|
2488
|
+
};
|
|
2489
|
+
}
|
|
2490
|
+
return {
|
|
2491
|
+
kind: "unsupported",
|
|
2492
|
+
message: outcome.message
|
|
2493
|
+
};
|
|
2494
|
+
}
|
|
2495
|
+
/**
|
|
2496
|
+
* Compact capability facts for the agent (§12.1).
|
|
2497
|
+
*
|
|
2498
|
+
* Versions and availability only: an agent needs to know whether an export is
|
|
2499
|
+
* possible, not where the binary lives, and the tools resolve the executable
|
|
2500
|
+
* themselves from the same configuration.
|
|
2501
|
+
*/
|
|
2502
|
+
async capabilities() {
|
|
2503
|
+
const [kicad, solidcraft] = await Promise.all([this.toolStatus("kicad"), this.toolStatus("solidcraft")]);
|
|
2504
|
+
return {
|
|
2505
|
+
kicad: {
|
|
2506
|
+
available: kicad.state === "configured",
|
|
2507
|
+
...kicad.version === void 0 ? {} : { version: kicad.version }
|
|
2508
|
+
},
|
|
2509
|
+
solidcraft: {
|
|
2510
|
+
available: solidcraft.state === "configured",
|
|
2511
|
+
...solidcraft.version === void 0 ? {} : { version: solidcraft.version },
|
|
2512
|
+
cliAvailable: solidcraft.state === "configured" && solidcraft.cliPath !== void 0
|
|
2513
|
+
}
|
|
2514
|
+
};
|
|
2515
|
+
}
|
|
2516
|
+
};
|
|
2517
|
+
//#endregion
|
|
4
2518
|
//#region src/index.ts
|
|
5
2519
|
const name = "@huaqiu/hardware-artifacts";
|
|
6
2520
|
const inject = ["webServer", "systemPrompt"];
|
|
@@ -15,8 +2529,22 @@ const inject = ["webServer", "systemPrompt"];
|
|
|
15
2529
|
const Config = Schema.object({
|
|
16
2530
|
kicadRoot: Schema.string().default("").volatile(),
|
|
17
2531
|
solidcraftRoot: Schema.string().default("").volatile(),
|
|
18
|
-
/**
|
|
19
|
-
|
|
2532
|
+
/** Last validated KiCad version; display metadata, never the source of truth. */
|
|
2533
|
+
kicadVersion: Schema.string().default("").volatile(),
|
|
2534
|
+
/** How the KiCad path was obtained (`manual` | `browse` | `download` | `detected`). */
|
|
2535
|
+
kicadSource: Schema.string().default("").volatile(),
|
|
2536
|
+
/** Epoch milliseconds of the last successful KiCad validation. */
|
|
2537
|
+
kicadValidatedAt: Schema.number().default(0).volatile(),
|
|
2538
|
+
solidcraftVersion: Schema.string().default("").volatile(),
|
|
2539
|
+
solidcraftSource: Schema.string().default("").volatile(),
|
|
2540
|
+
solidcraftValidatedAt: Schema.number().default(0).volatile(),
|
|
2541
|
+
/**
|
|
2542
|
+
* First-run setup progress: empty until the operator answers, then `deferred`
|
|
2543
|
+
* (skipped: never re-prompt, keep the reminder) or `complete`. This is the only
|
|
2544
|
+
* flag the client reads; the old `onboardingComplete` boolean was dropped with
|
|
2545
|
+
* its compatibility rule (internal-test build).
|
|
2546
|
+
*/
|
|
2547
|
+
toolchainSetup: Schema.string().default("").volatile(),
|
|
20
2548
|
/**
|
|
21
2549
|
* Place-order origin. Empty uses `HUAQIU_ORDER_BASE_URL`, then the Huaqiu
|
|
22
2550
|
* host. It is only the transport target; it does not imply the endpoint
|
|
@@ -87,11 +2615,87 @@ function apply(ctx, config = {}) {
|
|
|
87
2615
|
}
|
|
88
2616
|
});
|
|
89
2617
|
ctx.effect(() => ctx.provide("hardwareArtifacts", service));
|
|
2618
|
+
/**
|
|
2619
|
+
* Toolchain capability (status/validate/discover/download).
|
|
2620
|
+
*
|
|
2621
|
+
* It reads the same live config the service reads and writes back through the
|
|
2622
|
+
* Host's own settings service, so there is exactly one configuration authority
|
|
2623
|
+
* (§10.5). The write is best-effort: a profile that mounted this row under a
|
|
2624
|
+
* different id still lets the client persist through its config form.
|
|
2625
|
+
*/
|
|
2626
|
+
const SETTINGS_NS = "hardware-artifacts";
|
|
2627
|
+
const persistToolchain = async (patch) => {
|
|
2628
|
+
const settings = hostService("settings");
|
|
2629
|
+
if (settings?.update === void 0) return false;
|
|
2630
|
+
try {
|
|
2631
|
+
await settings.update(SETTINGS_NS, patch);
|
|
2632
|
+
return true;
|
|
2633
|
+
} catch {
|
|
2634
|
+
return false;
|
|
2635
|
+
}
|
|
2636
|
+
};
|
|
2637
|
+
/** The Host's own native directory chooser, when this host has one. */
|
|
2638
|
+
const pickFolder = async (title) => {
|
|
2639
|
+
const capability = hostService("directoryPicker")?.capability?.();
|
|
2640
|
+
if (capability?.kind !== "native" || capability.pick === void 0) return null;
|
|
2641
|
+
const abort = new AbortController();
|
|
2642
|
+
const timer = setTimeout(() => {
|
|
2643
|
+
abort.abort();
|
|
2644
|
+
}, 9e5);
|
|
2645
|
+
timer.unref?.();
|
|
2646
|
+
try {
|
|
2647
|
+
return await capability.pick(abort.signal);
|
|
2648
|
+
} finally {
|
|
2649
|
+
clearTimeout(timer);
|
|
2650
|
+
}
|
|
2651
|
+
};
|
|
2652
|
+
const toolchains = new ToolchainManager({
|
|
2653
|
+
settings: () => ({
|
|
2654
|
+
kicadRoot: readConfig(config.kicadRoot),
|
|
2655
|
+
solidcraftRoot: readConfig(config.solidcraftRoot),
|
|
2656
|
+
kicadVersion: readConfig(config.kicadVersion),
|
|
2657
|
+
kicadSource: readConfig(config.kicadSource),
|
|
2658
|
+
kicadValidatedAt: readConfig(config.kicadValidatedAt),
|
|
2659
|
+
solidcraftVersion: readConfig(config.solidcraftVersion),
|
|
2660
|
+
solidcraftSource: readConfig(config.solidcraftSource),
|
|
2661
|
+
solidcraftValidatedAt: readConfig(config.solidcraftValidatedAt)
|
|
2662
|
+
}),
|
|
2663
|
+
persist: persistToolchain,
|
|
2664
|
+
pickFolder
|
|
2665
|
+
});
|
|
2666
|
+
ctx.effect(() => ctx.provide("hardwareToolchains", toolchains));
|
|
2667
|
+
ctx.effect(() => {
|
|
2668
|
+
toolchains.loadManifest()?.catch(() => void 0);
|
|
2669
|
+
return () => {};
|
|
2670
|
+
}, "hardware-artifacts: toolchain manifest");
|
|
90
2671
|
if (ctx.webServer !== void 0) ctx.effect(() => ctx.webServer.register({
|
|
91
2672
|
kind: "prefix",
|
|
92
2673
|
path: HARDWARE_ROUTE_PREFIX,
|
|
93
|
-
handler: createHardwareHandler(service, {
|
|
2674
|
+
handler: createHardwareHandler(service, {
|
|
2675
|
+
resolveWorkspace: sessionWorkspace,
|
|
2676
|
+
toolchain: toolchains
|
|
2677
|
+
})
|
|
94
2678
|
}), "hardware-artifacts: local read/launch routes");
|
|
2679
|
+
/**
|
|
2680
|
+
* Agent tools.
|
|
2681
|
+
*
|
|
2682
|
+
* Acquired without `inject` for the same reason as the other optional
|
|
2683
|
+
* services: the panel and its routes must keep working in a host without a
|
|
2684
|
+
* tool registry, and a missing registry costs the agent surface, not the
|
|
2685
|
+
* plugin. The tools take a path and run `kicad-cli` themselves, so this is
|
|
2686
|
+
* the fabrication path that needs neither HQ Edge nor a running PCB editor.
|
|
2687
|
+
*/
|
|
2688
|
+
const tools = hostService("tools");
|
|
2689
|
+
if (tools !== void 0 && typeof tools.register === "function") for (const tool of createHardwareTools({
|
|
2690
|
+
service,
|
|
2691
|
+
workspaceOf: (sessionId) => sessionId === void 0 ? void 0 : sessionWorkspace(sessionId)
|
|
2692
|
+
})) {
|
|
2693
|
+
const label = tool.name ?? "tool";
|
|
2694
|
+
ctx.effect(() => {
|
|
2695
|
+
const dispose = tools.register(tool);
|
|
2696
|
+
return typeof dispose === "function" ? dispose : () => {};
|
|
2697
|
+
}, `hardware-artifacts: ${label}`);
|
|
2698
|
+
}
|
|
95
2699
|
const prompt = ctx.systemPrompt;
|
|
96
2700
|
if (prompt !== void 0 && typeof prompt.context === "function") ctx.effect(() => prompt.context({
|
|
97
2701
|
name: "hardware-environment",
|
|
@@ -101,4 +2705,4 @@ function apply(ctx, config = {}) {
|
|
|
101
2705
|
}), "hardware-artifacts: compact agent environment");
|
|
102
2706
|
}
|
|
103
2707
|
//#endregion
|
|
104
|
-
export { Config, DEFAULT_ORDER_BASE_URL, DEFAULT_ORDER_PAGE_BASE, HARDWARE_ROUTE_PREFIX, HardwareArtifactService, ORDER_PATHS, ORDER_SOURCE_TID, apply, createHardwareHandler, inject, name, orderBomCsv, orderBomRows, orderIdsFromUrl, parsePositions, pcbOrderForm, pcbOrderUrl, positionsCsv, readBoardFacts, smtOrderForm, smtOrderUrl, smtOrderUrlFromBackend, snapHoleTier, snapThickness, snapTraceTier };
|
|
2708
|
+
export { Config, DEFAULT_ORDER_BASE_URL, DEFAULT_ORDER_PAGE_BASE, HARDWARE_ROUTE_PREFIX, HardwareArtifactService, ORDER_PATHS, ORDER_SOURCE_TID, TOOLCHAIN_ROUTE_PREFIX, ToolchainManager, apply, createHardwareHandler, createHardwareTools, expectedCopperLayers, hardwareToolNames, inject, name, orderBomCsv, orderBomRows, orderIdsFromUrl, parsePositions, pcbOrderForm, pcbOrderUrl, positionsCsv, readBoardFacts, smtOrderForm, smtOrderUrl, smtOrderUrlFromBackend, snapHoleTier, snapThickness, snapTraceTier, validateFabricationPackage, validationSummary };
|