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
package/flash.mjs CHANGED
@@ -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
  // flash — writes a Flow B package into one of a board's two package slots.
18
17
  //
19
18
  // A slot holds a header in an erase sector of its own, then the package. The firmware
@@ -22,13 +21,11 @@
22
21
  // headers and writes the package, then the header, so its own write cut short never leaves the newest sequence on
23
22
  // a partial package. `pack` writes the image to a file instead, for a factory line or a drag-and-drop UF2, which
24
23
  // can't promise that order, so `flash` also checks the newest slot's package before it writes over the other.
25
-
26
- import {spawnSync} from 'node:child_process';
27
- import {mkdtempSync, readFileSync, rmSync, writeFileSync} from 'node:fs';
28
- import {tmpdir} from 'node:os';
29
- import {join} from 'node:path';
30
- import {crc32} from './assets/emit-container.mjs';
31
-
24
+ import { spawnSync } from 'node:child_process';
25
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
26
+ import { tmpdir } from 'node:os';
27
+ import { join } from 'node:path';
28
+ import { crc32 } from './assets/emit-container.mjs';
32
29
  export const SLOT_HEADER_BYTES = 4096; // bytes before the package: one erase sector
33
30
  const SLOT_HEADER_PAGE_BYTES = 256; // the part of it that is written
34
31
  const SEQUENCE_MAX = 0xffffffff;
@@ -40,7 +37,6 @@ const SLOT_PACKAGE_LENGTH_AT = 8;
40
37
  const SLOT_HEADER_CHECKED_BYTES = 12;
41
38
  const SLOT_HEADER_CRC_BYTES = 4;
42
39
  const SLOT_NAMES = ['a', 'b'];
43
-
44
40
  const CONTAINER_MAGIC = 'ERCF';
45
41
  const CONTAINER_MAGIC_BYTES = 4;
46
42
  const CONTAINER_CRC_AT = 8;
@@ -48,7 +44,6 @@ const CONTAINER_CRC_END = 12;
48
44
  const CONTAINER_TAG_AT = 12;
49
45
  const CONTAINER_TAG_LENGTH_BYTES = 2;
50
46
  const PACKAGE_TAG = 'erb';
51
-
52
47
  const ESP_PARTITION_TABLE_AT = 0x8000;
53
48
  const ESP_PARTITION_TABLE_BYTES = 0xc00;
54
49
  const ESP_PARTITION_ENTRY_BYTES = 32;
@@ -58,11 +53,9 @@ const ESP_PARTITION_SIZE_AT = 8;
58
53
  const ESP_PARTITION_LABEL_AT = 12;
59
54
  const ESP_PARTITION_LABEL_BYTES = 16;
60
55
  const ESP_SLOT_LABELS = ['erb_a', 'erb_b'];
61
-
62
56
  const PICO_REBOOT_TIMEOUT_MS = 10000;
63
57
  const PICO_READY_TRIES = 40;
64
58
  const PICO_READY_WAIT_MS = 250;
65
-
66
59
  const UF2_BLOCK_BYTES = 512;
67
60
  const UF2_PAYLOAD_BYTES = 256;
68
61
  const UF2_MAGIC_START_0 = 0x0a324655;
@@ -79,459 +72,362 @@ const UF2_BLOCK_COUNT_AT = 24;
79
72
  const UF2_FAMILY_AT = 28;
80
73
  const UF2_PAYLOAD_AT = 32;
81
74
  const UF2_MAGIC_END_AT = 508;
82
-
83
75
  /**
84
76
  * Where each board example keeps its slots. An ESP32 board's `flash` reads them from the partition table on the
85
77
  * board instead, so this is what `pack` prints for it. Keep it in step with the example's partitions.csv or
86
- * CMakeLists.txt: flash.unit.test.mjs checks that it is.
78
+ * CMakeLists.txt: flash.unit.test.mts checks that it is.
87
79
  */
88
80
  export const BOARDS = {
89
- 'esp32-2432s028r': {
90
- tool: 'esptool',
91
- chip: 'esp32',
92
- slots: [
93
- {address: 0x180000, bytes: 0x140000},
94
- {address: 0x2c0000, bytes: 0x140000},
95
- ],
96
- },
97
- 'esp32-s3': {
98
- tool: 'esptool',
99
- chip: 'esp32s3',
100
- slots: [
101
- {address: 0x510000, bytes: 0x200000},
102
- {address: 0x710000, bytes: 0x200000},
103
- ],
104
- },
105
- 'rp2040-touch-lcd-1.69': {
106
- tool: 'picotool',
107
- slots: [
108
- {address: 0x10100000, bytes: 0x80000},
109
- {address: 0x10180000, bytes: 0x80000},
110
- ],
111
- },
81
+ 'esp32-2432s028r': {
82
+ tool: 'esptool',
83
+ chip: 'esp32',
84
+ slots: [
85
+ { address: 0x180000, bytes: 0x140000 },
86
+ { address: 0x2c0000, bytes: 0x140000 },
87
+ ],
88
+ },
89
+ 'esp32-s3': {
90
+ tool: 'esptool',
91
+ chip: 'esp32s3',
92
+ slots: [
93
+ { address: 0x510000, bytes: 0x200000 },
94
+ { address: 0x710000, bytes: 0x200000 },
95
+ ],
96
+ },
97
+ 'rp2040-touch-lcd-1.69': {
98
+ tool: 'picotool',
99
+ slots: [
100
+ { address: 0x10100000, bytes: 0x80000 },
101
+ { address: 0x10180000, bytes: 0x80000 },
102
+ ],
103
+ },
112
104
  };
113
-
114
- const hex = value => `0x${value.toString(16)}`;
115
-
105
+ const hex = (value) => `0x${value.toString(16)}`;
116
106
  /** The board for a --board value; throws naming the ones there are. */
117
107
  export function boardByName(name) {
118
- const board = BOARDS[name];
119
- if (!board) {
120
- throw new Error(
121
- `${name ? `Unknown board "${name}"` : 'No board given'}: pass --board with one of ${Object.keys(BOARDS).join(', ')}.`,
122
- );
123
- }
124
- return board;
108
+ const board = name ? BOARDS[name] : undefined;
109
+ if (!board) {
110
+ throw new Error(`${name ? `Unknown board "${name}"` : 'No board given'}: pass --board with one of ${Object.keys(BOARDS).join(', ')}.`);
111
+ }
112
+ return board;
125
113
  }
126
-
127
114
  /** Checks the bytes are a whole Flow B package, so a stale or Flow A file never reaches a slot. */
128
115
  export function checkPackage(bytes) {
129
- if (
130
- bytes.length < CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES ||
131
- bytes.toString('latin1', 0, CONTAINER_MAGIC_BYTES) !== CONTAINER_MAGIC
132
- ) {
133
- throw new Error('Not a package: no ERCF container in this file.');
134
- }
135
- if (
136
- bytes.readUInt32LE(CONTAINER_CRC_AT) !==
137
- crc32(bytes.subarray(CONTAINER_CRC_END))
138
- ) {
139
- throw new Error('This package is corrupt: its CRC does not match.');
140
- }
141
- const tagBytes = bytes.readUInt16LE(CONTAINER_TAG_AT);
142
- const tag = bytes.toString(
143
- 'latin1',
144
- CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES,
145
- CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES + tagBytes,
146
- );
147
- if (tag !== PACKAGE_TAG) {
148
- throw new Error(
149
- `This is a Flow A container (built for ${tag}), not a Flow B package. Build one with: embedded-react build --aot`,
150
- );
151
- }
116
+ if (bytes.length < CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES ||
117
+ bytes.toString('latin1', 0, CONTAINER_MAGIC_BYTES) !== CONTAINER_MAGIC) {
118
+ throw new Error('Not a package: no ERCF container in this file.');
119
+ }
120
+ if (bytes.readUInt32LE(CONTAINER_CRC_AT) !==
121
+ crc32(bytes.subarray(CONTAINER_CRC_END))) {
122
+ throw new Error('This package is corrupt: its CRC does not match.');
123
+ }
124
+ const tagBytes = bytes.readUInt16LE(CONTAINER_TAG_AT);
125
+ const tag = bytes.toString('latin1', CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES, CONTAINER_TAG_AT + CONTAINER_TAG_LENGTH_BYTES + tagBytes);
126
+ if (tag !== PACKAGE_TAG) {
127
+ throw new Error(`This is a Flow A container (built for ${tag}), not a Flow B package. Build one with: embedded-react build --aot`);
128
+ }
152
129
  }
153
-
154
130
  /** Whether the bytes are a whole Flow B package. */
155
131
  function isWholePackage(bytes) {
156
- try {
157
- checkPackage(bytes);
158
- return true;
159
- } catch {
160
- return false;
161
- }
132
+ try {
133
+ checkPackage(bytes);
134
+ return true;
135
+ }
136
+ catch {
137
+ return false;
138
+ }
162
139
  }
163
-
164
140
  /** A slot's header page. */
165
141
  export function slotHeader(packageLength, sequence) {
166
- const header = Buffer.alloc(SLOT_HEADER_PAGE_BYTES, ERASED_BYTE);
167
- header.writeUInt32LE(SLOT_MAGIC, SLOT_MAGIC_AT);
168
- header.writeUInt32LE(sequence, SLOT_SEQUENCE_AT);
169
- header.writeUInt32LE(packageLength, SLOT_PACKAGE_LENGTH_AT);
170
- header.writeUInt32LE(
171
- crc32(header.subarray(0, SLOT_HEADER_CHECKED_BYTES)),
172
- SLOT_HEADER_CHECKED_BYTES,
173
- );
174
- return header;
142
+ const header = Buffer.alloc(SLOT_HEADER_PAGE_BYTES, ERASED_BYTE);
143
+ header.writeUInt32LE(SLOT_MAGIC, SLOT_MAGIC_AT);
144
+ header.writeUInt32LE(sequence, SLOT_SEQUENCE_AT);
145
+ header.writeUInt32LE(packageLength, SLOT_PACKAGE_LENGTH_AT);
146
+ header.writeUInt32LE(crc32(header.subarray(0, SLOT_HEADER_CHECKED_BYTES)), SLOT_HEADER_CHECKED_BYTES);
147
+ return header;
175
148
  }
176
-
177
149
  /** A slot's whole image: the header in its sector, then the package. */
178
150
  export function slotImage(packageBytes, sequence) {
179
- const headerSector = Buffer.alloc(SLOT_HEADER_BYTES, ERASED_BYTE);
180
- slotHeader(packageBytes.length, sequence).copy(headerSector);
181
- return Buffer.concat([headerSector, packageBytes]);
151
+ const headerSector = Buffer.alloc(SLOT_HEADER_BYTES, ERASED_BYTE);
152
+ slotHeader(packageBytes.length, sequence).copy(headerSector);
153
+ return Buffer.concat([headerSector, packageBytes]);
182
154
  }
183
-
184
155
  /** What a slot's first bytes say: its sequence and package length, or null when it has no valid header. */
185
156
  export function readSlotHeader(bytes, slotBytes) {
186
- if (
187
- bytes.length < SLOT_HEADER_CHECKED_BYTES + SLOT_HEADER_CRC_BYTES ||
188
- bytes.readUInt32LE(SLOT_MAGIC_AT) !== SLOT_MAGIC ||
189
- bytes.readUInt32LE(SLOT_HEADER_CHECKED_BYTES) !==
190
- crc32(bytes.subarray(0, SLOT_HEADER_CHECKED_BYTES))
191
- ) {
192
- return null;
193
- }
194
- const packageBytes = bytes.readUInt32LE(SLOT_PACKAGE_LENGTH_AT);
195
- if (packageBytes === 0 || packageBytes > slotBytes - SLOT_HEADER_BYTES) {
196
- return null;
197
- }
198
- return {sequence: bytes.readUInt32LE(SLOT_SEQUENCE_AT), packageBytes};
157
+ if (bytes.length < SLOT_HEADER_CHECKED_BYTES + SLOT_HEADER_CRC_BYTES ||
158
+ bytes.readUInt32LE(SLOT_MAGIC_AT) !== SLOT_MAGIC ||
159
+ bytes.readUInt32LE(SLOT_HEADER_CHECKED_BYTES) !==
160
+ crc32(bytes.subarray(0, SLOT_HEADER_CHECKED_BYTES))) {
161
+ return null;
162
+ }
163
+ const packageBytes = bytes.readUInt32LE(SLOT_PACKAGE_LENGTH_AT);
164
+ if (packageBytes === 0 || packageBytes > slotBytes - SLOT_HEADER_BYTES) {
165
+ return null;
166
+ }
167
+ return { sequence: bytes.readUInt32LE(SLOT_SEQUENCE_AT), packageBytes };
199
168
  }
200
-
201
169
  /** A slot's sequence from its first bytes, or null when it has no valid header. */
202
170
  export function readSlotSequence(bytes, slotBytes) {
203
- return readSlotHeader(bytes, slotBytes)?.sequence ?? null;
171
+ return readSlotHeader(bytes, slotBytes)?.sequence ?? null;
204
172
  }
205
-
206
173
  /**
207
174
  * Picks the slot for a new package from the two slots' sequences (null for none): the one that isn't the
208
175
  * newest, with the next sequence. The firmware makes the same choice (erb_package_slots_boot).
209
176
  */
210
177
  export function pickSlot([first, second]) {
211
- // A signed difference, so the order survives the sequence wrapping.
212
- const secondIsNewer =
213
- second !== null && (first === null || (second - first) << 0 > 0);
214
- const newest = secondIsNewer ? 1 : 0;
215
- const newestSequence = secondIsNewer ? second : first;
216
- if (newestSequence === null) return {slot: 0, sequence: 1, lastGood: null};
217
- return {
218
- slot: 1 - newest,
219
- sequence: (newestSequence + 1) >>> 0,
220
- lastGood: newest,
221
- };
178
+ // A signed difference, so the order survives the sequence wrapping.
179
+ const secondIsNewer = second !== null && (first === null || (second - first) << 0 > 0);
180
+ const newest = secondIsNewer ? 1 : 0;
181
+ const newestSequence = secondIsNewer ? second : first;
182
+ if (newestSequence === null)
183
+ return { slot: 0, sequence: 1, lastGood: null };
184
+ return {
185
+ slot: 1 - newest,
186
+ sequence: (newestSequence + 1) >>> 0,
187
+ lastGood: newest,
188
+ };
222
189
  }
223
-
224
190
  /**
225
191
  * Runs of bytes as UF2 blocks, in the order given, for a drag-and-drop onto an RP2040 in BOOTSEL mode.
226
192
  *
227
- * @param {{address: number, bytes: Buffer}[]} runs What to write where.
193
+ * @param runs What to write where.
228
194
  */
229
195
  export function uf2(runs) {
230
- const pages = runs.flatMap(({address, bytes}) =>
231
- Array.from(
232
- {length: Math.ceil(bytes.length / UF2_PAYLOAD_BYTES)},
233
- (_, page) => ({
196
+ const pages = runs.flatMap(({ address, bytes }) => Array.from({ length: Math.ceil(bytes.length / UF2_PAYLOAD_BYTES) }, (_, page) => ({
234
197
  address: address + page * UF2_PAYLOAD_BYTES,
235
- bytes: bytes.subarray(
236
- page * UF2_PAYLOAD_BYTES,
237
- (page + 1) * UF2_PAYLOAD_BYTES,
238
- ),
239
- }),
240
- ),
241
- );
242
- const blockCount = pages.length;
243
- const blocks = Buffer.alloc(blockCount * UF2_BLOCK_BYTES);
244
- for (let block = 0; block < blockCount; block++) {
245
- const at = block * UF2_BLOCK_BYTES;
246
- blocks.writeUInt32LE(UF2_MAGIC_START_0, at);
247
- blocks.writeUInt32LE(UF2_MAGIC_START_1, at + UF2_MAGIC_START_1_AT);
248
- blocks.writeUInt32LE(UF2_FLAG_FAMILY, at + UF2_FLAGS_AT);
249
- blocks.writeUInt32LE(pages[block].address, at + UF2_ADDRESS_AT);
250
- blocks.writeUInt32LE(UF2_PAYLOAD_BYTES, at + UF2_PAYLOAD_SIZE_AT);
251
- blocks.writeUInt32LE(block, at + UF2_BLOCK_NUMBER_AT);
252
- blocks.writeUInt32LE(blockCount, at + UF2_BLOCK_COUNT_AT);
253
- blocks.writeUInt32LE(UF2_FAMILY_RP2040, at + UF2_FAMILY_AT);
254
- // A short last page is padded as erased flash, since the bootrom programs whole pages.
255
- blocks.fill(
256
- ERASED_BYTE,
257
- at + UF2_PAYLOAD_AT,
258
- at + UF2_PAYLOAD_AT + UF2_PAYLOAD_BYTES,
259
- );
260
- pages[block].bytes.copy(blocks, at + UF2_PAYLOAD_AT);
261
- blocks.writeUInt32LE(UF2_MAGIC_END, at + UF2_MAGIC_END_AT);
262
- }
263
- return blocks;
198
+ bytes: bytes.subarray(page * UF2_PAYLOAD_BYTES, (page + 1) * UF2_PAYLOAD_BYTES),
199
+ })));
200
+ const blockCount = pages.length;
201
+ const blocks = Buffer.alloc(blockCount * UF2_BLOCK_BYTES);
202
+ for (let block = 0; block < blockCount; block++) {
203
+ const at = block * UF2_BLOCK_BYTES;
204
+ blocks.writeUInt32LE(UF2_MAGIC_START_0, at);
205
+ blocks.writeUInt32LE(UF2_MAGIC_START_1, at + UF2_MAGIC_START_1_AT);
206
+ blocks.writeUInt32LE(UF2_FLAG_FAMILY, at + UF2_FLAGS_AT);
207
+ blocks.writeUInt32LE(pages[block].address, at + UF2_ADDRESS_AT);
208
+ blocks.writeUInt32LE(UF2_PAYLOAD_BYTES, at + UF2_PAYLOAD_SIZE_AT);
209
+ blocks.writeUInt32LE(block, at + UF2_BLOCK_NUMBER_AT);
210
+ blocks.writeUInt32LE(blockCount, at + UF2_BLOCK_COUNT_AT);
211
+ blocks.writeUInt32LE(UF2_FAMILY_RP2040, at + UF2_FAMILY_AT);
212
+ // A short last page is padded as erased flash, since the bootrom programs whole pages.
213
+ blocks.fill(ERASED_BYTE, at + UF2_PAYLOAD_AT, at + UF2_PAYLOAD_AT + UF2_PAYLOAD_BYTES);
214
+ pages[block].bytes.copy(blocks, at + UF2_PAYLOAD_AT);
215
+ blocks.writeUInt32LE(UF2_MAGIC_END, at + UF2_MAGIC_END_AT);
216
+ }
217
+ return blocks;
264
218
  }
265
-
266
219
  /** The package slots in an ESP32 partition table's bytes, or null when the firmware on the board has none. */
267
220
  export function slotsFromPartitionTable(table) {
268
- const slots = [null, null];
269
- for (
270
- let at = 0;
271
- at + ESP_PARTITION_ENTRY_BYTES <= table.length;
272
- at += ESP_PARTITION_ENTRY_BYTES
273
- ) {
274
- if (table.readUInt16LE(at) !== ESP_PARTITION_MAGIC) break;
275
- const labelEnd = at + ESP_PARTITION_LABEL_AT + ESP_PARTITION_LABEL_BYTES;
276
- const label = table
277
- .toString('latin1', at + ESP_PARTITION_LABEL_AT, labelEnd)
278
- .replace(/\0.*$/, '');
279
- const index = ESP_SLOT_LABELS.indexOf(label);
280
- if (index >= 0) {
281
- slots[index] = {
282
- address: table.readUInt32LE(at + ESP_PARTITION_OFFSET_AT),
283
- bytes: table.readUInt32LE(at + ESP_PARTITION_SIZE_AT),
284
- };
221
+ const slots = [null, null];
222
+ for (let at = 0; at + ESP_PARTITION_ENTRY_BYTES <= table.length; at += ESP_PARTITION_ENTRY_BYTES) {
223
+ if (table.readUInt16LE(at) !== ESP_PARTITION_MAGIC)
224
+ break;
225
+ const labelEnd = at + ESP_PARTITION_LABEL_AT + ESP_PARTITION_LABEL_BYTES;
226
+ const label = table
227
+ .toString('latin1', at + ESP_PARTITION_LABEL_AT, labelEnd)
228
+ .replace(/\0.*$/, '');
229
+ const index = ESP_SLOT_LABELS.indexOf(label);
230
+ if (index >= 0) {
231
+ slots[index] = {
232
+ address: table.readUInt32LE(at + ESP_PARTITION_OFFSET_AT),
233
+ bytes: table.readUInt32LE(at + ESP_PARTITION_SIZE_AT),
234
+ };
235
+ }
285
236
  }
286
- }
287
- return slots.every(Boolean) ? slots : null;
237
+ return slots.every(Boolean) ? slots : null;
288
238
  }
289
-
290
239
  /** Runs the first of a tool's names that exists; throws with its output when it fails. */
291
- function runTool(names, args, {run, install, inherit = false, timeoutMs}) {
292
- for (const name of names) {
293
- const result = run(name, args, inherit, timeoutMs);
294
- if (result.error?.code === 'ENOENT') continue;
295
- if (result.error) throw result.error;
296
- if (result.status !== 0) {
297
- throw new Error(
298
- `${name} ${args.join(' ')} failed:\n${result.stderr ?? ''}${result.stdout ?? ''}`.trimEnd(),
299
- );
240
+ function runTool(names, args, { run, install, inherit = false, timeoutMs }) {
241
+ for (const name of names) {
242
+ const result = run(name, args, inherit, timeoutMs);
243
+ if (result.error?.code === 'ENOENT')
244
+ continue;
245
+ if (result.error)
246
+ throw result.error;
247
+ if (result.status !== 0) {
248
+ throw new Error(`${name} ${args.join(' ')} failed:\n${result.stderr ?? ''}${result.stdout ?? ''}`.trimEnd());
249
+ }
250
+ return;
300
251
  }
301
- return;
302
- }
303
- throw new Error(`${names[0]} wasn't found. ${install}`);
252
+ throw new Error(`${names[0]} wasn't found. ${install}`);
304
253
  }
305
-
306
- const sleepMs = ms =>
307
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
308
-
309
- const defaultRun = (command, args, inherit, timeoutMs) =>
310
- spawnSync(command, args, {
254
+ const sleepMs = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
255
+ const defaultRun = (command, args, inherit, timeoutMs) => spawnSync(command, args, {
311
256
  encoding: 'utf8',
312
257
  stdio: inherit ? 'inherit' : 'pipe',
313
258
  timeout: timeoutMs,
314
- });
315
-
316
- const espAccess = ({chip, port, run}) => {
317
- const names = process.env.ESPTOOL
318
- ? [process.env.ESPTOOL]
319
- : ['esptool', 'esptool.py'];
320
- const common = ['--chip', chip, ...(port ? ['--port', port] : [])];
321
- const options = {
322
- run,
323
- install: 'Export ESP-IDF first (. $IDF_PATH/export.sh), or set ESPTOOL.',
324
- };
325
- // The underscored commands: esptool 4 takes only these, and esptool 5 still does.
326
- const read = (address, bytes, file) =>
327
- runTool(
328
- names,
329
- [...common, 'read_flash', hex(address), hex(bytes), file],
330
- options,
331
- );
332
- return {
333
- read,
334
- slots: dir => {
335
- const file = join(dir, 'partitions.bin');
336
- read(ESP_PARTITION_TABLE_AT, ESP_PARTITION_TABLE_BYTES, file);
337
- const slots = slotsFromPartitionTable(readFileSync(file));
338
- if (!slots) {
339
- throw new Error(
340
- "The board's partition table has no erb_a and erb_b partitions. Flash this example's Flow B firmware first.",
341
- );
342
- }
343
- return slots;
344
- },
345
- write: (address, file) =>
346
- runTool(names, [...common, 'write_flash', hex(address), file], {
347
- ...options,
348
- inherit: true,
349
- }),
350
- begin: () => {},
351
- finish: () => {}, // esptool resets the board itself after each command
352
- };
259
+ });
260
+ const espAccess = ({ chip, port, run, }) => {
261
+ const names = process.env.ESPTOOL
262
+ ? [process.env.ESPTOOL]
263
+ : ['esptool', 'esptool.py'];
264
+ const common = ['--chip', chip, ...(port ? ['--port', port] : [])];
265
+ const options = {
266
+ run,
267
+ install: 'Export ESP-IDF first (. $IDF_PATH/export.sh), or set ESPTOOL.',
268
+ };
269
+ // The underscored commands: esptool 4 takes only these, and esptool 5 still does.
270
+ const read = (address, bytes, file) => runTool(names, [...common, 'read_flash', hex(address), hex(bytes), file], options);
271
+ return {
272
+ read,
273
+ slots: dir => {
274
+ const file = join(dir, 'partitions.bin');
275
+ read(ESP_PARTITION_TABLE_AT, ESP_PARTITION_TABLE_BYTES, file);
276
+ const slots = slotsFromPartitionTable(readFileSync(file));
277
+ if (!slots) {
278
+ throw new Error("The board's partition table has no erb_a and erb_b partitions. Flash this example's Flow B firmware first.");
279
+ }
280
+ return slots;
281
+ },
282
+ write: (address, file) => runTool(names, [...common, 'write_flash', hex(address), file], {
283
+ ...options,
284
+ inherit: true,
285
+ }),
286
+ begin: () => { },
287
+ finish: () => { }, // esptool resets the board itself after each command
288
+ };
353
289
  };
354
-
355
- const picoAccess = ({board, run, sleep}) => {
356
- const names = process.env.PICOTOOL ? [process.env.PICOTOOL] : ['picotool'];
357
- const options = {
358
- run,
359
- install:
360
- "Install one with USB support, such as Homebrew's, or set PICOTOOL. The copy a Pico SDK build fetches has none.",
361
- };
362
- // libusb on macOS can deadlock as the board detaches, leaving picotool stuck after the reboot worked. What comes
363
- // next shows whether it did, so a reboot that outlives the timeout isn't a failure.
364
- const reboot = args => {
365
- try {
366
- runTool(names, args, {...options, timeoutMs: PICO_REBOOT_TIMEOUT_MS});
367
- } catch (error) {
368
- if (error.code !== 'ETIMEDOUT') throw error;
369
- }
370
- };
371
- return {
372
- // The board stays in BOOTSEL for the whole write: a command straight after a -f one finds it still rebooting.
373
- // -f takes a running board there through its USB serial, and a board already there stays.
374
- begin: () => {
375
- reboot(['reboot', '-u', '-f']);
376
- for (let tries = 1; ; tries++) {
290
+ const picoAccess = ({ board, run, sleep, }) => {
291
+ const names = process.env.PICOTOOL ? [process.env.PICOTOOL] : ['picotool'];
292
+ const options = {
293
+ run,
294
+ install: "Install one with USB support, such as Homebrew's, or set PICOTOOL. The copy a Pico SDK build fetches has none.",
295
+ };
296
+ // libusb on macOS can deadlock as the board detaches, leaving picotool stuck after the reboot worked. What comes
297
+ // next shows whether it did, so a reboot that outlives the timeout isn't a failure.
298
+ const reboot = (args) => {
377
299
  try {
378
- runTool(names, ['info'], {
379
- ...options,
380
- timeoutMs: PICO_REBOOT_TIMEOUT_MS,
381
- });
382
- return;
383
- } catch (error) {
384
- if (tries === PICO_READY_TRIES) throw error;
385
- sleep(PICO_READY_WAIT_MS);
300
+ runTool(names, args, { ...options, timeoutMs: PICO_REBOOT_TIMEOUT_MS });
386
301
  }
387
- }
388
- },
389
- // Addresses are memory addresses for both commands: load's -o defaults to 0x10000000, the start of flash.
390
- read: (address, bytes, file) =>
391
- runTool(
392
- names,
393
- ['save', '-r', hex(address), hex(address + bytes), file, '-t', 'bin'],
394
- options,
395
- ),
396
- slots: () => board.slots,
397
- write: (address, file) =>
398
- runTool(names, ['load', file, '-t', 'bin', '-o', hex(address)], {
399
- ...options,
400
- inherit: true,
401
- }),
402
- finish: () => reboot(['reboot']),
403
- };
302
+ catch (error) {
303
+ if (error.code !== 'ETIMEDOUT')
304
+ throw error;
305
+ }
306
+ };
307
+ return {
308
+ // The board stays in BOOTSEL for the whole write: a command straight after a -f one finds it still rebooting.
309
+ // -f takes a running board there through its USB serial, and a board already there stays.
310
+ begin: () => {
311
+ reboot(['reboot', '-u', '-f']);
312
+ for (let tries = 1;; tries++) {
313
+ try {
314
+ runTool(names, ['info'], {
315
+ ...options,
316
+ timeoutMs: PICO_REBOOT_TIMEOUT_MS,
317
+ });
318
+ return;
319
+ }
320
+ catch (error) {
321
+ if (tries === PICO_READY_TRIES)
322
+ throw error;
323
+ sleep(PICO_READY_WAIT_MS);
324
+ }
325
+ }
326
+ },
327
+ // Addresses are memory addresses for both commands: load's -o defaults to 0x10000000, the start of flash.
328
+ read: (address, bytes, file) => runTool(names, ['save', '-r', hex(address), hex(address + bytes), file, '-t', 'bin'], options),
329
+ slots: () => board.slots,
330
+ write: (address, file) => runTool(names, ['load', file, '-t', 'bin', '-o', hex(address)], {
331
+ ...options,
332
+ inherit: true,
333
+ }),
334
+ finish: () => reboot(['reboot']),
335
+ };
404
336
  };
405
-
406
337
  /**
407
338
  * Writes a package's slot image to a file, for a line or a drag-and-drop. Nothing here knows what the board holds,
408
339
  * so it is for an empty board, or a slot and sequence you already know.
409
- *
410
- * @returns {{file: string, address: number, sequence: number, slot: string}}
411
340
  */
412
- export function packSlot({
413
- packageBytes,
414
- board,
415
- boardName,
416
- slotName = 'a',
417
- sequence = 1,
418
- outDir,
419
- }) {
420
- const slot = SLOT_NAMES.indexOf(slotName);
421
- if (slot < 0) throw new Error(`--slot takes a or b, got: ${slotName}`);
422
- // 0 is valid: it is what comes after the sequence wraps.
423
- if (!Number.isInteger(sequence) || sequence < 0 || sequence > SEQUENCE_MAX) {
424
- throw new Error(
425
- `--sequence takes a whole number from 0 to ${SEQUENCE_MAX}, got: ${sequence}`,
426
- );
427
- }
428
- checkPackage(packageBytes);
429
- const {address, bytes} = board.slots[slot];
430
- const image = slotImage(packageBytes, sequence);
431
- if (image.length > bytes) {
432
- throw new Error(
433
- `The package takes ${image.length} B with its header, and ${boardName}'s slots hold ${bytes} B.`,
434
- );
435
- }
436
- const isUf2 = board.tool === 'picotool';
437
- const file = join(outDir, `app.slot-${slotName}.${isUf2 ? 'uf2' : 'bin'}`);
438
- writeFileSync(
439
- file,
440
- isUf2
441
- ? uf2([
442
- {address: address + SLOT_HEADER_BYTES, bytes: packageBytes},
443
- {address, bytes: slotHeader(packageBytes.length, sequence)},
341
+ export function packSlot({ packageBytes, board, boardName, slotName = 'a', sequence = 1, outDir, }) {
342
+ const slot = SLOT_NAMES.indexOf(slotName);
343
+ if (slot < 0)
344
+ throw new Error(`--slot takes a or b, got: ${slotName}`);
345
+ // 0 is valid: it is what comes after the sequence wraps.
346
+ if (!Number.isInteger(sequence) || sequence < 0 || sequence > SEQUENCE_MAX) {
347
+ throw new Error(`--sequence takes a whole number from 0 to ${SEQUENCE_MAX}, got: ${sequence}`);
348
+ }
349
+ checkPackage(packageBytes);
350
+ const { address, bytes } = board.slots[slot];
351
+ const image = slotImage(packageBytes, sequence);
352
+ if (image.length > bytes) {
353
+ throw new Error(`The package takes ${image.length} B with its header, and ${boardName}'s slots hold ${bytes} B.`);
354
+ }
355
+ const isUf2 = board.tool === 'picotool';
356
+ const file = join(outDir, `app.slot-${slotName}.${isUf2 ? 'uf2' : 'bin'}`);
357
+ writeFileSync(file, isUf2
358
+ ? uf2([
359
+ { address: address + SLOT_HEADER_BYTES, bytes: packageBytes },
360
+ { address, bytes: slotHeader(packageBytes.length, sequence) },
444
361
  ])
445
- : image,
446
- );
447
- return {file, address, sequence, slot: slotName};
362
+ : image);
363
+ return { file, address, sequence, slot: slotName };
448
364
  }
449
-
450
365
  /**
451
366
  * Writes a package to a board: reads its slots, and writes the one that isn't the newest.
452
- *
453
- * @returns {{address: number, sequence: number, slot: string, lastGood: string|null}}
454
367
  */
455
- export function flashSlot({
456
- packageBytes,
457
- board,
458
- port,
459
- run = defaultRun,
460
- log = () => {},
461
- sleep = sleepMs,
462
- }) {
463
- checkPackage(packageBytes);
464
- const access =
465
- board.tool === 'picotool'
466
- ? picoAccess({board, run, sleep})
467
- : espAccess({chip: board.chip, port, run});
468
- const scratchDir = mkdtempSync(join(tmpdir(), 'er-flash-'));
469
- let begun = false;
470
- try {
471
- access.begin();
472
- begun = true;
473
- const slots = access.slots(scratchDir);
474
- const headers = slots.map((slot, index) => {
475
- const file = join(scratchDir, `header-${index}.bin`);
476
- access.read(slot.address, SLOT_HEADER_PAGE_BYTES, file);
477
- return readSlotHeader(readFileSync(file), slot.bytes);
478
- });
479
- let {slot, sequence, lastGood} = pickSlot(
480
- headers.map(header => header?.sequence ?? null),
481
- );
482
- // The newest slot is what this write leaves as the fallback, so it has to be whole. A write cut short can leave
483
- // a header over part of a package, and no boot may have cleared it yet.
484
- if (lastGood !== null) {
485
- const file = join(scratchDir, 'newest.bin');
486
- access.read(
487
- slots[lastGood].address + SLOT_HEADER_BYTES,
488
- headers[lastGood].packageBytes,
489
- file,
490
- );
491
- if (!isWholePackage(readFileSync(file))) {
492
- log(
493
- `Slot ${SLOT_NAMES[lastGood]} holds a partial package, so it goes first`,
494
- );
495
- const other = 1 - lastGood;
496
- slot = lastGood;
497
- lastGood = headers[other] ? other : null;
498
- }
368
+ export function flashSlot({ packageBytes, board, port, run = defaultRun, log = () => { }, sleep = sleepMs, }) {
369
+ checkPackage(packageBytes);
370
+ const access = board.tool === 'picotool'
371
+ ? picoAccess({ board, run, sleep })
372
+ : espAccess({ chip: board.chip, port, run });
373
+ const scratchDir = mkdtempSync(join(tmpdir(), 'er-flash-'));
374
+ let begun = false;
375
+ try {
376
+ access.begin();
377
+ begun = true;
378
+ const slots = access.slots(scratchDir);
379
+ const headers = slots.map((slot, index) => {
380
+ const file = join(scratchDir, `header-${index}.bin`);
381
+ access.read(slot.address, SLOT_HEADER_PAGE_BYTES, file);
382
+ return readSlotHeader(readFileSync(file), slot.bytes);
383
+ });
384
+ let { slot, sequence, lastGood } = pickSlot(headers.map(header => header?.sequence ?? null));
385
+ // The newest slot is what this write leaves as the fallback, so it has to be whole. A write cut short can leave
386
+ // a header over part of a package, and no boot may have cleared it yet.
387
+ if (lastGood !== null) {
388
+ const file = join(scratchDir, 'newest.bin');
389
+ access.read(slots[lastGood].address + SLOT_HEADER_BYTES, headers[lastGood].packageBytes, file);
390
+ if (!isWholePackage(readFileSync(file))) {
391
+ log(`Slot ${SLOT_NAMES[lastGood]} holds a partial package, so it goes first`);
392
+ const other = 1 - lastGood;
393
+ slot = lastGood;
394
+ lastGood = headers[other] ? other : null;
395
+ }
396
+ }
397
+ const { address, bytes } = slots[slot];
398
+ const slotBytesUsed = SLOT_HEADER_BYTES + packageBytes.length;
399
+ if (slotBytesUsed > bytes) {
400
+ throw new Error(`The package takes ${slotBytesUsed} B with its header, and this board's slots hold ${bytes} B.`);
401
+ }
402
+ const packageFile = join(scratchDir, 'package.bin');
403
+ const headerFile = join(scratchDir, 'header.bin');
404
+ writeFileSync(packageFile, packageBytes);
405
+ writeFileSync(headerFile, slotHeader(packageBytes.length, sequence));
406
+ log(`Writing slot ${SLOT_NAMES[slot]} at ${hex(address)}, sequence ${sequence} (${slotBytesUsed} B)`);
407
+ // The header last. Until then the slot still has its older sequence, or none, so it stays the one to write
408
+ // over if this is cut short, and the other slot stays the newest.
409
+ access.write(address + SLOT_HEADER_BYTES, packageFile);
410
+ access.write(address, headerFile);
411
+ begun = false;
412
+ access.finish();
413
+ return {
414
+ address,
415
+ sequence,
416
+ slot: SLOT_NAMES[slot],
417
+ lastGood: lastGood === null ? null : SLOT_NAMES[lastGood],
418
+ };
499
419
  }
500
- const {address, bytes} = slots[slot];
501
- const slotBytesUsed = SLOT_HEADER_BYTES + packageBytes.length;
502
- if (slotBytesUsed > bytes) {
503
- throw new Error(
504
- `The package takes ${slotBytesUsed} B with its header, and this board's slots hold ${bytes} B.`,
505
- );
420
+ catch (error) {
421
+ // Out of BOOTSEL if it can, without hiding what went wrong.
422
+ if (begun) {
423
+ try {
424
+ access.finish();
425
+ }
426
+ catch { }
427
+ }
428
+ throw error;
506
429
  }
507
- const packageFile = join(scratchDir, 'package.bin');
508
- const headerFile = join(scratchDir, 'header.bin');
509
- writeFileSync(packageFile, packageBytes);
510
- writeFileSync(headerFile, slotHeader(packageBytes.length, sequence));
511
- log(
512
- `Writing slot ${SLOT_NAMES[slot]} at ${hex(address)}, sequence ${sequence} (${slotBytesUsed} B)`,
513
- );
514
- // The header last. Until then the slot still has its older sequence, or none, so it stays the one to write
515
- // over if this is cut short, and the other slot stays the newest.
516
- access.write(address + SLOT_HEADER_BYTES, packageFile);
517
- access.write(address, headerFile);
518
- begun = false;
519
- access.finish();
520
- return {
521
- address,
522
- sequence,
523
- slot: SLOT_NAMES[slot],
524
- lastGood: lastGood === null ? null : SLOT_NAMES[lastGood],
525
- };
526
- } catch (error) {
527
- // Out of BOOTSEL if it can, without hiding what went wrong.
528
- if (begun) {
529
- try {
530
- access.finish();
531
- } catch {}
430
+ finally {
431
+ rmSync(scratchDir, { recursive: true, force: true });
532
432
  }
533
- throw error;
534
- } finally {
535
- rmSync(scratchDir, {recursive: true, force: true});
536
- }
537
433
  }