what-compiler 0.14.0 → 0.15.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 (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/babel.d.ts +78 -2
  4. package/dist/babel/auto-selector.min.js +94 -0
  5. package/dist/babel/common.min.js +2053 -0
  6. package/dist/babel/dev-metadata.min.js +106 -0
  7. package/dist/babel/dom.min.js +1669 -0
  8. package/dist/babel/jsx-root.min.js +13 -0
  9. package/dist/babel/lists.min.js +492 -0
  10. package/dist/babel/nesting.min.js +328 -0
  11. package/dist/babel/reactivity.min.js +1218 -0
  12. package/dist/babel/server-actions.min.js +85 -0
  13. package/dist/babel/ssr.min.js +496 -0
  14. package/dist/babel/types.min.js +9 -0
  15. package/dist/babel-plugin.min.js +101 -1
  16. package/dist/file-router.min.js +368 -12
  17. package/dist/framework-files.min.js +62 -0
  18. package/dist/hot.min.js +315 -0
  19. package/dist/index.min.js +13 -414
  20. package/dist/release.min.js +78 -0
  21. package/dist/runtime.min.js +9 -1
  22. package/dist/tables/import-changes.min.js +272 -0
  23. package/dist/tables/markup-rules.min.js +213 -0
  24. package/dist/vite-plugin.min.js +432 -399
  25. package/file-router.d.ts +3 -1
  26. package/index.d.ts +1 -1
  27. package/package.json +11 -2
  28. package/runtime.d.ts +2 -1
  29. package/src/babel/auto-selector.js +248 -0
  30. package/src/babel/common.js +3800 -0
  31. package/src/babel/dev-metadata.js +167 -0
  32. package/src/babel/dom.js +3386 -0
  33. package/src/babel/jsx-root.js +27 -0
  34. package/src/babel/lists.js +704 -0
  35. package/src/babel/nesting.js +260 -0
  36. package/src/babel/reactivity.js +1998 -0
  37. package/src/babel/server-actions.js +144 -0
  38. package/src/babel/ssr.js +870 -0
  39. package/src/babel/types.js +10 -0
  40. package/src/babel-plugin.js +185 -3598
  41. package/src/file-router.js +58 -38
  42. package/src/framework-files.js +106 -0
  43. package/src/hot.js +523 -0
  44. package/src/release.js +127 -0
  45. package/src/runtime.js +7 -7
  46. package/src/tables/import-changes.js +157 -0
  47. package/src/tables/markup-rules.js +388 -0
  48. package/src/vite-plugin.js +460 -175
  49. package/vite.d.ts +47 -3
  50. package/src/error-overlay.js +0 -428
@@ -0,0 +1,704 @@
1
+ // List detection shared by both back ends: which `.map()` calls return JSX,
2
+ // whether they carry a usable key, and the scope analysis the key function and
3
+ // the auto-selector both need.
4
+
5
+ import { t } from './types.js';
6
+ import { controlFlowTag, getAttrName, getAttributeValue, helper, uniqueName } from './common.js';
7
+ import { isPotentiallyReactive, isSignalIdentifier } from './reactivity.js';
8
+
9
+ // Names bound by a parameter pattern. Destructuring counts, so
10
+ // `({ id }, i) => <li key={id}>` binds `id` and a key of `id` resolves fine.
11
+ export function collectPatternNames(node, out) {
12
+ if (!node || typeof node !== 'object') return out;
13
+ switch (node.type) {
14
+ case 'Identifier': out.add(node.name); break;
15
+ case 'AssignmentPattern': collectPatternNames(node.left, out); break;
16
+ case 'RestElement': collectPatternNames(node.argument, out); break;
17
+ case 'ArrayPattern':
18
+ for (const el of node.elements) collectPatternNames(el, out);
19
+ break;
20
+ case 'ObjectPattern':
21
+ for (const p of node.properties) {
22
+ collectPatternNames(p.type === 'RestElement' ? p.argument : p.value, out);
23
+ }
24
+ break;
25
+ default: break;
26
+ }
27
+ return out;
28
+ }
29
+
30
+ // The key function is extracted OUT of the map callback and rebuilt as
31
+ // `(item) => keyExpr`, taking only the first parameter. So any name the key
32
+ // expression gets from somewhere else inside the callback becomes a free
33
+ // variable in the emitted code. This collects exactly those names: the
34
+ // parameters after the first, and everything declared in the callback body
35
+ // that is in scope at the return.
36
+ //
37
+ // Nested function bodies are deliberately not descended into. Their bindings
38
+ // cannot reach the return expression, so counting them would reject keys that
39
+ // are perfectly fine. A nested function's own name is hoisted, so that one
40
+ // is collected.
41
+ export function namesInvisibleToKeyFn(mapFn) {
42
+ const out = new Set();
43
+ for (let i = 1; i < mapFn.params.length; i++) collectPatternNames(mapFn.params[i], out);
44
+
45
+ const visit = (node) => {
46
+ if (!node || typeof node !== 'object') return;
47
+ if (Array.isArray(node)) { node.forEach(visit); return; }
48
+ switch (node.type) {
49
+ case 'VariableDeclaration':
50
+ for (const d of node.declarations) collectPatternNames(d.id, out);
51
+ return;
52
+ case 'FunctionDeclaration':
53
+ case 'ClassDeclaration':
54
+ if (node.id) out.add(node.id.name);
55
+ return; // body is its own scope
56
+ case 'FunctionExpression':
57
+ case 'ArrowFunctionExpression':
58
+ case 'ClassExpression':
59
+ return; // own scope
60
+ case 'CatchClause':
61
+ collectPatternNames(node.param, out);
62
+ visit(node.body);
63
+ return;
64
+ case 'ForStatement':
65
+ case 'ForInStatement':
66
+ case 'ForOfStatement':
67
+ visit(node.init); visit(node.left); visit(node.body);
68
+ return;
69
+ default: break;
70
+ }
71
+ for (const k of Object.keys(node)) {
72
+ if (k === 'loc' || k === 'start' || k === 'end' || k === 'type' ||
73
+ k === 'leadingComments' || k === 'trailingComments' || k === 'innerComments') continue;
74
+ const v = node[k];
75
+ if (v && typeof v === 'object') visit(v);
76
+ }
77
+ };
78
+
79
+ if (t.isBlockStatement(mapFn.body)) visit(mapFn.body.body);
80
+
81
+ // The first parameter IS passed to the key function, so anything it binds
82
+ // stays visible even if a nested scope happens to reuse the name.
83
+ for (const name of collectPatternNames(mapFn.params[0], new Set())) out.delete(name);
84
+ return out;
85
+ }
86
+
87
+ // Does `node` reference any of `names` as a value? Property positions are
88
+ // skipped so `item.i` does not look like a use of `i`, but the check is
89
+ // otherwise deliberately generous: a false positive costs keyed
90
+ // reconciliation, a false negative ships a ReferenceError.
91
+ function referencesAny(node, names) {
92
+ if (names.size === 0) return null;
93
+ let found = null;
94
+ const visit = (n) => {
95
+ if (found || !n || typeof n !== 'object') return;
96
+ if (Array.isArray(n)) { n.forEach(visit); return; }
97
+ if (n.type === 'Identifier') {
98
+ if (names.has(n.name)) found = n.name;
99
+ return;
100
+ }
101
+ for (const k of Object.keys(n)) {
102
+ if (k === 'loc' || k === 'start' || k === 'end' || k === 'type' ||
103
+ k === 'leadingComments' || k === 'trailingComments' || k === 'innerComments') continue;
104
+ if (n.type === 'MemberExpression' && k === 'property' && !n.computed) continue;
105
+ if ((n.type === 'ObjectProperty' || n.type === 'ObjectMethod') && k === 'key' && !n.computed) continue;
106
+ const v = n[k];
107
+ if (v && typeof v === 'object') visit(v);
108
+ }
109
+ };
110
+ visit(node);
111
+ return found;
112
+ }
113
+
114
+ // `source.map((item) => <Row key={...} />)`, or `source?.map(...)` (a nullish
115
+ // source is an empty list): the callback, the JSX it returns and its key.
116
+ // Returns null for anything else. With `requireKey` (the DOM back
117
+ // end, which lowers only keyed lists) a missing or unusable key returns null
118
+ // with a development warning; without it (the server back end, which renders
119
+ // every JSX-returning callback the same way) the key is optional and nothing is
120
+ // reported, because the client build of the same file already warned.
121
+ export function findMappedJsx(mapCall, state, requireKey) {
122
+ // Check: something.map(fn) or something?.map(fn)
123
+ if (!t.isCallExpression(mapCall) && !(t.isOptionalCallExpression(mapCall) && !mapCall.optional)) return null;
124
+ const callee = mapCall.callee;
125
+ if (!t.isMemberExpression(callee) && !t.isOptionalMemberExpression(callee)) return null;
126
+ if (callee.computed || !t.isIdentifier(callee.property, { name: 'map' })) return null;
127
+ if (mapCall.arguments.length < 1) return null;
128
+
129
+ const mapFn = mapCall.arguments[0];
130
+ if (!t.isArrowFunctionExpression(mapFn) && !t.isFunctionExpression(mapFn)) return null;
131
+ nameRowParam(mapFn, state);
132
+
133
+ // Get the map callback's return expression
134
+ /** @type {any} */
135
+ let returnExpr = null;
136
+ if (t.isArrowFunctionExpression(mapFn)) {
137
+ if (t.isExpression(mapFn.body)) {
138
+ returnExpr = mapFn.body;
139
+ } else if (t.isBlockStatement(mapFn.body)) {
140
+ const ret = mapFn.body.body.find(s => t.isReturnStatement(s));
141
+ if (ret) returnExpr = ret.argument;
142
+ }
143
+ } else if (t.isFunctionExpression(mapFn)) {
144
+ const ret = mapFn.body.body.find(s => t.isReturnStatement(s));
145
+ if (ret) returnExpr = ret.argument;
146
+ }
147
+
148
+ if (!returnExpr) return null;
149
+
150
+ // Check if the return is JSX with a `key` prop
151
+ if (!t.isJSXElement(returnExpr)) return null;
152
+ const attrs = returnExpr.openingElement.attributes;
153
+ /** @type {any} */
154
+ let keyAttr = null;
155
+ for (const attr of attrs) {
156
+ if (t.isJSXAttribute(attr) && getAttrName(attr) === 'key') {
157
+ keyAttr = attr;
158
+ break;
159
+ }
160
+ }
161
+ if (!requireKey) return { mapFn, returnExpr, keyAttr, keyValue: keyAttr ? getAttributeValue(keyAttr.value) : null };
162
+ if (!keyAttr) {
163
+ // JSX returned without a key — bail out, but warn at compile time so
164
+ // users notice they're missing keyed reconciliation. Only warn in dev
165
+ // (production builds are noiseless).
166
+ //
167
+ // The message names ERR_MISSING_KEY because that is the code the docs and
168
+ // the MCP `what_fix` tool already publish for this exact mistake. Without
169
+ // the code in the text there was nothing anywhere in the toolchain that
170
+ // ever emitted it, so an agent reading the warning had no way to reach
171
+ // the diagnosis and the worked example filed under that name. This is a
172
+ // BUILD-time report, not a runtime one: whether a list has keys is
173
+ // settled by the source, and the compiler is the only place that sees it.
174
+ if (process.env.NODE_ENV !== 'production') {
175
+ const loc = returnExpr.loc;
176
+ const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
177
+ const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
178
+ console.warn(
179
+ `[what-compiler] ERR_MISSING_KEY: .map() returning JSX without a \`key\` prop at ${fileName}${lineInfo}. ` +
180
+ `Without a key, the list cannot use keyed reconciliation — items are re-created on every update. ` +
181
+ `Add key={...} to enable efficient updates. ` +
182
+ `Run what_fix({ error: 'ERR_MISSING_KEY' }) for the worked example.`
183
+ );
184
+ }
185
+ return null;
186
+ }
187
+
188
+ // Extract the key expression
189
+ const keyValue = getAttributeValue(keyAttr.value);
190
+ if (!keyValue) return null;
191
+
192
+ // The key function is rebuilt as `(item, index) => keyExpr` and hoisted out
193
+ // of the callback, so it sees the first two parameters only. A key built
194
+ // from a variable declared in the callback body compiled to a key function
195
+ // with that name free: the list rendered correctly the first time, then the
196
+ // reconciler threw `ReferenceError` inside its effect, which was swallowed
197
+ // to a single console.error, and the list stayed frozen on its first render.
198
+ // Such a key falls back to the unkeyed path, with a warning.
199
+ //
200
+ // A key that reads the index (`key={i}`, `key={`${t.term}-${i}`}`) is keyed
201
+ // by item and position, as React keys it: the key function is handed the
202
+ // index (keyIndex), so a row stays while its key does (an item replaced at
203
+ // its position, a refetch) and an item that moves is a new row.
204
+ const invisible = keyInvisibleNames(mapFn);
205
+ const unreachable = referencesAny(keyValue, invisible);
206
+ if (unreachable) {
207
+ if (process.env.NODE_ENV !== 'production') {
208
+ const loc = returnExpr.loc;
209
+ const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
210
+ const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
211
+ console.warn(
212
+ `[what-compiler] key={...} at ${fileName}${lineInfo} reads \`${unreachable}\`, which is not available ` +
213
+ `to the key function (it receives the item and its index). \`${unreachable}\` is declared inside the map callback. ` +
214
+ `Falling back to an unkeyed list, built again on every update. Key by something on the item (key={item.id}) ` +
215
+ `or its index to get keyed reconciliation.`
216
+ );
217
+ }
218
+ return null;
219
+ }
220
+ return { mapFn, returnExpr, keyAttr, keyValue };
221
+ }
222
+
223
+ // A keyed `.map()` row reads its item through the runtime's item cell, so that
224
+ // a row whose key persists while its item is replaced by another object (an
225
+ // immutable update, a refetch) shows the new item and keeps its DOM: the
226
+ // callback `(item, i) => …` becomes `(cell, i, item) => …`, every read of
227
+ // `item` but the key expression becomes `read(cell)` (`read` is the runtime's
228
+ // _$item), which the row's bindings track, and the key expression keeps
229
+ // reading the item the row was built from, as a row's key cannot change while
230
+ // it lives. Returns false and changes nothing when the row reads the item only
231
+ // for its key (the row then gets the raw item), when the first parameter is
232
+ // not a plain name, or when that name is assigned or bound again inside the
233
+ // callback (rowItemUnread: the DOM target then builds the row again for a
234
+ // replaced item).
235
+ export function readItemThroughAccessor(mapFn, keyValue, read, cellName, indexName) {
236
+ const reads = rowItemReads(mapFn, keyValue);
237
+ if (reads === null || reads.length === 0) return false;
238
+ const itemName = mapFn.params[0].name;
239
+ for (const [holder, slot, field] of reads) {
240
+ const callee = read();
241
+ callee._whatRowItem = true;
242
+ // `row.name` reads the field `name`: a read while the row is built records
243
+ // that field, not the whole item (what-core _readRowItem), so a replaced
244
+ // item whose `name` is the same keeps the row.
245
+ const args = field !== undefined ? [t.identifier(cellName), t.stringLiteral(field)] : [t.identifier(cellName)];
246
+ const call = t.callExpression(callee, args);
247
+ // The item the row was built from, for the bindings of its plain fields.
248
+ call._whatRowItemName = itemName;
249
+ holder[slot] = call;
250
+ }
251
+ mapFn.params = [t.identifier(cellName), mapFn.params[1] || t.identifier(indexName), mapFn.params[0]];
252
+ return true;
253
+ }
254
+
255
+ // A plain field of a keyed row's item, read where the row renders text:
256
+ // `row.label`, `row.a.b`, `row?.label`, `row['x']` or the item itself, and
257
+ // nothing else (no call, no computed key that is not a literal). Returns the
258
+ // read of the item at its root (the DOM target's `_$item(cell)` call, the
259
+ // server target's marked name; see readItemThroughAccessor and
260
+ // markRowItemReads), or null. Such a field is a text binding the row's item
261
+ // cell writes (what-core render.js _$field), and the server writes it as plain
262
+ // text, with no markers.
263
+ export function rowField(expr) {
264
+ let node = expr;
265
+ while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
266
+ if (node.computed && !t.isStringLiteral(node.property) && !t.isNumericLiteral(node.property)) return null;
267
+ node = node.object;
268
+ }
269
+ if (t.isCallExpression(node) && node.callee._whatRowItem === true) return node;
270
+ if (t.isIdentifier(node) && node._whatRowItem === true) return node;
271
+ return null;
272
+ }
273
+
274
+ // `expr` with its item read (`root`, from rowField) replaced by `replacement`.
275
+ export function withItem(expr, root, replacement) {
276
+ if (expr === root) return replacement;
277
+ const copy = t.cloneNode(expr, false);
278
+ copy.object = withItem(expr.object, root, replacement);
279
+ return copy;
280
+ }
281
+
282
+ // The server target's half: the holes that read a keyed row's item are the
283
+ // reactive children the DOM target makes them, so the server brackets them
284
+ // with the markers the client's bindings claim. Marks each read (_whatRowItem).
285
+ export function markRowItemReads(mapFn, keyValue) {
286
+ const reads = rowItemReads(mapFn, keyValue);
287
+ if (reads !== null) for (const [holder, slot] of reads) holder[slot]._whatRowItem = true;
288
+ }
289
+
290
+ // Whether a keyed row reads its item in a way the reads cannot be found in
291
+ // (rowItemReads gives up): a parameter still destructured, or a name the
292
+ // callback binds again, assigns or uses as a JSX tag. Such a row cannot read
293
+ // its item through the cell, and a raw item would leave it showing the item it
294
+ // was built from after the item is replaced under its key.
295
+ export function rowItemUnread(mapFn, keyValue) {
296
+ return mapFn.params.length > 0 && rowItemReads(mapFn, keyValue) === null;
297
+ }
298
+
299
+ // --- A destructured row ---
300
+ // `items().map(({ id, label }) => <li key={id}>{label}</li>)` destructured its
301
+ // item where the row was built, so a row kept under its key (an item replaced
302
+ // by another object, an immutable update) showed the first item's fields
303
+ // forever; React renders the new item. The pattern becomes a parameter that
304
+ // is read where each name is used (`label` is `item.label`, a default
305
+ // `item.label === undefined ? 'x' : item.label`, a rest element a copy of the
306
+ // item without the names, what-core render.js _$omit), so the row reads its
307
+ // item like any other row does (readItemThroughAccessor). Both back ends make
308
+ // the change before they lower the row, so the server's markers are the
309
+ // client's. A pattern this cannot read the same way (an array pattern, a
310
+ // computed key, a default that is not a literal, a nested rest) or whose names
311
+ // the callback binds again or assigns keeps its destructuring.
312
+ function nameRowParam(mapFn, state) {
313
+ const pattern = mapFn.params[0];
314
+ if (!t.isObjectPattern(pattern)) return;
315
+ /** @type {Map<string, (item: any) => any>} */
316
+ const reads = new Map();
317
+ const excluded = [];
318
+ /** @type {any} */
319
+ let rest = null;
320
+ const leaf = (value, path) => {
321
+ /** @type {any} */
322
+ let fallback = null;
323
+ if (t.isAssignmentPattern(value)) {
324
+ fallback = value.right;
325
+ value = value.left;
326
+ if (!(t.isStringLiteral(fallback) || t.isNumericLiteral(fallback) || t.isBooleanLiteral(fallback) || t.isNullLiteral(fallback)
327
+ || (t.isTemplateLiteral(fallback) && fallback.expressions.length === 0))) return false;
328
+ }
329
+ if (t.isObjectPattern(value)) return fallback === null && fields(value, path, false);
330
+ if (!t.isIdentifier(value) || reads.has(value.name)) return false;
331
+ const at = (item) => path.reduce((obj, key) => t.memberExpression(obj, t.isValidIdentifier(key) ? t.identifier(key) : t.stringLiteral(key), !t.isValidIdentifier(key)), item);
332
+ reads.set(value.name, fallback === null ? at
333
+ : (item) => t.conditionalExpression(t.binaryExpression('===', at(item), t.unaryExpression('void', t.numericLiteral(0))), t.cloneNode(fallback), at(item)));
334
+ return true;
335
+ };
336
+ const fields = (node, path, top) => {
337
+ for (const prop of node.properties) {
338
+ if (t.isRestElement(prop)) {
339
+ if (!top || !t.isIdentifier(prop.argument)) return false;
340
+ rest = prop.argument;
341
+ continue;
342
+ }
343
+ const key = t.isIdentifier(prop.key) && !prop.computed ? prop.key.name : t.isStringLiteral(prop.key) ? prop.key.value : null;
344
+ if (key === null) return false;
345
+ if (top) excluded.push(key);
346
+ if (!leaf(prop.value, [...path, key])) return false;
347
+ }
348
+ return true;
349
+ };
350
+ if (!fields(pattern, [], true)) return;
351
+ const names = new Set(reads.keys());
352
+ if (rest !== null) names.add(rest.name);
353
+ const refs = namedReads(mapFn, names);
354
+ if (refs === null) return;
355
+ const item = uniqueName(state, '_row$');
356
+ for (const [holder, slot, name] of refs) {
357
+ const read = reads.get(name);
358
+ if (read !== undefined) holder[slot] = read(t.identifier(item));
359
+ }
360
+ mapFn.params[0] = t.identifier(item);
361
+ // The rest element, once, where the row is built: a copy of its item
362
+ // without the names (the row is built again for another item).
363
+ if (rest !== null) {
364
+ const omit = state.ssr ? state.file.addHelper('objectWithoutProperties') : helper(state, '_$omit');
365
+ const decl = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(rest.name),
366
+ t.callExpression(omit, [t.identifier(item), t.arrayExpression(excluded.map((k) => t.stringLiteral(k)))]))]);
367
+ if (!t.isBlockStatement(mapFn.body)) mapFn.body = t.blockStatement([t.returnStatement(mapFn.body)]);
368
+ mapFn.body.body.unshift(decl);
369
+ }
370
+ }
371
+
372
+ // The reads of `names` in a row callback, as [holder, slot, name], or null
373
+ // when the callback binds one of them again, assigns one, or uses one as a
374
+ // JSX tag.
375
+ function namedReads(mapFn, names) {
376
+ const reads = [];
377
+ let unsafe = false;
378
+ const binds = (p) => [...collectPatternNames(p, new Set())].some((n) => names.has(n));
379
+ const visit = (node, holder, slot) => {
380
+ if (unsafe || !node || typeof node !== 'object') return;
381
+ if (Array.isArray(node)) {
382
+ for (let i = 0; i < node.length; i++) visit(node[i], node, i);
383
+ return;
384
+ }
385
+ if (typeof node.type !== 'string') return;
386
+ switch (node.type) {
387
+ case 'Identifier':
388
+ if (names.has(node.name)) reads.push([holder, slot, node.name]);
389
+ return;
390
+ case 'JSXIdentifier':
391
+ if (names.has(node.name)) unsafe = true;
392
+ return;
393
+ case 'JSXAttribute':
394
+ visit(node.value, node, 'value');
395
+ return;
396
+ case 'MemberExpression':
397
+ case 'OptionalMemberExpression':
398
+ visit(node.object, node, 'object');
399
+ if (node.computed) visit(node.property, node, 'property');
400
+ return;
401
+ case 'ObjectProperty':
402
+ if (node.computed) visit(node.key, node, 'key');
403
+ if (node.shorthand && t.isIdentifier(node.value) && names.has(node.value.name)) {
404
+ node.shorthand = false;
405
+ node.value = t.cloneNode(node.value);
406
+ }
407
+ visit(node.value, node, 'value');
408
+ return;
409
+ case 'ObjectMethod':
410
+ case 'ClassMethod':
411
+ case 'ClassPrivateMethod':
412
+ if (node.params.some(binds)) { unsafe = true; return; }
413
+ if (node.computed) visit(node.key, node, 'key');
414
+ visit(node.body, node, 'body');
415
+ return;
416
+ case 'ClassProperty':
417
+ case 'ClassPrivateProperty':
418
+ if (node.computed) visit(node.key, node, 'key');
419
+ visit(node.value, node, 'value');
420
+ return;
421
+ case 'FunctionExpression':
422
+ case 'ArrowFunctionExpression':
423
+ case 'FunctionDeclaration':
424
+ if ((node.id && names.has(node.id.name)) || node.params.some(binds)) { unsafe = true; return; }
425
+ visit(node.params, node, 'params');
426
+ visit(node.body, node, 'body');
427
+ return;
428
+ case 'ClassDeclaration':
429
+ case 'ClassExpression':
430
+ if (node.id && names.has(node.id.name)) { unsafe = true; return; }
431
+ visit(node.superClass, node, 'superClass');
432
+ visit(node.body, node, 'body');
433
+ return;
434
+ case 'VariableDeclarator':
435
+ if (binds(node.id)) { unsafe = true; return; }
436
+ visit(node.init, node, 'init');
437
+ return;
438
+ case 'CatchClause':
439
+ if (node.param && binds(node.param)) { unsafe = true; return; }
440
+ visit(node.body, node, 'body');
441
+ return;
442
+ case 'AssignmentExpression':
443
+ if (binds(node.left)) { unsafe = true; return; }
444
+ break;
445
+ case 'UpdateExpression':
446
+ if (t.isIdentifier(node.argument) && names.has(node.argument.name)) { unsafe = true; return; }
447
+ break;
448
+ case 'LabeledStatement':
449
+ visit(node.body, node, 'body');
450
+ return;
451
+ case 'BreakStatement':
452
+ case 'ContinueStatement':
453
+ case 'MetaProperty':
454
+ return;
455
+ default:
456
+ if (node.type.startsWith('TS') && node.type !== 'TSAsExpression' && node.type !== 'TSSatisfiesExpression' && node.type !== 'TSNonNullExpression') return;
457
+ break;
458
+ }
459
+ for (const field of Object.keys(node)) {
460
+ if (field === 'loc' || field === 'start' || field === 'end' || field === 'type' || field === 'extra'
461
+ || field === 'typeAnnotation' || field === 'returnType' || field === 'typeParameters'
462
+ || field === 'leadingComments' || field === 'trailingComments' || field === 'innerComments') continue;
463
+ const value = node[field];
464
+ if (value && typeof value === 'object') visit(value, node, field);
465
+ }
466
+ };
467
+ for (let i = 1; i < mapFn.params.length; i++) if (binds(mapFn.params[i])) return null;
468
+ visit(mapFn.body, mapFn, 'body');
469
+ return unsafe ? null : reads;
470
+ }
471
+
472
+ // The number of the keyed list (a `.map()` call, a <For>) or the component
473
+ // written at `node`: where it starts in the source, the same for both
474
+ // targets, so the server's and the client's have one place in their
475
+ // component's output however many others are empty (what-core
476
+ // hydration-data.js _enterRow, _assignOwnerPath). Null for a node no source
477
+ // holds.
478
+ export function listSlot(node) {
479
+ return typeof node.start === 'number' ? t.numericLiteral(node.start) : null;
480
+ }
481
+
482
+ // --- A key outside a list ---
483
+ // A `key` on a component that is no list's row (`<Form key={user().id} />`)
484
+ // is React's way to start it again: a new instance whenever the key's value
485
+ // changes, the same key keeping the one it has. An element with one is built
486
+ // again the same way (`<input key={id()} />`: a new input, its typing gone).
487
+
488
+ // Before any JSX is lowered, on both targets: marks the key of a list's row
489
+ // (the JSX a `.map()` or `.flatMap()` callback returns, an arm of it, or what
490
+ // a <For>'s function returns), which the list reads, so that neither back
491
+ // end takes it for one outside a list (liveKey).
492
+ export function markRowKey(elPath, state) {
493
+ const key = elPath.node.openingElement.attributes.find((attr) => t.isJSXAttribute(attr) && getAttrName(attr) === 'key');
494
+ if (key === undefined) return;
495
+ let p = elPath;
496
+ for (;;) {
497
+ const parent = p.parentPath;
498
+ if (parent === null) return;
499
+ if ((parent.isConditionalExpression() && p.key !== 'test') || (parent.isLogicalExpression() && p.key === 'right')
500
+ || parent.isParenthesizedExpression() || parent.isTSAsExpression() || parent.isTSNonNullExpression()) {
501
+ p = parent;
502
+ continue;
503
+ }
504
+ const fn = parent.isArrowFunctionExpression() && p.key === 'body' ? parent : parent.isReturnStatement() ? parent.getFunctionParent() : null;
505
+ if (fn === null) return;
506
+ const holder = fn.parentPath;
507
+ const callee = holder.node.callee;
508
+ const mapped = (holder.isCallExpression() || holder.isOptionalCallExpression()) && fn.listKey === 'arguments'
509
+ && (t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) && !callee.computed
510
+ && t.isIdentifier(callee.property) && (callee.property.name === 'map' || callee.property.name === 'flatMap');
511
+ if (mapped || (holder.isJSXExpressionContainer() && controlFlowTag(holder.parent, state) === 'For')) key._whatRowKey = true;
512
+ return;
513
+ }
514
+ }
515
+
516
+ // The value of the key of a component or an element outside a list row when
517
+ // it can change: it reads a signal, a prop or a row's item. Both back ends
518
+ // build the JSX in a reactive child that runs again when the value changes (the DOM
519
+ // target's render.js _$keyed, the server's function child, which the
520
+ // hydratable renderers bracket and hydration adopts), so the two decide it
521
+ // alike. Null for no key, a row's, or one that cannot change, which costs
522
+ // nothing. A name holding a signal is read (`key={id}` is `id()`), as an
523
+ // attribute reads one (dom.js).
524
+ export function liveKey(node, state) {
525
+ for (const attr of node.openingElement.attributes) {
526
+ if (!t.isJSXAttribute(attr) || attr._whatRowKey === true || getAttrName(attr) !== 'key') continue;
527
+ const value = getAttributeValue(attr.value);
528
+ if (value == null || !(readsRowItem(value) || isPotentiallyReactive(value, state.signalNames, state.importedIdentifiers))) return null;
529
+ const fromProps = state.signalNames && state.signalNames.fromDestructuredProps;
530
+ return t.isIdentifier(value) && !(fromProps && fromProps.has(value.name)) && isSignalIdentifier(value.name, state.signalNames)
531
+ ? t.callExpression(value, [])
532
+ : value;
533
+ }
534
+ return null;
535
+ }
536
+
537
+ // The key of a `client:*` island that can change (liveKey), or null. A
538
+ // `client:static` island never runs in the browser, so no key can start it
539
+ // again there: building it again would only empty the server's HTML.
540
+ export function islandKey(node, mode, state) {
541
+ return mode === 'static' ? null : liveKey(node, state);
542
+ }
543
+
544
+ // Whether `node` reads a keyed row's item: the server target's marked name
545
+ // (markRowItemReads), outside any function in it.
546
+ export function readsRowItem(node) {
547
+ if (!node || typeof node !== 'object') return false;
548
+ if (Array.isArray(node)) return node.some(readsRowItem);
549
+ if (node._whatRowItem === true) return true;
550
+ if (t.isFunction(node)) return false;
551
+ for (const field of t.VISITOR_KEYS[node.type] || []) {
552
+ if (readsRowItem(node[field])) return true;
553
+ }
554
+ return false;
555
+ }
556
+
557
+ // Whether `found` (findMappedJsx) is a row the DOM target lowers to a keyed
558
+ // list: it has a key, and the key reads only the item.
559
+ export function isKeyedRow(found) {
560
+ return !!found.keyValue && !referencesAny(found.keyValue, keyInvisibleNames(found.mapFn));
561
+ }
562
+
563
+ // The names a key function `(item, index) => key` cannot see: those the
564
+ // callback declares, but its index when that is a plain name.
565
+ function keyInvisibleNames(mapFn) {
566
+ const names = namesInvisibleToKeyFn(mapFn);
567
+ if (t.isIdentifier(mapFn.params[1])) names.delete(mapFn.params[1].name);
568
+ return names;
569
+ }
570
+
571
+ /** The index name a keyed row's key reads (`key={`${t.term}-${i}`}`), else null. */
572
+ export function keyIndex(found) {
573
+ const index = found.mapFn.params[1];
574
+ return t.isIdentifier(index) && referencesAny(found.keyValue, new Set([index.name])) ? index.name : null;
575
+ }
576
+
577
+ // The reads of a keyed row's item other than its key expression, as
578
+ // [holder, slot, field] triples (none when the row reads only its key), or
579
+ // null when the row cannot read its item through a cell (see
580
+ // readItemThroughAccessor). `field` is the
581
+ // item's property a member read reads (`row.name`, `row['name']`), undefined
582
+ // for a read of the whole item or of a method it calls (`row.total()` may
583
+ // read any field through `this`).
584
+ function rowItemReads(mapFn, keyValue) {
585
+ const param = mapFn.params[0];
586
+ if (!t.isIdentifier(param)) return null;
587
+ const name = param.name;
588
+ const reads = [];
589
+ let unsafe = false;
590
+
591
+ const binds = (pattern) => collectPatternNames(pattern, new Set()).has(name);
592
+ const visit = (node, holder, slot) => {
593
+ if (unsafe || !node || typeof node !== 'object') return;
594
+ if (Array.isArray(node)) {
595
+ for (let i = 0; i < node.length; i++) visit(node[i], node, i);
596
+ return;
597
+ }
598
+ if (typeof node.type !== 'string') return;
599
+ if (node.type === keyValue.type && t.isNodesEquivalent(node, keyValue)) return;
600
+ switch (node.type) {
601
+ case 'Identifier':
602
+ if (node.name === name) reads.push([holder, slot]);
603
+ return;
604
+ case 'JSXIdentifier':
605
+ if (node.name === name) unsafe = true;
606
+ return;
607
+ case 'JSXAttribute':
608
+ // An attribute's name is not a read of the item: `<Row item={item} />`
609
+ // reads the item in its value only.
610
+ visit(node.value, node, 'value');
611
+ return;
612
+ case 'MemberExpression':
613
+ case 'OptionalMemberExpression':
614
+ if (t.isIdentifier(node.object, { name })) {
615
+ const called = (slot === 'callee' && (t.isCallExpression(holder) || t.isOptionalCallExpression(holder) || t.isNewExpression(holder)))
616
+ || (slot === 'tag' && t.isTaggedTemplateExpression(holder));
617
+ const key = !node.computed && t.isIdentifier(node.property) ? node.property.name
618
+ : node.computed && (t.isStringLiteral(node.property) || t.isNumericLiteral(node.property)) ? String(node.property.value)
619
+ : undefined;
620
+ reads.push([node, 'object', called ? undefined : key]);
621
+ } else {
622
+ visit(node.object, node, 'object');
623
+ }
624
+ if (node.computed) visit(node.property, node, 'property');
625
+ return;
626
+ case 'ObjectProperty':
627
+ if (node.computed) visit(node.key, node, 'key');
628
+ if (node.shorthand && t.isIdentifier(node.value, { name })) {
629
+ node.shorthand = false;
630
+ node.value = t.cloneNode(node.value);
631
+ }
632
+ visit(node.value, node, 'value');
633
+ return;
634
+ case 'ObjectMethod':
635
+ case 'ClassMethod':
636
+ case 'ClassPrivateMethod':
637
+ if (node.params.some(binds)) { unsafe = true; return; }
638
+ if (node.computed) visit(node.key, node, 'key');
639
+ visit(node.body, node, 'body');
640
+ return;
641
+ case 'ClassProperty':
642
+ case 'ClassPrivateProperty':
643
+ if (node.computed) visit(node.key, node, 'key');
644
+ visit(node.value, node, 'value');
645
+ return;
646
+ case 'FunctionExpression':
647
+ case 'ArrowFunctionExpression':
648
+ case 'FunctionDeclaration':
649
+ if ((node.id && node.id.name === name) || node.params.some(binds)) { unsafe = true; return; }
650
+ visit(node.params, node, 'params');
651
+ visit(node.body, node, 'body');
652
+ return;
653
+ case 'ClassDeclaration':
654
+ case 'ClassExpression':
655
+ if (node.id && node.id.name === name) { unsafe = true; return; }
656
+ visit(node.superClass, node, 'superClass');
657
+ visit(node.body, node, 'body');
658
+ return;
659
+ case 'VariableDeclarator':
660
+ if (binds(node.id)) { unsafe = true; return; }
661
+ visit(node.init, node, 'init');
662
+ return;
663
+ case 'CatchClause':
664
+ if (node.param && binds(node.param)) { unsafe = true; return; }
665
+ visit(node.body, node, 'body');
666
+ return;
667
+ case 'AssignmentExpression':
668
+ if (binds(node.left)) { unsafe = true; return; }
669
+ break;
670
+ case 'UpdateExpression':
671
+ if (t.isIdentifier(node.argument, { name })) { unsafe = true; return; }
672
+ break;
673
+ case 'LabeledStatement':
674
+ visit(node.body, node, 'body');
675
+ return;
676
+ case 'BreakStatement':
677
+ case 'ContinueStatement':
678
+ case 'MetaProperty':
679
+ return;
680
+ case 'TSAsExpression':
681
+ case 'TSSatisfiesExpression':
682
+ case 'TSNonNullExpression':
683
+ case 'TSTypeAssertion':
684
+ visit(node.expression, node, 'expression');
685
+ return;
686
+ default:
687
+ if (node.type.startsWith('TS')) return;
688
+ break;
689
+ }
690
+ for (const field of Object.keys(node)) {
691
+ if (field === 'loc' || field === 'start' || field === 'end' || field === 'type' || field === 'extra'
692
+ || field === 'typeAnnotation' || field === 'returnType' || field === 'typeParameters'
693
+ || field === 'leadingComments' || field === 'trailingComments' || field === 'innerComments') continue;
694
+ const value = node[field];
695
+ if (value && typeof value === 'object') visit(value, node, field);
696
+ }
697
+ };
698
+
699
+ for (let i = 1; i < mapFn.params.length; i++) {
700
+ if (binds(mapFn.params[i])) return null;
701
+ }
702
+ visit(mapFn.body, mapFn, 'body');
703
+ return unsafe ? null : reads;
704
+ }