@typecad/framework-zephyr 1.0.0-alpha.10

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 (150) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -0
  3. package/dist/async/timer-polyfill.d.ts +10 -0
  4. package/dist/async/timer-polyfill.js +95 -0
  5. package/dist/chips/controllers.d.ts +21 -0
  6. package/dist/chips/controllers.js +66 -0
  7. package/dist/chips/esp32.d.ts +2 -0
  8. package/dist/chips/esp32.js +59 -0
  9. package/dist/chips/esp32s3.d.ts +2 -0
  10. package/dist/chips/esp32s3.js +54 -0
  11. package/dist/chips/index.d.ts +15 -0
  12. package/dist/chips/index.js +45 -0
  13. package/dist/chips/resolve.d.ts +9 -0
  14. package/dist/chips/resolve.js +121 -0
  15. package/dist/chips/types.d.ts +154 -0
  16. package/dist/chips/types.js +14 -0
  17. package/dist/chips/xiao-ble.d.ts +2 -0
  18. package/dist/chips/xiao-ble.js +61 -0
  19. package/dist/debug-codegen.d.ts +33 -0
  20. package/dist/debug-codegen.js +162 -0
  21. package/dist/display/gfx.d.ts +17 -0
  22. package/dist/display/gfx.js +171 -0
  23. package/dist/display/index.d.ts +20 -0
  24. package/dist/display/index.js +53 -0
  25. package/dist/display/profiles.d.ts +25 -0
  26. package/dist/display/profiles.js +41 -0
  27. package/dist/display/touch-adapter.d.ts +9 -0
  28. package/dist/display/touch-adapter.js +95 -0
  29. package/dist/display/ui-adapter.d.ts +21 -0
  30. package/dist/display/ui-adapter.js +534 -0
  31. package/dist/doctor.d.ts +6 -0
  32. package/dist/doctor.js +48 -0
  33. package/dist/dt-config/kconfig.d.ts +27 -0
  34. package/dist/dt-config/kconfig.js +283 -0
  35. package/dist/dt-config/overlay.d.ts +35 -0
  36. package/dist/dt-config/overlay.js +246 -0
  37. package/dist/framework.manifest.d.ts +101 -0
  38. package/dist/framework.manifest.js +536 -0
  39. package/dist/index.d.ts +6 -0
  40. package/dist/index.js +17 -0
  41. package/dist/lowering/adc.d.ts +19 -0
  42. package/dist/lowering/adc.js +76 -0
  43. package/dist/lowering/ble.d.ts +20 -0
  44. package/dist/lowering/ble.js +419 -0
  45. package/dist/lowering/board.d.ts +9 -0
  46. package/dist/lowering/board.js +33 -0
  47. package/dist/lowering/gpio.d.ts +12 -0
  48. package/dist/lowering/gpio.js +123 -0
  49. package/dist/lowering/http.d.ts +23 -0
  50. package/dist/lowering/http.js +482 -0
  51. package/dist/lowering/i2c.d.ts +15 -0
  52. package/dist/lowering/i2c.js +114 -0
  53. package/dist/lowering/index.d.ts +29 -0
  54. package/dist/lowering/index.js +93 -0
  55. package/dist/lowering/interrupts.d.ts +21 -0
  56. package/dist/lowering/interrupts.js +91 -0
  57. package/dist/lowering/mqtt.d.ts +19 -0
  58. package/dist/lowering/mqtt.js +366 -0
  59. package/dist/lowering/power.d.ts +9 -0
  60. package/dist/lowering/power.js +64 -0
  61. package/dist/lowering/preferences.d.ts +23 -0
  62. package/dist/lowering/preferences.js +345 -0
  63. package/dist/lowering/pulse.d.ts +7 -0
  64. package/dist/lowering/pulse.js +82 -0
  65. package/dist/lowering/pwm.d.ts +15 -0
  66. package/dist/lowering/pwm.js +59 -0
  67. package/dist/lowering/random.d.ts +18 -0
  68. package/dist/lowering/random.js +129 -0
  69. package/dist/lowering/spi.d.ts +17 -0
  70. package/dist/lowering/spi.js +113 -0
  71. package/dist/lowering/timing.d.ts +9 -0
  72. package/dist/lowering/timing.js +63 -0
  73. package/dist/lowering/tone.d.ts +10 -0
  74. package/dist/lowering/tone.js +50 -0
  75. package/dist/lowering/uart.d.ts +15 -0
  76. package/dist/lowering/uart.js +102 -0
  77. package/dist/lowering/util.d.ts +4 -0
  78. package/dist/lowering/util.js +12 -0
  79. package/dist/lowering/wdt.d.ts +15 -0
  80. package/dist/lowering/wdt.js +80 -0
  81. package/dist/lowering/wifi.d.ts +21 -0
  82. package/dist/lowering/wifi.js +447 -0
  83. package/dist/lowering/worker-backing.d.ts +14 -0
  84. package/dist/lowering/worker-backing.js +79 -0
  85. package/dist/lowering/worker.d.ts +6 -0
  86. package/dist/lowering/worker.js +14 -0
  87. package/dist/strategy.d.ts +168 -0
  88. package/dist/strategy.js +1094 -0
  89. package/dist/toolchain/compat.d.ts +38 -0
  90. package/dist/toolchain/compat.js +133 -0
  91. package/dist/toolchain/debug-config.d.ts +82 -0
  92. package/dist/toolchain/debug-config.js +359 -0
  93. package/dist/toolchain/index.d.ts +73 -0
  94. package/dist/toolchain/index.js +444 -0
  95. package/dist/toolchain/scaffold.d.ts +15 -0
  96. package/dist/toolchain/scaffold.js +196 -0
  97. package/dist/toolchain/west-discover.d.ts +40 -0
  98. package/dist/toolchain/west-discover.js +203 -0
  99. package/dist/toolchain/west-spawn.d.ts +39 -0
  100. package/dist/toolchain/west-spawn.js +117 -0
  101. package/package.json +82 -0
  102. package/src/async/timer-polyfill.ts +107 -0
  103. package/src/chips/controllers.ts +74 -0
  104. package/src/chips/esp32.ts +62 -0
  105. package/src/chips/esp32s3.ts +57 -0
  106. package/src/chips/index.ts +54 -0
  107. package/src/chips/resolve.ts +146 -0
  108. package/src/chips/types.ts +163 -0
  109. package/src/chips/xiao-ble.ts +64 -0
  110. package/src/debug-codegen.ts +207 -0
  111. package/src/display/gfx.ts +190 -0
  112. package/src/display/index.ts +70 -0
  113. package/src/display/profiles.ts +63 -0
  114. package/src/display/touch-adapter.ts +100 -0
  115. package/src/display/ui-adapter.ts +558 -0
  116. package/src/doctor.ts +56 -0
  117. package/src/dt-config/kconfig.ts +308 -0
  118. package/src/dt-config/overlay.ts +293 -0
  119. package/src/framework.manifest.ts +558 -0
  120. package/src/index.ts +29 -0
  121. package/src/lowering/adc.ts +102 -0
  122. package/src/lowering/ble.ts +426 -0
  123. package/src/lowering/board.ts +38 -0
  124. package/src/lowering/gpio.ts +148 -0
  125. package/src/lowering/http.ts +488 -0
  126. package/src/lowering/i2c.ts +126 -0
  127. package/src/lowering/index.ts +86 -0
  128. package/src/lowering/interrupts.ts +114 -0
  129. package/src/lowering/mqtt.ts +371 -0
  130. package/src/lowering/power.ts +70 -0
  131. package/src/lowering/preferences.ts +354 -0
  132. package/src/lowering/pulse.ts +93 -0
  133. package/src/lowering/pwm.ts +74 -0
  134. package/src/lowering/random.ts +135 -0
  135. package/src/lowering/spi.ts +124 -0
  136. package/src/lowering/timing.ts +72 -0
  137. package/src/lowering/tone.ts +60 -0
  138. package/src/lowering/uart.ts +111 -0
  139. package/src/lowering/util.ts +12 -0
  140. package/src/lowering/wdt.ts +84 -0
  141. package/src/lowering/wifi.ts +452 -0
  142. package/src/lowering/worker-backing.ts +94 -0
  143. package/src/lowering/worker.ts +17 -0
  144. package/src/strategy.ts +1265 -0
  145. package/src/toolchain/compat.ts +145 -0
  146. package/src/toolchain/debug-config.ts +399 -0
  147. package/src/toolchain/index.ts +482 -0
  148. package/src/toolchain/scaffold.ts +196 -0
  149. package/src/toolchain/west-discover.ts +233 -0
  150. package/src/toolchain/west-spawn.ts +141 -0
@@ -0,0 +1,145 @@
1
+ // Zephyr version compatibility + board-target normalization.
2
+ //
3
+ // Two mechanisms absorb Zephyr version churn:
4
+ // 1. checkZephyrCompat() — compare the installed Zephyr version against the
5
+ // declared range (manifest.compat.zephyr) so an incompatible Zephyr fails
6
+ // fast with a clear message instead of a cryptic west/CMake board error.
7
+ // 2. resolveBoardTarget() — normalize the board target for the installed
8
+ // Zephyr version. Zephyr 4.3+ rejects bare multi-core board names
9
+ // (esp32s3_devkitc) and requires a qualified target
10
+ // (esp32s3_devkitc/esp32s3/procpu). This rewrites stale configs at build
11
+ // time so users don't have to regenerate them after a Zephyr upgrade.
12
+ //
13
+ // This module is intentionally pure (no chalk/ui/console) so it unit-tests
14
+ // cleanly; the doctor and the toolchain decide how to present results.
15
+
16
+ import { readFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import manifest from '../framework.manifest.js';
19
+
20
+ // ── minimal semver ──────────────────────────────────────────────────────────
21
+
22
+ /** Parse "4.3.99" / "v4.3" / "4.3.99-rc1" → [4, 3, 99]. Undefined if unparseable. */
23
+ export function parseVersion(v: string | undefined): [number, number, number] | undefined {
24
+ if (!v) return undefined;
25
+ const m = v.replace(/^v/i, '').match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
26
+ if (!m) return undefined;
27
+ return [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)];
28
+ }
29
+
30
+ /** Compare two version strings: -1 if a<b, 0 if equal, 1 if a>b. */
31
+ export function compareVersion(a: string, b: string): number {
32
+ const pa = parseVersion(a) ?? [0, 0, 0];
33
+ const pb = parseVersion(b) ?? [0, 0, 0];
34
+ for (let i = 0; i < 3; i++) {
35
+ if (pa[i]! < pb[i]!) return -1;
36
+ if (pa[i]! > pb[i]!) return 1;
37
+ }
38
+ return 0;
39
+ }
40
+
41
+ /**
42
+ * Evaluate a simple range of space-separated comparators against a version.
43
+ * Supported operators: >= <= > < =. Each comparator glues the operator to its
44
+ * version (">=4.3", "<5.0"); spaces between comparators are AND.
45
+ * satisfiesRange("4.3.99", ">=4.3 <5.0") === true
46
+ */
47
+ export function satisfiesRange(version: string, range: string): boolean {
48
+ return range
49
+ .trim()
50
+ .split(/\s+/)
51
+ .every((clause) => {
52
+ const m = clause.replace(/\s+/g, '').match(/^(>=|<=|>|<|=)(.+)$/);
53
+ if (!m) return true; // ignore anything that isn't a comparator
54
+ const cmp = compareVersion(version, m[2]!);
55
+ switch (m[1]) {
56
+ case '>=': return cmp >= 0;
57
+ case '<=': return cmp <= 0;
58
+ case '>': return cmp > 0;
59
+ case '<': return cmp < 0;
60
+ case '=': return cmp === 0;
61
+ default: return true;
62
+ }
63
+ });
64
+ }
65
+
66
+ // ── Zephyr version detection ────────────────────────────────────────────────
67
+
68
+ /**
69
+ * Detect the installed Zephyr version from ZEPHYR_BASE/VERSION. Returns
70
+ * undefined when ZEPHYR_BASE is unset or VERSION can't be read/parsed. Handles
71
+ * the CMake-style file (VERSION_MAJOR = 4 / VERSION_MINOR = 3 / PATCHLEVEL = 99)
72
+ * and a bare "4.3.99".
73
+ */
74
+ export function detectZephyrVersion(): string | undefined {
75
+ const base = process.env.ZEPHYR_BASE;
76
+ if (!base) return undefined;
77
+ let content: string;
78
+ try {
79
+ content = readFileSync(join(base, 'VERSION'), 'utf-8');
80
+ } catch {
81
+ return undefined;
82
+ }
83
+ const field = (key: string): string | undefined => {
84
+ const m = content.match(new RegExp(`^\\s*${key}\\s*=\\s*(\\d+)`, 'm'));
85
+ return m ? m[1] : undefined;
86
+ };
87
+ const major = field('VERSION_MAJOR');
88
+ if (major !== undefined) {
89
+ return `${major}.${field('VERSION_MINOR') ?? 0}.${field('PATCHLEVEL') ?? 0}`;
90
+ }
91
+ const m = content.match(/(\d+\.\d+(?:\.\d+)?)/);
92
+ return m ? m[1] : undefined;
93
+ }
94
+
95
+ // ── compat check ────────────────────────────────────────────────────────────
96
+
97
+ export type CompatStatus = 'ok' | 'undetectable' | 'out-of-range';
98
+
99
+ export interface CompatResult {
100
+ version: string | undefined;
101
+ /** Declared supported range (manifest.compat.zephyr), if any. */
102
+ range: string | undefined;
103
+ status: CompatStatus;
104
+ }
105
+
106
+ /**
107
+ * Compare the detected Zephyr version against the declared compat range. Pure:
108
+ * returns a status; the caller decides whether to throw/warn. 'ok' covers both
109
+ * "in range" and "no range declared".
110
+ */
111
+ export function checkZephyrCompat(version: string | undefined): CompatResult {
112
+ const range = manifest.compat?.zephyr;
113
+ if (!range) return { version, range, status: 'ok' };
114
+ if (version === undefined) return { version, range, status: 'undetectable' };
115
+ return { version, range, status: satisfiesRange(version, range) ? 'ok' : 'out-of-range' };
116
+ }
117
+
118
+ // ── board-target normalization ──────────────────────────────────────────────
119
+
120
+ /**
121
+ * For Zephyr >=4.3, multi-core ESP32 boards require a qualified board target
122
+ * (board/<soc>/<core>) — the bare id is rejected with "Board qualifiers … not
123
+ * found". Map each known multi-core board id to its procpu (main app core)
124
+ * qualified form. procpu is the core that runs application firmware; appcpu is
125
+ * the secondary core (selected explicitly only when offloading to it).
126
+ */
127
+ const QUALIFIED_TARGETS_GE_4_3: Record<string, string> = {
128
+ esp32_devkitc: 'esp32_devkitc/esp32/procpu',
129
+ esp32s3_devkitc: 'esp32s3_devkitc/esp32s3/procpu',
130
+ };
131
+
132
+ /**
133
+ * Normalize a board target for the installed Zephyr version. Rewrites a stale
134
+ * bare id (esp32s3_devkitc) to the qualified form on Zephyr >=4.3; idempotent
135
+ * if the target is already qualified. Older Zephyr, single-core boards
136
+ * (xiao_ble), and unknown boards pass through unchanged.
137
+ */
138
+ export function resolveBoardTarget(boardTarget: string, version: string | undefined): string {
139
+ const boardId = boardTarget.split('/')[0]!;
140
+ if (version !== undefined && satisfiesRange(version, '>=4.3')) {
141
+ const qualified = QUALIFIED_TARGETS_GE_4_3[boardId];
142
+ if (qualified) return qualified;
143
+ }
144
+ return boardTarget;
145
+ }
@@ -0,0 +1,399 @@
1
+ // ---------------------------------------------------------------------------
2
+ // debug-config.ts — VS Code / GDB debug artifact generation for `--debug`
3
+ //
4
+ // After a successful gdb-mode build, writes the artifacts that let the user
5
+ // press F5 in VS Code and attach GDB to the running Zephyr target.
6
+ //
7
+ // Uses the cortex-debug extension (NOT the ESP-IDF gdbtarget adapter) so the
8
+ // debug session is self-contained. cortex-debug starts OpenOCD as a child
9
+ // process via `servertype: "openocd"`; the preLaunch task handles only the
10
+ // build + flash step. After attach we issue `monitor reset init`, set a
11
+ // temporary hardware breakpoint at setup(), and continue — this ensures the
12
+ // breakpoint is deferred until the bootloader maps the app flash region.
13
+ //
14
+ // All generators are deterministic + idempotent so toggling --debug does not
15
+ // churn the tree.
16
+ // ---------------------------------------------------------------------------
17
+
18
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
19
+ import { join, resolve, dirname, relative } from 'node:path';
20
+
21
+ export interface DebugConfigOptions {
22
+ /** Absolute path to the Zephyr project root (contains CMakeLists.txt + src/). */
23
+ projectRoot: string;
24
+ /** Absolute path to the workspace root (the cuttlefish config dir — the folder VS Code has open). */
25
+ workspaceRoot: string;
26
+ /** The Zephyr app dir relative to the workspace root (e.g. 'src/out'). */
27
+ sketchRel: string;
28
+ /** The Zephyr board id (e.g. 'esp32s3_devkitc'). */
29
+ target: string;
30
+ /** Absolute path to the Zephyr build dir (<projectRoot>/build) — read for the SDK/GDB path. */
31
+ buildDir: string;
32
+ /** Absolute path to the emitted source map (*.thcppmap.json), if any. */
33
+ sourceMapPath?: string;
34
+ }
35
+
36
+ /**
37
+ * Resolve the GDB binary path for the target from the build cache. Zephyr
38
+ * records ZEPHYR_SDK_INSTALL_DIR in CMakeCache.txt at configure time, and the
39
+ * xtensa GDB lives at <sdk>/xtensa-espressif_esp32s3_zephyr-elf/bin/... (note
40
+ * the Zephyr-SDK naming, distinct from the ESP-IDF xtensa-esp32s3-elf-gdb).
41
+ *
42
+ * Returns the absolute gdb path on success, or undefined (the launch.json then
43
+ * omits gdbPath and relies on Cortex-Debug's default resolution).
44
+ */
45
+ export function resolveGdbPath(buildDir: string, target: string): string | undefined {
46
+ const cachePath = join(buildDir, 'CMakeCache.txt');
47
+ if (!existsSync(cachePath)) return undefined;
48
+ let sdk = '';
49
+ try {
50
+ const cache = readFileSync(cachePath, 'utf-8');
51
+ const m = cache.match(/^ZEPHYR_SDK_INSTALL_DIR:PATH=(.+)$/m);
52
+ if (m) sdk = m[1].trim();
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ if (!sdk) return undefined;
57
+ // The Zephyr SDK toolchain dir is target-specific. For esp32s3 it is
58
+ // xtensa-espressif_esp32s3_zephyr-elf (verified against zephyr-sdk-0.17.4).
59
+ const gdbName = 'xtensa-espressif_esp32s3_zephyr-elf-gdb.exe';
60
+ const gdbPath = join(sdk, 'xtensa-espressif_esp32s3_zephyr-elf', 'bin', gdbName);
61
+ return existsSync(gdbPath) ? gdbPath.replace(/\\/g, '/') : undefined;
62
+ }
63
+
64
+ /**
65
+ * Resolve the Espressif OpenOCD binary path. The esp32s3 needs the Espressif
66
+ * OpenOCD fork (openocd-esp32) — not the Zephyr SDK's openocd and not a
67
+ * generic/GDB-stub build — because only it carries the Xtensa + esp_usb_jtag
68
+ * support. It is NOT on PATH by default, so Cortex-Debug must be pointed at it
69
+ * explicitly or it fails with `spawn openocd.exe ENOENT`.
70
+ *
71
+ * Discovery order:
72
+ * 1. ESPRESSIF_TOOLCHAIN_PATH env (the var board.cmake reads) — if set, its
73
+ * openocd-esp32/bin/openocd.exe.
74
+ * 2. The standard ESP-IDF install layout: ~/.espressif/tools/openocd-esp32/
75
+ * <version>/openocd-esp32/bin/openocd.exe. Pick the newest version dir.
76
+ * Returns undefined if not found (the launch.json then omits openOCDPath and
77
+ * Cortex-Debug falls back to PATH / its openocdPath setting).
78
+ */
79
+ export function resolveOpenOcdPath(): string | undefined {
80
+ const candidates: string[] = [];
81
+ // 1. ESPRESSIF_TOOLCHAIN_PATH env
82
+ const envPath = process.env.ESPRESSIF_TOOLCHAIN_PATH;
83
+ if (envPath) {
84
+ candidates.push(join(envPath, 'openocd-esp32', 'bin', 'openocd.exe'));
85
+ }
86
+ // 2. ~/.espressif/tools/openocd-esp32/<version>/openocd-esp32/bin/openocd.exe
87
+ const home = process.env.USERPROFILE || process.env.HOME;
88
+ if (home) {
89
+ const base = join(home, '.espressif', 'tools', 'openocd-esp32');
90
+ let versions: string[] = [];
91
+ try {
92
+ versions = readdirSync(base).filter((v) =>
93
+ existsSync(join(base, v, 'openocd-esp32', 'bin', 'openocd.exe')),
94
+ );
95
+ } catch {
96
+ // dir absent
97
+ }
98
+ // newest version last — sort then reverse so the highest wins on match.
99
+ versions.sort().reverse();
100
+ for (const v of versions) {
101
+ candidates.push(join(base, v, 'openocd-esp32', 'bin', 'openocd.exe'));
102
+ }
103
+ }
104
+ for (const c of candidates) {
105
+ if (existsSync(c)) return resolve(c).replace(/\\/g, '/');
106
+ }
107
+ return undefined;
108
+ }
109
+
110
+ /**
111
+ * Resolve where to write the VS Code debug artifacts and how to express paths
112
+ * in them.
113
+ *
114
+ * VS Code reads `.vscode/` from the folder the user has OPENED — and for a
115
+ * cuttlefish project that is almost always the **cuttlefish project root**
116
+ * (the directory containing `cuttlefish.config.ts`), NOT the git repo root.
117
+ * The toolchain's `projectRoot` is the Zephyr *app* dir (e.g.
118
+ * `<projectRoot>/src/out`), which sits below the cuttlefish config dir. So we
119
+ * walk up from `projectRoot` to the nearest `cuttlefish.config.ts` and treat
120
+ * THAT as the workspace root. This makes F5 work when a user opens the project
121
+ * folder directly, and keeps launch.json paths relative to it.
122
+ *
123
+ * Returns { workspaceRoot, sketchRel } where workspaceRoot is the cuttlefish
124
+ * project root (the `.vscode/` target) and sketchRel is the Zephyr app dir
125
+ * (`projectRoot`) relative to it (e.g. 'src/out').
126
+ */
127
+ export function resolveDebugLocations(projectRoot: string): {
128
+ workspaceRoot: string;
129
+ sketchRel: string;
130
+ } {
131
+ // Walk up from the Zephyr app dir to find the cuttlefish project root (the
132
+ // nearest ancestor containing cuttlefish.config.ts). Fall back to projectRoot
133
+ // itself if none is found (single-dir project where the app sits at root).
134
+ let workspaceRoot = resolve(projectRoot);
135
+ let dir = resolve(projectRoot);
136
+ for (let i = 0; i < 20; i++) {
137
+ if (existsSync(join(dir, 'cuttlefish.config.ts'))) {
138
+ workspaceRoot = dir;
139
+ break;
140
+ }
141
+ const parent = dirname(dir);
142
+ if (parent === dir) break;
143
+ dir = parent;
144
+ }
145
+
146
+ const sketchRel = relative(workspaceRoot, resolve(projectRoot)).replace(/\\/g, '/');
147
+ return { workspaceRoot, sketchRel };
148
+ }
149
+
150
+ /** Read-merge-write a JSON file, adding/replacing a single config by a key. */
151
+ function mergeJsonArrayEntry<T extends Record<string, unknown>>(
152
+ filePath: string,
153
+ arrayKey: string,
154
+ matchKey: string,
155
+ entry: T,
156
+ ): void {
157
+ let doc: Record<string, unknown> = {};
158
+ if (existsSync(filePath)) {
159
+ try {
160
+ doc = JSON.parse(readFileSync(filePath, 'utf-8'));
161
+ } catch {
162
+ // malformed — start fresh
163
+ }
164
+ }
165
+ const arr = Array.isArray(doc[arrayKey]) ? (doc[arrayKey] as T[]) : [];
166
+ const idx = arr.findIndex((e) => e[matchKey] === entry[matchKey]);
167
+ if (idx >= 0) arr[idx] = entry;
168
+ else arr.push(entry);
169
+ doc[arrayKey] = arr;
170
+ mkdirSync(dirname(filePath), { recursive: true });
171
+ writeFileSync(filePath, JSON.stringify(doc, null, 2) + '\n', 'utf-8');
172
+ }
173
+
174
+ /**
175
+ * Generate the GDB Python frame-filter that rewrites cuttlefish's hoisted
176
+ * lambda frame names (`${prefix}_isr_N`) into readable `<lambda> @ file:line`
177
+ * in the call stack. Only emitted when the source map references `_isr_N`
178
+ * symbols; otherwise returns null (launch.json omits the `source` initCommand).
179
+ *
180
+ * Ported verbatim from the deleted framework-esp32/toolchain/gdb-script.ts —
181
+ * the filter is cuttlefish-internal (lambda hoisting is framework-agnostic).
182
+ */
183
+ export function generateGdbScript(sourceMapPath?: string): string | null {
184
+ if (!sourceMapPath || !existsSync(sourceMapPath)) return null;
185
+ let mapText = '';
186
+ try {
187
+ mapText = readFileSync(sourceMapPath, 'utf-8');
188
+ } catch {
189
+ return null;
190
+ }
191
+ // Only emit when the emitted code contains hoisted-lambda symbols.
192
+ if (!/_isr_\d+/.test(mapText)) return null;
193
+
194
+ // A GDB Python frame-filter. Registered via the launch.json initCommand
195
+ // `source <path>` so GDB auto-loads it on attach.
196
+ return [
197
+ '# Auto-generated by @typecad/framework-zephyr. GDB frame-filter that',
198
+ '# rewrites cuttlefish hoisted-lambda frame names (*_isr_N) into readable',
199
+ '# <lambda> form so the VS Code call stack is legible.',
200
+ 'import gdb',
201
+ 'import re',
202
+ '',
203
+ 'class CuttlefishLambdaFilter:',
204
+ ' def __init__(self):',
205
+ ' self.name = "cuttlefish_lambda"',
206
+ ' self.priority = 100',
207
+ ' self.enabled = True',
208
+ '',
209
+ ' def filter(self, frame_iter):',
210
+ ' isr_re = re.compile(r"(.*)_isr_(\\d+)")',
211
+ ' return (CuttlefishFrame(f) for f in frame_iter)',
212
+ '',
213
+ 'class CuttlefishFrame:',
214
+ ' def __init__(self, frame):',
215
+ ' self.frame = frame',
216
+ ' def __getattr__(self, name):',
217
+ ' val = getattr(self.frame, name)',
218
+ ' if name == "function":',
219
+ ' m = isr_re.match(val)',
220
+ ' if m: return "<lambda>"',
221
+ ' return val',
222
+ '',
223
+ 'gdb.frame_filters[CuttlefishLambdaFilter().name] = CuttlefishLambdaFilter()',
224
+ '',
225
+ ].join('\n');
226
+ }
227
+
228
+ /**
229
+ * Build the cortex-debug launch.json config for an ESP32-S3 (built-in USB-JTAG).
230
+ * `openOcdCfgRel` is the workspace-relative path to the generated
231
+ * .cuttlefish/openocd.cfg, passed to cortex-debug's configFiles.
232
+ */
233
+ function buildLaunchConfig(
234
+ o: DebugConfigOptions,
235
+ gdbScriptRel: string | undefined,
236
+ openOcdCfgRel: string,
237
+ ): Record<string, unknown> {
238
+ // The ELF is at <projectRoot>/build/zephyr/zephyr.elf (Zephyr's standard
239
+ // build output). cortex-debug uses `executable` (not `program`).
240
+ const executable = `\${workspaceFolder}/${o.sketchRel}/build/zephyr/zephyr.elf`;
241
+
242
+ // OpenOCD cfg relative to the workspace root so cortex-debug can pass it
243
+ // via the -f flag. Must be a list; cortex-debug prepends -f per entry.
244
+ const configFiles = [`\${workspaceFolder}/${openOcdCfgRel}`];
245
+
246
+ // GDB path resolved from the Zephyr SDK build cache (CMakeCache.txt).
247
+ const gdbPath = resolveGdbPath(o.buildDir, o.target);
248
+
249
+ // OpenOCD binary path — the Espressif fork (openocd-esp32) is required for
250
+ // the esp_usb_jtag adapter. cortex-debug's `serverpath` tells it where to
251
+ // find the binary (not on PATH by default).
252
+ const openocdPath = resolveOpenOcdPath();
253
+
254
+ // Post-attach commands executed after GDB connects to the OpenOCD gdbserver.
255
+ // set mem inaccessible-by-default off — suppresses "Cannot access memory"
256
+ // errors caused by overlapping Xtensa memory regions (flash-mapped
257
+ // 0x4200xxxx isn't accessible until the bootloader runs).
258
+ // mem 0x42000000 0x44000000 ro cache — tells GDB the app flash region IS
259
+ // read-only so -break-insert uses hw breakpoints, not sw breakpoints
260
+ // (which would fail with "Cannot access memory at 0x4200xxxx").
261
+ // monitor reset init — reset target + halt (bootloader maps flash)
262
+ // thb setup — temporary HW breakpoint at setup()
263
+ // c — continue; bootloader maps flash, breaks at setup()
264
+ //
265
+ // Paths use forward slashes — ${workspaceFolder} on Windows produces
266
+ // backslashes that GDB interprets as escape sequences (\t → tab, etc.).
267
+ const ws = o.workspaceRoot.replace(/\\/g, '/');
268
+ const postAttachCommands = [
269
+ `set directories ${ws}`,
270
+ 'set remote hardware-watchpoint-limit 2',
271
+ 'set remote hardware-breakpoint-limit 2',
272
+ 'set mem inaccessible-by-default off',
273
+ 'mem 0x42000000 0x44000000 ro cache',
274
+ 'monitor reset init',
275
+ 'thb setup',
276
+ 'c',
277
+ ];
278
+ if (gdbScriptRel) {
279
+ postAttachCommands.splice(1, 0, `source ${ws}/${gdbScriptRel}`);
280
+ }
281
+
282
+ const cfg: Record<string, unknown> = {
283
+ name: 'TypeCAD Debug (Zephyr, ESP32-S3)',
284
+ type: 'cortex-debug',
285
+ // Attach mode: no download (the ELF is already flashed). The server
286
+ // controller's attachCommands() just halts the target, then our
287
+ // postAttachCommands reset it, set a HW breakpoint at setup(), and
288
+ // continue. HW breakpoints use debug registers and work before the
289
+ // bootloader maps the app flash region.
290
+ request: 'attach',
291
+ cwd: '${workspaceFolder}',
292
+ executable,
293
+ servertype: 'openocd',
294
+ configFiles,
295
+ interface: 'jtag',
296
+ ...(gdbPath ? { gdbPath } : {}),
297
+ ...(openocdPath ? { serverpath: openocdPath } : {}),
298
+ postAttachCommands,
299
+ preLaunchTask: 'cuttlefish: build + flash (debug)',
300
+ };
301
+
302
+ // openOcdCfgRel is consumed by configFiles above. Referenced here only to
303
+ // keep the signature honest.
304
+ void openOcdCfgRel;
305
+
306
+ return cfg;
307
+ }
308
+
309
+ /**
310
+ * Build the tasks.json entry: rebuild + flash only. cortex-debug starts
311
+ * OpenOCD as a child process (servertype: "openocd"), so the preLaunch task
312
+ * just needs to build and upload — no isBackground / OpenOCD wrapping.
313
+ */
314
+ function buildTask(o: DebugConfigOptions): Record<string, unknown> {
315
+ return {
316
+ label: 'cuttlefish: build + flash (debug)',
317
+ type: 'shell',
318
+ command: 'npx cuttlefish build --compile --upload --debug',
319
+ options: { cwd: `\${workspaceFolder}/${o.sketchRel}` },
320
+ group: { kind: 'build', isDefault: false },
321
+ problemMatcher: [],
322
+ };
323
+ }
324
+
325
+ /**
326
+ * The adapter speed the S3's built-in USB-Serial-JTAG runs stably at.
327
+ *
328
+ * The interface cfg (esp_usb_jtag.cfg) defaults to 40000 (40 MHz), the chip
329
+ * max. The USB-Serial-JTAG peripheral is a software bitq adapter that bit-bangs
330
+ * JTAG over USB bulk transfers; at 40 MHz it can't keep up, drops transfers
331
+ * (LIBUSB_ERROR_IO / "missing data from bitq interface"), and the reset/halt
332
+ * sequence silently fails — leaving the target running with no breakpoint set
333
+ * (the "debugger starts but never stops / buttons don't work" symptom).
334
+ *
335
+ * 4000 (4 MHz) is the empirically-stable speed for this peripheral.
336
+ */
337
+ const OPENOCD_ADAPTER_SPEED = 4000;
338
+
339
+ /**
340
+ * Build the OpenOCD cfg content. Sources the board's own openocd.cfg (which
341
+ * sets ESP_RTOS Zephyr + ESP_ONLYCPU + the esp_usb_jtag driver + the esp32s3
342
+ * target) then overrides the adapter speed AFTER the driver loads — the order
343
+ * that a bare `-c "adapter speed N"` cannot guarantee (OpenOCD applies -c args
344
+ * in command-line order relative to -f, and Cortex-Debug injects its own
345
+ * helper/RTOS tcl, so the override can land before the driver exists or be
346
+ * re-defaulted). Putting it in the cfg, after the source, is deterministic.
347
+ */
348
+ function buildOpenOcdCfg(): string {
349
+ return [
350
+ '# Auto-generated by @typecad/framework-zephyr. Do not edit — regenerate',
351
+ '# with `cuttlefish build --debug`. Sources the board cfg (which loads the',
352
+ '# esp_usb_jtag adapter driver + esp32s3 target + ESP_RTOS Zephyr) then',
353
+ '# overrides the adapter speed to a USB-JTAG-stable value AFTER the driver',
354
+ '# is loaded. See debug-config.ts for the rationale.',
355
+ 'source [find board/esp32s3-builtin.cfg]',
356
+ `adapter speed ${OPENOCD_ADAPTER_SPEED}`,
357
+ '',
358
+ ].join('\n');
359
+ }
360
+
361
+ /**
362
+ * Write all gdb-mode debug artifacts for the given target. Called from the
363
+ * toolchain compile() after a successful build when debugMode === 'gdb'.
364
+ *
365
+ * Writes (all idempotent):
366
+ * <workspaceRoot>/.vscode/launch.json (cortex-debug config)
367
+ * <workspaceRoot>/.vscode/tasks.json (build + flash preLaunch task)
368
+ * <projectRoot>/.cuttlefish/openocd.cfg (OpenOCD cfg, adapter speed override)
369
+ * <projectRoot>/.cuttlefish/.cuttlefish-gdb.py (lambda frame filter, conditional)
370
+ */
371
+ export function writeDebugConfig(o: DebugConfigOptions): void {
372
+ const vscodeDir = join(o.workspaceRoot, '.vscode');
373
+ const cuttlefishDir = join(o.projectRoot, '.cuttlefish');
374
+ mkdirSync(cuttlefishDir, { recursive: true });
375
+
376
+ // openocd.cfg — written first so its relative path can be wired into the
377
+ // cortex-debug configFiles. cortex-debug starts OpenOCD as a child process
378
+ // and passes this file via -f.
379
+ const openOcdCfgPath = join(cuttlefishDir, 'openocd.cfg');
380
+ writeFileSync(openOcdCfgPath, buildOpenOcdCfg(), 'utf-8');
381
+ const openOcdCfgRel = `${o.sketchRel}/.cuttlefish/openocd.cfg`;
382
+
383
+ // launch.json — merge the cortex-debug config by name.
384
+ const gdbScript = generateGdbScript(o.sourceMapPath);
385
+ let gdbScriptRel: string | undefined;
386
+ if (gdbScript) {
387
+ const scriptPath = join(cuttlefishDir, '.cuttlefish-gdb.py');
388
+ writeFileSync(scriptPath, gdbScript, 'utf-8');
389
+ gdbScriptRel = `${o.sketchRel}/.cuttlefish/.cuttlefish-gdb.py`;
390
+ }
391
+
392
+ const launchConfig = buildLaunchConfig(o, gdbScriptRel, openOcdCfgRel);
393
+ mergeJsonArrayEntry(join(vscodeDir, 'launch.json'), 'configurations', 'name', launchConfig);
394
+
395
+ // tasks.json — merge the build+flash task by label. OpenOCD is managed by
396
+ // cortex-debug so the task is a simple synchronous build step.
397
+ const task = buildTask(o);
398
+ mergeJsonArrayEntry(join(vscodeDir, 'tasks.json'), 'tasks', 'label', task);
399
+ }