embedded-react 0.20.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 (140) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +3 -2
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +17 -47
  5. package/aot/compiler/alerts.mjs +604 -0
  6. package/aot/compiler/animations.mjs +299 -57
  7. package/aot/compiler/boot.mjs +27 -2
  8. package/aot/compiler/check.mjs +62 -10
  9. package/aot/compiler/collect.mjs +517 -137
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +276 -117
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/elements/button.mjs +182 -0
  14. package/aot/compiler/elements/image-background.mjs +76 -0
  15. package/aot/compiler/elements/image.mjs +2 -1
  16. package/aot/compiler/elements/props.mjs +47 -8
  17. package/aot/compiler/elements/rewrite.mjs +118 -0
  18. package/aot/compiler/elements/section-list.mjs +370 -0
  19. package/aot/compiler/expressions.mjs +1378 -97
  20. package/aot/compiler/handlers.mjs +1807 -354
  21. package/aot/compiler/helper-values.mjs +312 -0
  22. package/aot/compiler/ir/nodes.mjs +40 -1
  23. package/aot/compiler/ir/reads.mjs +206 -5
  24. package/aot/compiler/ir/text.mjs +5 -1
  25. package/aot/compiler/ir/types.mjs +12 -0
  26. package/aot/compiler/kept-states.mjs +177 -0
  27. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  28. package/aot/compiler/keyboard.mjs +1 -1
  29. package/aot/compiler/list-items.mjs +226 -0
  30. package/aot/compiler/list-order.mjs +586 -0
  31. package/aot/compiler/list-split.mjs +259 -0
  32. package/aot/compiler/loops.mjs +582 -0
  33. package/aot/compiler/lower.mjs +203 -53
  34. package/aot/compiler/native-files.mjs +439 -0
  35. package/aot/compiler/native-header.mjs +335 -0
  36. package/aot/compiler/native-modules.mjs +1173 -0
  37. package/aot/compiler/nodes.mjs +45 -31
  38. package/aot/compiler/options.mjs +3 -2
  39. package/aot/compiler/out.mjs +18 -1
  40. package/aot/compiler/package/animations.mjs +133 -23
  41. package/aot/compiler/package/assemble.mjs +2 -4
  42. package/aot/compiler/package/bytecode.mjs +37 -8
  43. package/aot/compiler/package/checks.mjs +4 -0
  44. package/aot/compiler/package/codegen.mjs +906 -33
  45. package/aot/compiler/package/enums.mjs +10 -0
  46. package/aot/compiler/package/format.mjs +16 -3
  47. package/aot/compiler/package/lower.mjs +707 -176
  48. package/aot/compiler/package/string-caps.mjs +515 -0
  49. package/aot/compiler/package/tables.mjs +24 -0
  50. package/aot/compiler/package/writer.mjs +22 -0
  51. package/aot/compiler/parse.mjs +3 -1
  52. package/aot/compiler/record-shapes.mjs +246 -0
  53. package/aot/compiler/records.mjs +654 -0
  54. package/aot/compiler/reducers.mjs +272 -0
  55. package/aot/compiler/scroll-to.mjs +112 -0
  56. package/aot/compiler/static-eval.mjs +315 -7
  57. package/aot/compiler/style-text.mjs +20 -5
  58. package/aot/compiler/svg.mjs +13 -7
  59. package/aot/compiler/switch-cases.mjs +198 -0
  60. package/aot/compiler/tagged-records.mjs +450 -0
  61. package/aot/compiler/typing.mjs +307 -0
  62. package/aot/compiler/updaters.mjs +321 -0
  63. package/aot/compiler/window-dimensions.mjs +94 -0
  64. package/aot/compiler/worked-values.mjs +319 -0
  65. package/aot/demo-file.mjs +30 -0
  66. package/aot/style-map.mjs +94 -3
  67. package/assets/bake-font.mjs +187 -244
  68. package/assets/bake-image.mjs +47 -71
  69. package/assets/bake-svg.mjs +465 -533
  70. package/assets/build-builtin-font.mjs +14 -27
  71. package/assets/emit-c.mjs +124 -204
  72. package/assets/emit-container.mjs +129 -197
  73. package/assets/emit-pack.mjs +92 -136
  74. package/assets/font-config.mjs +19 -27
  75. package/assets/font-sizes.mjs +432 -507
  76. package/assets/glyph-coverage.mjs +170 -214
  77. package/assets/index.mjs +52 -97
  78. package/assets/rasterize.mjs +173 -194
  79. package/assets/svg-loader.mjs +42 -48
  80. package/build.mjs +85 -94
  81. package/cli.mjs +490 -586
  82. package/compile-bin.mjs +24 -36
  83. package/flash.mjs +297 -401
  84. package/hotreload/dev-device.mjs +229 -270
  85. package/hotreload/pack-app.mjs +118 -159
  86. package/hotreload/pack-split.mjs +146 -213
  87. package/hotreload/package-transfer.mjs +128 -131
  88. package/hotreload/protocol.mjs +118 -118
  89. package/hotreload/uploader.mjs +132 -159
  90. package/hotreload/watch-tree.mjs +56 -65
  91. package/pack-container.mjs +94 -116
  92. package/package.json +19 -16
  93. package/persist-transform.mjs +89 -105
  94. package/qjsc-wasm.mjs +47 -72
  95. package/sim/embedded-react.wasm +0 -0
  96. package/sim/index.html +1 -1
  97. package/sim-server.mjs +260 -354
  98. package/src/embedded-react/Alert.mjs +112 -0
  99. package/src/embedded-react/Animated.mjs +412 -0
  100. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  101. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  102. package/src/embedded-react/Dimensions.mjs +32 -0
  103. package/src/embedded-react/Easing.mjs +34 -0
  104. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  105. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  106. package/src/embedded-react/Keyboard.mjs +82 -0
  107. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  108. package/src/embedded-react/PanResponder.mjs +256 -0
  109. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  110. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  111. package/src/embedded-react/SectionList.mjs +103 -0
  112. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  113. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  114. package/src/embedded-react/background-image.mjs +321 -0
  115. package/src/embedded-react/{components.js → components.mjs} +1 -3
  116. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  117. package/src/embedded-react/index.d.ts +238 -5
  118. package/src/embedded-react/index.js +26 -17
  119. package/src/embedded-react/layout-anim-config.mjs +85 -0
  120. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  121. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  122. package/src/embedded-react/nativeModule.mjs +371 -0
  123. package/src/embedded-react/split-style.mjs +57 -0
  124. package/src/embedded-react/svg-ops.mjs +1075 -0
  125. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  126. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  127. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  128. package/src/host-config.mjs +512 -0
  129. package/src/{native-ui.js → native-ui.mjs} +1 -8
  130. package/src/props.mjs +341 -0
  131. package/src/{renderer.js → renderer.mjs} +30 -44
  132. package/src/embedded-react/Animated.js +0 -440
  133. package/src/embedded-react/Easing.js +0 -39
  134. package/src/embedded-react/PanResponder.js +0 -330
  135. package/src/embedded-react/SectionList.js +0 -148
  136. package/src/embedded-react/layout-anim-config.js +0 -101
  137. package/src/embedded-react/split-style.js +0 -58
  138. package/src/embedded-react/svg-ops.js +0 -1295
  139. package/src/host-config.js +0 -548
  140. package/src/props.js +0 -306
@@ -13,7 +13,6 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
-
17
16
  // Build-time font-size discovery and coverage check. The engine has no runtime rasterizer: a font is
18
17
  // baked at fixed pixel sizes and font_registry_get() (engine/font/font_registry.c) snaps anything
19
18
  // else to the nearest baked size, ties going to the larger. So the bake has to know every size the
@@ -28,287 +27,268 @@
28
27
  //
29
28
  // What folding can't see is a size that only exists at runtime: a prop, state, a computed key. Those
30
29
  // are reported rather than guessed at, because the runtime result is a silent snap, not an error.
31
- import {parse} from '@babel/parser';
32
- import {BUILTIN_SIZES} from './bake-font.mjs';
33
- import {BUILTIN_FAMILY} from './glyph-coverage.mjs';
34
-
30
+ import { parse } from '@babel/parser';
31
+ import { BUILTIN_SIZES } from './bake-font.mjs';
32
+ import { BUILTIN_FAMILY } from './glyph-coverage.mjs';
35
33
  /** Sizes one family may register before the engine starts dropping them (FONT_FAMILY_MAX_SIZES). */
36
34
  const MAX_BAKED_SIZES = 16;
37
-
38
35
  /** Bounds of the engine's uint8 BitmapFont.pixel_size — a folded value outside them isn't a size. */
39
36
  const MIN_PX = 1;
40
37
  const MAX_PX = 255;
41
-
42
38
  /** The range er_text_measure()/er_text_draw() clamp a requested size into before resolving a font. */
43
39
  const RENDER_MIN_PX = 8;
44
40
  const RENDER_MAX_PX = 96;
45
-
46
41
  // A responsive scale multiplies out (two ternary arms times two more, …). Both limits keep a
47
42
  // pathological expression from turning discovery into a combinatorial walk; the cost of clipping is
48
43
  // an under-bake that the "could not be read" report below already covers.
49
44
  const MAX_CANDIDATES = 12;
50
45
  const MAX_DEPTH = 16;
51
-
52
46
  // Whole-word `fontSize: <number>` — the pre-folding scan, kept as the fallback for a source the
53
47
  // parser chokes on (a future syntax, a mangled bundle). Strictly weaker, never silently preferred.
54
48
  const LITERAL_SIZE = /\bfontSize\s*:\s*(\d+(?:\.\d+)?)/g;
55
-
56
49
  // Unresolved fontSize expressions are reported up to this many characters.
57
50
  const SNIPPET_MAX_LENGTH = 48;
58
-
59
51
  const PARSER_OPTIONS = {
60
- sourceType: 'unambiguous', // an IIFE bundle is a script; an app entry is a module
61
- errorRecovery: true,
62
- // Same pair the AOT parser uses: the TS plugin is harmless on plain JS/JSX and lets a .tsx app
63
- // through unchanged.
64
- plugins: ['jsx', 'typescript'],
52
+ sourceType: 'unambiguous', // an IIFE bundle is a script; an app entry is a module
53
+ errorRecovery: true,
54
+ // Same pair the AOT parser uses: the TS plugin is harmless on plain JS/JSX and lets a .tsx app
55
+ // through unchanged.
56
+ plugins: ['jsx', 'typescript'],
65
57
  };
66
-
67
58
  /*--- AST walking --------------------------------------------------------------------------------*/
68
-
69
59
  // Keys that hold position/comment bookkeeping rather than child nodes. Skipping them is purely a
70
60
  // speed matter (they carry no `type`), but on a 300 KB bundle it is most of the walk.
71
61
  const NON_NODE_KEYS = new Set([
72
- 'loc',
73
- 'start',
74
- 'end',
75
- 'range',
76
- 'extra',
77
- 'comments',
78
- 'leadingComments',
79
- 'trailingComments',
80
- 'innerComments',
62
+ 'loc',
63
+ 'start',
64
+ 'end',
65
+ 'range',
66
+ 'extra',
67
+ 'comments',
68
+ 'leadingComments',
69
+ 'trailingComments',
70
+ 'innerComments',
81
71
  ]);
82
-
83
72
  /** Depth-first visit of every AST node under `node`, in source order. */
84
73
  function walk(node, visit) {
85
- if (Array.isArray(node)) {
86
- for (const item of node) walk(item, visit);
87
- return;
88
- }
89
- if (!node || typeof node !== 'object' || typeof node.type !== 'string')
90
- return;
91
- visit(node);
92
- for (const key of Object.keys(node)) {
93
- if (NON_NODE_KEYS.has(key)) continue;
94
- const child = node[key];
95
- if (child && typeof child === 'object') walk(child, visit);
96
- }
74
+ if (Array.isArray(node)) {
75
+ for (const item of node)
76
+ walk(item, visit);
77
+ return;
78
+ }
79
+ if (!node || typeof node !== 'object')
80
+ return;
81
+ const fields = node;
82
+ if (typeof fields.type !== 'string')
83
+ return;
84
+ visit(node);
85
+ for (const key of Object.keys(fields)) {
86
+ if (NON_NODE_KEYS.has(key))
87
+ continue;
88
+ const child = fields[key];
89
+ if (child && typeof child === 'object')
90
+ walk(child, visit);
91
+ }
97
92
  }
98
-
99
93
  /** Static name of a non-computed property key, or null when the key isn't a fixed string. */
100
94
  function keyName(node) {
101
- if (node.computed) return null;
102
- const key = node.key;
103
- if (!key) return null;
104
- if (key.type === 'Identifier') return key.name;
105
- if (key.type === 'StringLiteral') return key.value;
106
- if (key.type === 'NumericLiteral') return String(key.value);
107
- return null;
95
+ if (node.computed)
96
+ return null;
97
+ const key = node.key;
98
+ if (!key)
99
+ return null;
100
+ if (key.type === 'Identifier')
101
+ return key.name;
102
+ if (key.type === 'StringLiteral')
103
+ return key.value;
104
+ if (key.type === 'NumericLiteral')
105
+ return String(key.value);
106
+ return null;
108
107
  }
109
-
110
108
  /*--- Constant folding ---------------------------------------------------------------------------*/
111
-
112
109
  // A folded value is either a number or a Scale: an object/array whose properties are themselves
113
110
  // candidate lists, so `TYPE.title` is a lookup and a ternary is a union.
114
- const scale = properties => ({properties});
115
- const isScale = value =>
116
- value !== null &&
117
- typeof value === 'object' &&
118
- value.properties instanceof Map;
119
-
111
+ const scale = (properties) => ({ properties });
112
+ const isScale = (value) => value !== null &&
113
+ typeof value === 'object' &&
114
+ value.properties instanceof Map;
120
115
  /** Trims a candidate list to the fan-out budget, dropping duplicates first. */
121
- const cap = values =>
122
- values.length > MAX_CANDIDATES
116
+ const cap = (values) => values.length > MAX_CANDIDATES
123
117
  ? [...new Set(values)].slice(0, MAX_CANDIDATES)
124
118
  : values;
125
-
126
119
  /** The numbers in a candidate list (a Scale is not a size). */
127
- const numbers = values => values.filter(value => typeof value === 'number');
128
-
120
+ const numbers = (values) => values.filter(value => typeof value === 'number');
129
121
  const ARITHMETIC = {
130
- '+': (left, right) => left + right,
131
- '-': (left, right) => left - right,
132
- '*': (left, right) => left * right,
133
- '/': (left, right) => left / right,
134
- '%': (left, right) => left % right,
135
- '**': (left, right) => left ** right,
122
+ '+': (left, right) => left + right,
123
+ '-': (left, right) => left - right,
124
+ '*': (left, right) => left * right,
125
+ '/': (left, right) => left / right,
126
+ '%': (left, right) => left % right,
127
+ '**': (left, right) => left ** right,
136
128
  };
137
-
138
129
  // Rounding is how a ratio-based scale lands on whole pixels (Math.round(base * 1.25)); min/max is
139
130
  // how it gets clamped. Anything else on Math is left unresolved rather than guessed.
140
131
  const MATH_FUNCTIONS = {
141
- round: Math.round,
142
- floor: Math.floor,
143
- ceil: Math.ceil,
144
- abs: Math.abs,
145
- min: Math.min,
146
- max: Math.max,
132
+ round: Math.round,
133
+ floor: Math.floor,
134
+ ceil: Math.ceil,
135
+ abs: Math.abs,
136
+ min: Math.min,
137
+ max: Math.max,
147
138
  };
148
-
149
139
  /**
150
140
  * Statically evaluates an expression to the values it can take.
151
141
  *
152
- * @param {object} node Expression AST node.
153
- * @param {object} scope Fold scope from buildScope().
154
- * @param {number} [depth] Recursion guard.
155
- * @returns {any[]} Candidate values (numbers and/or Scales); empty when nothing can be resolved.
142
+ * @param node Expression AST node.
143
+ * @param scope Fold scope from buildScope().
144
+ * @param depth Recursion guard.
145
+ * @returns Candidate values (numbers and/or Scales); empty when nothing can be resolved.
156
146
  */
157
147
  function evaluate(node, scope, depth = 0) {
158
- if (!node || depth > MAX_DEPTH) return [];
159
- const evaluateChild = child => evaluate(child, scope, depth + 1);
160
-
161
- switch (node.type) {
162
- case 'NumericLiteral':
163
- return [node.value];
164
-
165
- case 'Identifier':
166
- return lookup(node.name, scope, depth);
167
-
168
- // A parenthesized expression, a TS cast, a `!` assertion: transparent for our purposes.
169
- case 'ParenthesizedExpression':
170
- case 'TSAsExpression':
171
- case 'TSSatisfiesExpression':
172
- case 'TSNonNullExpression':
173
- case 'TSTypeAssertion':
174
- case 'TypeCastExpression':
175
- return evaluateChild(node.expression);
176
-
177
- case 'UnaryExpression': {
178
- if (node.operator !== '-' && node.operator !== '+') return [];
179
- const sign = node.operator === '-' ? -1 : 1;
180
- return numbers(evaluateChild(node.argument)).map(value => sign * value);
181
- }
182
-
183
- case 'BinaryExpression': {
184
- const operation = ARITHMETIC[node.operator];
185
- if (!operation) return [];
186
- const left = numbers(evaluateChild(node.left));
187
- const right = numbers(evaluateChild(node.right));
188
- const results = [];
189
- for (const leftValue of left)
190
- for (const rightValue of right)
191
- results.push(operation(leftValue, rightValue));
192
- return cap(results);
193
- }
194
-
195
- // Both arms: which one a responsive app takes depends on the panel it boots on, and the same
196
- // bundle runs on all of them.
197
- case 'ConditionalExpression':
198
- return cap([
199
- ...evaluateChild(node.consequent),
200
- ...evaluateChild(node.alternate),
201
- ]);
202
-
203
- // `a ?? b` / `a || b` are the same shape of choice; `&&` can only ever yield its right arm.
204
- case 'LogicalExpression':
205
- return node.operator === '&&'
206
- ? evaluateChild(node.right)
207
- : cap([...evaluateChild(node.left), ...evaluateChild(node.right)]);
208
-
209
- case 'ObjectExpression': {
210
- const properties = new Map();
211
- for (const property of node.properties) {
212
- if (property.type === 'SpreadElement') {
213
- for (const base of evaluateChild(property.argument).filter(isScale))
214
- for (const [key, values] of base.properties)
215
- properties.set(key, values);
216
- continue;
148
+ if (!node || depth > MAX_DEPTH)
149
+ return [];
150
+ const evaluateChild = (child) => evaluate(child, scope, depth + 1);
151
+ switch (node.type) {
152
+ case 'NumericLiteral':
153
+ return [node.value];
154
+ case 'Identifier':
155
+ return lookup(node.name, scope, depth);
156
+ // A parenthesized expression, a TS cast, a `!` assertion: transparent for our purposes.
157
+ case 'ParenthesizedExpression':
158
+ case 'TSAsExpression':
159
+ case 'TSSatisfiesExpression':
160
+ case 'TSNonNullExpression':
161
+ case 'TSTypeAssertion':
162
+ case 'TypeCastExpression':
163
+ return evaluateChild(node.expression);
164
+ case 'UnaryExpression': {
165
+ if (node.operator !== '-' && node.operator !== '+')
166
+ return [];
167
+ const sign = node.operator === '-' ? -1 : 1;
168
+ return numbers(evaluateChild(node.argument)).map(value => sign * value);
217
169
  }
218
- if (property.type !== 'ObjectProperty') continue; // a method is never a size
219
- const name = keyName(property);
220
- if (name === null) continue;
221
- const values = evaluateChild(property.value);
222
- if (values.length) properties.set(name, values);
223
- }
224
- return [scale(properties)];
225
- }
226
-
227
- case 'ArrayExpression': {
228
- const properties = new Map();
229
- node.elements.forEach((element, index) => {
230
- if (!element || element.type === 'SpreadElement') return;
231
- const values = evaluateChild(element);
232
- if (values.length) properties.set(String(index), values);
233
- });
234
- return [scale(properties)];
235
- }
236
-
237
- case 'MemberExpression': {
238
- const objects = evaluateChild(node.object).filter(isScale);
239
- if (!objects.length) return [];
240
- const key = memberKey(node, scope, depth);
241
- const results = [];
242
- for (const object of objects) {
243
- // An unresolvable key (`TYPE[variant]`) still narrows things to one scale, and every entry
244
- // in it is something the app can reach — take the lot rather than nothing.
245
- if (key === null) {
246
- for (const values of object.properties.values())
247
- results.push(...values);
248
- } else {
249
- results.push(...(object.properties.get(key) ?? []));
170
+ case 'BinaryExpression': {
171
+ const operation = ARITHMETIC[node.operator];
172
+ if (!operation)
173
+ return [];
174
+ const left = numbers(evaluateChild(node.left));
175
+ const right = numbers(evaluateChild(node.right));
176
+ const results = [];
177
+ for (const leftValue of left)
178
+ for (const rightValue of right)
179
+ results.push(operation(leftValue, rightValue));
180
+ return cap(results);
250
181
  }
251
- }
252
- return cap(results);
253
- }
254
-
255
- case 'CallExpression': {
256
- const {callee} = node;
257
- if (
258
- callee?.type !== 'MemberExpression' ||
259
- callee.computed ||
260
- callee.object?.type !== 'Identifier' ||
261
- callee.object.name !== 'Math' ||
262
- callee.property?.type !== 'Identifier'
263
- )
264
- return [];
265
- const mathFunction = MATH_FUNCTIONS[callee.property.name];
266
- if (!mathFunction) return [];
267
- // Every argument must resolve, or the result isn't the one the app computes.
268
- const argumentValues = node.arguments.map(argument =>
269
- numbers(evaluateChild(argument)),
270
- );
271
- if (
272
- !argumentValues.length ||
273
- argumentValues.some(candidates => !candidates.length)
274
- )
275
- return [];
276
- return cap(
277
- combine(argumentValues).map(values => mathFunction(...values)),
278
- );
182
+ // Both arms: which one a responsive app takes depends on the panel it boots on, and the same
183
+ // bundle runs on all of them.
184
+ case 'ConditionalExpression':
185
+ return cap([
186
+ ...evaluateChild(node.consequent),
187
+ ...evaluateChild(node.alternate),
188
+ ]);
189
+ // `a ?? b` / `a || b` are the same shape of choice; `&&` can only ever yield its right arm.
190
+ case 'LogicalExpression':
191
+ return node.operator === '&&'
192
+ ? evaluateChild(node.right)
193
+ : cap([...evaluateChild(node.left), ...evaluateChild(node.right)]);
194
+ case 'ObjectExpression': {
195
+ const properties = new Map();
196
+ for (const property of node.properties) {
197
+ if (property.type === 'SpreadElement') {
198
+ for (const base of evaluateChild(property.argument).filter(isScale))
199
+ for (const [key, values] of base.properties)
200
+ properties.set(key, values);
201
+ continue;
202
+ }
203
+ if (property.type !== 'ObjectProperty')
204
+ continue; // a method is never a size
205
+ const name = keyName(property);
206
+ if (name === null)
207
+ continue;
208
+ const values = evaluateChild(property.value);
209
+ if (values.length)
210
+ properties.set(name, values);
211
+ }
212
+ return [scale(properties)];
213
+ }
214
+ case 'ArrayExpression': {
215
+ const properties = new Map();
216
+ node.elements.forEach((element, index) => {
217
+ if (!element || element.type === 'SpreadElement')
218
+ return;
219
+ const values = evaluateChild(element);
220
+ if (values.length)
221
+ properties.set(String(index), values);
222
+ });
223
+ return [scale(properties)];
224
+ }
225
+ case 'MemberExpression': {
226
+ const objects = evaluateChild(node.object).filter(isScale);
227
+ if (!objects.length)
228
+ return [];
229
+ const key = memberKey(node, scope, depth);
230
+ const results = [];
231
+ for (const object of objects) {
232
+ // An unresolvable key (`TYPE[variant]`) still narrows things to one scale, and every entry
233
+ // in it is something the app can reach — take the lot rather than nothing.
234
+ if (key === null) {
235
+ for (const values of object.properties.values())
236
+ results.push(...values);
237
+ }
238
+ else {
239
+ results.push(...(object.properties.get(key) ?? []));
240
+ }
241
+ }
242
+ return cap(results);
243
+ }
244
+ case 'CallExpression': {
245
+ const { callee } = node;
246
+ if (callee?.type !== 'MemberExpression' ||
247
+ callee.computed ||
248
+ callee.object?.type !== 'Identifier' ||
249
+ callee.object.name !== 'Math' ||
250
+ callee.property?.type !== 'Identifier')
251
+ return [];
252
+ const mathFunction = MATH_FUNCTIONS[callee.property.name];
253
+ if (!mathFunction)
254
+ return [];
255
+ // Every argument must resolve, or the result isn't the one the app computes.
256
+ const argumentValues = node.arguments.map(argument => numbers(evaluateChild(argument)));
257
+ if (!argumentValues.length ||
258
+ argumentValues.some(candidates => !candidates.length))
259
+ return [];
260
+ return cap(combine(argumentValues).map(values => mathFunction(...values)));
261
+ }
262
+ default:
263
+ return [];
279
264
  }
280
-
281
- default:
282
- return [];
283
- }
284
265
  }
285
-
286
266
  /** Cartesian product of per-argument candidate lists, clipped to the fan-out budget. */
287
267
  function combine(lists) {
288
- let rows = [[]];
289
- for (const list of lists) {
290
- const next = [];
291
- for (const row of rows)
292
- for (const value of list) {
293
- if (next.length >= MAX_CANDIDATES) break;
294
- next.push([...row, value]);
295
- }
296
- rows = next;
297
- }
298
- return rows;
268
+ let rows = [[]];
269
+ for (const list of lists) {
270
+ const next = [];
271
+ for (const row of rows)
272
+ for (const value of list) {
273
+ if (next.length >= MAX_CANDIDATES)
274
+ break;
275
+ next.push([...row, value]);
276
+ }
277
+ rows = next;
278
+ }
279
+ return rows;
299
280
  }
300
-
301
281
  /** Property name a member expression reads, resolving a computed key when it folds to a constant. */
302
282
  function memberKey(node, scope, depth) {
303
- if (!node.computed)
304
- return node.property.type === 'Identifier' ? node.property.name : null;
305
- if (node.property.type === 'StringLiteral') return node.property.value;
306
- if (node.property.type === 'NumericLiteral')
307
- return String(node.property.value);
308
- const folded = numbers(evaluate(node.property, scope, depth + 1));
309
- return folded.length === 1 ? String(folded[0]) : null;
283
+ if (!node.computed)
284
+ return node.property.type === 'Identifier' ? node.property.name : null;
285
+ if (node.property.type === 'StringLiteral')
286
+ return node.property.value;
287
+ if (node.property.type === 'NumericLiteral')
288
+ return String(node.property.value);
289
+ const folded = numbers(evaluate(node.property, scope, depth + 1));
290
+ return folded.length === 1 ? String(folded[0]) : null;
310
291
  }
311
-
312
292
  /**
313
293
  * Resolves a name to its candidate values, memoizing the answer (including "nothing").
314
294
  *
@@ -317,20 +297,18 @@ function memberKey(node, scope, depth) {
317
297
  * names a bundle contains are only ever evaluated for the handful a fontSize actually reads.
318
298
  */
319
299
  function lookup(name, scope, depth) {
320
- const known = scope.environment.get(name);
321
- if (known !== undefined) return known; // a memoized "nothing" is an answer, not a miss
322
- const bound = scope.bindings.get(name);
323
- if (!bound || scope.resolving.has(name)) return [];
324
-
325
- scope.resolving.add(name);
326
- const values = cap(
327
- bound.flatMap(node => evaluate(node, scope, depth + 1)).filter(isScale),
328
- );
329
- scope.resolving.delete(name);
330
- scope.environment.set(name, values);
331
- return values;
300
+ const known = scope.environment.get(name);
301
+ if (known !== undefined)
302
+ return known; // a memoized "nothing" is an answer, not a miss
303
+ const bound = scope.bindings.get(name);
304
+ if (!bound || scope.resolving.has(name))
305
+ return [];
306
+ scope.resolving.add(name);
307
+ const values = cap(bound.flatMap(node => evaluate(node, scope, depth + 1)).filter(isScale));
308
+ scope.resolving.delete(name);
309
+ scope.environment.set(name, values);
310
+ return values;
332
311
  }
333
-
334
312
  /**
335
313
  * Builds the fold scope for one program: the names it binds to a constant, and the names a scale is
336
314
  * handed down under.
@@ -345,142 +323,137 @@ function lookup(name, scope, depth) {
345
323
  * this to the "pass the scale down" pattern it is for. A name passed different scales in different
346
324
  * places resolves to all of them, which over-bakes at worst; declared names always win.
347
325
  *
348
- * @param {object} ast Parsed program.
349
- * @returns {{environment: Map<string,any[]>, bindings: Map<string,object[]>, resolving: Set<string>}}
326
+ * @param ast Parsed program.
350
327
  */
351
328
  function buildScope(ast) {
352
- const declarations = [];
353
- const counts = new Map();
354
- const bindings = new Map();
355
- const bind = (name, node) => {
356
- if (node.type !== 'Identifier' && node.type !== 'MemberExpression') return;
357
- const list = bindings.get(name);
358
- if (list) list.push(node);
359
- else bindings.set(name, [node]);
360
- };
361
-
362
- walk(ast.program, node => {
363
- if (node.type === 'VariableDeclarator') {
364
- if (node.id?.type === 'Identifier' && node.init) {
365
- declarations.push(node);
366
- counts.set(node.id.name, (counts.get(node.id.name) ?? 0) + 1);
367
- }
368
- return;
369
- }
370
- if (
371
- node.type === 'JSXAttribute' &&
372
- node.name?.type === 'JSXIdentifier' &&
373
- node.value?.type === 'JSXExpressionContainer'
374
- ) {
375
- bind(node.name.name, node.value.expression);
376
- return;
377
- }
378
- if (node.type === 'ObjectProperty') {
379
- const name = keyName(node);
380
- if (name !== null) bind(name, node.value);
381
- }
382
- });
383
-
384
- // Constants fold first, against no bindings at all: lookup() memoizes what it resolves, and a
385
- // binding consulted mid-fold could cache an answer taken from a half-built environment. Two passes,
386
- // so a scale that reads a constant declared below it still folds; a third would only help a chain
387
- // that deep, which no type scale is.
388
- const scope = {
389
- environment: new Map(),
390
- bindings: new Map(),
391
- resolving: new Set(),
392
- };
393
- for (let pass = 0; pass < 2; pass++) {
394
- for (const declaration of declarations) {
395
- const name = declaration.id.name;
396
- if (counts.get(name) > 1) continue;
397
- const values = evaluate(declaration.init, scope);
398
- if (values.length) scope.environment.set(name, values);
329
+ const declarations = [];
330
+ const counts = new Map();
331
+ const bindings = new Map();
332
+ const bind = (name, node) => {
333
+ if (node.type !== 'Identifier' && node.type !== 'MemberExpression')
334
+ return;
335
+ const list = bindings.get(name);
336
+ if (list)
337
+ list.push(node);
338
+ else
339
+ bindings.set(name, [node]);
340
+ };
341
+ walk(ast.program, node => {
342
+ if (node.type === 'VariableDeclarator') {
343
+ if (node.id?.type === 'Identifier' && node.init) {
344
+ declarations.push(node);
345
+ counts.set(node.id.name, (counts.get(node.id.name) ?? 0) + 1);
346
+ }
347
+ return;
348
+ }
349
+ if (node.type === 'JSXAttribute' &&
350
+ node.name?.type === 'JSXIdentifier' &&
351
+ node.value?.type === 'JSXExpressionContainer') {
352
+ bind(node.name.name, node.value.expression);
353
+ return;
354
+ }
355
+ if (node.type === 'ObjectProperty') {
356
+ const name = keyName(node);
357
+ if (name !== null)
358
+ bind(name, node.value);
359
+ }
360
+ });
361
+ // Constants fold first, against no bindings at all: lookup() memoizes what it resolves, and a
362
+ // binding consulted mid-fold could cache an answer taken from a half-built environment. Two passes,
363
+ // so a scale that reads a constant declared below it still folds; a third would only help a chain
364
+ // that deep, which no type scale is.
365
+ const scope = {
366
+ environment: new Map(),
367
+ bindings: new Map(),
368
+ resolving: new Set(),
369
+ };
370
+ for (let pass = 0; pass < 2; pass++) {
371
+ for (const declaration of declarations) {
372
+ const name = declaration.id.name;
373
+ if (counts.get(name) > 1)
374
+ continue;
375
+ const values = evaluate(declaration.init, scope);
376
+ if (values.length)
377
+ scope.environment.set(name, values);
378
+ }
399
379
  }
400
- }
401
- // A declared name resolves to its declaration or to nothing; it never falls through to a binding.
402
- for (const name of counts.keys()) bindings.delete(name);
403
- scope.bindings = bindings;
404
- return scope;
380
+ // A declared name resolves to its declaration or to nothing; it never falls through to a binding.
381
+ for (const name of counts.keys())
382
+ bindings.delete(name);
383
+ scope.bindings = bindings;
384
+ return scope;
405
385
  }
406
-
407
386
  /*--- Discovery ----------------------------------------------------------------------------------*/
408
-
409
387
  /** Rounds a folded value to a bakeable pixel size, or null when it isn't one. */
410
388
  function toPixelSize(value) {
411
- const pixelSize = Math.round(value);
412
- return Number.isFinite(pixelSize) &&
413
- pixelSize >= MIN_PX &&
414
- pixelSize <= MAX_PX
415
- ? pixelSize
416
- : null;
389
+ const pixelSize = Math.round(value);
390
+ return Number.isFinite(pixelSize) &&
391
+ pixelSize >= MIN_PX &&
392
+ pixelSize <= MAX_PX
393
+ ? pixelSize
394
+ : null;
417
395
  }
418
-
419
396
  /** One-line, length-capped rendering of the expression behind an unresolved fontSize. */
420
397
  function snippet(source, node) {
421
- const raw = source.slice(node.start, node.end).replace(/\s+/g, ' ').trim();
422
- return raw.length > SNIPPET_MAX_LENGTH
423
- ? `${raw.slice(0, SNIPPET_MAX_LENGTH - 1)}…`
424
- : raw;
398
+ const raw = source.slice(node.start, node.end).replace(/\s+/g, ' ').trim();
399
+ return raw.length > SNIPPET_MAX_LENGTH
400
+ ? `${raw.slice(0, SNIPPET_MAX_LENGTH - 1)}…`
401
+ : raw;
425
402
  }
426
-
427
403
  /** Literal-only discovery, for a source the parser rejected. */
428
404
  function scanLiterals(source) {
429
- const sizes = new Set();
430
- for (const match of source.matchAll(LITERAL_SIZE)) {
431
- const pixelSize = toPixelSize(Number(match[1]));
432
- if (pixelSize !== null) sizes.add(pixelSize);
433
- }
434
- return {sizes: [...sizes].sort((left, right) => left - right), dynamic: []};
405
+ const sizes = new Set();
406
+ for (const match of source.matchAll(LITERAL_SIZE)) {
407
+ const pixelSize = toPixelSize(Number(match[1]));
408
+ if (pixelSize !== null)
409
+ sizes.add(pixelSize);
410
+ }
411
+ return { sizes: [...sizes].sort((left, right) => left - right), dynamic: [] };
435
412
  }
436
-
437
413
  /**
438
414
  * Finds the pixel sizes an app's text renders at, folding constants so a token-driven scale is
439
415
  * discovered rather than missed.
440
416
  *
441
- * @param {string} source JS/JSX/TSX source: a bundle, a chunk, or a single app entry.
442
- * @returns {{sizes: number[], dynamic: Array<{expr:string, count:number}>}} Ascending de-duplicated
443
- * sizes, plus the `fontSize` expressions that could not be resolved at build time.
417
+ * @param source JS/JSX/TSX source: a bundle, a chunk, or a single app entry.
418
+ * @returns The sizes, plus the `fontSize` expressions that could not be resolved at build time.
444
419
  */
445
420
  export function analyzeFontSizes(source) {
446
- if (!source) return {sizes: [], dynamic: []};
447
- let ast;
448
- try {
449
- ast = parse(source, PARSER_OPTIONS);
450
- } catch {
451
- return scanLiterals(source); // never worse than the literal scan this replaced
452
- }
453
-
454
- const scope = buildScope(ast);
455
- const sizes = new Set();
456
- const dynamic = new Map(); // expression text → occurrences
457
- walk(ast.program, node => {
458
- if (node.type !== 'ObjectProperty' || keyName(node) !== 'fontSize') return;
459
- // A value that resolves but can't be baked (0, negative, past the engine's uint8 pixel_size) is
460
- // an authoring slip, not a discovery failure: leave it out of the bake and out of the report.
461
- const resolved = numbers(evaluate(node.value, scope));
462
- if (resolved.length) {
463
- for (const value of resolved) {
464
- const pixelSize = toPixelSize(value);
465
- if (pixelSize !== null) sizes.add(pixelSize);
466
- }
467
- return;
421
+ if (!source)
422
+ return { sizes: [], dynamic: [] };
423
+ let ast;
424
+ try {
425
+ ast = parse(source, PARSER_OPTIONS);
426
+ }
427
+ catch {
428
+ return scanLiterals(source); // never worse than the literal scan this replaced
468
429
  }
469
- const expression = snippet(source, node.value);
470
- dynamic.set(expression, (dynamic.get(expression) ?? 0) + 1);
471
- });
472
-
473
- return {
474
- sizes: [...sizes].sort((left, right) => left - right),
475
- dynamic: [...dynamic]
476
- .map(([expression, count]) => ({expr: expression, count}))
477
- .sort(
478
- (left, right) =>
479
- right.count - left.count || left.expr.localeCompare(right.expr),
480
- ),
481
- };
430
+ const scope = buildScope(ast);
431
+ const sizes = new Set();
432
+ const dynamic = new Map(); // expression text → occurrences
433
+ walk(ast.program, node => {
434
+ if (node.type !== 'ObjectProperty' || keyName(node) !== 'fontSize')
435
+ return;
436
+ // A value that resolves but can't be baked (0, negative, past the engine's uint8 pixel_size) is
437
+ // an authoring slip, not a discovery failure: leave it out of the bake and out of the report.
438
+ const resolved = numbers(evaluate(node.value, scope));
439
+ if (resolved.length) {
440
+ for (const value of resolved) {
441
+ const pixelSize = toPixelSize(value);
442
+ if (pixelSize !== null)
443
+ sizes.add(pixelSize);
444
+ }
445
+ return;
446
+ }
447
+ const expression = snippet(source, node.value);
448
+ dynamic.set(expression, (dynamic.get(expression) ?? 0) + 1);
449
+ });
450
+ return {
451
+ sizes: [...sizes].sort((left, right) => left - right),
452
+ dynamic: [...dynamic]
453
+ .map(([expression, count]) => ({ expr: expression, count }))
454
+ .sort((left, right) => right.count - left.count || left.expr.localeCompare(right.expr)),
455
+ };
482
456
  }
483
-
484
457
  /**
485
458
  * Compact signature of the sizes a source uses. Watch loops fold this into their "did the asset
486
459
  * inputs change?" key so a `fontSize` edit re-runs the check below.
@@ -490,47 +463,41 @@ export function analyzeFontSizes(source) {
490
463
  * re-bake never happens. Sizes that resolve and sizes that don't both count — swapping a constant
491
464
  * for a runtime value changes what is reported without changing what is baked.
492
465
  *
493
- * @param {{sizes:number[], dynamic:Array<{expr:string}>}} used analyzeFontSizes() result.
494
- * @returns {string} Sizes and unresolved expressions, joined.
466
+ * @param used analyzeFontSizes() result.
467
+ * @returns Sizes and unresolved expressions, joined.
495
468
  */
496
469
  export function fontSizeSignature(used) {
497
- const {sizes = [], dynamic = []} = used ?? {};
498
- return `${sizes.join(',')}|${dynamic.map(entry => entry.expr).join('\u0000')}`;
470
+ const { sizes = [], dynamic = [] } = used ?? {};
471
+ return `${sizes.join(',')}|${dynamic.map(entry => entry.expr).join('\u0000')}`;
499
472
  }
500
-
501
473
  /*--- Coverage check -----------------------------------------------------------------------------*/
502
-
503
474
  /** Pixel sizes a bakeFont() result — or the job that produced it — covers. */
504
475
  function bakedSizes(font) {
505
- return (font.sizes ?? [])
506
- .map(size => (typeof size === 'number' ? size : size?.pixelSize))
507
- .filter(pixelSize => Number.isFinite(pixelSize));
476
+ return (font.sizes ?? [])
477
+ .map(size => (typeof size === 'number' ? size : size?.pixelSize))
478
+ .filter((pixelSize) => Number.isFinite(pixelSize));
508
479
  }
509
-
510
480
  /**
511
481
  * The size the engine substitutes for an unbaked one: nearest wins, a tie goes to the larger.
512
482
  * Mirrors pick_closest() in engine/font/font_registry.c, including the clamp the text renderer
513
483
  * applies to the requested size first.
514
484
  *
515
- * @param {number[]} baked Sizes the family is baked at (non-empty).
516
- * @param {number} wanted The size the app asked for.
517
- * @returns {number} The size that actually renders.
485
+ * @param baked Sizes the family is baked at (non-empty).
486
+ * @param wanted The size the app asked for.
487
+ * @returns The size that actually renders.
518
488
  */
519
489
  export function pickBakedSize(baked, wanted) {
520
- const target = Math.min(Math.max(wanted, RENDER_MIN_PX), RENDER_MAX_PX);
521
- let best = baked[0];
522
- for (const size of baked.slice(1)) {
523
- const difference = Math.abs(target - size);
524
- const bestDifference = Math.abs(target - best);
525
- if (
526
- difference < bestDifference ||
527
- (difference === bestDifference && size > best)
528
- )
529
- best = size;
530
- }
531
- return best;
490
+ const target = Math.min(Math.max(wanted, RENDER_MIN_PX), RENDER_MAX_PX);
491
+ let best = baked[0];
492
+ for (const size of baked.slice(1)) {
493
+ const difference = Math.abs(target - size);
494
+ const bestDifference = Math.abs(target - best);
495
+ if (difference < bestDifference ||
496
+ (difference === bestDifference && size > best))
497
+ best = size;
498
+ }
499
+ return best;
532
500
  }
533
-
534
501
  /**
535
502
  * Finds the used sizes no font in the bake covers.
536
503
  *
@@ -538,155 +505,113 @@ export function pickBakedSize(baked, wanted) {
538
505
  * each imported font when there are any (they all render the app's text, and a family missing a size
539
506
  * is the bug worth reporting), the engine's built-in font when there are none.
540
507
  *
541
- * @param {object} opts
542
- * @param {number[]} [opts.sizes] Sizes the app uses (from analyzeFontSizes).
543
- * @param {Array<object>} [opts.fonts] bakeFont() results or jobs; empty means built-in font only.
544
- * @returns {{gaps: Array<{size:number, family:string, snapsTo:number, baked:number[]}>,
545
- * dropped: Array<{family:string, registered:number[], ignored:number[]}>}} `gaps` are sizes
546
- * that will snap; `dropped` splits a family baked past the engine's per-family limit into
547
- * the sizes that register and the ones that never do.
508
+ * @returns `gaps` are sizes that will snap; `dropped` are the families baked past the engine's limit.
548
509
  */
549
- export function findSizeGaps({sizes = [], fonts = []}) {
550
- const checked = fonts.length
551
- ? fonts.map(font => ({family: font.family, baked: bakedSizes(font)}))
552
- : [{family: BUILTIN_FAMILY, baked: [...BUILTIN_SIZES]}];
553
-
554
- const gaps = [];
555
- const dropped = [];
556
- for (const {family, baked} of checked) {
557
- if (!baked.length) continue;
558
- // Registration stops at the limit, so anything past it is not merely unbaked but unreachable.
559
- const live = baked.slice(0, MAX_BAKED_SIZES);
560
- if (baked.length > live.length)
561
- dropped.push({
562
- family,
563
- registered: live,
564
- ignored: baked.slice(MAX_BAKED_SIZES),
565
- });
566
- for (const size of sizes)
567
- if (!live.includes(size))
568
- gaps.push({
569
- size,
570
- family,
571
- snapsTo: pickBakedSize(live, size),
572
- baked: live,
573
- });
574
- }
575
- return {gaps: gaps.sort((left, right) => left.size - right.size), dropped};
510
+ export function findSizeGaps({ sizes = [], fonts = [], }) {
511
+ const checked = fonts.length
512
+ ? fonts.map(font => ({ family: font.family, baked: bakedSizes(font) }))
513
+ : [{ family: BUILTIN_FAMILY, baked: [...BUILTIN_SIZES] }];
514
+ const gaps = [];
515
+ const dropped = [];
516
+ for (const { family, baked } of checked) {
517
+ if (!baked.length)
518
+ continue;
519
+ // Registration stops at the limit, so anything past it is not merely unbaked but unreachable.
520
+ const live = baked.slice(0, MAX_BAKED_SIZES);
521
+ if (baked.length > live.length)
522
+ dropped.push({
523
+ family,
524
+ registered: live,
525
+ ignored: baked.slice(MAX_BAKED_SIZES),
526
+ });
527
+ for (const size of sizes)
528
+ if (!live.includes(size))
529
+ gaps.push({
530
+ size,
531
+ family,
532
+ snapsTo: pickBakedSize(live, size),
533
+ baked: live,
534
+ });
535
+ }
536
+ return { gaps: gaps.sort((left, right) => left.size - right.size), dropped };
576
537
  }
577
-
578
538
  const MAX_LISTED = 8;
579
-
580
539
  /** `[a, b, c]` as an assets.config.js `sizes` line would spell it. */
581
- const sizeList = sizes =>
582
- `[${[...sizes].sort((left, right) => left - right).join(', ')}]`;
583
-
540
+ const sizeList = (sizes) => `[${[...sizes].sort((left, right) => left - right).join(', ')}]`;
584
541
  /** A family name as a valid object key (a family is a file basename — `Inter-Regular` needs quotes). */
585
- const configKey = family =>
586
- /^[A-Za-z_$][\w$]*$/.test(family) ? family : JSON.stringify(family);
587
-
542
+ const configKey = (family) => /^[A-Za-z_$][\w$]*$/.test(family) ? family : JSON.stringify(family);
588
543
  /**
589
544
  * Renders the size check as a developer-facing warning, ending with the change that fixes it.
590
545
  *
591
- * @param {object} opts
592
- * @param {Array<object>} [opts.gaps] From findSizeGaps().
593
- * @param {Array<object>} [opts.dropped] From findSizeGaps().
594
- * @param {Array<object>} [opts.dynamic] From analyzeFontSizes().
595
- * @param {Array<object>} [opts.fonts] The same fonts, for the suggested config line.
596
- * @returns {string} The warning text (empty when there is nothing to report).
546
+ * @returns The warning text (empty when there is nothing to report).
597
547
  */
598
- export function formatFontSizeReport({
599
- gaps = [],
600
- dropped = [],
601
- dynamic = [],
602
- fonts = [],
603
- }) {
604
- const blocks = [];
605
-
606
- if (gaps.length) {
607
- const lines = gaps
608
- .slice(0, MAX_LISTED)
609
- .map(
610
- gap =>
611
- ` ${gap.size}px → renders at ${gap.snapsTo}px in ${gap.family} (baked: ${gap.baked.join(', ')})`,
612
- );
613
- if (gaps.length > MAX_LISTED)
614
- lines.push(` … and ${gaps.length - MAX_LISTED} more`);
615
- blocks.push(
616
- `embedded-react: ${gaps.length} font size(s) the app uses are not baked and will render at the ` +
617
- `nearest baked size:\n${lines.join('\n')}\n${gapFix(gaps, fonts)}`,
618
- );
619
- }
620
-
621
- if (dynamic.length) {
622
- const total = dynamic.reduce((sum, entry) => sum + entry.count, 0);
623
- const lines = dynamic.slice(0, MAX_LISTED).map(entry => {
624
- const times = entry.count > 1 ? ` (×${entry.count})` : '';
625
- return ` fontSize: ${entry.expr}${times}`;
626
- });
627
- if (dynamic.length > MAX_LISTED)
628
- lines.push(` … and ${dynamic.length - MAX_LISTED} more`);
629
- blocks.push(
630
- `embedded-react: ${total} fontSize value(s) could not be read at build time, so no size was ` +
631
- `baked for them (each snaps to the nearest baked size at runtime):\n${lines.join('\n')}\n` +
632
- ` fix: name the size where it is used, from a module-level constant the bake can fold ` +
633
- `(const TYPE = {body: 14};\n fontSize: TYPE.body) — one arriving through a prop or ` +
634
- `state can't be traced. Or pin the sizes:\n assets.config.js → ` +
635
- `fonts: {${fonts.length ? configKey(fonts[0].family) : '<Family>'}: {sizes: [...]}}`,
636
- );
637
- }
638
-
639
- for (const droppedFamily of dropped) {
640
- blocks.push(
641
- `embedded-react: ${droppedFamily.family} is baked at more than ${MAX_BAKED_SIZES} sizes — the engine ` +
642
- `registers the first ${MAX_BAKED_SIZES} and ignores ${sizeList(droppedFamily.ignored)}, so text at ` +
643
- `those sizes snaps to one that did register.\n fix: choose the ${MAX_BAKED_SIZES} that ` +
644
- `matter — assets.config.js → fonts: {${configKey(droppedFamily.family)}: {sizes: ${sizeList(droppedFamily.registered)}}}`,
645
- );
646
- }
647
-
648
- return blocks.join('\n');
548
+ export function formatFontSizeReport({ gaps = [], dropped = [], dynamic = [], fonts = [], }) {
549
+ const blocks = [];
550
+ if (gaps.length) {
551
+ const lines = gaps
552
+ .slice(0, MAX_LISTED)
553
+ .map(gap => ` ${gap.size}px → renders at ${gap.snapsTo}px in ${gap.family} (baked: ${gap.baked.join(', ')})`);
554
+ if (gaps.length > MAX_LISTED)
555
+ lines.push(` … and ${gaps.length - MAX_LISTED} more`);
556
+ blocks.push(`embedded-react: ${gaps.length} font size(s) the app uses are not baked and will render at the ` +
557
+ `nearest baked size:\n${lines.join('\n')}\n${gapFix(gaps, fonts)}`);
558
+ }
559
+ if (dynamic.length) {
560
+ const total = dynamic.reduce((sum, entry) => sum + entry.count, 0);
561
+ const lines = dynamic.slice(0, MAX_LISTED).map(entry => {
562
+ const times = entry.count > 1 ? ` (×${entry.count})` : '';
563
+ return ` fontSize: ${entry.expr}${times}`;
564
+ });
565
+ if (dynamic.length > MAX_LISTED)
566
+ lines.push(` … and ${dynamic.length - MAX_LISTED} more`);
567
+ blocks.push(`embedded-react: ${total} fontSize value(s) could not be read at build time, so no size was ` +
568
+ `baked for them (each snaps to the nearest baked size at runtime):\n${lines.join('\n')}\n` +
569
+ ` fix: name the size where it is used, from a module-level constant the bake can fold ` +
570
+ `(const TYPE = {body: 14};\n fontSize: TYPE.body) — one arriving through a prop or ` +
571
+ `state can't be traced. Or pin the sizes:\n assets.config.js → ` +
572
+ `fonts: {${fonts.length ? configKey(fonts[0].family) : '<Family>'}: {sizes: [...]}}`);
573
+ }
574
+ for (const droppedFamily of dropped) {
575
+ blocks.push(`embedded-react: ${droppedFamily.family} is baked at more than ${MAX_BAKED_SIZES} sizes — the engine ` +
576
+ `registers the first ${MAX_BAKED_SIZES} and ignores ${sizeList(droppedFamily.ignored)}, so text at ` +
577
+ `those sizes snaps to one that did register.\n fix: choose the ${MAX_BAKED_SIZES} that ` +
578
+ `matter — assets.config.js → fonts: {${configKey(droppedFamily.family)}: {sizes: ${sizeList(droppedFamily.registered)}}}`);
579
+ }
580
+ return blocks.join('\n');
649
581
  }
650
-
651
582
  /** The config (or design) change that closes a set of gaps. */
652
583
  function gapFix(gaps, fonts) {
653
- if (!fonts.length) {
654
- return (
655
- ` fix: the built-in font is baked at ${sizeList(BUILTIN_SIZES)} — use one of those sizes, or ` +
656
- `import a .ttf/.otf\n and bake your own (assets.config.js → fonts: ` +
657
- `{<Family>: {sizes: ${sizeList(new Set(gaps.map(gap => gap.size)))}}})`
658
- );
659
- }
660
- const perFamily = fonts
661
- .map(font => {
662
- const missing = gaps
663
- .filter(gap => gap.family === font.family)
664
- .map(gap => gap.size);
665
- if (!missing.length) return null;
666
- const wanted = new Set([...bakedSizes(font), ...missing]);
667
- return `${configKey(font.family)}: {sizes: ${sizeList(wanted)}}`;
584
+ if (!fonts.length) {
585
+ return (` fix: the built-in font is baked at ${sizeList(BUILTIN_SIZES)} — use one of those sizes, or ` +
586
+ `import a .ttf/.otf\n and bake your own (assets.config.js → fonts: ` +
587
+ `{<Family>: {sizes: ${sizeList(new Set(gaps.map(gap => gap.size)))}}})`);
588
+ }
589
+ const perFamily = fonts
590
+ .map(font => {
591
+ const missing = gaps
592
+ .filter(gap => gap.family === font.family)
593
+ .map(gap => gap.size);
594
+ if (!missing.length)
595
+ return null;
596
+ const wanted = new Set([...bakedSizes(font), ...missing]);
597
+ return `${configKey(font.family)}: {sizes: ${sizeList(wanted)}}`;
668
598
  })
669
- .filter(Boolean);
670
- return ` fix: assets.config.js → fonts: {${perFamily.join(', ')}}`;
599
+ .filter(Boolean);
600
+ return ` fix: assets.config.js → fonts: {${perFamily.join(', ')}}`;
671
601
  }
672
-
673
602
  let lastWarning = null; // dev loops re-bake on every save — don't reprint an unchanged warning
674
-
675
603
  /**
676
604
  * Checks size coverage and warns. Repeats are suppressed while the warning is unchanged, so a
677
605
  * watch/hot-reload loop reports each gap once rather than on every save.
678
606
  *
679
- * @param {object} opts
680
- * @param {{sizes:number[], dynamic:Array<object>}} opts.used analyzeFontSizes() result.
681
- * @param {Array<object>} [opts.fonts] bakeFont() results or jobs; empty means built-in font only.
682
- * @param {Function} [opts.log] Sink for the warning (default console.warn).
683
- * @returns {{gaps:Array<object>, dropped:Array<object>}} What was found (both empty when clean).
607
+ * @returns What was found (both empty when clean).
684
608
  */
685
- export function warnFontSizes({used, fonts = [], log = console.warn}) {
686
- const {sizes = [], dynamic = []} = used ?? {};
687
- const {gaps, dropped} = findSizeGaps({sizes, fonts});
688
- const text = formatFontSizeReport({gaps, dropped, dynamic, fonts});
689
- if (text && text !== lastWarning) log(text);
690
- lastWarning = text || null;
691
- return {gaps, dropped};
609
+ export function warnFontSizes({ used, fonts = [], log = console.warn, }) {
610
+ const { sizes = [], dynamic = [] } = used ?? {};
611
+ const { gaps, dropped } = findSizeGaps({ sizes, fonts });
612
+ const text = formatFontSizeReport({ gaps, dropped, dynamic, fonts });
613
+ if (text && text !== lastWarning)
614
+ log(text);
615
+ lastWarning = text || null;
616
+ return { gaps, dropped };
692
617
  }