dsh-stm32 0.1.8 → 0.1.9

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.
Files changed (127) hide show
  1. package/README.md +567 -409
  2. package/README_EN.md +544 -410
  3. package/client/client.js +7033 -5021
  4. package/docs/reading-guide.md +921 -921
  5. package/lib/client.js +7033 -5021
  6. package/lib/commands/register.js +2 -0
  7. package/lib/data/firmware-packages.js +35 -0
  8. package/lib/data/firmware-pins.js +7 -0
  9. package/lib/data/install-guides.js +110 -0
  10. package/lib/data/ioc-presets.js +118 -0
  11. package/lib/engine/build.js +88 -2
  12. package/lib/engine/datasheet/auto.js +74 -0
  13. package/lib/engine/datasheet/digest.js +74 -0
  14. package/lib/engine/datasheet/lcsc.js +60 -0
  15. package/lib/engine/datasheet/pinout.js +119 -0
  16. package/lib/engine/datasheet/price.js +152 -0
  17. package/lib/engine/datasheet/search.js +147 -0
  18. package/lib/engine/datasheet/store.js +371 -0
  19. package/lib/engine/debug-session.js +2 -1
  20. package/lib/engine/ecad/autobuild.js +156 -0
  21. package/lib/engine/ecad/bom.js +238 -0
  22. package/lib/engine/ecad/brief.js +205 -0
  23. package/lib/engine/ecad/checks.js +239 -0
  24. package/lib/engine/ecad/design.js +177 -0
  25. package/lib/engine/ecad/dfm.js +314 -0
  26. package/lib/engine/ecad/easyeda.js +454 -0
  27. package/lib/engine/ecad/fabrication.js +104 -0
  28. package/lib/engine/ecad/gen/footprint.js +159 -0
  29. package/lib/engine/ecad/gen/symbol.js +103 -0
  30. package/lib/engine/ecad/import.js +372 -0
  31. package/lib/engine/ecad/jlcpcb.js +141 -0
  32. package/lib/engine/ecad/libs.js +316 -0
  33. package/lib/engine/ecad/models3d.js +89 -0
  34. package/lib/engine/ecad/netgate.js +286 -0
  35. package/lib/engine/ecad/normalize.js +182 -0
  36. package/lib/engine/ecad/package.js +126 -0
  37. package/lib/engine/ecad/padmerge.js +128 -0
  38. package/lib/engine/ecad/padprecheck.js +123 -0
  39. package/lib/engine/ecad/part-import.js +257 -0
  40. package/lib/engine/ecad/pcb/apply.js +53 -0
  41. package/lib/engine/ecad/pcb/emc-deep.js +396 -0
  42. package/lib/engine/ecad/pcb/emc.js +275 -0
  43. package/lib/engine/ecad/pcb/geometry.js +63 -0
  44. package/lib/engine/ecad/pcb/gerber.js +499 -0
  45. package/lib/engine/ecad/pcb/hand-sync.js +242 -0
  46. package/lib/engine/ecad/pcb/impedance.js +119 -0
  47. package/lib/engine/ecad/pcb/ipc-open.js +78 -0
  48. package/lib/engine/ecad/pcb/ipc-script.js +276 -0
  49. package/lib/engine/ecad/pcb/ipc.js +129 -0
  50. package/lib/engine/ecad/pcb/krt.js +182 -0
  51. package/lib/engine/ecad/pcb/links.js +393 -0
  52. package/lib/engine/ecad/pcb/mech.js +201 -0
  53. package/lib/engine/ecad/pcb/model-fix.js +178 -0
  54. package/lib/engine/ecad/pcb/netlist.js +146 -0
  55. package/lib/engine/ecad/pcb/pcb-svg.js +199 -0
  56. package/lib/engine/ecad/pcb/placement.js +140 -0
  57. package/lib/engine/ecad/pcb/power.js +203 -0
  58. package/lib/engine/ecad/pcb/render3d.js +208 -0
  59. package/lib/engine/ecad/pcb/route.js +167 -0
  60. package/lib/engine/ecad/pcb/router.js +469 -0
  61. package/lib/engine/ecad/pcb/rules.js +122 -0
  62. package/lib/engine/ecad/pcb/scene.js +513 -0
  63. package/lib/engine/ecad/pcb/stackup.js +154 -0
  64. package/lib/engine/ecad/pcb/swap.js +222 -0
  65. package/lib/engine/ecad/pcb/tracks.js +70 -0
  66. package/lib/engine/ecad/runtime.js +227 -0
  67. package/lib/engine/ecad/toolchain.js +146 -0
  68. package/lib/engine/ecad/tsci.js +362 -0
  69. package/lib/engine/ecad/zip.js +98 -0
  70. package/lib/engine/generate-script.js +4 -1
  71. package/lib/engine/generate.js +145 -5
  72. package/lib/engine/ioc-plan.js +12 -2
  73. package/lib/engine/mcu-info.js +134 -0
  74. package/lib/engine/pdf/curve.js +321 -0
  75. package/lib/engine/pdf/png.js +83 -0
  76. package/lib/engine/pdf/reader.js +336 -0
  77. package/lib/engine/pdf/schematic.js +93 -0
  78. package/lib/engine/pdf/tables.js +249 -0
  79. package/lib/engine/pdf/toolchain.js +50 -0
  80. package/lib/engine/probe.js +45 -0
  81. package/lib/engine/project-conf.js +93 -38
  82. package/lib/engine/project-layout.js +198 -0
  83. package/lib/engine/project-repair.js +205 -0
  84. package/lib/engine/schematic/checks.js +153 -0
  85. package/lib/engine/schematic/draw.js +390 -0
  86. package/lib/engine/schematic/edit.js +229 -0
  87. package/lib/engine/schematic/kicad-sch.js +225 -0
  88. package/lib/engine/schematic/model.js +442 -0
  89. package/lib/engine/schematic/nets.js +219 -0
  90. package/lib/engine/schematic/pcb.js +144 -0
  91. package/lib/engine/schematic/review.js +134 -0
  92. package/lib/engine/schematic/sexpr.js +134 -0
  93. package/lib/engine/schematic/to-ioc.js +197 -0
  94. package/lib/engine/schematic/transform.js +25 -0
  95. package/lib/engine/session-context.js +93 -6
  96. package/lib/engine/toolchain-gate.js +8 -0
  97. package/lib/engine/web-api.js +269 -32
  98. package/lib/index.js +56 -5
  99. package/lib/skill/stm32-workflow.js +1 -1
  100. package/lib/tools/build.js +10 -2
  101. package/lib/tools/code-patch.js +2 -2
  102. package/lib/tools/datasheet.js +447 -0
  103. package/lib/tools/debug-session.js +9 -4
  104. package/lib/tools/debug.js +2 -2
  105. package/lib/tools/doctor.js +2 -2
  106. package/lib/tools/ecad.js +903 -0
  107. package/lib/tools/flash.js +2 -2
  108. package/lib/tools/gen.js +166 -0
  109. package/lib/tools/generate.js +7 -5
  110. package/lib/tools/import-circuit.js +146 -0
  111. package/lib/tools/ioc-apply.js +2 -2
  112. package/lib/tools/ioc-inspect.js +2 -2
  113. package/lib/tools/ioc-plan.js +2 -2
  114. package/lib/tools/ioc-verify.js +2 -2
  115. package/lib/tools/layout.js +92 -0
  116. package/lib/tools/mcu-info.js +163 -0
  117. package/lib/tools/part-import.js +182 -0
  118. package/lib/tools/pcb.js +2316 -0
  119. package/lib/tools/pdf.js +423 -0
  120. package/lib/tools/project-dir.js +19 -1
  121. package/lib/tools/regs.js +2 -2
  122. package/lib/tools/route-plan.js +2 -2
  123. package/lib/tools/rtt.js +2 -2
  124. package/lib/tools/sch-draw.js +433 -0
  125. package/lib/tools/sch-edit.js +145 -0
  126. package/lib/tools/schematic.js +817 -0
  127. package/package.json +1 -1
@@ -0,0 +1,371 @@
1
+ /**
2
+ * 数据手册本地缓存(S119)。
3
+ *
4
+ * 目标:同一颗非 STM32 器件只下第一份手册,之后一律读本地。缓存按立创编号分目录,
5
+ * 文件名取 PDF 内容的 sha256 前缀,meta.json 记来源与抓取时间——出处可回溯、内容可校验。
6
+ *
7
+ * 失败也留痕:`_negative/<编号>.json` 记下原因与时间,24 小时内不再重试,避免每次构建都去撞墙。
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { fetchLcscProduct } from "./lcsc.js";
14
+ const INDEX_FILE = "index.json";
15
+ const NEGATIVE_DIR = "_negative";
16
+ const NEGATIVE_TTL_MS = 24 * 60 * 60 * 1000;
17
+ const DEFAULT_MAX_MB = 40;
18
+ const DEFAULT_GAP_MS = 1500;
19
+ let lastRequestAt = 0;
20
+ /** 缓存根目录:`DSH_STM32_DATASHEETS` 优先,否则 `~/.dsh-stm32/datasheets`。 */
21
+ export function datasheetCacheDir(env = process.env) {
22
+ const explicit = (env["DSH_STM32_DATASHEETS"] ?? "").trim();
23
+ if (explicit !== "")
24
+ return explicit;
25
+ return join(env["USERPROFILE"]?.trim() || homedir(), ".dsh-stm32", "datasheets");
26
+ }
27
+ export function isLcscCode(value) {
28
+ return /^(?:lcsc:)?C\d{3,}$/iu.test(value.trim());
29
+ }
30
+ export function normalizeCode(value) {
31
+ return value.trim().replace(/^lcsc:/iu, "").toUpperCase();
32
+ }
33
+ function emptyIndex() {
34
+ return { version: 1, entries: {} };
35
+ }
36
+ export function readIndex(cacheDir) {
37
+ const file = join(cacheDir, INDEX_FILE);
38
+ if (!existsSync(file))
39
+ return scanIndex(cacheDir);
40
+ try {
41
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
42
+ if (parsed.version !== 1 || typeof parsed.entries !== "object" || parsed.entries === null)
43
+ return emptyIndex();
44
+ return parsed;
45
+ }
46
+ catch {
47
+ return emptyIndex();
48
+ }
49
+ }
50
+ /** 索引丢了也能从各目录的 meta.json 重建(缓存目录被人手工动过时的自愈)。 */
51
+ function scanIndex(cacheDir) {
52
+ const index = emptyIndex();
53
+ if (!existsSync(cacheDir))
54
+ return index;
55
+ for (const name of readdirSync(cacheDir)) {
56
+ if (name.startsWith("_"))
57
+ continue;
58
+ const metaFile = join(cacheDir, name, "meta.json");
59
+ if (!existsSync(metaFile))
60
+ continue;
61
+ try {
62
+ const entry = JSON.parse(readFileSync(metaFile, "utf8"));
63
+ if (typeof entry.code === "string" && typeof entry.sha256 === "string")
64
+ index.entries[entry.code] = entry;
65
+ }
66
+ catch {
67
+ // 坏掉的 meta 跳过:宁缺,不要把脏数据带进索引。
68
+ }
69
+ }
70
+ return index;
71
+ }
72
+ function writeIndex(cacheDir, index) {
73
+ mkdirSync(cacheDir, { recursive: true });
74
+ writeFileSync(join(cacheDir, INDEX_FILE), JSON.stringify(index, null, 2) + "\n", "utf8");
75
+ }
76
+ export function entryFile(cacheDir, entry) {
77
+ return join(cacheDir, entry.code, entry.pdfFile);
78
+ }
79
+ /** 缓存是否还在:meta 存在、PDF 存在、sha256 对得上。 */
80
+ export function entryUsable(cacheDir, entry) {
81
+ const file = entryFile(cacheDir, entry);
82
+ if (!existsSync(file))
83
+ return false;
84
+ try {
85
+ return sha256Of(readFileSync(file)) === entry.sha256;
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ export function sha256Of(buffer) {
92
+ return createHash("sha256").update(buffer).digest("hex");
93
+ }
94
+ /** 把 `C25137` / `lcsc:C25137` / MPN 解析成本地 PDF 路径。 */
95
+ export function resolveDatasheetRef(cacheDir, ref) {
96
+ if (existsSync(ref))
97
+ return null;
98
+ const index = readIndex(cacheDir);
99
+ const wanted = ref.trim();
100
+ const byCode = index.entries[normalizeCode(wanted)];
101
+ if (byCode !== undefined && entryUsable(cacheDir, byCode))
102
+ return { file: entryFile(cacheDir, byCode), entry: byCode };
103
+ const lowered = wanted.toLowerCase();
104
+ for (const entry of Object.values(index.entries)) {
105
+ if (entry.mpn.toLowerCase() === lowered && entryUsable(cacheDir, entry)) {
106
+ return { file: entryFile(cacheDir, entry), entry };
107
+ }
108
+ }
109
+ return null;
110
+ }
111
+ function negativeFile(cacheDir, code) {
112
+ return join(cacheDir, NEGATIVE_DIR, code + ".json");
113
+ }
114
+ function negativeReason(cacheDir, code) {
115
+ const file = negativeFile(cacheDir, code);
116
+ if (!existsSync(file))
117
+ return "";
118
+ try {
119
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
120
+ if (typeof parsed.at !== "number" || Date.now() - parsed.at > NEGATIVE_TTL_MS)
121
+ return "";
122
+ return parsed.error ?? "上次抓取失败";
123
+ }
124
+ catch {
125
+ return "";
126
+ }
127
+ }
128
+ function writeNegative(cacheDir, code, error) {
129
+ mkdirSync(join(cacheDir, NEGATIVE_DIR), { recursive: true });
130
+ writeFileSync(negativeFile(cacheDir, code), JSON.stringify({ code, error, at: Date.now() }) + "\n", "utf8");
131
+ }
132
+ function clearNegative(cacheDir, code) {
133
+ const file = negativeFile(cacheDir, code);
134
+ if (existsSync(file))
135
+ rmSync(file, { force: true });
136
+ }
137
+ function gapMs() {
138
+ const fromEnv = Number.parseInt(process.env["DSH_STM32_DS_MIN_GAP_MS"] ?? "", 10);
139
+ return Number.isFinite(fromEnv) && fromEnv >= 0 ? fromEnv : DEFAULT_GAP_MS;
140
+ }
141
+ async function throttle() {
142
+ const wait = gapMs() - (Date.now() - lastRequestAt);
143
+ if (wait > 0)
144
+ await new Promise((resolve) => setTimeout(resolve, wait));
145
+ lastRequestAt = Date.now();
146
+ }
147
+ /**
148
+ * 确保某颗器件的 PDF 在本地。
149
+ * 命中缓存时零网络;`offline` 时不发请求;失败写入负缓存(24 小时)。
150
+ */
151
+ export async function ensureDatasheet(codeSpec, options = {}) {
152
+ const cacheDir = options.cacheDir ?? datasheetCacheDir(options.env);
153
+ const code = normalizeCode(codeSpec);
154
+ if (!/^C\d{3,}$/u.test(code)) {
155
+ return { ok: false, error: "编号不像立创商品编号:" + codeSpec + "(形如 C25137)" };
156
+ }
157
+ const index = readIndex(cacheDir);
158
+ const existing = index.entries[code];
159
+ if (existing !== undefined && !(options.refresh ?? false) && entryUsable(cacheDir, existing)) {
160
+ return { ok: true, cached: true, entry: existing, file: entryFile(cacheDir, existing) };
161
+ }
162
+ if (options.offline ?? false) {
163
+ return { ok: false, error: "离线模式(DSH_STM32_OFFLINE=1),本地没有 " + code + " 的手册" };
164
+ }
165
+ if (!(options.refresh ?? false)) {
166
+ const reason = negativeReason(cacheDir, code);
167
+ if (reason !== "")
168
+ return { ok: false, error: "24 小时内抓取失败过,暂不重试:" + reason };
169
+ }
170
+ const fetchImpl = options.fetchImpl ?? fetch;
171
+ await throttle();
172
+ const page = await fetchLcscProduct(code, { fetchImpl, timeoutMs: options.timeoutMs, signal: options.signal });
173
+ if (!page.ok) {
174
+ writeNegative(cacheDir, code, page.error);
175
+ return { ok: false, error: page.error };
176
+ }
177
+ await throttle();
178
+ const controller = new AbortController();
179
+ const timer = setTimeout(() => controller.abort(), 60_000);
180
+ let buffer;
181
+ try {
182
+ const response = await fetchImpl(page.product.pdfUrl, {
183
+ signal: options.signal === undefined ? controller.signal : AbortSignal.any([controller.signal, options.signal]),
184
+ redirect: "follow",
185
+ headers: { "user-agent": "dsh-stm32 datasheet fetcher (pdf)" },
186
+ });
187
+ if (!response.ok) {
188
+ const error = "PDF 返回 HTTP " + String(response.status) + ":" + page.product.pdfUrl;
189
+ writeNegative(cacheDir, code, error);
190
+ return { ok: false, error };
191
+ }
192
+ buffer = Buffer.from(await response.arrayBuffer());
193
+ }
194
+ catch (error) {
195
+ const reason = "下载 PDF 失败:" + (error instanceof Error ? error.message : String(error));
196
+ writeNegative(cacheDir, code, reason);
197
+ return { ok: false, error: reason };
198
+ }
199
+ finally {
200
+ clearTimeout(timer);
201
+ }
202
+ const maxBytes = (options.maxMb ?? DEFAULT_MAX_MB) * 1024 * 1024;
203
+ if (buffer.length > maxBytes) {
204
+ const error = "PDF 超过上限(" + String(Math.round(buffer.length / 1024 / 1024)) + " MB > " + String(options.maxMb ?? DEFAULT_MAX_MB) + " MB)";
205
+ writeNegative(cacheDir, code, error);
206
+ return { ok: false, error };
207
+ }
208
+ if (buffer.subarray(0, 5).toString("latin1") !== "%PDF-") {
209
+ const error = "下载到的不是 PDF(开头不是 %PDF-):" + page.product.pdfUrl;
210
+ writeNegative(cacheDir, code, error);
211
+ return { ok: false, error };
212
+ }
213
+ const entry = storeBuffer(cacheDir, page.product, buffer);
214
+ clearNegative(cacheDir, code);
215
+ return { ok: true, cached: false, entry, file: entryFile(cacheDir, entry) };
216
+ }
217
+ /** 把一份 PDF 写进缓存(下载与手工导入共用)。 */
218
+ export function storeBuffer(cacheDir, product, buffer) {
219
+ const sha256 = sha256Of(buffer);
220
+ const dir = join(cacheDir, product.code);
221
+ mkdirSync(dir, { recursive: true });
222
+ for (const name of readdirSync(dir)) {
223
+ if (name.endsWith(".pdf") && name !== sha256.slice(0, 12) + ".pdf")
224
+ rmSync(join(dir, name), { force: true });
225
+ }
226
+ const pdfFile = sha256.slice(0, 12) + ".pdf";
227
+ writeFileSync(join(dir, pdfFile), buffer);
228
+ const entry = {
229
+ code: product.code,
230
+ mpn: product.mpn,
231
+ brand: product.brand,
232
+ title: product.title,
233
+ sha256,
234
+ bytes: buffer.length,
235
+ pdfFile,
236
+ sourceUrl: product.sourceUrl,
237
+ pdfUrl: product.pdfUrl,
238
+ fetchedAt: new Date().toISOString(),
239
+ };
240
+ writeFileSync(join(dir, "meta.json"), JSON.stringify(entry, null, 2) + "\n", "utf8");
241
+ const index = readIndex(cacheDir);
242
+ index.entries[product.code] = entry;
243
+ writeIndex(cacheDir, index);
244
+ return entry;
245
+ }
246
+ /** 手工导入:用户自己放一份 PDF 进来(离线/反爬时的退路)。 */
247
+ export function importDatasheet(cacheDir, file, product = {}) {
248
+ if (!existsSync(file))
249
+ return { ok: false, error: "文件不存在:" + file };
250
+ const buffer = readFileSync(file);
251
+ if (buffer.subarray(0, 5).toString("latin1") !== "%PDF-")
252
+ return { ok: false, error: "不是 PDF:" + file };
253
+ const code = normalizeCode(product.code ?? "");
254
+ const product2 = {
255
+ code: /^C\d{3,}$/u.test(code) ? code : "manual-" + sha256Of(buffer).slice(0, 8),
256
+ mpn: product.mpn ?? "",
257
+ brand: product.brand ?? "",
258
+ title: product.title ?? file,
259
+ pdfUrl: product.pdfUrl ?? "",
260
+ sourceUrl: product.sourceUrl ?? file,
261
+ };
262
+ const entry = storeBuffer(cacheDir, product2, buffer);
263
+ return { ok: true, cached: false, entry, file: entryFile(cacheDir, entry) };
264
+ }
265
+ export function listDatasheets(cacheDir) {
266
+ const index = readIndex(cacheDir);
267
+ const entries = [];
268
+ let totalBytes = 0;
269
+ for (const entry of Object.values(index.entries)) {
270
+ if (!entryUsable(cacheDir, entry))
271
+ continue;
272
+ entries.push(entry);
273
+ totalBytes += entry.bytes;
274
+ }
275
+ entries.sort((a, b) => a.code.localeCompare(b.code));
276
+ return { cacheDir, entries, totalBytes };
277
+ }
278
+ /** 缓存占用(不影响列表):目录里 PDF 的实际大小,含手写目录。 */
279
+ export function cacheBytes(cacheDir) {
280
+ if (!existsSync(cacheDir))
281
+ return 0;
282
+ let total = 0;
283
+ for (const name of readdirSync(cacheDir)) {
284
+ const file = join(cacheDir, name);
285
+ if (!statSync(file).isFile()) {
286
+ const entry = readIndex(cacheDir).entries[name];
287
+ if (entry !== undefined)
288
+ total += entry.bytes;
289
+ }
290
+ }
291
+ return total;
292
+ }
293
+ /** 手工导入的便捷封装:按位号名复制进缓存(面板/工具用)。 */
294
+ export function importDatasheetFile(cacheDir, source, code, mpn) {
295
+ mkdirSync(cacheDir, { recursive: true });
296
+ const temp = join(cacheDir, "_import.pdf");
297
+ copyFileSync(source, temp);
298
+ const result = importDatasheet(cacheDir, temp, { code, mpn });
299
+ rmSync(temp, { force: true });
300
+ return result;
301
+ }
302
+ /**
303
+ * 清理缓存(S124):按编号删,或按「超过 N 天没再抓过」删。
304
+ *
305
+ * 不做容量上限:手册是外部证据,删多少应该由人决定;这里只提供可复核的入口——
306
+ * 返回删了哪些、释放多少字节、还剩哪些,删之前先确认索引里确实有这一份。
307
+ */
308
+ export function pruneDatasheets(cacheDir, options = {}) {
309
+ const index = readIndex(cacheDir);
310
+ const codes = new Set(Object.keys(index.entries));
311
+ const removed = [];
312
+ const notes = [];
313
+ const wanted = (options.remove ?? []).map((value) => normalizeCode(value)).filter((value) => value !== "");
314
+ for (const code of wanted) {
315
+ const entry = index.entries[code];
316
+ if (entry === undefined) {
317
+ notes.push("缓存里没有 " + code + ",跳过");
318
+ continue;
319
+ }
320
+ removeEntry(cacheDir, entry, removed);
321
+ codes.delete(code);
322
+ }
323
+ if (options.olderThanDays !== undefined && options.olderThanDays > 0) {
324
+ const cutoff = Date.now() - options.olderThanDays * 24 * 3600 * 1000;
325
+ for (const code of [...codes]) {
326
+ const entry = index.entries[code];
327
+ if (entry === undefined)
328
+ continue;
329
+ const stamp = Date.parse(entry.fetchedAt);
330
+ if (Number.isNaN(stamp) || stamp >= cutoff)
331
+ continue;
332
+ removeEntry(cacheDir, entry, removed);
333
+ codes.delete(code);
334
+ }
335
+ }
336
+ if (removed.length === 0 && notes.length === 0)
337
+ notes.push("没有给出要删的编号,也没有超过期限的条目");
338
+ const bytes = removed.reduce((sum, item) => sum + item.bytes, 0);
339
+ const keptEntries = {};
340
+ for (const [code, entry] of Object.entries(index.entries))
341
+ if (codes.has(code))
342
+ keptEntries[code] = entry;
343
+ writeIndex(cacheDir, { version: 1, entries: keptEntries });
344
+ const kept = [...codes].sort((a, b) => a.localeCompare(b));
345
+ return { ok: true, error: "", removed, bytes, kept, notes };
346
+ }
347
+ function removeEntry(cacheDir, entry, removed) {
348
+ const file = entryFile(cacheDir, entry);
349
+ let bytes = entry.bytes;
350
+ try {
351
+ const stat = statSync(file);
352
+ bytes = stat.size;
353
+ }
354
+ catch {
355
+ // 文件已经不在,按索引里记的字节数计
356
+ }
357
+ try {
358
+ rmSync(file, { force: true });
359
+ }
360
+ catch {
361
+ // 删不掉就仍然从索引里摘掉,下次扫描会重建
362
+ }
363
+ const dir = join(cacheDir, entry.code);
364
+ try {
365
+ rmSync(join(dir, "digest.json"), { force: true });
366
+ }
367
+ catch {
368
+ // 索引文件删不掉不影响结论
369
+ }
370
+ removed.push({ code: entry.code, bytes });
371
+ }
@@ -128,6 +128,7 @@ function emptyReport(errors, message) {
128
128
  startedAt: 0, idleTtlMs: DEFAULT_IDLE_TTL_MS, hardTtlMs: DEFAULT_HARD_TTL_MS, remainingMs: 0,
129
129
  breakpoints: quotaOf(0, F1_BREAKPOINT_BUDGET.code),
130
130
  watchpoints: quotaOf(0, F1_BREAKPOINT_BUDGET.data),
131
+ owner: "",
131
132
  errors, message,
132
133
  };
133
134
  }
@@ -203,7 +204,7 @@ export class DebugSessionManager {
203
204
  configFile: session.configFile,
204
205
  elfPath: session.elfPath, startedAt: session.startedAt, idleTtlMs: session.idleTtlMs,
205
206
  hardTtlMs: session.hardTtlMs, remainingMs: this.remainingMs(session),
206
- breakpoints: session.breakpoints, watchpoints: session.watchpoints, errors: [],
207
+ breakpoints: session.breakpoints, watchpoints: session.watchpoints, owner: session.owner, errors: [],
207
208
  message: "调试会话进行中(端口 " + String(session.port) + ",剩余 " + String(Math.ceil(this.remainingMs(session) / 1000)) + " s)",
208
209
  };
209
210
  }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * 回合末自动构建(S136)。
3
+ *
4
+ * 目标:你在对话里改完电路源码,回到 KiCad 就能看到最新的原理图与 PCB,不必先想起点按钮。
5
+ * 三条约束换来「不烦人」:
6
+ * 1. 只在源码比产物新、或上次构建失败时才跑;
7
+ * 2. 每回合最多一次,两次之间至少 60 s;
8
+ * 3. 只跑构建 + 检查(ERC/DRC/DFM),不导出 Gerber/STEP——导出是一次性交付动作,留在按钮里。
9
+ */
10
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { runEcadDesign } from "./design.js";
13
+ import { runtimeReady } from "./runtime.js";
14
+ /** 两次自动构建之间的最小间隔:防止连续小改动把机器拖满。 */
15
+ export const AUTO_BUILD_MIN_INTERVAL_MS = 60_000;
16
+ export function ecadStateFile(projectDir) {
17
+ return join(projectDir, ".dsh-stm32", "ecad-state.json");
18
+ }
19
+ export function readAutoState(projectDir) {
20
+ const file = ecadStateFile(projectDir);
21
+ if (!existsSync(file))
22
+ return null;
23
+ try {
24
+ const raw = JSON.parse(readFileSync(file, "utf8"));
25
+ return {
26
+ lastAttemptAt: typeof raw.lastAttemptAt === "number" ? raw.lastAttemptAt : 0,
27
+ lastOk: raw.lastOk === true,
28
+ lastError: typeof raw.lastError === "string" ? raw.lastError : "",
29
+ lastDurationMs: typeof raw.lastDurationMs === "number" ? raw.lastDurationMs : 0,
30
+ lastTurn: typeof raw.lastTurn === "string" ? raw.lastTurn : "",
31
+ pendingExport: raw.pendingExport === true,
32
+ };
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ export function writeAutoState(projectDir, state) {
39
+ const file = ecadStateFile(projectDir);
40
+ mkdirSync(dirname(file), { recursive: true });
41
+ writeFileSync(file, JSON.stringify(state, null, 2) + "\n", "utf8");
42
+ }
43
+ const SKIP_DIRS = new Set(["node_modules", "dist", ".history", ".git", "build"]);
44
+ /** 目录里最新的修改时间;不存在返回 0。 */
45
+ function newestMtime(path, accept, depth = 0) {
46
+ if (depth > 6 || !existsSync(path))
47
+ return 0;
48
+ let stat;
49
+ try {
50
+ stat = statSync(path);
51
+ }
52
+ catch {
53
+ return 0;
54
+ }
55
+ if (stat.isFile())
56
+ return accept("") ? stat.mtimeMs : 0;
57
+ let newest = 0;
58
+ let entries;
59
+ try {
60
+ entries = readdirSync(path, { withFileTypes: true });
61
+ }
62
+ catch {
63
+ return 0;
64
+ }
65
+ for (const entry of entries) {
66
+ if (entry.isDirectory()) {
67
+ if (SKIP_DIRS.has(entry.name))
68
+ continue;
69
+ newest = Math.max(newest, newestMtime(join(path, entry.name), accept, depth + 1));
70
+ continue;
71
+ }
72
+ if (!entry.isFile())
73
+ continue;
74
+ if (!accept(entry.name))
75
+ continue;
76
+ try {
77
+ newest = Math.max(newest, statSync(join(path, entry.name)).mtimeMs);
78
+ }
79
+ catch {
80
+ // 读不到就跳过:这是启发式判断,不值得中断。
81
+ }
82
+ }
83
+ return newest;
84
+ }
85
+ const isSourceFile = (name) => name.endsWith(".circuit.tsx") || name.endsWith(".circuit.ts") || name.endsWith(".kicad_mod") || name.endsWith(".kicad_sym");
86
+ const isProductFile = (name) => name.endsWith(".kicad_pcb") || name.endsWith(".kicad_sch");
87
+ /** 电路源码是否比产物新。产物缺失也算脏(从没成功构建过)。 */
88
+ export function circuitDirty(workspace) {
89
+ const sourceMtime = Math.max(newestMtime(workspace.circuitDir, isSourceFile), newestMtime(workspace.libsDir, isSourceFile));
90
+ const productMtime = newestMtime(workspace.kicadDir, isProductFile);
91
+ if (productMtime === 0) {
92
+ return { dirty: sourceMtime > 0, reason: sourceMtime > 0 ? "还没有可用产物" : "没有电路源码", sourceMtime, productMtime };
93
+ }
94
+ if (sourceMtime > productMtime) {
95
+ return { dirty: true, reason: "源码比产物新", sourceMtime, productMtime };
96
+ }
97
+ return { dirty: false, reason: "产物已是最新", sourceMtime, productMtime };
98
+ }
99
+ /** 是否该跑一次自动构建。纯函数,便于单测覆盖三种拒绝理由。 */
100
+ export function decideAutoBuild(input) {
101
+ if (!input.dirty.dirty)
102
+ return { go: false, reason: input.dirty.reason };
103
+ const minInterval = input.minIntervalMs ?? AUTO_BUILD_MIN_INTERVAL_MS;
104
+ const state = input.state;
105
+ if (state !== null) {
106
+ if (state.lastTurn === input.turn && state.lastTurn !== "") {
107
+ return { go: false, reason: "本回合已经构建过" };
108
+ }
109
+ if (input.now - state.lastAttemptAt < minInterval) {
110
+ const wait = Math.ceil((minInterval - (input.now - state.lastAttemptAt)) / 1000);
111
+ return { go: false, reason: "距上次构建不足 " + String(wait) + " s" };
112
+ }
113
+ }
114
+ return { go: true, reason: input.dirty.reason };
115
+ }
116
+ /**
117
+ * 跑一次回合末自动构建。
118
+ *
119
+ * 运行时还没装时直接跳过——安装 730 MB 必须由用户点一次确认,不能藏在回合结束里。
120
+ */
121
+ export async function runAutoBuild(request) {
122
+ const { subprocess, toolchain, workspace } = request;
123
+ const now = request.now ?? Date.now();
124
+ const dirty = circuitDirty(workspace);
125
+ const state = readAutoState(workspace.projectDir);
126
+ const decision = decideAutoBuild({ dirty, state, now, turn: request.turn, minIntervalMs: request.minIntervalMs });
127
+ if (!decision.go)
128
+ return { ran: false, reason: decision.reason, ok: false, error: "", durationMs: 0, design: null };
129
+ if (!existsSync(join(workspace.circuitDir, "node_modules", "tscircuit", "cli.mjs"))) {
130
+ return { ran: false, reason: "依赖还没装:先在一键设计里确认安装共享运行时", ok: false, error: "", durationMs: 0, design: null };
131
+ }
132
+ const started = Date.now();
133
+ const design = await runEcadDesign({
134
+ subprocess,
135
+ toolchain,
136
+ workspace,
137
+ artifacts: false,
138
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
139
+ });
140
+ const durationMs = Date.now() - started;
141
+ writeAutoState(workspace.projectDir, {
142
+ lastAttemptAt: now,
143
+ lastOk: design.ok,
144
+ lastError: design.error,
145
+ lastDurationMs: durationMs,
146
+ lastTurn: request.turn,
147
+ // 通过检查就挂一个「待导出」标记:STEP/Gerber 是交付动作,等用户点头再导。
148
+ pendingExport: design.ok,
149
+ });
150
+ return { ran: true, reason: decision.reason, ok: design.ok, error: design.error, durationMs, design };
151
+ }
152
+ /** 运行时是否已就绪(面板用一句话说明「依赖装在哪」)。 */
153
+ export function runtimeLinked(circuitDir) {
154
+ return existsSync(join(circuitDir, "node_modules", "tscircuit", "cli.mjs"));
155
+ }
156
+ export { runtimeReady };