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/sim-server.mjs CHANGED
@@ -13,385 +13,291 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
- // sim-server.mjs — the shared WASM-simulator bundler + dev server.
16
+ // sim-server.mts — the shared WASM-simulator bundler + dev server.
18
17
  //
19
18
  // esbuild-bundles a JSX app → app.js, bakes its imported images/fonts → assets.pack, and either (a) serves
20
19
  // the prebuilt embedded-react.{js,wasm} host page with live hot reload (runDevServer), or (b) produces those
21
20
  // files once for a static export (buildApp). useState survives a hot reload via the Babel persist transform.
22
21
  //
23
- // Used by the consumer CLI (cli.mjs → `npx embedded-react dev` / `export`) and the repo dev loop
24
- // (tools/web-sim/dev.mjs). The only differences are paths, passed in here.
25
-
26
- import {createServer} from 'node:http';
27
- import {readFile} from 'node:fs/promises';
28
- import {existsSync, readFileSync, statSync} from 'node:fs';
29
- import {createRequire} from 'node:module';
30
- import {pathToFileURL} from 'node:url';
31
- import {basename, dirname, extname, relative, resolve} from 'node:path';
32
-
33
- const HERE = dirname(
34
- new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'),
35
- );
22
+ // Used by the consumer CLI (cli.mts → `npx embedded-react dev` / `export`) and the repo dev loop
23
+ // (tools/web-sim/dev.mts). The only differences are paths, passed in here.
24
+ import { createServer } from 'node:http';
25
+ import { readFile } from 'node:fs/promises';
26
+ import { existsSync, readFileSync, statSync } from 'node:fs';
27
+ import { createRequire } from 'node:module';
28
+ import { pathToFileURL } from 'node:url';
29
+ import { basename, dirname, extname, relative, resolve } from 'node:path';
30
+ const HERE = dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
36
31
  const require = createRequire(import.meta.url);
37
32
  const esbuild = require('esbuild');
38
- const {bakeAssetPack} = await import(
39
- pathToFileURL(resolve(HERE, 'assets/index.mjs')).href
40
- );
41
- const {resolveFontJobs} = await import(
42
- pathToFileURL(resolve(HERE, 'assets/font-config.mjs')).href
43
- );
44
- const {analyzeFontSizes, fontSizeSignature, warnFontSizes} = await import(
45
- pathToFileURL(resolve(HERE, 'assets/font-sizes.mjs')).href
46
- );
47
- const {textSignature, warnMissingGlyphs} = await import(
48
- pathToFileURL(resolve(HERE, 'assets/glyph-coverage.mjs')).href
49
- );
50
- const {registerSvgVectorLoader} = await import(
51
- pathToFileURL(resolve(HERE, 'assets/svg-loader.mjs')).href
52
- );
53
- const {transformPersist, shouldPersist} = await import(
54
- pathToFileURL(resolve(HERE, 'persist-transform.mjs')).href
55
- );
56
- const {loadAppFile, loadDependencyFile} =
57
- await import('./aot/app-file-loader.mjs');
58
-
59
- const REACT_PIN = Object.fromEntries(
60
- ['react', 'react-reconciler', 'scheduler']
33
+ const { bakeAssetPack } = await import('./assets/index.mjs');
34
+ const { resolveFontJobs } = await import('./assets/font-config.mjs');
35
+ const { analyzeFontSizes, fontSizeSignature, warnFontSizes } = await import('./assets/font-sizes.mjs');
36
+ const { textSignature, warnMissingGlyphs } = await import('./assets/glyph-coverage.mjs');
37
+ const { registerSvgVectorLoader } = await import('./assets/svg-loader.mjs');
38
+ const { transformPersist, shouldPersist } = await import('./persist-transform.mjs');
39
+ const { loadAppFile, loadDependencyFile } = await import('./aot/app-file-loader.mjs');
40
+ const REACT_PIN = Object.fromEntries(['react', 'react-reconciler', 'scheduler']
61
41
  .map(packageName => [
62
- packageName,
63
- resolve(HERE, 'node_modules', packageName),
64
- ])
65
- .filter(([, pinPath]) => existsSync(pinPath)),
66
- );
67
-
42
+ packageName,
43
+ resolve(HERE, 'node_modules', packageName),
44
+ ])
45
+ .filter(([, pinPath]) => existsSync(pinPath)));
68
46
  const MIME = {
69
- '.html': 'text/html; charset=utf-8',
70
- '.js': 'text/javascript; charset=utf-8',
71
- '.wasm': 'application/wasm',
72
- '.pack': 'application/octet-stream',
47
+ '.html': 'text/html; charset=utf-8',
48
+ '.js': 'text/javascript; charset=utf-8',
49
+ '.wasm': 'application/wasm',
50
+ '.pack': 'application/octet-stream',
73
51
  };
74
- const assetName = filePath => basename(filePath).replace(/\.[^.]+$/, '');
75
- const mtime = filePath => {
76
- try {
77
- return statSync(filePath).mtimeMs;
78
- } catch {
79
- return 0;
80
- }
52
+ const assetName = (filePath) => basename(filePath).replace(/\.[^.]+$/, '');
53
+ const mtime = (filePath) => {
54
+ try {
55
+ return statSync(filePath).mtimeMs;
56
+ }
57
+ catch {
58
+ return 0;
59
+ }
81
60
  };
82
-
83
61
  /**
84
62
  * Build the esbuild config + asset baker for one app bundle. Owns its own asset-discovery state, so it is
85
63
  * safe to use for either a one-shot build or a watching context.
86
- *
87
- * @param {object} o
88
- * @param {string} o.entry, o.projectRoot, o.libSrc, o.outDir
89
- * @param {string[]} o.nodePaths
90
- * @param {boolean} [o.persist] Apply the useState→persist transform (dev hot reload). Default true.
91
- * @param {() => void} [o.onRebuilt] Called after each successful build + asset bake (e.g. broadcast reload).
92
- * @returns {{ options: object, bundlePath: string, packPath: string }}
93
64
  */
94
- function createBundle({
95
- entry,
96
- projectRoot,
97
- libSrc,
98
- nodePaths,
99
- outDir,
100
- persist = true,
101
- onRebuilt,
102
- }) {
103
- const bundlePath = resolve(outDir, 'app.js');
104
- const packPath = resolve(outDir, 'assets.pack');
105
- const projectRootNormalized = projectRoot.replace(/\\/g, '/');
106
- const images = new Map();
107
- const fonts = new Map();
108
- let lastAssetSignature = null;
109
-
110
- async function bakePack() {
111
- const bundleSource = readFileSync(bundlePath, 'utf8');
112
- const usedSizes = analyzeFontSizes(bundleSource);
113
-
114
- let assetsConfig = {};
115
- const assetsConfigPath = resolve(projectRoot, 'assets.config.js');
116
- if (existsSync(assetsConfigPath))
117
- assetsConfig =
118
- (
119
- await import(
120
- `${pathToFileURL(assetsConfigPath).href}?t=${mtime(assetsConfigPath)}`
121
- )
122
- ).default || {};
123
- const fontConfig = assetsConfig.fonts || {};
124
- const imageConfig = assetsConfig.images || {};
125
-
126
- const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
127
- const imageJobs = [...images.entries()].map(([name, path]) => ({
128
- path,
129
- name,
130
- format: imageConfig[name]?.format,
131
- }));
132
-
133
- // The app's text is an asset input too: new characters and new font sizes must both be
134
- // re-checked against the bake even when no font or image file changed.
135
- const assetSignature = JSON.stringify({
136
- text: textSignature(bundleSource),
137
- fontSizes: fontSizeSignature(usedSizes),
138
- images: imageJobs
139
- .map(job => [job.name, job.path, mtime(job.path), job.format])
140
- .sort(),
141
- fonts: fontJobs
142
- .map(job => [
143
- job.family,
144
- job.path,
145
- mtime(job.path),
146
- job.sizes,
147
- job.bpp,
148
- job.glyphs,
149
- job.extraGlyphs,
150
- ])
151
- .sort(),
152
- });
153
- if (assetSignature === lastAssetSignature) return;
154
- lastAssetSignature = assetSignature;
155
- if (!imageJobs.length && !fontJobs.length) {
156
- // Built-in font only → no pack, but its glyph and size coverage still bind.
157
- warnMissingGlyphs({source: bundleSource});
158
- warnFontSizes({used: usedSizes});
159
- return;
160
- }
161
-
162
- try {
163
- const summary = bakeAssetPack({
164
- images: imageJobs,
165
- fonts: fontJobs,
166
- outPath: packPath,
167
- source: bundleSource,
168
- usedSizes,
169
- });
170
- console.log(
171
- ` assets → ${summary.images} image(s), ${summary.fonts} font size(s), ${summary.bytes} B`,
172
- );
173
- } catch (error) {
174
- console.error(` asset bake failed: ${error.message}`);
65
+ function createBundle({ entry, projectRoot, libSrc, nodePaths, outDir, persist = true, onRebuilt, }) {
66
+ const bundlePath = resolve(outDir, 'app.js');
67
+ const packPath = resolve(outDir, 'assets.pack');
68
+ const projectRootNormalized = projectRoot.replace(/\\/g, '/');
69
+ const images = new Map();
70
+ const fonts = new Map();
71
+ let lastAssetSignature = null;
72
+ async function bakePack() {
73
+ const bundleSource = readFileSync(bundlePath, 'utf8');
74
+ const usedSizes = analyzeFontSizes(bundleSource);
75
+ let assetsConfig = {};
76
+ const assetsConfigPath = resolve(projectRoot, 'assets.config.js');
77
+ if (existsSync(assetsConfigPath))
78
+ assetsConfig =
79
+ (await import(`${pathToFileURL(assetsConfigPath).href}?t=${mtime(assetsConfigPath)}`)).default || {};
80
+ const fontConfig = assetsConfig.fonts || {};
81
+ const imageConfig = assetsConfig.images || {};
82
+ const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
83
+ const imageJobs = [...images.entries()].map(([name, path]) => ({
84
+ path,
85
+ name,
86
+ format: imageConfig[name]?.format,
87
+ }));
88
+ // The app's text is an asset input too: new characters and new font sizes must both be
89
+ // re-checked against the bake even when no font or image file changed.
90
+ const assetSignature = JSON.stringify({
91
+ text: textSignature(bundleSource),
92
+ fontSizes: fontSizeSignature(usedSizes),
93
+ images: imageJobs
94
+ .map(job => [job.name, job.path, mtime(job.path), job.format])
95
+ .sort(),
96
+ fonts: fontJobs
97
+ .map(job => [
98
+ job.family,
99
+ job.path,
100
+ mtime(job.path),
101
+ job.sizes,
102
+ job.bpp,
103
+ job.glyphs,
104
+ job.extraGlyphs,
105
+ ])
106
+ .sort(),
107
+ });
108
+ if (assetSignature === lastAssetSignature)
109
+ return;
110
+ lastAssetSignature = assetSignature;
111
+ if (!imageJobs.length && !fontJobs.length) {
112
+ // Built-in font only → no pack, but its glyph and size coverage still bind.
113
+ warnMissingGlyphs({ source: bundleSource });
114
+ warnFontSizes({ used: usedSizes });
115
+ return;
116
+ }
117
+ try {
118
+ const summary = bakeAssetPack({
119
+ images: imageJobs,
120
+ fonts: fontJobs,
121
+ outPath: packPath,
122
+ source: bundleSource,
123
+ usedSizes,
124
+ });
125
+ console.log(` assets → ${summary.images} image(s), ${summary.fonts} font size(s), ${summary.bytes} B`);
126
+ }
127
+ catch (error) {
128
+ console.error(` asset bake failed: ${error.message}`);
129
+ }
175
130
  }
176
- }
177
-
178
- const options = {
179
- entryPoints: [entry],
180
- bundle: true,
181
- format: 'iife',
182
- outfile: bundlePath,
183
- platform: 'neutral',
184
- target: 'es2020',
185
- jsx: 'automatic',
186
- alias: {'embedded-react': libSrc, ...REACT_PIN},
187
- nodePaths,
188
- define: {'process.env.NODE_ENV': '"production"'},
189
- legalComments: 'none',
190
- logLevel: 'silent',
191
- plugins: [
192
- {
193
- name: 'embedded-react-websim',
194
- setup(pluginBuild) {
195
- pluginBuild.onStart(() => {
196
- images.clear();
197
- fonts.clear();
198
- });
199
- pluginBuild.onLoad({filter: /\.(jsx?|tsx?)$/}, async loadArgs => {
200
- // Only the app's own source — never dependencies (see shouldPersist: excluding node_modules is what
201
- // stops the library's usePersistentState being rewritten to call itself). Native modules get their
202
- // signatures and mocks, and with persist on, useState persists. A package's native modules get theirs too.
203
- if (!shouldPersist(loadArgs.path, projectRootNormalized))
204
- return loadDependencyFile(loadArgs.path, {mocks: true});
205
- try {
206
- return await loadAppFile(
207
- loadArgs.path,
208
- persist
209
- ? source =>
210
- transformPersist(
211
- source,
212
- relative(projectRoot, loadArgs.path).replace(
213
- /\\/g,
214
- '/',
215
- ),
216
- )
217
- : undefined,
218
- {mocks: true},
219
- );
220
- } catch (error) {
221
- return {errors: [{text: `persist transform: ${error.message}`}]};
222
- }
223
- });
224
- pluginBuild.onLoad(
225
- {filter: /\.(png|jpe?g|webp|gif|bmp)$/i},
226
- loadArgs => {
227
- images.set(assetName(loadArgs.path), loadArgs.path);
228
- return {
229
- contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
230
- loader: 'js',
231
- };
131
+ const options = {
132
+ entryPoints: [entry],
133
+ bundle: true,
134
+ format: 'iife',
135
+ outfile: bundlePath,
136
+ platform: 'neutral',
137
+ target: 'es2020',
138
+ jsx: 'automatic',
139
+ alias: { 'embedded-react': libSrc, ...REACT_PIN },
140
+ nodePaths,
141
+ define: { 'process.env.NODE_ENV': '"production"' },
142
+ legalComments: 'none',
143
+ logLevel: 'silent',
144
+ plugins: [
145
+ {
146
+ name: 'embedded-react-websim',
147
+ setup(pluginBuild) {
148
+ pluginBuild.onStart(() => {
149
+ images.clear();
150
+ fonts.clear();
151
+ });
152
+ pluginBuild.onLoad({ filter: /\.(jsx?|tsx?)$/ }, async (loadArgs) => {
153
+ // Only the app's own source — never dependencies (see shouldPersist: excluding node_modules is what
154
+ // stops the library's usePersistentState being rewritten to call itself). Native modules get their
155
+ // signatures and mocks, and with persist on, useState persists. A package's native modules get theirs too.
156
+ if (!shouldPersist(loadArgs.path, projectRootNormalized))
157
+ return loadDependencyFile(loadArgs.path, { mocks: true });
158
+ try {
159
+ return await loadAppFile(loadArgs.path, persist
160
+ ? (source) => transformPersist(source, relative(projectRoot, loadArgs.path).replace(/\\/g, '/'))
161
+ : undefined, { mocks: true });
162
+ }
163
+ catch (error) {
164
+ return { errors: [{ text: `persist transform: ${error.message}` }] };
165
+ }
166
+ });
167
+ pluginBuild.onLoad({ filter: /\.(png|jpe?g|webp|gif|bmp)$/i }, loadArgs => {
168
+ images.set(assetName(loadArgs.path), loadArgs.path);
169
+ return {
170
+ contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
171
+ loader: 'js',
172
+ };
173
+ });
174
+ pluginBuild.onLoad({ filter: /\.(ttf|otf)$/i }, loadArgs => {
175
+ fonts.set(assetName(loadArgs.path), loadArgs.path);
176
+ return {
177
+ contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
178
+ loader: 'js',
179
+ };
180
+ });
181
+ registerSvgVectorLoader(pluginBuild, (name, svgPath) => images.set(name, svgPath)); // raster-fallback SVGs join the image pack
182
+ pluginBuild.onEnd(async (result) => {
183
+ if (result.errors.length) {
184
+ console.error(`✗ build failed (${result.errors.length} error(s))`);
185
+ return;
186
+ }
187
+ await bakePack();
188
+ if (onRebuilt)
189
+ onRebuilt();
190
+ });
191
+ },
232
192
  },
233
- );
234
- pluginBuild.onLoad({filter: /\.(ttf|otf)$/i}, loadArgs => {
235
- fonts.set(assetName(loadArgs.path), loadArgs.path);
236
- return {
237
- contents: `module.exports = ${JSON.stringify(assetName(loadArgs.path))};`,
238
- loader: 'js',
239
- };
240
- });
241
- registerSvgVectorLoader(pluginBuild, (name, svgPath) =>
242
- images.set(name, svgPath),
243
- ); // raster-fallback SVGs join the image pack
244
- pluginBuild.onEnd(async result => {
245
- if (result.errors.length) {
246
- console.error(
247
- `✗ build failed (${result.errors.length} error(s))`,
248
- );
249
- return;
250
- }
251
- await bakePack();
252
- if (onRebuilt) onRebuilt();
253
- });
254
- },
255
- },
256
- ],
257
- };
258
-
259
- return {options, bundlePath, packPath};
193
+ ],
194
+ };
195
+ return { options, bundlePath, packPath };
260
196
  }
261
-
262
197
  /**
263
198
  * One-shot bundle + asset bake into outDir (app.js [+ assets.pack]). For the static export.
264
199
  * Persist transform is off (a static page has no hot reload to preserve state across).
265
200
  */
266
- export async function buildApp({
267
- entry,
268
- projectRoot,
269
- libSrc,
270
- nodePaths,
271
- outDir,
272
- }) {
273
- const {options} = createBundle({
274
- entry,
275
- projectRoot,
276
- libSrc,
277
- nodePaths,
278
- outDir,
279
- persist: false,
280
- });
281
- await esbuild.build(options);
201
+ export async function buildApp({ entry, projectRoot, libSrc, nodePaths, outDir, }) {
202
+ const { options } = createBundle({
203
+ entry,
204
+ projectRoot,
205
+ libSrc,
206
+ nodePaths,
207
+ outDir,
208
+ persist: false,
209
+ });
210
+ await esbuild.build(options);
282
211
  }
283
-
284
212
  /**
285
213
  * Run the simulator dev server: watch + bundle + bake + serve + hot reload.
286
- *
287
- * @param {object} o
288
- * @param {string} o.entry, o.projectRoot, o.libSrc, o.indexHtml, o.simDir, o.outDir, o.label
289
- * @param {string[]} o.nodePaths
290
- * @param {number} o.port
291
214
  */
292
- export async function runDevServer({
293
- entry,
294
- projectRoot,
295
- libSrc,
296
- nodePaths,
297
- indexHtml,
298
- simDir,
299
- outDir,
300
- port,
301
- label,
302
- }) {
303
- const clients = new Set();
304
- const broadcastReload = () => {
305
- for (const response of clients) response.write('data: reload\n\n');
306
- };
307
-
308
- const {options} = createBundle({
309
- entry,
310
- projectRoot,
311
- libSrc,
312
- nodePaths,
313
- outDir,
314
- persist: true,
315
- onRebuilt: () => {
316
- console.log('↻ rebuilt → reloading');
317
- broadcastReload();
318
- },
319
- });
320
-
321
- const buildContext = await esbuild.context(options);
322
- await buildContext.rebuild();
323
- await buildContext.watch();
324
-
325
- // Serve the host page; embedded-react.{js,wasm} from simDir, the freshly bundled app.js/assets.pack from
326
- // outDir. The page references ./public/<name>. window.__erHot is injected so the page connects to /reload.
327
- const send = async (response, file) => {
328
- try {
329
- const body = await readFile(file);
330
- response
331
- .writeHead(200, {
332
- 'content-type': MIME[extname(file)] || 'application/octet-stream',
333
- 'cache-control': 'no-store',
334
- })
335
- .end(body);
336
- } catch {
337
- response.writeHead(404).end('not found');
338
- }
339
- };
340
- const server = createServer(async (request, response) => {
341
- const path = decodeURIComponent(
342
- new URL(request.url, 'http://localhost').pathname,
343
- );
344
- if (path === '/reload') {
345
- response.writeHead(200, {
346
- 'content-type': 'text/event-stream',
347
- 'cache-control': 'no-cache',
348
- connection: 'keep-alive',
349
- });
350
- response.write('retry: 1000\n\n');
351
- clients.add(response);
352
- request.on('close', () => clients.delete(response));
353
- return;
354
- }
355
- if (path === '/' || path === '/index.html') {
356
- try {
357
- const html = (await readFile(indexHtml, 'utf8')).replace(
358
- '</head>',
359
- '<script>window.__erHot=true</script></head>',
360
- );
361
- response
362
- .writeHead(200, {
363
- 'content-type': MIME['.html'],
364
- 'cache-control': 'no-store',
365
- })
366
- .end(html);
367
- } catch {
215
+ export async function runDevServer({ entry, projectRoot, libSrc, nodePaths, indexHtml, simDir, outDir, port, label, }) {
216
+ const clients = new Set();
217
+ const broadcastReload = () => {
218
+ for (const response of clients)
219
+ response.write('data: reload\n\n');
220
+ };
221
+ const { options } = createBundle({
222
+ entry,
223
+ projectRoot,
224
+ libSrc,
225
+ nodePaths,
226
+ outDir,
227
+ persist: true,
228
+ onRebuilt: () => {
229
+ console.log('↻ rebuilt → reloading');
230
+ broadcastReload();
231
+ },
232
+ });
233
+ const buildContext = await esbuild.context(options);
234
+ await buildContext.rebuild();
235
+ await buildContext.watch();
236
+ // Serve the host page; embedded-react.{js,wasm} from simDir, the freshly bundled app.js/assets.pack from
237
+ // outDir. The page references ./public/<name>. window.__erHot is injected so the page connects to /reload.
238
+ const send = async (response, file) => {
239
+ try {
240
+ const body = await readFile(file);
241
+ response
242
+ .writeHead(200, {
243
+ 'content-type': MIME[extname(file)] || 'application/octet-stream',
244
+ 'cache-control': 'no-store',
245
+ })
246
+ .end(body);
247
+ }
248
+ catch {
249
+ response.writeHead(404).end('not found');
250
+ }
251
+ };
252
+ const server = createServer(async (request, response) => {
253
+ const path = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
254
+ if (path === '/reload') {
255
+ response.writeHead(200, {
256
+ 'content-type': 'text/event-stream',
257
+ 'cache-control': 'no-cache',
258
+ connection: 'keep-alive',
259
+ });
260
+ response.write('retry: 1000\n\n');
261
+ clients.add(response);
262
+ request.on('close', () => clients.delete(response));
263
+ return;
264
+ }
265
+ if (path === '/' || path === '/index.html') {
266
+ try {
267
+ const html = (await readFile(indexHtml, 'utf8')).replace('</head>', '<script>window.__erHot=true</script></head>');
268
+ response
269
+ .writeHead(200, {
270
+ 'content-type': MIME['.html'],
271
+ 'cache-control': 'no-store',
272
+ })
273
+ .end(html);
274
+ }
275
+ catch {
276
+ response.writeHead(404).end('not found');
277
+ }
278
+ return;
279
+ }
280
+ if (path.startsWith('/public/')) {
281
+ const name = basename(path); // flat filename only
282
+ const dir = name === 'embedded-react.js' || name === 'embedded-react.wasm'
283
+ ? simDir
284
+ : outDir;
285
+ return void send(response, resolve(dir, name));
286
+ }
368
287
  response.writeHead(404).end('not found');
369
- }
370
- return;
371
- }
372
- if (path.startsWith('/public/')) {
373
- const name = basename(path); // flat filename only
374
- const dir =
375
- name === 'embedded-react.js' || name === 'embedded-react.wasm'
376
- ? simDir
377
- : outDir;
378
- return void send(response, resolve(dir, name));
379
- }
380
- response.writeHead(404).end('not found');
381
- });
382
-
383
- await new Promise(onListening => server.listen(port, onListening));
384
- console.log(`embedded-react WASM sim → http://localhost:${port}/`);
385
- console.log(`watching ${label} — edit & save to hot-reload. Ctrl-C to quit.`);
386
-
387
- const shutdown = async () => {
388
- try {
389
- await buildContext.dispose();
390
- } catch {}
391
- server.close();
392
- process.exit(0);
393
- };
394
- process.on('SIGINT', shutdown);
395
- process.on('SIGTERM', shutdown);
396
- return {ctx: buildContext, server};
288
+ });
289
+ await new Promise(onListening => server.listen(port, onListening));
290
+ console.log(`embedded-react WASM sim → http://localhost:${port}/`);
291
+ console.log(`watching ${label} — edit & save to hot-reload. Ctrl-C to quit.`);
292
+ const shutdown = async () => {
293
+ try {
294
+ await buildContext.dispose();
295
+ }
296
+ catch { }
297
+ server.close();
298
+ process.exit(0);
299
+ };
300
+ process.on('SIGINT', shutdown);
301
+ process.on('SIGTERM', shutdown);
302
+ return { ctx: buildContext, server };
397
303
  }