embedded-react 0.19.0 → 0.20.0

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 (116) hide show
  1. package/README.md +7 -3
  2. package/aot/compile.mjs +178 -58
  3. package/aot/compiler/animations.mjs +290 -281
  4. package/aot/compiler/boot.mjs +70 -33
  5. package/aot/compiler/branch-merge.mjs +4 -3
  6. package/aot/compiler/check.mjs +9 -9
  7. package/aot/compiler/collect.mjs +324 -205
  8. package/aot/compiler/control-flow.mjs +209 -197
  9. package/aot/compiler/diagnostics.mjs +22 -25
  10. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  11. package/aot/compiler/elements/dial.mjs +91 -77
  12. package/aot/compiler/elements/flat-list.mjs +24 -22
  13. package/aot/compiler/elements/image.mjs +51 -50
  14. package/aot/compiler/elements/modal.mjs +31 -30
  15. package/aot/compiler/elements/props.mjs +23 -23
  16. package/aot/compiler/elements/switch.mjs +42 -34
  17. package/aot/compiler/elements/text-input.mjs +34 -32
  18. package/aot/compiler/expressions.mjs +372 -333
  19. package/aot/compiler/handlers.mjs +473 -387
  20. package/aot/compiler/ir/functions.mjs +11 -1
  21. package/aot/compiler/ir/nodes.mjs +4 -4
  22. package/aot/compiler/ir/reads.mjs +19 -19
  23. package/aot/compiler/ir/types.mjs +14 -14
  24. package/aot/compiler/ir/vectors.mjs +5 -1
  25. package/aot/compiler/keyboard.mjs +17 -7
  26. package/aot/compiler/lower.mjs +77 -80
  27. package/aot/compiler/nodes.mjs +169 -152
  28. package/aot/compiler/options.mjs +35 -30
  29. package/aot/compiler/out.mjs +18 -22
  30. package/aot/compiler/package/animations.mjs +669 -0
  31. package/aot/compiler/package/arena.mjs +252 -0
  32. package/aot/compiler/package/assemble.mjs +177 -0
  33. package/aot/compiler/package/bytecode.mjs +286 -0
  34. package/aot/compiler/package/checks.mjs +1022 -0
  35. package/aot/compiler/package/codegen.mjs +1329 -0
  36. package/aot/compiler/package/enums.mjs +138 -0
  37. package/aot/compiler/package/format.mjs +760 -0
  38. package/aot/compiler/package/layouts.mjs +136 -0
  39. package/aot/compiler/package/lower.mjs +1606 -0
  40. package/aot/compiler/package/props.mjs +118 -0
  41. package/aot/compiler/package/tables.mjs +103 -0
  42. package/aot/compiler/package/vectors.mjs +502 -0
  43. package/aot/compiler/package/writer.mjs +664 -0
  44. package/aot/compiler/pan-responder.mjs +69 -61
  45. package/aot/compiler/parse.mjs +21 -21
  46. package/aot/compiler/static-eval.mjs +25 -23
  47. package/aot/compiler/style-text.mjs +161 -172
  48. package/aot/compiler/svg.mjs +477 -251
  49. package/aot/screenshot-smoke.mjs +54 -40
  50. package/aot/style-map.mjs +102 -90
  51. package/assets/bake-font.mjs +123 -77
  52. package/assets/bake-image.mjs +39 -22
  53. package/assets/bake-svg.mjs +361 -262
  54. package/assets/build-builtin-font.mjs +11 -7
  55. package/assets/emit-c.mjs +77 -58
  56. package/assets/emit-container.mjs +123 -37
  57. package/assets/emit-pack.mjs +77 -67
  58. package/assets/font-config.mjs +9 -6
  59. package/assets/font-sizes.mjs +163 -123
  60. package/assets/glyph-coverage.mjs +74 -54
  61. package/assets/index.mjs +31 -9
  62. package/assets/rasterize.mjs +126 -99
  63. package/assets/svg-loader.mjs +8 -8
  64. package/build.mjs +14 -12
  65. package/cli.mjs +359 -172
  66. package/compile-bin.mjs +3 -3
  67. package/flash.mjs +537 -0
  68. package/hotreload/dev-device.mjs +90 -33
  69. package/hotreload/pack-app.mjs +55 -43
  70. package/hotreload/pack-split.mjs +46 -37
  71. package/hotreload/package-transfer.mjs +175 -0
  72. package/hotreload/protocol.mjs +50 -37
  73. package/hotreload/uploader.mjs +38 -27
  74. package/hotreload/watch-tree.mjs +19 -19
  75. package/pack-container.mjs +28 -20
  76. package/package.json +7 -8
  77. package/persist-transform.mjs +34 -28
  78. package/qjsc-wasm.mjs +25 -14
  79. package/sim/embedded-react.cjs +1 -1
  80. package/sim/embedded-react.js +1 -1
  81. package/sim/embedded-react.wasm +0 -0
  82. package/sim/index.html +94 -85
  83. package/sim-server.mjs +101 -82
  84. package/src/embedded-react/Animated.js +24 -24
  85. package/src/embedded-react/Easing.js +1 -1
  86. package/src/embedded-react/FlatList.js +3 -3
  87. package/src/embedded-react/LayoutAnimation.js +8 -5
  88. package/src/embedded-react/PanResponder.js +75 -71
  89. package/src/embedded-react/Pressable.js +2 -8
  90. package/src/embedded-react/SectionList.js +6 -6
  91. package/src/embedded-react/StyleSheet.js +4 -3
  92. package/src/embedded-react/TouchableOpacity.js +13 -8
  93. package/src/embedded-react/index.d.ts +5 -5
  94. package/src/embedded-react/layout-anim-config.js +10 -4
  95. package/src/embedded-react/list-child.js +5 -5
  96. package/src/embedded-react/named-colors.js +1 -1
  97. package/src/embedded-react/split-style.js +11 -11
  98. package/src/embedded-react/svg-ops.js +760 -593
  99. package/src/embedded-react/useHostValue.js +3 -3
  100. package/src/embedded-react/usePersistentState.js +6 -6
  101. package/src/embedded-react/warn-props.js +1 -1
  102. package/src/host-config.js +60 -53
  103. package/src/props.js +49 -41
  104. package/src/renderer.js +7 -4
  105. package/aot/compiler/assemble.mjs +0 -944
  106. package/aot/compiler/c/animations.mjs +0 -436
  107. package/aot/compiler/c/boot.mjs +0 -127
  108. package/aot/compiler/c/expressions.mjs +0 -270
  109. package/aot/compiler/c/functions.mjs +0 -268
  110. package/aot/compiler/c/keyboard.mjs +0 -96
  111. package/aot/compiler/c/nodes.mjs +0 -303
  112. package/aot/compiler/c/pan-responder.mjs +0 -136
  113. package/aot/compiler/c/statements.mjs +0 -319
  114. package/aot/compiler/c/text.mjs +0 -83
  115. package/aot/compiler/c/vectors.mjs +0 -381
  116. package/aot/compiler/c-syntax.mjs +0 -127
package/cli.mjs CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  existsSync,
29
29
  mkdirSync,
30
30
  readFileSync,
31
+ statSync,
31
32
  writeFileSync,
32
33
  } from 'node:fs';
33
34
  import {fileURLToPath, pathToFileURL} from 'node:url';
@@ -41,13 +42,17 @@ import {
41
42
  } from './hotreload/pack-split.mjs';
42
43
  import {runDeviceDevServer} from './hotreload/dev-device.mjs';
43
44
  import {detectDevicePorts, preferCalloutPath} from './hotreload/uploader.mjs';
45
+ import {boardByName, flashSlot, packSlot} from './flash.mjs';
44
46
 
45
- const PKG_ROOT = dirname(fileURLToPath(import.meta.url));
47
+ const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
46
48
 
47
49
  // QuickJS release the bytecode container targets — MUST match bridges/quickjs/CMakeLists.txt and
48
50
  // ER_QUICKJS_TAG in er_runtime.c (the device loader rejects a mismatch). The wasm that compiles the
49
51
  // bytecode embeds this same QuickJS.
50
- const QJS_TAG = 'v0.15.0';
52
+ const QUICKJS_TAG = 'v0.15.0';
53
+
54
+ const DEFAULT_PORT = 3333;
55
+ const BYTES_PER_KILOBYTE = 1024;
51
56
 
52
57
  function usage() {
53
58
  console.log(`embedded-react — React Native for embedded MCUs
@@ -57,15 +62,31 @@ Usage:
57
62
  embedded-react dev [entry] --device [port] Hot-reload on a real board over USB (Flow A): re-pack
58
63
  the app and stream it on every save. Omit <port> (or
59
64
  pass 'auto') to auto-detect the ESP32 USB-Serial-JTAG.
65
+ --aot → Flow B: compile a package and send it instead.
60
66
  embedded-react export [entry] [--out <dir>] Build a self-contained static playground (no server)
61
67
  embedded-react build [entry] [--out <dir>] Build the device artifact:
62
68
  default → app.erpkg (Flow A: QuickJS bytecode + assets,
63
69
  upload to the device's config region)
64
- --aot → app.gen.c/.h + assets.generated.c (Flow B:
65
- no QuickJS, compiled into firmware)
66
- --aot --screen <WxH> bake the target panel size so a
67
- responsive app folds to that board's layout
68
- (e.g. --screen 240x320)
70
+ --aot → app.erpkg (Flow B package, for the Flow B
71
+ runtime: write it to a slot with flash)
72
+ It has a layout for every panel size:
73
+ the screen picks one at boot.
74
+ --aot --screen <WxH>,<WxH> keep only the layouts
75
+ those panels pick, to save flash
76
+ --aot --release → a package without its debug
77
+ table, written beside it as app.erdbg
78
+ --aot --bake → app.erpkg.c (the package as a const
79
+ array, for a board with no spare partition)
80
+ embedded-react flash [package] --board <name> [--port <p>]
81
+ Write a package to the board's staging slot. The firmware
82
+ runs it at the next boot if it passes verification, and
83
+ keeps the last good package until then.
84
+ embedded-react pack [package] --board <name> [--slot a|b] [--sequence <n>] [--out <dir>]
85
+ Write a slot's image to a file, for a factory line or a
86
+ drag-and-drop UF2, without a board attached.
87
+
88
+ board esp32-2432s028r, esp32-s3 or rp2040-touch-lcd-1.69
89
+ package defaults to dist/app.erpkg
69
90
 
70
91
  entry dev/export/build use ./index.jsx, ./src/index.jsx, or package.json "main";
71
92
  build --aot uses ./App.jsx or ./src/App.jsx. Pass one to override.
@@ -74,7 +95,7 @@ Usage:
74
95
 
75
96
  /** Locate the package's prebuilt simulator assets (the .wasm ships with this package). */
76
97
  function simDirOrExit() {
77
- const simDir = resolve(PKG_ROOT, 'sim');
98
+ const simDir = resolve(PACKAGE_ROOT, 'sim');
78
99
  if (!existsSync(resolve(simDir, 'embedded-react.wasm'))) {
79
100
  console.error(
80
101
  'The prebuilt simulator (sim/embedded-react.wasm) is missing from this install.',
@@ -87,23 +108,23 @@ function simDirOrExit() {
87
108
  return simDir;
88
109
  }
89
110
 
90
- const libSrc = () => resolve(PKG_ROOT, 'src/embedded-react/index.js');
111
+ const libSrc = () => resolve(PACKAGE_ROOT, 'src/embedded-react/index.js');
91
112
  const nodePaths = cwd => [
92
- resolve(PKG_ROOT, 'node_modules'),
113
+ resolve(PACKAGE_ROOT, 'node_modules'),
93
114
  resolve(cwd, 'node_modules'),
94
115
  ];
95
116
 
96
117
  /** Resolve the app entry: an explicit arg, else common conventions, else package.json "main"/"source". */
97
118
  function resolveEntry(cwd, explicit) {
98
119
  if (explicit) {
99
- const p = resolve(cwd, explicit);
100
- if (!existsSync(p)) {
101
- console.error(`Entry not found: ${p}`);
120
+ const entryPath = resolve(cwd, explicit);
121
+ if (!existsSync(entryPath)) {
122
+ console.error(`Entry not found: ${entryPath}`);
102
123
  process.exit(1);
103
124
  }
104
- return p;
125
+ return entryPath;
105
126
  }
106
- for (const rel of [
127
+ for (const relativePath of [
107
128
  'index.jsx',
108
129
  'src/index.jsx',
109
130
  'index.tsx',
@@ -111,17 +132,17 @@ function resolveEntry(cwd, explicit) {
111
132
  'App.jsx',
112
133
  'src/App.jsx',
113
134
  ]) {
114
- const p = resolve(cwd, rel);
115
- if (existsSync(p)) return p;
135
+ const entryPath = resolve(cwd, relativePath);
136
+ if (existsSync(entryPath)) return entryPath;
116
137
  }
117
- const pkgPath = resolve(cwd, 'package.json');
118
- if (existsSync(pkgPath)) {
138
+ const packageJsonPath = resolve(cwd, 'package.json');
139
+ if (existsSync(packageJsonPath)) {
119
140
  try {
120
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
121
- for (const field of [pkg.source, pkg.main]) {
122
- if (field) {
123
- const p = resolve(cwd, field);
124
- if (existsSync(p)) return p;
141
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
142
+ for (const entryField of [packageJson.source, packageJson.main]) {
143
+ if (entryField) {
144
+ const entryPath = resolve(cwd, entryField);
145
+ if (existsSync(entryPath)) return entryPath;
125
146
  }
126
147
  }
127
148
  } catch {
@@ -138,34 +159,34 @@ function resolveEntry(cwd, explicit) {
138
159
  }
139
160
 
140
161
  function optValue(args, flag) {
141
- const idx = args.indexOf(flag);
142
- if (idx < 0) return null;
143
- const value = args[idx + 1];
162
+ const flagIndex = args.indexOf(flag);
163
+ if (flagIndex < 0) return null;
164
+ const value = args[flagIndex + 1];
144
165
  if (!value || value.startsWith('--')) {
145
166
  console.error(`Missing value for ${flag}\n`);
146
167
  usage();
147
168
  process.exit(1);
148
169
  }
149
- return {value, idx, valueIdx: idx + 1};
170
+ return {value, index: flagIndex, valueIndex: flagIndex + 1};
150
171
  }
151
172
 
152
173
  /** Like optValue, but the value is OPTIONAL: `--flag` alone → {value: null}; `--flag x` → {value: 'x'}. */
153
174
  function optFlagMaybeValue(args, flag) {
154
- const idx = args.indexOf(flag);
155
- if (idx < 0) return null;
156
- const next = args[idx + 1];
157
- const hasValue = next != null && !next.startsWith('--');
175
+ const flagIndex = args.indexOf(flag);
176
+ if (flagIndex < 0) return null;
177
+ const nextArg = args[flagIndex + 1];
178
+ const hasValue = nextArg != null && !nextArg.startsWith('--');
158
179
  return {
159
- value: hasValue ? next : null,
160
- idx,
161
- valueIdx: hasValue ? idx + 1 : -1,
180
+ value: hasValue ? nextArg : null,
181
+ index: flagIndex,
182
+ valueIndex: hasValue ? flagIndex + 1 : -1,
162
183
  };
163
184
  }
164
185
 
165
186
  /** A token that names a serial port rather than an app entry file (so `--device App.jsx` isn't a port). */
166
- const looksLikeDevicePath = s =>
167
- /^(\/dev\/|com\d|\\\\\.\\)/i.test(s) ||
168
- /(tty|usbmodem|usbserial|cu\.)/i.test(s);
187
+ const looksLikeDevicePath = token =>
188
+ /^(\/dev\/|com\d|\\\\\.\\)/i.test(token) ||
189
+ /(tty|usbmodem|usbserial|cu\.)/i.test(token);
169
190
 
170
191
  /**
171
192
  * Resolve the `--device` port. An explicit path is the universal, board-agnostic mechanism (any serial
@@ -186,11 +207,11 @@ async function resolveDevicePortOrExit(explicit) {
186
207
  process.exit(1);
187
208
  }
188
209
  if (matches.length === 1) {
189
- const p = matches[0];
190
- const path = preferCalloutPath(p.path);
210
+ const port = matches[0];
211
+ const path = preferCalloutPath(port.path);
191
212
  console.log(
192
213
  `✓ auto-detected ESP32 USB-Serial-JTAG at ${path}` +
193
- (p.serialNumber ? ` (SN ${p.serialNumber})` : ''),
214
+ (port.serialNumber ? ` (SN ${port.serialNumber})` : ''),
194
215
  );
195
216
  return path;
196
217
  }
@@ -205,13 +226,13 @@ async function resolveDevicePortOrExit(explicit) {
205
226
  console.error(' embedded-react dev --device <port>');
206
227
  if (all.length) {
207
228
  console.error('\n Serial ports seen (pick yours):');
208
- for (const p of all)
229
+ for (const port of all)
209
230
  console.error(
210
- ` ${p.path}` +
211
- (p.vendorId && p.productId
212
- ? ` [${p.vendorId}:${p.productId}]`
231
+ ` ${port.path}` +
232
+ (port.vendorId && port.productId
233
+ ? ` [${port.vendorId}:${port.productId}]`
213
234
  : '') +
214
- (p.manufacturer ? ` ${p.manufacturer}` : ''),
235
+ (port.manufacturer ? ` ${port.manufacturer}` : ''),
215
236
  );
216
237
  } else {
217
238
  console.error(
@@ -229,23 +250,31 @@ async function resolveDevicePortOrExit(explicit) {
229
250
  console.error(
230
251
  `✗ found ${matches.length} ESP32 USB-Serial-JTAG ports; pass one explicitly with --device <port>:`,
231
252
  );
232
- for (const p of matches)
253
+ for (const port of matches)
233
254
  console.error(
234
- ` ${preferCalloutPath(p.path)}${p.serialNumber ? ` (SN ${p.serialNumber})` : ''}`,
255
+ ` ${preferCalloutPath(port.path)}${port.serialNumber ? ` (SN ${port.serialNumber})` : ''}`,
235
256
  );
236
257
  process.exit(1);
237
258
  }
238
259
 
239
260
  async function dev(args) {
240
261
  const cwd = process.cwd();
241
- const deviceOpt = optFlagMaybeValue(args, '--device');
262
+ const deviceOption = optFlagMaybeValue(args, '--device');
263
+ const aot = args.includes('--aot');
264
+ if (aot && !deviceOption) {
265
+ console.error(
266
+ '--aot only applies to --device: the simulator runs the app as Flow A.\n',
267
+ );
268
+ usage();
269
+ process.exit(1);
270
+ }
242
271
 
243
272
  // --device [port] → stream the app to a real board over USB on every save (on-device hot reload).
244
273
  // With no port (or `auto`), the ESP32 USB-Serial-JTAG is auto-detected. Otherwise → the WASM simulator.
245
- if (deviceOpt) {
274
+ if (deviceOption) {
246
275
  // The token-after --device is normally the port. But `--device App.jsx` means "auto-detect + this
247
276
  // entry": if the value names an existing file (and isn't a device path), treat it as the entry.
248
- let deviceValue = deviceOpt.value;
277
+ let deviceValue = deviceOption.value;
249
278
  let entryFromDeviceSlot = null;
250
279
  if (
251
280
  deviceValue &&
@@ -259,12 +288,26 @@ async function dev(args) {
259
288
  const explicit =
260
289
  entryFromDeviceSlot ??
261
290
  args.find(
262
- (a, i) =>
263
- !a.startsWith('--') &&
264
- i !== deviceOpt.idx &&
265
- i !== deviceOpt.valueIdx,
291
+ (arg, argIndex) =>
292
+ !arg.startsWith('--') &&
293
+ argIndex !== deviceOption.index &&
294
+ argIndex !== deviceOption.valueIndex,
266
295
  );
267
296
 
297
+ if (aot) {
298
+ const appPath = resolveAppComponent(cwd, explicit);
299
+ const device = await resolveDevicePortOrExit(deviceValue);
300
+ await runDeviceDevServer({
301
+ entry: appPath,
302
+ projectRoot: cwd,
303
+ device,
304
+ label: appPath,
305
+ compilePackage: async () =>
306
+ Buffer.from((await compileAppPackage(cwd, appPath)).file.bytes),
307
+ });
308
+ return;
309
+ }
310
+
268
311
  const simDir = simDirOrExit();
269
312
  const entry = resolveEntry(cwd, explicit);
270
313
  const device = await resolveDevicePortOrExit(deviceValue);
@@ -281,14 +324,18 @@ async function dev(args) {
281
324
  return;
282
325
  }
283
326
 
284
- const portOpt = optValue(args, '--port');
285
- const consumed = new Set(portOpt ? [portOpt.idx, portOpt.valueIdx] : []);
286
- const explicit = args.find((a, i) => !a.startsWith('--') && !consumed.has(i));
327
+ const portOption = optValue(args, '--port');
328
+ const consumed = new Set(
329
+ portOption ? [portOption.index, portOption.valueIndex] : [],
330
+ );
331
+ const explicit = args.find(
332
+ (arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex),
333
+ );
287
334
 
288
335
  const simDir = simDirOrExit();
289
336
  const entry = resolveEntry(cwd, explicit);
290
337
 
291
- const port = portOpt ? parseInt(portOpt.value, 10) : 3333;
338
+ const port = portOption ? parseInt(portOption.value, 10) : DEFAULT_PORT;
292
339
  const outDir = resolve(tmpdir(), 'embedded-react-sim');
293
340
  mkdirSync(outDir, {recursive: true});
294
341
 
@@ -307,16 +354,20 @@ async function dev(args) {
307
354
 
308
355
  async function exportApp(args) {
309
356
  const cwd = process.cwd();
310
- const outIdx = args.indexOf('--out');
311
- const outDir = resolve(cwd, outIdx >= 0 ? args[outIdx + 1] : 'sim-export');
357
+ const outIndex = args.indexOf('--out');
358
+ const outDir = resolve(
359
+ cwd,
360
+ outIndex >= 0 ? args[outIndex + 1] : 'sim-export',
361
+ );
312
362
  const explicit = args.find(
313
- (a, i) => !a.startsWith('--') && (outIdx < 0 || i !== outIdx + 1),
363
+ (arg, argIndex) =>
364
+ !arg.startsWith('--') && (outIndex < 0 || argIndex !== outIndex + 1),
314
365
  );
315
366
 
316
367
  const simDir = simDirOrExit();
317
368
  const entry = resolveEntry(cwd, explicit);
318
- const pub = resolve(outDir, 'public');
319
- mkdirSync(pub, {recursive: true});
369
+ const publicDir = resolve(outDir, 'public');
370
+ mkdirSync(publicDir, {recursive: true});
320
371
 
321
372
  // Bundle the app + bake assets into public/, then drop the prebuilt module + host page alongside.
322
373
  await buildApp({
@@ -324,10 +375,10 @@ async function exportApp(args) {
324
375
  projectRoot: cwd,
325
376
  libSrc: libSrc(),
326
377
  nodePaths: nodePaths(cwd),
327
- outDir: pub,
378
+ outDir: publicDir,
328
379
  });
329
- for (const f of ['embedded-react.js', 'embedded-react.wasm'])
330
- copyFileSync(resolve(simDir, f), resolve(pub, f));
380
+ for (const fileName of ['embedded-react.js', 'embedded-react.wasm'])
381
+ copyFileSync(resolve(simDir, fileName), resolve(publicDir, fileName));
331
382
  copyFileSync(resolve(simDir, 'index.html'), resolve(outDir, 'index.html'));
332
383
 
333
384
  console.log(
@@ -339,39 +390,23 @@ async function exportApp(args) {
339
390
  }
340
391
 
341
392
  /** Resolve the root component file for the AOT compiler (App.jsx), distinct from the registry entry. */
342
- /**
343
- * The project identity stamped into app.gen.h as ER_AOT_DEMO / ER_AOT_DEMO_<name>, which a board example
344
- * guards on (see the header's own comment). It is the directory of the nearest package.json at or above
345
- * the App component, so `demos/watch-face/App.jsx` is `watch-face` whether the build runs from that
346
- * directory or names the entry from somewhere else — and a scaffolded `src/App.jsx` reports its project
347
- * folder rather than `src`. Deriving it from the cwd instead would stamp whatever directory you ran from.
348
- */
349
- function projectIdentity(appPath) {
350
- let dir = dirname(appPath);
351
- for (let i = 0; i < 64; i++) {
352
- // A package.json at a filesystem root has no directory name to report — basename('/') is '' — so
353
- // treat it as absent rather than stamp an empty identity (`ER_AOT_DEMO_` with nothing after it).
354
- if (existsSync(resolve(dir, 'package.json')) && basename(dir))
355
- return basename(dir);
356
- const up = dirname(dir);
357
- if (up === dir) break; // filesystem root
358
- dir = up;
359
- }
360
- return basename(dirname(appPath)) || 'app';
361
- }
362
-
363
393
  function resolveAppComponent(cwd, explicit) {
364
394
  if (explicit) {
365
- const p = resolve(cwd, explicit);
366
- if (!existsSync(p)) {
367
- console.error(`Entry not found: ${p}`);
395
+ const entryPath = resolve(cwd, explicit);
396
+ if (!existsSync(entryPath)) {
397
+ console.error(`Entry not found: ${entryPath}`);
368
398
  process.exit(1);
369
399
  }
370
- return p;
400
+ return entryPath;
371
401
  }
372
- for (const rel of ['App.jsx', 'src/App.jsx', 'App.tsx', 'src/App.tsx']) {
373
- const p = resolve(cwd, rel);
374
- if (existsSync(p)) return p;
402
+ for (const relativePath of [
403
+ 'App.jsx',
404
+ 'src/App.jsx',
405
+ 'App.tsx',
406
+ 'src/App.tsx',
407
+ ]) {
408
+ const entryPath = resolve(cwd, relativePath);
409
+ if (existsSync(entryPath)) return entryPath;
375
410
  }
376
411
  console.error(
377
412
  'No App component found. Pass one explicitly: embedded-react build --aot <App.jsx>',
@@ -379,66 +414,109 @@ function resolveAppComponent(cwd, explicit) {
379
414
  process.exit(1);
380
415
  }
381
416
 
382
- /** Flow B (--aot): compile the App component to C (app.gen.{c,h}) + bake assets, to compile into firmware. */
383
- async function buildAot(cwd, explicit, outDir, screen) {
384
- const {compileSource, bakeSvgArtifacts} = await import('./aot/compile.mjs');
385
- const {bakeAssets} = await import('./assets/index.mjs');
417
+ /**
418
+ * Compiles the App component with what goes into the build: its package file and its image jobs.
419
+ * Throws with the reason, so a watch loop can carry on past a bad save.
420
+ */
421
+ async function compileAppPackage(
422
+ cwd,
423
+ appPath,
424
+ {screens = null, release = false} = {},
425
+ ) {
426
+ const {compilePackage, bakeSvgArtifacts, packPackage} =
427
+ await import('./aot/compile.mjs');
428
+ const {bakeAssetPackBytes} = await import('./assets/index.mjs');
386
429
  const {warnMissingGlyphs} = await import('./assets/glyph-coverage.mjs');
387
430
  const {analyzeFontSizes, warnFontSizes} =
388
431
  await import('./assets/font-sizes.mjs');
389
- const appPath = resolveAppComponent(cwd, explicit);
390
432
  const appDir = dirname(appPath);
391
- const src = readFileSync(appPath, 'utf8');
392
- let result;
393
- try {
394
- // Bake <Svg source> .svg imports → vector artifacts (incl. gradients), then compile with them in hand.
395
- const svgArtifacts = await bakeSvgArtifacts(src, appDir);
396
- // app.gen.h records WHICH app it came from and a board example guards on that marker, so it must name
397
- // the source project — the same ER_AOT_DEMO_watch_2d_face that `npm run aot -- watch-face` produces.
398
- // The target panel size (--screen <WxH>) folds a responsive app's `screen.width` branch to the one
399
- // that the board renders. Without it, the compiler falls back to ER_AOT_SCREEN_W/H, then 800x480.
400
- result = compileSource(src, projectIdentity(appPath), {
401
- filename: appPath,
402
- svgArtifacts,
403
- screen, // null without --screen
404
- });
405
- } catch (e) {
406
- console.error(e && e.aotLoc ? e.message : e?.message || String(e));
407
- process.exit(1);
408
- }
409
- writeFileSync(resolve(outDir, 'app.gen.c'), result.c);
410
- writeFileSync(resolve(outDir, 'app.gen.h'), result.h);
433
+ const source = readFileSync(appPath, 'utf8');
434
+ // Bake <Svg source> .svg imports → vector artifacts (incl. gradients), then compile with them in hand.
435
+ const svgArtifacts = await bakeSvgArtifacts(source, appDir);
436
+ // A package has every layout the app's breakpoints call for, and --screen <WxH>,<WxH> keeps only those the
437
+ // sizes pick.
438
+ const result = compilePackage(source, basename(dirname(appPath)), {
439
+ filename: appPath,
440
+ svgArtifacts,
441
+ screen: screens?.[0] ?? null, // null without --screen
442
+ screens,
443
+ release,
444
+ });
411
445
 
412
446
  // Optional per-image overrides (same file the JS flows read): assets.config.js
413
447
  // export default { images: { 'bg': { format: 'rgb565' } } }
414
- let cfg = {};
415
- const cp = resolve(cwd, 'assets.config.js');
416
- if (existsSync(cp))
417
- cfg = (await import(pathToFileURL(cp).href)).default || {};
418
- const imageConfig = cfg.images || {};
419
-
420
- const imageJobs = result.images.map(im => ({
421
- name: im.name,
422
- path: resolve(appDir, im.importPath),
423
- format: imageConfig[im.name]?.format,
448
+ let assetsConfig = {};
449
+ const assetsConfigPath = resolve(cwd, 'assets.config.js');
450
+ if (existsSync(assetsConfigPath))
451
+ assetsConfig =
452
+ (
453
+ await import(
454
+ `${pathToFileURL(assetsConfigPath).href}?t=${statSync(assetsConfigPath).mtimeMs}`
455
+ )
456
+ ).default || {};
457
+ const imageConfig = assetsConfig.images || {};
458
+
459
+ const imageJobs = result.images.map(image => ({
460
+ name: image.name,
461
+ path: resolve(appDir, image.importPath),
462
+ format: imageConfig[image.name]?.format,
424
463
  }));
425
- for (const j of imageJobs) {
426
- if (!existsSync(j.path)) {
427
- console.error(`<Image> asset "${j.name}" not found at ${j.path}`);
428
- process.exit(1);
464
+ for (const job of imageJobs) {
465
+ if (!existsSync(job.path)) {
466
+ throw new Error(`<Image> asset "${job.name}" not found at ${job.path}`);
429
467
  }
430
468
  }
431
469
  // Flow B renders everything in the engine's built-in font (no font imports) — check the app's text
432
470
  // and its font sizes against what that font actually covers.
433
- warnMissingGlyphs({source: src, jsx: true});
434
- warnFontSizes({used: analyzeFontSizes(src)});
435
- const baked = bakeAssets({images: imageJobs, fonts: [], outDir});
436
- console.log(
437
- `✓ Flow B (AOT) → ${relative(cwd, outDir) || '.'}/app.gen.c (+ app.gen.h, assets.generated.c — ${baked.images} image(s))`,
471
+ warnMissingGlyphs({source, jsx: true});
472
+ warnFontSizes({used: analyzeFontSizes(source)});
473
+ const file = packPackage(
474
+ result,
475
+ imageJobs.length ? bakeAssetPackBytes({images: imageJobs}) : undefined,
476
+ );
477
+ return {result, file, imageJobs};
478
+ }
479
+
480
+ /**
481
+ * Flow B (--aot): compile the App component to a Flow B package (app.erpkg) with its assets inside, for the Flow B
482
+ * runtime to load: for release without its debug table (app.erdbg beside it), and baked as a const array
483
+ * (app.erpkg.c) to link into the firmware.
484
+ */
485
+ async function buildAot(
486
+ cwd,
487
+ explicit,
488
+ outDir,
489
+ screens,
490
+ {release = false, bake = false} = {},
491
+ ) {
492
+ const {bakePackage, resourceReport} = await import('./aot/compile.mjs');
493
+ const appPath = resolveAppComponent(cwd, explicit);
494
+ let compiled;
495
+ try {
496
+ compiled = await compileAppPackage(cwd, appPath, {screens, release});
497
+ } catch (error) {
498
+ console.error(
499
+ error && error.aotLoc ? error.message : error?.message || String(error),
500
+ );
501
+ process.exit(1);
502
+ }
503
+ const {result, file, imageJobs} = compiled;
504
+ const displayDir = relative(cwd, outDir) || '.';
505
+ const name = bake ? 'app.erpkg.c' : 'app.erpkg';
506
+ writeFileSync(
507
+ resolve(outDir, name),
508
+ bake ? bakePackage(file.bytes) : file.bytes,
438
509
  );
439
510
  console.log(
440
- ' No QuickJS on the device: compile these into your firmware against the engine (er_scene.h).',
511
+ `✓ Flow B package → ${displayDir}/${name} (${release ? 'release' : 'debug'}, ${imageJobs.length} image(s))`,
441
512
  );
513
+ if (release) {
514
+ writeFileSync(resolve(outDir, 'app.erdbg'), result.debug);
515
+ console.log(
516
+ ` Debug table → ${displayDir}/app.erdbg (${result.debug.length} B), to map a fault back to the source`,
517
+ );
518
+ }
519
+ console.log(resourceReport(result, file).join('\n'));
442
520
  }
443
521
 
444
522
  /**
@@ -453,13 +531,13 @@ async function buildAot(cwd, explicit, outDir, screen) {
453
531
  async function buildContainer(cwd, explicit, outDir) {
454
532
  const simDir = simDirOrExit();
455
533
  const entry = resolveEntry(cwd, explicit);
456
- const lib = libSrc();
534
+ const librarySource = libSrc();
457
535
  const paths = nodePaths(cwd);
458
536
 
459
537
  // Release artifact: strip the embedded source text + debug tables from the bytecode (~8x smaller
460
538
  // erpkg; stack traces lose line numbers). The dev loop (`embedded-react dev`) keeps them.
461
539
  const vendor = await packVendor({
462
- libSrc: lib,
540
+ libSrc: librarySource,
463
541
  nodePaths: paths,
464
542
  simDir,
465
543
  strip: true,
@@ -467,7 +545,7 @@ async function buildContainer(cwd, explicit, outDir) {
467
545
  const app = await packApp({
468
546
  entry,
469
547
  projectRoot: cwd,
470
- libSrc: lib,
548
+ libSrc: librarySource,
471
549
  nodePaths: paths,
472
550
  simDir,
473
551
  strip: true,
@@ -480,9 +558,9 @@ async function buildContainer(cwd, explicit, outDir) {
480
558
 
481
559
  const outPath = resolve(outDir, 'app.erpkg');
482
560
  writeFileSync(outPath, container);
483
- const kb = n => `${(n / 1024).toFixed(1)} KB`;
561
+ const kb = byteCount => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
484
562
  console.log(
485
- `✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QJS_TAG}, ` +
563
+ `✓ Flow A → ${relative(cwd, outPath) || 'app.erpkg'} (${kb(container.length)}; qjs ${QUICKJS_TAG}, ` +
486
564
  `vendor ${kb(vendor.bytecodeLen)} + app ${kb(app.bytecodeLen)}` +
487
565
  (app.assetsLen ? `, assets ${kb(app.assetsLen)}` : '') +
488
566
  ')',
@@ -495,18 +573,30 @@ async function buildContainer(cwd, explicit, outDir) {
495
573
  );
496
574
  }
497
575
 
498
- /** `embedded-react build [--aot] [entry] [--out dir] [--screen WxH]` — produce the device artifact. */
576
+ /**
577
+ * `embedded-react build [--aot [--release] [--bake]] [entry] [--out dir] [--screen WxH[,WxH…]]` — produce the
578
+ * device artifact.
579
+ */
499
580
  async function build(args) {
500
581
  const cwd = process.cwd();
501
582
  const aot = args.includes('--aot');
502
- const outIdx = args.indexOf('--out');
503
- const outDir = resolve(cwd, outIdx >= 0 ? args[outIdx + 1] : 'dist');
504
-
505
- // --screen <WxH> (AOT only): the target panel size, baked so a responsive app folds to the branch that
506
- // board renders (e.g., 240x320 → the compact layout). Flow A reads the screen from the host at runtime.
507
- const screenIdx = args.indexOf('--screen');
508
- let screen = null;
509
- if (screenIdx >= 0) {
583
+ const release = args.includes('--release');
584
+ const bake = args.includes('--bake');
585
+ for (const flag of ['--release', '--bake']) {
586
+ if (args.includes(flag) && !aot) {
587
+ console.error(`${flag} only applies to --aot.\n`);
588
+ usage();
589
+ process.exit(1);
590
+ }
591
+ }
592
+ const outIndex = args.indexOf('--out');
593
+ const outDir = resolve(cwd, outIndex >= 0 ? args[outIndex + 1] : 'dist');
594
+
595
+ // --screen <WxH> (AOT only): the panels to keep layouts for, comma-separated. Optional: a package has every
596
+ // layout without it. Flow A reads the screen from the host at runtime.
597
+ const screenIndex = args.indexOf('--screen');
598
+ let screens = null;
599
+ if (screenIndex >= 0) {
510
600
  if (!aot) {
511
601
  console.error(
512
602
  '--screen only applies to --aot (Flow A reads the panel size from the host at runtime).\n',
@@ -514,40 +604,137 @@ async function build(args) {
514
604
  usage();
515
605
  process.exit(1);
516
606
  }
517
- const raw = args[screenIdx + 1];
518
- const m = raw && /^([1-9]\d*)x([1-9]\d*)$/i.exec(raw);
519
- if (!m) {
607
+ const screenList = args[screenIndex + 1];
608
+ const sizes = (screenList ?? '')
609
+ .split(',')
610
+ .map(size => /^([1-9]\d*)x([1-9]\d*)$/i.exec(size));
611
+ if (!screenList || sizes.some(size => !size)) {
520
612
  console.error(
521
- `--screen expects <width>x<height> (e.g. --screen 240x320), got: ${raw ?? '(nothing)'}\n`,
613
+ `--screen expects <width>x<height> (e.g. --screen 240x320), got: ${screenList ?? '(nothing)'}\n`,
522
614
  );
523
615
  usage();
524
616
  process.exit(1);
525
617
  }
526
- screen = {width: Number(m[1]), height: Number(m[2])};
618
+ screens = sizes.map(size => ({
619
+ width: Number(size[1]),
620
+ height: Number(size[2]),
621
+ }));
527
622
  }
528
623
 
529
624
  // Consume the flag VALUES so they aren't mistaken for the entry (which is a bare, non-`--` token).
530
625
  const consumed = new Set();
531
- if (outIdx >= 0) consumed.add(outIdx + 1);
532
- if (screenIdx >= 0) consumed.add(screenIdx + 1);
533
- const explicit = args.find((a, i) => !a.startsWith('--') && !consumed.has(i));
626
+ if (outIndex >= 0) consumed.add(outIndex + 1);
627
+ if (screenIndex >= 0) consumed.add(screenIndex + 1);
628
+ const explicit = args.find(
629
+ (arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex),
630
+ );
534
631
 
535
632
  mkdirSync(outDir, {recursive: true});
536
- if (aot) await buildAot(cwd, explicit, outDir, screen);
633
+ if (aot) await buildAot(cwd, explicit, outDir, screens, {release, bake});
537
634
  else await buildContainer(cwd, explicit, outDir);
538
635
  }
539
636
 
540
- const [cmd, ...rest] = process.argv.slice(2);
541
- if (cmd === 'dev') {
542
- await dev(rest);
543
- } else if (cmd === 'export') {
544
- await exportApp(rest);
545
- } else if (cmd === 'build') {
546
- await build(rest);
547
- } else if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') {
637
+ /** Reads the package a `pack` or `flash` names, or dist/app.erpkg; exits saying how to build one when it's missing. */
638
+ function readPackageOrExit(cwd, explicit) {
639
+ const path = resolve(cwd, explicit ?? 'dist/app.erpkg');
640
+ if (!existsSync(path)) {
641
+ console.error(
642
+ `No package at ${path}. Build one with: embedded-react build --aot`,
643
+ );
644
+ process.exit(1);
645
+ }
646
+ return readFileSync(path);
647
+ }
648
+
649
+ /** The bare arguments, once the values of the listed flags are set aside. */
650
+ function bareArgs(args, flagsWithValues) {
651
+ const consumed = new Set();
652
+ for (const flag of flagsWithValues) {
653
+ const flagIndex = args.indexOf(flag);
654
+ if (flagIndex >= 0) consumed.add(flagIndex + 1);
655
+ }
656
+ return args.filter(
657
+ (arg, argIndex) => !arg.startsWith('--') && !consumed.has(argIndex),
658
+ );
659
+ }
660
+
661
+ /** `embedded-react pack [package] --board <name> [--slot a|b] [--sequence n] [--out dir]` */
662
+ function pack(args) {
663
+ const cwd = process.cwd();
664
+ const boardName = optValue(args, '--board')?.value;
665
+ const outDir = resolve(cwd, optValue(args, '--out')?.value ?? 'dist');
666
+ const sequence = Number(optValue(args, '--sequence')?.value ?? 1);
667
+ try {
668
+ const board = boardByName(boardName);
669
+ const [explicit] = bareArgs(args, [
670
+ '--board',
671
+ '--slot',
672
+ '--sequence',
673
+ '--out',
674
+ ]);
675
+ mkdirSync(outDir, {recursive: true});
676
+ const packed = packSlot({
677
+ packageBytes: readPackageOrExit(cwd, explicit),
678
+ board,
679
+ boardName,
680
+ slotName: optValue(args, '--slot')?.value,
681
+ sequence,
682
+ outDir,
683
+ });
684
+ console.log(
685
+ `✓ Slot ${packed.slot}, sequence ${packed.sequence} → ${relative(cwd, packed.file)}, for flash address 0x${packed.address.toString(16)}`,
686
+ );
687
+ } catch (error) {
688
+ console.error(error.message);
689
+ process.exit(1);
690
+ }
691
+ }
692
+
693
+ /** `embedded-react flash [package] --board <name> [--port p]` */
694
+ function flash(args) {
695
+ const cwd = process.cwd();
696
+ const boardName = optValue(args, '--board')?.value;
697
+ try {
698
+ const board = boardByName(boardName);
699
+ const [explicit] = bareArgs(args, ['--board', '--port']);
700
+ const written = flashSlot({
701
+ packageBytes: readPackageOrExit(cwd, explicit),
702
+ board,
703
+ port: optValue(args, '--port')?.value,
704
+ log: line => console.log(line),
705
+ });
706
+ console.log(
707
+ `✓ Package written to slot ${written.slot}, sequence ${written.sequence}. The board runs it at its next boot if it passes verification` +
708
+ (written.lastGood
709
+ ? `, and slot ${written.lastGood} stays as the last good package.`
710
+ : '.'),
711
+ );
712
+ } catch (error) {
713
+ console.error(error.message);
714
+ process.exit(1);
715
+ }
716
+ }
717
+
718
+ const [command, ...commandArgs] = process.argv.slice(2);
719
+ if (command === 'dev') {
720
+ await dev(commandArgs);
721
+ } else if (command === 'export') {
722
+ await exportApp(commandArgs);
723
+ } else if (command === 'build') {
724
+ await build(commandArgs);
725
+ } else if (command === 'pack') {
726
+ pack(commandArgs);
727
+ } else if (command === 'flash') {
728
+ flash(commandArgs);
729
+ } else if (
730
+ !command ||
731
+ command === '--help' ||
732
+ command === '-h' ||
733
+ command === 'help'
734
+ ) {
548
735
  usage();
549
736
  } else {
550
- console.error(`Unknown command: ${cmd}\n`);
737
+ console.error(`Unknown command: ${command}\n`);
551
738
  usage();
552
739
  process.exit(1);
553
740
  }