@turingcode/cli 0.2.13 → 0.3.5

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 (185) hide show
  1. package/README.md +2 -0
  2. package/dist/cli/create-cli.d.ts +10 -0
  3. package/dist/cli/create-cli.js +17 -4
  4. package/dist/cli/index.d.ts +9 -0
  5. package/dist/cli/index.js +5 -1
  6. package/dist/core/bound-error.d.ts +10 -0
  7. package/dist/core/date.d.ts +12 -0
  8. package/dist/core/exact/expression.d.ts +49 -0
  9. package/dist/core/exact/fraction.d.ts +85 -0
  10. package/dist/core/exact/fraction.js +2 -0
  11. package/dist/core/files.d.ts +44 -0
  12. package/dist/core/files.js +48 -3
  13. package/dist/core/json-shape.d.ts +45 -0
  14. package/dist/core/json-shape.js +1 -0
  15. package/dist/core/mcp.d.ts +92 -0
  16. package/dist/core/mcp.js +56 -15
  17. package/dist/core/query.d.ts +69 -0
  18. package/dist/core/query.js +2 -2
  19. package/dist/core/report.d.ts +11 -0
  20. package/dist/core/tables/csv.d.ts +29 -0
  21. package/dist/core/tables/csv.js +54 -25
  22. package/dist/core/tables/markdown.d.ts +22 -0
  23. package/dist/core/tables/markdown.js +8 -2
  24. package/dist/core/tables/types.d.ts +25 -0
  25. package/dist/features/contract/check.d.ts +30 -0
  26. package/dist/features/contract/command.d.ts +12 -0
  27. package/dist/features/contract/command.js +64 -64
  28. package/dist/features/contract/describe.d.ts +22 -0
  29. package/dist/features/contract/diagnostics.d.ts +111 -0
  30. package/dist/features/contract/diagnostics.js +7 -4
  31. package/dist/features/contract/load.d.ts +58 -0
  32. package/dist/features/contract/load.js +4 -4
  33. package/dist/features/contract/model.d.ts +67 -0
  34. package/dist/features/contract/rules.d.ts +149 -0
  35. package/dist/features/contract/rules.js +31 -4
  36. package/dist/features/debug/clear_breakpoint.d.ts +3 -0
  37. package/dist/features/debug/clear_breakpoint.js +24 -0
  38. package/dist/features/debug/command.d.ts +5 -0
  39. package/dist/features/debug/command.js +66 -0
  40. package/dist/features/debug/continue.d.ts +3 -0
  41. package/dist/features/debug/continue.js +22 -0
  42. package/dist/features/debug/debug_start.d.ts +3 -0
  43. package/dist/features/debug/debug_start.js +22 -0
  44. package/dist/features/debug/debug_stop.d.ts +3 -0
  45. package/dist/features/debug/debug_stop.js +11 -0
  46. package/dist/features/debug/evaluate.d.ts +3 -0
  47. package/dist/features/debug/evaluate.js +48 -0
  48. package/dist/features/debug/get_stack.d.ts +3 -0
  49. package/dist/features/debug/get_stack.js +14 -0
  50. package/dist/features/debug/get_variables.d.ts +3 -0
  51. package/dist/features/debug/get_variables.js +26 -0
  52. package/dist/features/debug/halt.d.ts +3 -0
  53. package/dist/features/debug/halt.js +16 -0
  54. package/dist/features/debug/set_breakpoint.d.ts +3 -0
  55. package/dist/features/debug/set_breakpoint.js +30 -0
  56. package/dist/features/debug/step.d.ts +3 -0
  57. package/dist/features/debug/step.js +23 -0
  58. package/dist/features/install-mods/command.d.ts +6 -0
  59. package/dist/features/install-mods/command.js +18 -0
  60. package/dist/features/install-mods/install.d.ts +23 -0
  61. package/dist/features/install-mods/install.js +49 -0
  62. package/dist/features/install-skills/command.d.ts +7 -0
  63. package/dist/features/install-skills/command.js +22 -0
  64. package/dist/features/install-skills/install.d.ts +14 -0
  65. package/dist/features/install-skills/install.js +29 -0
  66. package/dist/features/probe/command.d.ts +5 -0
  67. package/dist/features/probe/command.js +112 -0
  68. package/dist/features/probe/kill_all_debuggers.d.ts +3 -0
  69. package/dist/features/probe/kill_all_debuggers.js +50 -0
  70. package/dist/features/probe/list_probes.d.ts +3 -0
  71. package/dist/features/probe/list_probes.js +8 -0
  72. package/dist/features/probe/program_project.d.ts +3 -0
  73. package/dist/features/probe/program_project.js +29 -0
  74. package/dist/features/probe/read_fault_status.d.ts +3 -0
  75. package/dist/features/probe/read_fault_status.js +19 -0
  76. package/dist/features/probe/read_memory.d.ts +3 -0
  77. package/dist/features/probe/read_memory.js +36 -0
  78. package/dist/features/probe/read_peripheral.d.ts +3 -0
  79. package/dist/features/probe/read_peripheral.js +60 -0
  80. package/dist/features/probe/reset_probe_usb.d.ts +3 -0
  81. package/dist/features/probe/reset_probe_usb.js +17 -0
  82. package/dist/features/probe/reset_target.d.ts +3 -0
  83. package/dist/features/probe/reset_target.js +16 -0
  84. package/dist/features/probe/target_info.d.ts +3 -0
  85. package/dist/features/probe/target_info.js +34 -0
  86. package/dist/features/project/analysis_static.d.ts +3 -0
  87. package/dist/features/project/analysis_static.js +19 -0
  88. package/dist/features/project/analysis_syntax_check.d.ts +3 -0
  89. package/dist/features/project/analysis_syntax_check.js +21 -0
  90. package/dist/features/project/command.d.ts +5 -0
  91. package/dist/features/project/command.js +64 -0
  92. package/dist/features/project/project_build.d.ts +3 -0
  93. package/dist/features/project/project_build.js +22 -0
  94. package/dist/features/project/project_download_template.d.ts +3 -0
  95. package/dist/features/project/project_download_template.js +34 -0
  96. package/dist/features/project/project_regenerate.d.ts +2 -0
  97. package/dist/features/project/project_regenerate.js +20 -0
  98. package/dist/features/project/project_sync_from_server.d.ts +2 -0
  99. package/dist/features/project/project_sync_from_server.js +13 -0
  100. package/dist/features/project/project_sync_to_server.d.ts +2 -0
  101. package/dist/features/project/project_sync_to_server.js +51 -0
  102. package/dist/features/project/stm32_cubetools_download_drivers.d.ts +3 -0
  103. package/dist/features/project/stm32_cubetools_download_drivers.js +19 -0
  104. package/dist/features/status/command.d.ts +2 -0
  105. package/dist/features/status/command.js +6 -0
  106. package/dist/features/status/get_status.d.ts +3 -0
  107. package/dist/features/status/get_status.js +44 -0
  108. package/dist/features/table/check.d.ts +38 -0
  109. package/dist/features/table/check.js +5 -5
  110. package/dist/features/table/command.d.ts +3 -0
  111. package/dist/features/table/read.d.ts +28 -0
  112. package/dist/features/table/read.js +9 -9
  113. package/dist/features/tool/command.d.ts +35 -0
  114. package/dist/features/tool/command.js +95 -66
  115. package/dist/lib.d.ts +15 -0
  116. package/dist/lib.js +11 -0
  117. package/dist/stm32/actions/DebugAction.d.ts +65 -0
  118. package/dist/stm32/actions/DebugAction.js +106 -0
  119. package/dist/stm32/actions/DebugActionInfo.d.ts +11 -0
  120. package/dist/stm32/actions/DebugActionInfo.js +11 -0
  121. package/dist/stm32/actions/DebugActionListProbes.d.ts +10 -0
  122. package/dist/stm32/actions/DebugActionListProbes.js +10 -0
  123. package/dist/stm32/actions/DebugActionProgram.d.ts +34 -0
  124. package/dist/stm32/actions/DebugActionProgram.js +81 -0
  125. package/dist/stm32/actions/DebugActionRead.d.ts +39 -0
  126. package/dist/stm32/actions/DebugActionRead.js +61 -0
  127. package/dist/stm32/actions/DebugActionReset.d.ts +12 -0
  128. package/dist/stm32/actions/DebugActionReset.js +9 -0
  129. package/dist/stm32/actions/DebugActionServer.d.ts +11 -0
  130. package/dist/stm32/actions/DebugActionServer.js +11 -0
  131. package/dist/stm32/analysis.d.ts +20 -0
  132. package/dist/stm32/analysis.js +21 -0
  133. package/dist/stm32/build.d.ts +34 -0
  134. package/dist/stm32/build.js +79 -0
  135. package/dist/stm32/context.d.ts +23 -0
  136. package/dist/stm32/context.js +42 -0
  137. package/dist/stm32/daemon.d.ts +65 -0
  138. package/dist/stm32/daemon.js +209 -0
  139. package/dist/stm32/regen.d.ts +68 -0
  140. package/dist/stm32/regen.js +231 -0
  141. package/dist/stm32/session.d.ts +137 -0
  142. package/dist/stm32/session.js +375 -0
  143. package/dist/stm32/sync.d.ts +25 -0
  144. package/dist/stm32/sync.js +74 -0
  145. package/dist/stm32/tool.d.ts +45 -0
  146. package/dist/stm32/tool.js +20 -0
  147. package/dist/stm32/toolCommand.d.ts +50 -0
  148. package/dist/stm32/toolCommand.js +100 -0
  149. package/dist/stm32/utils/discover_tools.d.ts +25 -0
  150. package/dist/stm32/utils/discover_tools.js +121 -0
  151. package/dist/stm32/utils/downloadzip_utils.d.ts +57 -0
  152. package/dist/stm32/utils/downloadzip_utils.js +180 -0
  153. package/dist/stm32/utils/faultUtils.d.ts +15 -0
  154. package/dist/stm32/utils/faultUtils.js +69 -0
  155. package/dist/stm32/utils/findElf.d.ts +9 -0
  156. package/dist/stm32/utils/findElf.js +19 -0
  157. package/dist/stm32/utils/hash_utils.d.ts +19 -0
  158. package/dist/stm32/utils/hash_utils.js +28 -0
  159. package/dist/stm32/utils/listSyncFiles.d.ts +9 -0
  160. package/dist/stm32/utils/listSyncFiles.js +100 -0
  161. package/dist/stm32/utils/mcu_utils.d.ts +58 -0
  162. package/dist/stm32/utils/mcu_utils.js +100 -0
  163. package/dist/stm32/utils/project_utils.d.ts +54 -0
  164. package/dist/stm32/utils/project_utils.js +104 -0
  165. package/dist/stm32/utils/svdUtils.d.ts +31 -0
  166. package/dist/stm32/utils/svdUtils.js +30 -0
  167. package/dist/stm32/utils/truncate.d.ts +7 -0
  168. package/dist/stm32/utils/truncate.js +9 -0
  169. package/dist/stm32/utils/usb_utils.d.ts +5 -0
  170. package/dist/stm32/utils/usb_utils.js +23 -0
  171. package/dist/stm32/utils/user_code.d.ts +17 -0
  172. package/dist/stm32/utils/user_code.js +45 -0
  173. package/dist/stm32/utils/utils_mutex.d.ts +15 -0
  174. package/dist/stm32/utils/utils_mutex.js +113 -0
  175. package/dist/stm32/validate.d.ts +17 -0
  176. package/dist/stm32/validate.js +46 -0
  177. package/mods/claude/.claude-plugin/marketplace.json +8 -0
  178. package/mods/claude/turingcode-skills/.claude-plugin/plugin.json +5 -0
  179. package/mods/claude/turingcode-skills/skills/turingcode-cli/SKILL.md +44 -0
  180. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/SKILL.md +47 -0
  181. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/concurrency.md +42 -0
  182. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/init-and-timing.md +35 -0
  183. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/input-and-bounds.md +21 -0
  184. package/mods/claude/turingcode-skills/skills/turingcode-firmware-code/references/registers-and-units.md +35 -0
  185. package/package.json +11 -3
@@ -0,0 +1,28 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ /**
5
+ * Hashes data with sha256.
6
+ * @param data the bytes or text to hash
7
+ * @returns the hex digest
8
+ */
9
+ export function sha256(data) {
10
+ return createHash('sha256').update(data).digest('hex');
11
+ }
12
+ /**
13
+ * Reads files and hashes their contents with sha256.
14
+ * @param root the folder the file names are relative to
15
+ * @param files file names relative to root
16
+ * @returns a map of each file name to its hex digest
17
+ */
18
+ export async function sha256Files(root, files) {
19
+ return Object.fromEntries(await Promise.all(files.map(async (name) => [name, sha256(await readFile(join(root, name)))])));
20
+ }
21
+ /**
22
+ * Formats a file hash map as `sha256sum` output, the manifest the server's sync links take.
23
+ * @param manifest map of posix file names to their hex sha256
24
+ * @returns one `<sha256> <name>` line per file
25
+ */
26
+ export function toSha256sum(manifest) {
27
+ return Object.entries(manifest).map(([name, hash]) => `${hash} ${name}\n`).join('');
28
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Lists the project files to push (posix relative paths): everything except build/, folders starting with a dot,
3
+ * .env files, .zip/.csv/.gz/.gzip/.rar files, .md files other than README.md, files over 10 MB and git-ignored files. Drivers/ is always listed, even when git-ignored.
4
+ * Only the files whose hash differs from the server's copy are uploaded, so the unchanged Drivers/ costs only its manifest entries.
5
+ * Files and folders in included_files of .turingcode/settings.json are synced despite these rules, except archives and files over 10 MB.
6
+ * Logs a warning when git is unavailable, as .gitignore is then not applied.
7
+ * ponytail: without git installed, .gitignore is not applied (only the fixed excludes); parse it here if that matters.
8
+ */
9
+ export declare function listSyncFiles(root: string): Promise<string[]>;
@@ -0,0 +1,100 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readdir, rm, stat } from "node:fs/promises";
3
+ import { join, sep } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { loadProjectSettings } from "./project_utils.js";
6
+ const run = promisify(execFile);
7
+ const LS_FILES = ["ls-files", "--cached", "--others", "--exclude-standard", "-z"];
8
+ const MAX_FILE_SIZE = 10 * 1024 * 1024;
9
+ const ALWAYS_SKIPPED = /\.(zip|gz|gzip|rar)$/i; /** archives, even when listed in included_files */
10
+ /**
11
+ * Path rules for listed files (included_files bypass them): skips build/, dot folders, .env files,
12
+ * .csv and .md files except README.md.
13
+ * @param rel posix path relative to the project root
14
+ * @returns true if the path passes the rules
15
+ */
16
+ function isSyncablePre(rel) {
17
+ return (!rel.startsWith("build/") &&
18
+ !/(^|\/)\.[^/]*\//.test(rel) && /** dot folders at any depth: .git, .turingcode, .codex, .vscode, ... */
19
+ !/(^|\/)\.env(\.[^/]*)?$/.test(rel) && /** .env, .env.local, ... */
20
+ !/\.csv$/i.test(rel) && /** data dumps */
21
+ (!/\.md$/i.test(rel) || /(^|\/)README\.md$/i.test(rel)) /** docs, except READMEs */);
22
+ }
23
+ /**
24
+ * Final check applied to every file, included_files too: not an archive, still exists and small enough to sync;
25
+ * logs a warning for files over MAX_FILE_SIZE.
26
+ * @param root project root
27
+ * @param rel posix path relative to root
28
+ * @returns true if the file is not an archive, exists and is at most MAX_FILE_SIZE bytes
29
+ */
30
+ async function isSyncableFinal(root, rel) {
31
+ if (ALWAYS_SKIPPED.test(rel))
32
+ return false;
33
+ const st = await stat(join(root, rel)).catch(() => undefined);
34
+ if (!st?.isFile())
35
+ return false; /** deleted-but-tracked files are skipped, and folders */
36
+ if (st.size <= MAX_FILE_SIZE)
37
+ return true;
38
+ console.warn(`[sync] skipping ${rel}: larger than 10 MB`);
39
+ return false;
40
+ }
41
+ /**
42
+ Runs `git ls-files` (tracked + untracked, .gitignore applied) in root;
43
+ returns undefined and logs a warning if git is missing or fails.
44
+ */
45
+ async function gitListFiles(root) {
46
+ const list = async (extra) => (await run("git", [...extra, ...LS_FILES], { cwd: root, maxBuffer: 64 * 1024 * 1024, windowsHide: true })).stdout.split("\0").filter(Boolean);
47
+ const listed = await list([]).catch(() => []);
48
+ if (listed.length)
49
+ return listed;
50
+ /** Not a repo, or ignored by a parent repo: a throwaway git dir in .turingcode still applies the project's .gitignore files. */
51
+ const gitDir = join(root, ".turingcode", `git-${process.pid}`);
52
+ try {
53
+ await run("git", ["init", "-q", "--bare", gitDir], { windowsHide: true });
54
+ return await list([`--git-dir=${gitDir}`, `--work-tree=${root}`]);
55
+ }
56
+ catch (e) {
57
+ console.warn(`[sync] ${e?.code === "ENOENT" ? "git not found" : `git failed: ${e?.message}`}`);
58
+ return undefined;
59
+ }
60
+ finally {
61
+ await rm(gitDir, { recursive: true, force: true });
62
+ }
63
+ }
64
+ /**
65
+ * Lists every file under root/dir, recursively.
66
+ * @param root project root folder
67
+ * @param dir subfolder of root to walk ("" for root itself)
68
+ * @returns posix paths relative to root; empty when dir is missing
69
+ */
70
+ async function walkFiles(root, dir = "") {
71
+ const ents = await readdir(join(root, dir), { recursive: true, withFileTypes: true }).catch(() => []);
72
+ return ents.filter((e) => e.isFile()).map((e) => join(e.parentPath, e.name).slice(root.length + 1).split(sep).join("/"));
73
+ }
74
+ /**
75
+ * Lists the project files to push (posix relative paths): everything except build/, folders starting with a dot,
76
+ * .env files, .zip/.csv/.gz/.gzip/.rar files, .md files other than README.md, files over 10 MB and git-ignored files. Drivers/ is always listed, even when git-ignored.
77
+ * Only the files whose hash differs from the server's copy are uploaded, so the unchanged Drivers/ costs only its manifest entries.
78
+ * Files and folders in included_files of .turingcode/settings.json are synced despite these rules, except archives and files over 10 MB.
79
+ * Logs a warning when git is unavailable, as .gitignore is then not applied.
80
+ * ponytail: without git installed, .gitignore is not applied (only the fixed excludes); parse it here if that matters.
81
+ */
82
+ export async function listSyncFiles(root) {
83
+ let all = await gitListFiles(root);
84
+ if (!all) {
85
+ console.warn("[sync] git is not available, so .gitignore was not applied: syncing everything except build/, dot folders, .env, .md and archive/.csv files");
86
+ all = await walkFiles(root);
87
+ }
88
+ else {
89
+ /** git lists a submodule or nested repo as its folder: sync the files in it.
90
+ * shortcut: the nested repo's own .gitignore is not applied; list it with gitListFiles if its build output gets synced. */
91
+ const expanded = await Promise.all(all.map(async (p) => ((await stat(join(root, p)).catch(() => undefined))?.isDirectory() ? walkFiles(root, p) : [p])));
92
+ all = [...new Set([...expanded.flat(), ...(await walkFiles(root, "Drivers"))])];
93
+ }
94
+ const filtered = all.filter(isSyncablePre);
95
+ const { included_files } = await loadProjectSettings(root);
96
+ const included = await Promise.all(included_files.map(async (p) => ((await stat(join(root, p)).catch(() => undefined))?.isFile() ? [p] : walkFiles(root, p))));
97
+ const candidates = [...new Set([...filtered, ...included.flat()])];
98
+ const syncable = await Promise.all(candidates.map((rel) => isSyncableFinal(root, rel)));
99
+ return candidates.filter((_, i) => syncable[i]);
100
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Returns the CubeMX MCU name (e.g. STM32G474RETx) from a project_template or project_create reply.
3
+ * @param text the server reply
4
+ * @returns the MCU name, or undefined when the reply names none
5
+ */
6
+ export declare function getMcuFromText(text: string): string | undefined;
7
+ /**
8
+ * Tells whether an STM32 has an Armv6-M core (Cortex-M0/M0+), which has no CFSR/HFSR fault status registers.
9
+ * @param mcu CubeMX MCU name (e.g. STM32G071RBTx)
10
+ * @returns true for the C0, F0, G0, L0, U0, WB0 and WL3 families
11
+ */
12
+ export declare function isArmv6m(mcu: string): boolean;
13
+ /**
14
+ * Tells whether an STM32 is a G47x/G48x with 128 or 256 KB flash, whose probe-rs flash algorithm
15
+ * only fits the single-bank layout (FLASH_OPTR.DBANK = 0).
16
+ * @param mcu CubeMX MCU name (e.g. STM32G474CCTx)
17
+ * @returns true for STM32G47x/G48x parts with flash size code B or C
18
+ */
19
+ export declare function hasSingleBankFlashAlgo(mcu: string): boolean;
20
+ /**
21
+ * Reads the CubeMX MCU name (e.g. STM32G474RETx) from the .ioc file at the project root.
22
+ * @param root project root (folder with .mxproject)
23
+ * @returns the Mcu.UserName value, which probe-rs accepts as its chip name
24
+ */
25
+ export declare function getMcuFromIoc(root: string): Promise<string>;
26
+ /** What STM32_Programmer_CLI reports about the connected target. */
27
+ export interface TargetInfo {
28
+ deviceId?: string; /** e.g. 0x422 */
29
+ name?: string; /** e.g. STM32F302xB-xC/STM32F303xB-xC/F358xx */
30
+ flashKb?: number;
31
+ cpu?: string;
32
+ voltage?: string;
33
+ }
34
+ /**
35
+ * Parses the `Key : value` lines STM32_Programmer_CLI prints on connect.
36
+ * @param text its output
37
+ * @returns the fields it found
38
+ */
39
+ export declare function parseTargetInfo(text: string): TargetInfo;
40
+ /**
41
+ * The product lines of a device name, e.g. `STM32F302xB-xC/STM32F303xB-xC/F358xx` -> F302, F303, F358.
42
+ * @param name device name from STM32_Programmer_CLI
43
+ * @returns the lines, without the STM32 prefix
44
+ */
45
+ export declare function deviceLines(name: string): string[];
46
+ /**
47
+ * Picks the CubeMX MCU names that match a connected target's product lines and flash size.
48
+ * @param names CubeMX MCU names (e.g. from list_mcu_names)
49
+ * @param info the target info
50
+ * @returns the matching names; all of the lines' names when the flash size has no letter
51
+ */
52
+ export declare function matchMcuNames(names: string[], info: TargetInfo): string[];
53
+ /**
54
+ * The family code list_mcu_names takes for a product line: F303 -> F3, G474 -> G4, WB55 -> WB.
55
+ * @param line product line without the STM32 prefix
56
+ * @returns the family code
57
+ */
58
+ export declare function lineFamily(line: string): string;
@@ -0,0 +1,100 @@
1
+ import { readFile, readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ /**
4
+ * Server reply formats that name the resolved CubeMX MCU
5
+ * Error replies are left out.
6
+ */
7
+ const MCU_PATTERNS = [
8
+ /^Barebone project template for (STM32\w+) \(/m, /** PROJECT_TEMPLATE_READY */
9
+ /^Created project '[^']*' \((STM32\w+), /m, /** PROJECT_CREATED */
10
+ ];
11
+ /**
12
+ * Returns the CubeMX MCU name (e.g. STM32G474RETx) from a project_template or project_create reply.
13
+ * @param text the server reply
14
+ * @returns the MCU name, or undefined when the reply names none
15
+ */
16
+ export function getMcuFromText(text) {
17
+ for (const re of MCU_PATTERNS) {
18
+ const m = text.match(re);
19
+ if (m)
20
+ return m[1];
21
+ }
22
+ return undefined;
23
+ }
24
+ /**
25
+ * Tells whether an STM32 has an Armv6-M core (Cortex-M0/M0+), which has no CFSR/HFSR fault status registers.
26
+ * @param mcu CubeMX MCU name (e.g. STM32G071RBTx)
27
+ * @returns true for the C0, F0, G0, L0, U0, WB0 and WL3 families
28
+ */
29
+ export function isArmv6m(mcu) {
30
+ return /^STM32(C0|F0|G0|L0|U0|WB0|WL3)/.test(mcu);
31
+ }
32
+ /**
33
+ * Tells whether an STM32 is a G47x/G48x with 128 or 256 KB flash, whose probe-rs flash algorithm
34
+ * only fits the single-bank layout (FLASH_OPTR.DBANK = 0).
35
+ * @param mcu CubeMX MCU name (e.g. STM32G474CCTx)
36
+ * @returns true for STM32G47x/G48x parts with flash size code B or C
37
+ */
38
+ export function hasSingleBankFlashAlgo(mcu) {
39
+ return /^STM32G4[78]\d.[BC]/.test(mcu);
40
+ }
41
+ /**
42
+ * Reads the CubeMX MCU name (e.g. STM32G474RETx) from the .ioc file at the project root.
43
+ * @param root project root (folder with .mxproject)
44
+ * @returns the Mcu.UserName value, which probe-rs accepts as its chip name
45
+ */
46
+ export async function getMcuFromIoc(root) {
47
+ const ioc = (await readdir(root)).find((n) => n.toLowerCase().endsWith(".ioc"));
48
+ if (!ioc)
49
+ throw new Error(`No .ioc file in ${root}: cannot tell which MCU to program`);
50
+ const m = (await readFile(join(root, ioc), "utf8")).match(/^Mcu\.UserName=(\S+)/m);
51
+ if (!m)
52
+ throw new Error(`No Mcu.UserName in ${ioc}: cannot tell which MCU to program`);
53
+ return m[1];
54
+ }
55
+ /**
56
+ * Parses the `Key : value` lines STM32_Programmer_CLI prints on connect.
57
+ * @param text its output
58
+ * @returns the fields it found
59
+ */
60
+ export function parseTargetInfo(text) {
61
+ const get = (key) => text.match(new RegExp(`^\\s*${key}\\s*:\\s*(.+?)\\s*$`, 'm'))?.[1];
62
+ const flash = get('Flash size')?.match(/^(\d+)\s*KBytes/i);
63
+ const mb = get('Flash size')?.match(/^(\d+)\s*MBytes/i);
64
+ return {
65
+ deviceId: get('Device ID'),
66
+ name: get('Device name'),
67
+ flashKb: flash ? Number(flash[1]) : mb ? Number(mb[1]) * 1024 : undefined,
68
+ cpu: get('Device CPU'),
69
+ voltage: get('Voltage'),
70
+ };
71
+ }
72
+ /** The flash size letter of a CubeMX MCU name (the 11th character, e.g. STM32F303C[C]Tx) by size in KB */
73
+ const FLASH_CODES = { 16: '4', 32: '6', 64: '8', 128: 'B', 192: 'Z', 256: 'C', 384: 'D', 512: 'E', 768: 'F', 1024: 'G', 1536: 'H', 2048: 'I' };
74
+ /**
75
+ * The product lines of a device name, e.g. `STM32F302xB-xC/STM32F303xB-xC/F358xx` -> F302, F303, F358.
76
+ * @param name device name from STM32_Programmer_CLI
77
+ * @returns the lines, without the STM32 prefix
78
+ */
79
+ export function deviceLines(name) {
80
+ return name.split('/').map((part) => part.trim().replace(/^STM32/i, '').split(/x|-/)[0].toUpperCase()).filter(Boolean);
81
+ }
82
+ /**
83
+ * Picks the CubeMX MCU names that match a connected target's product lines and flash size.
84
+ * @param names CubeMX MCU names (e.g. from list_mcu_names)
85
+ * @param info the target info
86
+ * @returns the matching names; all of the lines' names when the flash size has no letter
87
+ */
88
+ export function matchMcuNames(names, info) {
89
+ const lines = info.name ? deviceLines(info.name) : [];
90
+ const code = info.flashKb !== undefined ? FLASH_CODES[info.flashKb] : undefined;
91
+ return names.filter((n) => lines.some((l) => n.startsWith(`STM32${l}`)) && (!code || n[10] === code));
92
+ }
93
+ /**
94
+ * The family code list_mcu_names takes for a product line: F303 -> F3, G474 -> G4, WB55 -> WB.
95
+ * @param line product line without the STM32 prefix
96
+ * @returns the family code
97
+ */
98
+ export function lineFamily(line) {
99
+ return line.match(/^[A-Z]\d/)?.[0] ?? line.match(/^[A-Z]+/)?.[0] ?? line;
100
+ }
@@ -0,0 +1,54 @@
1
+ export interface ProjectSettings {
2
+ included_files: string[]; /** posix paths relative to the project root; files or folders synced even when otherwise excluded */
3
+ }
4
+ /**
5
+ * Loads <root>/.turingcode/settings.json, filling missing keys with defaults.
6
+ * @param root project root folder
7
+ * @returns the project settings; defaults when the file does not exist
8
+ * @throws when the file is not valid JSON, a key has the wrong type, or a path points outside the project
9
+ */
10
+ export declare function loadProjectSettings(root: string): Promise<ProjectSettings>;
11
+ /**
12
+ * Turns a settings path into a posix path relative to root, refusing paths outside the project.
13
+ * @param root project root folder
14
+ * @param p path as written in settings.json
15
+ * @param file settings file, for the error message
16
+ * @returns the normalized relative path ("" for the root itself)
17
+ */
18
+ export declare function toProjectPath(root: string, p: string, file: string): string;
19
+ /**
20
+ * Finds the project folder from a start folder: the nearest folder at or above it holding .turingcode/ (where the
21
+ * VS Code extension and the debug daemon keep their files; not the home folder's) or a .ioc or .mxproject file, else start itself.
22
+ * @param start folder to start from, default the working directory
23
+ * @returns the project root folder and name (its folder name)
24
+ */
25
+ export declare function findProject(start?: string): Promise<{
26
+ root: string;
27
+ name: string;
28
+ }>;
29
+ /**
30
+ * Finds the STM32 project inside the project folder: the folder itself or a subfolder holding a .ioc or .mxproject file.
31
+ * @param start folder to start from, see findProject
32
+ * @returns the STM32 project root and name (its folder name)
33
+ * @throws when no STM32 project or more than one is found
34
+ */
35
+ export declare function findStm32Project(start?: string): Promise<{
36
+ root: string;
37
+ name: string;
38
+ }>;
39
+ /**
40
+ * Finds the STM32 project in a given folder without looking above it: the folder itself or a subfolder holding a .ioc or .mxproject file.
41
+ * @param root folder to search, e.g. the folder open in VS Code
42
+ * @returns the STM32 project root and name (its folder name)
43
+ * @throws when no STM32 project or more than one is found
44
+ */
45
+ export declare function findStm32ProjectIn(root: string): Promise<{
46
+ root: string;
47
+ name: string;
48
+ }>;
49
+ /**
50
+ * Lists dir and every folder below it that holds a .ioc or .mxproject file, without walking SKIPPED_DIRS.
51
+ * @param dir folder to search
52
+ * @returns the matching folders, absolute
53
+ */
54
+ export declare function findIocFolders(dir: string): Promise<string[]>;
@@ -0,0 +1,104 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
3
+ import { homedir } from "node:os";
4
+ const DEFAULTS = { included_files: [] };
5
+ /**
6
+ * Loads <root>/.turingcode/settings.json, filling missing keys with defaults.
7
+ * @param root project root folder
8
+ * @returns the project settings; defaults when the file does not exist
9
+ * @throws when the file is not valid JSON, a key has the wrong type, or a path points outside the project
10
+ */
11
+ export async function loadProjectSettings(root) {
12
+ const file = join(root, ".turingcode", "settings.json");
13
+ const text = await readFile(file, "utf8").catch((e) => (e?.code === "ENOENT" ? undefined : Promise.reject(e)));
14
+ if (text === undefined)
15
+ return { ...DEFAULTS };
16
+ let raw;
17
+ try {
18
+ raw = JSON.parse(text);
19
+ }
20
+ catch (e) {
21
+ throw new Error(`${file} is not valid JSON: ${e?.message}`);
22
+ }
23
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw))
24
+ throw new Error(`${file} must contain a JSON object`);
25
+ const included = raw.included_files ?? [];
26
+ if (!Array.isArray(included) || !included.every((p) => typeof p === "string"))
27
+ throw new Error(`${file}: included_files must be an array of strings`);
28
+ return { included_files: included.map((p) => toProjectPath(root, p, file)).filter(Boolean) };
29
+ }
30
+ /**
31
+ * Turns a settings path into a posix path relative to root, refusing paths outside the project.
32
+ * @param root project root folder
33
+ * @param p path as written in settings.json
34
+ * @param file settings file, for the error message
35
+ * @returns the normalized relative path ("" for the root itself)
36
+ */
37
+ export function toProjectPath(root, p, file) {
38
+ const rel = relative(root, resolve(root, p));
39
+ if (rel.startsWith("..") || isAbsolute(rel))
40
+ throw new Error(`${file}: "${p}" is outside the project`);
41
+ return rel.split(/[\\/]/).join("/");
42
+ }
43
+ /**
44
+ * Finds the project folder from a start folder: the nearest folder at or above it holding .turingcode/ (where the
45
+ * VS Code extension and the debug daemon keep their files; not the home folder's) or a .ioc or .mxproject file, else start itself.
46
+ * @param start folder to start from, default the working directory
47
+ * @returns the project root folder and name (its folder name)
48
+ */
49
+ export async function findProject(start = process.cwd()) {
50
+ const ancestors = [];
51
+ for (let dir = resolve(start);; dir = dirname(dir)) {
52
+ ancestors.push(dir);
53
+ if (dirname(dir) === dir)
54
+ break;
55
+ }
56
+ const holds = async (dir, test) => (await readdir(dir, { withFileTypes: true }).catch(() => [])).some((e) => test(e.name, e.isDirectory()));
57
+ /** the home folder's .turingcode/ holds user settings, not a project, so it never marks one */
58
+ const home = resolve(homedir());
59
+ for (const dir of ancestors) {
60
+ const marked = await holds(dir, (n, isDir) => isDir ? n === ".turingcode" && dir !== home && dirname(dir) !== dir : /^(\.mxproject|.+\.ioc)$/.test(n));
61
+ if (marked)
62
+ return { root: dir, name: basename(dir) };
63
+ }
64
+ return { root: resolve(start), name: basename(resolve(start)) };
65
+ }
66
+ /**
67
+ * Finds the STM32 project inside the project folder: the folder itself or a subfolder holding a .ioc or .mxproject file.
68
+ * @param start folder to start from, see findProject
69
+ * @returns the STM32 project root and name (its folder name)
70
+ * @throws when no STM32 project or more than one is found
71
+ */
72
+ export async function findStm32Project(start) {
73
+ return findStm32ProjectIn((await findProject(start)).root);
74
+ }
75
+ /**
76
+ * Finds the STM32 project in a given folder without looking above it: the folder itself or a subfolder holding a .ioc or .mxproject file.
77
+ * @param root folder to search, e.g. the folder open in VS Code
78
+ * @returns the STM32 project root and name (its folder name)
79
+ * @throws when no STM32 project or more than one is found
80
+ */
81
+ export async function findStm32ProjectIn(root) {
82
+ const roots = await findIocFolders(root);
83
+ if (!roots.length)
84
+ throw new Error(`No STM32 project (folder with a .ioc or .mxproject file) found in ${root}`);
85
+ if (roots.length > 1)
86
+ throw new Error(`Several STM32 projects found in ${root}:\n${roots.join("\n")}`);
87
+ return { root: roots[0], name: basename(roots[0]) };
88
+ }
89
+ /**
90
+ * Folders never searched for a .ioc: generated or vendored trees that can hold many files, and dot folders
91
+ * (.git, and .turingcode whose regen baseline holds a copy of the .ioc).
92
+ */
93
+ const SKIPPED_DIRS = /^(Drivers|build|node_modules|\..*)$/;
94
+ /**
95
+ * Lists dir and every folder below it that holds a .ioc or .mxproject file, without walking SKIPPED_DIRS.
96
+ * @param dir folder to search
97
+ * @returns the matching folders, absolute
98
+ */
99
+ export async function findIocFolders(dir) {
100
+ const ents = await readdir(dir, { withFileTypes: true }).catch(() => []);
101
+ const here = ents.some((e) => e.isFile() && /^(\.mxproject|.+\.ioc)$/.test(e.name)) ? [dir] : [];
102
+ const below = await Promise.all(ents.filter((e) => e.isDirectory() && !SKIPPED_DIRS.test(e.name)).map((e) => findIocFolders(join(dir, e.name))));
103
+ return [...here, ...below.flat()];
104
+ }
@@ -0,0 +1,31 @@
1
+ export interface SvdField {
2
+ name: string;
3
+ bitOffset: number;
4
+ bitWidth: number;
5
+ }
6
+ export interface SvdRegister {
7
+ name: string;
8
+ addressOffsetInt: number;
9
+ safeToRead: boolean;
10
+ fields: SvdField[];
11
+ }
12
+ export interface SvdPeripheral {
13
+ svd: string;
14
+ name: string;
15
+ baseAddressInt: number;
16
+ registers: SvdRegister[];
17
+ }
18
+ /**
19
+ * A peripheral's SVD data: from the project's cache (.turingcode/svd/<chip>/<NAME>.json) when present,
20
+ * else from the server's mcu_register_lookup, then cached so later reads work offline.
21
+ * @param root project root
22
+ * @param chip CubeMX MCU name
23
+ * @param name peripheral instance, e.g. GPIOA
24
+ * @param call server tool caller
25
+ * @returns the peripheral and whether it came from the cache
26
+ * @throws when the server reply is not the peripheral's JSON (nothing is cached then)
27
+ */
28
+ export declare function loadPeripheral(root: string, chip: string, name: string, call: (tool: string, args: object) => Promise<string>): Promise<{
29
+ peripheral: SvdPeripheral;
30
+ cached: boolean;
31
+ }>;
@@ -0,0 +1,30 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { replyBody } from "../../core/mcp.js";
4
+ /**
5
+ * A peripheral's SVD data: from the project's cache (.turingcode/svd/<chip>/<NAME>.json) when present,
6
+ * else from the server's mcu_register_lookup, then cached so later reads work offline.
7
+ * @param root project root
8
+ * @param chip CubeMX MCU name
9
+ * @param name peripheral instance, e.g. GPIOA
10
+ * @param call server tool caller
11
+ * @returns the peripheral and whether it came from the cache
12
+ * @throws when the server reply is not the peripheral's JSON (nothing is cached then)
13
+ */
14
+ export async function loadPeripheral(root, chip, name, call) {
15
+ const file = join(root, '.turingcode', 'svd', chip, `${name.toUpperCase()}.json`);
16
+ const saved = await readFile(file, 'utf8').catch(() => undefined);
17
+ if (saved !== undefined)
18
+ return { peripheral: JSON.parse(saved), cached: true };
19
+ const text = replyBody(await call('mcu_register_lookup', { part_name: chip, peripheral: name }));
20
+ let peripheral;
21
+ try {
22
+ peripheral = JSON.parse(text);
23
+ }
24
+ catch {
25
+ throw new Error(text);
26
+ }
27
+ await mkdir(dirname(file), { recursive: true });
28
+ await writeFile(file, JSON.stringify(peripheral));
29
+ return { peripheral, cached: false };
30
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Cuts text to at most max characters, ending it with "..." when it was longer.
3
+ * @param text the text to shorten
4
+ * @param max the maximum length of the result, including the "..."
5
+ * @returns text unchanged when it fits, otherwise its first max - 3 characters plus "..."
6
+ */
7
+ export declare function truncate(text: string, max: number): string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Cuts text to at most max characters, ending it with "..." when it was longer.
3
+ * @param text the text to shorten
4
+ * @param max the maximum length of the result, including the "..."
5
+ * @returns text unchanged when it fits, otherwise its first max - 3 characters plus "..."
6
+ */
7
+ export function truncate(text, max) {
8
+ return text.length <= max ? text : `${text.slice(0, max - 3)}...`;
9
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Restarts every connected ST-LINK USB device, waking one stuck in USB sleep.
3
+ * @returns the instance IDs of the restarted devices
4
+ */
5
+ export declare function resetStlinkUsb(): Promise<string[]>;
@@ -0,0 +1,23 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ const run = promisify(execFile);
4
+ /** ST-LINK hardware IDs: V2, V2-1, V3 (three USB configurations), V3SET. */
5
+ const STLINK_IDS = ['3748', '374B', '374E', '374F', '3753', '3754'].map((pid) => `USB\\VID_0483&PID_${pid}`);
6
+ /**
7
+ * Restarts every connected ST-LINK USB device, waking one stuck in USB sleep.
8
+ * @returns the instance IDs of the restarted devices
9
+ */
10
+ export async function resetStlinkUsb() {
11
+ if (process.platform !== 'win32')
12
+ throw new Error('USB reset is only supported on Windows (pnputil)');
13
+ const restarted = [];
14
+ for (const hwid of STLINK_IDS) {
15
+ /** pnputil exits non-zero when no device matches. */
16
+ const { stdout } = await run('pnputil', ['/enum-devices', '/connected', '/deviceid', hwid], { windowsHide: true }).catch(() => ({ stdout: '' }));
17
+ for (const [, id] of stdout.matchAll(/^Instance ID:\s+(.+)$/gm)) {
18
+ await run('pnputil', ['/restart-device', id.trim()], { windowsHide: true });
19
+ restarted.push(id.trim());
20
+ }
21
+ }
22
+ return restarted;
23
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * CubeMX keeps only the code between the USER CODE BEGIN and USER CODE END markers when it regenerates a file.
3
+ */
4
+ export interface UserSection {
5
+ name: string;
6
+ start: number; /** body is text.slice(start, end): the lines between the two markers */
7
+ end: number;
8
+ }
9
+ /**
10
+ * Scans a source file for CubeMX user code sections, collecting every marker mismatch instead of stopping at the first.
11
+ * @param text the file contents
12
+ * @returns the well-formed sections in file order and the mismatch errors
13
+ */
14
+ export declare function scanUserSections(text: string): {
15
+ sections: UserSection[];
16
+ errors: string[];
17
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * CubeMX keeps only the code between the USER CODE BEGIN and USER CODE END markers when it regenerates a file.
3
+ */
4
+ const MARKER = /\/\*\s*USER CODE (BEGIN|END)\s+(.+?)\s*\*\//g;
5
+ /**
6
+ * Scans a source file for CubeMX user code sections, collecting every marker mismatch instead of stopping at the first.
7
+ * @param text the file contents
8
+ * @returns the well-formed sections in file order and the mismatch errors
9
+ */
10
+ export function scanUserSections(text) {
11
+ const sections = [];
12
+ const errors = [];
13
+ let open;
14
+ const lineOf = (at) => text.slice(0, at).split('\n').length;
15
+ for (const m of text.matchAll(MARKER)) {
16
+ const [marker, kind, name] = m;
17
+ const at = m.index;
18
+ const line = lineOf(at);
19
+ if (kind === 'BEGIN') {
20
+ if (open)
21
+ errors.push(`line ${open.line}: USER CODE BEGIN ${open.name} has no matching END`);
22
+ if (sections.some((s) => s.name === name))
23
+ errors.push(`line ${line}: USER CODE section "${name}" appears twice`);
24
+ /** Body starts on the line after the marker when nothing else follows it on its line. */
25
+ const after = at + marker.length;
26
+ const eol = /^[ \t]*\r?\n/.exec(text.slice(after));
27
+ open = { name, start: after + (eol ? eol[0].length : 0), line };
28
+ }
29
+ else if (open?.name !== name) {
30
+ errors.push(`line ${line}: USER CODE END ${name} has no matching BEGIN`);
31
+ }
32
+ else {
33
+ /** Body ends before the END marker's indentation when the marker starts its line. */
34
+ const lineStart = text.lastIndexOf('\n', at - 1) + 1;
35
+ const end = lineStart >= open.start && /^[ \t]*$/.test(text.slice(lineStart, at))
36
+ ? lineStart
37
+ : at;
38
+ sections.push({ name, start: open.start, end });
39
+ open = undefined;
40
+ }
41
+ }
42
+ if (open)
43
+ errors.push(`line ${open.line}: USER CODE BEGIN ${open.name} has no matching END`);
44
+ return { sections, errors };
45
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Makes claimProbe also take a lock file, so other processes see the probe as busy.
3
+ * @param file lock file path, e.g. <project>/.turingcode/probe.lock; undefined turns the lock file off
4
+ */
5
+ export declare function setProbeLockFile(file: string | undefined): void;
6
+ /**
7
+ * Takes the probe for a debug action or the debug session; fails if another run holds it.
8
+ * @param name name of the run, shown in the error when a later claim fails
9
+ */
10
+ export declare function claimProbe(name: string): void;
11
+ /**
12
+ * Releases the probe taken with claimProbe, and the lock file if this process holds it; removes the lock's
13
+ * folder when that leaves it empty.
14
+ */
15
+ export declare function releaseProbe(): void;