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
@@ -20,32 +20,42 @@
20
20
  // boots from), streams it over the serial/USB port as an ERHR frame, and prints the device's logs that
21
21
  // come back. The firmware swaps the new config in live — no reflash, no reboot. State written with
22
22
  // usePersistentState (or plain useState in this dev mode) survives the reload, like the simulator.
23
+ //
24
+ // With a compilePackage function it is the Flow B loop (`--device --aot`): each save compiles a package and sends it
25
+ // as a PackageTransfer, and the app starts over, since a package's state doesn't carry across yet.
23
26
 
24
27
  import {relative} from 'node:path';
28
+ import {PackageTransfer} from './package-transfer.mjs';
25
29
  import {packApp, emitAppFrame} from './pack-split.mjs';
26
30
  import {SerialUploader, listSerialPorts} from './uploader.mjs';
27
31
  import {watchTree} from './watch-tree.mjs';
28
32
 
29
- const kb = n => `${(n / 1024).toFixed(1)} KB`;
33
+ const BYTES_PER_KB = 1024;
34
+ const WATCH_DEBOUNCE_MS = 120;
35
+ const LIVENESS_CHECKS = 30;
36
+ const LIVENESS_INTERVAL_MS = 100;
37
+
38
+ const kb = bytes => `${(bytes / BYTES_PER_KB).toFixed(1)} KB`;
30
39
 
31
40
  /** Debounce: coalesce a burst of file events (editors often write several) into one rebuild. */
32
- function debounce(fn, ms) {
33
- let t = null;
41
+ function debounce(callback, delayMs) {
42
+ let timer = null;
34
43
  return (...args) => {
35
- if (t) clearTimeout(t);
36
- t = setTimeout(() => {
37
- t = null;
38
- fn(...args);
39
- }, ms);
44
+ if (timer) clearTimeout(timer);
45
+ timer = setTimeout(() => {
46
+ timer = null;
47
+ callback(...args);
48
+ }, delayMs);
40
49
  };
41
50
  }
42
51
 
43
52
  /**
44
53
  * Run the device hot-reload dev loop until interrupted.
45
54
  *
46
- * @param {object} o
47
- * @param {string} o.entry, o.projectRoot, o.libSrc, o.simDir, o.label, o.device
48
- * @param {string[]} o.nodePaths
55
+ * @param {object} options
56
+ * @param {string} options.entry, options.projectRoot, options.libSrc, options.simDir, options.label, options.device
57
+ * @param {string[]} options.nodePaths
58
+ * @param {() => Promise<Buffer>} [options.compilePackage] Flow B: builds the package to send. Throws to report a build error.
49
59
  */
50
60
  export async function runDeviceDevServer({
51
61
  entry,
@@ -55,6 +65,7 @@ export async function runDeviceDevServer({
55
65
  simDir,
56
66
  device,
57
67
  label,
68
+ compilePackage,
58
69
  }) {
59
70
  // Each push ends with exactly one terminal line in the device's log stream:
60
71
  // "hot reload: ok (...)" → loaded and running
@@ -69,12 +80,17 @@ export async function runDeviceDevServer({
69
80
  let sawAnyLog = false;
70
81
  let sawReceiverAck = false;
71
82
  let closing = false; // set on Ctrl-C so we don't surface errors from a write canceled by the shutdown
83
+ let transfer = null;
72
84
  const onDeviceLog = line => {
73
85
  if (closing) return;
74
86
  sawAnyLog = true;
75
- console.log(` ▸ ${line}`);
76
- if (/dropped frame/i.test(line) || /hot reload:/i.test(line))
87
+ if (/dropped frame/i.test(line) || /(hot|erb) reload:/i.test(line))
77
88
  sawReceiverAck = true;
89
+ if (transfer) {
90
+ if (!transfer.onLine(line)) console.log(` ▸ ${line}`);
91
+ return;
92
+ }
93
+ console.log(` ▸ ${line}`);
78
94
  if (!settleOutcome) return;
79
95
  if (/dropped frame/i.test(line)) settleOutcome('dropped');
80
96
  else if (/hot reload:\s*ok\b/i.test(line)) settleOutcome('ok');
@@ -82,17 +98,22 @@ export async function runDeviceDevServer({
82
98
  };
83
99
 
84
100
  const uploader = new SerialUploader({device, onLog: onDeviceLog});
101
+ if (compilePackage) {
102
+ transfer = new PackageTransfer({
103
+ write: frame => uploader.writeFrame(frame),
104
+ });
105
+ }
85
106
 
86
107
  try {
87
108
  await uploader.open();
88
- } catch (e) {
89
- console.error(`✗ ${e.message}`);
109
+ } catch (error) {
110
+ console.error(`✗ ${error.message}`);
90
111
  const ports = await listSerialPorts();
91
112
  if (ports.length) {
92
113
  console.error('\nAvailable ports:');
93
- for (const p of ports)
114
+ for (const port of ports)
94
115
  console.error(
95
- ` ${p.path}${p.manufacturer ? ` (${p.manufacturer})` : ''}`,
116
+ ` ${port.path}${port.manufacturer ? ` (${port.manufacturer})` : ''}`,
96
117
  );
97
118
  }
98
119
  process.exit(1);
@@ -103,7 +124,9 @@ export async function runDeviceDevServer({
103
124
  `watching ${relative(projectRoot, entry) || label} — edit & save to push. Ctrl-C to quit.`,
104
125
  );
105
126
  console.log(
106
- ' sending app-only frames; the device must be running a split build (embedded-react build) so the vendor is resident.',
127
+ compilePackage
128
+ ? ' sending Flow B packages; the device must be running a Flow B firmware built with ER_HOTRELOAD=1.'
129
+ : ' sending app-only frames; the device must be running a split build (embedded-react build) so the vendor is resident.',
107
130
  );
108
131
 
109
132
  const APPLY_TIMEOUT_MS = 15000; // a normal reload settles in ~3-4 s; this only catches a stuck device
@@ -115,12 +138,12 @@ export async function runDeviceDevServer({
115
138
  const nextOutcome = (timeoutMs = APPLY_TIMEOUT_MS) =>
116
139
  new Promise(resolve => {
117
140
  let done = false;
118
- const finish = r => {
141
+ const finish = outcome => {
119
142
  if (done) return;
120
143
  done = true;
121
144
  settleOutcome = null;
122
145
  clearTimeout(timer);
123
- resolve(r);
146
+ resolve(outcome);
124
147
  };
125
148
  const timer = setTimeout(() => finish('timeout'), timeoutMs);
126
149
  settleOutcome = finish; // armed before the send so the terminal log can't be missed
@@ -137,10 +160,10 @@ export async function runDeviceDevServer({
137
160
  ) => {
138
161
  for (let attempt = 0; ; attempt++) {
139
162
  const outcome = nextOutcome(timeoutMs);
140
- uploader.send(container).catch(err => {
163
+ uploader.send(container).catch(error => {
141
164
  if (closing) return;
142
165
  if (settleOutcome) settleOutcome('senderr');
143
- else console.error(`✗ send failed: ${err.message}`);
166
+ else console.error(`✗ send failed: ${error.message}`);
144
167
  });
145
168
  const result = await outcome;
146
169
  if (result === 'ok' || result === 'rejected') return result;
@@ -157,6 +180,34 @@ export async function runDeviceDevServer({
157
180
  }
158
181
  };
159
182
 
183
+ let triedToSend = false; // a first save that doesn't build says nothing about the board
184
+
185
+ /** One Flow B cycle: compile a package, send it and report how it went. */
186
+ const reloadPackage = async ({probe}) => {
187
+ const started = Date.now();
188
+ let packageData;
189
+ try {
190
+ packageData = await compilePackage();
191
+ } catch (error) {
192
+ console.error(`✗ build failed: ${error.message}`);
193
+ return;
194
+ }
195
+ triedToSend = true;
196
+ const result = await transfer
197
+ .send(packageData, probe ? {beginTimeoutMs: PROBE_TIMEOUT_MS} : {})
198
+ .catch(error => {
199
+ if (!closing) console.error(`✗ send failed: ${error.message}`);
200
+ return 'senderr';
201
+ });
202
+ if (result === 'ok') {
203
+ console.log(
204
+ `↻ reloaded package ${kb(packageData.length)} in ${Date.now() - started} ms`,
205
+ );
206
+ } else if (result !== 'rejected' && result !== 'senderr') {
207
+ console.error(`✗ reload ${result} — save again to retry`);
208
+ }
209
+ };
210
+
160
211
  // Single-flight: one build→send→apply cycle at a time. A save that lands mid-cycle just re-arms it, so
161
212
  // we rebuild and resend the latest source once the current reload settles — pushes never overlap.
162
213
  let inFlight = false;
@@ -171,8 +222,13 @@ export async function runDeviceDevServer({
171
222
  let firstSend = probe; // the probe timeout applies to the initial push only
172
223
  do {
173
224
  queued = false;
225
+ if (compilePackage) {
226
+ await reloadPackage({probe: firstSend});
227
+ firstSend = false;
228
+ continue;
229
+ }
174
230
  const started = Date.now();
175
- let container, bytecodeLen, assetsLen;
231
+ let container, bytecodeLength, assetsLength;
176
232
  try {
177
233
  const app = await packApp({
178
234
  entry,
@@ -186,12 +242,13 @@ export async function runDeviceDevServer({
186
242
  appBytecode: app.bytecode,
187
243
  assetPack: app.assetPack,
188
244
  });
189
- bytecodeLen = app.bytecodeLen;
190
- assetsLen = app.assetsLen;
191
- } catch (e) {
192
- console.error(`✗ build failed: ${e.message}`);
245
+ bytecodeLength = app.bytecodeLen;
246
+ assetsLength = app.assetsLen;
247
+ } catch (error) {
248
+ console.error(`✗ build failed: ${error.message}`);
193
249
  continue;
194
250
  }
251
+ triedToSend = true;
195
252
  const result = await sendAndConfirm(
196
253
  container,
197
254
  firstSend ? {timeoutMs: PROBE_TIMEOUT_MS, probe: true} : {},
@@ -199,8 +256,8 @@ export async function runDeviceDevServer({
199
256
  firstSend = false;
200
257
  if (result === 'ok') {
201
258
  console.log(
202
- `↻ reloaded app ${kb(container.length)} (bytecode ${kb(bytecodeLen)}` +
203
- (assetsLen ? `, assets ${kb(assetsLen)}` : '') +
259
+ `↻ reloaded app ${kb(container.length)} (bytecode ${kb(bytecodeLength)}` +
260
+ (assetsLength ? `, assets ${kb(assetsLength)}` : '') +
204
261
  `) in ${Date.now() - started} ms`,
205
262
  );
206
263
  }
@@ -213,11 +270,11 @@ export async function runDeviceDevServer({
213
270
  // Before flooding the port with a frame, give the board a moment to prove it's alive (one log line is
214
271
  // enough). Flooding a firmware that never drains its RX can congest the link, so we sample liveness
215
272
  // first — this is also what tells "hot reload disabled" apart from "dead/wrong port" if no ack comes.
216
- for (let i = 0; i < 30 && !sawAnyLog; i++)
217
- await new Promise(r => setTimeout(r, 100));
273
+ for (let check = 0; check < LIVENESS_CHECKS && !sawAnyLog; check++)
274
+ await new Promise(resolve => setTimeout(resolve, LIVENESS_INTERVAL_MS));
218
275
 
219
276
  await reloadCycle({probe: true});
220
- if (!sawReceiverAck) {
277
+ if (triedToSend && !sawReceiverAck) {
221
278
  console.warn('');
222
279
  console.warn('⚠ the board never acknowledged the hot-reload frame.');
223
280
  if (sawAnyLog) {
@@ -236,7 +293,7 @@ export async function runDeviceDevServer({
236
293
  console.warn('');
237
294
  }
238
295
 
239
- const onChange = debounce(reloadCycle, 120);
296
+ const onChange = debounce(reloadCycle, WATCH_DEBOUNCE_MS);
240
297
  const onWatchEvent = (_event, file) => {
241
298
  if (!file) return;
242
299
  // Ignore churn that can't affect the bundle (build output, deps, VCS, editor temp files).
@@ -36,13 +36,13 @@ const QJS_TAG = 'v0.15.0';
36
36
  /**
37
37
  * Bundle + compile + bake an app into an ERCF container Buffer.
38
38
  *
39
- * @param {object} o
40
- * @param {string} o.entry App entry (index.jsx/tsx).
41
- * @param {string} o.projectRoot Project cwd (for assets.config.js + persist scoping).
42
- * @param {string} o.libSrc Path to the embedded-react library entry (aliased as 'embedded-react').
43
- * @param {string[]} o.nodePaths esbuild nodePaths (package + project node_modules).
44
- * @param {string} o.simDir Dir holding the prebuilt sim wasm (used to compile bytecode).
45
- * @param {boolean} [o.persist] Apply the useState→persist transform (dev hot reload preserves state).
39
+ * @param {object} options
40
+ * @param {string} options.entry App entry (index.jsx/tsx).
41
+ * @param {string} options.projectRoot Project cwd (for assets.config.js + persist scoping).
42
+ * @param {string} options.libSrc Path to the embedded-react library entry (aliased as 'embedded-react').
43
+ * @param {string[]} options.nodePaths esbuild nodePaths (package + project node_modules).
44
+ * @param {string} options.simDir Dir holding the prebuilt sim wasm (used to compile bytecode).
45
+ * @param {boolean} [options.persist] Apply the useState→persist transform (dev hot reload preserves state).
46
46
  * @returns {Promise<{container: Buffer, bytecodeLen: number, assetsLen: number}>}
47
47
  */
48
48
  export async function packAppContainer({
@@ -66,7 +66,7 @@ export async function packAppContainer({
66
66
  const {registerSvgVectorLoader} = await import('../assets/svg-loader.mjs');
67
67
  const {compileToBytecode} = await import('../qjsc-wasm.mjs');
68
68
 
69
- const assetName = p => basename(p).replace(/\.[^.]+$/, '');
69
+ const assetName = filePath => basename(filePath).replace(/\.[^.]+$/, '');
70
70
  const images = new Map();
71
71
  const fonts = new Map();
72
72
 
@@ -77,59 +77,71 @@ export async function packAppContainer({
77
77
  const {transformPersist, shouldPersist} =
78
78
  await import('../persist-transform.mjs');
79
79
  const {relative} = await import('node:path');
80
- const projNorm = projectRoot.replace(/\\/g, '/');
81
- persistHooks = {transformPersist, shouldPersist, relative, projNorm};
80
+ const normalizedProjectRoot = projectRoot.replace(/\\/g, '/');
81
+ persistHooks = {
82
+ transformPersist,
83
+ shouldPersist,
84
+ relative,
85
+ normalizedProjectRoot,
86
+ };
82
87
  }
83
88
 
84
89
  const assetPlugin = {
85
90
  name: 'embedded-react-assets',
86
- setup(b) {
91
+ setup(build) {
87
92
  if (persistHooks) {
88
- b.onLoad({filter: /\.(jsx?|tsx?)$/}, a => {
89
- const {transformPersist, shouldPersist, relative, projNorm} =
90
- persistHooks;
91
- if (!shouldPersist(a.path, projNorm)) return undefined;
93
+ build.onLoad({filter: /\.(jsx?|tsx?)$/}, args => {
94
+ const {
95
+ transformPersist,
96
+ shouldPersist,
97
+ relative,
98
+ normalizedProjectRoot,
99
+ } = persistHooks;
100
+ if (!shouldPersist(args.path, normalizedProjectRoot))
101
+ return undefined;
92
102
  try {
93
- const loader = a.path.endsWith('.tsx')
103
+ const loader = args.path.endsWith('.tsx')
94
104
  ? 'tsx'
95
- : a.path.endsWith('.ts')
105
+ : args.path.endsWith('.ts')
96
106
  ? 'ts'
97
107
  : 'jsx';
98
108
  return {
99
109
  contents: transformPersist(
100
- readFileSync(a.path, 'utf8'),
101
- relative(projectRoot, a.path).replace(/\\/g, '/'),
110
+ readFileSync(args.path, 'utf8'),
111
+ relative(projectRoot, args.path).replace(/\\/g, '/'),
102
112
  ),
103
113
  loader,
104
114
  };
105
- } catch (e) {
106
- return {errors: [{text: `persist transform: ${e.message}`}]};
115
+ } catch (error) {
116
+ return {errors: [{text: `persist transform: ${error.message}`}]};
107
117
  }
108
118
  });
109
119
  }
110
- b.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, a => {
111
- const n = assetName(a.path);
112
- images.set(n, a.path);
120
+ build.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
121
+ const name = assetName(args.path);
122
+ images.set(name, args.path);
113
123
  return {
114
- contents: `module.exports = ${JSON.stringify(n)};`,
124
+ contents: `module.exports = ${JSON.stringify(name)};`,
115
125
  loader: 'js',
116
126
  };
117
127
  });
118
- b.onLoad({filter: /\.(ttf|otf)$/i}, a => {
119
- const f = assetName(a.path);
120
- fonts.set(f, a.path);
128
+ build.onLoad({filter: /\.(ttf|otf)$/i}, args => {
129
+ const family = assetName(args.path);
130
+ fonts.set(family, args.path);
121
131
  return {
122
- contents: `module.exports = ${JSON.stringify(f)};`,
132
+ contents: `module.exports = ${JSON.stringify(family)};`,
123
133
  loader: 'js',
124
134
  };
125
135
  });
126
- registerSvgVectorLoader(b, (name, p) => images.set(name, p));
136
+ registerSvgVectorLoader(build, (name, pngPath) =>
137
+ images.set(name, pngPath),
138
+ );
127
139
  },
128
140
  };
129
141
 
130
- const tmp = resolve(tmpdir(), 'embedded-react-build');
131
- mkdirSync(tmp, {recursive: true});
132
- const bundlePath = resolve(tmp, 'app.bundle.js');
142
+ const buildDirectory = resolve(tmpdir(), 'embedded-react-build');
143
+ mkdirSync(buildDirectory, {recursive: true});
144
+ const bundlePath = resolve(buildDirectory, 'app.bundle.js');
133
145
  await esbuild.build({
134
146
  entryPoints: [entry],
135
147
  bundle: true,
@@ -145,17 +157,17 @@ export async function packAppContainer({
145
157
  legalComments: 'none',
146
158
  logLevel: 'silent',
147
159
  });
148
- const bundleSrc = readFileSync(bundlePath, 'utf8');
160
+ const bundleSource = readFileSync(bundlePath, 'utf8');
149
161
 
150
- const bytecode = await compileToBytecode(bundleSrc, simDir, {strip});
162
+ const bytecode = await compileToBytecode(bundleSource, simDir, {strip});
151
163
 
152
- const usedSizes = analyzeFontSizes(bundleSrc);
153
- let cfg = {};
154
- const cp = resolve(projectRoot, 'assets.config.js');
155
- if (existsSync(cp))
156
- cfg = (await import(pathToFileURL(cp).href)).default || {};
157
- const fontConfig = cfg.fonts || {};
158
- const imageConfig = cfg.images || {};
164
+ const usedSizes = analyzeFontSizes(bundleSource);
165
+ let config = {};
166
+ const configPath = resolve(projectRoot, 'assets.config.js');
167
+ if (existsSync(configPath))
168
+ config = (await import(pathToFileURL(configPath).href)).default || {};
169
+ const fontConfig = config.fonts || {};
170
+ const imageConfig = config.images || {};
159
171
  const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
160
172
  const imageJobs = [...images.entries()].map(([name, path]) => ({
161
173
  path,
@@ -164,7 +176,7 @@ export async function packAppContainer({
164
176
  }));
165
177
  const bakedImages = imageJobs.map(bakeImage);
166
178
  const bakedFonts = fontJobs.map(bakeFont);
167
- warnMissingGlyphs({source: bundleSrc, fonts: bakedFonts});
179
+ warnMissingGlyphs({source: bundleSource, fonts: bakedFonts});
168
180
  warnFontSizes({used: usedSizes, fonts: bakedFonts});
169
181
  const assetPack =
170
182
  bakedImages.length || bakedFonts.length
@@ -36,7 +36,7 @@
36
36
  import {createRequire} from 'node:module';
37
37
  import {pathToFileURL} from 'node:url';
38
38
  import {basename, dirname, resolve, relative} from 'node:path';
39
- import {existsSync, readFileSync} from 'node:fs';
39
+ import {existsSync, readFileSync, statSync} from 'node:fs';
40
40
 
41
41
  const require = createRequire(import.meta.url);
42
42
 
@@ -88,14 +88,14 @@ globalThis.require = function (id) {
88
88
  /**
89
89
  * Bundle the vendor chunk (react + reconciler + embedded-react lib) to a self-contained IIFE source.
90
90
  *
91
- * @param {object} o
92
- * @param {string} o.libSrc embedded-react library entry (aliased as 'embedded-react').
93
- * @param {string[]} o.nodePaths esbuild nodePaths (package + project node_modules).
91
+ * @param {object} options
92
+ * @param {string} options.libSrc embedded-react library entry (aliased as 'embedded-react').
93
+ * @param {string[]} options.nodePaths esbuild nodePaths (package + project node_modules).
94
94
  * @returns {Promise<string>} The bundled JS source.
95
95
  */
96
96
  export async function bundleVendorSource({libSrc, nodePaths}) {
97
97
  const esbuild = require('esbuild');
98
- const out = await esbuild.build({
98
+ const result = await esbuild.build({
99
99
  ...esbuildCommon(nodePaths),
100
100
  stdin: {
101
101
  contents: vendorEntrySource(),
@@ -105,7 +105,7 @@ export async function bundleVendorSource({libSrc, nodePaths}) {
105
105
  },
106
106
  alias: {'embedded-react': libSrc},
107
107
  });
108
- return out.outputFiles[0].text;
108
+ return result.outputFiles[0].text;
109
109
  }
110
110
 
111
111
  /**
@@ -114,51 +114,55 @@ export async function bundleVendorSource({libSrc, nodePaths}) {
114
114
  * own source gets the useState→persist transform so state survives a live reload.
115
115
  */
116
116
  function makeAssetPlugin({images, fonts, persistHooks, projectRoot}) {
117
- const assetName = p => basename(p).replace(/\.[^.]+$/, '');
117
+ const assetName = filePath => basename(filePath).replace(/\.[^.]+$/, '');
118
118
  return {
119
119
  name: 'embedded-react-assets',
120
- async setup(b) {
120
+ async setup(build) {
121
121
  const {registerSvgVectorLoader} =
122
122
  await import('../assets/svg-loader.mjs');
123
123
  if (persistHooks) {
124
- b.onLoad({filter: /\.(jsx?|tsx?)$/}, a => {
125
- const {transformPersist, shouldPersist, projNorm} = persistHooks;
126
- if (!shouldPersist(a.path, projNorm)) return undefined;
124
+ build.onLoad({filter: /\.(jsx?|tsx?)$/}, args => {
125
+ const {transformPersist, shouldPersist, normalizedProjectRoot} =
126
+ persistHooks;
127
+ if (!shouldPersist(args.path, normalizedProjectRoot))
128
+ return undefined;
127
129
  try {
128
- const loader = a.path.endsWith('.tsx')
130
+ const loader = args.path.endsWith('.tsx')
129
131
  ? 'tsx'
130
- : a.path.endsWith('.ts')
132
+ : args.path.endsWith('.ts')
131
133
  ? 'ts'
132
134
  : 'jsx';
133
135
  return {
134
136
  contents: transformPersist(
135
- readFileSync(a.path, 'utf8'),
136
- relative(projectRoot, a.path).replace(/\\/g, '/'),
137
+ readFileSync(args.path, 'utf8'),
138
+ relative(projectRoot, args.path).replace(/\\/g, '/'),
137
139
  ),
138
140
  loader,
139
141
  };
140
- } catch (e) {
141
- return {errors: [{text: `persist transform: ${e.message}`}]};
142
+ } catch (error) {
143
+ return {errors: [{text: `persist transform: ${error.message}`}]};
142
144
  }
143
145
  });
144
146
  }
145
- b.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, a => {
146
- const n = assetName(a.path);
147
- images.set(n, a.path);
147
+ build.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
148
+ const name = assetName(args.path);
149
+ images.set(name, args.path);
148
150
  return {
149
- contents: `module.exports = ${JSON.stringify(n)};`,
151
+ contents: `module.exports = ${JSON.stringify(name)};`,
150
152
  loader: 'js',
151
153
  };
152
154
  });
153
- b.onLoad({filter: /\.(ttf|otf)$/i}, a => {
154
- const f = assetName(a.path);
155
- fonts.set(f, a.path);
155
+ build.onLoad({filter: /\.(ttf|otf)$/i}, args => {
156
+ const family = assetName(args.path);
157
+ fonts.set(family, args.path);
156
158
  return {
157
- contents: `module.exports = ${JSON.stringify(f)};`,
159
+ contents: `module.exports = ${JSON.stringify(family)};`,
158
160
  loader: 'js',
159
161
  };
160
162
  });
161
- registerSvgVectorLoader(b, (name, p) => images.set(name, p));
163
+ registerSvgVectorLoader(build, (name, pngPath) =>
164
+ images.set(name, pngPath),
165
+ );
162
166
  },
163
167
  };
164
168
  }
@@ -184,17 +188,17 @@ export async function bundleAppSource({
184
188
  persistHooks = {
185
189
  transformPersist,
186
190
  shouldPersist,
187
- projNorm: projectRoot.replace(/\\/g, '/'),
191
+ normalizedProjectRoot: projectRoot.replace(/\\/g, '/'),
188
192
  };
189
193
  }
190
194
 
191
- const out = await esbuild.build({
195
+ const result = await esbuild.build({
192
196
  ...esbuildCommon(nodePaths),
193
197
  entryPoints: [entry],
194
198
  external: VENDOR_EXTERNALS,
195
199
  plugins: [makeAssetPlugin({images, fonts, persistHooks, projectRoot})],
196
200
  });
197
- return {source: out.outputFiles[0].text, images, fonts};
201
+ return {source: result.outputFiles[0].text, images, fonts};
198
202
  }
199
203
 
200
204
  /** Bake the discovered images/fonts into an ERPK asset pack (or null if there are none). */
@@ -209,12 +213,17 @@ async function bakeAssets({images, fonts, source, projectRoot}) {
209
213
 
210
214
  const usedSizes = analyzeFontSizes(source);
211
215
 
212
- let cfg = {};
213
- const cp = resolve(projectRoot, 'assets.config.js');
214
- if (existsSync(cp))
215
- cfg = (await import(pathToFileURL(cp).href)).default || {};
216
- const fontConfig = cfg.fonts || {};
217
- const imageConfig = cfg.images || {};
216
+ let config = {};
217
+ const configPath = resolve(projectRoot, 'assets.config.js');
218
+ if (existsSync(configPath))
219
+ config =
220
+ (
221
+ await import(
222
+ `${pathToFileURL(configPath).href}?t=${statSync(configPath).mtimeMs}`
223
+ )
224
+ ).default || {};
225
+ const fontConfig = config.fonts || {};
226
+ const imageConfig = config.images || {};
218
227
 
219
228
  const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
220
229
  const imageJobs = [...images.entries()].map(([name, path]) => ({
@@ -294,9 +303,9 @@ export function emitAppFrame({appBytecode, assetPack}) {
294
303
  }
295
304
 
296
305
  // emitBootContainer/emitAppFrame are async (emit() dynamically imports the emitter) — callers await them.
297
- async function emit(opts) {
306
+ async function emit(options) {
298
307
  const {emitContainer} = await import('../assets/emit-container.mjs');
299
- return emitContainer({...opts, qjsTag: QJS_TAG});
308
+ return emitContainer({...options, qjsTag: QJS_TAG});
300
309
  }
301
310
 
302
311
  export {QJS_TAG};