@typecad/cuttlefish 0.1.0-alpha.2 → 1.0.0-alpha.11

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 (224) hide show
  1. package/README.md +10 -10
  2. package/dist/api/board-types.d.ts +1 -1
  3. package/dist/api/config.d.ts +38 -2
  4. package/dist/api/index.d.ts +1 -1
  5. package/dist/api/schema/types.d.ts +15 -0
  6. package/dist/api/shared/async-runtime-static.d.ts +12 -1
  7. package/dist/api/shared/async-runtime-static.js +69 -24
  8. package/dist/api/shared/async-symbol-detector.d.ts +11 -0
  9. package/dist/api/shared/async-symbol-detector.js +140 -0
  10. package/dist/api/shared/async-types.d.ts +24 -0
  11. package/dist/api/shared/coop-scheduler.d.ts +60 -0
  12. package/dist/api/shared/coop-scheduler.js +149 -0
  13. package/dist/api/shared/display-adapter.d.ts +4 -3
  14. package/dist/api/shared/display-adapter.js +15 -118
  15. package/dist/api/shared/display-adapters/sdl.js +38 -31
  16. package/dist/api/shared/display-profile.d.ts +47 -25
  17. package/dist/api/shared/display-profile.js +31 -164
  18. package/dist/api/shared/framework-manifest-registry.d.ts +9 -0
  19. package/dist/api/shared/framework-manifest-registry.js +27 -0
  20. package/dist/api/shared/framework-manifest.d.ts +595 -0
  21. package/dist/api/shared/framework-manifest.js +193 -0
  22. package/dist/api/shared/glcdfont.d.ts +12 -0
  23. package/dist/api/shared/glcdfont.js +124 -0
  24. package/dist/api/shared/graphics-strategy.d.ts +37 -0
  25. package/dist/api/shared/hal-op-ir.d.ts +764 -1
  26. package/dist/api/shared/hal-op-ir.js +129 -1
  27. package/dist/api/shared/index.d.ts +22 -2
  28. package/dist/api/shared/index.js +26 -1
  29. package/dist/api/shared/ir-core.d.ts +4 -0
  30. package/dist/api/shared/ir-declarations.d.ts +6 -0
  31. package/dist/api/shared/native-display-op-resolver.d.ts +10 -0
  32. package/dist/api/shared/native-display-op-resolver.js +64 -0
  33. package/dist/api/shared/platform-strategy.d.ts +119 -2
  34. package/dist/api/shared/polyfill-helper-registry.js +18 -1
  35. package/dist/api/shared/promise-runtime.d.ts +1 -1
  36. package/dist/api/shared/promise-runtime.js +95 -13
  37. package/dist/api/shared/spdx-licenses.d.ts +139 -0
  38. package/dist/api/shared/spdx-licenses.js +385 -0
  39. package/dist/api/shared/toolchain-types.d.ts +17 -0
  40. package/dist/api/shared/types.d.ts +8 -0
  41. package/dist/api/shared/validate-framework-manifest.d.ts +28 -0
  42. package/dist/api/shared/validate-framework-manifest.js +494 -0
  43. package/dist/api/shared/worker-runtime-polyfill.d.ts +22 -0
  44. package/dist/api/shared/worker-runtime-polyfill.js +34 -0
  45. package/dist/api/shared/worker-runtime.d.ts +69 -0
  46. package/dist/api/shared/worker-runtime.js +163 -0
  47. package/dist/cli-utils.d.ts +1 -0
  48. package/dist/cli-utils.js +3 -1
  49. package/dist/cli.js +249 -32
  50. package/dist/config-loader.d.ts +7 -2
  51. package/dist/config-loader.js +23 -3
  52. package/dist/config-schema.d.ts +112 -70
  53. package/dist/config-schema.js +14 -0
  54. package/dist/contract/board-generator.d.ts +17 -0
  55. package/dist/contract/board-generator.js +57 -0
  56. package/dist/contract/contract-parser.d.ts +217 -0
  57. package/dist/contract/contract-parser.js +224 -0
  58. package/dist/contract/index.d.ts +22 -0
  59. package/dist/contract/index.js +68 -0
  60. package/dist/create/board-codegen.js +4 -4
  61. package/dist/create/board-generators.js +4 -5
  62. package/dist/create/board-spec.d.ts +72 -75
  63. package/dist/create/board-spec.js +0 -1
  64. package/dist/create/framework-catalog.d.ts +64 -0
  65. package/dist/create/framework-catalog.js +136 -0
  66. package/dist/create/index.d.ts +5 -1
  67. package/dist/create/index.js +3 -1
  68. package/dist/create/init-scaffold.d.ts +12 -3
  69. package/dist/create/init-scaffold.js +49 -14
  70. package/dist/create/init-templates.d.ts +4 -0
  71. package/dist/create/init-templates.js +271 -17
  72. package/dist/create/init-wizard.js +41 -27
  73. package/dist/create/install-deps.d.ts +32 -0
  74. package/dist/create/install-deps.js +46 -0
  75. package/dist/debug/preprocessor.js +178 -39
  76. package/dist/debug/types.d.ts +23 -0
  77. package/dist/diagnostics/mermaid-builder.d.ts +1 -1
  78. package/dist/diagnostics/mermaid-builder.js +34 -24
  79. package/dist/emit/compliance/arxml-writer.d.ts +11 -0
  80. package/dist/emit/compliance/arxml-writer.js +34 -0
  81. package/dist/emit/compliance/compliance-context.d.ts +57 -0
  82. package/dist/emit/compliance/compliance-context.js +113 -0
  83. package/dist/emit/compliance/deviation-ledger.d.ts +27 -0
  84. package/dist/emit/compliance/deviation-ledger.js +47 -0
  85. package/dist/emit/compliance/deviation-writer.d.ts +30 -0
  86. package/dist/emit/compliance/deviation-writer.js +37 -0
  87. package/dist/emit/compliance/index.d.ts +7 -0
  88. package/dist/emit/compliance/index.js +6 -0
  89. package/dist/emit/compliance/rule-engine.d.ts +13 -0
  90. package/dist/emit/compliance/rule-engine.js +101 -0
  91. package/dist/emit/compliance/rules.d.ts +16 -0
  92. package/dist/emit/compliance/rules.js +191 -0
  93. package/dist/emit/compliance/types.d.ts +59 -0
  94. package/dist/emit/compliance/types.js +8 -0
  95. package/dist/emit/cpp-emitter.js +4 -3
  96. package/dist/emit/emitters/class-emitter.js +6 -1
  97. package/dist/emit/emitters/emitter-context.d.ts +28 -1
  98. package/dist/emit/emitters/function-emitter-impl.js +153 -53
  99. package/dist/emit/emitters/line-appender.js +19 -0
  100. package/dist/emit/emitters/line-marker.d.ts +38 -0
  101. package/dist/emit/emitters/line-marker.js +39 -0
  102. package/dist/emit/emitters/output-finalizer.d.ts +6 -0
  103. package/dist/emit/emitters/output-finalizer.js +101 -12
  104. package/dist/emit/emitters/setup.d.ts +17 -0
  105. package/dist/emit/emitters/setup.js +372 -30
  106. package/dist/emit/emitters/top-level-prep.js +8 -0
  107. package/dist/emit/emitters/type-decl-emitter.js +28 -3
  108. package/dist/emit/emitters/ui-emitter.js +33 -9
  109. package/dist/emit/expression-renderer.d.ts +1 -1
  110. package/dist/emit/expression-renderer.js +91 -6
  111. package/dist/emit/route-hal-op.js +18 -5
  112. package/dist/emit/snprintf-helpers.js +15 -4
  113. package/dist/emit/statement-renderer.d.ts +10 -0
  114. package/dist/emit/statement-renderer.js +34 -5
  115. package/dist/emit/utils/async-state-machine.js +221 -125
  116. package/dist/emit/utils/hal-op-cpp-type.d.ts +6 -0
  117. package/dist/emit/utils/hal-op-cpp-type.js +40 -0
  118. package/dist/framework-package.js +2 -0
  119. package/dist/framework-registry.d.ts +17 -0
  120. package/dist/install/framework-catalog.d.ts +53 -0
  121. package/dist/install/framework-catalog.js +107 -0
  122. package/dist/install/handle-install.d.ts +35 -0
  123. package/dist/install/handle-install.js +177 -0
  124. package/dist/install/index.d.ts +4 -0
  125. package/dist/install/index.js +3 -0
  126. package/dist/ir/adc-range-validation.js +40 -26
  127. package/dist/ir/build-ir-state.d.ts +1 -0
  128. package/dist/ir/build-ir-state.js +14 -0
  129. package/dist/ir/build-ir.js +9 -5
  130. package/dist/ir/call-graph.js +16 -0
  131. package/dist/ir/expression-to-ir.js +207 -6
  132. package/dist/ir/feature-registry.js +7 -25
  133. package/dist/ir/function-builder.js +22 -0
  134. package/dist/ir/hal/hal-emitter.d.ts +5 -2
  135. package/dist/ir/hal/hal-emitter.js +50 -18
  136. package/dist/ir/hal/hal-parser.d.ts +6 -0
  137. package/dist/ir/hal/hal-parser.js +81 -0
  138. package/dist/ir/hal/hal-plugins.js +733 -1
  139. package/dist/ir/identifier-collector.js +35 -0
  140. package/dist/ir/interrupt-analysis.d.ts +5 -1
  141. package/dist/ir/interrupt-analysis.js +16 -19
  142. package/dist/ir/memory-budget-validation.js +1 -0
  143. package/dist/ir/network-validation.d.ts +4 -0
  144. package/dist/ir/network-validation.js +184 -0
  145. package/dist/ir/ownership-analysis.js +39 -1
  146. package/dist/ir/peripheral-ownership.js +5 -0
  147. package/dist/ir/peripheral-validation.d.ts +1 -1
  148. package/dist/ir/peripheral-validation.js +6 -3
  149. package/dist/ir/pin-alias-conflict.d.ts +1 -1
  150. package/dist/ir/pin-alias-conflict.js +2 -1
  151. package/dist/ir/pin-capability-validation.js +71 -32
  152. package/dist/ir/pin-mode-validation.d.ts +2 -2
  153. package/dist/ir/pin-mode-validation.js +54 -18
  154. package/dist/ir/pin-safety.d.ts +1 -1
  155. package/dist/ir/pin-safety.js +2 -1
  156. package/dist/ir/program-analysis.d.ts +81 -0
  157. package/dist/ir/program-analysis.js +429 -0
  158. package/dist/ir/pulldown-validation.d.ts +1 -1
  159. package/dist/ir/pulldown-validation.js +2 -1
  160. package/dist/ir/pwm-timer-sharing.d.ts +1 -1
  161. package/dist/ir/pwm-timer-sharing.js +2 -1
  162. package/dist/ir/render-expr.js +11 -0
  163. package/dist/ir/resource-analysis.js +2 -0
  164. package/dist/ir/timer0-pwm-timing-conflict.d.ts +1 -1
  165. package/dist/ir/timer0-pwm-timing-conflict.js +2 -1
  166. package/dist/ir/timing-validation.d.ts +6 -1
  167. package/dist/ir/timing-validation.js +61 -13
  168. package/dist/ir/transformers/call-statement.js +105 -0
  169. package/dist/ir/transformers/expressions.js +62 -0
  170. package/dist/ir/transformers/hal-call-resolver.js +21 -0
  171. package/dist/ir/transformers/hal-emit-helpers.js +1 -1
  172. package/dist/ir/transformers/namespace-methods.js +17 -12
  173. package/dist/ir/transformers/ui-reactive.js +2 -2
  174. package/dist/ir/transformers/variables.js +137 -19
  175. package/dist/ir/try-catch-validation.js +2 -0
  176. package/dist/ir/type-resolution.js +20 -2
  177. package/dist/ir/ui-element-auto-wire.js +7 -5
  178. package/dist/ir/unit-suspicion-validation.js +9 -7
  179. package/dist/ir/utils/map-statements.d.ts +4 -0
  180. package/dist/ir/utils/map-statements.js +79 -0
  181. package/dist/ir/validation-orchestrator.js +15 -8
  182. package/dist/ir/worker-analysis.d.ts +10 -0
  183. package/dist/ir/worker-analysis.js +261 -0
  184. package/dist/libdef/c-to-decl.d.ts +27 -0
  185. package/dist/libdef/c-to-decl.js +397 -0
  186. package/dist/libdef/component-decls.d.ts +2 -0
  187. package/dist/libdef/component-decls.js +6 -0
  188. package/dist/libdef/component-discovery.d.ts +43 -0
  189. package/dist/libdef/component-discovery.js +83 -0
  190. package/dist/libdef/cpp-to-decl.d.ts +9 -0
  191. package/dist/libdef/cpp-to-decl.js +72 -0
  192. package/dist/libdef/registry.js +5 -2
  193. package/dist/lint-cache.d.ts +59 -0
  194. package/dist/lint-cache.js +257 -0
  195. package/dist/orchestrator/graph-builder.js +14 -9
  196. package/dist/platform/coop-scheduler-runtime.d.ts +19 -0
  197. package/dist/platform/coop-scheduler-runtime.js +41 -0
  198. package/dist/platform/generic-strategy.d.ts +15 -3
  199. package/dist/platform/generic-strategy.js +49 -4
  200. package/dist/safety/safety-bridge.d.ts +11 -0
  201. package/dist/safety/safety-bridge.js +48 -0
  202. package/dist/safety/sidecar-bridge.d.ts +5 -0
  203. package/dist/safety/sidecar-bridge.js +22 -0
  204. package/dist/safety-hook.d.ts +79 -0
  205. package/dist/safety-hook.js +35 -0
  206. package/dist/testing.d.ts +8 -2
  207. package/dist/testing.js +9 -2
  208. package/dist/transpile.d.ts +3 -0
  209. package/dist/transpile.js +191 -49
  210. package/dist/types.d.ts +22 -3
  211. package/dist/ui-hook.d.ts +17 -3
  212. package/dist/utils/cli.js +123 -2
  213. package/dist/utils/fs.d.ts +13 -0
  214. package/dist/utils/fs.js +50 -0
  215. package/dist/utils/ui.js +3 -1
  216. package/package.json +23 -3
  217. package/dist/api/shared/display-adapters/eink-mono.d.ts +0 -2
  218. package/dist/api/shared/display-adapters/eink-mono.js +0 -53
  219. package/dist/api/shared/display-adapters/ssd1309.d.ts +0 -2
  220. package/dist/api/shared/display-adapters/ssd1309.js +0 -136
  221. package/dist/api/shared/display-adapters/st7796.d.ts +0 -2
  222. package/dist/api/shared/display-adapters/st7796.js +0 -132
  223. package/dist/ir/heap-array-validation.d.ts +0 -24
  224. package/dist/ir/heap-array-validation.js +0 -29
@@ -1,12 +1,20 @@
1
1
  import { LINT_RULES } from '../ir/feature-registry.js';
2
2
  export function generateProjectPackageJson(options) {
3
3
  const { projectName, frameworkPackage, boardPackage } = options;
4
+ // @typecad/hal is needed by every build, not just embedded ones: the
5
+ // transpiler unconditionally warms the HAL source modules (loadHALModules in
6
+ // transpile.ts), and resolveHALSourceDir() throws "Could not resolve
7
+ // @typecad/hal/src/" if the package is absent. Embedded targets pull it in
8
+ // transitively (@typecad/framework-arduino + board packages depend on it),
9
+ // but native targets have no board package and @typecad/framework-native does
10
+ // not declare it, so HAL must be an explicit direct dependency here.
4
11
  const deps = {
5
- "@typecad/cuttlefish": "^0.1.0-alpha.1",
6
- [frameworkPackage]: "^0.1.0-alpha.1",
12
+ "@typecad/cuttlefish": "^1.0.0-alpha.3",
13
+ "@typecad/hal": "^1.0.0-alpha.3",
14
+ [frameworkPackage]: "^1.0.0-alpha.3",
7
15
  };
8
16
  if (boardPackage) {
9
- deps[boardPackage] = "^0.1.0-alpha.1";
17
+ deps[boardPackage] = "^1.0.0-alpha.3";
10
18
  }
11
19
  const depsJson = Object.entries(deps)
12
20
  .map(([k, v]) => ` "${k}": "${v}"`)
@@ -15,12 +23,27 @@ export function generateProjectPackageJson(options) {
15
23
  // eslint-transpiler-rules plugin (which is plain JS, no dep). Without these
16
24
  // devDependencies `npm run lint` fails to resolve the parser/plugin in a
17
25
  // freshly created project. Versions mirror the repo demo's package.json.
18
- const devDepsJson = [
26
+ const baseDevDeps = [
19
27
  ' "eslint": "^10.4.1"',
20
28
  ' "@typescript-eslint/parser": "^8.61.0"',
21
29
  ' "@typescript-eslint/eslint-plugin": "^8.61.0"',
22
- ].join(',\n');
30
+ ];
31
+ // Developer-utility scripts shared by every target (native + embedded).
32
+ // None require hardware or extra dependencies:
33
+ // dev — auto-retranspile on save (transpile-only; append --compile
34
+ // to also compile on each change). The fast "does it
35
+ // typecheck" feedback loop.
36
+ // gen-decls — generate TypeScript .d.ts from C++ headers. File-argument:
37
+ // `npm run gen-decls -- lib/foo.h` or `-- --all lib/`.
38
+ // gen-libdefs — generate library-definition stubs from a TS file's imports.
39
+ // File-argument: `npm run gen-libdefs -- src/main.ts`.
40
+ const devScripts = [
41
+ '"dev": "cuttlefish build --watch"',
42
+ '"gen-decls": "cuttlefish gen-decls"',
43
+ '"gen-libdefs": "cuttlefish gen-libdefs"',
44
+ ];
23
45
  if (options.isNative) {
46
+ const devDepsJson = baseDevDeps.join(',\n');
24
47
  return `{
25
48
  "name": "${projectName}",
26
49
  "version": "1.0.0",
@@ -28,7 +51,8 @@ export function generateProjectPackageJson(options) {
28
51
  "scripts": {
29
52
  "build": "cuttlefish build",
30
53
  "compile": "cuttlefish build --compile",
31
- "lint": "eslint --config .cuttlefish/eslint.config.mjs src/"
54
+ "lint": "eslint --config .cuttlefish/eslint.config.mjs src/",
55
+ ${devScripts.join(',\n ')}
32
56
  },
33
57
  "dependencies": {
34
58
  ${depsJson}
@@ -39,6 +63,19 @@ ${devDepsJson}
39
63
  }
40
64
  `;
41
65
  }
66
+ // Embedded projects get two host-side testing tiers:
67
+ // - @typecad/expect: hardware tests run on the board via cuttlefish-test
68
+ // (`npm run test:hw`), scoped to tests/**/*.test.ts.
69
+ // - @typecad/simulator + vitest: simulate the board in Node (`npm run
70
+ // simulate`), scoped to sim/**/*.test.ts so vitest never collides with the
71
+ // @typecad/expect no-op stubs under tests/.
72
+ // Versions mirror the workspace's published releases / root devDeps.
73
+ const devDepsJson = [
74
+ ...baseDevDeps,
75
+ ' "@typecad/expect": "^1.0.0-alpha.3"',
76
+ ' "@typecad/simulator": "^1.0.0-alpha.3"',
77
+ ' "vitest": "^4.0.18"',
78
+ ].join(',\n');
42
79
  return `{
43
80
  "name": "${projectName}",
44
81
  "version": "1.0.0",
@@ -48,7 +85,10 @@ ${devDepsJson}
48
85
  "compile": "cuttlefish build --compile",
49
86
  "upload": "cuttlefish build --compile --upload",
50
87
  "monitor": "cuttlefish build --compile --upload --monitor",
51
- "lint": "eslint --config .cuttlefish/eslint.config.mjs src/"
88
+ "test:hw": "npm exec -- cuttlefish-test",
89
+ "simulate": "vitest run sim/",
90
+ "lint": "eslint --config .cuttlefish/eslint.config.mjs src/",
91
+ ${devScripts.join(',\n ')}
52
92
  },
53
93
  "dependencies": {
54
94
  ${depsJson}
@@ -85,9 +125,10 @@ export function generateProjectTsconfig(options) {
85
125
  "noEmit": true,
86
126
  "resolveJsonModule": true,
87
127
  "allowArbitraryExtensions": true,
128
+ "allowImportingTsExtensions": true,
88
129
  "rootDirs": ["src", "types"]${paths}
89
130
  },
90
- "include": ["src/**/*.ts", "types/**/*.ts", "cuttlefish.config.ts"${options.boardPackage ? ', ".cuttlefish/cuttlefish-env.d.ts"' : ''}]
131
+ "include": ["src/**/*.ts", "types/**/*.ts", "cuttlefish.config.ts", ".cuttlefish/cuttlefish-env.d.ts"${options.isNative ? '' : ', "sim/**/*.ts"'}]
91
132
  }
92
133
  `;
93
134
  }
@@ -117,8 +158,12 @@ export default config;
117
158
  `;
118
159
  }
119
160
  const buildTarget = options.buildTarget;
120
- const resolvedToolchain = options.toolchainType ?? 'arduino-cli';
121
- const buildTargetLine = buildTarget ? `\n // Framework data\n frameworkData: {\n buildTarget: '${buildTarget}',\n },` : '';
161
+ const resolvedToolchain = options.toolchainType
162
+ ?? 'arduino-cli';
163
+ let frameworkDataBlock = '';
164
+ if (buildTarget) {
165
+ frameworkDataBlock = `\n // Framework data\n frameworkData: {\n buildTarget: '${buildTarget}',\n },`;
166
+ }
122
167
  const mcuLine = options.mcu
123
168
  ? `\n // MCU package — provides silicon-level pin definitions\n mcu: '${options.mcu.startsWith('@') ? options.mcu : `@typecad/mcu-${options.mcu}`}',\n`
124
169
  : '';
@@ -127,6 +172,11 @@ export default config;
127
172
  : '';
128
173
  const portHint = process.platform === 'win32' ? 'COM4' : '/dev/ttyACM0';
129
174
  const baudLine = options.baudRate ? `\n\n // Console polyfill configuration\n console: {\n baudRate: ${options.baudRate},\n // Serial port for upload/monitor. Override with --port on the CLI.\n port: '${portHint}',\n },` : '';
175
+ // Hardware test runner configuration — used by \`npm run test:hw\` (cuttlefish-test,
176
+ // provided by @typecad/expect). It transpiles each tests/**/*.test.ts file,
177
+ // flashes it to the board, and evaluates the assertions over serial.
178
+ const resolvedBaud = options.baudRate ?? 115200;
179
+ const testLine = `\n\n // Hardware test runner (@typecad/expect / \`npm run test:hw\`)\n test: {\n // Serial port for the test board. Override with --port on the CLI or the\n // CUTTLEFISH_PORT env var (e.g. CUTTLEFISH_PORT=/dev/ttyUSB0 npm run test:hw).\n port: '${portHint}',\n baudRate: ${resolvedBaud},\n timeout: 30000,\n include: ['tests/**/*.test.ts'],\n },`;
130
180
  return `// ---------------------------------------------------------------------------
131
181
  // cuttlefish.config.ts — Project configuration
132
182
  //
@@ -143,7 +193,7 @@ const config: CuttlefishConfig = {
143
193
  target: '${options.architecture}',${mcuLine}${boardLine}
144
194
 
145
195
  // Framework package — controls code generation strategy
146
- framework: '${options.frameworkPackage}',${buildTargetLine}
196
+ framework: '${options.frameworkPackage}',${frameworkDataBlock}
147
197
 
148
198
  // Output / build options
149
199
  output: {
@@ -155,7 +205,7 @@ const config: CuttlefishConfig = {
155
205
  // Toolchain configuration
156
206
  toolchain: {
157
207
  type: '${resolvedToolchain}',
158
- },${baudLine}
208
+ },${baudLine}${testLine}
159
209
  };
160
210
 
161
211
  export default config;
@@ -173,6 +223,22 @@ declare global {
173
223
  type Owned<T = unknown> = T;
174
224
  type Shared<T = unknown> = T;
175
225
  type Mutable<T = unknown> = T;
226
+ // SafeVariable: SEU-resistant storage. The transpiler lowers SafeVariable<number>
227
+ // to a C++ template with inverted-redundancy storage. Declared as an interface
228
+ // (not a type alias) so the TS type checker recognizes method calls.
229
+ // Arithmetic T only (integral or floating-point); string is rejected by a
230
+ // static_assert in the emitted C++ template.
231
+ interface SafeVariable<T = number> { set(value: T): void; get(): T; valid(): boolean; hasFault(): boolean; }
232
+ // SafeInt: chainable bounds-checked signed-integer arithmetic. The transpiler
233
+ // lowers SafeInt<number> to SafeInt<int32_t> (a C++ template with sticky-fault
234
+ // overflow detection). Signed integer T only — unsigned/bool/float/string are
235
+ // rejected by a static_assert in the emitted C++ template.
236
+ interface SafeInt<T = number> {
237
+ add(delta: T): SafeInt<T>; sub(delta: T): SafeInt<T>;
238
+ mul(factor: T): SafeInt<T>; divide(d: T): SafeInt<T>; mod(d: T): SafeInt<T>;
239
+ negate(): SafeInt<T>; absValue(): SafeInt<T>;
240
+ get(): T; hasFault(): boolean; valid(): boolean; reset(newValue: T): void;
241
+ }
176
242
 
177
243
  type uint8_t = number;
178
244
  type int8_t = number;
@@ -198,6 +264,20 @@ declare global {
198
264
  error(...args: unknown[]): void;
199
265
  }
200
266
  const console: Console;
267
+
268
+ // Convenience helper for volatile variables in TypeCAD programs.
269
+ // The transpiler detects calls to volatile() and emits the C++ volatile qualifier.
270
+ declare function volatile<T>(value: T): T;
271
+
272
+ // JS-style timers (declared here so a project does not need "dom" in tsconfig
273
+ // lib to type setInterval/setTimeout). The transpiler rewrites these to
274
+ // __tc_setInterval/__tc_setTimeout and emits the timer_methods polyfill when
275
+ // used. Note: Timing.setInterval/setTimeout (from @typecad/hal) is the
276
+ // preferred single entry point and is typed via the @typecad/board import.
277
+ declare function setInterval(handler: () => void, timeout?: number): number;
278
+ declare function setTimeout(handler: () => void, timeout?: number): number;
279
+ declare function clearInterval(id: number): void;
280
+ declare function clearTimeout(id: number): void;
201
281
  }
202
282
 
203
283
  export {};
@@ -216,6 +296,22 @@ declare global {
216
296
  type Owned<T = unknown> = T;
217
297
  type Shared<T = unknown> = T;
218
298
  type Mutable<T = unknown> = T;
299
+ // SafeVariable: SEU-resistant storage. The transpiler lowers SafeVariable<number>
300
+ // to a C++ template with inverted-redundancy storage. Declared as an interface
301
+ // (not a type alias) so the TS type checker recognizes method calls.
302
+ // Arithmetic T only (integral or floating-point); string is rejected by a
303
+ // static_assert in the emitted C++ template.
304
+ interface SafeVariable<T = number> { set(value: T): void; get(): T; valid(): boolean; hasFault(): boolean; }
305
+ // SafeInt: chainable bounds-checked signed-integer arithmetic. The transpiler
306
+ // lowers SafeInt<number> to SafeInt<int32_t> (a C++ template with sticky-fault
307
+ // overflow detection). Signed integer T only — unsigned/bool/float/string are
308
+ // rejected by a static_assert in the emitted C++ template.
309
+ interface SafeInt<T = number> {
310
+ add(delta: T): SafeInt<T>; sub(delta: T): SafeInt<T>;
311
+ mul(factor: T): SafeInt<T>; divide(d: T): SafeInt<T>; mod(d: T): SafeInt<T>;
312
+ negate(): SafeInt<T>; absValue(): SafeInt<T>;
313
+ get(): T; hasFault(): boolean; valid(): boolean; reset(newValue: T): void;
314
+ }
219
315
 
220
316
  type uint8_t = number;
221
317
  type int8_t = number;
@@ -241,6 +337,20 @@ declare global {
241
337
  error(...args: unknown[]): void;
242
338
  }
243
339
  const console: Console;
340
+
341
+ // Convenience helper for volatile variables in TypeCAD programs.
342
+ // The transpiler detects calls to volatile() and emits the C++ volatile qualifier.
343
+ declare function volatile<T>(value: T): T;
344
+
345
+ // JS-style timers (declared here so a project does not need "dom" in tsconfig
346
+ // lib to type setInterval/setTimeout). The transpiler rewrites these to
347
+ // __tc_setInterval/__tc_setTimeout and emits the timer_methods polyfill when
348
+ // used. Note: Timing.setInterval/setTimeout (from @typecad/hal) is the
349
+ // preferred single entry point and is typed via the @typecad/board import.
350
+ declare function setInterval(handler: () => void, timeout?: number): number;
351
+ declare function setTimeout(handler: () => void, timeout?: number): number;
352
+ declare function clearInterval(id: number): void;
353
+ declare function clearTimeout(id: number): void;
244
354
  }
245
355
 
246
356
  declare module '@typecad/board' {
@@ -286,6 +396,148 @@ while (true) {
286
396
  }
287
397
  `;
288
398
  }
399
+ export function generateStarterTest(_options) {
400
+ return `// ---------------------------------------------------------------------------
401
+ // Hardware test — Basics
402
+ //
403
+ // Runs on the board via \`npm run test:hw\` (cuttlefish-test). Each test file is
404
+ // transpiled, flashed to the board, and its assertions are evaluated on the host
405
+ // over serial. Change the serial port in cuttlefish.config.ts (the \`test.port\`
406
+ // field) or override it with the CUTTLEFISH_PORT env var.
407
+ //
408
+ // API: describe(...).it(...).expect(value).<matcher>() chains. Import pin
409
+ // objects from '@typecad/board' to assert on real hardware I/O. Every file ends
410
+ // with done().
411
+ // ---------------------------------------------------------------------------
412
+
413
+ import { describe, done } from '@typecad/expect';
414
+
415
+ describe("Basics")
416
+ .it("adds two numbers")
417
+ .expect(
418
+ (() => {
419
+ const a = 1;
420
+ let b = 2;
421
+ return a + b;
422
+ })
423
+ ).toBe(3)
424
+ .it("multiplies two numbers")
425
+ .expect(
426
+ (() => {
427
+ let a = 3;
428
+ let b = 4;
429
+ return a * b;
430
+ })
431
+ ).toBe(12)
432
+ .it("reads an array element")
433
+ .expect(
434
+ (() => {
435
+ const data = new Uint8Array([0xAA, 0x10, 0x20]);
436
+ return data[1];
437
+ })
438
+ ).toBe(0x10)
439
+ .it("clamps a value to a range")
440
+ .expect(
441
+ (() => {
442
+ const value = 2000;
443
+ return Math.max(0, Math.min(1023, value));
444
+ })
445
+ ).toBe(1023);
446
+
447
+ done();
448
+ `;
449
+ }
450
+ export function generateStarterSim(options) {
451
+ const boardType = options.targetId;
452
+ return `// ---------------------------------------------------------------------------
453
+ // Hardware simulation — Button + LED
454
+ //
455
+ // Runs entirely on your computer with \`npm run simulate\` (vitest + the
456
+ // @typecad/simulator package). No board, serial port, or arduino-cli required.
457
+ // The simulator mirrors the pins/peripherals of your ${options.targetDisplayName}
458
+ // (${boardType}); you inject fake inputs and assert on the outputs in Node.
459
+ //
460
+ // This is the fast tier — iterate on logic here, then confirm on real hardware
461
+ // with \`npm run test:hw\` (which flashes tests/ to the board).
462
+ // ---------------------------------------------------------------------------
463
+
464
+ import { describe, it, expect, beforeEach } from "vitest";
465
+ import {
466
+ createSimBoard,
467
+ type SimBoard,
468
+ type SimDigitalPin,
469
+ } from "@typecad/simulator";
470
+
471
+ // ===========================================================================
472
+ // FIRMWARE LOGIC
473
+ // ---------------------------------------------------------------------------
474
+ // Factor your firmware into a function that takes the simulated pins as
475
+ // arguments. In a real project this same logic runs on the board against real
476
+ // pins — here it runs against the sim board so you can test it without hardware.
477
+ // ===========================================================================
478
+
479
+ /**
480
+ * Reads a button and reflects its state on an LED.
481
+ *
482
+ * To use your own logic: replace the body of this function with whatever your
483
+ * firmware does (read a sensor, drive a motor, print to serial, ...). As long
484
+ * as it only touches pins you pass in, the simulator can exercise it.
485
+ */
486
+ function reflectButtonOnLed(button: SimDigitalPin, led: SimDigitalPin): void {
487
+ // The button pin is pulled HIGH (1) at rest and reads LOW (0) when pressed.
488
+ if (button.isLow()) {
489
+ led.high();
490
+ } else {
491
+ led.low();
492
+ }
493
+ }
494
+
495
+ // ===========================================================================
496
+ // TEST BENCH
497
+ // ---------------------------------------------------------------------------
498
+ // \`createSimBoard\` builds an in-memory version of your board. The pin numbers
499
+ // below match the physical pinout. Add the pins/peripherals your firmware uses:
500
+ // board.digital(n), board.analog(n), board.pwm(n), board.serial(n),
501
+ // board.i2c(n), board.spi(n), board.interrupt(n).
502
+ // ===========================================================================
503
+
504
+ function setupSim(): { board: SimBoard; button: SimDigitalPin; led: SimDigitalPin } {
505
+ // boardType mirrors the target chosen with \`cuttlefish create\`.
506
+ const board = createSimBoard({ boardType: "${boardType}" });
507
+
508
+ const button = board.digital(2).asInputPullUp(); // button on pin 2 (INPUT_PULLUP)
509
+ const led = board.digital(13).asOutput(false); // LED on pin 13
510
+
511
+ return { board, button, led };
512
+ }
513
+
514
+ describe("Button + LED (simulator)", () => {
515
+ beforeEach(() => {
516
+ // A fresh board per test keeps state isolated. For a long-running sim you
517
+ // can call board.reset() between cycles instead.
518
+ });
519
+
520
+ it("keeps the LED off while the button is released", () => {
521
+ const { button, led } = setupSim();
522
+
523
+ // Button at rest: INPUT_PULLUP reads HIGH.
524
+ reflectButtonOnLed(button, led);
525
+
526
+ expect(led.getBitValue()).toBe(0);
527
+ });
528
+
529
+ it("turns the LED on while the button is pressed", () => {
530
+ const { button, led } = setupSim();
531
+
532
+ // Simulate a press: drive the button pin LOW.
533
+ button.injectValue(0);
534
+ reflectButtonOnLed(button, led);
535
+
536
+ expect(led.getBitValue()).toBe(1);
537
+ });
538
+ });
539
+ `;
540
+ }
289
541
  export function generateBoardForwardingFile(boardPackage) {
290
542
  return `// ---------------------------------------------------------------------------
291
543
  // .cuttlefish/board.ts — Dynamically generated forwarding board package
@@ -328,11 +580,13 @@ export default [
328
580
  files: ["src/**/*.ts"],
329
581
  languageOptions: {
330
582
  parser: tsparser,
331
- parserOptions: {
332
- // Type-aware parsing so @typescript-eslint/no-explicit-any resolves
333
- // imported bindings to their real types instead of defaulting to any.
334
- project: "./tsconfig.json",
335
- },
583
+ // NOTE: do NOT set parserOptions.project here. None of the rules below
584
+ // (no-restricted-syntax, the cuttlefish/* AST rules, no-explicit-any,
585
+ // no-eval, ...) consume type information, so enabling type-aware linting
586
+ // only forces ESLint to build a full TS type-program per file — ~3.4s of
587
+ // pure overhead on small projects with zero change to what is detected.
588
+ // If a future rule needs types, scope project to that rule only via
589
+ // parserOptions on a dedicated config block, not globally.
336
590
  },
337
591
  plugins: {
338
592
  "@typescript-eslint": tseslint,
@@ -2,6 +2,7 @@ import * as readline from "node:readline/promises";
2
2
  import { stdin as input, stdout as output } from "node:process";
3
3
  import chalk from "chalk";
4
4
  import { KNOWN_TARGETS } from "./init-scaffold.js";
5
+ import { frameworksForTarget, frameworkCatalogEntry, FRAMEWORK_CATALOG, frameworkTargetProfile } from "./framework-catalog.js";
5
6
  function validateProjectName(name) {
6
7
  if (!name || name.trim().length === 0) {
7
8
  return "Project name cannot be empty.";
@@ -84,34 +85,43 @@ export async function runInitWizard(partialOptions) {
84
85
  targetId = await promptSelect(rl, "Target", targetOptions);
85
86
  }
86
87
  const target = KNOWN_TARGETS.find((t) => t.id === targetId);
87
- // 3. Framework (only for embedded targets)
88
+ // 3. Framework. Narrow to the frameworks compatible with the selected board
89
+ // (see framework-catalog), then let the user pick. The chosen package is
90
+ // installed into the new project by `cuttlefish create`, so we offer every
91
+ // compatible framework regardless of what is currently installed — no
92
+ // require.resolve discovery (which also avoided an ESM `require` pitfall
93
+ // where the lookup always failed and made the wizard dead-end).
88
94
  let framework = target.framework;
89
95
  let frameworkPackage = target.frameworkPackage;
90
- if (!target.isNative) {
91
- const frameworkOptions = [
92
- { label: "Arduino (digitalWrite, Wire, SPI)", value: 'arduino', pkg: '@typecad/framework-arduino' },
93
- ];
94
- if (target.architecture === 'avr') {
95
- frameworkOptions.push({ label: "Bare-metal AVR (PORTB, etc.)", value: 'avr', pkg: '@typecad/framework-avr' });
96
- }
97
- if (partialOptions?.framework) {
98
- const match = frameworkOptions.find(f => f.value === partialOptions.framework);
99
- framework = match?.value ?? partialOptions.framework;
100
- frameworkPackage = match?.pkg ?? `@typecad/framework-${partialOptions.framework}`;
101
- console.log(`${chalk.cyan("?")} Framework: ${chalk.white(framework)}`);
102
- }
103
- else if (frameworkOptions.length === 1) {
104
- framework = frameworkOptions[0].value;
105
- frameworkPackage = frameworkOptions[0].pkg;
106
- console.log(`${chalk.cyan("?")} Framework: ${chalk.white(frameworkOptions[0].label)}`);
107
- }
108
- else {
109
- const selected = await promptSelect(rl, "Framework", frameworkOptions.map(f => ({ label: f.label, value: f.value })));
110
- const match = frameworkOptions.find(f => f.value === selected);
111
- framework = match.value;
112
- frameworkPackage = match.pkg;
96
+ const compatible = frameworksForTarget(target).filter((f) => f.installable);
97
+ if (compatible.length === 0) {
98
+ // Defensive: every known target maps to at least one framework in the catalog.
99
+ throw new Error(`No installable frameworks are compatible with target '${target.id}'.`);
100
+ }
101
+ if (partialOptions?.framework) {
102
+ const requested = frameworkCatalogEntry(partialOptions.framework);
103
+ if (!requested) {
104
+ const available = FRAMEWORK_CATALOG.filter((f) => f.installable).map((f) => f.id).join(", ");
105
+ throw new Error(`Unknown framework '${partialOptions.framework}'. Available: ${available}`);
113
106
  }
107
+ framework = requested.id;
108
+ frameworkPackage = requested.packageName;
109
+ console.log(`${chalk.cyan("?")} Framework: ${chalk.white(requested.label)}`);
110
+ }
111
+ else if (compatible.length === 1) {
112
+ framework = compatible[0].id;
113
+ frameworkPackage = compatible[0].packageName;
114
+ console.log(`${chalk.cyan("?")} Framework: ${chalk.white(compatible[0].label)}`);
115
+ }
116
+ else {
117
+ const selected = await promptSelect(rl, "Framework", compatible.map((f) => ({ label: f.label, value: f.id })));
118
+ const match = compatible.find((f) => f.id === selected);
119
+ framework = match.id;
120
+ frameworkPackage = match.packageName;
114
121
  }
122
+ // Resolve the framework-specific build target + toolchain (e.g. a Zephyr
123
+ // board id + 'west' vs the Arduino FQBN + 'arduino-cli'). See framework-catalog.
124
+ const profile = frameworkTargetProfile(target, framework);
115
125
  // 4. Baud rate (only for embedded)
116
126
  let baudRate;
117
127
  if (!target.isNative) {
@@ -148,12 +158,16 @@ export async function runInitWizard(partialOptions) {
148
158
  isNative: target.isNative,
149
159
  architecture: target.architecture,
150
160
  boardPackage: target.boardPackage,
151
- frameworkPackage,
152
- framework,
153
- buildTarget: target.buildTarget,
161
+ frameworkPackage: frameworkPackage ?? '',
162
+ framework: framework ?? '',
163
+ buildTarget: profile.buildTarget ?? target.buildTarget,
164
+ ...(profile.toolchainType ? { toolchainType: profile.toolchainType } : {}),
154
165
  mcu: target.mcu,
155
166
  baudRate,
156
167
  includeSketch,
168
+ ...(target.frameworkData
169
+ ? { frameworkData: target.frameworkData }
170
+ : {}),
157
171
  };
158
172
  }
159
173
  catch (err) {
@@ -0,0 +1,32 @@
1
+ import { type PackageManager } from "./framework-catalog.js";
2
+ export interface ProjectInstallResult {
3
+ pm: PackageManager;
4
+ }
5
+ interface InstallCommand {
6
+ bin: PackageManager;
7
+ args: string[];
8
+ cwd: string;
9
+ }
10
+ interface InstallRunResult {
11
+ /** Exit status; null when the process could not be launched (ENOENT, etc.). */
12
+ status: number | null;
13
+ /** Populated only when the binary could not be launched. */
14
+ launchError?: string;
15
+ }
16
+ type InstallRunner = (cmd: InstallCommand) => InstallRunResult;
17
+ /**
18
+ * FOR TESTS ONLY. Replaces the real spawn-based installer with `runner`.
19
+ * Pass `undefined` to restore the real executor.
20
+ */
21
+ export declare function __setProjectInstallRunnerForTest(runner: InstallRunner | undefined): void;
22
+ /**
23
+ * Run `<pm> install` in `projectDir`. Throws on launch failure or non-zero exit
24
+ * so the create command can catch it and fall back to instructing the user to
25
+ * run the install manually (the scaffold itself already succeeded).
26
+ */
27
+ export declare function installProjectDependencies(opts: {
28
+ projectDir: string;
29
+ /** Where to detect the user's preferred package manager. Defaults to cwd. */
30
+ cwd?: string;
31
+ }): ProjectInstallResult;
32
+ export {};
@@ -0,0 +1,46 @@
1
+ // Installs all dependencies in a freshly scaffolded project directory, as the
2
+ // final step of `cuttlefish create` so the new project is ready to build with
3
+ // no separate `npm install` step. The package manager is detected from the
4
+ // INVOKING directory (process.cwd()) — a pnpm/yarn user gets their tool of
5
+ // choice even though the new project has no lockfile yet.
6
+ import { spawnSync } from "node:child_process";
7
+ import { detectPackageManager } from "./framework-catalog.js";
8
+ let testRunner;
9
+ /**
10
+ * FOR TESTS ONLY. Replaces the real spawn-based installer with `runner`.
11
+ * Pass `undefined` to restore the real executor.
12
+ */
13
+ export function __setProjectInstallRunnerForTest(runner) {
14
+ testRunner = runner;
15
+ }
16
+ function runRealInstall(cmd) {
17
+ // stdio: "inherit" streams the package manager's own output to the terminal
18
+ // (install progress, deprecation warnings, etc.).
19
+ const result = spawnSync(cmd.bin, cmd.args, { cwd: cmd.cwd, stdio: "inherit" });
20
+ if (result.error) {
21
+ const errno = result.error.code;
22
+ return {
23
+ status: null,
24
+ launchError: errno === "ENOENT" ? `'${cmd.bin}' not found on PATH` : String(result.error),
25
+ };
26
+ }
27
+ return { status: result.status };
28
+ }
29
+ /**
30
+ * Run `<pm> install` in `projectDir`. Throws on launch failure or non-zero exit
31
+ * so the create command can catch it and fall back to instructing the user to
32
+ * run the install manually (the scaffold itself already succeeded).
33
+ */
34
+ export function installProjectDependencies(opts) {
35
+ const pm = detectPackageManager(opts.cwd ?? process.cwd());
36
+ const cmd = { bin: pm, args: ["install"], cwd: opts.projectDir };
37
+ const run = testRunner ?? runRealInstall;
38
+ const result = run(cmd);
39
+ if (result.launchError) {
40
+ throw new Error(`Failed to run '${pm}': ${result.launchError}`);
41
+ }
42
+ if (result.status !== 0) {
43
+ throw new Error(`'${pm} install' exited with code ${result.status}.`);
44
+ }
45
+ return { pm };
46
+ }