@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/service.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as groupBomRows, S as SourceResult, _ 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, l as HardwareArtifactService, m as NativeApplication, n as BomResult, o as GlbRequest, p as Installations, r as BomRow, s as GlbResult, t as ArtifactKind, u as HardwareArtifactsOptions, v as OrderPackageSummary, w as parseCsv, x as SourceRequest, y as PlaceOrderRequest } from "./service-CtVn7z8b.mjs";
1
+ import { C as groupBomRows, S as SourceResult, _ 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, l as HardwareArtifactService, m as NativeApplication, n as BomResult, o as GlbRequest, p as Installations, r as BomRow, s as GlbResult, t as ArtifactKind, u as HardwareArtifactsOptions, v as OrderPackageSummary, w as parseCsv, x as SourceRequest, y as PlaceOrderRequest } from "./service-BGecln85.mjs";
2
2
  export { ArtifactKind, BomResult, BomRow, DiscoveryResult, FabricationResult, GlbRequest, GlbResult, HardwareArtifact, HardwareArtifactService, HardwareArtifactsOptions, HardwareProject, InstallationInfo, Installations, NativeApplication, OpenArtifactRequest, OpenArtifactResult, OrderConfigInfo, OrderPackageSummary, PlaceOrderRequest, PlaceOrderResult, SourceRequest, SourceResult, groupBomRows, parseCsv };
package/lib/service.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as groupBomRows, r as parseCsv, t as HardwareArtifactService } from "./service-Yrc2C_eo.mjs";
1
+ import { n as groupBomRows, r as parseCsv, t as HardwareArtifactService } from "./service-Bo58tzXv.mjs";
2
2
  export { HardwareArtifactService, groupBomRows, parseCsv };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@huaqiu/hardware-artifacts",
3
- "version": "0.7.18",
3
+ "version": "0.7.20",
4
4
  "type": "module",
5
5
  "description": "Hardware Engineering host capability: deterministic artifact discovery, installation resolution, native application launch and compact agent context.",
6
6
  "license": "MIT",
@@ -23,6 +23,7 @@
23
23
  "dsh": "^0.2.2-rc.1"
24
24
  },
25
25
  "dependencies": {
26
+ "@deepseek-ai/dsh-tools": "^0.2.1-rc.2",
26
27
  "@deepseek-ai/schemastery": "^3.18.1",
27
28
  "fflate": "^0.8.2"
28
29
  },
package/src/index.ts CHANGED
@@ -10,6 +10,8 @@ import type {} from '@deepseek-ai/dsh-host-webserver'
10
10
  import Schema from '@deepseek-ai/schemastery'
11
11
  import { createHardwareHandler, HARDWARE_ROUTE_PREFIX } from './routes.js'
12
12
  import { HardwareArtifactService } from './service.js'
13
+ import { createHardwareTools } from './tools.js'
14
+ import { ToolchainManager, type ToolchainConfigPatch } from './toolchain/index.js'
13
15
 
14
16
  export type {
15
17
  ArtifactKind,
@@ -35,8 +37,20 @@ export {
35
37
  snapTraceTier,
36
38
  } from './order.js'
37
39
  export type { BoardFacts, PositionRow } from './order.js'
38
- export { createHardwareHandler, HARDWARE_ROUTE_PREFIX } from './routes.js'
40
+ export {
41
+ expectedCopperLayers, validateFabricationPackage, validationSummary,
42
+ } from './package.js'
43
+ export type { PackageIssue, PackageIssueCode, PackageValidation } from './package.js'
44
+ export { createHardwareTools, hardwareToolNames } from './tools.js'
45
+ export type { HardwareToolEnv } from './tools.js'
46
+ export { createHardwareHandler, HARDWARE_ROUTE_PREFIX, TOOLCHAIN_ROUTE_PREFIX } from './routes.js'
39
47
  export type { HardwareHandlerOptions, WorkspaceResolver } from './routes.js'
48
+ export { ToolchainManager } from './toolchain/index.js'
49
+ export type {
50
+ InstallErrorCode, InstallJobSnapshot, InstallPhase, ManifestEntry, ManifestFailure,
51
+ ToolDiscovery, ToolStatus, ToolchainConfigPatch, ToolchainManagerOptions, ToolchainSettings,
52
+ ToolchainStatus, ToolchainId, ToolchainSource, ValidationOutcome,
53
+ } from './toolchain/index.js'
40
54
 
41
55
  export const name = '@huaqiu/hardware-artifacts'
42
56
  export const inject = ['webServer', 'systemPrompt'] as const
@@ -52,8 +66,22 @@ export const inject = ['webServer', 'systemPrompt'] as const
52
66
  export const Config = Schema.object({
53
67
  kicadRoot: Schema.string().default('').volatile(),
54
68
  solidcraftRoot: Schema.string().default('').volatile(),
55
- /** Set by the first-run wizard once setup was completed or skipped. */
56
- onboardingComplete: Schema.boolean().default(false).volatile(),
69
+ /** Last validated KiCad version; display metadata, never the source of truth. */
70
+ kicadVersion: Schema.string().default('').volatile(),
71
+ /** How the KiCad path was obtained (`manual` | `browse` | `download` | `detected`). */
72
+ kicadSource: Schema.string().default('').volatile(),
73
+ /** Epoch milliseconds of the last successful KiCad validation. */
74
+ kicadValidatedAt: Schema.number().default(0).volatile(),
75
+ solidcraftVersion: Schema.string().default('').volatile(),
76
+ solidcraftSource: Schema.string().default('').volatile(),
77
+ solidcraftValidatedAt: Schema.number().default(0).volatile(),
78
+ /**
79
+ * First-run setup progress: empty until the operator answers, then `deferred`
80
+ * (skipped: never re-prompt, keep the reminder) or `complete`. This is the only
81
+ * flag the client reads; the old `onboardingComplete` boolean was dropped with
82
+ * its compatibility rule (internal-test build).
83
+ */
84
+ toolchainSetup: Schema.string().default('').volatile(),
57
85
  /**
58
86
  * Place-order origin. Empty uses `HUAQIU_ORDER_BASE_URL`, then the Huaqiu
59
87
  * host. It is only the transport target; it does not imply the endpoint
@@ -76,7 +104,13 @@ export type ConfigValue<T> = T | { get(): T }
76
104
  export interface HardwareArtifactsPluginConfig {
77
105
  readonly kicadRoot?: ConfigValue<string>
78
106
  readonly solidcraftRoot?: ConfigValue<string>
79
- readonly onboardingComplete?: ConfigValue<boolean>
107
+ readonly kicadVersion?: ConfigValue<string>
108
+ readonly kicadSource?: ConfigValue<string>
109
+ readonly kicadValidatedAt?: ConfigValue<number>
110
+ readonly solidcraftVersion?: ConfigValue<string>
111
+ readonly solidcraftSource?: ConfigValue<string>
112
+ readonly solidcraftValidatedAt?: ConfigValue<number>
113
+ readonly toolchainSetup?: ConfigValue<string>
80
114
  readonly orderBaseUrl?: ConfigValue<string>
81
115
  readonly accessToken?: ConfigValue<string>
82
116
  }
@@ -93,6 +127,8 @@ function readConfig<T>(value: ConfigValue<T> | undefined): T | undefined {
93
127
  declare module '@deepseek-ai/cordis' {
94
128
  interface Context {
95
129
  hardwareArtifacts: HardwareArtifactService
130
+ /** Toolchain configuration, discovery and installation capability. */
131
+ hardwareToolchains: ToolchainManager
96
132
  }
97
133
  }
98
134
 
@@ -172,14 +208,97 @@ export function apply(ctx: Context, config: HardwareArtifactsPluginConfig = {}):
172
208
  })
173
209
  ctx.effect(() => ctx.provide('hardwareArtifacts', service))
174
210
 
211
+ /**
212
+ * Toolchain capability (status/validate/discover/download).
213
+ *
214
+ * It reads the same live config the service reads and writes back through the
215
+ * Host's own settings service, so there is exactly one configuration authority
216
+ * (§10.5). The write is best-effort: a profile that mounted this row under a
217
+ * different id still lets the client persist through its config form.
218
+ */
219
+ const SETTINGS_NS = 'hardware-artifacts'
220
+ const persistToolchain = async (patch: ToolchainConfigPatch): Promise<boolean> => {
221
+ const settings = hostService<{ update?: (ns: string, patch: object, expected?: number) => Promise<void> }>('settings')
222
+ if (settings?.update === undefined) return false
223
+ try {
224
+ await settings.update(SETTINGS_NS, patch)
225
+ return true
226
+ } catch {
227
+ return false
228
+ }
229
+ }
230
+
231
+ /** The Host's own native directory chooser, when this host has one. */
232
+ const pickFolder = async (title: string): Promise<string | null> => {
233
+ void title
234
+ const capability = hostService<{
235
+ capability?: () => { kind?: string; pick?: (signal: AbortSignal) => Promise<string | null> }
236
+ }>('directoryPicker')?.capability?.()
237
+ if (capability?.kind !== 'native' || capability.pick === undefined) return null
238
+ const abort = new AbortController()
239
+ const timer = setTimeout(() => { abort.abort() }, 15 * 60_000)
240
+ timer.unref?.()
241
+ try {
242
+ return await capability.pick(abort.signal)
243
+ } finally {
244
+ clearTimeout(timer)
245
+ }
246
+ }
247
+
248
+ const toolchains = new ToolchainManager({
249
+ settings: () => ({
250
+ kicadRoot: readConfig(config.kicadRoot),
251
+ solidcraftRoot: readConfig(config.solidcraftRoot),
252
+ kicadVersion: readConfig(config.kicadVersion),
253
+ kicadSource: readConfig(config.kicadSource),
254
+ kicadValidatedAt: readConfig(config.kicadValidatedAt),
255
+ solidcraftVersion: readConfig(config.solidcraftVersion),
256
+ solidcraftSource: readConfig(config.solidcraftSource),
257
+ solidcraftValidatedAt: readConfig(config.solidcraftValidatedAt),
258
+ }),
259
+ persist: persistToolchain,
260
+ pickFolder,
261
+ })
262
+ ctx.effect(() => ctx.provide('hardwareToolchains', toolchains))
263
+ // The manifest is resolved once at boot, off the first UI request (§4.2).
264
+ ctx.effect(() => {
265
+ void toolchains.loadManifest()?.catch(() => undefined)
266
+ return (): void => {}
267
+ }, 'hardware-artifacts: toolchain manifest')
268
+
175
269
  if (ctx.webServer !== undefined) {
176
270
  ctx.effect(() => ctx.webServer.register({
177
271
  kind: 'prefix',
178
272
  path: HARDWARE_ROUTE_PREFIX,
179
- handler: createHardwareHandler(service, { resolveWorkspace: sessionWorkspace }),
273
+ handler: createHardwareHandler(service, { resolveWorkspace: sessionWorkspace, toolchain: toolchains }),
180
274
  }), 'hardware-artifacts: local read/launch routes')
181
275
  }
182
276
 
277
+ /**
278
+ * Agent tools.
279
+ *
280
+ * Acquired without `inject` for the same reason as the other optional
281
+ * services: the panel and its routes must keep working in a host without a
282
+ * tool registry, and a missing registry costs the agent surface, not the
283
+ * plugin. The tools take a path and run `kicad-cli` themselves, so this is
284
+ * the fabrication path that needs neither HQ Edge nor a running PCB editor.
285
+ */
286
+ const tools = hostService<{ register(tool: unknown): (() => void) | void }>('tools')
287
+ if (tools !== undefined && typeof tools.register === 'function') {
288
+ for (const tool of createHardwareTools({
289
+ service,
290
+ // A session-less call has no workspace to authorize against; the tool
291
+ // falls back to the process directory rather than inventing one here.
292
+ workspaceOf: sessionId => (sessionId === undefined ? undefined : sessionWorkspace(sessionId)),
293
+ })) {
294
+ const label = (tool as { readonly name?: string }).name ?? 'tool'
295
+ ctx.effect(() => {
296
+ const dispose = tools.register(tool)
297
+ return typeof dispose === 'function' ? dispose : (): void => {}
298
+ }, `hardware-artifacts: ${label}`)
299
+ }
300
+ }
301
+
183
302
  const prompt = (ctx as Context & { systemPrompt?: SystemPromptFace }).systemPrompt
184
303
  if (prompt !== undefined && typeof prompt.context === 'function') {
185
304
  ctx.effect(() => prompt.context({
package/src/order.ts CHANGED
@@ -61,6 +61,15 @@ export interface BoardFacts {
61
61
  readonly innerOz?: number
62
62
  /** Placed pads, used for the assembly form's `patch_pad_number`. */
63
63
  readonly padCount?: number
64
+ /**
65
+ * Display names the board gives its copper layers, canonical name as value
66
+ * (`{ top_copper: 'F_Cu' }`).
67
+ *
68
+ * A board may rename `F.Cu`/`In*.Cu`/`B.Cu`, and KiCad then writes that name
69
+ * into the plot's filename. The package validator needs the mapping to
70
+ * recognise the board's own copper. Only renamed layers appear.
71
+ */
72
+ readonly copperAliases?: Readonly<Record<string, string>>
64
73
  }
65
74
 
66
75
  /** One file inside the fabrication zip. */
@@ -223,6 +232,18 @@ export function readBoardFacts(text: string): BoardFacts {
223
232
  isNode(entry) && typeof entry[1] === 'string' && entry[1].endsWith('.Cu'))
224
233
  const layers = copperLayers.length
225
234
 
235
+ // `(0 "F.Cu" power "top_copper")` — the fourth field is the display name the
236
+ // designer chose. Keep it: KiCad plots that name into the gerber filename, so
237
+ // without the mapping a renamed copper layer is not recognisable as copper.
238
+ const copperAliases: Record<string, string> = {}
239
+ for (const entry of copperLayers) {
240
+ const canonical = entry[1]
241
+ const display = entry[3]
242
+ if (typeof canonical !== 'string' || typeof display !== 'string') continue
243
+ if (display === canonical || display.trim() === '') continue
244
+ copperAliases[display] = canonical.replace(/\./gu, '_')
245
+ }
246
+
226
247
  const general = child(root, 'general')
227
248
  const thicknessMm = numberAt(child(general ?? [], 'thickness'), 1) ?? 1.6
228
249
 
@@ -292,6 +313,7 @@ export function readBoardFacts(text: string): BoardFacts {
292
313
  ...(outerThickness === undefined ? {} : { outerOz: snapOz(outerThickness, [1, 2, 3, 4]) }),
293
314
  ...(innerThickness === undefined ? {} : { innerOz: snapOz(innerThickness, [0.5, 1, 2, 3, 4]) }),
294
315
  ...(allPads === 0 ? {} : { padCount: smdPads > 0 ? smdPads : allPads }),
316
+ ...(Object.keys(copperAliases).length === 0 ? {} : { copperAliases }),
295
317
  }
296
318
  }
297
319
 
package/src/package.ts ADDED
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Fabrication package validation.
3
+ *
4
+ * The exporter (`kicad-cli pcb export gerbers|drill`) reports success when it
5
+ * wrote *something*; it does not claim the result is a fabricable board. Three
6
+ * failures survive that exit code and are only visible by reading the file set:
7
+ *
8
+ * - a copper layer in the stackup with no plotted gerber, which fabricates a
9
+ * board missing that layer;
10
+ * - no `Edge.Cuts` plot, which means no board outline — the order form is
11
+ * then submitted with a 0 × 0 size;
12
+ * - a zero-byte plot, which the plotter writes when a layer had nothing to
13
+ * draw and the profile still lists the file.
14
+ *
15
+ * Layer identity is read from the plot's Protel suffix first (`.gtl`, `.gbl`,
16
+ * `.g1`…), because the text KiCad writes between the board name and the suffix
17
+ * is the board's *display* name for that layer and is user-editable: a board
18
+ * that renamed `F.Cu` to `top_copper` plots `board-top_copper.gtl`. Reading the
19
+ * name alone would report that package as having no copper at all. For a plot
20
+ * written with extended (`.gbr`) names, where the suffix carries no layer
21
+ * identity, the board's own display names are matched through `facts`.
22
+ *
23
+ * The checks are pure functions over `{ name, bytes }` and the board facts the
24
+ * file itself declares, so a caller can validate an archive it did not produce
25
+ * (a colleague's zip, a cached revision) and get the same answer.
26
+ *
27
+ * @module
28
+ */
29
+
30
+ import type { BoardFacts, PackageFile } from './order.js'
31
+
32
+ /** Every way a package can be judged unfit to fabricate. */
33
+ export type PackageIssueCode =
34
+ | 'no-copper'
35
+ | 'missing-copper-layer'
36
+ | 'unexpected-copper-layer'
37
+ | 'no-board-outline'
38
+ | 'zero-area'
39
+ | 'no-drill'
40
+ | 'empty-file'
41
+ | 'unexpected-file'
42
+
43
+ export interface PackageIssue {
44
+ readonly code: PackageIssueCode
45
+ /** `error` blocks an order; `warning` is reported and left to the user. */
46
+ readonly severity: 'error' | 'warning'
47
+ readonly message: string
48
+ readonly file?: string
49
+ }
50
+
51
+ export interface PackageValidation {
52
+ /** True when no issue is an error; warnings may still be present. */
53
+ readonly ok: boolean
54
+ readonly checkedAt: string
55
+ readonly errors: readonly PackageIssue[]
56
+ readonly warnings: readonly PackageIssue[]
57
+ /** Copper layers found in the package, in the file's own naming. */
58
+ readonly copperLayers: readonly string[]
59
+ /** Layers the stackup expects but the package does not contain. */
60
+ readonly missingLayers: readonly string[]
61
+ readonly hasOutline: boolean
62
+ readonly hasDrill: boolean
63
+ }
64
+
65
+ /**
66
+ * Gerber/drill suffixes that carry no fabrication intent.
67
+ *
68
+ * A `.gbrjob` is KiCad's job metadata and is written next to the plots; it is
69
+ * neither a layer nor an error.
70
+ */
71
+ const NON_LAYER_SUFFIXES = new Set(['gbrjob', 'txt', 'csv', 'json'])
72
+
73
+ const DRILL_SUFFIXES = new Set(['drl', 'xln', 'exc', 'ncd'])
74
+
75
+ /**
76
+ * Plot file suffixes.
77
+ *
78
+ * KiCad writes `.gbr` when the plotter is set to extended names, but its
79
+ * default is the Protel set: `.gtl`/`.gbl` for outer copper, `.g1`…`.g32` for
80
+ * inner copper, `.gm1` for the outline, and letters for the technical layers.
81
+ * Both spellings appear in real packages — a validator that knows only `.gbr`
82
+ * declares every inner layer missing.
83
+ */
84
+ const GERBER_SUFFIXES = /^(?:gbr|g\d{1,2}|gm\d{1,2}|gko|gml|g[tsbop][a-z])$/iu
85
+
86
+ /** The layer names KiCad puts between the board name and the suffix. */
87
+ const LAYER_TOKENS = /^(?:[FB]_[A-Za-z0-9_]+|In\d+_Cu|Edge_Cuts|Margin|User_[A-Za-z0-9_]+|[A-Za-z0-9]+_User)$/u
88
+
89
+ /**
90
+ * Protel plot suffixes that name their own layer.
91
+ *
92
+ * KiCad's default plotter writes the Protel set. The suffix is a fixed function
93
+ * of the layer, while the text before it is the board's *display* name for that
94
+ * layer and is therefore whatever the designer typed. A board that renamed
95
+ * `F.Cu` to `top_copper` plots `board-top_copper.gtl`, and one that renamed
96
+ * `In1.Cu` plots `board-inner_ground.g1` — both perfectly fabricable, and both
97
+ * unreadable from the name alone.
98
+ */
99
+ const PROTEL_LAYERS: Readonly<Record<string, string>> = Object.freeze({
100
+ gtl: 'F_Cu',
101
+ gbl: 'B_Cu',
102
+ gts: 'F_Mask',
103
+ gbs: 'B_Mask',
104
+ gto: 'F_SilkS',
105
+ gbo: 'B_SilkS',
106
+ gtp: 'F_Paste',
107
+ gbp: 'B_Paste',
108
+ gta: 'F_Adhes',
109
+ gba: 'B_Adhes',
110
+ gm1: 'Edge_Cuts',
111
+ })
112
+
113
+ /** `gtl` → `F_Cu`; `g3` → `In3_Cu`; `undefined` for a suffix that names no layer. */
114
+ function protelLayer(suffix: string): string | undefined {
115
+ const fixed = PROTEL_LAYERS[suffix]
116
+ if (fixed !== undefined) return fixed
117
+ const inner = /^g(\d{1,2})$/u.exec(suffix)
118
+ if (inner === null) return undefined
119
+ // Inner copper is numbered from 1 in both spellings: `.g1` is `In1_Cu`.
120
+ const index = Number(inner[1])
121
+ return index >= 1 ? `In${String(index)}_Cu` : undefined
122
+ }
123
+
124
+ /**
125
+ * `board-F_Cu.gbr` → `F_Cu`; `undefined` for a file that is not a plot.
126
+ *
127
+ * `aliases` maps a board's display names back onto the canonical ones
128
+ * (`{ top_copper: 'F_Cu' }`). It is the only way to read a plot whose layer was
129
+ * renamed *and* written with extended (`.gbr`) names, where the suffix carries
130
+ * no layer identity.
131
+ */
132
+ function gerberLayer(name: string, aliases?: Readonly<Record<string, string>>): string | undefined {
133
+ const dot = name.lastIndexOf('.')
134
+ if (dot <= 0) return undefined
135
+ const suffix = name.slice(dot + 1).toLowerCase()
136
+ if (!GERBER_SUFFIXES.test(suffix)) return undefined
137
+ const protel = protelLayer(suffix)
138
+ if (protel !== undefined) return protel
139
+ const stem = name.slice(0, dot)
140
+ // KiCad names every plot `<board>-<layer>`, and a board name may itself
141
+ // contain hyphens, so the layer is what follows the last one.
142
+ const dash = stem.lastIndexOf('-')
143
+ const layer = dash === -1 ? stem : stem.slice(dash + 1)
144
+ if (LAYER_TOKENS.test(layer)) return layer
145
+ const alias = aliases?.[layer]
146
+ return alias !== undefined && LAYER_TOKENS.test(alias) ? alias : undefined
147
+ }
148
+
149
+ function suffixOf(name: string): string {
150
+ const dot = name.lastIndexOf('.')
151
+ return dot === -1 ? '' : name.slice(dot + 1).toLowerCase()
152
+ }
153
+
154
+ /** The copper layers a KiCad stackup of this size must contain, in order. */
155
+ export function expectedCopperLayers(layers: number): string[] {
156
+ const count = Number.isFinite(layers) && layers >= 2 ? Math.floor(layers) : 2
157
+ const inner: string[] = []
158
+ for (let index = 1; index <= count - 2; index += 1) inner.push(`In${String(index)}_Cu`)
159
+ return ['F_Cu', ...inner, 'B_Cu']
160
+ }
161
+
162
+ /**
163
+ * Judge one package against the board facts it was plotted from.
164
+ *
165
+ * `facts` must come from the same board file (`readBoardFacts`); measuring a
166
+ * package against another board's stackup is the very mistake this catches.
167
+ *
168
+ * @param files - every member of the archive, with its uncompressed size.
169
+ * @param facts - geometry and stackup declared by the source board.
170
+ */
171
+ export function validateFabricationPackage(
172
+ files: readonly PackageFile[],
173
+ facts: BoardFacts,
174
+ ): PackageValidation {
175
+ const errors: PackageIssue[] = []
176
+ const warnings: PackageIssue[] = []
177
+
178
+ const layers = new Set<string>()
179
+ let hasOutline = false
180
+ let hasDrill = false
181
+ let unreadable = 0
182
+
183
+ for (const file of files) {
184
+ if (file.bytes === 0) {
185
+ errors.push({
186
+ code: 'empty-file',
187
+ severity: 'error',
188
+ message: `${file.name} is empty; the plotter wrote a file it did not fill`,
189
+ file: file.name,
190
+ })
191
+ }
192
+ const layer = gerberLayer(file.name, facts.copperAliases)
193
+ if (layer !== undefined) {
194
+ layers.add(layer)
195
+ if (layer === 'Edge_Cuts') hasOutline = true
196
+ continue
197
+ }
198
+ if (DRILL_SUFFIXES.has(suffixOf(file.name))) hasDrill = true
199
+ else if (!NON_LAYER_SUFFIXES.has(suffixOf(file.name))) unreadable += 1
200
+ }
201
+
202
+ const copperLayers = [...layers].filter(layer => layer.endsWith('_Cu'))
203
+ const expected = expectedCopperLayers(facts.layers)
204
+ const missing = expected.filter(layer => !layers.has(layer))
205
+
206
+ if (copperLayers.length === 0) {
207
+ errors.push({
208
+ code: 'no-copper',
209
+ severity: 'error',
210
+ message: 'no copper gerber in the package; nothing would be etched',
211
+ })
212
+ } else if (missing.length > 0) {
213
+ errors.push({
214
+ code: 'missing-copper-layer',
215
+ severity: 'error',
216
+ message: `the board declares ${String(facts.layers)} copper layers but ${missing.join(', ')} `
217
+ + `${missing.length === 1 ? 'was' : 'were'} not plotted; ordering this package would produce a `
218
+ + 'board missing that layer',
219
+ })
220
+ }
221
+
222
+ const extra = copperLayers.filter(layer => !expected.includes(layer))
223
+ if (extra.length > 0) {
224
+ warnings.push({
225
+ code: 'unexpected-copper-layer',
226
+ severity: 'warning',
227
+ message: `the package plots ${extra.join(', ')}, which the declared stackup does not contain`,
228
+ })
229
+ }
230
+
231
+ if (!hasOutline) {
232
+ errors.push({
233
+ code: 'no-board-outline',
234
+ severity: 'error',
235
+ message: 'no Edge.Cuts gerber in the package; the fabricator would have no board outline to cut',
236
+ })
237
+ }
238
+
239
+ if (!(facts.widthMm > 0) || !(facts.heightMm > 0)) {
240
+ errors.push({
241
+ code: 'zero-area',
242
+ severity: 'error',
243
+ message: 'the board outline could not be measured, so the order form would carry a 0 × 0 size',
244
+ })
245
+ }
246
+
247
+ // A board may legitimately be SMD-only, so a missing drill file is reported
248
+ // rather than refused: the fabricator still needs to know there are no holes.
249
+ if (!hasDrill) {
250
+ warnings.push({
251
+ code: 'no-drill',
252
+ severity: 'warning',
253
+ message: 'no drill file in the package; it is only correct for a board with no through-holes',
254
+ })
255
+ }
256
+
257
+ if (unreadable > 0) {
258
+ warnings.push({
259
+ code: 'unexpected-file',
260
+ severity: 'warning',
261
+ message: `${String(unreadable)} file(s) are neither gerber, drill nor job metadata and were ignored`,
262
+ })
263
+ }
264
+
265
+ return {
266
+ ok: errors.length === 0,
267
+ checkedAt: new Date().toISOString(),
268
+ errors,
269
+ warnings,
270
+ copperLayers,
271
+ missingLayers: missing,
272
+ hasOutline,
273
+ hasDrill,
274
+ }
275
+ }
276
+
277
+ /** One sentence a human or agent can act on, or `undefined` when valid. */
278
+ export function validationSummary(validation: PackageValidation): string | undefined {
279
+ if (validation.ok && validation.warnings.length === 0) return undefined
280
+ const parts = [...validation.errors, ...validation.warnings].map(issue => issue.message)
281
+ return parts.join('; ')
282
+ }