embedded-react 0.21.0 → 0.22.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 (99) hide show
  1. package/README.md +2 -2
  2. package/aot/compile.mjs +1 -1
  3. package/aot/compiler/alerts.mjs +604 -0
  4. package/aot/compiler/check.mjs +1 -1
  5. package/aot/compiler/collect.mjs +1 -1
  6. package/aot/compiler/elements/button.mjs +3 -3
  7. package/aot/compiler/elements/image-background.mjs +1 -1
  8. package/aot/compiler/elements/props.mjs +10 -6
  9. package/aot/compiler/elements/section-list.mjs +1 -1
  10. package/aot/compiler/expressions.mjs +29 -2
  11. package/aot/compiler/handlers.mjs +73 -16
  12. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  13. package/aot/compiler/keyboard.mjs +1 -1
  14. package/aot/compiler/lower.mjs +12 -0
  15. package/aot/compiler/nodes.mjs +17 -9
  16. package/aot/compiler/out.mjs +4 -0
  17. package/aot/compiler/package/codegen.mjs +36 -2
  18. package/aot/compiler/package/format.mjs +5 -3
  19. package/aot/compiler/package/lower.mjs +53 -19
  20. package/aot/compiler/scroll-to.mjs +112 -0
  21. package/aot/compiler/style-text.mjs +2 -2
  22. package/aot/compiler/svg.mjs +6 -3
  23. package/aot/compiler/updaters.mjs +1 -0
  24. package/aot/style-map.mjs +44 -1
  25. package/assets/bake-font.mjs +187 -244
  26. package/assets/bake-image.mjs +47 -71
  27. package/assets/bake-svg.mjs +465 -533
  28. package/assets/build-builtin-font.mjs +14 -27
  29. package/assets/emit-c.mjs +124 -204
  30. package/assets/emit-container.mjs +129 -197
  31. package/assets/emit-pack.mjs +92 -136
  32. package/assets/font-config.mjs +19 -27
  33. package/assets/font-sizes.mjs +432 -507
  34. package/assets/glyph-coverage.mjs +170 -214
  35. package/assets/index.mjs +52 -97
  36. package/assets/rasterize.mjs +173 -194
  37. package/assets/svg-loader.mjs +42 -48
  38. package/build.mjs +84 -101
  39. package/cli.mjs +482 -621
  40. package/compile-bin.mjs +24 -36
  41. package/flash.mjs +297 -401
  42. package/hotreload/dev-device.mjs +229 -270
  43. package/hotreload/pack-app.mjs +118 -159
  44. package/hotreload/pack-split.mjs +144 -200
  45. package/hotreload/package-transfer.mjs +128 -131
  46. package/hotreload/protocol.mjs +118 -118
  47. package/hotreload/uploader.mjs +132 -159
  48. package/hotreload/watch-tree.mjs +56 -65
  49. package/pack-container.mjs +93 -123
  50. package/package.json +19 -16
  51. package/persist-transform.mjs +89 -105
  52. package/qjsc-wasm.mjs +47 -72
  53. package/sim/embedded-react.wasm +0 -0
  54. package/sim/index.html +1 -1
  55. package/sim-server.mjs +260 -354
  56. package/src/embedded-react/Alert.mjs +112 -0
  57. package/src/embedded-react/Animated.mjs +412 -0
  58. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  59. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  60. package/src/embedded-react/{Dimensions.js → Dimensions.mjs} +12 -17
  61. package/src/embedded-react/Easing.mjs +34 -0
  62. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  63. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  64. package/src/embedded-react/Keyboard.mjs +82 -0
  65. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  66. package/src/embedded-react/PanResponder.mjs +256 -0
  67. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  68. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  69. package/src/embedded-react/SectionList.mjs +103 -0
  70. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  71. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  72. package/src/embedded-react/background-image.mjs +321 -0
  73. package/src/embedded-react/{components.js → components.mjs} +1 -3
  74. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  75. package/src/embedded-react/index.d.ts +155 -2
  76. package/src/embedded-react/index.js +26 -19
  77. package/src/embedded-react/layout-anim-config.mjs +85 -0
  78. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  79. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  80. package/src/embedded-react/nativeModule.mjs +371 -0
  81. package/src/embedded-react/split-style.mjs +57 -0
  82. package/src/embedded-react/svg-ops.mjs +1075 -0
  83. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  84. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  85. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  86. package/src/host-config.mjs +512 -0
  87. package/src/{native-ui.js → native-ui.mjs} +1 -8
  88. package/src/props.mjs +341 -0
  89. package/src/{renderer.js → renderer.mjs} +30 -44
  90. package/src/embedded-react/Animated.js +0 -440
  91. package/src/embedded-react/Easing.js +0 -39
  92. package/src/embedded-react/PanResponder.js +0 -330
  93. package/src/embedded-react/SectionList.js +0 -146
  94. package/src/embedded-react/layout-anim-config.js +0 -101
  95. package/src/embedded-react/nativeModule.js +0 -462
  96. package/src/embedded-react/split-style.js +0 -58
  97. package/src/embedded-react/svg-ops.js +0 -1295
  98. package/src/host-config.js +0 -548
  99. package/src/props.js +0 -306
@@ -13,7 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // dev-device — the on-device hot-reload dev loop (`embedded-react dev --device <port>`).
18
17
  //
19
18
  // Watches the project, re-packs the app to an .erpkg on every save (the same Flow A build the device
@@ -23,295 +22,255 @@
23
22
  //
24
23
  // With a compilePackage function it is the Flow B loop (`--device --aot`): each save compiles a package and sends it
25
24
  // as a PackageTransfer, and the app starts over, since a package's state doesn't carry across yet.
26
-
27
- import {relative} from 'node:path';
28
- import {PackageTransfer} from './package-transfer.mjs';
29
- import {packApp, emitAppFrame} from './pack-split.mjs';
30
- import {SerialUploader, listSerialPorts} from './uploader.mjs';
31
- import {watchTree} from './watch-tree.mjs';
32
-
25
+ import { relative } from 'node:path';
26
+ import { PackageTransfer } from './package-transfer.mjs';
27
+ import { packApp, emitAppFrame } from './pack-split.mjs';
28
+ import { SerialUploader, listSerialPorts } from './uploader.mjs';
29
+ import { watchTree } from './watch-tree.mjs';
33
30
  const BYTES_PER_KB = 1024;
34
31
  const WATCH_DEBOUNCE_MS = 120;
35
32
  const LIVENESS_CHECKS = 30;
36
33
  const LIVENESS_INTERVAL_MS = 100;
37
-
38
- const kb = bytes => `${(bytes / BYTES_PER_KB).toFixed(1)} KB`;
39
-
34
+ const kb = (bytes) => `${(bytes / BYTES_PER_KB).toFixed(1)} KB`;
40
35
  /** Debounce: coalesce a burst of file events (editors often write several) into one rebuild. */
41
36
  function debounce(callback, delayMs) {
42
- let timer = null;
43
- return (...args) => {
44
- if (timer) clearTimeout(timer);
45
- timer = setTimeout(() => {
46
- timer = null;
47
- callback(...args);
48
- }, delayMs);
49
- };
37
+ let timer = null;
38
+ return () => {
39
+ if (timer)
40
+ clearTimeout(timer);
41
+ timer = setTimeout(() => {
42
+ timer = null;
43
+ callback();
44
+ }, delayMs);
45
+ };
50
46
  }
51
-
52
47
  /**
53
48
  * Run the device hot-reload dev loop until interrupted.
54
- *
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.
59
49
  */
60
- export async function runDeviceDevServer({
61
- entry,
62
- projectRoot,
63
- libSrc,
64
- nodePaths,
65
- simDir,
66
- device,
67
- label,
68
- compilePackage,
69
- }) {
70
- // Each push ends with exactly one terminal line in the device's log stream:
71
- // "hot reload: ok (...)" → loaded and running
72
- // "hot reload: <reason>" → loaded but the container was rejected (an app/runtime error)
73
- // "dropped frame: <reason>" → the upload was corrupt / overran the device's RX buffer (transport)
74
- // We watch for it to gate the next send (so a second push can't land while the device is still
75
- // applying — which would overrun its RX buffer and corrupt that frame) and to resend after a drop.
76
- let settleOutcome = null;
77
- // Track whether the board is alive at all (any log line) and whether a hot-reload RECEIVER is actually
78
- // running (it prints a "hot reload: …" or "dropped frame: …" line per frame). Firmware built WITHOUT
79
- // ER_HOTRELOAD still prints normal logs but never those — that's how we flag a disabled build below.
80
- let sawAnyLog = false;
81
- let sawReceiverAck = false;
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;
84
- const onDeviceLog = line => {
85
- if (closing) return;
86
- sawAnyLog = true;
87
- if (/dropped frame/i.test(line) || /(hot|erb) reload:/i.test(line))
88
- sawReceiverAck = true;
89
- if (transfer) {
90
- if (!transfer.onLine(line)) console.log(` ▸ ${line}`);
91
- return;
92
- }
93
- console.log(` ▸ ${line}`);
94
- if (!settleOutcome) return;
95
- if (/dropped frame/i.test(line)) settleOutcome('dropped');
96
- else if (/hot reload:\s*ok\b/i.test(line)) settleOutcome('ok');
97
- else if (/hot reload:/i.test(line)) settleOutcome('rejected');
98
- };
99
-
100
- const uploader = new SerialUploader({device, onLog: onDeviceLog});
101
- if (compilePackage) {
102
- transfer = new PackageTransfer({
103
- write: frame => uploader.writeFrame(frame),
104
- });
105
- }
106
-
107
- try {
108
- await uploader.open();
109
- } catch (error) {
110
- console.error(`✗ ${error.message}`);
111
- const ports = await listSerialPorts();
112
- if (ports.length) {
113
- console.error('\nAvailable ports:');
114
- for (const port of ports)
115
- console.error(
116
- ` ${port.path}${port.manufacturer ? ` (${port.manufacturer})` : ''}`,
117
- );
118
- }
119
- process.exit(1);
120
- }
121
-
122
- console.log(`embedded-react on-device hot reload → ${device}`);
123
- console.log(
124
- `watching ${relative(projectRoot, entry) || label} — edit & save to push. Ctrl-C to quit.`,
125
- );
126
- console.log(
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.',
130
- );
131
-
132
- const APPLY_TIMEOUT_MS = 15000; // a normal reload settles in ~3-4 s; this only catches a stuck device
133
- const PROBE_TIMEOUT_MS = 8000; // initial push: shorter, so a hot-reload-disabled board is flagged fast
134
- const MAX_RESENDS = 2;
135
-
136
- /** Resolves with the device's terminal status ('ok' | 'rejected' | 'dropped' | 'timeout') for the
137
- * push currently in flight. */
138
- const nextOutcome = (timeoutMs = APPLY_TIMEOUT_MS) =>
139
- new Promise(resolve => {
140
- let done = false;
141
- const finish = outcome => {
142
- if (done) return;
143
- done = true;
144
- settleOutcome = null;
145
- clearTimeout(timer);
146
- resolve(outcome);
147
- };
148
- const timer = setTimeout(() => finish('timeout'), timeoutMs);
149
- settleOutcome = finish; // armed before the send so the terminal log can't be missed
150
- });
151
-
152
- /** Send a container and wait for the device to apply it, resending on a transport drop/timeout. */
153
- const sendAndConfirm = async (
154
- container,
155
- {
156
- timeoutMs = APPLY_TIMEOUT_MS,
157
- maxResends = MAX_RESENDS,
158
- probe = false,
159
- } = {},
160
- ) => {
161
- for (let attempt = 0; ; attempt++) {
162
- const outcome = nextOutcome(timeoutMs);
163
- uploader.send(container).catch(error => {
164
- if (closing) return;
165
- if (settleOutcome) settleOutcome('senderr');
166
- else console.error(`✗ send failed: ${error.message}`);
167
- });
168
- const result = await outcome;
169
- if (result === 'ok' || result === 'rejected') return result;
170
- // On the initial probe, a timeout / write stall means nothing is consuming frames — don't spin.
171
- if (probe && (result === 'timeout' || result === 'senderr'))
172
- return result;
173
- if (attempt >= maxResends) {
174
- console.error(
175
- `✗ reload ${result} after ${attempt + 1} attempts — save again to retry`,
176
- );
177
- return result;
178
- }
179
- console.log(`↻ ${result}; resending (${attempt + 1}/${maxResends})…`);
50
+ export async function runDeviceDevServer({ entry, projectRoot, libSrc, nodePaths, simDir, device, label, compilePackage, }) {
51
+ // Each push ends with exactly one terminal line in the device's log stream:
52
+ // "hot reload: ok (...)" → loaded and running
53
+ // "hot reload: <reason>" → loaded but the container was rejected (an app/runtime error)
54
+ // "dropped frame: <reason>" → the upload was corrupt / overran the device's RX buffer (transport)
55
+ // We watch for it to gate the next send (so a second push can't land while the device is still
56
+ // applying — which would overrun its RX buffer and corrupt that frame) and to resend after a drop.
57
+ let settleOutcome = null;
58
+ // Track whether the board is alive at all (any log line) and whether a hot-reload RECEIVER is actually
59
+ // running (it prints a "hot reload: …" or "dropped frame: …" line per frame). Firmware built WITHOUT
60
+ // ER_HOTRELOAD still prints normal logs but never those — that's how we flag a disabled build below.
61
+ let sawAnyLog = false;
62
+ let sawReceiverAck = false;
63
+ let closing = false; // set on Ctrl-C so we don't surface errors from a write canceled by the shutdown
64
+ let transfer = null;
65
+ const onDeviceLog = (line) => {
66
+ if (closing)
67
+ return;
68
+ sawAnyLog = true;
69
+ if (/dropped frame/i.test(line) || /(hot|erb) reload:/i.test(line))
70
+ sawReceiverAck = true;
71
+ if (transfer) {
72
+ if (!transfer.onLine(line))
73
+ console.log(` ▸ ${line}`);
74
+ return;
75
+ }
76
+ console.log(` ▸ ${line}`);
77
+ if (!settleOutcome)
78
+ return;
79
+ if (/dropped frame/i.test(line))
80
+ settleOutcome('dropped');
81
+ else if (/hot reload:\s*ok\b/i.test(line))
82
+ settleOutcome('ok');
83
+ else if (/hot reload:/i.test(line))
84
+ settleOutcome('rejected');
85
+ };
86
+ const uploader = new SerialUploader({ device, onLog: onDeviceLog });
87
+ if (compilePackage) {
88
+ transfer = new PackageTransfer({
89
+ write: frame => uploader.writeFrame(frame),
90
+ });
180
91
  }
181
- };
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
92
  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`);
93
+ await uploader.open();
208
94
  }
209
- };
210
-
211
- // Single-flight: one build→send→apply cycle at a time. A save that lands mid-cycle just re-arms it, so
212
- // we rebuild and resend the latest source once the current reload settles — pushes never overlap.
213
- let inFlight = false;
214
- let queued = false;
215
- const reloadCycle = async ({probe = false} = {}) => {
216
- if (inFlight) {
217
- queued = true;
218
- return;
95
+ catch (error) {
96
+ console.error(`✗ ${error.message}`);
97
+ const ports = await listSerialPorts();
98
+ if (ports.length) {
99
+ console.error('\nAvailable ports:');
100
+ for (const port of ports)
101
+ console.error(` ${port.path}${port.manufacturer ? ` (${port.manufacturer})` : ''}`);
102
+ }
103
+ process.exit(1);
219
104
  }
220
- inFlight = true;
221
- try {
222
- let firstSend = probe; // the probe timeout applies to the initial push only
223
- do {
224
- queued = false;
225
- if (compilePackage) {
226
- await reloadPackage({probe: firstSend});
227
- firstSend = false;
228
- continue;
105
+ console.log(`embedded-react on-device hot reload → ${device}`);
106
+ console.log(`watching ${relative(projectRoot, entry) || label} — edit & save to push. Ctrl-C to quit.`);
107
+ console.log(compilePackage
108
+ ? ' sending Flow B packages; the device must be running a Flow B firmware built with ER_HOTRELOAD=1.'
109
+ : ' sending app-only frames; the device must be running a split build (embedded-react build) so the vendor is resident.');
110
+ const APPLY_TIMEOUT_MS = 15000; // a normal reload settles in ~3-4 s; this only catches a stuck device
111
+ const PROBE_TIMEOUT_MS = 8000; // initial push: shorter, so a hot-reload-disabled board is flagged fast
112
+ const MAX_RESENDS = 2;
113
+ /** Resolves with the device's terminal status ('ok' | 'rejected' | 'dropped' | 'timeout') for the
114
+ * push currently in flight. */
115
+ const nextOutcome = (timeoutMs = APPLY_TIMEOUT_MS) => new Promise(resolve => {
116
+ let done = false;
117
+ const finish = (outcome) => {
118
+ if (done)
119
+ return;
120
+ done = true;
121
+ settleOutcome = null;
122
+ clearTimeout(timer);
123
+ resolve(outcome);
124
+ };
125
+ const timer = setTimeout(() => finish('timeout'), timeoutMs);
126
+ settleOutcome = finish; // armed before the send so the terminal log can't be missed
127
+ });
128
+ /** Send a container and wait for the device to apply it, resending on a transport drop/timeout. */
129
+ const sendAndConfirm = async (container, { timeoutMs = APPLY_TIMEOUT_MS, maxResends = MAX_RESENDS, probe = false, } = {}) => {
130
+ for (let attempt = 0;; attempt++) {
131
+ const outcome = nextOutcome(timeoutMs);
132
+ uploader.send(container).catch(error => {
133
+ if (closing)
134
+ return;
135
+ if (settleOutcome)
136
+ settleOutcome('senderr');
137
+ else
138
+ console.error(`✗ send failed: ${error.message}`);
139
+ });
140
+ const result = await outcome;
141
+ if (result === 'ok' || result === 'rejected')
142
+ return result;
143
+ // On the initial probe, a timeout / write stall means nothing is consuming frames — don't spin.
144
+ if (probe && (result === 'timeout' || result === 'senderr'))
145
+ return result;
146
+ if (attempt >= maxResends) {
147
+ console.error(`✗ reload ${result} after ${attempt + 1} attempts — save again to retry`);
148
+ return result;
149
+ }
150
+ console.log(`↻ ${result}; resending (${attempt + 1}/${maxResends})…`);
229
151
  }
152
+ };
153
+ let triedToSend = false; // a first save that doesn't build says nothing about the board
154
+ /** One Flow B cycle: compile a package, send it and report how it went. */
155
+ const reloadPackage = async (compilePackage, { probe }) => {
230
156
  const started = Date.now();
231
- let container, bytecodeLength, assetsLength;
157
+ let packageData;
232
158
  try {
233
- const app = await packApp({
234
- entry,
235
- projectRoot,
236
- libSrc,
237
- nodePaths,
238
- simDir,
239
- persist: true,
240
- });
241
- container = await emitAppFrame({
242
- appBytecode: app.bytecode,
243
- assetPack: app.assetPack,
244
- });
245
- bytecodeLength = app.bytecodeLen;
246
- assetsLength = app.assetsLen;
247
- } catch (error) {
248
- console.error(`✗ build failed: ${error.message}`);
249
- continue;
159
+ packageData = await compilePackage();
160
+ }
161
+ catch (error) {
162
+ console.error(`✗ build failed: ${error.message}`);
163
+ return;
250
164
  }
251
165
  triedToSend = true;
252
- const result = await sendAndConfirm(
253
- container,
254
- firstSend ? {timeoutMs: PROBE_TIMEOUT_MS, probe: true} : {},
255
- );
256
- firstSend = false;
166
+ const result = await transfer
167
+ .send(packageData, probe ? { beginTimeoutMs: PROBE_TIMEOUT_MS } : {})
168
+ .catch((error) => {
169
+ if (!closing)
170
+ console.error(`✗ send failed: ${error.message}`);
171
+ return 'senderr';
172
+ });
257
173
  if (result === 'ok') {
258
- console.log(
259
- `↻ reloaded app ${kb(container.length)} (bytecode ${kb(bytecodeLength)}` +
260
- (assetsLength ? `, assets ${kb(assetsLength)}` : '') +
261
- `) in ${Date.now() - started} ms`,
262
- );
174
+ console.log(`↻ reloaded package ${kb(packageData.length)} in ${Date.now() - started} ms`);
263
175
  }
264
- } while (queued);
265
- } finally {
266
- inFlight = false;
267
- }
268
- };
269
-
270
- // Before flooding the port with a frame, give the board a moment to prove it's alive (one log line is
271
- // enough). Flooding a firmware that never drains its RX can congest the link, so we sample liveness
272
- // first — this is also what tells "hot reload disabled" apart from "dead/wrong port" if no ack comes.
273
- for (let check = 0; check < LIVENESS_CHECKS && !sawAnyLog; check++)
274
- await new Promise(resolve => setTimeout(resolve, LIVENESS_INTERVAL_MS));
275
-
276
- await reloadCycle({probe: true});
277
- if (triedToSend && !sawReceiverAck) {
278
- console.warn('');
279
- console.warn('⚠ the board never acknowledged the hot-reload frame.');
280
- if (sawAnyLog) {
281
- console.warn(
282
- ' It IS sending logs, so the port is right — but nothing is consuming reload frames.',
283
- );
284
- console.warn(
285
- " Its firmware likely doesn't have the on-device hot-reload receiver enabled.",
286
- );
287
- } else {
288
- console.warn(
289
- ' No logs are coming back either — check the USB cable/port, and that the app is running.',
290
- );
176
+ else if (result !== 'rejected' && result !== 'senderr') {
177
+ console.error(`✗ reload ${result} — save again to retry`);
178
+ }
179
+ };
180
+ // Single-flight: one build→send→apply cycle at a time. A save that lands mid-cycle just re-arms it, so
181
+ // we rebuild and resend the latest source once the current reload settles — pushes never overlap.
182
+ let inFlight = false;
183
+ let queued = false;
184
+ const reloadCycle = async ({ probe = false } = {}) => {
185
+ if (inFlight) {
186
+ queued = true;
187
+ return;
188
+ }
189
+ inFlight = true;
190
+ try {
191
+ let firstSend = probe; // the probe timeout applies to the initial push only
192
+ do {
193
+ queued = false;
194
+ if (compilePackage) {
195
+ await reloadPackage(compilePackage, { probe: firstSend });
196
+ firstSend = false;
197
+ continue;
198
+ }
199
+ const started = Date.now();
200
+ let container, bytecodeLength, assetsLength;
201
+ try {
202
+ const app = await packApp({
203
+ entry,
204
+ projectRoot,
205
+ libSrc,
206
+ nodePaths,
207
+ simDir,
208
+ persist: true,
209
+ });
210
+ container = await emitAppFrame({
211
+ appBytecode: app.bytecode,
212
+ assetPack: app.assetPack,
213
+ });
214
+ bytecodeLength = app.bytecodeLen;
215
+ assetsLength = app.assetsLen;
216
+ }
217
+ catch (error) {
218
+ console.error(`✗ build failed: ${error.message}`);
219
+ continue;
220
+ }
221
+ triedToSend = true;
222
+ const result = await sendAndConfirm(container, firstSend ? { timeoutMs: PROBE_TIMEOUT_MS, probe: true } : {});
223
+ firstSend = false;
224
+ if (result === 'ok') {
225
+ console.log(`↻ reloaded app ${kb(container.length)} (bytecode ${kb(bytecodeLength)}` +
226
+ (assetsLength ? `, assets ${kb(assetsLength)}` : '') +
227
+ `) in ${Date.now() - started} ms`);
228
+ }
229
+ } while (queued);
230
+ }
231
+ finally {
232
+ inFlight = false;
233
+ }
234
+ };
235
+ // Before flooding the port with a frame, give the board a moment to prove it's alive (one log line is
236
+ // enough). Flooding a firmware that never drains its RX can congest the link, so we sample liveness
237
+ // first — this is also what tells "hot reload disabled" apart from "dead/wrong port" if no ack comes.
238
+ for (let check = 0; check < LIVENESS_CHECKS && !sawAnyLog; check++)
239
+ await new Promise(resolve => setTimeout(resolve, LIVENESS_INTERVAL_MS));
240
+ await reloadCycle({ probe: true });
241
+ if (triedToSend && !sawReceiverAck) {
242
+ console.warn('');
243
+ console.warn('⚠ the board never acknowledged the hot-reload frame.');
244
+ if (sawAnyLog) {
245
+ console.warn(' It IS sending logs, so the port is right — but nothing is consuming reload frames.');
246
+ console.warn(" Its firmware likely doesn't have the on-device hot-reload receiver enabled.");
247
+ }
248
+ else {
249
+ console.warn(' No logs are coming back either — check the USB cable/port, and that the app is running.');
250
+ }
251
+ console.warn(' (still watching — fix it and save again to retry)');
252
+ console.warn('');
291
253
  }
292
- console.warn(' (still watching — fix it and save again to retry)');
293
- console.warn('');
294
- }
295
-
296
- const onChange = debounce(reloadCycle, WATCH_DEBOUNCE_MS);
297
- const onWatchEvent = (_event, file) => {
298
- if (!file) return;
299
- // Ignore churn that can't affect the bundle (build output, deps, VCS, editor temp files).
300
- if (/(^|\/)(node_modules|dist|\.git)(\/|$)/.test(file)) return;
301
- if (/\.(erpkg|map)$|~$|\.swp$/.test(file)) return;
302
- onChange();
303
- };
304
-
305
- // Recursively watch the project so edits under src/** push too — on every platform, including ones
306
- // where fs.watch's native {recursive:true} isn't available (older Linux/Node).
307
- const watcher = watchTree(projectRoot, onWatchEvent);
308
-
309
- const shutdown = async () => {
310
- closing = true;
311
- watcher.close();
312
- await uploader.close();
313
- process.exit(0);
314
- };
315
- process.on('SIGINT', shutdown);
316
- process.on('SIGTERM', shutdown);
254
+ const onChange = debounce(reloadCycle, WATCH_DEBOUNCE_MS);
255
+ const onWatchEvent = (_event, file) => {
256
+ if (!file)
257
+ return;
258
+ // Ignore churn that can't affect the bundle (build output, deps, VCS, editor temp files).
259
+ if (/(^|\/)(node_modules|dist|\.git)(\/|$)/.test(file))
260
+ return;
261
+ if (/\.(erpkg|map)$|~$|\.swp$/.test(file))
262
+ return;
263
+ onChange();
264
+ };
265
+ // Recursively watch the project so edits under src/** push too — on every platform, including ones
266
+ // where fs.watch's native {recursive:true} isn't available (older Linux/Node).
267
+ const watcher = watchTree(projectRoot, onWatchEvent);
268
+ const shutdown = async () => {
269
+ closing = true;
270
+ watcher.close();
271
+ await uploader.close();
272
+ process.exit(0);
273
+ };
274
+ process.on('SIGINT', shutdown);
275
+ process.on('SIGTERM', shutdown);
317
276
  }