@huaqiu/hardware-artifacts 0.7.12 → 0.7.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.mts CHANGED
@@ -1,21 +1,64 @@
1
- import { ArtifactKind, DiscoveryResult, HardwareArtifact, HardwareArtifactService, HardwareArtifactsOptions, HardwareProject, InstallationInfo, Installations, NativeApplication, OpenArtifactRequest, OpenArtifactResult } from "./service.mjs";
2
- import { HARDWARE_ROUTE_PREFIX, createHardwareHandler } from "./routes.mjs";
1
+ import { A as PositionRow, B as smtOrderUrl, D as DEFAULT_ORDER_PAGE_BASE, E as DEFAULT_ORDER_BASE_URL, F as pcbOrderForm, H as snapHoleTier, I as pcbOrderUrl, L as positionsCsv, M as orderBomRows, N as orderIdsFromUrl, O as ORDER_PATHS, P as parsePositions, R as readBoardFacts, T as BoardFacts, U as snapThickness, V as smtOrderUrlFromBackend, W as snapTraceTier, _ as OrderConfigInfo, a as FabricationResult, b as PlaceOrderResult, c as HardwareArtifact, d as HardwareProject, f as InstallationInfo, g as OpenArtifactResult, h as OpenArtifactRequest, i as DiscoveryResult, j as orderBomCsv, k as ORDER_SOURCE_TID, l as HardwareArtifactService, m as NativeApplication, p as Installations, t as ArtifactKind, u as HardwareArtifactsOptions, y as PlaceOrderRequest, z as smtOrderForm } from "./service-CtVn7z8b.mjs";
2
+ import { HARDWARE_ROUTE_PREFIX, HardwareHandlerOptions, WorkspaceResolver, createHardwareHandler } from "./routes.mjs";
3
3
  import Schema from "@deepseek-ai/schemastery";
4
4
  import { Context } from "@deepseek-ai/cordis";
5
5
  //#region src/index.d.ts
6
6
  declare const name = "@huaqiu/hardware-artifacts";
7
7
  declare const inject: readonly ["webServer", "systemPrompt"];
8
- /** User-scoped installation settings persisted by DSH's host-backed config. */
8
+ /**
9
+ * User-scoped installation settings persisted by DSH's host-backed config.
10
+ *
11
+ * Every field is `.volatile()`: DSH's settings service only projects volatile
12
+ * fields into editable forms, and only volatile writes are persisted to the
13
+ * active profile patch. A non-volatile field here would make the Hardware
14
+ * Engineering settings page read-only by construction.
15
+ */
9
16
  declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
10
- kicadRoot: Schema<string, string, "defined">;
11
- solidcraftRoot: Schema<string, string, "defined">;
17
+ kicadRoot: Schema<string, string, "volatile-defined">;
18
+ solidcraftRoot: Schema<string, string, "volatile-defined">;
19
+ /** Set by the first-run wizard once setup was completed or skipped. */
20
+ onboardingComplete: Schema<boolean, boolean, "volatile-defined">;
21
+ /**
22
+ * Place-order origin. Empty uses `HUAQIU_ORDER_BASE_URL`, then the Huaqiu
23
+ * host. It is only the transport target; it does not imply the endpoint
24
+ * supports the order contract.
25
+ */
26
+ orderBaseUrl: Schema<string, string, "volatile-defined">;
27
+ /**
28
+ * Huaqiu access token for the assembly endpoint. Volatile so it stays in the
29
+ * profile patch and never reaches the client bundle.
30
+ */
31
+ accessToken: Schema<string, string, "volatile-defined">;
12
32
  }>>, Schemastery.ObjectT<NoInfer<{
13
- kicadRoot: Schema<string, string, "defined">;
14
- solidcraftRoot: Schema<string, string, "defined">;
33
+ kicadRoot: Schema<string, string, "volatile-defined">;
34
+ solidcraftRoot: Schema<string, string, "volatile-defined">;
35
+ /** Set by the first-run wizard once setup was completed or skipped. */
36
+ onboardingComplete: Schema<boolean, boolean, "volatile-defined">;
37
+ /**
38
+ * Place-order origin. Empty uses `HUAQIU_ORDER_BASE_URL`, then the Huaqiu
39
+ * host. It is only the transport target; it does not imply the endpoint
40
+ * supports the order contract.
41
+ */
42
+ orderBaseUrl: Schema<string, string, "volatile-defined">;
43
+ /**
44
+ * Huaqiu access token for the assembly endpoint. Volatile so it stays in the
45
+ * profile patch and never reaches the client bundle.
46
+ */
47
+ accessToken: Schema<string, string, "volatile-defined">;
15
48
  }>>, "plain">;
49
+ /**
50
+ * A schema field value: a plain value, or the stable reference a volatile
51
+ * field resolves to (`{ get(): T }`, see `@deepseek-ai/cosmokit`).
52
+ */
53
+ type ConfigValue<T> = T | {
54
+ get(): T;
55
+ };
16
56
  interface HardwareArtifactsPluginConfig {
17
- readonly kicadRoot?: string;
18
- readonly solidcraftRoot?: string;
57
+ readonly kicadRoot?: ConfigValue<string>;
58
+ readonly solidcraftRoot?: ConfigValue<string>;
59
+ readonly onboardingComplete?: ConfigValue<boolean>;
60
+ readonly orderBaseUrl?: ConfigValue<string>;
61
+ readonly accessToken?: ConfigValue<string>;
19
62
  }
20
63
  declare module '@deepseek-ai/cordis' {
21
64
  interface Context {
@@ -24,4 +67,4 @@ declare module '@deepseek-ai/cordis' {
24
67
  }
25
68
  declare function apply(ctx: Context, config?: HardwareArtifactsPluginConfig): void;
26
69
  //#endregion
27
- export { type ArtifactKind, Config, type DiscoveryResult, HARDWARE_ROUTE_PREFIX, type HardwareArtifact, HardwareArtifactService, type HardwareArtifactsOptions, HardwareArtifactsPluginConfig, type HardwareProject, type InstallationInfo, type Installations, type NativeApplication, type OpenArtifactRequest, type OpenArtifactResult, apply, createHardwareHandler, inject, name };
70
+ export { type ArtifactKind, type BoardFacts, Config, ConfigValue, DEFAULT_ORDER_BASE_URL, DEFAULT_ORDER_PAGE_BASE, type DiscoveryResult, type FabricationResult, HARDWARE_ROUTE_PREFIX, type HardwareArtifact, HardwareArtifactService, type HardwareArtifactsOptions, HardwareArtifactsPluginConfig, type HardwareHandlerOptions, type HardwareProject, type InstallationInfo, type Installations, type NativeApplication, ORDER_PATHS, ORDER_SOURCE_TID, type OpenArtifactRequest, type OpenArtifactResult, type OrderConfigInfo, type PlaceOrderRequest, type PlaceOrderResult, type PositionRow, type WorkspaceResolver, apply, createHardwareHandler, inject, name, orderBomCsv, orderBomRows, orderIdsFromUrl, parsePositions, pcbOrderForm, pcbOrderUrl, positionsCsv, readBoardFacts, smtOrderForm, smtOrderUrl, smtOrderUrlFromBackend, snapHoleTier, snapThickness, snapTraceTier };
package/lib/index.mjs CHANGED
@@ -1,24 +1,96 @@
1
1
  import { HARDWARE_ROUTE_PREFIX, createHardwareHandler } from "./routes.mjs";
2
- import { HardwareArtifactService } from "./service.mjs";
2
+ import { _ as smtOrderUrl, a as DEFAULT_ORDER_PAGE_BASE, b as snapThickness, c as orderBomCsv, d as parsePositions, f as pcbOrderForm, g as smtOrderForm, h as readBoardFacts, i as DEFAULT_ORDER_BASE_URL, l as orderBomRows, m as positionsCsv, o as ORDER_PATHS, p as pcbOrderUrl, s as ORDER_SOURCE_TID, t as HardwareArtifactService, u as orderIdsFromUrl, v as smtOrderUrlFromBackend, x as snapTraceTier, y as snapHoleTier } from "./service-Yrc2C_eo.mjs";
3
3
  import Schema from "@deepseek-ai/schemastery";
4
4
  //#region src/index.ts
5
5
  const name = "@huaqiu/hardware-artifacts";
6
6
  const inject = ["webServer", "systemPrompt"];
7
- /** User-scoped installation settings persisted by DSH's host-backed config. */
7
+ /**
8
+ * User-scoped installation settings persisted by DSH's host-backed config.
9
+ *
10
+ * Every field is `.volatile()`: DSH's settings service only projects volatile
11
+ * fields into editable forms, and only volatile writes are persisted to the
12
+ * active profile patch. A non-volatile field here would make the Hardware
13
+ * Engineering settings page read-only by construction.
14
+ */
8
15
  const Config = Schema.object({
9
- kicadRoot: Schema.string().default(""),
10
- solidcraftRoot: Schema.string().default("")
16
+ kicadRoot: Schema.string().default("").volatile(),
17
+ solidcraftRoot: Schema.string().default("").volatile(),
18
+ /** Set by the first-run wizard once setup was completed or skipped. */
19
+ onboardingComplete: Schema.boolean().default(false).volatile(),
20
+ /**
21
+ * Place-order origin. Empty uses `HUAQIU_ORDER_BASE_URL`, then the Huaqiu
22
+ * host. It is only the transport target; it does not imply the endpoint
23
+ * supports the order contract.
24
+ */
25
+ orderBaseUrl: Schema.string().default("").volatile(),
26
+ /**
27
+ * Huaqiu access token for the assembly endpoint. Volatile so it stays in the
28
+ * profile patch and never reaches the client bundle.
29
+ */
30
+ accessToken: Schema.string().default("").volatile()
11
31
  });
32
+ /** Read one config field, resolving a volatile reference at call time. */
33
+ function readConfig(value) {
34
+ if (value === void 0) return void 0;
35
+ if (typeof value === "object" && value !== null && typeof value.get === "function") return value.get();
36
+ return value;
37
+ }
12
38
  function apply(ctx, config = {}) {
39
+ /**
40
+ * Read one optional host service without declaring it in `inject`.
41
+ *
42
+ * `hardwareArtifacts` must stay usable — and unit-testable — in a profile
43
+ * where auth, sessions or a sandbox policy are absent; each caller degrades
44
+ * on its own instead of the whole plugin refusing to mount.
45
+ */
46
+ const hostService = (name) => {
47
+ const get = ctx.get;
48
+ return typeof get === "function" ? get.call(ctx, name) : void 0;
49
+ };
50
+ /**
51
+ * The signed-in Huaqiu session, when the auth plugin is mounted.
52
+ *
53
+ * Read lazily rather than declared in `inject`: only the order path needs the
54
+ * token.
55
+ */
56
+ const huaqiuAuth = () => hostService("huaqiuAuth");
57
+ /**
58
+ * Workspace root of one DSH session, from the host's own session header.
59
+ *
60
+ * This is what makes authorization survive a workspace switch: the base for
61
+ * a read comes from the session the request names, so another session's
62
+ * discovery cannot revoke it. Falling back to the sandbox policy root keeps
63
+ * a session without a header usable instead of unauthorized.
64
+ */
65
+ const sessionWorkspace = async (sessionId) => {
66
+ const live = hostService("sessions")?.get?.(sessionId)?.header?.cwd;
67
+ if (live !== void 0) return live;
68
+ try {
69
+ const stored = await hostService("sessionPersistence")?.stat?.(sessionId);
70
+ if (stored?.header?.cwd !== void 0) return stored.header.cwd;
71
+ } catch {}
72
+ return hostService("sandboxPolicy")?.workspaceRoot;
73
+ };
13
74
  const service = new HardwareArtifactService({
14
- ...config.kicadRoot ? { kicadRoot: config.kicadRoot } : {},
15
- ...config.solidcraftRoot ? { solidcraftRoot: config.solidcraftRoot } : {}
75
+ settings: () => ({
76
+ kicadRoot: readConfig(config.kicadRoot),
77
+ solidcraftRoot: readConfig(config.solidcraftRoot),
78
+ orderBaseUrl: readConfig(config.orderBaseUrl),
79
+ accessToken: readConfig(config.accessToken)
80
+ }),
81
+ authToken: async () => {
82
+ try {
83
+ return await huaqiuAuth()?.auth?.getAccessToken?.() ?? null;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
16
88
  });
17
89
  ctx.effect(() => ctx.provide("hardwareArtifacts", service));
18
90
  if (ctx.webServer !== void 0) ctx.effect(() => ctx.webServer.register({
19
91
  kind: "prefix",
20
92
  path: HARDWARE_ROUTE_PREFIX,
21
- handler: createHardwareHandler(service)
93
+ handler: createHardwareHandler(service, { resolveWorkspace: sessionWorkspace })
22
94
  }), "hardware-artifacts: local read/launch routes");
23
95
  const prompt = ctx.systemPrompt;
24
96
  if (prompt !== void 0 && typeof prompt.context === "function") ctx.effect(() => prompt.context({
@@ -29,4 +101,4 @@ function apply(ctx, config = {}) {
29
101
  }), "hardware-artifacts: compact agent environment");
30
102
  }
31
103
  //#endregion
32
- export { Config, HARDWARE_ROUTE_PREFIX, HardwareArtifactService, apply, createHardwareHandler, inject, name };
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 };
package/lib/routes.d.mts CHANGED
@@ -1,7 +1,18 @@
1
- import { HardwareArtifactService } from "./service.mjs";
1
+ import { l as HardwareArtifactService } from "./service-CtVn7z8b.mjs";
2
2
  import { IncomingMessage, ServerResponse } from "node:http";
3
3
  //#region src/routes.d.ts
4
4
  declare const HARDWARE_ROUTE_PREFIX = "/api/v1/hardware";
5
- declare function createHardwareHandler(service: HardwareArtifactService): (req: IncomingMessage, res: ServerResponse) => void;
5
+ /**
6
+ * Resolve the workspace root of one DSH session, host-side.
7
+ *
8
+ * Supplied by the plugin from the `sessions` service, so the base for an
9
+ * authorization check comes from the session header rather than from a value
10
+ * the browser sent — and never from whichever session discovered last.
11
+ */
12
+ type WorkspaceResolver = (sessionId: string) => Promise<string | undefined> | string | undefined;
13
+ interface HardwareHandlerOptions {
14
+ readonly resolveWorkspace?: WorkspaceResolver;
15
+ }
16
+ declare function createHardwareHandler(service: HardwareArtifactService, options?: HardwareHandlerOptions): (req: IncomingMessage, res: ServerResponse) => void;
6
17
  //#endregion
7
- export { HARDWARE_ROUTE_PREFIX, createHardwareHandler };
18
+ export { HARDWARE_ROUTE_PREFIX, HardwareHandlerOptions, WorkspaceResolver, createHardwareHandler };
package/lib/routes.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs";
1
2
  //#region src/routes.ts
2
3
  const HARDWARE_ROUTE_PREFIX = "/api/v1/hardware";
3
4
  function sendJson(res, status, body) {
@@ -28,8 +29,55 @@ async function readJson(req, maxBytes = 65536) {
28
29
  function asString(value) {
29
30
  return typeof value === "string" && value.length > 0 ? value : void 0;
30
31
  }
31
- function createHardwareHandler(service) {
32
- let lastDiscovery;
32
+ function failure(error) {
33
+ const code = typeof error.code === "string" ? String(error.code) : "internal";
34
+ return {
35
+ status: typeof error.status === "number" ? Number(error.status) : 500,
36
+ body: {
37
+ ok: false,
38
+ error: {
39
+ code,
40
+ message: error instanceof Error ? error.message : String(error)
41
+ }
42
+ }
43
+ };
44
+ }
45
+ /** Roots a request may read: the caller's workspace, then the host's own. */
46
+ function rootsOf(body) {
47
+ if (body === null || typeof body !== "object") return [];
48
+ return [asString(body.cwd), asString(body.workspace)].filter((value) => value !== void 0);
49
+ }
50
+ /** The DSH session a request belongs to: a query field for reads, a body field for writes. */
51
+ function sessionOf(url, body) {
52
+ return (body === null || typeof body !== "object" ? void 0 : asString(body.session)) ?? asString(url.searchParams.get("session") ?? void 0);
53
+ }
54
+ /**
55
+ * Everything one request may read: the roots it named plus the workspace of the
56
+ * session it belongs to.
57
+ *
58
+ * The session's workspace is resolved here, not taken from `cwd`: the browser
59
+ * sends whichever cwd its session hook held at render time, and a viewer that
60
+ * stayed mounted across a workspace switch would otherwise authorize against a
61
+ * workspace it no longer shows.
62
+ */
63
+ async function authorizeRequest(options, url, body) {
64
+ const sessionId = sessionOf(url, body);
65
+ const roots = rootsOf(body);
66
+ for (const key of ["cwd", "workspace"]) {
67
+ const value = asString(url.searchParams.get(key) ?? void 0);
68
+ if (value !== void 0 && !roots.includes(value)) roots.push(value);
69
+ }
70
+ if (sessionId === void 0 || options.resolveWorkspace === void 0) return { roots };
71
+ try {
72
+ const workspace = await options.resolveWorkspace(sessionId);
73
+ if (workspace !== void 0 && workspace !== "") roots.push(workspace);
74
+ } catch {}
75
+ return {
76
+ roots,
77
+ sessionId
78
+ };
79
+ }
80
+ function createHardwareHandler(service, options = {}) {
33
81
  return (req, res) => {
34
82
  if (!isTrustedRequest(req)) {
35
83
  sendJson(res, 403, {
@@ -46,11 +94,16 @@ function createHardwareHandler(service) {
46
94
  const url = new URL(req.url ?? "/", "http://dsh.internal");
47
95
  const p = url.pathname;
48
96
  if (req.method === "GET" && p === `/api/v1/hardware/projects`) {
49
- const result = service.discover(asString(url.searchParams.get("cwd") ?? void 0) ?? process.cwd(), asString(url.searchParams.get("project") ?? void 0));
50
- lastDiscovery = result;
97
+ const sessionId = asString(url.searchParams.get("session") ?? void 0);
98
+ let workspace = asString(url.searchParams.get("cwd") ?? void 0);
99
+ if (workspace === void 0 && sessionId !== void 0 && options.resolveWorkspace !== void 0) try {
100
+ workspace = await options.resolveWorkspace(sessionId);
101
+ } catch {
102
+ workspace = void 0;
103
+ }
51
104
  sendJson(res, 200, {
52
105
  ok: true,
53
- ...result
106
+ ...service.discover(workspace ?? process.cwd(), asString(url.searchParams.get("project") ?? void 0), sessionId)
54
107
  });
55
108
  return;
56
109
  }
@@ -62,25 +115,308 @@ function createHardwareHandler(service) {
62
115
  return;
63
116
  }
64
117
  if (req.method === "GET" && p === `/api/v1/hardware/environment`) {
118
+ const sessionId = asString(url.searchParams.get("session") ?? void 0);
65
119
  sendJson(res, 200, {
66
120
  ok: true,
67
- text: service.environmentText(lastDiscovery),
121
+ text: service.environmentText(service.discovery(sessionId)),
68
122
  childEnv: service.childEnvironment()
69
123
  });
70
124
  return;
71
125
  }
126
+ if (req.method === "GET" && p === `/api/v1/hardware/source`) {
127
+ const artifactPath = asString(url.searchParams.get("path"));
128
+ if (artifactPath === void 0) {
129
+ sendJson(res, 400, {
130
+ ok: false,
131
+ error: {
132
+ code: "invalid-request",
133
+ message: "path is required"
134
+ }
135
+ });
136
+ return;
137
+ }
138
+ const revision = asString(url.searchParams.get("revision") ?? void 0);
139
+ const { roots, sessionId } = await authorizeRequest(options, url);
140
+ try {
141
+ sendJson(res, 200, {
142
+ ok: true,
143
+ ...await service.readSource({
144
+ artifactPath,
145
+ ...revision === void 0 ? {} : { expectedRevision: revision },
146
+ roots,
147
+ ...sessionId === void 0 ? {} : { sessionId }
148
+ })
149
+ });
150
+ } catch (error) {
151
+ const { status, body } = failure(error);
152
+ sendJson(res, status, body);
153
+ }
154
+ return;
155
+ }
156
+ if (req.method === "GET" && p === `/api/v1/hardware/order`) {
157
+ sendJson(res, 200, {
158
+ ok: true,
159
+ ...await service.orderConfig()
160
+ });
161
+ return;
162
+ }
163
+ if (req.method === "POST" && p === `/api/v1/hardware/fabrication`) {
164
+ const body = await readJson(req);
165
+ const artifactPath = asString(body.path);
166
+ if (artifactPath === void 0) {
167
+ sendJson(res, 400, {
168
+ ok: false,
169
+ error: {
170
+ code: "invalid-request",
171
+ message: "path is required"
172
+ }
173
+ });
174
+ return;
175
+ }
176
+ const schematic = asString(body.schematic);
177
+ const { roots, sessionId } = await authorizeRequest(options, url, body);
178
+ try {
179
+ const prepared = await service.fabricate({
180
+ boardPath: artifactPath,
181
+ ...schematic === void 0 ? {} : { schematicPath: schematic },
182
+ roots,
183
+ ...sessionId === void 0 ? {} : { sessionId }
184
+ });
185
+ sendJson(res, 200, {
186
+ ok: true,
187
+ boardPath: prepared.boardPath,
188
+ revision: prepared.revision,
189
+ generatedAt: prepared.generatedAt,
190
+ facts: prepared.facts,
191
+ archive: prepared.archive,
192
+ ...prepared.assembly === void 0 ? {} : { assembly: prepared.assembly }
193
+ });
194
+ } catch (error) {
195
+ const { status, body: failureBody } = failure(error);
196
+ sendJson(res, status, failureBody);
197
+ }
198
+ return;
199
+ }
200
+ if (req.method === "POST" && p === `/api/v1/hardware/order/pcb`) {
201
+ const body = await readJson(req);
202
+ if (body.confirm !== true) {
203
+ sendJson(res, 400, {
204
+ ok: false,
205
+ error: {
206
+ code: "confirmation-required",
207
+ message: "placing an order uploads the board files and requires explicit confirmation"
208
+ }
209
+ });
210
+ return;
211
+ }
212
+ const artifactPath = asString(body.path);
213
+ if (artifactPath === void 0) {
214
+ sendJson(res, 400, {
215
+ ok: false,
216
+ error: {
217
+ code: "invalid-request",
218
+ message: "path is required"
219
+ }
220
+ });
221
+ return;
222
+ }
223
+ const schematic = asString(body.schematic);
224
+ const { roots, sessionId } = await authorizeRequest(options, url, body);
225
+ try {
226
+ sendJson(res, 200, {
227
+ ok: true,
228
+ ...await service.placeOrder({
229
+ kind: "pcb",
230
+ boardPath: artifactPath,
231
+ ...schematic === void 0 ? {} : { schematicPath: schematic },
232
+ roots,
233
+ ...sessionId === void 0 ? {} : { sessionId },
234
+ ...typeof body.quantity === "number" ? { quantity: body.quantity } : {},
235
+ ...body.launch === false ? { launch: false } : {}
236
+ })
237
+ });
238
+ } catch (error) {
239
+ const { status, body: failureBody } = failure(error);
240
+ sendJson(res, status, failureBody);
241
+ }
242
+ return;
243
+ }
244
+ if (req.method === "POST" && p === `/api/v1/hardware/order/smt`) {
245
+ const body = await readJson(req);
246
+ if (body.confirm !== true) {
247
+ sendJson(res, 400, {
248
+ ok: false,
249
+ error: {
250
+ code: "confirmation-required",
251
+ message: "placing an assembly order uploads the board, BOM and positions and requires explicit confirmation"
252
+ }
253
+ });
254
+ return;
255
+ }
256
+ const artifactPath = asString(body.path);
257
+ if (artifactPath === void 0) {
258
+ sendJson(res, 400, {
259
+ ok: false,
260
+ error: {
261
+ code: "invalid-request",
262
+ message: "path is required"
263
+ }
264
+ });
265
+ return;
266
+ }
267
+ const schematic = asString(body.schematic);
268
+ const { roots, sessionId } = await authorizeRequest(options, url, body);
269
+ try {
270
+ sendJson(res, 200, {
271
+ ok: true,
272
+ ...await service.placeOrder({
273
+ kind: "smt",
274
+ boardPath: artifactPath,
275
+ ...schematic === void 0 ? {} : { schematicPath: schematic },
276
+ roots,
277
+ ...sessionId === void 0 ? {} : { sessionId },
278
+ ...typeof body.quantity === "number" ? { quantity: body.quantity } : {},
279
+ ...body.launch === false ? { launch: false } : {}
280
+ })
281
+ });
282
+ } catch (error) {
283
+ const { status, body: failureBody } = failure(error);
284
+ sendJson(res, status, failureBody);
285
+ }
286
+ return;
287
+ }
288
+ if (req.method === "POST" && p === `/api/v1/hardware/order/open`) {
289
+ const orderUrl = asString((await readJson(req)).url);
290
+ if (orderUrl === void 0) {
291
+ sendJson(res, 400, {
292
+ ok: false,
293
+ error: {
294
+ code: "invalid-request",
295
+ message: "url is required"
296
+ }
297
+ });
298
+ return;
299
+ }
300
+ try {
301
+ sendJson(res, 200, {
302
+ ok: true,
303
+ ...service.openOrderUrl(orderUrl)
304
+ });
305
+ } catch (error) {
306
+ const { status, body: failureBody } = failure(error);
307
+ sendJson(res, status, failureBody);
308
+ }
309
+ return;
310
+ }
311
+ if (req.method === "POST" && p === `/api/v1/hardware/bom`) {
312
+ const body = await readJson(req);
313
+ const artifactPath = asString(body.path);
314
+ if (artifactPath === void 0) {
315
+ sendJson(res, 400, {
316
+ ok: false,
317
+ error: {
318
+ code: "invalid-request",
319
+ message: "path is required"
320
+ }
321
+ });
322
+ return;
323
+ }
324
+ const { roots, sessionId } = await authorizeRequest(options, url, body);
325
+ try {
326
+ sendJson(res, 200, {
327
+ ok: true,
328
+ ...await service.exportBom({
329
+ artifactPath,
330
+ roots,
331
+ ...sessionId === void 0 ? {} : { sessionId }
332
+ })
333
+ });
334
+ } catch (error) {
335
+ const { status, body } = failure(error);
336
+ sendJson(res, status, body);
337
+ }
338
+ return;
339
+ }
340
+ if (req.method === "POST" && p === `/api/v1/hardware/glb`) {
341
+ const body = await readJson(req);
342
+ const artifactPath = asString(body.path);
343
+ if (artifactPath === void 0) {
344
+ sendJson(res, 400, {
345
+ ok: false,
346
+ error: {
347
+ code: "invalid-request",
348
+ message: "path is required"
349
+ }
350
+ });
351
+ return;
352
+ }
353
+ const { roots, sessionId } = await authorizeRequest(options, url, body);
354
+ try {
355
+ const glb = await service.exportGlb({
356
+ artifactPath,
357
+ roots,
358
+ ...sessionId === void 0 ? {} : { sessionId }
359
+ });
360
+ const query = new URLSearchParams({
361
+ path: glb.path,
362
+ revision: glb.revision
363
+ });
364
+ sendJson(res, 200, {
365
+ ok: true,
366
+ path: glb.path,
367
+ revision: glb.revision,
368
+ bytes: glb.bytes,
369
+ generatedAt: glb.generatedAt,
370
+ cached: glb.cached,
371
+ url: `/api/v1/hardware/glb-file?${query.toString()}`
372
+ });
373
+ } catch (error) {
374
+ const { status, body } = failure(error);
375
+ sendJson(res, status, body);
376
+ }
377
+ return;
378
+ }
379
+ if (req.method === "GET" && p === `/api/v1/hardware/glb-file`) {
380
+ const artifactPath = asString(url.searchParams.get("path"));
381
+ const revision = asString(url.searchParams.get("revision"));
382
+ if (artifactPath === void 0 || revision === void 0) {
383
+ sendJson(res, 400, {
384
+ ok: false,
385
+ error: {
386
+ code: "invalid-request",
387
+ message: "path and revision are required"
388
+ }
389
+ });
390
+ return;
391
+ }
392
+ try {
393
+ const file = service.glbFile(artifactPath, revision);
394
+ const bytes = readFileSync(file);
395
+ res.writeHead(200, {
396
+ "content-type": "model/gltf-binary",
397
+ "content-length": bytes.byteLength,
398
+ "cache-control": "no-store",
399
+ "x-huaqiu-source-revision": revision
400
+ });
401
+ res.end(bytes);
402
+ } catch (error) {
403
+ const { status, body } = failure(error);
404
+ sendJson(res, status, body);
405
+ }
406
+ return;
407
+ }
72
408
  if (req.method === "POST" && p === `/api/v1/hardware/open`) {
73
409
  const body = await readJson(req);
74
410
  const application = asString(body.application);
75
411
  const artifactPath = asString(body.artifactPath);
76
412
  const kind = asString(body.kind);
77
- if (application !== "kicad" && application !== "solidcraft") {
413
+ if (application !== "kicad") {
78
414
  sendJson(res, 400, {
79
- ok: false,
80
415
  error: {
81
416
  code: "invalid-application",
82
- message: "application must be kicad or solidcraft"
83
- }
417
+ message: "application must be kicad"
418
+ },
419
+ ok: false
84
420
  });
85
421
  return;
86
422
  }
@@ -105,14 +441,8 @@ function createHardwareHandler(service) {
105
441
  })
106
442
  });
107
443
  } catch (error) {
108
- const code = typeof error.code === "string" ? String(error.code) : "launch-failed";
109
- sendJson(res, typeof error.status === "number" ? Number(error.status) : 500, {
110
- ok: false,
111
- error: {
112
- code,
113
- message: error instanceof Error ? error.message : String(error)
114
- }
115
- });
444
+ const { status, body } = failure(error);
445
+ sendJson(res, status, body);
116
446
  }
117
447
  return;
118
448
  }
@@ -124,13 +454,8 @@ function createHardwareHandler(service) {
124
454
  }
125
455
  });
126
456
  } catch (error) {
127
- sendJson(res, typeof error.status === "number" ? Number(error.status) : 500, {
128
- ok: false,
129
- error: {
130
- code: "internal",
131
- message: error instanceof Error ? error.message : String(error)
132
- }
133
- });
457
+ const { status, body } = failure(error);
458
+ sendJson(res, status, body);
134
459
  }
135
460
  })();
136
461
  };