embedded-react 0.12.0 → 0.14.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 (38) hide show
  1. package/README.md +222 -6
  2. package/aot/compile.mjs +3316 -364
  3. package/aot/style-map.mjs +30 -6
  4. package/assets/bake-font.mjs +104 -12
  5. package/assets/bake-svg.mjs +11 -1
  6. package/assets/build-builtin-font.mjs +6 -12
  7. package/assets/emit-c.mjs +10 -2
  8. package/assets/emit-container.mjs +4 -2
  9. package/assets/font-config.mjs +49 -0
  10. package/assets/font-sizes.mjs +652 -0
  11. package/assets/glyph-coverage.mjs +281 -0
  12. package/assets/index.mjs +29 -5
  13. package/build.mjs +11 -21
  14. package/cli.mjs +41 -3
  15. package/compile-bin.mjs +71 -0
  16. package/hotreload/pack-app.mjs +8 -21
  17. package/hotreload/pack-split.mjs +12 -27
  18. package/pack-container.mjs +10 -47
  19. package/package.json +2 -1
  20. package/sim/embedded-react.wasm +0 -0
  21. package/sim/index.html +32 -3
  22. package/sim-server.mjs +33 -27
  23. package/src/embedded-react/Animated.js +23 -9
  24. package/src/embedded-react/Button.js +98 -0
  25. package/src/embedded-react/FlatList.js +88 -0
  26. package/src/embedded-react/ImageBackground.js +67 -0
  27. package/src/embedded-react/PanResponder.js +326 -0
  28. package/src/embedded-react/SectionList.js +148 -0
  29. package/src/embedded-react/TouchableOpacity.js +152 -0
  30. package/src/embedded-react/components.js +4 -3
  31. package/src/embedded-react/index.d.ts +867 -60
  32. package/src/embedded-react/index.js +7 -2
  33. package/src/embedded-react/list-child.js +54 -0
  34. package/src/embedded-react/svg-ops.js +309 -77
  35. package/src/embedded-react/warn-props.js +80 -0
  36. package/src/host-config.js +103 -3
  37. package/src/props.js +40 -0
  38. package/src/renderer.js +31 -0
@@ -0,0 +1,281 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ // Build-time glyph-coverage check: a character the app renders but the bake has no glyph for is
18
+ // silently substituted with '?' by the engine (font_glyph() in engine/font/font_bitmap.c), so the
19
+ // only way to find out used to be looking at the device. Every bake path (build, pack, sim, hot
20
+ // reload, AOT) runs this over the app source and warns with the `assets.config.js` line that fixes it.
21
+ //
22
+ // The check is source-driven: it reads string and template literals (plus JSX element text, for the
23
+ // unbundled `.jsx` the AOT flow compiles). Non-ASCII from a runtime source — a fetched string,
24
+ // String.fromCharCode — can't be seen here. Comments are skipped: an em dash in prose is not text.
25
+ import {
26
+ ASCII_FIRST,
27
+ ASCII_LAST,
28
+ BUILTIN_EXTRAS,
29
+ loadGlyphProbe,
30
+ } from './bake-font.mjs';
31
+
32
+ /** Name used for the engine's fallback font in warnings (it has no family of its own). */
33
+ export const BUILTIN_FAMILY = 'the built-in font';
34
+
35
+ // Comments first so an apostrophe inside one can't open a bogus string; then the three literal
36
+ // forms. Bundled output is machine-generated, so the simple form is enough (a regex literal
37
+ // containing a lone quote is the only realistic misread, and it costs at most a stray sample).
38
+ const LITERALS =
39
+ /\/\/[^\n]*|\/\*[\s\S]*?\*\/|'(?:[^'\\\n]|\\[\s\S])*'|"(?:[^"\\\n]|\\[\s\S])*"|`(?:[^`\\]|\\[\s\S])*`/g;
40
+
41
+ const SIMPLE_ESCAPES = {n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v'};
42
+
43
+ /** Resolves the \u{...}, \uXXXX, \xNN and simple escapes a bundler emits back to characters. */
44
+ function decodeEscapes(body) {
45
+ return body.replace(
46
+ /\\u\{([0-9a-fA-F]{1,6})\}|\\u([0-9a-fA-F]{4})|\\x([0-9a-fA-F]{2})|\\([\s\S])/g,
47
+ (_m, braced, u, x, other) => {
48
+ if (braced !== undefined) {
49
+ const cp = parseInt(braced, 16);
50
+ return cp <= 0x10ffff ? String.fromCodePoint(cp) : '';
51
+ }
52
+ if (u !== undefined) return String.fromCharCode(parseInt(u, 16));
53
+ if (x !== undefined) return String.fromCharCode(parseInt(x, 16));
54
+ return SIMPLE_ESCAPES[other] ?? other; // \\ \' \" \` and friends: the character itself
55
+ },
56
+ );
57
+ }
58
+
59
+ /** Invisible/formatting characters that are never baked and never render — not worth warning about. */
60
+ function ignorable(cp) {
61
+ return (
62
+ (cp >= 0x7f && cp <= 0x9f) || // DEL + C1 controls
63
+ (cp >= 0x200b && cp <= 0x200f) || // zero-width + bidi marks
64
+ (cp >= 0x2028 && cp <= 0x202e) || // line/paragraph separators + bidi overrides
65
+ (cp >= 0xfe00 && cp <= 0xfe0f) || // variation selectors
66
+ cp === 0xfeff // BOM
67
+ );
68
+ }
69
+
70
+ // Text between two tags in unbundled JSX: `<Text>24° out</Text>`. Braces are excluded so an
71
+ // expression child stays out of it — its own literals are already covered by LITERALS.
72
+ const JSX_TEXT = />([^<>{}]+)</g;
73
+
74
+ /**
75
+ * Collects every non-ASCII character that appears in the app's rendered text.
76
+ *
77
+ * @param {string} source JS source (a bundle, a chunk, or a single component file).
78
+ * @param {object} [opts]
79
+ * @param {boolean} [opts.jsx] Also read JSX element text. Set it for unbundled `.jsx` — a bundler
80
+ * has already turned element text into string literals, and on bundled output the extra
81
+ * pass would only misread `a > b` comparisons.
82
+ * @returns {Map<number, string>} Codepoint → a short excerpt of the text it was found in.
83
+ */
84
+ export function scanTextCodepoints(source, {jsx = false} = {}) {
85
+ const found = new Map();
86
+ const collect = text => {
87
+ let i = 0;
88
+ for (const ch of text) {
89
+ const cp = ch.codePointAt(0);
90
+ if (cp > ASCII_LAST && !ignorable(cp) && !found.has(cp))
91
+ found.set(cp, excerpt(text, i, ch.length));
92
+ i += ch.length;
93
+ }
94
+ };
95
+
96
+ // Blank each token out as it is read, so the JSX pass below sees neither strings (already
97
+ // collected) nor comments (never rendered) — only real element text.
98
+ const bare = source.replace(LITERALS, tok => {
99
+ if (tok[0] !== '/') collect(decodeEscapes(tok.slice(1, -1)));
100
+ return ' '.repeat(tok.length);
101
+ });
102
+ if (jsx) for (const m of bare.matchAll(JSX_TEXT)) collect(m[1]);
103
+ return found;
104
+ }
105
+
106
+ /**
107
+ * Compact signature of the non-ASCII characters a source renders. Watch loops fold this into their
108
+ * "did the asset inputs change?" key so new text is re-checked, not just new fonts.
109
+ *
110
+ * @param {string} source JS source to scan.
111
+ * @param {object} [opts] Passed through to scanTextCodepoints (e.g. `{jsx: true}`).
112
+ * @returns {string} Sorted codepoints, comma-joined.
113
+ */
114
+ export function textSignature(source, opts) {
115
+ return [...scanTextCodepoints(source, opts).keys()]
116
+ .sort((a, b) => a - b)
117
+ .join(',');
118
+ }
119
+
120
+ /** A one-line, printable window of `text` around the character at `at` (a UTF-16 index). */
121
+ function excerpt(text, at, len) {
122
+ const start = Math.max(0, at - 12);
123
+ const end = Math.min(text.length, at + len + 12);
124
+ const body = text
125
+ .slice(start, end)
126
+ .replace(/[\n\r\t]/g, ' ')
127
+ .replace(/^[\udc00-\udfff]|[\ud800-\udbff]$/g, '') // a pair split by the window
128
+ .trim();
129
+ return `${start > 0 ? '…' : ''}${body}${end < text.length ? '…' : ''}`;
130
+ }
131
+
132
+ /** The set of codepoints a baked font can render: the dense ASCII range plus its baked extras. */
133
+ function coverageOf(baked) {
134
+ const size = baked.sizes?.[0];
135
+ const covered = new Set();
136
+ const first = size ? size.first : ASCII_FIRST;
137
+ const last = size ? size.last : ASCII_LAST;
138
+ for (let cp = first; cp <= last; cp++) covered.add(cp);
139
+ for (const e of size?.extras ?? []) covered.add(e.codepoint);
140
+ return covered;
141
+ }
142
+
143
+ /** The engine's fallback font, shaped like a bakeFont() result so both go through one code path. */
144
+ function builtinFont() {
145
+ return {
146
+ family: BUILTIN_FAMILY,
147
+ sizes: [
148
+ {
149
+ first: ASCII_FIRST,
150
+ last: ASCII_LAST,
151
+ extras: BUILTIN_EXTRAS.map(codepoint => ({codepoint})),
152
+ },
153
+ ],
154
+ };
155
+ }
156
+
157
+ /**
158
+ * Finds the characters the app renders that some font in the bake has no glyph for.
159
+ *
160
+ * Which fonts are checked follows what the app can actually draw with: with imported fonts, each
161
+ * baked font is checked (text using that family is the whole reason it was imported, and a
162
+ * character the app's own font lacks is exactly the bug worth reporting); with none, the engine's
163
+ * built-in fallback is checked instead.
164
+ *
165
+ * @param {object} opts
166
+ * @param {string} opts.source App/bundle JS to scan for rendered text.
167
+ * @param {Array<object>} [opts.fonts] bakeFont() results; empty means built-in font only.
168
+ * @param {boolean} [opts.jsx] Source is unbundled JSX — read element text too.
169
+ * @returns {Array<{codepoint:number, char:string, sample:string, missingFrom:string[],
170
+ * noGlyphIn:string[]}>} Sorted by codepoint. `noGlyphIn` narrows `missingFrom` to the
171
+ * fonts whose file has no glyph for the character at all — baking it there can't help.
172
+ */
173
+ export function findMissingGlyphs({source, fonts = [], jsx = false}) {
174
+ const checked = fonts.length ? fonts : [builtinFont()];
175
+ const coverage = checked.map(f => ({
176
+ family: f.family,
177
+ path: f.path,
178
+ covered: coverageOf(f),
179
+ }));
180
+ // Opened lazily and only for a font with a gap: most builds have none and pay nothing.
181
+ const probes = new Map();
182
+ const hasGlyph = (font, cp) => {
183
+ if (!font.path) return true; // the built-in font's coverage is its bake, nothing more to ask
184
+ if (!probes.has(font.path))
185
+ probes.set(font.path, loadGlyphProbe(font.path));
186
+ return probes.get(font.path)(cp);
187
+ };
188
+
189
+ const missing = [];
190
+ for (const [cp, sample] of scanTextCodepoints(source, {jsx})) {
191
+ const gaps = coverage.filter(c => !c.covered.has(cp));
192
+ if (!gaps.length) continue;
193
+ missing.push({
194
+ codepoint: cp,
195
+ char: String.fromCodePoint(cp),
196
+ sample,
197
+ missingFrom: gaps.map(g => g.family),
198
+ noGlyphIn: gaps.filter(g => !hasGlyph(g, cp)).map(g => g.family),
199
+ });
200
+ }
201
+ return missing.sort((a, b) => a.codepoint - b.codepoint);
202
+ }
203
+
204
+ const MAX_LISTED = 12;
205
+
206
+ /**
207
+ * Renders findMissingGlyphs() output as a developer-facing warning, ending with the config change
208
+ * that fixes it.
209
+ *
210
+ * @param {Array<object>} missing Result of findMissingGlyphs().
211
+ * @param {Array<object>} [fonts] The same bakeFont() results, for the suggested config line.
212
+ * @returns {string} The warning text (empty when nothing is missing).
213
+ */
214
+ export function formatMissingGlyphs(missing, fonts = []) {
215
+ if (!missing.length) return '';
216
+ const lines = missing.slice(0, MAX_LISTED).map(m => {
217
+ const hex = m.codepoint.toString(16).toUpperCase().padStart(4, '0');
218
+ const note = m.noGlyphIn.length
219
+ ? ` (the font file itself has no glyph for it — pick a font that covers it)`
220
+ : '';
221
+ return ` U+${hex} '${m.char}' missing from ${m.missingFrom.join(', ')}${note} in "${m.sample}"`;
222
+ });
223
+ if (missing.length > MAX_LISTED)
224
+ lines.push(` … and ${missing.length - MAX_LISTED} more`);
225
+
226
+ // One config entry per font, listing only what baking it there would actually fix.
227
+ const perFamily = fonts
228
+ .map(f => {
229
+ const chars = missing
230
+ .filter(
231
+ m =>
232
+ m.missingFrom.includes(f.family) && !m.noGlyphIn.includes(f.family),
233
+ )
234
+ .map(m => m.char)
235
+ .join('');
236
+ // A family is a file basename, so it often needs quoting to be a valid key ('Inter-Regular').
237
+ const key = /^[A-Za-z_$][\w$]*$/.test(f.family)
238
+ ? f.family
239
+ : JSON.stringify(f.family);
240
+ return chars ? `${key}: {extraGlyphs: ${JSON.stringify(chars)}}` : null;
241
+ })
242
+ .filter(Boolean);
243
+
244
+ const fix = perFamily.length
245
+ ? ` fix: assets.config.js → fonts: {${perFamily.join(', ')}}`
246
+ : fonts.length
247
+ ? ` fix: bake these from a font that has them (assets.config.js → fonts: {<Family>: {extraGlyphs: ...}})`
248
+ : ` fix: the built-in font covers ASCII + common symbols only — import a .ttf/.otf and bake the\n` +
249
+ ` rest with assets.config.js → fonts: {<Family>: {extraGlyphs: ${JSON.stringify(missing.map(m => m.char).join(''))}}}`;
250
+
251
+ return (
252
+ `embedded-react: ${missing.length} character(s) in the app's text have no baked glyph and will ` +
253
+ `render as '?':\n${lines.join('\n')}\n${fix}`
254
+ );
255
+ }
256
+
257
+ let lastWarning = null; // dev loops re-bake on every save — don't reprint an unchanged warning
258
+
259
+ /**
260
+ * Checks glyph coverage and warns. Repeats are suppressed while the warning is unchanged, so a
261
+ * watch/hot-reload loop reports each gap once rather than on every save.
262
+ *
263
+ * @param {object} opts
264
+ * @param {string} opts.source App/bundle JS to scan for rendered text.
265
+ * @param {Array<object>} [opts.fonts] bakeFont() results; empty means built-in font only.
266
+ * @param {boolean} [opts.jsx] Source is unbundled JSX — read element text too.
267
+ * @param {Function} [opts.log] Sink for the warning (default console.warn).
268
+ * @returns {Array<object>} The missing-glyph records (empty when coverage is complete).
269
+ */
270
+ export function warnMissingGlyphs({
271
+ source,
272
+ fonts = [],
273
+ jsx = false,
274
+ log = console.warn,
275
+ }) {
276
+ const missing = findMissingGlyphs({source, fonts, jsx});
277
+ const text = formatMissingGlyphs(missing, fonts);
278
+ if (text && text !== lastWarning) log(text);
279
+ lastWarning = text || null;
280
+ return missing;
281
+ }
package/assets/index.mjs CHANGED
@@ -23,6 +23,8 @@ import {bakeImage} from './bake-image.mjs';
23
23
  import {bakeFont} from './bake-font.mjs';
24
24
  import {emitAssetsC} from './emit-c.mjs';
25
25
  import {emitAssetPack} from './emit-pack.mjs';
26
+ import {warnMissingGlyphs} from './glyph-coverage.mjs';
27
+ import {warnFontSizes} from './font-sizes.mjs';
26
28
 
27
29
  /**
28
30
  * Bakes the given assets and writes assets.generated.{c,h} into outDir.
@@ -30,14 +32,25 @@ import {emitAssetPack} from './emit-pack.mjs';
30
32
  * @param {object} opts
31
33
  * @param {Array<{path:string,name:string,format?:string}>} [opts.images] Discovered image
32
34
  * imports; format 'rgb565' bakes 16-bit (see bake-image.mjs), default ARGB8888.
33
- * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any}>} [opts.fonts]
34
- * Discovered font imports with their resolved size/bpp/glyph config.
35
+ * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any,extraGlyphs:any}>}
36
+ * [opts.fonts] Discovered font imports with their resolved size/bpp/glyph config.
35
37
  * @param {string} opts.outDir Directory to write the generated files into.
38
+ * @param {string} [opts.source] Bundled app JS — scanned for text the bake has no glyph for.
39
+ * @param {{sizes:number[],dynamic:Array<object>}} [opts.usedSizes] analyzeFontSizes() result,
40
+ * checked against what was baked so an unbaked size is reported rather than silently snapped.
36
41
  * @returns {{cPath:string, hPath:string, images:number, fonts:number}}
37
42
  */
38
- export function bakeAssets({images = [], fonts = [], outDir}) {
43
+ export function bakeAssets({
44
+ images = [],
45
+ fonts = [],
46
+ outDir,
47
+ source,
48
+ usedSizes,
49
+ }) {
39
50
  const bakedImages = images.map(i => bakeImage(i));
40
51
  const bakedFonts = fonts.map(f => bakeFont(f));
52
+ if (source) warnMissingGlyphs({source, fonts: bakedFonts});
53
+ if (usedSizes) warnFontSizes({used: usedSizes, fonts: bakedFonts});
41
54
 
42
55
  const headerName = 'assets.generated.h';
43
56
  const {c, h} = emitAssetsC({
@@ -62,13 +75,24 @@ export function bakeAssets({images = [], fonts = [], outDir}) {
62
75
  *
63
76
  * @param {object} opts
64
77
  * @param {Array<{path:string,name:string}>} [opts.images]
65
- * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any}>} [opts.fonts]
78
+ * @param {Array<{path:string,family:string,sizes:number[],bpp:number,glyphs:any,extraGlyphs:any}>}
79
+ * [opts.fonts]
66
80
  * @param {string} opts.outPath Path to write the .pack file.
81
+ * @param {string} [opts.source] Bundled app JS — scanned for text the bake has no glyph for.
82
+ * @param {{sizes:number[],dynamic:Array<object>}} [opts.usedSizes] analyzeFontSizes() result.
67
83
  * @returns {{path:string, bytes:number, images:number, fonts:number}}
68
84
  */
69
- export function bakeAssetPack({images = [], fonts = [], outPath}) {
85
+ export function bakeAssetPack({
86
+ images = [],
87
+ fonts = [],
88
+ outPath,
89
+ source,
90
+ usedSizes,
91
+ }) {
70
92
  const bakedImages = images.map(i => bakeImage(i));
71
93
  const bakedFonts = fonts.map(f => bakeFont(f));
94
+ if (source) warnMissingGlyphs({source, fonts: bakedFonts});
95
+ if (usedSizes) warnFontSizes({used: usedSizes, fonts: bakedFonts});
72
96
  const pack = emitAssetPack({images: bakedImages, fonts: bakedFonts});
73
97
  fs.mkdirSync(path.dirname(outPath), {recursive: true});
74
98
  fs.writeFileSync(outPath, pack);
package/build.mjs CHANGED
@@ -31,6 +31,8 @@ import {fileURLToPath, pathToFileURL} from 'node:url';
31
31
  import {dirname, resolve, basename} from 'node:path';
32
32
  import {existsSync, readdirSync, readFileSync} from 'node:fs';
33
33
  import {bakeAssets} from './assets/index.mjs';
34
+ import {resolveFontJobs} from './assets/font-config.mjs';
35
+ import {analyzeFontSizes} from './assets/font-sizes.mjs';
34
36
  import {registerSvgVectorLoader} from './assets/svg-loader.mjs';
35
37
 
36
38
  const here = dirname(fileURLToPath(import.meta.url)); // bridges/quickjs/js
@@ -119,20 +121,15 @@ await build({
119
121
  console.log(`Bundled demo "${demo}" -> dist/app.bundle.js`);
120
122
 
121
123
  // --- Bake imported assets ---------------------------------------------------------------------
122
- // Fonts are pre-rasterized at fixed sizes (the engine has no runtime rasterizer), so bake exactly
123
- // the literal fontSize values the bundle uses. Computed/dynamic sizes can't be discovered statically
124
- // and will snap to the nearest baked size at runtime; pin them via assets.config.js if needed.
124
+ // Fonts are pre-rasterized at fixed sizes (the engine has no runtime rasterizer), so bake exactly the
125
+ // fontSize values the bundle uses — constants and token scales folded, not just literals. A size that
126
+ // only exists at runtime can't be discovered; the bake reports those rather than snapping silently.
125
127
  const bundleSrc = readFileSync(bundlePath, 'utf8');
126
- const discoveredSizes = [
127
- ...new Set(
128
- [...bundleSrc.matchAll(/\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g)].map(m =>
129
- Math.round(Number(m[1])),
130
- ),
131
- ),
132
- ].sort((a, b) => a - b);
128
+ const usedSizes = analyzeFontSizes(bundleSrc);
133
129
 
134
130
  // Optional per-demo overrides: demos/<demo>/assets.config.js
135
- // export default { fonts: { 'Family': { sizes: [..], bpp: 4, glyphs: 'ascii'|'common'|[cps] } } }
131
+ // export default { fonts: { 'Family': { sizes: [..], bpp: 4, glyphs: 'ascii'|'common'|[cps],
132
+ // extraGlyphs: '°±' } } }
136
133
  let config = {};
137
134
  const configPath = resolve(demoDir, 'assets.config.js');
138
135
  if (existsSync(configPath)) {
@@ -141,16 +138,7 @@ if (existsSync(configPath)) {
141
138
  const fontConfig = config.fonts || {};
142
139
  const imageConfig = config.images || {};
143
140
 
144
- const fontJobs = [...fonts.entries()].map(([family, path]) => {
145
- const fc = fontConfig[family] || {};
146
- const sizes =
147
- fc.sizes && fc.sizes.length
148
- ? fc.sizes
149
- : discoveredSizes.length
150
- ? discoveredSizes
151
- : [16];
152
- return {path, family, sizes, bpp: fc.bpp ?? 4, glyphs: fc.glyphs ?? 'ascii'};
153
- });
141
+ const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
154
142
  const imageJobs = [...images.entries()].map(([name, path]) => ({
155
143
  path,
156
144
  name,
@@ -161,6 +149,8 @@ const summary = bakeAssets({
161
149
  images: imageJobs,
162
150
  fonts: fontJobs,
163
151
  outDir: distDir,
152
+ source: bundleSrc,
153
+ usedSizes,
164
154
  });
165
155
  const fontDesc = fontJobs.length
166
156
  ? fontJobs
package/cli.mjs CHANGED
@@ -31,7 +31,7 @@ import {
31
31
  writeFileSync,
32
32
  } from 'node:fs';
33
33
  import {fileURLToPath, pathToFileURL} from 'node:url';
34
- import {dirname, relative, resolve} from 'node:path';
34
+ import {basename, dirname, relative, resolve} from 'node:path';
35
35
  import {tmpdir} from 'node:os';
36
36
  import {buildApp, runDevServer} from './sim-server.mjs';
37
37
  import {
@@ -339,6 +339,27 @@ async function exportApp(args) {
339
339
  }
340
340
 
341
341
  /** Resolve the root component file for the AOT compiler (App.jsx), distinct from the registry entry. */
342
+ /**
343
+ * The project identity stamped into app.gen.h as ER_AOT_DEMO / ER_AOT_DEMO_<name>, which a board example
344
+ * guards on (see the header's own comment). It is the directory of the nearest package.json at or above
345
+ * the App component, so `demos/watch-face/App.jsx` is `watch-face` whether the build runs from that
346
+ * directory or names the entry from somewhere else — and a scaffolded `src/App.jsx` reports its project
347
+ * folder rather than `src`. Deriving it from the cwd instead would stamp whatever directory you ran from.
348
+ */
349
+ function projectIdentity(appPath) {
350
+ let dir = dirname(appPath);
351
+ for (let i = 0; i < 64; i++) {
352
+ // A package.json at a filesystem root has no directory name to report — basename('/') is '' — so
353
+ // treat it as absent rather than stamp an empty identity (`ER_AOT_DEMO_` with nothing after it).
354
+ if (existsSync(resolve(dir, 'package.json')) && basename(dir))
355
+ return basename(dir);
356
+ const up = dirname(dir);
357
+ if (up === dir) break; // filesystem root
358
+ dir = up;
359
+ }
360
+ return basename(dirname(appPath)) || 'app';
361
+ }
362
+
342
363
  function resolveAppComponent(cwd, explicit) {
343
364
  if (explicit) {
344
365
  const p = resolve(cwd, explicit);
@@ -368,6 +389,9 @@ async function buildAot(cwd, explicit, outDir, screen) {
368
389
  }
369
390
  const {compileSource, bakeSvgArtifacts} = await import('./aot/compile.mjs');
370
391
  const {bakeAssets} = await import('./assets/index.mjs');
392
+ const {warnMissingGlyphs} = await import('./assets/glyph-coverage.mjs');
393
+ const {analyzeFontSizes, warnFontSizes} =
394
+ await import('./assets/font-sizes.mjs');
371
395
  const appPath = resolveAppComponent(cwd, explicit);
372
396
  const appDir = dirname(appPath);
373
397
  const src = readFileSync(appPath, 'utf8');
@@ -375,7 +399,12 @@ async function buildAot(cwd, explicit, outDir, screen) {
375
399
  try {
376
400
  // Bake <Svg source> .svg imports → vector artifacts (incl. gradients), then compile with them in hand.
377
401
  const svgArtifacts = await bakeSvgArtifacts(src, appDir);
378
- result = compileSource(src, 'app', {filename: appPath, svgArtifacts});
402
+ // app.gen.h records WHICH app it came from and a board example guards on that marker, so it must name
403
+ // the source project — the same ER_AOT_DEMO_watch_2d_face that `npm run aot -- watch-face` produces.
404
+ result = compileSource(src, projectIdentity(appPath), {
405
+ filename: appPath,
406
+ svgArtifacts,
407
+ });
379
408
  } catch (e) {
380
409
  console.error(e && e.aotLoc ? e.message : e?.message || String(e));
381
410
  process.exit(1);
@@ -402,6 +431,10 @@ async function buildAot(cwd, explicit, outDir, screen) {
402
431
  process.exit(1);
403
432
  }
404
433
  }
434
+ // Flow B renders everything in the engine's built-in font (no font imports) — check the app's text
435
+ // and its font sizes against what that font actually covers.
436
+ warnMissingGlyphs({source: src, jsx: true});
437
+ warnFontSizes({used: analyzeFontSizes(src)});
405
438
  const baked = bakeAssets({images: imageJobs, fonts: [], outDir});
406
439
  console.log(
407
440
  `✓ Flow B (AOT) → ${relative(cwd, outDir) || '.'}/app.gen.c (+ app.gen.h, assets.generated.c — ${baked.images} image(s))`,
@@ -428,7 +461,12 @@ async function buildContainer(cwd, explicit, outDir) {
428
461
 
429
462
  // Release artifact: strip the embedded source text + debug tables from the bytecode (~8x smaller
430
463
  // erpkg; stack traces lose line numbers). The dev loop (`embedded-react dev`) keeps them.
431
- const vendor = await packVendor({libSrc: lib, nodePaths: paths, simDir, strip: true});
464
+ const vendor = await packVendor({
465
+ libSrc: lib,
466
+ nodePaths: paths,
467
+ simDir,
468
+ strip: true,
469
+ });
432
470
  const app = await packApp({
433
471
  entry,
434
472
  projectRoot: cwd,
@@ -0,0 +1,71 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ // compile-bin.mjs — finds the QuickJS bytecode precompiler (er-bridge-quickjs-compile).
18
+ //
19
+ // pack-container.mjs needs it to turn a bundle into the bytecode a container carries, and parity.mjs
20
+ // preflights it because Flow A renders from a packed container. Both look in the same build dirs and
21
+ // honour the same ER_COMPILE_BIN override, so the search lives here instead of in each caller.
22
+
23
+ import {existsSync} from 'node:fs';
24
+ import {dirname, resolve} from 'node:path';
25
+ import {fileURLToPath} from 'node:url';
26
+
27
+ const here = dirname(fileURLToPath(import.meta.url)); // bridges/quickjs/js
28
+ const repoRoot = resolve(here, '../../..');
29
+ const exe = process.platform === 'win32' ? '.exe' : '';
30
+
31
+ const SEARCH_DIRS = [
32
+ 'bridges/quickjs/build',
33
+ 'examples/linux/build/bridges/quickjs',
34
+ 'tools/simulator/build/bridges/quickjs',
35
+ ];
36
+
37
+ /**
38
+ * Returns the precompiler's path, or null when there isn't one.
39
+ *
40
+ * ER_COMPILE_BIN wins, but it still has to point at a file that exists: an override with a typo in it
41
+ * used to sail through every caller's check and only fail later, deep in a build, as a bare ENOENT
42
+ * from spawn. Returning null instead routes it to compileBinHelp(), which names the real problem.
43
+ */
44
+ export function findCompileBin() {
45
+ const override = process.env.ER_COMPILE_BIN;
46
+ if (override) {
47
+ return existsSync(override) ? override : null;
48
+ }
49
+ return (
50
+ SEARCH_DIRS.map(d =>
51
+ resolve(repoRoot, d, `er-bridge-quickjs-compile${exe}`),
52
+ ).find(existsSync) || null
53
+ );
54
+ }
55
+
56
+ /** What to print when findCompileBin() comes back null — a bad override is a different problem. */
57
+ export function compileBinHelp() {
58
+ const override = process.env.ER_COMPILE_BIN;
59
+ if (override) {
60
+ return (
61
+ `ER_COMPILE_BIN is set to "${override}", but there is no file there.\n` +
62
+ 'Point it at a built er-bridge-quickjs-compile, or unset it to search the usual build dirs.'
63
+ );
64
+ }
65
+ return [
66
+ 'Bytecode precompiler (er-bridge-quickjs-compile) not found. Build it once:',
67
+ ' cmake -S bridges/quickjs -B bridges/quickjs/build',
68
+ ' cmake --build bridges/quickjs/build --target er-bridge-quickjs-compile',
69
+ '(or set ER_COMPILE_BIN to the binary path)',
70
+ ].join('\n');
71
+ }
@@ -57,6 +57,10 @@ export async function packAppContainer({
57
57
  const esbuild = require('esbuild');
58
58
  const {bakeImage} = await import('../assets/bake-image.mjs');
59
59
  const {bakeFont} = await import('../assets/bake-font.mjs');
60
+ const {resolveFontJobs} = await import('../assets/font-config.mjs');
61
+ const {analyzeFontSizes, warnFontSizes} =
62
+ await import('../assets/font-sizes.mjs');
63
+ const {warnMissingGlyphs} = await import('../assets/glyph-coverage.mjs');
60
64
  const {emitAssetPack} = await import('../assets/emit-pack.mjs');
61
65
  const {emitContainer} = await import('../assets/emit-container.mjs');
62
66
  const {registerSvgVectorLoader} = await import('../assets/svg-loader.mjs');
@@ -145,33 +149,14 @@ export async function packAppContainer({
145
149
 
146
150
  const bytecode = await compileToBytecode(bundleSrc, simDir, {strip});
147
151
 
148
- const discoveredSizes = [
149
- ...new Set(
150
- [...bundleSrc.matchAll(/\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g)].map(m =>
151
- Math.round(Number(m[1])),
152
- ),
153
- ),
154
- ].sort((a, b) => a - b);
152
+ const usedSizes = analyzeFontSizes(bundleSrc);
155
153
  let cfg = {};
156
154
  const cp = resolve(projectRoot, 'assets.config.js');
157
155
  if (existsSync(cp))
158
156
  cfg = (await import(pathToFileURL(cp).href)).default || {};
159
157
  const fontConfig = cfg.fonts || {};
160
158
  const imageConfig = cfg.images || {};
161
- const fontJobs = [...fonts.entries()].map(([family, path]) => {
162
- const fc = fontConfig[family] || {};
163
- return {
164
- path,
165
- family,
166
- sizes: fc.sizes?.length
167
- ? fc.sizes
168
- : discoveredSizes.length
169
- ? discoveredSizes
170
- : [16],
171
- bpp: fc.bpp ?? 4,
172
- glyphs: fc.glyphs ?? 'ascii',
173
- };
174
- });
159
+ const fontJobs = resolveFontJobs(fonts, fontConfig, usedSizes.sizes);
175
160
  const imageJobs = [...images.entries()].map(([name, path]) => ({
176
161
  path,
177
162
  name,
@@ -179,6 +164,8 @@ export async function packAppContainer({
179
164
  }));
180
165
  const bakedImages = imageJobs.map(bakeImage);
181
166
  const bakedFonts = fontJobs.map(bakeFont);
167
+ warnMissingGlyphs({source: bundleSrc, fonts: bakedFonts});
168
+ warnFontSizes({used: usedSizes, fonts: bakedFonts});
182
169
  const assetPack =
183
170
  bakedImages.length || bakedFonts.length
184
171
  ? emitAssetPack({images: bakedImages, fonts: bakedFonts})