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
@@ -0,0 +1,686 @@
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
+ * Custom hooks: `function useThing(…) {…}` in the app's file. Each call is replaced by a copy of the hook's body,
18
+ * its parameters replaced by the call's arguments and its locals renamed for that call, so every call site gets
19
+ * state of its own, as a child component's instance does. A name the call binds takes the local the hook returns
20
+ * under it, so `const {count, inc} = useCounter(0)` reads the hook's own state as `count`.
21
+ */
22
+ /*----------------------------------------------------------------------------------------------------------------------
23
+ - Imports
24
+ ---------------------------------------------------------------------------------------------------------------------*/
25
+ import { traverse, types } from '@babel/core';
26
+ import { aotError } from './diagnostics.mjs';
27
+ import { isFn } from './collect.mjs';
28
+ /*----------------------------------------------------------------------------------------------------------------------
29
+ - Implementation
30
+ ---------------------------------------------------------------------------------------------------------------------*/
31
+ /**
32
+ * Whether a name is a hook's, as React names them: `use` and then a capital or a digit.
33
+ *
34
+ * @param name The name.
35
+ *
36
+ * @returns Whether it is.
37
+ */
38
+ const isHookName = (name) => /^use[A-Z0-9]/.test(name);
39
+ /**
40
+ * An error located at a node.
41
+ *
42
+ * @param message The message.
43
+ * @param hint How to fix it.
44
+ * @param node Where it is.
45
+ *
46
+ * @returns The error.
47
+ */
48
+ function refusal(message, hint, node) {
49
+ const error = aotError(message, hint);
50
+ if (node?.loc) {
51
+ error.aotLoc = node.loc.start;
52
+ }
53
+ return error;
54
+ }
55
+ /**
56
+ * The module's custom hooks, by name: function declarations and functions held by a `const`, exported or not.
57
+ *
58
+ * @param program The module.
59
+ *
60
+ * @returns The hooks.
61
+ */
62
+ function hooksOf(program) {
63
+ const hooks = new Map();
64
+ for (const statement of program.body) {
65
+ const declaration = statement.type === 'ExportNamedDeclaration' ||
66
+ statement.type === 'ExportDefaultDeclaration'
67
+ ? statement.declaration
68
+ : statement;
69
+ if (declaration?.type === 'FunctionDeclaration') {
70
+ if (declaration.id && isHookName(declaration.id.name)) {
71
+ hooks.set(declaration.id.name, {
72
+ functionNode: declaration,
73
+ statement,
74
+ });
75
+ }
76
+ }
77
+ else if (declaration?.type === 'VariableDeclaration') {
78
+ for (const declarator of declaration.declarations) {
79
+ if (declarator.id.type === 'Identifier' &&
80
+ isHookName(declarator.id.name) &&
81
+ isFn(declarator.init)) {
82
+ if (declaration.declarations.length > 1) {
83
+ throw refusal(`AOT: hook "${declarator.id.name}" must be declared on its own`, `give it a declaration of its own: const ${declarator.id.name} = (…) => {…};`, declarator);
84
+ }
85
+ hooks.set(declarator.id.name, {
86
+ functionNode: declarator.init,
87
+ statement,
88
+ });
89
+ }
90
+ }
91
+ }
92
+ }
93
+ // An arrow with an expression body returns it.
94
+ for (const { functionNode } of hooks.values()) {
95
+ if (functionNode.body.type !== 'BlockStatement') {
96
+ functionNode.body = types.blockStatement([
97
+ types.returnStatement(functionNode.body),
98
+ ]);
99
+ }
100
+ }
101
+ return hooks;
102
+ }
103
+ /**
104
+ * The module's components, which may call hooks: functions named with a capital, as React names them. A hook called
105
+ * in any other function is left for the check that refuses it.
106
+ *
107
+ * @param program The module.
108
+ *
109
+ * @returns The components, with their names.
110
+ */
111
+ function componentsOf(program) {
112
+ const isComponentName = (name) => Boolean(name && /^[A-Z]/.test(name));
113
+ const callers = [];
114
+ for (const statement of program.body) {
115
+ const declaration = statement.type === 'ExportNamedDeclaration' ||
116
+ statement.type === 'ExportDefaultDeclaration'
117
+ ? statement.declaration
118
+ : statement;
119
+ if (declaration?.type === 'FunctionDeclaration') {
120
+ const name = declaration.id?.name;
121
+ if (isComponentName(name))
122
+ callers.push([name, declaration]);
123
+ }
124
+ else if (declaration?.type === 'VariableDeclaration') {
125
+ for (const declarator of declaration.declarations) {
126
+ const name = declarator.id.name;
127
+ if (isFn(declarator.init) && isComponentName(name)) {
128
+ callers.push([name, declarator.init]);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return callers;
134
+ }
135
+ /**
136
+ * The path of a function, in a file of its own so its scopes are worked out afresh. Names from outside it have no
137
+ * binding there.
138
+ *
139
+ * @param functionNode The function.
140
+ *
141
+ * @returns Its path.
142
+ */
143
+ function functionPath(functionNode) {
144
+ traverse.cache.clear();
145
+ const file = types.file(types.program([
146
+ functionNode.type === 'FunctionDeclaration'
147
+ ? functionNode
148
+ : types.expressionStatement(functionNode),
149
+ ]));
150
+ let found = null;
151
+ traverse(file, {
152
+ Function(path) {
153
+ if (path.node === functionNode) {
154
+ found = path;
155
+ path.stop();
156
+ }
157
+ },
158
+ });
159
+ return found;
160
+ }
161
+ /**
162
+ * The names a node reads that it doesn't bind.
163
+ *
164
+ * @param path The node's path, in a file of its own.
165
+ *
166
+ * @returns The names.
167
+ */
168
+ function freeNames(path) {
169
+ const names = new Set();
170
+ const add = (reference) => {
171
+ if (!reference.scope.hasBinding(reference.node.name, true)) {
172
+ names.add(reference.node.name);
173
+ }
174
+ };
175
+ if (path.isReferencedIdentifier()) {
176
+ add(path);
177
+ }
178
+ path.traverse({ ReferencedIdentifier: add });
179
+ return names;
180
+ }
181
+ /**
182
+ * The names an expression reads that it doesn't bind.
183
+ *
184
+ * @param expression The expression.
185
+ *
186
+ * @returns The names.
187
+ */
188
+ function freeNamesOfExpression(expression) {
189
+ traverse.cache.clear();
190
+ const file = types.file(types.program([
191
+ types.expressionStatement(types.cloneNode(expression, true)),
192
+ ]));
193
+ let names = new Set();
194
+ traverse(file, {
195
+ Program(path) {
196
+ names = freeNames(path);
197
+ path.stop();
198
+ },
199
+ });
200
+ return names;
201
+ }
202
+ /**
203
+ * Whether a function binds a name anywhere: itself, or a block or function inside it.
204
+ *
205
+ * @param path The function.
206
+ * @param name The name.
207
+ * @param gone Its own bindings that are gone: parameters replaced by arguments.
208
+ *
209
+ * @returns Whether it does.
210
+ */
211
+ function bindsAnywhere(path, name, gone) {
212
+ if (path.scope.hasOwnBinding(name) && !gone.has(name))
213
+ return true;
214
+ let found = false;
215
+ path.traverse({
216
+ Scopable(inner) {
217
+ if (inner.scope !== path.scope && inner.scope.hasOwnBinding(name)) {
218
+ found = true;
219
+ inner.stop();
220
+ }
221
+ },
222
+ });
223
+ return found;
224
+ }
225
+ /**
226
+ * The hook call a statement at the top of a function body makes: `const x = useThing(…)` or `useThing(…);`.
227
+ *
228
+ * @param statement The statement.
229
+ * @param hooks The module's hooks.
230
+ *
231
+ * @returns The call, or null when it makes none.
232
+ */
233
+ function callSiteOf(statement, hooks) {
234
+ const hookOf = (node) => node?.type === 'CallExpression' &&
235
+ node.callee.type === 'Identifier' &&
236
+ hooks.has(node.callee.name)
237
+ ? node.callee.name
238
+ : null;
239
+ if (statement.type === 'ExpressionStatement') {
240
+ const hook = hookOf(statement.expression);
241
+ return hook
242
+ ? {
243
+ hook,
244
+ call: statement.expression,
245
+ target: null,
246
+ kind: 'const',
247
+ }
248
+ : null;
249
+ }
250
+ if (statement.type === 'VariableDeclaration' &&
251
+ statement.declarations.length === 1) {
252
+ const [declarator] = statement.declarations;
253
+ const hook = hookOf(declarator.init);
254
+ return hook
255
+ ? {
256
+ hook,
257
+ call: declarator.init,
258
+ target: declarator.id,
259
+ kind: statement.kind,
260
+ }
261
+ : null;
262
+ }
263
+ return null;
264
+ }
265
+ /**
266
+ * The name a pattern element binds, and its default.
267
+ *
268
+ * @param element The element.
269
+ * @param hook The hook's name, for the error.
270
+ *
271
+ * @returns The name and default.
272
+ */
273
+ function patternName(element, hook) {
274
+ if (element.type === 'Identifier')
275
+ return { name: element.name };
276
+ if (element.type === 'AssignmentPattern' &&
277
+ element.left.type === 'Identifier') {
278
+ return { name: element.left.name, fallback: element.right };
279
+ }
280
+ throw refusal(`AOT: the result of hook "${hook}" can only be destructured one level deep`, `bind each part to a name: const {a, b} = ${hook}(…), then destructure a and b on their own.`, element);
281
+ }
282
+ /**
283
+ * The value an object the hook returns has under a key.
284
+ *
285
+ * @param object The object.
286
+ * @param key The key.
287
+ * @param hook The hook's name, for the error.
288
+ *
289
+ * @returns The value, or null when it has none.
290
+ */
291
+ function valueOfKey(object, key, hook) {
292
+ for (const property of object.properties) {
293
+ if (property.type === 'SpreadElement') {
294
+ throw refusal(`AOT: hook "${hook}" returns an object with a spread`, 'list each value the hook returns: return {a, b}.', property);
295
+ }
296
+ const name = property.computed
297
+ ? property.key.type === 'StringLiteral'
298
+ ? property.key.value
299
+ : null
300
+ : property.key.type === 'Identifier'
301
+ ? property.key.name
302
+ : property.key.type === 'StringLiteral'
303
+ ? property.key.value
304
+ : null;
305
+ if (name !== key)
306
+ continue;
307
+ if (property.type === 'ObjectMethod') {
308
+ return types.functionExpression(null, property.params, property.body, property.generator, property.async);
309
+ }
310
+ return property.value;
311
+ }
312
+ return null;
313
+ }
314
+ /**
315
+ * The key of a pattern's property.
316
+ *
317
+ * @param property The property.
318
+ * @param hook The hook's name, for the error.
319
+ *
320
+ * @returns The key.
321
+ */
322
+ function patternKey(property, hook) {
323
+ if (!property.computed && property.key.type === 'Identifier') {
324
+ return property.key.name;
325
+ }
326
+ if (property.key.type === 'StringLiteral')
327
+ return property.key.value;
328
+ throw refusal(`AOT: the result of hook "${hook}" can only be destructured by name`, `name each key: const {a, b} = ${hook}(…).`, property);
329
+ }
330
+ /**
331
+ * Replaces a read of a parameter with the argument.
332
+ *
333
+ * @param reference The read.
334
+ * @param value The argument.
335
+ */
336
+ function replaceReference(reference, value) {
337
+ const parent = reference.parent;
338
+ if (parent.type === 'ObjectProperty' &&
339
+ parent.shorthand &&
340
+ parent.value === reference.node) {
341
+ parent.shorthand = false;
342
+ }
343
+ reference.replaceWith(value);
344
+ }
345
+ /**
346
+ * Inlines custom hooks into the module's functions. Each call at the top of a component or hook body becomes the
347
+ * hook's statements, renamed for the call, and the names the call binds read what the hook returns. A hook called
348
+ * anywhere else is refused, and the hooks' declarations are dropped.
349
+ *
350
+ * @param ast The parsed module, rewritten in place.
351
+ */
352
+ export function inlineCustomHooks(ast) {
353
+ const program = ast.program;
354
+ const hooks = hooksOf(program);
355
+ if (!hooks.size)
356
+ return;
357
+ // How many times each hook has been inlined, which names its locals at the next call.
358
+ const counts = new Map();
359
+ const expanded = new Set();
360
+ /**
361
+ * Inlines one call: the statements it is replaced by.
362
+ *
363
+ * @param caller The function making the call.
364
+ * @param callerName Its name, for errors.
365
+ * @param site The call.
366
+ *
367
+ * @returns The statements.
368
+ */
369
+ const inlineCall = (caller, callerName, site) => {
370
+ const { hook: name, call, target } = site;
371
+ const count = (counts.get(name) ?? 0) + 1;
372
+ counts.set(name, count);
373
+ const suffix = `@${name}#${count}`;
374
+ const callerPath = functionPath(caller);
375
+ const callerScope = callerPath.scope;
376
+ // A binding of the caller's with the hook's name would be what JS calls.
377
+ if (callerScope.hasOwnBinding(name)) {
378
+ throw refusal(`AOT: "${name}" here is not the hook: a binding of that name hides it`, `rename the binding in ${callerName}, so ${name} names the hook.`, call);
379
+ }
380
+ // A name the hook reads from the module must mean the same where it is inlined.
381
+ const copy = types.cloneNode(hooks.get(name).functionNode, true);
382
+ const hookPath = functionPath(copy);
383
+ for (const freeName of freeNames(hookPath)) {
384
+ if (callerScope.hasOwnBinding(freeName)) {
385
+ throw refusal(`AOT: hook "${name}" reads "${freeName}", which ${callerName} declares too`, `the hook is inlined into ${callerName}, where its own "${freeName}" would hide the one ` +
386
+ `${name} reads. Rename one of them.`, call);
387
+ }
388
+ }
389
+ // The hook returns once, at its end, since its statements run on into the caller's.
390
+ const statements = copy.body.body;
391
+ const last = statements.at(-1);
392
+ hookPath.traverse({
393
+ ReturnStatement(path) {
394
+ if (path.getFunctionParent()?.node === copy && path.node !== last) {
395
+ throw refusal(`AOT: hook "${name}" returns before its end`, 'a custom hook is inlined where it is called, so it can only return as its last ' +
396
+ 'statement. Work the result out in a variable and return that.', path.node);
397
+ }
398
+ },
399
+ });
400
+ const returned = last?.type === 'ReturnStatement' ? (last.argument ?? null) : null;
401
+ const body = last?.type === 'ReturnStatement' ? statements.slice(0, -1) : statements;
402
+ // Every local of the hook gets a name of its own for this call.
403
+ const locals = new Set();
404
+ for (const local of Object.keys(hookPath.scope.bindings)) {
405
+ if (hookPath.scope.bindings[local].kind === 'param')
406
+ continue;
407
+ hookPath.scope.rename(local, local + suffix);
408
+ locals.add(local + suffix);
409
+ }
410
+ // Each read of a parameter reads the argument instead, as the caller has it.
411
+ copy.params.forEach((parameter, index) => {
412
+ const { name: parameterName, fallback } = (() => {
413
+ if (parameter.type === 'Identifier' ||
414
+ (parameter.type === 'AssignmentPattern' &&
415
+ parameter.left.type === 'Identifier')) {
416
+ return patternName(parameter, name);
417
+ }
418
+ throw refusal(`AOT: hook "${name}" can only take named parameters`, `name each one, a default allowed: function ${name}(a, b = 1). Destructure inside the hook.`, parameter);
419
+ })();
420
+ const argument = call.arguments[index];
421
+ if (argument &&
422
+ argument.type !== 'SpreadElement' &&
423
+ !types.isExpression(argument)) {
424
+ throw refusal(`AOT: unsupported argument to hook "${name}"`, 'pass each argument as a value.', argument);
425
+ }
426
+ if (argument?.type === 'SpreadElement') {
427
+ throw refusal(`AOT: a spread argument to hook "${name}" is not supported`, `pass each argument on its own: ${name}(a, b).`, argument);
428
+ }
429
+ const binding = hookPath.scope.getOwnBinding(parameterName);
430
+ if (!binding.constant) {
431
+ throw refusal(`AOT: hook "${name}" sets its parameter "${parameterName}"`, 'the parameter is replaced by the argument, so copy it into a local of its own first: ' +
432
+ `let value = ${parameterName};`, binding.constantViolations[0].node);
433
+ }
434
+ // A local of the hook's must not take the place of a name the argument reads.
435
+ const value = argument ??
436
+ fallback ?? { type: 'Identifier', name: 'undefined' };
437
+ const argumentNames = argument
438
+ ? freeNamesOfExpression(argument)
439
+ : new Set();
440
+ for (const reference of binding.referencePaths) {
441
+ for (const argumentName of argumentNames) {
442
+ const inner = reference.scope.getBinding(argumentName);
443
+ if (inner &&
444
+ !(inner.kind === 'param' && inner.scope === hookPath.scope)) {
445
+ throw refusal(`AOT: an argument to hook "${name}" reads "${argumentName}", which ${name} declares too`, `the argument is read inside ${name}, where its own "${argumentName}" would hide ` +
446
+ "the caller's. Rename one of them.", argument);
447
+ }
448
+ }
449
+ replaceReference(reference, types.cloneNode(value, true));
450
+ }
451
+ });
452
+ const parameterNames = new Set(copy.params.map(parameter => parameter.type === 'AssignmentPattern'
453
+ ? parameter.left.name
454
+ : parameter.name));
455
+ copy.params = [];
456
+ // The names the call binds, and the values of the result each takes.
457
+ const bindings = [];
458
+ let direct = false;
459
+ // `result.key` reads, for a result bound to one name, replaced by the name each key is bound to.
460
+ const memberReads = new Map();
461
+ if (target && !returned) {
462
+ throw refusal(`AOT: hook "${name}" returns nothing`, `call it as a statement: ${name}(…);`, target);
463
+ }
464
+ else if (!target ||
465
+ !returned ||
466
+ returned.type === 'CallExpression' ||
467
+ isFn(returned)) {
468
+ direct = Boolean(target);
469
+ }
470
+ else if (target.type === 'Identifier') {
471
+ if (returned.type === 'ObjectExpression') {
472
+ // Each read must name a key, as `result.key`.
473
+ const binding = callerScope.getOwnBinding(target.name);
474
+ for (const reference of binding.referencePaths) {
475
+ const member = reference.parentPath;
476
+ const isRead = member?.isMemberExpression() &&
477
+ member.node.object === reference.node &&
478
+ (!member.node.computed ||
479
+ member.node.property.type === 'StringLiteral') &&
480
+ !(member.parentPath.isAssignmentExpression() &&
481
+ member.parentPath.node.left === member.node) &&
482
+ !member.parentPath.isUpdateExpression();
483
+ if (!isRead) {
484
+ throw refusal(`AOT: the result of hook "${name}" can only be read by key`, `read it as ${target.name}.key, or destructure it: const {a, b} = ${name}(…).`, reference.node);
485
+ }
486
+ const property = member.node
487
+ .property;
488
+ const key = property.type === 'StringLiteral'
489
+ ? property.value
490
+ : property.name;
491
+ memberReads.set(key, [
492
+ ...(memberReads.get(key) ?? []),
493
+ member,
494
+ ]);
495
+ }
496
+ for (const key of memberReads.keys()) {
497
+ bindings.push({
498
+ name: `${target.name}:${key}`,
499
+ value: valueOfKey(returned, key, name),
500
+ });
501
+ }
502
+ }
503
+ else {
504
+ bindings.push({ name: target.name, value: returned });
505
+ }
506
+ }
507
+ else if (target.type === 'ArrayPattern') {
508
+ if (returned.type !== 'ArrayExpression') {
509
+ direct = true;
510
+ }
511
+ else {
512
+ target.elements.forEach((element, index) => {
513
+ if (!element)
514
+ return;
515
+ if (element.type === 'RestElement') {
516
+ throw refusal(`AOT: a rest element can't take the result of hook "${name}"`, 'name each element: const [a, b] = …', element);
517
+ }
518
+ const value = returned.elements[index] ?? null;
519
+ if (value?.type === 'SpreadElement') {
520
+ throw refusal(`AOT: hook "${name}" returns an array with a spread`, 'list each value the hook returns: return [a, b].', value);
521
+ }
522
+ bindings.push({ ...patternName(element, name), value });
523
+ });
524
+ }
525
+ }
526
+ else if (target.type === 'ObjectPattern') {
527
+ if (returned.type !== 'ObjectExpression') {
528
+ direct = true;
529
+ }
530
+ else {
531
+ for (const property of target.properties) {
532
+ if (property.type === 'RestElement') {
533
+ throw refusal(`AOT: a rest element can't take the result of hook "${name}"`, 'name each key: const {a, b} = …', property);
534
+ }
535
+ bindings.push({
536
+ ...patternName(property.value, name),
537
+ value: valueOfKey(returned, patternKey(property, name), name),
538
+ });
539
+ }
540
+ }
541
+ }
542
+ else {
543
+ direct = true;
544
+ }
545
+ // A name the call binds takes the hook's local it is bound to, when no name in the hook would clash.
546
+ const hookFreeNames = freeNames(hookPath);
547
+ const claimed = new Set();
548
+ const remaining = bindings.filter(binding => {
549
+ const local = binding.value;
550
+ if (local?.type !== 'Identifier' ||
551
+ !locals.has(local.name) ||
552
+ claimed.has(local.name) ||
553
+ hookFreeNames.has(binding.name) ||
554
+ bindsAnywhere(hookPath, binding.name, parameterNames)) {
555
+ return true;
556
+ }
557
+ claimed.add(local.name);
558
+ hookPath.scope.rename(local.name, binding.name);
559
+ return false;
560
+ });
561
+ // The others are declared after the hook's statements, or read as the name they stand for.
562
+ const declarations = [];
563
+ const declare = (pattern, init) => {
564
+ declarations.push({
565
+ type: 'VariableDeclaration',
566
+ kind: site.kind,
567
+ declarations: [{ type: 'VariableDeclarator', id: pattern, init }],
568
+ loc: call.loc,
569
+ });
570
+ };
571
+ const aliases = new Map();
572
+ for (const { name: bound, value, fallback } of remaining) {
573
+ const init = value ?? fallback;
574
+ if (!init) {
575
+ throw refusal(`AOT: hook "${name}" returns no "${bound.split(':').at(-1)}"`, 'read only the values the hook returns, or give the name a default.', target);
576
+ }
577
+ if (init.type === 'Identifier') {
578
+ aliases.set(bound, init.name);
579
+ }
580
+ else if (isFn(init) || init.type === 'CallExpression') {
581
+ declare({ type: 'Identifier', name: bound }, init);
582
+ }
583
+ else {
584
+ // Any other value is worked out where it is read, as a memo is.
585
+ declare({ type: 'Identifier', name: bound }, types.callExpression(types.identifier('useMemo'), [
586
+ types.arrowFunctionExpression([], init),
587
+ types.arrayExpression([]),
588
+ ]));
589
+ }
590
+ }
591
+ if (direct) {
592
+ declare(target, returned);
593
+ }
594
+ else if (!target && returned?.type === 'CallExpression') {
595
+ declarations.push(types.expressionStatement(returned));
596
+ }
597
+ // In the caller, `result.key` reads the name its key is bound to, and an alias reads what it stands for.
598
+ for (const [key, reads] of memberReads) {
599
+ const bound = `${target.name}:${key}`;
600
+ for (const read of reads) {
601
+ read.replaceWith(types.identifier(aliases.get(bound) ?? bound));
602
+ }
603
+ }
604
+ for (const [alias, original] of aliases) {
605
+ if (alias.includes(':'))
606
+ continue;
607
+ const binding = callerScope.getOwnBinding(alias);
608
+ for (const reference of binding.referencePaths) {
609
+ if (reference.scope.getBinding(original) !==
610
+ callerScope.getBinding(original)) {
611
+ throw refusal(`AOT: "${alias}" stands for "${original}", which a function in ${callerName} declares too`, 'rename the inner one.', reference.node);
612
+ }
613
+ }
614
+ callerScope.rename(alias, original);
615
+ }
616
+ return [...body, ...declarations];
617
+ };
618
+ /**
619
+ * Inlines the hook calls at the top of a function's body, the hooks' own calls first.
620
+ *
621
+ * @param functionNode The function.
622
+ * @param functionName Its name, for errors.
623
+ * @param stack The hooks being expanded, so one that calls itself is refused.
624
+ */
625
+ const expandBody = (functionNode, functionName, stack) => {
626
+ if (functionNode.body.type !== 'BlockStatement')
627
+ return;
628
+ const body = functionNode.body.body;
629
+ for (let index = 0; index < body.length; index++) {
630
+ // A declaration of several names is split, so each hook call has a declaration of its own.
631
+ const statement = body[index];
632
+ if (statement.type === 'VariableDeclaration' &&
633
+ statement.declarations.length > 1 &&
634
+ statement.declarations.some(declarator => callSiteOf({ ...statement, declarations: [declarator] }, hooks))) {
635
+ body.splice(index, 1, ...statement.declarations.map(declarator => ({
636
+ ...statement,
637
+ declarations: [declarator],
638
+ })));
639
+ }
640
+ const site = callSiteOf(body[index], hooks);
641
+ if (!site)
642
+ continue;
643
+ expandHook(site.hook, stack, site.call);
644
+ const statements = inlineCall(functionNode, functionName, site);
645
+ body.splice(index, 1, ...statements);
646
+ index += statements.length - 1;
647
+ }
648
+ };
649
+ /**
650
+ * Inlines the hook calls a hook makes, once.
651
+ *
652
+ * @param name The hook.
653
+ * @param stack The hooks being expanded.
654
+ * @param call The call that reached it, for the error.
655
+ */
656
+ const expandHook = (name, stack, call) => {
657
+ if (expanded.has(name))
658
+ return;
659
+ if (stack.includes(name)) {
660
+ throw refusal(`AOT: hook "${name}" calls itself`, "a custom hook is inlined where it is called, so it can't call itself, directly or through " +
661
+ 'another hook.', call);
662
+ }
663
+ expandBody(hooks.get(name).functionNode, name, [...stack, name]);
664
+ expanded.add(name);
665
+ };
666
+ for (const name of hooks.keys()) {
667
+ expandHook(name, []);
668
+ }
669
+ for (const [name, functionNode] of componentsOf(program)) {
670
+ expandBody(functionNode, name, []);
671
+ }
672
+ // Every call has been inlined, so the declarations go; a hook read anywhere else is refused.
673
+ const definitions = new Set([...hooks.values()].map(hook => hook.statement));
674
+ program.body = program.body.filter(statement => !definitions.has(statement));
675
+ traverse.cache.clear();
676
+ traverse(ast, {
677
+ ReferencedIdentifier(path) {
678
+ const hookName = path.node.name;
679
+ if (hooks.has(hookName) && !path.scope.hasBinding(hookName, true)) {
680
+ throw refusal(`AOT: hook "${hookName}" must be called at the top of a component or another hook`, 'as React requires, call it on its own line at the top of the function body: ' +
681
+ `const value = ${hookName}(…). Flow B inlines it there.`, path.node);
682
+ }
683
+ },
684
+ });
685
+ traverse.cache.clear();
686
+ }