dsh-stm32 0.1.0 → 0.1.2

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 (82) hide show
  1. package/README.md +127 -29
  2. package/README_EN.md +125 -29
  3. package/client/client.js +682 -0
  4. package/docs/development-notes.md +1385 -5
  5. package/docs/logic-audit.md +607 -0
  6. package/docs/reading-guide.md +738 -0
  7. package/lib/client.js +682 -0
  8. package/lib/commands/register.js +214 -12
  9. package/lib/data/chips.js +134 -4
  10. package/lib/data/clock-f1.js +158 -0
  11. package/lib/data/cmsis-sources.js +316 -0
  12. package/lib/data/f1-ram.generated.js +34 -0
  13. package/lib/data/firmware-packages.js +352 -0
  14. package/lib/data/install-guides.js +190 -0
  15. package/lib/data/search-roots.js +135 -15
  16. package/lib/data/stm32f1.js +186 -0
  17. package/lib/data/toolchain-config.js +310 -0
  18. package/lib/engine/build.js +121 -16
  19. package/lib/engine/cache.js +336 -0
  20. package/lib/engine/clock-plan.js +608 -0
  21. package/lib/engine/cmake-sources.js +428 -0
  22. package/lib/engine/code-patch.js +18 -6
  23. package/lib/engine/debug-session.js +163 -4
  24. package/lib/engine/debug.js +84 -19
  25. package/lib/engine/doctor.js +395 -4
  26. package/lib/engine/fetch.js +287 -0
  27. package/lib/engine/firmware-install.js +668 -0
  28. package/lib/engine/flash.js +145 -15
  29. package/lib/engine/fs-longpath.js +107 -0
  30. package/lib/engine/generate-cache.js +118 -0
  31. package/lib/engine/generate-script.js +30 -8
  32. package/lib/engine/generate.js +296 -14
  33. package/lib/engine/hal-chip.js +230 -0
  34. package/lib/engine/ioc-plan.js +47 -8
  35. package/lib/engine/msys2-install.js +1870 -0
  36. package/lib/engine/probe.js +57 -6
  37. package/lib/engine/project-export.js +129 -0
  38. package/lib/engine/register-clock.js +132 -0
  39. package/lib/engine/register-linker.js +129 -0
  40. package/lib/engine/register-template.js +449 -0
  41. package/lib/engine/regs.js +18 -4
  42. package/lib/engine/route-plan.js +553 -0
  43. package/lib/engine/scaffold.js +303 -72
  44. package/lib/engine/subprocess-runner.js +2 -0
  45. package/lib/engine/tar.js +250 -0
  46. package/lib/engine/text-file.js +150 -0
  47. package/lib/engine/thirdparty.js +243 -0
  48. package/lib/engine/tool-env.js +51 -0
  49. package/lib/engine/toolchain-gate.js +386 -0
  50. package/lib/engine/vscode-config.js +99 -0
  51. package/lib/engine/web-api.js +375 -0
  52. package/lib/engine/web-routes.js +100 -0
  53. package/lib/engine/xcube-catalog.js +102 -0
  54. package/lib/engine/xcube.js +254 -0
  55. package/lib/engine/zip.js +142 -0
  56. package/lib/index.js +44 -2
  57. package/lib/skill/stm32-workflow.js +3 -3
  58. package/lib/tools/build.js +55 -3
  59. package/lib/tools/cache.js +250 -0
  60. package/lib/tools/code-patch.js +29 -2
  61. package/lib/tools/debug-session.js +56 -14
  62. package/lib/tools/debug.js +43 -2
  63. package/lib/tools/doctor.js +16 -3
  64. package/lib/tools/env-install.js +472 -0
  65. package/lib/tools/env-probe.js +6 -2
  66. package/lib/tools/firmware-install.js +255 -0
  67. package/lib/tools/flash.js +41 -2
  68. package/lib/tools/generate.js +96 -10
  69. package/lib/tools/ioc-apply.js +27 -11
  70. package/lib/tools/ioc-inspect.js +4 -2
  71. package/lib/tools/ioc-plan.js +209 -11
  72. package/lib/tools/project-create.js +229 -21
  73. package/lib/tools/project-dir.js +95 -0
  74. package/lib/tools/project-export.js +100 -0
  75. package/lib/tools/regs.js +82 -7
  76. package/lib/tools/route-plan.js +467 -0
  77. package/package.json +11 -4
  78. package/templates/register/CMakeLists.txt +52 -0
  79. package/templates/register/Core/Src/main.c +72 -0
  80. package/templates/scaffold/openocd.cfg +8 -0
  81. package/templates/scaffold/vscode/launch.json +8 -6
  82. package/templates/scaffold/vscode/settings.json +5 -11
@@ -0,0 +1,336 @@
1
+ /**
2
+ * 下载缓存("可检索的缓存目录")。
3
+ *
4
+ * 为什么要有它:寄存器版模板、未来的各类模板与工具链产物都不能预置进插件(用户 2026-10-24 决定:
5
+ * 插件要能覆盖任意 STM32,不可能每颗芯片都打一份进 npm 包)。做法是第一次用时从网上下载,
6
+ * 落到一个**可检索**的本地缓存目录,之后一律复用——所以缓存必须自带一份 index.json:
7
+ * 谁、哪一代、从哪个 URL 下的、多大、什么时候下的,都要能直接读出来,而不是靠猜目录里有什么。
8
+ *
9
+ * 目录:DSH_STM32_CACHE 覆盖,默认 %LOCALAPPDATA%\dsh-stm32\cache。
10
+ */
11
+ import crypto from "node:crypto";
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { cmsisEntryAliases } from "../data/cmsis-sources.js";
16
+ export const CACHE_INDEX_VERSION = 1;
17
+ /** 缓存根目录:环境变量优先,其次 LOCALAPPDATA,再退 USERPROFILE、临时目录。 */
18
+ export function cacheRootInfo(env = process.env) {
19
+ const override = (env.DSH_STM32_CACHE ?? "").trim();
20
+ if (override !== "") {
21
+ const root = path.resolve(expandHome(override, env));
22
+ return { root, indexPath: path.join(root, "index.json"), origin: "DSH_STM32_CACHE" };
23
+ }
24
+ const localAppData = (env.LOCALAPPDATA ?? "").trim();
25
+ if (localAppData !== "") {
26
+ const root = path.join(localAppData, "dsh-stm32", "cache");
27
+ return { root, indexPath: path.join(root, "index.json"), origin: "LOCALAPPDATA" };
28
+ }
29
+ const userProfile = (env.USERPROFILE ?? "").trim();
30
+ if (userProfile !== "") {
31
+ const root = path.join(userProfile, "AppData", "Local", "dsh-stm32", "cache");
32
+ return { root, indexPath: path.join(root, "index.json"), origin: "USERPROFILE" };
33
+ }
34
+ const root = path.join(os.tmpdir(), "dsh-stm32-cache");
35
+ return { root, indexPath: path.join(root, "index.json"), origin: "临时目录(没有 LOCALAPPDATA/USERPROFILE)" };
36
+ }
37
+ export function cacheRoot(env = process.env) {
38
+ return cacheRootInfo(env).root;
39
+ }
40
+ function expandHome(value, env) {
41
+ if (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) {
42
+ const home = (env.USERPROFILE ?? env.HOME ?? "").trim();
43
+ if (home !== "")
44
+ return path.join(home, value.slice(1));
45
+ }
46
+ return value;
47
+ }
48
+ export function emptyCacheIndex() {
49
+ return { version: CACHE_INDEX_VERSION, updatedAt: "", entries: [] };
50
+ }
51
+ /**
52
+ * 读索引。坏 JSON 不抛:缓存是可以重建的,读到坏文件就当作空索引 + 一条错误说明,
53
+ * 让调用方(工具卡片)把话讲清楚,而不是整个工具炸掉。
54
+ */
55
+ export function readCacheIndex(env = process.env) {
56
+ const info = cacheRootInfo(env);
57
+ if (!fs.existsSync(info.indexPath))
58
+ return { index: emptyCacheIndex(), error: null, path: info.indexPath };
59
+ try {
60
+ const raw = fs.readFileSync(info.indexPath, "utf8");
61
+ const parsed = JSON.parse(raw);
62
+ const entries = Array.isArray(parsed.entries) ? parsed.entries.filter(isCacheEntry) : [];
63
+ return {
64
+ index: { version: typeof parsed.version === "number" ? parsed.version : CACHE_INDEX_VERSION, updatedAt: typeof parsed.updatedAt === "string" ? parsed.updatedAt : "", entries },
65
+ error: null,
66
+ path: info.indexPath,
67
+ };
68
+ }
69
+ catch (error) {
70
+ return { index: emptyCacheIndex(), error: "缓存索引读不了(" + info.indexPath + "):" + errorText(error) + ";当作空索引,重新下载会覆盖它。", path: info.indexPath };
71
+ }
72
+ }
73
+ function isCacheEntry(value) {
74
+ if (typeof value !== "object" || value === null)
75
+ return false;
76
+ const entry = value;
77
+ return typeof entry.id === "string" && typeof entry.kind === "string" && typeof entry.root === "string" && Array.isArray(entry.files);
78
+ }
79
+ /**
80
+ * 写索引失败(可识别、带路径)。单独一个类型是为了让调用方把「索引没写成」和
81
+ * 「网络挂了」分开,并且能依赖一条硬承诺:抛错时旧索引逐字节没动。
82
+ */
83
+ export class CacheIndexWriteError extends Error {
84
+ indexPath;
85
+ constructor(indexPath, detail) {
86
+ super("缓存索引写不进去(" + indexPath + "):" + detail);
87
+ this.name = "CacheIndexWriteError";
88
+ this.indexPath = indexPath;
89
+ }
90
+ }
91
+ let tmpSeq = 0;
92
+ /** 唯一的临时名:pid + 自增序号 + 随机,同进程连续写、多进程同时写都不会撞。 */
93
+ function uniqueIndexTmp(indexPath) {
94
+ tmpSeq += 1;
95
+ const rand = Math.random().toString(16).slice(2, 10);
96
+ return indexPath + ".tmp-" + String(process.pid) + "-" + String(tmpSeq) + "-" + rand;
97
+ }
98
+ /** Windows 文件名不允许冒号,时间戳里的 : 与 . 都换成 -。 */
99
+ function stamp() {
100
+ return new Date().toISOString().replace(/[:.]/gu, "-");
101
+ }
102
+ /** 备份名:index.json.broken-<ts> / index.json.bak-<ts>;同一毫秒撞上就加序号。 */
103
+ function freeBackupPath(indexPath, tag) {
104
+ const base = indexPath + "." + tag + "-" + stamp();
105
+ if (!fs.existsSync(base))
106
+ return base;
107
+ for (let extra = 2; extra < 1000; extra += 1) {
108
+ const candidate = base + "-" + String(extra);
109
+ if (!fs.existsSync(candidate))
110
+ return candidate;
111
+ }
112
+ return base + "-" + String(Date.now());
113
+ }
114
+ function safeRemove(remove, file) {
115
+ try {
116
+ remove(file);
117
+ }
118
+ catch {
119
+ // 临时文件删不掉不影响结论。
120
+ }
121
+ }
122
+ /**
123
+ * 索引读不出来时先留一份 index.json.broken-<ts> 再重建:
124
+ * 坏文件里其它条目还有人工救回来的价值,直接覆盖等于把它们一起抹掉。
125
+ */
126
+ function preserveBrokenIndex(indexPath, reason) {
127
+ const backup = freeBackupPath(indexPath, "broken");
128
+ try {
129
+ fs.renameSync(indexPath, backup);
130
+ return backup;
131
+ }
132
+ catch (renameError) {
133
+ try {
134
+ fs.copyFileSync(indexPath, backup);
135
+ return backup;
136
+ }
137
+ catch (copyError) {
138
+ throw new CacheIndexWriteError(indexPath, reason + ";留一份备份也没成功(" + errorText(renameError) + " / " + errorText(copyError) + "),为免覆盖掉还能救回来的条目,这次不写索引。");
139
+ }
140
+ }
141
+ }
142
+ /**
143
+ * 原子换索引:tmp 用唯一名 → rename;rename 失败(Windows 上目标被占用是常见原因)
144
+ * 就先把旧索引改名成 index.json.bak-<ts>(**不删**)再搬一次;第二次仍失败就把备份原样放回。
145
+ * 硬承诺:函数抛错时旧索引仍在,绝不出现「删了好索引、新的又没搬过来」。
146
+ */
147
+ export function writeCacheIndex(index, env = process.env, io = {}) {
148
+ const info = cacheRootInfo(env);
149
+ const rename = io.rename ?? ((from, to) => { fs.renameSync(from, to); });
150
+ const writeFile = io.writeFile ?? ((file, text) => { fs.writeFileSync(file, text, "utf8"); });
151
+ const remove = io.remove ?? ((file) => { fs.rmSync(file, { force: true }); });
152
+ fs.mkdirSync(path.dirname(info.indexPath), { recursive: true });
153
+ const next = { version: CACHE_INDEX_VERSION, updatedAt: new Date().toISOString(), entries: index.entries };
154
+ const tmp = uniqueIndexTmp(info.indexPath);
155
+ try {
156
+ writeFile(tmp, JSON.stringify(next, null, 2) + "\n");
157
+ }
158
+ catch (error) {
159
+ safeRemove(remove, tmp);
160
+ throw new CacheIndexWriteError(info.indexPath, "临时文件写不进去(" + errorText(error) + "),旧索引没有动。");
161
+ }
162
+ try {
163
+ rename(tmp, info.indexPath);
164
+ return info.indexPath;
165
+ }
166
+ catch (first) {
167
+ if (!fs.existsSync(info.indexPath)) {
168
+ safeRemove(remove, tmp);
169
+ throw new CacheIndexWriteError(info.indexPath, "换索引失败(" + errorText(first) + "),旧索引没有动。");
170
+ }
171
+ }
172
+ const backup = freeBackupPath(info.indexPath, "bak");
173
+ try {
174
+ rename(info.indexPath, backup);
175
+ }
176
+ catch (error) {
177
+ safeRemove(remove, tmp);
178
+ throw new CacheIndexWriteError(info.indexPath, "旧索引既换不动也备份不了(" + errorText(error) + "),旧索引没有动。");
179
+ }
180
+ try {
181
+ rename(tmp, info.indexPath);
182
+ return info.indexPath;
183
+ }
184
+ catch (second) {
185
+ let restored = false;
186
+ try {
187
+ rename(backup, info.indexPath);
188
+ restored = true;
189
+ }
190
+ catch {
191
+ restored = false;
192
+ }
193
+ safeRemove(remove, tmp);
194
+ throw new CacheIndexWriteError(info.indexPath, "换索引失败(" + errorText(second) + ")" + (restored ? ",旧索引已原样放回。" : ",旧索引备份留在 " + backup + ",请手工改回 index.json。"));
195
+ }
196
+ }
197
+ /** 同 id 覆盖写(缓存条目重建时用)。索引读坏了先备份成 index.json.broken-<ts> 再重建。 */
198
+ export function upsertCacheEntry(entry, env = process.env) {
199
+ const read = readCacheIndex(env);
200
+ if (read.error !== null && fs.existsSync(read.path))
201
+ preserveBrokenIndex(read.path, read.error);
202
+ const index = read.index;
203
+ const entries = index.entries.filter((item) => item.id !== entry.id);
204
+ entries.push(entry);
205
+ entries.sort((a, b) => a.id.localeCompare(b.id));
206
+ const next = { version: CACHE_INDEX_VERSION, updatedAt: new Date().toISOString(), entries };
207
+ writeCacheIndex(next, env);
208
+ return next;
209
+ }
210
+ export function removeCacheEntry(id, env = process.env) {
211
+ const read = readCacheIndex(env);
212
+ // 索引读坏时删条目同样会把别的条目一起写没:先备份坏文件再动手(A2 同源缺陷)。
213
+ if (read.error !== null && fs.existsSync(read.path))
214
+ preserveBrokenIndex(read.path, read.error);
215
+ const index = read.index;
216
+ const target = index.entries.find((item) => item.id === id);
217
+ if (target === undefined)
218
+ return { removed: false, indexPath: cacheRootInfo(env).indexPath };
219
+ const rest = index.entries.filter((item) => item.id !== id);
220
+ writeCacheIndex({ version: CACHE_INDEX_VERSION, updatedAt: "", entries: rest }, env);
221
+ if (isInside(cacheRootInfo(env).root, target.root))
222
+ fs.rmSync(target.root, { recursive: true, force: true });
223
+ return { removed: true, indexPath: cacheRootInfo(env).indexPath };
224
+ }
225
+ export function findCacheEntry(index, kind, id) {
226
+ return index.entries.find((item) => item.kind === kind && item.id === id) ?? null;
227
+ }
228
+ /**
229
+ * 按"用户可能怎么写"找缓存条目:先精确命中 id,再按 cmsis 条目的别名找。
230
+ *
231
+ * 为什么需要:条目 id 的规范写法变过(0.1 是 cmsis:F1:startup_stm32f103xb,0.2 是
232
+ * cmsis:F1:103xb),而用户是照着文档/旧报错/记忆敲的(cmsis:F1:startup_stm32f103xb、
233
+ * F1:B、STM32F103C8T6 都可能)。只做精确匹配的后果是:缓存里明明有一份健康的 14 个文件,
234
+ * 却被判"没缓存"重下一遍;purge 更是删不掉——用户以为删了,下次还是旧文件。
235
+ */
236
+ export function resolveCacheEntry(index, ref) {
237
+ const direct = findCacheEntry(index, "cmsis", ref);
238
+ if (direct !== null)
239
+ return direct;
240
+ for (const candidate of cmsisEntryAliases(ref)) {
241
+ const found = findCacheEntry(index, "cmsis", candidate);
242
+ if (found !== null)
243
+ return found;
244
+ }
245
+ return null;
246
+ }
247
+ /** 0.1 的老 id:cmsis:F1:startup_stm32f103xb(0.2 是 cmsis:F1:103xb)。 */
248
+ const LEGACY_CMSIS_ID = /^cmsis:([A-Za-z0-9]+):startup_(stm32f1\d{2}[0-9a-z]+)$/u;
249
+ /**
250
+ * 清掉「已被新 id 取代」的旧缓存条目。
251
+ *
252
+ * 为什么要专门做:0.2 把 id 从 cmsis:F1:startup_stm32f103xb 改成 cmsis:F1:103xb,
253
+ * resolveCacheEntry 靠别名让老条目照样能命中——于是同一份模板可能在磁盘上留两份
254
+ * (每份 11 个文件、几百 KB)。只有「新 id 真的存在」时才删旧的,否则删了下次还得重下。
255
+ */
256
+ export function pruneLegacyEntries(env = process.env) {
257
+ const read = readCacheIndex(env);
258
+ const index = read.index;
259
+ const removed = [];
260
+ const kept = [];
261
+ let reclaimedBytes = 0;
262
+ for (const entry of index.entries) {
263
+ const match = LEGACY_CMSIS_ID.exec(entry.id);
264
+ if (match === null)
265
+ continue;
266
+ const family = match[1] ?? "";
267
+ const stem = match[2] ?? "";
268
+ const line = stem.slice(6, 9);
269
+ const group = stem.slice(9);
270
+ const newId = "cmsis:" + family + ":" + line + group;
271
+ if (findCacheEntry(index, "cmsis", newId) === null) {
272
+ kept.push(entry.id);
273
+ continue;
274
+ }
275
+ const result = removeCacheEntry(entry.id, env);
276
+ if (result.removed) {
277
+ removed.push(entry.id);
278
+ reclaimedBytes += entry.totalBytes;
279
+ }
280
+ }
281
+ return { removed, kept, reclaimedBytes };
282
+ }
283
+ /**
284
+ * 校验条目里的文件还在不在、内容对不对。
285
+ * 有 sha256 的条目比内容哈希(A38):字节数只能挡半截文件,挡不住"同样大小、内容被换掉"。
286
+ * 老条目没有 sha256 时退回只比字节数,不把已存在的缓存判死。
287
+ */
288
+ export function checkCacheEntry(entry) {
289
+ const missing = [];
290
+ const changed = [];
291
+ for (const file of entry.files) {
292
+ const full = path.join(entry.root, file.path);
293
+ if (!fs.existsSync(full)) {
294
+ missing.push(file.path);
295
+ continue;
296
+ }
297
+ const size = fs.statSync(full).size;
298
+ if (size !== file.bytes) {
299
+ changed.push(file.path + "(" + String(size) + " ≠ " + String(file.bytes) + " 字节)");
300
+ continue;
301
+ }
302
+ if (file.sha256 !== undefined && file.sha256 !== "") {
303
+ let actual = "";
304
+ try {
305
+ actual = sha256OfFile(full);
306
+ }
307
+ catch {
308
+ missing.push(file.path);
309
+ continue;
310
+ }
311
+ if (actual !== file.sha256)
312
+ changed.push(file.path + "(内容 sha256 对不上,可能被替换过)");
313
+ }
314
+ }
315
+ return { entry, missing, changed, ok: missing.length === 0 && changed.length === 0 };
316
+ }
317
+ /** 算文件内容的 sha256(小写 hex)。缓存登记与校验共用同一口径。 */
318
+ export function sha256OfFile(file) {
319
+ return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
320
+ }
321
+ export function describeCacheBytes(bytes) {
322
+ if (bytes < 1024)
323
+ return String(bytes) + " B";
324
+ if (bytes < 1024 * 1024)
325
+ return (bytes / 1024).toFixed(1) + " KB";
326
+ if (bytes < 1024 * 1024 * 1024)
327
+ return (bytes / (1024 * 1024)).toFixed(1) + " MB";
328
+ return (bytes / (1024 * 1024 * 1024)).toFixed(2) + " GB";
329
+ }
330
+ function isInside(root, candidate) {
331
+ const rel = path.relative(path.resolve(root), path.resolve(candidate));
332
+ return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
333
+ }
334
+ function errorText(error) {
335
+ return error instanceof Error ? error.message : String(error);
336
+ }