embedded-react 0.18.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 (117) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +8 -4
  3. package/aot/compile.mjs +178 -58
  4. package/aot/compiler/animations.mjs +290 -281
  5. package/aot/compiler/boot.mjs +70 -33
  6. package/aot/compiler/branch-merge.mjs +4 -3
  7. package/aot/compiler/check.mjs +9 -9
  8. package/aot/compiler/collect.mjs +324 -205
  9. package/aot/compiler/control-flow.mjs +209 -197
  10. package/aot/compiler/diagnostics.mjs +22 -25
  11. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  12. package/aot/compiler/elements/dial.mjs +91 -77
  13. package/aot/compiler/elements/flat-list.mjs +24 -22
  14. package/aot/compiler/elements/image.mjs +51 -50
  15. package/aot/compiler/elements/modal.mjs +31 -30
  16. package/aot/compiler/elements/props.mjs +23 -23
  17. package/aot/compiler/elements/switch.mjs +42 -34
  18. package/aot/compiler/elements/text-input.mjs +34 -32
  19. package/aot/compiler/expressions.mjs +372 -333
  20. package/aot/compiler/handlers.mjs +473 -387
  21. package/aot/compiler/ir/functions.mjs +11 -1
  22. package/aot/compiler/ir/nodes.mjs +4 -4
  23. package/aot/compiler/ir/reads.mjs +19 -19
  24. package/aot/compiler/ir/types.mjs +14 -14
  25. package/aot/compiler/ir/vectors.mjs +5 -1
  26. package/aot/compiler/keyboard.mjs +17 -7
  27. package/aot/compiler/lower.mjs +77 -80
  28. package/aot/compiler/nodes.mjs +169 -152
  29. package/aot/compiler/options.mjs +35 -30
  30. package/aot/compiler/out.mjs +18 -22
  31. package/aot/compiler/package/animations.mjs +669 -0
  32. package/aot/compiler/package/arena.mjs +252 -0
  33. package/aot/compiler/package/assemble.mjs +177 -0
  34. package/aot/compiler/package/bytecode.mjs +286 -0
  35. package/aot/compiler/package/checks.mjs +1022 -0
  36. package/aot/compiler/package/codegen.mjs +1329 -0
  37. package/aot/compiler/package/enums.mjs +138 -0
  38. package/aot/compiler/package/format.mjs +760 -0
  39. package/aot/compiler/package/layouts.mjs +136 -0
  40. package/aot/compiler/package/lower.mjs +1606 -0
  41. package/aot/compiler/package/props.mjs +118 -0
  42. package/aot/compiler/package/tables.mjs +103 -0
  43. package/aot/compiler/package/vectors.mjs +502 -0
  44. package/aot/compiler/package/writer.mjs +664 -0
  45. package/aot/compiler/pan-responder.mjs +69 -61
  46. package/aot/compiler/parse.mjs +21 -21
  47. package/aot/compiler/static-eval.mjs +25 -23
  48. package/aot/compiler/style-text.mjs +161 -172
  49. package/aot/compiler/svg.mjs +477 -251
  50. package/aot/screenshot-smoke.mjs +55 -41
  51. package/aot/style-map.mjs +102 -90
  52. package/assets/bake-font.mjs +123 -77
  53. package/assets/bake-image.mjs +39 -22
  54. package/assets/bake-svg.mjs +361 -262
  55. package/assets/build-builtin-font.mjs +14 -10
  56. package/assets/emit-c.mjs +83 -62
  57. package/assets/emit-container.mjs +124 -38
  58. package/assets/emit-pack.mjs +77 -67
  59. package/assets/font-config.mjs +9 -6
  60. package/assets/font-sizes.mjs +163 -123
  61. package/assets/glyph-coverage.mjs +74 -54
  62. package/assets/index.mjs +31 -9
  63. package/assets/rasterize.mjs +126 -99
  64. package/assets/svg-loader.mjs +8 -8
  65. package/build.mjs +16 -14
  66. package/cli.mjs +359 -172
  67. package/compile-bin.mjs +5 -5
  68. package/flash.mjs +537 -0
  69. package/hotreload/dev-device.mjs +90 -33
  70. package/hotreload/pack-app.mjs +55 -43
  71. package/hotreload/pack-split.mjs +46 -37
  72. package/hotreload/package-transfer.mjs +175 -0
  73. package/hotreload/protocol.mjs +51 -38
  74. package/hotreload/uploader.mjs +38 -27
  75. package/hotreload/watch-tree.mjs +19 -19
  76. package/pack-container.mjs +31 -23
  77. package/package.json +11 -12
  78. package/persist-transform.mjs +34 -28
  79. package/qjsc-wasm.mjs +25 -14
  80. package/sim/embedded-react.cjs +1 -1
  81. package/sim/embedded-react.js +1 -1
  82. package/sim/embedded-react.wasm +0 -0
  83. package/sim/index.html +94 -85
  84. package/sim-server.mjs +101 -82
  85. package/src/embedded-react/Animated.js +24 -24
  86. package/src/embedded-react/Easing.js +1 -1
  87. package/src/embedded-react/FlatList.js +4 -4
  88. package/src/embedded-react/LayoutAnimation.js +8 -5
  89. package/src/embedded-react/PanResponder.js +75 -71
  90. package/src/embedded-react/Pressable.js +2 -8
  91. package/src/embedded-react/SectionList.js +6 -6
  92. package/src/embedded-react/StyleSheet.js +4 -3
  93. package/src/embedded-react/TouchableOpacity.js +13 -8
  94. package/src/embedded-react/index.d.ts +5 -5
  95. package/src/embedded-react/layout-anim-config.js +10 -4
  96. package/src/embedded-react/list-child.js +5 -5
  97. package/src/embedded-react/named-colors.js +1 -1
  98. package/src/embedded-react/split-style.js +11 -11
  99. package/src/embedded-react/svg-ops.js +760 -593
  100. package/src/embedded-react/useHostValue.js +3 -3
  101. package/src/embedded-react/usePersistentState.js +6 -6
  102. package/src/embedded-react/warn-props.js +1 -1
  103. package/src/host-config.js +60 -53
  104. package/src/props.js +49 -41
  105. package/src/renderer.js +7 -4
  106. package/aot/compiler/assemble.mjs +0 -944
  107. package/aot/compiler/c/animations.mjs +0 -436
  108. package/aot/compiler/c/boot.mjs +0 -127
  109. package/aot/compiler/c/expressions.mjs +0 -270
  110. package/aot/compiler/c/functions.mjs +0 -268
  111. package/aot/compiler/c/keyboard.mjs +0 -96
  112. package/aot/compiler/c/nodes.mjs +0 -303
  113. package/aot/compiler/c/pan-responder.mjs +0 -136
  114. package/aot/compiler/c/statements.mjs +0 -319
  115. package/aot/compiler/c/text.mjs +0 -83
  116. package/aot/compiler/c/vectors.mjs +0 -381
  117. package/aot/compiler/c-syntax.mjs +0 -127
package/NOTICE CHANGED
@@ -48,7 +48,7 @@ under their own respective licenses and copyrights:
48
48
  Used by the Flow A bridge to drive the native engine.
49
49
 
50
50
  The embedded-react public API (e.g. the View / Text / Pressable / Animated /
51
- StyleSheet modules under bridges/quickjs/js/src/embedded-react/) is an original,
51
+ StyleSheet modules under packages/embedded-react/src/embedded-react/) is an original,
52
52
  independent reimplementation inspired by the React Native API surface. It is not
53
53
  derived from or copied out of React Native's source, and is the original work of
54
54
  Cory Lamming.
package/README.md CHANGED
@@ -36,9 +36,13 @@ The package is the React Native analog: hooks come from `react`, everything else
36
36
  | Command | What it does |
37
37
  |---|---|
38
38
  | `npx embedded-react dev` | Runs your app in the browser simulator with hot reload; the engine `.wasm` ships prebuilt, so there is no native toolchain |
39
- | `npx embedded-react dev --device` | The same, streamed to a connected board over USB (a firmware built with hot reload) |
39
+ | `npx embedded-react dev --device` | The same, streamed to a connected board over USB (a firmware built with hot reload). `--aot` sends Flow B packages |
40
40
  | `npx embedded-react build` | The Flow A device artifact, `dist/app.erpkg` (bytecode + baked assets + CRC) |
41
- | `npx embedded-react build --aot --screen WxH` | The Flow B artifact, `app.gen.c` + `assets.generated.c`, to compile into firmware |
41
+ | `npx embedded-react build --aot` | A Flow B package, `dist/app.erpkg`, for the Flow B runtime to load. State, handlers, timers, effects, lists, animations, PanResponder, `<Svg>` and the keyboard config. It holds every layout the app's breakpoints call for, and `--screen 240x320,320x240` keeps only the ones those sizes pick |
42
+ | `npx embedded-react build --aot --release` | A Flow B package for release, without its debug table, which goes beside it as `dist/app.erdbg` |
43
+ | `npx embedded-react build --aot --bake` | A Flow B package as a C array, `dist/app.erpkg.c`, to link into firmware with no spare partition |
44
+ | `npx embedded-react flash --board NAME` | Writes `dist/app.erpkg` to the board's staging slot, through `esptool` or `picotool`. The last good package stays until the new one passes verification |
45
+ | `npx embedded-react pack --board NAME` | Writes a slot's image to a file, as a UF2 on the RP2040, for a factory line or a board that isn't attached |
42
46
  | `npx embedded-react export` | A self-contained static copy of the simulator with your app, for any static host |
43
47
 
44
48
  ## Where to read more
@@ -52,7 +56,7 @@ The package is the React Native analog: hooks come from `react`, everything else
52
56
 
53
57
  ## Part of a monorepo
54
58
 
55
- This package is the `bridges/quickjs/js` folder of the
59
+ This package is the `packages/embedded-react` folder of the
56
60
  [Embedded React](https://github.com/TheMasterCoder007/embedded-react) repository. The C engine, the
57
61
  hardware backends, the board examples, the demo apps and the simulators live there, and the engine is
58
62
  distributed separately as C source (CMake `FetchContent`, the ESP-IDF Component Registry, PlatformIO)
@@ -67,7 +71,7 @@ build one of the apps in `demos/` against the in-repo library, `npm test` runs t
67
71
  ```
68
72
  src/embedded-react/ the public package surface (components, StyleSheet, Animated, PanResponder, hooks)
69
73
  src/host-config.js the react-reconciler host config → NativeUI.* (the C bridge)
70
- aot/ the Flow B JSX→C compiler
74
+ aot/ the Flow B JSX→package compiler
71
75
  assets/ build-time bakers: images, fonts, SVG, the ERPK container writer
72
76
  cli.mjs, sim-server.mjs the `embedded-react` CLI and the shared simulator dev server
73
77
  sim/ the prebuilt engine .wasm the simulator runs
package/aot/compile.mjs CHANGED
@@ -14,41 +14,40 @@
14
14
  * limitations under the License.
15
15
  */
16
16
  /*
17
- * `npm run aot [demo]` — the Flow B ahead-of-time compiler (vertical slice).
17
+ * `npm run aot [demo]` — the Flow B ahead-of-time compiler.
18
18
  *
19
- * Compiles a demo's JSX straight to C against er_scene.h: no QuickJS, no JS at runtime. The generated
20
- * app.gen.c builds the engine node tree directly and wires state + events, so it fits an MCU with only
19
+ * Compiles a demo's JSX to a package (dist/app.erpkg) that the Flow B runtime verifies and runs: no QuickJS, no JS
20
+ * at runtime. The program builds the engine node tree and wires state + events, so it fits an MCU with only
21
21
  * internal RAM.
22
22
  *
23
23
  * Supported subset (grows demo by demo; unsupported syntax throws "AOT: ..."):
24
24
  * - View / Text / Pressable / TouchableOpacity / Image / ScrollView elements
25
25
  * - StyleSheet + inline styles → ERProps (static values)
26
26
  * - text with literal + {interpolation} segments (interpolations may reference state)
27
- * - useState(initial) → C state; on* handlers (onPress/onPressIn/onPressOut/onLongPress) → C functions
28
- * - setState(value) and setState(prev => expr); a small C expression subset (literals, identifiers,
27
+ * - useState(initial) → state slots; on* handlers (onPress/onPressIn/onPressOut/onLongPress) → functions
28
+ * - setState(value) and setState(prev => expr); a small expression subset (literals, identifiers,
29
29
  * + - * / %, comparisons, ?:)
30
30
  *
31
31
  * The compiler tracks which nodes depend on which state, so a state change re-sets ONLY the dependent
32
- * nodes (er_node_set_props) — no diffing, no reconciler. See the root README (Flow B).
32
+ * nodes — no diffing, no reconciler. See the root README (Flow B).
33
33
  *
34
34
  * npm run aot # default demo (thermostat) — but use a minimal demo for the slice
35
35
  * npm run aot -- watch-face # a specific demo by folder name
36
+ * npm run aot -- <demo> --screen 240x320 # the panels the package keeps layouts for
36
37
  *
37
- * This file is the entry: compileSource(src) compiles a source string (pure, so it can be unit-tested on
38
- * inline JSX), and the CLI at the bottom reads a demo's App.jsx and writes dist/app.gen.{c,h}. The
38
+ * This file is the entry: compilePackage(src) compiles a source string (pure, so it can be unit-tested on
39
+ * inline JSX), and the CLI at the bottom reads a demo's App.jsx and writes dist/app.erpkg. The
39
40
  * compiler itself lives in compiler/, one module per stage. The pipeline: parse the App.jsx → collect
40
41
  * the module's component, state, hooks & refs → lower each piece (expressions, styles/text, handlers,
41
- * nodes) → write the lowered app as app.gen.c.
42
+ * nodes) → write the lowered app as a package.
42
43
  *
43
44
  * compiler/options.mts resolveOptions — screen size + buffer caps, from opts, then ER_AOT_*
44
45
  * compiler/types.mts the types the stages share (Env, StatementContext, state/ref records)
45
46
  * compiler/out.mts Out — the handlers, effects and drawings lowering collects
46
47
  * compiler/diagnostics.mts aotError / withLoc / formatAotError — locate + hint unsupported syntax
47
48
  * compiler/static-eval.mts evalStatic — fold the compile-time-constant subset (styles, initials)
48
- * compiler/c-syntax.mts cstr / floatLit / i64Lit — JS values spelled as C
49
49
  * compiler/expressions.mts lowerExprWide — lower a JS expression (state/props/refs) to the IR
50
50
  * compiler/ir/*.mts the IR the stages lower to (ir/app.mts: the whole lowered app)
51
- * compiler/c/*.mts the C backend: prints the IR as C (emitExpr returns it as a CExpr)
52
51
  * compiler/parse.mts parseApp — JSX/TSX source → AST (types stripped, `undefined` normalized)
53
52
  * compiler/collect.mts moduleScope + collect{State, Components, Callbacks, Memos, Effects}
54
53
  * compiler/animations.mts collect{Anims,Refs}, Easing, interpolate, Animated.start() chains
@@ -62,7 +61,7 @@
62
61
  * compiler/keyboard.mts setKeyboardConfig({...}) → the keyboard config
63
62
  * compiler/lower.mts lowerApp — run the stages above over the parsed app
64
63
  * compiler/check.mts the check pass — the values lowering recorded, checked in order
65
- * compiler/assemble.mts writeApp — write the lowered app as app.gen.{c,h}
64
+ * compiler/package/*.mts the package backend: the IR as a Flow B program, its container and report
66
65
  *
67
66
  * The compiler is TypeScript (.mts), which Node runs by stripping the types. tools/stage-npm-package.mjs
68
67
  * compiles it to JavaScript for the npm package.
@@ -71,40 +70,42 @@
71
70
  - Imports
72
71
  ---------------------------------------------------------------------------------------------------------------------*/
73
72
  import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, } from 'node:fs';
74
- import { resolve, dirname } from 'node:path';
73
+ import { basename, resolve, dirname } from 'node:path';
75
74
  import { fileURLToPath } from 'node:url';
76
- import { bakeAssets } from '../assets/index.mjs';
75
+ import { bakeAssetPackBytes } from '../assets/index.mjs';
77
76
  import { warnMissingGlyphs } from '../assets/glyph-coverage.mjs';
78
77
  import { analyzeFontSizes, warnFontSizes } from '../assets/font-sizes.mjs';
79
78
  import { formatAotError } from './compiler/diagnostics.mjs';
80
79
  import { resolveOptions } from './compiler/options.mjs';
81
80
  import { bakeSvgArtifacts } from './compiler/collect.mjs';
82
- import { demoMarker, compileSourceImpl } from './compiler/assemble.mjs';
83
81
  import { inferWideSlots, sameSlotWidths } from './compiler/expressions.mjs';
82
+ import { assemblePackage, bakePackage, compilePanel, packPackage, resourceReport, } from './compiler/package/assemble.mjs';
83
+ import { MAX_LAYOUTS, runCheck } from './compiler/package/checks.mjs';
84
+ import { SizeSearch } from './compiler/package/layouts.mjs';
84
85
  /*----------------------------------------------------------------------------------------------------------------------
85
86
  - Constants
86
87
  ---------------------------------------------------------------------------------------------------------------------*/
87
- const aotDir = dirname(fileURLToPath(import.meta.url)); // bridges/quickjs/js/aot
88
- const repoRoot = resolve(aotDir, '../../../..');
89
- const demosDir = resolve(repoRoot, 'demos');
90
- const distDir = resolve(aotDir, '..', 'dist');
88
+ const aotDirectory = dirname(fileURLToPath(import.meta.url)); // packages/embedded-react/aot
89
+ const repositoryRoot = resolve(aotDirectory, '../../..');
90
+ const demosDirectory = resolve(repositoryRoot, 'demos');
91
+ const distDirectory = resolve(aotDirectory, '..', 'dist');
92
+ /** Where the search for an app's layouts starts. */
93
+ const FIRST_SIZE = { width: 240, height: 320 };
91
94
  /*----------------------------------------------------------------------------------------------------------------------
92
95
  - Implementation
93
96
  ---------------------------------------------------------------------------------------------------------------------*/
94
- export { bakeSvgArtifacts, demoMarker };
97
+ export { bakePackage, bakeSvgArtifacts, packPackage, resourceReport };
95
98
  /**
96
99
  * A state or ref slot is typed from its initial value, so `useState(0)` is an int until a setter stores
97
- * Date.now() in it. A compile records every value stored into an int slot (env.stores), and the typing pass
100
+ * Date.now() in it. A compile records every value stored into an int slot (environment.stores), and the typing pass
98
101
  * infers from them which slots have to hold 64 bits, following a timestamp through every slot it reaches; the
99
102
  * app is then compiled again with those slots widened, so every read of a slot sees its final type.
100
103
  *
101
- * @param src The App.jsx/App.tsx source text.
102
- * @param demo Demo name (only used in the generated-by header comment).
103
- * @param opts compileSource's options, resolved (see resolveOptions).
104
+ * @param compileOnce One compile with the given slots widened, recording the values stored into int slots.
104
105
  *
105
- * @returns The generated app.gen.c and app.gen.h, and what they contain.
106
+ * @returns What the last compile produced.
106
107
  */
107
- function compileWidened(src, demo, opts) {
108
+ function compileWidened(compileOnce) {
108
109
  // The slots found so far that need 64 bits; every pass compiles with all of them widened.
109
110
  let wide = new Map();
110
111
  for (;;) {
@@ -113,7 +114,7 @@ function compileWidened(src, demo, opts) {
113
114
  let result;
114
115
  let error;
115
116
  try {
116
- result = compileSourceImpl(src, demo, opts, wide, stores);
117
+ result = compileOnce(wide, stores);
117
118
  }
118
119
  catch (caught) {
119
120
  error = caught;
@@ -130,38 +131,158 @@ function compileWidened(src, demo, opts) {
130
131
  }
131
132
  }
132
133
  /**
133
- * Public entry: compile JSX source → { c, h, ... }. On an AOT error, annotate it with file:line:col + a
134
- * source code-frame (+ hint) so the failure points at the exact unsupported construct.
134
+ * Runs a compilation, annotating an AOT error with file:line:col + a source code-frame (+ hint) so the failure
135
+ * points at the exact unsupported construct.
135
136
  *
136
- * @param src The App.jsx/App.tsx source text.
137
- * @param demo Demo name (only used in the generated-by header comment).
138
- * @param opts filename, svgArtifacts, ts, and the screen and caps resolveOptions documents.
137
+ * @param source The App.jsx/App.tsx source text.
138
+ * @param demo Demo name, for the file the error names when opts has none.
139
+ * @param options The compile's options.
140
+ * @param resolved The same options, resolved.
141
+ * @param compileOnce One compile, as compileWidened runs it.
139
142
  *
140
- * @returns The generated app.gen.c and app.gen.h, and what they contain.
143
+ * @returns What the compile produced.
141
144
  */
142
- export function compileSource(src, demo = 'app', opts = {}) {
143
- const resolved = resolveOptions(opts);
145
+ function compileLocated(source, demo, options, resolved, compileOnce) {
144
146
  try {
145
- return compileWidened(src, demo, resolved);
147
+ return compileWidened(compileOnce);
146
148
  }
147
149
  catch (error) {
148
150
  // Point an AOT error at its place in the source; any other error passes through unchanged.
149
151
  if (error &&
150
152
  typeof error.message === 'string' &&
151
153
  error.message.startsWith('AOT:')) {
152
- throw formatAotError(error, src, opts.filename || `demos/${demo}/App.jsx`, resolved);
154
+ throw formatAotError(error, source, options.filename || `demos/${demo}/App.jsx`, resolved);
153
155
  }
154
156
  throw error;
155
157
  }
156
158
  }
157
- // CLI entry (`node aot/compile.mts [demo]`), only when run directly: compile a demo into dist/app.gen.{c,h}.
159
+ /**
160
+ * The sizes a package build was told to keep layouts for: options.screens, options.screen or ER_AOT_SCREEN_W/H.
161
+ *
162
+ * @param options The build's options.
163
+ *
164
+ * @returns The sizes, or null to find every layout.
165
+ */
166
+ function requestedScreens(options) {
167
+ if (options.screens?.length)
168
+ return options.screens;
169
+ if (options.screen)
170
+ return [options.screen];
171
+ const fromEnv = (name) => (process.env[name] ?? '').trim() !== '';
172
+ return fromEnv('ER_AOT_SCREEN_W') || fromEnv('ER_AOT_SCREEN_H')
173
+ ? [resolveOptions(options).screen]
174
+ : null;
175
+ }
176
+ /**
177
+ * The error for an app with too many layouts, naming the value that took the most different values across them.
178
+ *
179
+ * @param panels The layouts so far.
180
+ * @param named The build names its panels already.
181
+ *
182
+ * @returns The error.
183
+ */
184
+ function tooManyLayouts(panels, named) {
185
+ const values = new Map();
186
+ for (const { assumptions } of panels) {
187
+ for (const assumption of assumptions) {
188
+ const source = assumption.source ?? 'a value derived from `screen`';
189
+ const seen = values.get(source) ?? new Set();
190
+ seen.add(assumption.kind === 'value' ? assumption.value : seen.size);
191
+ values.set(source, seen);
192
+ }
193
+ }
194
+ const [worst] = [...values].sort(([, left], [, right]) => right.size - left.size)[0] ?? ['the app'];
195
+ return new Error(`AOT: this app needs more than ${MAX_LAYOUTS} layouts, because \`${worst}\` changes what is compiled at ` +
196
+ 'too many sizes.\n\nA breakpoint picks between a few layouts; a value worked out from `screen` belongs in ' +
197
+ 'a style, which boot works out. ' +
198
+ (named
199
+ ? 'Or name fewer panels.'
200
+ : 'To build for fixed panels, name them: --screen 240x320,800x480.'));
201
+ }
202
+ /**
203
+ * Public entry for the package output: compile JSX source to a Flow B program section, and its debug section.
204
+ *
205
+ * With no sizes named, it finds the app's layouts: it compiles one, finds a size that layout's check rejects, and
206
+ * compiles again until every size has a layout. Named sizes keep only the layouts they pick. An AOT error is annotated
207
+ * with file:line:col + a source code-frame (+ hint), so the failure points at the exact unsupported construct.
208
+ *
209
+ * @param source The App.jsx/App.tsx source text.
210
+ * @param demo Demo name, for the file an error names when opts has none.
211
+ * @param compileOptions filename, svgArtifacts, ts, screens, release, and the screen and caps resolveOptions documents.
212
+ *
213
+ * @returns The program and debug sections, and what the package holds.
214
+ */
215
+ export function compilePackage(source, demo = 'app', compileOptions = {}) {
216
+ const panels = [];
217
+ const checks = () => panels.map(panel => panel.program.panels[0].check);
218
+ const compileAt = (screen, searched) => {
219
+ const options = resolveOptions({ ...compileOptions, screen });
220
+ const resolved = searched
221
+ ? { ...options, screenFrom: 'search' }
222
+ : options;
223
+ panels.push(compileLocated(source, demo, compileOptions, resolved, (wide, stores) => compilePanel(source, resolved, wide, stores)));
224
+ };
225
+ const requested = requestedScreens(compileOptions);
226
+ if (requested) {
227
+ const seen = new Set();
228
+ for (const screen of requested) {
229
+ const { width, height } = resolveOptions({
230
+ ...compileOptions,
231
+ screen,
232
+ }).screen;
233
+ const size = `${width}x${height}`;
234
+ if (seen.has(size)) {
235
+ throw new Error(`AOT: the panel ${size} is listed twice`);
236
+ }
237
+ seen.add(size);
238
+ if (!checks().some(check => runCheck(check, width, height))) {
239
+ if (panels.length === MAX_LAYOUTS)
240
+ throw tooManyLayouts(panels, true);
241
+ compileAt({ width, height }, false);
242
+ }
243
+ }
244
+ }
245
+ else {
246
+ const search = new SizeSearch();
247
+ let next = FIRST_SIZE;
248
+ while (next && next !== 'gave-up') {
249
+ if (panels.length === MAX_LAYOUTS)
250
+ throw tooManyLayouts(panels, false);
251
+ compileAt(next, true);
252
+ if (!runCheck(checks().at(-1), next.width, next.height)) {
253
+ throw new Error(`AOT: the layout for ${next.width}x${next.height} doesn't take that size. This is a compiler bug.`);
254
+ }
255
+ next = search.next(checks());
256
+ }
257
+ if (next === 'gave-up') {
258
+ throw new Error("AOT: can't tell which layouts this app needs: its checks are too intricate to work out for every size. " +
259
+ 'Name the panels it runs on: --screen 240x320,800x480.');
260
+ }
261
+ }
262
+ return assemblePackage(panels, basename(compileOptions.filename || 'App.jsx'), compileOptions.release);
263
+ }
264
+ // CLI entry (`node aot/compile.mts [demo]`), only when run directly: compile a demo into dist/app.erpkg.
158
265
  if (process.argv[1] &&
159
266
  resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url))) {
160
267
  // Find the demo's App.jsx, listing the available demos when it is missing.
161
- const demo = process.argv[2] || process.env.DEMO || 'thermostat';
162
- const appPath = resolve(demosDir, demo, 'App.jsx');
163
- const availableDemos = existsSync(demosDir)
164
- ? readdirSync(demosDir, { withFileTypes: true })
268
+ const commandArguments = process.argv.slice(2);
269
+ const screenAt = commandArguments.indexOf('--screen');
270
+ const screens = screenAt < 0
271
+ ? undefined
272
+ : (commandArguments[screenAt + 1] ?? '').split(',').map(size => {
273
+ const match = /^([1-9]\d*)x([1-9]\d*)$/i.exec(size);
274
+ if (!match) {
275
+ console.error(`AOT: --screen expects <width>x<height> (e.g. --screen 240x320), got: ${commandArguments[screenAt + 1] ?? '(nothing)'}`);
276
+ process.exit(1);
277
+ }
278
+ return { width: Number(match[1]), height: Number(match[2]) };
279
+ });
280
+ const demo = commandArguments.find((argument, index) => !argument.startsWith('--') && (screenAt < 0 || index !== screenAt + 1)) ||
281
+ process.env.DEMO ||
282
+ 'thermostat';
283
+ const appPath = resolve(demosDirectory, demo, 'App.jsx');
284
+ const availableDemos = existsSync(demosDirectory)
285
+ ? readdirSync(demosDirectory, { withFileTypes: true })
165
286
  .filter(entry => entry.isDirectory())
166
287
  .map(entry => entry.name)
167
288
  : [];
@@ -170,13 +291,14 @@ if (process.argv[1] &&
170
291
  process.exit(1);
171
292
  }
172
293
  // Compile the app, baking <Svg source> .svg imports first so the compile itself stays pure (no I/O).
173
- const src = readFileSync(appPath, 'utf8');
294
+ const source = readFileSync(appPath, 'utf8');
174
295
  let result;
175
296
  try {
176
- const svgArtifacts = await bakeSvgArtifacts(src, resolve(demosDir, demo));
177
- result = compileSource(src, demo, {
178
- filename: resolve(demosDir, demo, 'App.jsx'),
179
- svgArtifacts,
297
+ result = compilePackage(source, demo, {
298
+ filename: resolve(demosDirectory, demo, 'App.jsx'),
299
+ svgArtifacts: await bakeSvgArtifacts(source, resolve(demosDirectory, demo)),
300
+ screen: screens?.[0],
301
+ screens,
180
302
  });
181
303
  }
182
304
  catch (error) {
@@ -184,14 +306,10 @@ if (process.argv[1] &&
184
306
  console.error(error && error.aotLoc ? error.message : error?.message || String(error));
185
307
  process.exit(1);
186
308
  }
187
- // Write the generated C.
188
- mkdirSync(distDir, { recursive: true });
189
- writeFileSync(resolve(distDir, 'app.gen.c'), result.c);
190
- writeFileSync(resolve(distDir, 'app.gen.h'), result.h);
191
309
  // Locate the images the app imports; each importPath is source-relative to the demo's App.jsx.
192
310
  const imageJobs = result.images.map(image => ({
193
311
  name: image.name,
194
- path: resolve(demosDir, demo, image.importPath),
312
+ path: resolve(demosDirectory, demo, image.importPath),
195
313
  }));
196
314
  // Stop on an imported image that is not on disk.
197
315
  for (const job of imageJobs) {
@@ -201,10 +319,12 @@ if (process.argv[1] &&
201
319
  }
202
320
  }
203
321
  // Flow B renders all text in the built-in font, so check the app's glyphs and font sizes against it.
204
- warnMissingGlyphs({ source: src, jsx: true });
205
- warnFontSizes({ used: analyzeFontSizes(src) });
206
- // Bake images with Flow A's baker, even with none (a no-op), so the AOT host can always build and call it.
207
- const baked = bakeAssets({ images: imageJobs, fonts: [], outDir: distDir });
208
- console.log(`AOT: compiled demo "${demo}" -> dist/app.gen.c (${result.nodes} nodes, ${result.state} state, ` +
209
- `${result.handlers} handler(s), ${result.updates} dynamic) + ${baked.images} image(s) -> dist/assets.generated.c`);
322
+ warnMissingGlyphs({ source: source, jsx: true });
323
+ warnFontSizes({ used: analyzeFontSizes(source) });
324
+ // The package carries its images as an asset pack.
325
+ const file = packPackage(result, imageJobs.length ? bakeAssetPackBytes({ images: imageJobs }) : undefined);
326
+ mkdirSync(distDirectory, { recursive: true });
327
+ writeFileSync(resolve(distDirectory, 'app.erpkg'), file.bytes);
328
+ console.log(`AOT: compiled demo "${demo}" -> dist/app.erpkg`);
329
+ console.log(resourceReport(result, file).join('\n'));
210
330
  }