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,14 +13,13 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // `npm run pack [demo]` — builds a deployable ERCF config container (dist/app.erpkg).
18
17
  //
19
18
  // The full release path for Flow A: bundle the app (esbuild → IIFE), precompile it to QuickJS
20
19
  // bytecode (so the device never ships the parser or source text), bake the imported images/fonts into
21
20
  // an ERPK pack, and wrap both — with a QuickJS version stamp and an integrity CRC — into a single
22
21
  // .erpkg. That one file is "the config": load it with er_runtime_load_container() on the desktop, or
23
- // upload it to a device's config region. See packages/embedded-react/assets/emit-container.mjs for the
22
+ // upload it to a device's config region. See packages/embedded-react/assets/emit-container.mts for the
24
23
  // format, and er_runtime.h for the loader.
25
24
  //
26
25
  // npm run pack # default demo (thermostat)
@@ -28,176 +27,147 @@
28
27
  //
29
28
  // Prereq: the bytecode precompiler (er-bridge-quickjs-compile) must be built. This script searches the
30
29
  // usual build dirs and tells you how to build it if it's missing (override with ER_COMPILE_BIN).
31
- import {build} from 'esbuild';
32
- import {spawnSync} from 'node:child_process';
33
- import {fileURLToPath, pathToFileURL} from 'node:url';
34
- import {dirname, resolve, basename} from 'node:path';
35
- import {
36
- existsSync,
37
- readdirSync,
38
- readFileSync,
39
- writeFileSync,
40
- mkdirSync,
41
- } from 'node:fs';
42
- import {bakeImage} from './assets/bake-image.mjs';
43
- import {bakeFont} from './assets/bake-font.mjs';
44
- import {resolveFontJobs} from './assets/font-config.mjs';
45
- import {analyzeFontSizes, warnFontSizes} from './assets/font-sizes.mjs';
46
- import {warnMissingGlyphs} from './assets/glyph-coverage.mjs';
47
- import {emitAssetPack} from './assets/emit-pack.mjs';
48
- import {emitContainer} from './assets/emit-container.mjs';
49
- import {registerSvgVectorLoader} from './assets/svg-loader.mjs';
50
- import {findCompileBin, compileBinHelp} from './compile-bin.mjs';
51
- import {loadAppFile, loadDependencyFile} from './aot/app-file-loader.mjs';
52
- import {demoFile} from './aot/demo-file.mjs';
53
-
30
+ import { build } from 'esbuild';
31
+ import { spawnSync } from 'node:child_process';
32
+ import { fileURLToPath, pathToFileURL } from 'node:url';
33
+ import { dirname, resolve, basename } from 'node:path';
34
+ import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, } from 'node:fs';
35
+ import { bakeImage } from './assets/bake-image.mjs';
36
+ import { bakeFont } from './assets/bake-font.mjs';
37
+ import { resolveFontJobs } from './assets/font-config.mjs';
38
+ import { analyzeFontSizes, warnFontSizes } from './assets/font-sizes.mjs';
39
+ import { warnMissingGlyphs } from './assets/glyph-coverage.mjs';
40
+ import { emitAssetPack } from './assets/emit-pack.mjs';
41
+ import { emitContainer } from './assets/emit-container.mjs';
42
+ import { registerSvgVectorLoader } from './assets/svg-loader.mjs';
43
+ import { findCompileBin, compileBinHelp } from './compile-bin.mjs';
44
+ import { loadAppFile, loadDependencyFile } from './aot/app-file-loader.mjs';
45
+ import { demoFile } from './aot/demo-file.mjs';
54
46
  // QuickJS release the bytecode targets — MUST match the FetchContent pin in
55
47
  // bridges/quickjs/CMakeLists.txt and ER_QUICKJS_TAG in er_runtime.c. The loader rejects a mismatch.
56
48
  const QUICKJS_TAG = 'v0.15.0';
57
49
  const BYTES_PER_KILOBYTE = 1024;
58
-
59
50
  const here = dirname(fileURLToPath(import.meta.url)); // packages/embedded-react
60
51
  const repoRoot = resolve(here, '../..');
61
52
  const demosDir = resolve(repoRoot, 'demos');
62
53
  const libEntry = resolve(here, 'src/embedded-react/index.js');
63
54
  const nodeModules = resolve(here, 'node_modules');
64
55
  const distDir = resolve(here, 'dist');
65
-
66
56
  const demo = process.argv[2] || process.env.DEMO || 'thermostat';
67
57
  const demoDir = resolve(demosDir, demo);
68
58
  const entry = demoFile(demoDir, 'index');
69
59
  if (!existsSync(entry)) {
70
- const available = existsSync(demosDir)
71
- ? readdirSync(demosDir, {withFileTypes: true})
72
- .filter(entry => entry.isDirectory())
73
- .map(entry => entry.name)
74
- : [];
75
- console.error(`Demo "${demo}" not found (expected ${entry}).`);
76
- console.error(`Available demos: ${available.join(', ') || '(none)'}`);
77
- process.exit(1);
60
+ const available = existsSync(demosDir)
61
+ ? readdirSync(demosDir, { withFileTypes: true })
62
+ .filter(entry => entry.isDirectory())
63
+ .map(entry => entry.name)
64
+ : [];
65
+ console.error(`Demo "${demo}" not found (expected ${entry}).`);
66
+ console.error(`Available demos: ${available.join(', ') || '(none)'}`);
67
+ process.exit(1);
78
68
  }
79
-
80
69
  // --- Locate the bytecode precompiler -----------------------------------------------------------
81
70
  const compileBin = findCompileBin();
82
71
  if (!compileBin) {
83
- console.error(compileBinHelp());
84
- process.exit(1);
72
+ console.error(compileBinHelp());
73
+ process.exit(1);
85
74
  }
86
-
87
- // --- Bundle the app (same import-driven asset discovery as build.mjs) ---------------------------
75
+ // --- Bundle the app (same import-driven asset discovery as build.mts) ---------------------------
88
76
  const images = new Map(); // name -> path
89
77
  const fonts = new Map(); // family -> path
90
78
  const assetPlugin = {
91
- name: 'embedded-react-assets',
92
- setup(pluginBuild) {
93
- // The demo's own files give its native modules their signatures, and so do a package's.
94
- pluginBuild.onLoad({filter: /\.(jsx?|tsx?)$/}, args =>
95
- args.path.startsWith(demoDir)
96
- ? loadAppFile(args.path)
97
- : loadDependencyFile(args.path),
98
- );
99
- pluginBuild.onLoad({filter: /\.(png|jpe?g|webp|gif|bmp)$/i}, args => {
100
- const name = basename(args.path).replace(/\.[^.]+$/, '');
101
- images.set(name, args.path);
102
- return {
103
- contents: `module.exports = ${JSON.stringify(name)};`,
104
- loader: 'js',
105
- };
106
- });
107
- pluginBuild.onLoad({filter: /\.(ttf|otf)$/i}, args => {
108
- const family = basename(args.path).replace(/\.[^.]+$/, '');
109
- fonts.set(family, args.path);
110
- return {
111
- contents: `module.exports = ${JSON.stringify(family)};`,
112
- loader: 'js',
113
- };
114
- });
115
- registerSvgVectorLoader(pluginBuild, (name, svgPath) =>
116
- images.set(name, svgPath),
117
- ); // raster-fallback SVGs join the image pack
118
- },
79
+ name: 'embedded-react-assets',
80
+ setup(pluginBuild) {
81
+ // The demo's own files give its native modules their signatures, and so do a package's.
82
+ pluginBuild.onLoad({ filter: /\.(jsx?|tsx?)$/ }, args => args.path.startsWith(demoDir)
83
+ ? loadAppFile(args.path)
84
+ : loadDependencyFile(args.path));
85
+ pluginBuild.onLoad({ filter: /\.(png|jpe?g|webp|gif|bmp)$/i }, args => {
86
+ const name = basename(args.path).replace(/\.[^.]+$/, '');
87
+ images.set(name, args.path);
88
+ return {
89
+ contents: `module.exports = ${JSON.stringify(name)};`,
90
+ loader: 'js',
91
+ };
92
+ });
93
+ pluginBuild.onLoad({ filter: /\.(ttf|otf)$/i }, args => {
94
+ const family = basename(args.path).replace(/\.[^.]+$/, '');
95
+ fonts.set(family, args.path);
96
+ return {
97
+ contents: `module.exports = ${JSON.stringify(family)};`,
98
+ loader: 'js',
99
+ };
100
+ });
101
+ registerSvgVectorLoader(pluginBuild, (name, svgPath) => images.set(name, svgPath)); // raster-fallback SVGs join the image pack
102
+ },
119
103
  };
120
-
121
- mkdirSync(distDir, {recursive: true});
104
+ mkdirSync(distDir, { recursive: true });
122
105
  const bundlePath = resolve(distDir, 'app.bundle.js');
123
106
  await build({
124
- entryPoints: [entry],
125
- bundle: true,
126
- format: 'iife',
127
- outfile: bundlePath,
128
- platform: 'neutral',
129
- target: 'es2020',
130
- jsx: 'automatic',
131
- // Pin React to THIS package's copy: a demo/consumer project may carry its own node_modules
132
- // (e.g., after `npm install` for device-dev deps), and esbuild resolving `react` from there while
133
- // the library resolves its copy from here yields two React instances — the hook dispatcher is
134
- // null and every component throws. One copy, always.
135
- alias: {
136
- 'embedded-react': libEntry,
137
- react: resolve(nodeModules, 'react'),
138
- 'react-reconciler': resolve(nodeModules, 'react-reconciler'),
139
- scheduler: resolve(nodeModules, 'scheduler'),
140
- },
141
- nodePaths: [nodeModules],
142
- plugins: [assetPlugin],
143
- define: {'process.env.NODE_ENV': '"production"'},
144
- legalComments: 'none',
145
- logLevel: 'info',
107
+ entryPoints: [entry],
108
+ bundle: true,
109
+ format: 'iife',
110
+ outfile: bundlePath,
111
+ platform: 'neutral',
112
+ target: 'es2020',
113
+ jsx: 'automatic',
114
+ // Pin React to THIS package's copy: a demo/consumer project may carry its own node_modules
115
+ // (e.g., after `npm install` for device-dev deps), and esbuild resolving `react` from there while
116
+ // the library resolves its copy from here yields two React instances — the hook dispatcher is
117
+ // null and every component throws. One copy, always.
118
+ alias: {
119
+ 'embedded-react': libEntry,
120
+ react: resolve(nodeModules, 'react'),
121
+ 'react-reconciler': resolve(nodeModules, 'react-reconciler'),
122
+ scheduler: resolve(nodeModules, 'scheduler'),
123
+ },
124
+ nodePaths: [nodeModules],
125
+ plugins: [assetPlugin],
126
+ define: { 'process.env.NODE_ENV': '"production"' },
127
+ legalComments: 'none',
128
+ logLevel: 'info',
146
129
  });
147
130
  console.log(`Bundled demo "${demo}" -> dist/app.bundle.js`);
148
-
149
131
  // --- Precompile to QuickJS bytecode -------------------------------------------------------------
150
132
  const bytecodePath = resolve(distDir, 'app.bundle.qbc');
151
133
  const compileResult = spawnSync(compileBin, [bundlePath, bytecodePath], {
152
- stdio: 'inherit',
134
+ stdio: 'inherit',
153
135
  });
154
136
  if (compileResult.status !== 0) {
155
- console.error('Bytecode compile failed.');
156
- process.exit(1);
137
+ console.error('Bytecode compile failed.');
138
+ process.exit(1);
157
139
  }
158
140
  const bytecode = readFileSync(bytecodePath);
159
-
160
- // --- Bake imported assets into an ERPK pack (same sizing rules as build.mjs / sim.mjs) ----------
141
+ // --- Bake imported assets into an ERPK pack (same sizing rules as build.mts / sim.mts) ----------
161
142
  const bundleSource = readFileSync(bundlePath, 'utf8');
162
143
  const usedSizes = analyzeFontSizes(bundleSource);
163
-
164
144
  let config = {};
165
145
  const configPath = resolve(demoDir, 'assets.config.js');
166
146
  if (existsSync(configPath))
167
- config = (await import(pathToFileURL(configPath).href)).default || {};
147
+ config = (await import(pathToFileURL(configPath).href)).default || {};
168
148
  const fontConfig = config.fonts || {};
169
149
  const imageConfig = config.images || {};
170
-
171
150
  const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
172
151
  const imageJobs = [...images.entries()].map(([name, path]) => ({
173
- path,
174
- name,
175
- format: imageConfig[name]?.format,
152
+ path,
153
+ name,
154
+ format: imageConfig[name]?.format,
176
155
  }));
177
-
178
156
  const bakedImages = imageJobs.map(imageJob => bakeImage(imageJob));
179
157
  const bakedFonts = fontJobs.map(fontJob => bakeFont(fontJob));
180
- warnMissingGlyphs({source: bundleSource, fonts: bakedFonts});
181
- warnFontSizes({used: usedSizes, fonts: bakedFonts});
182
- const assetPack =
183
- bakedImages.length || bakedFonts.length
184
- ? emitAssetPack({images: bakedImages, fonts: bakedFonts})
158
+ warnMissingGlyphs({ source: bundleSource, fonts: bakedFonts });
159
+ warnFontSizes({ used: usedSizes, fonts: bakedFonts });
160
+ const assetPack = bakedImages.length || bakedFonts.length
161
+ ? emitAssetPack({ images: bakedImages, fonts: bakedFonts })
185
162
  : null;
186
- const fontSizeCount = bakedFonts.reduce(
187
- (count, font) => count + font.sizes.length,
188
- 0,
189
- );
190
-
163
+ const fontSizeCount = bakedFonts.reduce((count, font) => count + font.sizes.length, 0);
191
164
  // --- Wrap into the ERCF container ---------------------------------------------------------------
192
- const container = emitContainer({bytecode, assetPack, qjsTag: QUICKJS_TAG});
165
+ const container = emitContainer({ bytecode, assetPack, qjsTag: QUICKJS_TAG });
193
166
  const outPath = resolve(distDir, 'app.erpkg');
194
167
  writeFileSync(outPath, container);
195
-
196
- const kb = byteCount => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
197
- console.log(
198
- `Packed config -> dist/app.erpkg (${kb(container.length)})\n` +
168
+ const kb = (byteCount) => `${(byteCount / BYTES_PER_KILOBYTE).toFixed(1)} KB`;
169
+ console.log(`Packed config -> dist/app.erpkg (${kb(container.length)})\n` +
199
170
  ` qjs ${QUICKJS_TAG} · bytecode ${kb(bytecode.length)}` +
200
171
  (assetPack
201
- ? ` · assets ${kb(assetPack.length)} (${bakedImages.length} image(s), ${fontSizeCount} font size(s))`
202
- : ' · no assets'),
203
- );
172
+ ? ` · assets ${kb(assetPack.length)} (${bakedImages.length} image(s), ${fontSizeCount} font size(s))`
173
+ : ' · no assets'));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "embedded-react",
3
- "version": "0.21.0",
3
+ "version": "0.22.0",
4
4
  "type": "module",
5
5
  "description": "React Native-style component package + reconciler that drives the embedded-react C engine through the QuickJS NativeUI bridge (Flow A).",
6
6
  "license": "Apache-2.0",
@@ -62,27 +62,27 @@
62
62
  "!**/*.test.js"
63
63
  ],
64
64
  "scripts": {
65
- "build": "node build.mjs",
66
- "pack": "node pack-container.mjs",
65
+ "build": "node build.mts",
66
+ "pack": "node pack-container.mts",
67
67
  "aot": "node aot/compile.mts",
68
68
  "aot:smoke": "node aot/screenshot-smoke.mjs",
69
69
  "erb:frames": "node test/erb-frames/erb-frames.mts",
70
70
  "erb:frames:record": "node test/erb-frames/erb-frames.mts --record",
71
- "erb:corpus": "node test/erb-fuzz/make-corpus.mjs",
72
- "parity": "node parity.mjs",
73
- "version:sync": "node ../../tools/sync-version.mjs",
74
- "version:check": "node ../../tools/sync-version.mjs --check",
75
- "release": "node ../../tools/release.mjs",
76
- "build:builtin-font": "node assets/build-builtin-font.mjs",
77
- "sim": "node sim.mjs",
78
- "dev": "node cli.mjs dev",
79
- "create": "node create-embedded-react.mjs",
71
+ "erb:corpus": "node test/erb-fuzz/make-corpus.mts",
72
+ "parity": "node parity.mts",
73
+ "version:sync": "node ../../tools/sync-version.mts",
74
+ "version:check": "node ../../tools/sync-version.mts --check",
75
+ "release": "node ../../tools/release.mts",
76
+ "build:builtin-font": "node assets/build-builtin-font.mts",
77
+ "sim": "node sim.mts",
78
+ "dev": "node cli.mts dev",
79
+ "create": "node create-embedded-react.mts",
80
80
  "test": "vitest run",
81
81
  "test:watch": "vitest",
82
- "test:runtime": "node test/runtime/run.mjs",
83
- "test:bytecode": "node test/runtime/run.mjs --bytecode",
84
- "test:split": "node test/runtime/split-roundtrip.mjs",
85
- "typecheck": "tsc -p tsconfig.types.json && tsc -p tsconfig.aot.json && tsc -p tsconfig.frames.json"
82
+ "test:runtime": "node test/runtime/run.mts",
83
+ "test:bytecode": "node test/runtime/run.mts --bytecode",
84
+ "test:split": "node test/runtime/split-roundtrip.mts",
85
+ "typecheck": "tsc -p tsconfig.types.json && tsc -p tsconfig.aot.json && tsc -p tsconfig.frames.json && tsc -p tsconfig.runtime.json"
86
86
  },
87
87
  "dependencies": {
88
88
  "@babel/code-frame": "^7.29.7",
@@ -102,7 +102,10 @@
102
102
  "@types/babel__code-frame": "^7.27.0",
103
103
  "@types/babel__core": "^7.20.5",
104
104
  "@types/node": "^22.20.4",
105
+ "@types/opentype.js": "^1.3.10",
106
+ "@types/pngjs": "^6.0.5",
105
107
  "@types/react": "18.3.1",
108
+ "@types/react-reconciler": "^0.28.9",
106
109
  "typescript": "^5.5.0",
107
110
  "vitest": "^4.1.11"
108
111
  },
@@ -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
  // Simulator-only Babel transform: rewrites `useState(init)` in app code to a persisting helper so
18
17
  // state transparently survives a hot reload (see tools/simulator/README.md). Plain
19
18
  // `useState` from 'react' just persists in the simulator; on a device (no transform, no __erPersist)
@@ -24,85 +23,74 @@
24
23
  // stable across the edits you make most often (JSX/logic). Adding/removing a useState in a component,
25
24
  // or renaming it, shifts that component's keys and resets its state — press R in the sim for a clean
26
25
  // reset any time.
27
- import {transformSync} from '@babel/core';
26
+ import { transformSync } from '@babel/core';
27
+ // @ts-expect-error The package ships no types.
28
28
  import syntaxJsx from '@babel/plugin-syntax-jsx';
29
-
30
29
  /** Best-effort name of the function/component enclosing a path (for a stable, readable key). */
31
30
  function enclosingName(path) {
32
- const functionPath = path.getFunctionParent();
33
- if (!functionPath) return '_';
34
- if (functionPath.node.id && functionPath.node.id.name)
35
- return functionPath.node.id.name; // function Foo() {}
36
- const parent = functionPath.parentPath && functionPath.parentPath.node;
37
- if (parent) {
38
- if (parent.type === 'VariableDeclarator' && parent.id && parent.id.name)
39
- return parent.id.name; // const Foo = () =>
40
- if (parent.key && parent.key.name) return parent.key.name; // method / property
41
- if (
42
- parent.type === 'AssignmentExpression' &&
43
- parent.left &&
44
- parent.left.name
45
- )
46
- return parent.left.name;
47
- }
48
- return '_';
31
+ const functionPath = path.getFunctionParent();
32
+ if (!functionPath)
33
+ return '_';
34
+ // Read loosely: only some kinds of function and parent have these fields.
35
+ const functionNode = functionPath.node;
36
+ if (functionNode.id && functionNode.id.name)
37
+ return functionNode.id.name; // function Foo() {}
38
+ const parent = functionPath.parentPath && functionPath.parentPath.node;
39
+ if (parent) {
40
+ if (parent.type === 'VariableDeclarator' && parent.id && parent.id.name)
41
+ return parent.id.name; // const Foo = () =>
42
+ if (parent.key && parent.key.name)
43
+ return parent.key.name; // method / property
44
+ if (parent.type === 'AssignmentExpression' &&
45
+ parent.left &&
46
+ parent.left.name)
47
+ return parent.left.name;
48
+ }
49
+ return '_';
49
50
  }
50
-
51
51
  /** Babel plugin: useState(init) → __erPersistState("key", init), importing the helper when used. */
52
- function persistPlugin({types}) {
53
- return {
54
- name: 'er-persist-usestate',
55
- visitor: {
56
- Program: {
57
- enter(_path, state) {
58
- state.erCounters = new Map();
59
- state.erUsed = false;
52
+ function persistPlugin({ types, }) {
53
+ return {
54
+ name: 'er-persist-usestate',
55
+ visitor: {
56
+ Program: {
57
+ enter(_path, state) {
58
+ state.erCounters = new Map();
59
+ state.erUsed = false;
60
+ },
61
+ exit(path, state) {
62
+ if (!state.erUsed)
63
+ return;
64
+ path.unshiftContainer('body', types.importDeclaration([
65
+ types.importSpecifier(types.identifier('__erPersistState'), types.identifier('usePersistentState')),
66
+ ], types.stringLiteral('embedded-react')));
67
+ },
68
+ },
69
+ CallExpression(path, state) {
70
+ if (!types.isIdentifier(path.node.callee, { name: 'useState' }))
71
+ return;
72
+ // Only rewrite the real useState (an imported binding from react / embedded-react).
73
+ const binding = path.scope.getBinding('useState');
74
+ if (!binding || binding.kind !== 'module')
75
+ return;
76
+ const declaration = binding.path.parentPath && binding.path.parentPath.node;
77
+ const source = declaration && declaration.source && declaration.source.value;
78
+ if (source !== 'react' && source !== 'embedded-react')
79
+ return;
80
+ const functionName = enclosingName(path);
81
+ const index = state.erCounters.get(functionName) || 0;
82
+ state.erCounters.set(functionName, index + 1);
83
+ const key = `${state.opts.moduleId}::${functionName}#${index}`;
84
+ path.replaceWith(types.callExpression(types.identifier('__erPersistState'), [
85
+ types.stringLiteral(key),
86
+ ...path.node.arguments,
87
+ ]));
88
+ state.erUsed = true;
89
+ path.skip();
90
+ },
60
91
  },
61
- exit(path, state) {
62
- if (!state.erUsed) return;
63
- path.unshiftContainer(
64
- 'body',
65
- types.importDeclaration(
66
- [
67
- types.importSpecifier(
68
- types.identifier('__erPersistState'),
69
- types.identifier('usePersistentState'),
70
- ),
71
- ],
72
- types.stringLiteral('embedded-react'),
73
- ),
74
- );
75
- },
76
- },
77
- CallExpression(path, state) {
78
- if (!types.isIdentifier(path.node.callee, {name: 'useState'})) return;
79
- // Only rewrite the real useState (an imported binding from react / embedded-react).
80
- const binding = path.scope.getBinding('useState');
81
- if (!binding || binding.kind !== 'module') return;
82
- const declaration =
83
- binding.path.parentPath && binding.path.parentPath.node;
84
- const source =
85
- declaration && declaration.source && declaration.source.value;
86
- if (source !== 'react' && source !== 'embedded-react') return;
87
-
88
- const functionName = enclosingName(path);
89
- const index = state.erCounters.get(functionName) || 0;
90
- state.erCounters.set(functionName, index + 1);
91
- const key = `${state.opts.moduleId}::${functionName}#${index}`;
92
-
93
- path.replaceWith(
94
- types.callExpression(types.identifier('__erPersistState'), [
95
- types.stringLiteral(key),
96
- ...path.node.arguments,
97
- ]),
98
- );
99
- state.erUsed = true;
100
- path.skip();
101
- },
102
- },
103
- };
92
+ };
104
93
  }
105
-
106
94
  /**
107
95
  * Whether `absolutePath` is an app source file that should receive the persist transform: under the project
108
96
  * root, but NOT a dependency. The library itself lives under the project root in a consumer install
@@ -111,46 +99,42 @@ function persistPlugin({types}) {
111
99
  * Excluding `node_modules` is what keeps the helper (and react) untransformed in a published install,
112
100
  * not just in the monorepo (where the library happens to sit outside the demo's project root).
113
101
  *
114
- * @param {string} absolutePath Absolute path of the module esbuild is loading.
115
- * @param {string} projectRootNormalized Project root, forward-slash normalized.
116
- * @returns {boolean}
102
+ * @param absolutePath Absolute path of the module esbuild is loading.
103
+ * @param projectRootNormalized Project root, forward-slash normalized.
117
104
  */
118
105
  export function shouldPersist(absolutePath, projectRootNormalized) {
119
- const normalizedPath = absolutePath.replace(/\\/g, '/');
120
- return (
121
- normalizedPath.startsWith(projectRootNormalized) &&
122
- !normalizedPath.includes('/node_modules/')
123
- );
106
+ const normalizedPath = absolutePath.replace(/\\/g, '/');
107
+ return (normalizedPath.startsWith(projectRootNormalized) &&
108
+ !normalizedPath.includes('/node_modules/'));
124
109
  }
125
-
126
110
  /**
127
111
  * Applies the persist transform to a module's source.
128
112
  *
129
113
  * TypeScript entries (.ts/.tsx) are parsed with the `typescript` plugin enabled; the type syntax is
130
- * preserved in the output and stripped downstream by esbuild's ts/tsx loader (see sim-server.mjs).
114
+ * preserved in the output and stripped downstream by esbuild's ts/tsx loader (see sim-server.mts).
131
115
  *
132
- * @param {string} code Module source (JSX and/or TypeScript allowed).
133
- * @param {string} moduleId Stable module identifier (used in keys; e.g. a path relative to the app).
134
- * @returns {string} Transformed source (JSX/TS preserved for esbuild to handle).
116
+ * @param code Module source (JSX and/or TypeScript allowed).
117
+ * @param moduleId Stable module identifier (used in keys; e.g. a path relative to the app).
118
+ * @returns Transformed source (JSX/TS preserved for esbuild to handle).
135
119
  */
136
120
  export function transformPersist(code, moduleId) {
137
- // Enable the babel parser plugins this module's extension needs. `.tsx` is jsx+typescript; `.ts` is
138
- // typescript-only (the jsx plugin would misparse `<T>` type assertions); everything else is jsx.
139
- const isTs = /\.tsx?$/.test(moduleId);
140
- const isTsx = /\.tsx$/.test(moduleId);
141
- const parserPlugins = isTsx
142
- ? ['jsx', 'typescript']
143
- : isTs
144
- ? ['typescript']
145
- : ['jsx'];
146
- const result = transformSync(code, {
147
- filename: moduleId,
148
- babelrc: false,
149
- configFile: false,
150
- sourceType: 'module',
151
- parserOpts: {plugins: parserPlugins},
152
- // syntaxJsx only enables jsx parsing; for ts/tsx we drive the parser via parserOpts above instead.
153
- plugins: [...(isTs ? [] : [syntaxJsx]), [persistPlugin, {moduleId}]],
154
- });
155
- return result.code;
121
+ // Enable the babel parser plugins this module's extension needs. `.tsx` is jsx+typescript; `.ts` is
122
+ // typescript-only (the jsx plugin would misparse `<T>` type assertions); everything else is jsx.
123
+ const isTs = /\.tsx?$/.test(moduleId);
124
+ const isTsx = /\.tsx$/.test(moduleId);
125
+ const parserPlugins = isTsx
126
+ ? ['jsx', 'typescript']
127
+ : isTs
128
+ ? ['typescript']
129
+ : ['jsx'];
130
+ const result = transformSync(code, {
131
+ filename: moduleId,
132
+ babelrc: false,
133
+ configFile: false,
134
+ sourceType: 'module',
135
+ parserOpts: { plugins: parserPlugins },
136
+ // syntaxJsx only enables jsx parsing; for ts/tsx we drive the parser via parserOpts above instead.
137
+ plugins: [...(isTs ? [] : [syntaxJsx]), [persistPlugin, { moduleId }]],
138
+ });
139
+ return result.code;
156
140
  }