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.
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/babel.d.ts +78 -2
- package/dist/babel/auto-selector.min.js +94 -0
- package/dist/babel/common.min.js +2053 -0
- package/dist/babel/dev-metadata.min.js +106 -0
- package/dist/babel/dom.min.js +1669 -0
- package/dist/babel/jsx-root.min.js +13 -0
- package/dist/babel/lists.min.js +492 -0
- package/dist/babel/nesting.min.js +328 -0
- package/dist/babel/reactivity.min.js +1218 -0
- package/dist/babel/server-actions.min.js +85 -0
- package/dist/babel/ssr.min.js +496 -0
- package/dist/babel/types.min.js +9 -0
- package/dist/babel-plugin.min.js +101 -1
- package/dist/file-router.min.js +368 -12
- package/dist/framework-files.min.js +62 -0
- package/dist/hot.min.js +315 -0
- package/dist/index.min.js +13 -414
- package/dist/release.min.js +78 -0
- package/dist/runtime.min.js +9 -1
- package/dist/tables/import-changes.min.js +272 -0
- package/dist/tables/markup-rules.min.js +213 -0
- package/dist/vite-plugin.min.js +432 -399
- package/file-router.d.ts +3 -1
- package/index.d.ts +1 -1
- package/package.json +11 -2
- package/runtime.d.ts +2 -1
- package/src/babel/auto-selector.js +248 -0
- package/src/babel/common.js +3800 -0
- package/src/babel/dev-metadata.js +167 -0
- package/src/babel/dom.js +3386 -0
- package/src/babel/jsx-root.js +27 -0
- package/src/babel/lists.js +704 -0
- package/src/babel/nesting.js +260 -0
- package/src/babel/reactivity.js +1998 -0
- package/src/babel/server-actions.js +144 -0
- package/src/babel/ssr.js +870 -0
- package/src/babel/types.js +10 -0
- package/src/babel-plugin.js +185 -3598
- package/src/file-router.js +58 -38
- package/src/framework-files.js +106 -0
- package/src/hot.js +523 -0
- package/src/release.js +127 -0
- package/src/runtime.js +7 -7
- package/src/tables/import-changes.js +157 -0
- package/src/tables/markup-rules.js +388 -0
- package/src/vite-plugin.js +460 -175
- package/vite.d.ts +47 -3
- package/src/error-overlay.js +0 -428
|
@@ -0,0 +1,3800 @@
|
|
|
1
|
+
// The front end both back ends share: how JSX is classified (element,
|
|
2
|
+
// component, control flow), how attribute names are normalized, the namespace
|
|
3
|
+
// every element is in, the child slots an element's children flatten to, and
|
|
4
|
+
// the hygienic names the generated code introduces.
|
|
5
|
+
|
|
6
|
+
import {
|
|
7
|
+
HTML_ENCODINGS,
|
|
8
|
+
INNER_HTML_PROPS,
|
|
9
|
+
MATHML_IN_TEXT_POINTS,
|
|
10
|
+
MATHML_TEXT_INTEGRATION_POINTS,
|
|
11
|
+
SVG_HTML_INTEGRATION_POINTS,
|
|
12
|
+
VOID_ELEMENTS,
|
|
13
|
+
isRefusedAttr,
|
|
14
|
+
isUnsafeUrl,
|
|
15
|
+
isUrlAttr,
|
|
16
|
+
attributeName,
|
|
17
|
+
rawTextHazard,
|
|
18
|
+
FIELD_PROPS,
|
|
19
|
+
FIELD_TAGS,
|
|
20
|
+
ATTRIBUTE_VALUE_TYPES,
|
|
21
|
+
} from '../tables/markup-rules.js';
|
|
22
|
+
import { t } from './types.js';
|
|
23
|
+
|
|
24
|
+
const EVENT_MODIFIERS = new Set(['preventDefault', 'stopPropagation', 'once', 'capture', 'passive', 'self']);
|
|
25
|
+
export const EVENT_OPTION_MODIFIERS = new Set(['once', 'capture', 'passive']);
|
|
26
|
+
|
|
27
|
+
// A bare specifier that resolves to this framework, entry point included:
|
|
28
|
+
// 'what-framework', 'what-framework/render', 'what-core', 'what-core/render'.
|
|
29
|
+
// Used to decide whether an imported binding is provably ours before the plugin
|
|
30
|
+
// changes how a call to it is compiled.
|
|
31
|
+
export function isWhatModuleSource(source) {
|
|
32
|
+
return source === 'what-framework'
|
|
33
|
+
|| source.startsWith('what-framework/')
|
|
34
|
+
|| source === 'what-core'
|
|
35
|
+
|| source.startsWith('what-core/');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// Normalize JSX text per React/Babel rules:
|
|
39
|
+
// - Split on newlines, treat tabs as spaces.
|
|
40
|
+
// - For interior lines: trim leading and trailing horizontal whitespace.
|
|
41
|
+
// - For the first line: only trim trailing whitespace.
|
|
42
|
+
// - For the last line: only trim leading whitespace.
|
|
43
|
+
// - Skip lines that are entirely whitespace (don't add a separator space).
|
|
44
|
+
// - Join the remaining non-empty lines with single spaces.
|
|
45
|
+
//
|
|
46
|
+
// This preserves leading/trailing single-line whitespace that sits next to
|
|
47
|
+
// an expression like `{count} items` — without this, the space is eaten and
|
|
48
|
+
// the rendered output reads `5items`.
|
|
49
|
+
export function normalizeJsxText(value) {
|
|
50
|
+
// Single-line text (no newlines): preserve the original (just tabs->spaces).
|
|
51
|
+
// This keeps the space in cases like `{a} {b}` where the JSXText is " ".
|
|
52
|
+
if (!/[\r\n]/.test(value)) {
|
|
53
|
+
return value.replace(/\t/g, ' ');
|
|
54
|
+
}
|
|
55
|
+
const lines = value.split(/\r\n|\n|\r/);
|
|
56
|
+
let lastNonEmpty = -1;
|
|
57
|
+
for (let i = 0; i < lines.length; i++) {
|
|
58
|
+
if (/[^ \t]/.test(lines[i])) lastNonEmpty = i;
|
|
59
|
+
}
|
|
60
|
+
if (lastNonEmpty === -1) return '';
|
|
61
|
+
let out = '';
|
|
62
|
+
for (let i = 0; i < lines.length; i++) {
|
|
63
|
+
let line = lines[i].replace(/\t/g, ' ');
|
|
64
|
+
const isFirst = i === 0;
|
|
65
|
+
const isLast = i === lines.length - 1;
|
|
66
|
+
if (!isFirst) line = line.replace(/^ +/, '');
|
|
67
|
+
if (!isLast) line = line.replace(/ +$/, '');
|
|
68
|
+
if (!line) continue;
|
|
69
|
+
if (i !== lastNonEmpty) line += ' ';
|
|
70
|
+
out += line;
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// --- Generated names ---
|
|
76
|
+
//
|
|
77
|
+
// Every binding the compiler introduces (`_el$0`, `_tmpl$0`, `_c$0`, `_sel$0`,
|
|
78
|
+
// the `_$insert` style helper imports, ...) is unique in its file. The names
|
|
79
|
+
// the file already spells anywhere (bindings, references, globals, JSX tags)
|
|
80
|
+
// are collected in the one pass Program.enter makes before any JSX is lowered;
|
|
81
|
+
// a generated name skips every one of them. Counters are per prefix, so a file
|
|
82
|
+
// with no collision gets exactly the names it always did.
|
|
83
|
+
|
|
84
|
+
export function initFileState(state) {
|
|
85
|
+
state._usedNames = new Set();
|
|
86
|
+
state._nameCounters = new Map();
|
|
87
|
+
state._helperNames = new Map();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function recordName(state, name) {
|
|
91
|
+
state._usedNames.add(name);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `_el$0`, `_el$1`, ... skipping any name the file already uses. */
|
|
95
|
+
export function uniqueName(state, prefix) {
|
|
96
|
+
let n = state._nameCounters.get(prefix) || 0;
|
|
97
|
+
let name = `${prefix}${n++}`;
|
|
98
|
+
while (state._usedNames.has(name)) name = `${prefix}${n++}`;
|
|
99
|
+
state._nameCounters.set(prefix, n);
|
|
100
|
+
state._usedNames.add(name);
|
|
101
|
+
return name;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* The local name of a runtime helper the generated code calls, as an
|
|
106
|
+
* identifier: `name` itself unless the file already uses it, then `name2`,
|
|
107
|
+
* `name3`, ... The back end emits one import specifier per helper it handed
|
|
108
|
+
* out (see helperLocals).
|
|
109
|
+
*/
|
|
110
|
+
export function helper(state, name) {
|
|
111
|
+
let local = state._helperNames.get(name);
|
|
112
|
+
if (local === undefined) {
|
|
113
|
+
local = name;
|
|
114
|
+
for (let n = 2; state._usedNames.has(local); n++) local = `${name}${n}`;
|
|
115
|
+
state._usedNames.add(local);
|
|
116
|
+
state._helperNames.set(name, local);
|
|
117
|
+
}
|
|
118
|
+
return t.identifier(local);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The helpers `helper()` handed out, as [name, local] pairs in first-use order. */
|
|
122
|
+
export function helperLocals(state) {
|
|
123
|
+
return state._helperNames;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Warn-once tracking for unknown event modifier segments. Keyed by
|
|
127
|
+
// `${filename}::${segment}` so each typo is reported at most once per file
|
|
128
|
+
// per compile process. Without the filename in the key, the same typo in
|
|
129
|
+
// two different files would silently warn for the first file only —
|
|
130
|
+
// problematic in long-running Vite dev servers.
|
|
131
|
+
const _unknownModifierWarned = new Set();
|
|
132
|
+
|
|
133
|
+
export function hasEventModifiers(name, state) {
|
|
134
|
+
// Any `__` in an `on*` attribute is intended as modifier syntax — even
|
|
135
|
+
// if every segment is unknown. Returning false there would emit the
|
|
136
|
+
// attribute as a plain delegated-event property (e.g.
|
|
137
|
+
// `el.$$onclick__totalyWrong = handler`), which never fires. Instead,
|
|
138
|
+
// always route through the modifier-handling branch so the parser can
|
|
139
|
+
// warn about the typo and drop the unknown segments.
|
|
140
|
+
if (!name.includes('__')) return false;
|
|
141
|
+
if (!name.startsWith('on')) return false;
|
|
142
|
+
const parts = name.split('__');
|
|
143
|
+
const tail = parts.slice(1).filter(s => s !== '');
|
|
144
|
+
if (tail.length === 0) return false;
|
|
145
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
146
|
+
const unknown = tail.filter(m => !EVENT_MODIFIERS.has(m));
|
|
147
|
+
const filename = (state && (state.filename || (state.file && state.file.opts && state.file.opts.filename))) || '<unknown>';
|
|
148
|
+
for (const m of unknown) {
|
|
149
|
+
const key = `${filename}::${m}`;
|
|
150
|
+
if (!_unknownModifierWarned.has(key)) {
|
|
151
|
+
_unknownModifierWarned.add(key);
|
|
152
|
+
console.warn(
|
|
153
|
+
`[what-compiler] Unknown event modifier "__${m}" in attribute "${name}" (${filename}). ` +
|
|
154
|
+
`Known modifiers: ${[...EVENT_MODIFIERS].join(', ')}. ` +
|
|
155
|
+
`Unknown segments are ignored.`
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function parseEventModifiers(name) {
|
|
164
|
+
// Support both '|' (template strings) and '__' (JSX-safe) as modifier delimiters
|
|
165
|
+
const delimiter = name.includes('|') ? '|' : '__';
|
|
166
|
+
const parts = name.split(delimiter);
|
|
167
|
+
const eventName = parts[0];
|
|
168
|
+
const modifiers = parts.slice(1).filter(m => EVENT_MODIFIERS.has(m));
|
|
169
|
+
return { eventName, modifiers };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// React's capture-phase names: `onClickCapture` listens for `click` in the
|
|
173
|
+
// capture phase (what-core dom.js does the same for h() and spreads), so the
|
|
174
|
+
// name without `Capture` is returned. `onGotPointerCapture` and
|
|
175
|
+
// `onLostPointerCapture` are events of their own, and return null.
|
|
176
|
+
export function captureEventName(name) {
|
|
177
|
+
return name.endsWith('Capture') && !name.endsWith('PointerCapture') ? name.slice(0, -7) : null;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// The DOM event an event prop listens for: its name in lower case, and
|
|
181
|
+
// `dblclick` for React's `onDoubleClick` (what-core dom.js and render.js do
|
|
182
|
+
// the same for h() and spreads).
|
|
183
|
+
export function eventType(name) {
|
|
184
|
+
const type = name.slice(2).toLowerCase();
|
|
185
|
+
return type === 'doubleclick' ? 'dblclick' : type;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export function isBindingAttribute(name) {
|
|
189
|
+
return name.startsWith('bind:');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function getBindingProperty(name) {
|
|
193
|
+
return name.slice(5);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function isComponent(name) {
|
|
197
|
+
return /^[A-Z]/.test(name);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Build the Error for a JSX shape the compiler refuses to lower.
|
|
201
|
+
//
|
|
202
|
+
// Every fine-grained transform is reachable two ways: from the JSXElement
|
|
203
|
+
// visitor, where `path` is a real NodePath, and recursively from a parent
|
|
204
|
+
// transform, which passes a SYNTHETIC `{ node: child }` (see the
|
|
205
|
+
// transformElementFineGrained / transformFragmentFineGrained calls further
|
|
206
|
+
// down). Only the visitor's path carries buildCodeFrameError, so calling it
|
|
207
|
+
// unguarded threw "path.buildCodeFrameError is not a function" — an internal
|
|
208
|
+
// crash in place of the diagnostic the author was meant to act on. That hit
|
|
209
|
+
// the ordinary shapes, not the exotic ones: `<div><Show>…</Show></div>` is
|
|
210
|
+
// already synthetic, so only a control-flow tag that was the ENTIRE return
|
|
211
|
+
// value ever reported properly.
|
|
212
|
+
//
|
|
213
|
+
// Guarding the call is not enough either. `throw new Error(message)` reaches
|
|
214
|
+
// the developer, but with no file and no line, which for a build error in a
|
|
215
|
+
// 300-file app is barely better than the crash. state.file is Babel's File
|
|
216
|
+
// for the module being compiled and its buildCodeFrameError(node, msg) pins
|
|
217
|
+
// the frame from the node's own loc, so a synthetic path still gets the same
|
|
218
|
+
// pointed-at source the visitor path does.
|
|
219
|
+
export function compileError(path, state, message) {
|
|
220
|
+
if (typeof path?.buildCodeFrameError === 'function') {
|
|
221
|
+
return path.buildCodeFrameError(message);
|
|
222
|
+
}
|
|
223
|
+
const node = path?.node;
|
|
224
|
+
if (node && typeof state?.file?.buildCodeFrameError === 'function') {
|
|
225
|
+
return state.file.buildCodeFrameError(node, message);
|
|
226
|
+
}
|
|
227
|
+
// No NodePath and no File (a direct unit-test call, or a node the parser
|
|
228
|
+
// never produced). Name the file and line by hand so the message still
|
|
229
|
+
// says where to look.
|
|
230
|
+
const loc = node?.loc?.start;
|
|
231
|
+
const filename = state?.filename || state?.file?.opts?.filename || '<unknown>';
|
|
232
|
+
return new Error(
|
|
233
|
+
`[what-compiler] ${message} (${loc ? `${filename}:${loc.line}:${loc.column + 1}` : filename})`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// A compile error that carries an ERR_* code and names its position as
|
|
238
|
+
// path:line:column (1-based column, path relative to projectRoot) in the
|
|
239
|
+
// message, with `loc` in the { file, line, column } form Vite's error overlay
|
|
240
|
+
// reads (0-based column, as Babel reports it).
|
|
241
|
+
export function codedCompileError(node, state, { code }, message) {
|
|
242
|
+
const start = node.loc && node.loc.start;
|
|
243
|
+
const file = String(state?.file?.opts?.filename || '<unknown>').replace(/\\/g, '/');
|
|
244
|
+
const root = String(state?.opts?.projectRoot || state?.file?.opts?.cwd || '').replace(/\\/g, '/').replace(/\/+$/, '');
|
|
245
|
+
const shown = root && file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file;
|
|
246
|
+
const where = start ? ` at ${shown}:${start.line}:${start.column + 1}` : '';
|
|
247
|
+
const error = compileError({ node }, state, `${code}${where}: ${message}`);
|
|
248
|
+
if (start) error.loc = { file, line: start.line, column: start.column };
|
|
249
|
+
error.code = code;
|
|
250
|
+
return error;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// --- Static markup ---
|
|
254
|
+
//
|
|
255
|
+
// A tag, attribute or text the source fixes is written into markup as it is:
|
|
256
|
+
// the DOM back end's template string, which the browser parses, and the server
|
|
257
|
+
// back end's string templates. So the markup rules the runtime applies to a
|
|
258
|
+
// value on every path (what-core's markup-rules.js) are applied to a static
|
|
259
|
+
// one here, as a compile error where it is written.
|
|
260
|
+
|
|
261
|
+
export function unsafeMarkup(node, state, message) {
|
|
262
|
+
return codedCompileError(node, state, { code: 'ERR_UNSAFE_STATIC_MARKUP' }, message);
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** The JSX name of a tag as written: `div`, `Foo.Bar`, `svg:rect`. */
|
|
266
|
+
function jsxTagName(name) {
|
|
267
|
+
if (t.isJSXMemberExpression(name)) return `${jsxTagName(name.object)}.${name.property.name}`;
|
|
268
|
+
if (t.isJSXNamespacedName(name)) return `${name.namespace.name}:${name.name.name}`;
|
|
269
|
+
return name.name;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// `<svg:rect>` is a JSX namespaced name, not an SVG element: markup has no
|
|
273
|
+
// namespace prefixes, and an element's namespace comes from where it stands.
|
|
274
|
+
export function checkElementName(node, state) {
|
|
275
|
+
const name = node.openingElement.name;
|
|
276
|
+
if (t.isJSXNamespacedName(name)) {
|
|
277
|
+
throw unsafeMarkup(node, state,
|
|
278
|
+
`<${jsxTagName(name)}> is a namespaced tag name, which markup does not have. Write <${name.name.name}> inside <${name.namespace.name}>.`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// A static attribute value: `value` is true for a valueless attribute, else the
|
|
283
|
+
// literal, or null/false when it writes nothing.
|
|
284
|
+
export function checkStaticAttribute(attr, key, name, value, state) {
|
|
285
|
+
const present = value !== undefined && value !== null && value !== false;
|
|
286
|
+
if (present && isRefusedAttr(key)) {
|
|
287
|
+
throw unsafeMarkup(attr, state, key.toLowerCase() === 'srcdoc'
|
|
288
|
+
? 'srcdoc is parsed by the browser as a whole document, so escaping cannot make it safe; it is never written.'
|
|
289
|
+
: `${key} replaces the element with its value parsed as markup, so escaping cannot make it safe; it is never written.`);
|
|
290
|
+
}
|
|
291
|
+
if (typeof value === 'string' && isUrlAttr(key) && isUnsafeUrl(value)) {
|
|
292
|
+
throw unsafeMarkup(attr, state,
|
|
293
|
+
`${key}=${JSON.stringify(value)} uses a javascript:, vbscript: or data: URL, which is never written.`);
|
|
294
|
+
}
|
|
295
|
+
if (present && INNER_HTML_PROPS.has(name)) {
|
|
296
|
+
throw unsafeMarkup(attr, state,
|
|
297
|
+
`${name} takes { __html: trustedString }, never a string, so markup cannot reach the page by accident.`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Static text inside a <script> or <style>, which is written as it is: it must
|
|
302
|
+
// not hold a sequence that ends the element (what-core's rawTextHazard).
|
|
303
|
+
export function checkStaticRawText(node, tag, text, state) {
|
|
304
|
+
if (rawTextHazard(tag, text)) {
|
|
305
|
+
throw unsafeMarkup(node, state, tag === 'script'
|
|
306
|
+
? `the text of a <script> is written as it is, so it cannot contain "</" or "<!--", which can end the element. Write "<\\/" and "\\x3C!--" in a string, or pass the code as dangerouslySetInnerHTML={{ __html }}.`
|
|
307
|
+
: `the text of a <style> is written as it is, so it cannot contain "</", which can end the element. Write "<\\/" in a string instead.`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// --- Islands and control flow, both back ends ---
|
|
312
|
+
|
|
313
|
+
// JSX inside an island prop, outside any function in it. Island props are
|
|
314
|
+
// serialized to JSON for the browser, and markup is not data.
|
|
315
|
+
function jsxInValue(node) {
|
|
316
|
+
if (!node || typeof node !== 'object') return null;
|
|
317
|
+
if (t.isJSXElement(node) || t.isJSXFragment(node)) return node;
|
|
318
|
+
if (t.isFunction(node)) return null;
|
|
319
|
+
for (const key of t.VISITOR_KEYS[node.type] || []) {
|
|
320
|
+
const value = node[key];
|
|
321
|
+
const found = Array.isArray(value) ? value.map(jsxInValue).find(Boolean) : jsxInValue(value);
|
|
322
|
+
if (found) return found;
|
|
323
|
+
}
|
|
324
|
+
return null;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export function checkIslandProp(name, value, node, state) {
|
|
328
|
+
const jsx = jsxInValue(value);
|
|
329
|
+
if (!jsx) return;
|
|
330
|
+
throw codedCompileError(jsx, state, { code: 'ERR_JSX_ISLAND_PROP' },
|
|
331
|
+
`JSX is not an island prop: "${name}" of <${jsxTagName(node.openingElement.name)}> is serialized to JSON for the browser, and markup is not data. ` +
|
|
332
|
+
'Pass it as a child of the island, or pass the data and build the markup inside the island.');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// `client:media="(min-width: 40em)"` or `client:media={query}`.
|
|
336
|
+
export function directiveValue(attr) {
|
|
337
|
+
if (!attr.value) return null;
|
|
338
|
+
if (t.isStringLiteral(attr.value)) return attr.value;
|
|
339
|
+
if (t.isJSXExpressionContainer(attr.value) && !t.isJSXEmptyExpression(attr.value.expression)) return attr.value.expression;
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// The render function a <Show> or <For> child is: the only child that is not
|
|
344
|
+
// whitespace, written as a function. Null when the children are content.
|
|
345
|
+
export function renderFunctionChild(children) {
|
|
346
|
+
const meaningful = children.filter(c => !(t.isJSXText(c) && !normalizeJsxText(c.value))
|
|
347
|
+
&& !(t.isJSXExpressionContainer(c) && t.isJSXEmptyExpression(c.expression)));
|
|
348
|
+
if (meaningful.length !== 1) return null;
|
|
349
|
+
const only = meaningful[0];
|
|
350
|
+
return t.isJSXExpressionContainer(only) && t.isFunction(only.expression) ? only.expression : null;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Dotted tags (<Ctx.Provider>, <Foo.Bar.Baz>) are always components.
|
|
354
|
+
export function isComponentElement(el) {
|
|
355
|
+
const name = el.openingElement ? el.openingElement.name : el.name;
|
|
356
|
+
if (t.isJSXMemberExpression(name)) return true;
|
|
357
|
+
return t.isJSXIdentifier(name) && isComponent(name.name);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// A tag whose binding came from a package other than What. isWhatTag is the
|
|
361
|
+
// stronger claim: the binding came from What, so the tag is provably ours.
|
|
362
|
+
function isForeignTag(name, state) {
|
|
363
|
+
return !!(state.foreignImports && state.foreignImports.has(name));
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function isWhatTag(name, state) {
|
|
367
|
+
return !!(state.whatImports && state.whatImports.has(name));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Literal <Match> arms are proof enough that a <Switch> is What's, whoever it
|
|
371
|
+
// was imported from: a bare specifier can be a re-export of What's control
|
|
372
|
+
// flow just as a relative one can, and nobody writes <Match> arms against a
|
|
373
|
+
// third-party <Switch>. Unlike <Show> and <For>, <Switch> has no working
|
|
374
|
+
// runtime path, so guessing wrong here renders the fallback forever. An arm
|
|
375
|
+
// written under the name What's Match was imported as counts too.
|
|
376
|
+
function hasLiteralMatchArms(node, state) {
|
|
377
|
+
return node.children.some((child) => t.isJSXElement(child) && t.isJSXIdentifier(child.openingElement.name)
|
|
378
|
+
&& (child.openingElement.name.name === 'Match' || (state != null && whatControlFlow(state).get(child.openingElement.name.name) === 'Match')));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// --- What's control flow, by where it was imported from ---
|
|
382
|
+
//
|
|
383
|
+
// <For>, <Show>, <Switch> and <Match> lower to inserters and conditionals
|
|
384
|
+
// (dom.js transformElementFineGrained, ssr.js jsxValue). The tag is what the
|
|
385
|
+
// file imported from What, under whatever name: `import { Switch as Branch }`
|
|
386
|
+
// lowers `<Branch>` as a <Switch>, so a file can keep the name `Switch` for a
|
|
387
|
+
// UI toggle of its own. A tag that was not imported from What keeps the old
|
|
388
|
+
// rule: lowered by its name unless a package other than What exports it.
|
|
389
|
+
|
|
390
|
+
const CONTROL_FLOW = new Set(['For', 'Show', 'Switch', 'Match']);
|
|
391
|
+
|
|
392
|
+
/** The local names this file imports What's control flow under, to the name What exports. */
|
|
393
|
+
function whatControlFlow(state) {
|
|
394
|
+
if (state._whatControlFlow) return state._whatControlFlow;
|
|
395
|
+
/** @type {Map<string, string>} */
|
|
396
|
+
const names = new Map();
|
|
397
|
+
for (const node of state.file?.ast?.program?.body ?? []) {
|
|
398
|
+
if (!t.isImportDeclaration(node) || node.importKind === 'type' || !isWhatModuleSource(node.source.value)) continue;
|
|
399
|
+
for (const spec of node.specifiers) {
|
|
400
|
+
if (!t.isImportSpecifier(spec) || spec.importKind === 'type') continue;
|
|
401
|
+
const imported = spec.imported.name ?? spec.imported.value;
|
|
402
|
+
if (CONTROL_FLOW.has(imported)) names.set(spec.local.name, imported);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
state._whatControlFlow = names;
|
|
406
|
+
return names;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* The control flow built-in the JSX element `el` is, as What exports it
|
|
411
|
+
* ('For', 'Show', 'Switch' or 'Match'), or null for any other element. A
|
|
412
|
+
* third party's <Switch> is What's only when its literal <Match> arms say so.
|
|
413
|
+
*/
|
|
414
|
+
export function controlFlowTag(el, state) {
|
|
415
|
+
const name = el && el.openingElement ? el.openingElement.name : null;
|
|
416
|
+
if (!t.isJSXIdentifier(name)) return null;
|
|
417
|
+
const local = name.name;
|
|
418
|
+
const imported = whatControlFlow(state).get(local);
|
|
419
|
+
if (imported !== undefined) return imported;
|
|
420
|
+
if (!CONTROL_FLOW.has(local)) return null;
|
|
421
|
+
if (!isForeignTag(local, state)) return local;
|
|
422
|
+
return local === 'Switch' && hasLiteralMatchArms(el, state) ? 'Switch' : null;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// --- The JSX handed straight to hydrate() ---
|
|
426
|
+
//
|
|
427
|
+
// hydrate() can only adopt the server's markup from an UNBUILT tree: a node
|
|
428
|
+
// that has already been built has its bindings wired to itself, so hydrateNode
|
|
429
|
+
// inserts it and lets the trim delete everything the server sent. The
|
|
430
|
+
// documented client entry, `hydrate(<App />, el)`, lowered to
|
|
431
|
+
// `_$createComponent(App, ...)`, which runs App and builds its DOM before
|
|
432
|
+
// hydrate() is even called — so every compiled app that hydrated threw its
|
|
433
|
+
// server render away and re-rendered from scratch, silently in production
|
|
434
|
+
// where the warning is stripped.
|
|
435
|
+
//
|
|
436
|
+
// Only the first argument is the tree; the second is the container. And only a
|
|
437
|
+
// binding that provably resolves to OUR hydrate qualifies, because rewriting a
|
|
438
|
+
// call to somebody else's `hydrate` would change what their code means.
|
|
439
|
+
export function isHydrateRootArgument(path) {
|
|
440
|
+
// transformElementFineGrained is also called with a bare `{ node }` stand-in
|
|
441
|
+
// when it recurses into children, and a child is never the hydrate root.
|
|
442
|
+
const parent = path.parentPath;
|
|
443
|
+
if (!parent || typeof parent.isCallExpression !== 'function' || !parent.isCallExpression()) {
|
|
444
|
+
return false;
|
|
445
|
+
}
|
|
446
|
+
if (parent.node.arguments[0] !== path.node) return false;
|
|
447
|
+
return isWhatHydrateCallee(parent.node.callee, parent.scope);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// Resolve the callee through Babel's scope rather than by name, so a local
|
|
451
|
+
// `function hydrate()` or `const hydrate = ...` that shadows the import is left
|
|
452
|
+
// alone. getBinding returns the NEAREST binding, which is exactly the shadowing
|
|
453
|
+
// rule the language itself applies. An unresolved (global) `hydrate` is not
|
|
454
|
+
// ours either, so it stays untouched too.
|
|
455
|
+
function isWhatHydrateCallee(callee, scope) {
|
|
456
|
+
// `ns.hydrate(...)` after `import * as ns from 'what-framework'`.
|
|
457
|
+
if (t.isMemberExpression(callee) && !callee.computed
|
|
458
|
+
&& t.isIdentifier(callee.property, { name: 'hydrate' })
|
|
459
|
+
&& t.isIdentifier(callee.object)) {
|
|
460
|
+
return importedFrom(scope.getBinding(callee.object.name), t.isImportNamespaceSpecifier, null);
|
|
461
|
+
}
|
|
462
|
+
if (!t.isIdentifier(callee)) return false;
|
|
463
|
+
// `import { hydrate }` and `import { hydrate as boot }` alike: the binding
|
|
464
|
+
// remembers the name that was IMPORTED, which is the one that matters.
|
|
465
|
+
return importedFrom(scope.getBinding(callee.name), t.isImportSpecifier, 'hydrate');
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// A binding is ours when it came from an import declaration of a What module
|
|
469
|
+
// through the expected specifier kind, optionally carrying a required imported
|
|
470
|
+
// name (`hydrate` for a named import, none for a namespace).
|
|
471
|
+
export function importedFrom(binding, isSpecifier, importedName) {
|
|
472
|
+
if (!binding || binding.kind !== 'module' || !binding.path) return false;
|
|
473
|
+
const spec = binding.path.node;
|
|
474
|
+
if (!isSpecifier(spec)) return false;
|
|
475
|
+
if (importedName !== null) {
|
|
476
|
+
const imported = spec.imported;
|
|
477
|
+
const name = t.isIdentifier(imported) ? imported.name
|
|
478
|
+
: t.isStringLiteral(imported) ? imported.value
|
|
479
|
+
: null;
|
|
480
|
+
if (name !== importedName) return false;
|
|
481
|
+
}
|
|
482
|
+
const decl = binding.path.parent;
|
|
483
|
+
return t.isImportDeclaration(decl) && isWhatModuleSource(decl.source.value);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// JSXMemberExpression -> MemberExpression callee for _$createComponent.
|
|
487
|
+
export function componentCallee(name) {
|
|
488
|
+
if (t.isJSXMemberExpression(name)) {
|
|
489
|
+
return t.memberExpression(componentCallee(name.object), t.identifier(name.property.name));
|
|
490
|
+
}
|
|
491
|
+
return t.identifier(name.name);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// What a `client:*` island hands _$Island (what-core components.js), on both
|
|
495
|
+
// targets: the component, the island's name, the trigger and its media query,
|
|
496
|
+
// and the component's props as an object of their own (`props`, left out when
|
|
497
|
+
// there are none), so a prop may have any name, `name` and `mode` included.
|
|
498
|
+
// The name is the tag as written, which a minifier leaves alone, so the
|
|
499
|
+
// server and the browser write the same data-island.
|
|
500
|
+
export function islandOptions(tag, mode, mediaQuery, props) {
|
|
501
|
+
const options = [
|
|
502
|
+
t.objectProperty(t.identifier('component'), componentCallee(tag)),
|
|
503
|
+
t.objectProperty(t.identifier('name'), t.stringLiteral(jsxTagName(tag))),
|
|
504
|
+
t.objectProperty(t.identifier('mode'), t.stringLiteral(mode)),
|
|
505
|
+
];
|
|
506
|
+
if (mediaQuery) options.push(t.objectProperty(t.identifier('mediaQuery'), mediaQuery));
|
|
507
|
+
if (props) options.push(t.objectProperty(t.identifier('props'), props));
|
|
508
|
+
return t.objectExpression(options);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// --- Props a component reads where it uses them ---
|
|
512
|
+
// Compiled JSX hands a component JSX as a getter that builds it when read:
|
|
513
|
+
// its children (dom.js _installLazyChildren), and the JSX it passes in any
|
|
514
|
+
// other prop (`header={<Nav />}`, _$slots). It hands a prop whose value reads
|
|
515
|
+
// a signal (`on={count() > 0}`) as a getter too, a live prop (what-core
|
|
516
|
+
// dom.js _isLiveProp), which reads the expression again wherever it is read.
|
|
517
|
+
// Destructuring a prop, in the parameter list or from props in the body,
|
|
518
|
+
// reads its getter there, once, before the component's output exists: a
|
|
519
|
+
// live prop would freeze at its first value, and JSX would be built before a
|
|
520
|
+
// boundary or a provider it is forwarded into is entered (the boundary never
|
|
521
|
+
// catches, the provider publishes too late) and, while hydrating, off the
|
|
522
|
+
// walk, taking the place of the server's nodes for it.
|
|
523
|
+
//
|
|
524
|
+
// So a destructured prop is read where it is used instead:
|
|
525
|
+
// - when every read of it places it, each read becomes a placing read of
|
|
526
|
+
// `props.<key>` where it stands, which builds JSX where it renders, as
|
|
527
|
+
// `props.children` written there does (and places a live prop as a
|
|
528
|
+
// reactive child);
|
|
529
|
+
// - otherwise, in a function that renders JSX, each read becomes the read
|
|
530
|
+
// `props.<key>` where it stands, which the JSX bindings around it track
|
|
531
|
+
// (reactivity.js isPropsRead).
|
|
532
|
+
// A binding that is reassigned, one with a default that is not a plain
|
|
533
|
+
// literal (`items = []` would be a new array at every read), a nested
|
|
534
|
+
// pattern, one used as a JSX tag (`<Icon />`) and a computed key keep their
|
|
535
|
+
// destructuring, read once.
|
|
536
|
+
//
|
|
537
|
+
// The DOM back end also marks a read of `props.<key>` written by hand where
|
|
538
|
+
// it is placed. A placing read is `_$place(props, "key")` (render.js), which
|
|
539
|
+
// the reactivity analysis treats as the property read it is; the server back
|
|
540
|
+
// end renders vnodes, which build where they are placed, and reads
|
|
541
|
+
// `props.<key>`.
|
|
542
|
+
export function deferPlacedProps(fnPath, state) {
|
|
543
|
+
const params = fnPath.node.params;
|
|
544
|
+
if (params.length === 0 && fnPath.isClassMethod({ kind: 'method' }) && !fnPath.node.computed && t.isIdentifier(fnPath.node.key, { name: 'render' })) {
|
|
545
|
+
readThisPropsWhereUsed(fnPath, state);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
// A second parameter that is a name is forwardRef's render function's ref
|
|
549
|
+
// (`({ as: Tag, ...rest }, ref) => …`): the first is still the props.
|
|
550
|
+
if (params.length === 0 || params.length > 2 || (params.length === 2 && !t.isIdentifier(params[1])) || isRowFunction(fnPath, state)) return;
|
|
551
|
+
const param = params[0];
|
|
552
|
+
const rendersJsx = containsJsx(fnPath.node);
|
|
553
|
+
const builds = rendersJsx ? JSX : componentWithoutJsx(fnPath, state);
|
|
554
|
+
if (builds !== H && builds !== PROP) warnDelegatedRender(fnPath, state);
|
|
555
|
+
if (builds === null) return;
|
|
556
|
+
if (builds !== PROP) warnBranchedReturn(fnPath, state);
|
|
557
|
+
// A component that renders JSX or calls h() reads a destructured prop as
|
|
558
|
+
// `props.<key>` where it is used, so a binding or an h() thunk over it
|
|
559
|
+
// (`h('i', {}, () => value)`) follows the parent's state.
|
|
560
|
+
const readsLive = builds !== PROP;
|
|
561
|
+
if (t.isObjectPattern(param)) {
|
|
562
|
+
const found = placedProps(fnPath, param, fnPath.scope, state, readsLive);
|
|
563
|
+
if (found === null || !movesIntoBody(fnPath, found.others)) return;
|
|
564
|
+
const propsId = fnPath.scope.generateUidIdentifier('props');
|
|
565
|
+
if (param.typeAnnotation) propsId.typeAnnotation = param.typeAnnotation;
|
|
566
|
+
readAtUse(fnPath, found, propsId, state);
|
|
567
|
+
params[0] = propsId;
|
|
568
|
+
if (rendersJsx) fnPath.node._whatPropsParam = propsId.name;
|
|
569
|
+
// The parameter was a pattern: `props.<key>()` is a destructured
|
|
570
|
+
// accessor prop's call (auto-selector.js sourceOf).
|
|
571
|
+
fnPath.node._whatPropsPattern = true;
|
|
572
|
+
const declarators = otherProps(fnPath, found, propsId, state);
|
|
573
|
+
if (declarators.length > 0) {
|
|
574
|
+
if (!t.isBlockStatement(fnPath.node.body)) {
|
|
575
|
+
fnPath.node.body = t.blockStatement([t.returnStatement(fnPath.node.body)]);
|
|
576
|
+
}
|
|
577
|
+
fnPath.node.body.body.unshift(t.variableDeclaration('const', declarators));
|
|
578
|
+
// collectSignalNamesFromScope classifies a component's props by reading
|
|
579
|
+
// the parameter list, so the moved pattern has to stay visible to it or
|
|
580
|
+
// every sibling prop silently stops being treated as reactive.
|
|
581
|
+
fnPath.node._whatMovedProps = t.objectPattern(found.others);
|
|
582
|
+
}
|
|
583
|
+
} else if (t.isIdentifier(param)) {
|
|
584
|
+
let binding = fnPath.scope.getBinding(param.name);
|
|
585
|
+
if (!binding || binding.constantViolations.length > 0) return;
|
|
586
|
+
// Its reads `props.<key>` in JSX are bindings (reactivity.js isPropsRead).
|
|
587
|
+
if (rendersJsx) fnPath.node._whatPropsParam = param.name;
|
|
588
|
+
if (rendersJsx && inlinePropAliases(fnPath, binding)) {
|
|
589
|
+
fnPath.scope.crawl();
|
|
590
|
+
binding = fnPath.scope.getBinding(param.name);
|
|
591
|
+
if (!binding) return;
|
|
592
|
+
}
|
|
593
|
+
if (!readPropsWhereUsed(fnPath, binding, param, state, readsLive)) return;
|
|
594
|
+
} else {
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
fnPath.scope.crawl();
|
|
598
|
+
readRestsWhereUsed(fnPath, state, readsLive);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// The reads of the props object `binding` (named `id`) where they are used:
|
|
602
|
+
// a pattern destructured from it in the body (`const { children } = props`)
|
|
603
|
+
// and a read `props.<key>` where it is placed. Whether any was rewritten.
|
|
604
|
+
function readPropsWhereUsed(fnPath, binding, id, state, rendersJsx) {
|
|
605
|
+
const rewrites = [];
|
|
606
|
+
const reads = [];
|
|
607
|
+
const merges = [];
|
|
608
|
+
for (const ref of binding.referencePaths) {
|
|
609
|
+
const decl = ref.parentPath;
|
|
610
|
+
if (!state.ssr && rendersJsx && decl.isSpreadElement() && decl.parentPath.isObjectExpression()) {
|
|
611
|
+
if (!merges.includes(decl.parentPath) && mergesLive(decl.parentPath, fnPath)) merges.push(decl.parentPath);
|
|
612
|
+
} else if (decl.isVariableDeclarator() && ref.key === 'init' && t.isObjectPattern(decl.node.id)) {
|
|
613
|
+
// `const { children } = props` in the body, or in a function of it
|
|
614
|
+
// that renders JSX (`const row = () => { const { a, ...rest } = props; … }`).
|
|
615
|
+
const inner = ref.getFunctionParent();
|
|
616
|
+
if (inner !== fnPath && !containsJsx(inner.node)) continue;
|
|
617
|
+
if (decl.parent.kind === 'var') {
|
|
618
|
+
if (rendersJsx) warnReadOnce(fnPath, state, decl.node.id, `{ ${[...collectNames(decl.node.id)].join(', ')} }`, 'it is declared with `var`', 'declare it with `const`');
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
const found = placedProps(fnPath, decl.node.id, decl.scope, state, rendersJsx);
|
|
622
|
+
if (found !== null) rewrites.push([decl, found]);
|
|
623
|
+
} else if (!state.ssr && decl.isMemberExpression() && ref.key === 'object' && !t.isNumericLiteral(decl.node.property)
|
|
624
|
+
&& propertyName(decl.node.property, decl.node.computed) !== null && placesValue(decl, fnPath, state)) {
|
|
625
|
+
reads.push(decl);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
if (rewrites.length === 0 && reads.length === 0 && merges.length === 0) return false;
|
|
629
|
+
for (const obj of merges) {
|
|
630
|
+
// `{ ...rest, className: 'fixed' }`: the sources merged in order, getters
|
|
631
|
+
// kept (render.js _$merge), where object spread would read each getter
|
|
632
|
+
// once. A name it is declared as is read as the props are (readRestsWhereUsed).
|
|
633
|
+
const parts = [];
|
|
634
|
+
for (const prop of obj.node.properties) {
|
|
635
|
+
if (t.isSpreadElement(prop)) parts.push(prop.argument);
|
|
636
|
+
else if (parts.length > 0 && t.isObjectExpression(parts[parts.length - 1]) && !parts[parts.length - 1]._whatSource) parts[parts.length - 1].properties.push(prop);
|
|
637
|
+
else parts.push(t.objectExpression([prop]));
|
|
638
|
+
}
|
|
639
|
+
for (const part of parts) if (!t.isObjectExpression(part) || part.properties.some((p) => t.isSpreadElement(p))) part._whatSource = true;
|
|
640
|
+
const declarator = obj.parentPath;
|
|
641
|
+
obj.replaceWith(t.callExpression(helper(state, '_$merge'), parts));
|
|
642
|
+
if (declarator.isVariableDeclarator() && t.isIdentifier(declarator.node.id)) {
|
|
643
|
+
declarator.node._whatPropsRest = true;
|
|
644
|
+
(fnPath.node._whatPropsRests ||= []).push(declarator.node.id.name);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
for (const [decl, found] of rewrites) {
|
|
648
|
+
readAtUse(fnPath, found, id, state);
|
|
649
|
+
const declarators = otherProps(fnPath, found, id, state);
|
|
650
|
+
if (declarators.length > 0) decl.replaceWithMultiple(declarators);
|
|
651
|
+
else decl.remove();
|
|
652
|
+
}
|
|
653
|
+
for (const read of reads) read.replaceWith(placingRead(id, propertyName(read.node.property, read.node.computed), state));
|
|
654
|
+
return true;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// Whether the object literal at `obj`, which spreads a props object, can be
|
|
658
|
+
// that object merged with the rest of the literal and still be what the code
|
|
659
|
+
// reads: plain properties and spreads only, either spread straight onto JSX
|
|
660
|
+
// (`<a {...{ ...rest, id }} />`) or the value of a `const` in the component
|
|
661
|
+
// that is only spread (onto JSX or into another literal) and read by key. An
|
|
662
|
+
// object the code hands elsewhere, writes or calls a method of keeps object
|
|
663
|
+
// spread's plain copy.
|
|
664
|
+
function mergesLive(obj, fnPath) {
|
|
665
|
+
if (!obj.node.properties.every((p) => t.isSpreadElement(p)
|
|
666
|
+
|| (t.isObjectProperty(p) && !(propertyName(p.key, p.computed) === '__proto__' && !p.computed)))) return false;
|
|
667
|
+
const parent = obj.parentPath;
|
|
668
|
+
if (parent.isJSXSpreadAttribute()) return true;
|
|
669
|
+
if (!parent.isVariableDeclarator() || obj.key !== 'init' || !t.isIdentifier(parent.node.id)) return false;
|
|
670
|
+
if (parent.parent.kind !== 'const' || parent.getFunctionParent() !== fnPath) return false;
|
|
671
|
+
const binding = parent.scope.getBinding(parent.node.id.name);
|
|
672
|
+
if (!binding || binding.constantViolations.length > 0 || binding.referencePaths.length === 0) return false;
|
|
673
|
+
return binding.referencePaths.every((ref) => {
|
|
674
|
+
const at = ref.parentPath;
|
|
675
|
+
if (at.isJSXSpreadAttribute()) return true;
|
|
676
|
+
if (at.isSpreadElement()) return at.parentPath.isObjectExpression();
|
|
677
|
+
if (!(at.isMemberExpression() && ref.key === 'object' && propertyName(at.node.property, at.node.computed) !== null)) return false;
|
|
678
|
+
const use = at.parentPath;
|
|
679
|
+
return !(use.isAssignmentExpression() && at.key === 'left') && !use.isUpdateExpression()
|
|
680
|
+
&& !(use.isUnaryExpression({ operator: 'delete' })) && !(use.isCallExpression() && at.key === 'callee');
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// A rest element of the props (otherProps marks its declarator,
|
|
685
|
+
// `_whatPropsRest`) holds the props' getters, so it is read the way the props
|
|
686
|
+
// are: destructured again (`const { href, ...more } = rest`), read by key
|
|
687
|
+
// (`rest.href`, a binding in JSX: reactivity.js isPropsRead) and placed
|
|
688
|
+
// (`{rest.children}`). Its own rest elements are, in turn.
|
|
689
|
+
function readRestsWhereUsed(fnPath, state, rendersJsx) {
|
|
690
|
+
const done = new Set();
|
|
691
|
+
for (let pass = 0; pass < 8; pass++) {
|
|
692
|
+
const pending = [];
|
|
693
|
+
fnPath.traverse({
|
|
694
|
+
Function(inner) { inner.skip(); },
|
|
695
|
+
VariableDeclarator(decl) {
|
|
696
|
+
if (decl.node._whatPropsRest === true && !done.has(decl.node)) pending.push(decl);
|
|
697
|
+
},
|
|
698
|
+
});
|
|
699
|
+
if (pending.length === 0) return;
|
|
700
|
+
let changed = false;
|
|
701
|
+
for (const decl of pending) {
|
|
702
|
+
done.add(decl.node);
|
|
703
|
+
const binding = decl.scope.getBinding(decl.node.id.name);
|
|
704
|
+
if (!binding || binding.constantViolations.length > 0) continue;
|
|
705
|
+
if (readPropsWhereUsed(fnPath, binding, t.identifier(decl.node.id.name), state, rendersJsx)) changed = true;
|
|
706
|
+
}
|
|
707
|
+
if (!changed) return;
|
|
708
|
+
fnPath.scope.crawl();
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// A class component's render() that destructures its props
|
|
713
|
+
// (`const { value } = this.props`) reads each name as `this.props.<key>`
|
|
714
|
+
// where it is used: what-core runs a class component once, with the live
|
|
715
|
+
// props object as `this.props`, so a destructured name kept its first value
|
|
716
|
+
// where `{this.props.value}` follows the parent. Only plain names with a
|
|
717
|
+
// static key, read where `this` is the method's (the method itself or arrow
|
|
718
|
+
// functions in it); anything else keeps its destructuring.
|
|
719
|
+
function readThisPropsWhereUsed(fnPath, state) {
|
|
720
|
+
if (state.frameworkFile || !containsJsx(fnPath.node)) return;
|
|
721
|
+
for (const stmt of fnPath.get('body.body')) {
|
|
722
|
+
if (!stmt.isVariableDeclaration({ kind: 'const' })) continue;
|
|
723
|
+
for (const decl of stmt.get('declarations')) {
|
|
724
|
+
const { id, init } = decl.node;
|
|
725
|
+
if (!t.isObjectPattern(id) || !t.isMemberExpression(init) || init.computed || !t.isThisExpression(init.object) || !t.isIdentifier(init.property, { name: 'props' })) continue;
|
|
726
|
+
// A rest element would take in the names moved out of the pattern.
|
|
727
|
+
if (id.properties.some((p) => t.isRestElement(p))) continue;
|
|
728
|
+
const keep = [];
|
|
729
|
+
for (const prop of id.properties) {
|
|
730
|
+
const key = t.isObjectProperty(prop) ? propertyName(prop.key, prop.computed) : null;
|
|
731
|
+
const binding = key !== null && t.isIdentifier(prop.value) ? decl.scope.getBinding(prop.value.name) : null;
|
|
732
|
+
const movable = binding && binding.constantViolations.length === 0 && binding.referencePaths.every((ref) => {
|
|
733
|
+
if (ref.isJSXIdentifier()) return false;
|
|
734
|
+
for (let fn = ref.getFunctionParent(); fn !== fnPath; fn = fn.getFunctionParent()) if (!fn || !fn.isArrowFunctionExpression()) return false;
|
|
735
|
+
return true;
|
|
736
|
+
});
|
|
737
|
+
if (!movable) { keep.push(prop); continue; }
|
|
738
|
+
for (const ref of binding.referencePaths) {
|
|
739
|
+
if (ref.parentPath.isObjectProperty({ shorthand: true }) && ref.key === 'value') ref.parent.shorthand = false;
|
|
740
|
+
const read = t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier('props')), propKey(key), !t.isIdentifier(propKey(key)));
|
|
741
|
+
// A name called as it is (`format()`, a tag, `new`) is called with
|
|
742
|
+
// no receiver: `(0, this.props.format)()`, never with the props as `this`.
|
|
743
|
+
const called = (ref.key === 'callee' && (ref.parentPath.isCallExpression() || ref.parentPath.isOptionalCallExpression() || ref.parentPath.isNewExpression()))
|
|
744
|
+
|| (ref.key === 'tag' && ref.parentPath.isTaggedTemplateExpression());
|
|
745
|
+
ref.replaceWith(called ? t.sequenceExpression([t.numericLiteral(0), read]) : read);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
if (keep.length === id.properties.length) continue;
|
|
749
|
+
if (keep.length === 0) decl.remove();
|
|
750
|
+
else id.properties = keep;
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// --- Aliases of a prop ---
|
|
756
|
+
//
|
|
757
|
+
// `const ev = props.ev;` and then `{ev.label}` read the prop's getter once,
|
|
758
|
+
// where the alias is declared, so the JSX showed the first value forever (in
|
|
759
|
+
// a keyed row, the row's first item). React evaluates it on every render. An
|
|
760
|
+
// alias that is a `const` holding a member chain off props (`props.ev`,
|
|
761
|
+
// `props.ev.item`, `props.ev?.item`, literal keys only), declared in the
|
|
762
|
+
// component's own body and never reassigned, is read as that chain where
|
|
763
|
+
// each read stands: the way a destructured prop is (readAtUse), so a read in
|
|
764
|
+
// JSX is a live binding. An alias of an alias resolves the same way. Any
|
|
765
|
+
// other initializer (a call, arithmetic, `let`) is read once, as before.
|
|
766
|
+
|
|
767
|
+
/** Rewrite the prop aliases of the component `fnPath` whose props are `binding`; whether any was. */
|
|
768
|
+
function inlinePropAliases(fnPath, binding) {
|
|
769
|
+
let changed = false;
|
|
770
|
+
for (let pass = 0; pass < 8; pass++) {
|
|
771
|
+
const aliases = [];
|
|
772
|
+
for (const ref of binding.referencePaths) {
|
|
773
|
+
const alias = propAlias(ref, fnPath);
|
|
774
|
+
if (alias !== null && !aliases.some((a) => a.binding === alias.binding)) aliases.push(alias);
|
|
775
|
+
}
|
|
776
|
+
if (aliases.length === 0) break;
|
|
777
|
+
for (const { decl, binding: alias, init } of aliases) {
|
|
778
|
+
for (const read of alias.referencePaths) {
|
|
779
|
+
if (read.parentPath.isObjectProperty({ shorthand: true }) && read.key === 'value') read.parent.shorthand = false;
|
|
780
|
+
read.replaceWith(t.cloneNode(init, true));
|
|
781
|
+
}
|
|
782
|
+
decl.remove();
|
|
783
|
+
}
|
|
784
|
+
changed = true;
|
|
785
|
+
fnPath.scope.crawl();
|
|
786
|
+
const next = fnPath.scope.getBinding(/** @type {any} */ (binding.identifier).name);
|
|
787
|
+
if (!next) break;
|
|
788
|
+
binding = next;
|
|
789
|
+
}
|
|
790
|
+
return changed;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
// The alias `const name = <ref>.a.b` that the props reference `ref` starts,
|
|
794
|
+
// as { decl, binding, init }, or null.
|
|
795
|
+
function propAlias(ref, fnPath) {
|
|
796
|
+
let top = ref;
|
|
797
|
+
for (;;) {
|
|
798
|
+
const parent = top.parentPath;
|
|
799
|
+
if (!(parent.isMemberExpression() || parent.isOptionalMemberExpression()) || top.key !== 'object') break;
|
|
800
|
+
if (parent.node.computed && propertyName(parent.node.property, true) === null) return null;
|
|
801
|
+
top = parent;
|
|
802
|
+
}
|
|
803
|
+
if (top === ref) return null;
|
|
804
|
+
const decl = top.parentPath;
|
|
805
|
+
if (!decl.isVariableDeclarator() || top.key !== 'init' || !t.isIdentifier(decl.node.id)) return null;
|
|
806
|
+
if (decl.parent.kind !== 'const' || decl.getFunctionParent() !== fnPath) return null;
|
|
807
|
+
const alias = decl.scope.getBinding(decl.node.id.name);
|
|
808
|
+
if (!alias || alias.constantViolations.length > 0 || alias.referencePaths.length === 0) return null;
|
|
809
|
+
// A tag (`<ev.Icon />`) names a component, not a value to read live.
|
|
810
|
+
if (alias.referencePaths.some((read) => read.isJSXIdentifier())) return null;
|
|
811
|
+
// JSX handed in a prop is built when it is read (render.js _$slots): an
|
|
812
|
+
// alias of it, read in the run, is that build, which a thunk running later
|
|
813
|
+
// indexes (`{() => panels[at()]}`, core test lazy-props). So `children`,
|
|
814
|
+
// which is always JSX, and an alias read with a computed key keep the
|
|
815
|
+
// value they read in the run.
|
|
816
|
+
const first = t.isMemberExpression(top.node) || t.isOptionalMemberExpression(top.node) ? firstKey(top.node) : null;
|
|
817
|
+
if (first === 'children') return null;
|
|
818
|
+
if (alias.referencePaths.some((read) => (read.parentPath.isMemberExpression() || read.parentPath.isOptionalMemberExpression())
|
|
819
|
+
&& read.key === 'object' && read.parent.computed && propertyName(read.parent.property, true) === null)) return null;
|
|
820
|
+
return { decl, binding: alias, init: top.node };
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// The first key read off the root of the member chain `node` (`props.a.b` → 'a').
|
|
824
|
+
function firstKey(node) {
|
|
825
|
+
while (t.isMemberExpression(node.object) || t.isOptionalMemberExpression(node.object)) node = node.object;
|
|
826
|
+
return propertyName(node.property, node.computed);
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// --- Fields of props read in a component's run ---
|
|
830
|
+
//
|
|
831
|
+
// A keyed `.map()` row hands a component its item through a getter
|
|
832
|
+
// (`get item() { return _$item(cell) }`). A read of the item by the code that
|
|
833
|
+
// builds the row records what it read (what-core reactive.js _rowItem), and a
|
|
834
|
+
// getter cannot tell which field the component goes on to read: `props.item.id`
|
|
835
|
+
// in the body recorded the whole item, so any replacement under the key built
|
|
836
|
+
// the row again, with the component's state. So a member read of a prop,
|
|
837
|
+
// `props.<name>.<key>` with both keys static (`item.id` for a destructured
|
|
838
|
+
// `item`), reads as `_$propField(props, "name", "key")` (render.js), which
|
|
839
|
+
// records the field `key` when the getter returns the row's item as it is:
|
|
840
|
+
// - where the component's run reads it: its body, and functions of it, which
|
|
841
|
+
// read the item once when they run during the build and plainly after;
|
|
842
|
+
// - in a prop it hands a component (`<Title text={props.item.title} />`),
|
|
843
|
+
// whose getter the child's body reads.
|
|
844
|
+
// A read in the JSX that builds elements is a binding, which follows the
|
|
845
|
+
// item, and stays as it is. A call (`props.item.format()`), a write, an
|
|
846
|
+
// optional chain and the server back end keep the read as written. The reads
|
|
847
|
+
// are marked here, before JSX is lowered, and rewritten once it is
|
|
848
|
+
// (readPropFields), so the reactivity analysis sees the member reads they are.
|
|
849
|
+
|
|
850
|
+
/** Mark the member reads of props that readPropFields rewrites, in the component `fnPath`. */
|
|
851
|
+
export function markPropFieldReads(fnPath, state) {
|
|
852
|
+
const name = fnPath.node._whatPropsParam;
|
|
853
|
+
if (state.ssr || name === undefined) return;
|
|
854
|
+
const binding = fnPath.scope.getBinding(name);
|
|
855
|
+
if (!binding || binding.kind !== 'param' || binding.constantViolations.length > 0) return;
|
|
856
|
+
for (const ref of binding.referencePaths) {
|
|
857
|
+
const inner = ref.parentPath;
|
|
858
|
+
if (!inner.isMemberExpression() || ref.key !== 'object') continue;
|
|
859
|
+
const outer = inner.parentPath;
|
|
860
|
+
if (!outer.isMemberExpression() || inner.key !== 'object') continue;
|
|
861
|
+
const prop = propertyName(inner.node.property, inner.node.computed);
|
|
862
|
+
if (prop === null || prop === 'children' || propertyName(outer.node.property, outer.node.computed) === null) continue;
|
|
863
|
+
if (!isReadOnly(outer) || !inComponentRun(outer, fnPath)) continue;
|
|
864
|
+
outer.node._whatPropField = true;
|
|
865
|
+
state.marksPropFields = true;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// Whether the member expression `path` is only read: not called as a method,
|
|
870
|
+
// a tag, written, deleted or a pattern's target.
|
|
871
|
+
function isReadOnly(path) {
|
|
872
|
+
const parent = path.parent;
|
|
873
|
+
const key = path.key;
|
|
874
|
+
if ((t.isCallExpression(parent) || t.isOptionalCallExpression(parent) || t.isNewExpression(parent)) && key === 'callee') return false;
|
|
875
|
+
if (t.isTaggedTemplateExpression(parent) && key === 'tag') return false;
|
|
876
|
+
if ((t.isAssignmentExpression(parent) || t.isForInStatement(parent) || t.isForOfStatement(parent)) && key === 'left') return false;
|
|
877
|
+
if (t.isUpdateExpression(parent) || t.isUnaryExpression(parent, { operator: 'delete' })) return false;
|
|
878
|
+
return !(t.isArrayPattern(parent) || t.isRestElement(parent) || (t.isAssignmentPattern(parent) && key === 'left') || (t.isObjectProperty(parent) && t.isObjectPattern(path.parentPath.parent)));
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// Whether `path`, in the component `fnPath`, is read by the component's run
|
|
882
|
+
// rather than by a binding of its JSX: outside JSX, or in the value of a prop
|
|
883
|
+
// handed to a component, outside any function there.
|
|
884
|
+
function inComponentRun(path, fnPath) {
|
|
885
|
+
let inFunction = false;
|
|
886
|
+
for (let p = path.parentPath; p !== null && p !== fnPath; p = p.parentPath) {
|
|
887
|
+
if (p.isFunction()) inFunction = true;
|
|
888
|
+
else if (p.isJSXExpressionContainer()) {
|
|
889
|
+
const attr = p.parentPath;
|
|
890
|
+
if (inFunction || !attr.isJSXAttribute() || !t.isJSXIdentifier(attr.node.name) || attr.node.name.name === 'key' || attr.node.name.name === 'ref') return false;
|
|
891
|
+
return isComponentElement(attr.parentPath.parent);
|
|
892
|
+
} else if (p.isJSXElement() || p.isJSXFragment() || p.isJSXSpreadAttribute() || p.isJSXSpreadChild()) return false;
|
|
893
|
+
}
|
|
894
|
+
return true;
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
/**
|
|
898
|
+
* Rewrite each marked member read of props (markPropFieldReads) as
|
|
899
|
+
* `_$propField(props, "name", "key")`, with the ERR_PROP_READ_ONCE record of
|
|
900
|
+
* a value derived from it that the page checks (warnDerivedPropOnce) as a
|
|
901
|
+
* fourth argument. A value whose reads are not all rewritten is reported
|
|
902
|
+
* now, at build time.
|
|
903
|
+
*/
|
|
904
|
+
export function readPropFields(path, state) {
|
|
905
|
+
for (const check of state._readOnceChecks ?? []) {
|
|
906
|
+
if (check.nodes.every((node) => node._whatPropField === true)) continue;
|
|
907
|
+
for (const node of check.nodes) node._whatReadOnce = undefined;
|
|
908
|
+
check.warn();
|
|
909
|
+
}
|
|
910
|
+
if (!state.marksPropFields) return;
|
|
911
|
+
/** @type {any[]} */
|
|
912
|
+
const records = [];
|
|
913
|
+
path.traverse({
|
|
914
|
+
MemberExpression(member) {
|
|
915
|
+
const node = member.node;
|
|
916
|
+
if (node._whatPropField !== true) return;
|
|
917
|
+
const inner = /** @type {any} */ (node.object);
|
|
918
|
+
const args = [
|
|
919
|
+
t.identifier(inner.object.name),
|
|
920
|
+
t.stringLiteral(/** @type {string} */ (propertyName(inner.property, inner.computed))),
|
|
921
|
+
t.stringLiteral(/** @type {string} */ (propertyName(node.property, node.computed))),
|
|
922
|
+
];
|
|
923
|
+
const check = node._whatReadOnce;
|
|
924
|
+
if (check) {
|
|
925
|
+
if (check.id === null) {
|
|
926
|
+
check.id = path.scope.generateUidIdentifier('readOnce');
|
|
927
|
+
records.push(t.variableDeclarator(check.id, diagnosticRecord(check.record)));
|
|
928
|
+
}
|
|
929
|
+
args.push(t.identifier(check.id.name));
|
|
930
|
+
}
|
|
931
|
+
member.replaceWith(t.callExpression(helper(state, '_$propField'), args));
|
|
932
|
+
},
|
|
933
|
+
});
|
|
934
|
+
if (records.length > 0) path.unshiftContainer('body', t.variableDeclaration('const', records));
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// --- Which functions are components ---
|
|
938
|
+
// Reading props where they are used changes what a function's parameter
|
|
939
|
+
// reads (`_$place`, `_$omit`, `props.<key>` for a destructured name), so it
|
|
940
|
+
// applies to a component only:
|
|
941
|
+
// - a function that renders JSX (JSX anywhere in its body, nested callbacks
|
|
942
|
+
// included), whatever its name: a component, a memo() or forwardRef()
|
|
943
|
+
// render function, a render helper;
|
|
944
|
+
// - a function with no JSX that is named as a component (`function Card`,
|
|
945
|
+
// `const Card = …`, `memo(…)` or `forwardRef(…)` assigned to `Card`,
|
|
946
|
+
// `Tabs.Panel = …`, a default export) and renders as one: it calls What's
|
|
947
|
+
// h() (imported from what-framework or what-core), so
|
|
948
|
+
// `function Box({ as, ...rest }) { return h(as, rest) }` keeps `rest` live,
|
|
949
|
+
// or it returns a prop as it is (`return props.children`,
|
|
950
|
+
// `({ children }) => children`), which is placed where it renders.
|
|
951
|
+
// Nothing else is: a helper that destructures its argument, capitalised or
|
|
952
|
+
// not (`function Point({ x, y, ...rest })` returning an object), a
|
|
953
|
+
// forwardRef() implementation that calls the render function it was given
|
|
954
|
+
// (what-react's `ForwardRefComponent`), a higher-order component that calls
|
|
955
|
+
// the component it wraps, a reducer, a class's method. In What's own packages
|
|
956
|
+
// (framework-files.js) only a function that renders JSX is.
|
|
957
|
+
//
|
|
958
|
+
// Two more call What's h() and so render as one with no name of a component:
|
|
959
|
+
// a function a factory returns (`const Make = () => ({ value }) => h(…)`)
|
|
960
|
+
// and a hook handed props (`function useLook({ value }) { return h(…); }`).
|
|
961
|
+
const JSX = 1, H = 2, PROP = 3, CALL = 4;
|
|
962
|
+
|
|
963
|
+
/** How a function with no JSX renders as a component (H, PROP), else null. */
|
|
964
|
+
function componentWithoutJsx(fnPath, state) {
|
|
965
|
+
if (state.frameworkFile) return null;
|
|
966
|
+
if (callsWhatH(fnPath)) return namedAsComponent(fnPath) || returnedByFunction(fnPath) || /^use[A-Z]/.test(componentName(fnPath)) ? H : null;
|
|
967
|
+
if (handsHelperProps(fnPath, state)) return CALL;
|
|
968
|
+
return namedAsComponent(fnPath) && returnsProp(fnPath) ? PROP : null;
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// `() => (props) => …`, `function make() { return function (props) { … }; }`.
|
|
972
|
+
function returnedByFunction(fnPath) {
|
|
973
|
+
const parent = fnPath.parentPath;
|
|
974
|
+
if (parent.isArrowFunctionExpression() && fnPath.key === 'body') return true;
|
|
975
|
+
return parent.isReturnStatement() && parent.getFunctionParent() !== null;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
function namedAsComponent(fnPath) {
|
|
979
|
+
if (/^[A-Z]/.test(componentName(fnPath))) return true;
|
|
980
|
+
let at = fnPath.parentPath;
|
|
981
|
+
while (at && at.isCallExpression()) at = at.parentPath;
|
|
982
|
+
if (!at) return false;
|
|
983
|
+
if (at.isExportDefaultDeclaration()) return true;
|
|
984
|
+
// `Tabs.Panel = (props) => …`, `{ Panel: (props) => … }`.
|
|
985
|
+
if (at.isAssignmentExpression() && t.isMemberExpression(at.node.left) && !at.node.left.computed) return /^[A-Z]/.test(at.node.left.property.name || '');
|
|
986
|
+
return at.isObjectProperty() && !at.node.computed && t.isIdentifier(at.node.key) && /^[A-Z]/.test(at.node.key.name);
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
// A call of What's h(): `h(…)` imported from a What module, or `ns.h(…)` of
|
|
990
|
+
// a namespace import of one.
|
|
991
|
+
function callsWhatH(fnPath) {
|
|
992
|
+
let found = false;
|
|
993
|
+
fnPath.traverse({
|
|
994
|
+
CallExpression(call) {
|
|
995
|
+
if (found) return call.stop();
|
|
996
|
+
const callee = call.node.callee;
|
|
997
|
+
if (t.isIdentifier(callee)) found = importedFrom(call.scope.getBinding(callee.name), t.isImportSpecifier, 'h');
|
|
998
|
+
else if (t.isMemberExpression(callee) && !callee.computed && t.isIdentifier(callee.property, { name: 'h' }) && t.isIdentifier(callee.object)) {
|
|
999
|
+
found = importedFrom(call.scope.getBinding(callee.object.name), t.isImportNamespaceSpecifier, null);
|
|
1000
|
+
}
|
|
1001
|
+
if (found) call.stop();
|
|
1002
|
+
},
|
|
1003
|
+
});
|
|
1004
|
+
return found;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Whether the function returns one of its props as it is: `props.<key>`, a
|
|
1008
|
+
// name destructured from its props (in the parameter list or from the props
|
|
1009
|
+
// in its body), in a branch of a conditional, a logical expression or an
|
|
1010
|
+
// array.
|
|
1011
|
+
function returnsProp(fnPath) {
|
|
1012
|
+
const param = fnPath.node.params[0];
|
|
1013
|
+
const isProp = (node) => {
|
|
1014
|
+
while (t.isTSAsExpression(node) || t.isTSSatisfiesExpression(node) || t.isTSNonNullExpression(node) || t.isParenthesizedExpression(node)) node = node.expression;
|
|
1015
|
+
if (t.isConditionalExpression(node)) return isProp(node.consequent) || isProp(node.alternate);
|
|
1016
|
+
if (t.isLogicalExpression(node)) return isProp(node.left) || isProp(node.right);
|
|
1017
|
+
if (t.isArrayExpression(node)) return node.elements.some((e) => e !== null && isProp(e));
|
|
1018
|
+
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
|
1019
|
+
let root = node;
|
|
1020
|
+
while (t.isMemberExpression(root) || t.isOptionalMemberExpression(root)) root = root.object;
|
|
1021
|
+
return t.isIdentifier(param) && t.isIdentifier(root, { name: param.name }) && fnPath.scope.getBinding(param.name)?.kind === 'param';
|
|
1022
|
+
}
|
|
1023
|
+
if (!t.isIdentifier(node)) return false;
|
|
1024
|
+
const binding = fnPath.scope.getBinding(node.name);
|
|
1025
|
+
if (!binding || binding.scope !== fnPath.scope) return false;
|
|
1026
|
+
if (binding.kind === 'param') return t.isObjectPattern(param) && binding.path.parentPath?.node === fnPath.node;
|
|
1027
|
+
const decl = binding.path;
|
|
1028
|
+
return decl.isVariableDeclarator() && t.isObjectPattern(decl.node.id) && t.isIdentifier(param)
|
|
1029
|
+
&& t.isIdentifier(decl.node.init, { name: param.name });
|
|
1030
|
+
};
|
|
1031
|
+
const body = fnPath.node.body;
|
|
1032
|
+
if (!t.isBlockStatement(body)) return isProp(body);
|
|
1033
|
+
let found = false;
|
|
1034
|
+
fnPath.traverse({
|
|
1035
|
+
Function(inner) { inner.skip(); },
|
|
1036
|
+
ReturnStatement(ret) {
|
|
1037
|
+
if (!found && ret.node.argument && isProp(ret.node.argument)) found = true;
|
|
1038
|
+
},
|
|
1039
|
+
});
|
|
1040
|
+
return found;
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// Whether a function renders JSX: JSX anywhere in its body, nested callbacks
|
|
1044
|
+
// included (`items.map((i) => <li />)`).
|
|
1045
|
+
function containsJsx(fn) {
|
|
1046
|
+
let found = false;
|
|
1047
|
+
t.traverseFast(fn.body, (node) => {
|
|
1048
|
+
if (node.type === 'JSXElement' || node.type === 'JSXFragment') found = true;
|
|
1049
|
+
});
|
|
1050
|
+
return found;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
// A callback a method calls (`.map(row => …)`, `.then(…)`), the row
|
|
1054
|
+
// function of a <For>, or a function an attribute passes (a <For>'s `key`,
|
|
1055
|
+
// an event handler, a render prop): its parameter is an item or an event,
|
|
1056
|
+
// not props, and the list lowerings read a row's fields themselves
|
|
1057
|
+
// (lists.js).
|
|
1058
|
+
function isRowFunction(fnPath, state) {
|
|
1059
|
+
const parent = fnPath.parentPath;
|
|
1060
|
+
if (parent.isCallExpression() && fnPath.listKey === 'arguments') return t.isMemberExpression(parent.node.callee) || t.isOptionalMemberExpression(parent.node.callee);
|
|
1061
|
+
if (!parent.isJSXExpressionContainer()) return false;
|
|
1062
|
+
return parent.parentPath.isJSXAttribute() || (parent.parentPath.isJSXElement() && isLoweredTag(parent.parentPath.node, 'For', state));
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// The properties of `pattern` read where they are used (`placed`: each read
|
|
1066
|
+
// places the value; `live`: in a function that renders JSX, read as
|
|
1067
|
+
// `props.<key>`; each with its key, binding and literal default), else null
|
|
1068
|
+
// when there are none. `others` are the pattern's other properties, and
|
|
1069
|
+
// `rest` its rest element.
|
|
1070
|
+
function placedProps(fnPath, pattern, scope, state, rendersJsx) {
|
|
1071
|
+
const counts = new Map();
|
|
1072
|
+
for (const prop of pattern.properties) {
|
|
1073
|
+
const name = t.isObjectProperty(prop) ? propertyName(prop.key, prop.computed) : null;
|
|
1074
|
+
if (name !== null) counts.set(name, (counts.get(name) || 0) + 1);
|
|
1075
|
+
}
|
|
1076
|
+
const placed = [];
|
|
1077
|
+
const live = [];
|
|
1078
|
+
const others = [];
|
|
1079
|
+
for (const prop of pattern.properties) {
|
|
1080
|
+
const entry = t.isObjectProperty(prop) ? readProp(fnPath, prop, scope) : null;
|
|
1081
|
+
// `{ style: { color } }`: each name is read as `props.style.color` where
|
|
1082
|
+
// it is used, as a live prop is, in a function that renders JSX.
|
|
1083
|
+
const nested = entry === null && rendersJsx && t.isObjectProperty(prop) ? nestedProps(fnPath, prop, scope) : null;
|
|
1084
|
+
if (nested !== null && counts.get(nested[0].key) === 1
|
|
1085
|
+
&& nested.every((leaf) => leaf.binding.referencePaths.every((ref) => !ref.isJSXIdentifier()))) {
|
|
1086
|
+
live.push(...nested);
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
// A second key would still read the getter where it is destructured.
|
|
1090
|
+
if (entry === null || counts.get(entry.key) !== 1) {
|
|
1091
|
+
others.push(prop);
|
|
1092
|
+
if (rendersJsx && t.isObjectProperty(prop)) readOnce(fnPath, state, prop, counts);
|
|
1093
|
+
} else if (entry.binding.referencePaths.every((ref) => placesValue(ref, fnPath, state))) placed.push(entry);
|
|
1094
|
+
else if (rendersJsx && entry.binding.referencePaths.every((ref) => !ref.isJSXIdentifier())) live.push(entry);
|
|
1095
|
+
else others.push(prop);
|
|
1096
|
+
}
|
|
1097
|
+
const last = others[others.length - 1];
|
|
1098
|
+
const rest = t.isRestElement(last) ? last : null;
|
|
1099
|
+
// A rest element is always built here, even with no prop read where it is
|
|
1100
|
+
// used: destructured natively it would read every getter once
|
|
1101
|
+
// (`({ as: Tag, ...rest }) => <Tag {...rest} />` showed the first `href`
|
|
1102
|
+
// forever), where _$omit keeps them.
|
|
1103
|
+
if (placed.length === 0 && live.length === 0 && rest === null) return null;
|
|
1104
|
+
// The rest object is built by naming the keys it leaves out.
|
|
1105
|
+
if (rest !== null && (!t.isIdentifier(rest.argument)
|
|
1106
|
+
|| others.some((p) => t.isObjectProperty(p) && propertyName(p.key, p.computed) === null))) {
|
|
1107
|
+
if (rendersJsx && t.isIdentifier(rest.argument)) warnReadOnce(fnPath, state, rest, `...${rest.argument.name}`, 'the pattern has a computed key, so the keys the rest element leaves out are not known', `name the keys (\`const { [key]: v } = props\` apart from \`const { a, ...${rest.argument.name} } = props\`)`);
|
|
1108
|
+
return null;
|
|
1109
|
+
}
|
|
1110
|
+
return { placed, live, others, rest };
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// --- ERR_PROP_READ_ONCE ---
|
|
1114
|
+
// A destructured prop the compiler cannot read where it is used is read once,
|
|
1115
|
+
// when the component runs, and keeps that value when the parent's state
|
|
1116
|
+
// changes, where React would render the new one. That is never silent: a
|
|
1117
|
+
// development build says so at compile time, with the fix.
|
|
1118
|
+
|
|
1119
|
+
/** Report why the destructured prop `prop` is read once, if it is used. */
|
|
1120
|
+
function readOnce(fnPath, state, prop, counts) {
|
|
1121
|
+
const key = propertyName(prop.key, prop.computed);
|
|
1122
|
+
const value = t.isAssignmentPattern(prop.value) ? prop.value.left : prop.value;
|
|
1123
|
+
const name = t.isIdentifier(value) ? value.name : key ?? '(pattern)';
|
|
1124
|
+
if (t.isIdentifier(value)) {
|
|
1125
|
+
const binding = fnPath.scope.getBinding(value.name);
|
|
1126
|
+
if (!binding || binding.referencePaths.length === 0) return;
|
|
1127
|
+
// A component held in a prop and used as a tag (`as: Tag`) is read where
|
|
1128
|
+
// the component runs by design: see docs/GOTCHAS.md.
|
|
1129
|
+
if (binding.referencePaths.some((ref) => ref.isJSXIdentifier())) return;
|
|
1130
|
+
if (binding.constantViolations.length > 0) {
|
|
1131
|
+
return warnReadOnce(fnPath, state, prop, name, 'it is assigned again in the component', `leave the prop as it is and write a new name (\`const shown = () => props.${key ?? name} ?? fallback\`)`);
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
if (key === null) return warnReadOnce(fnPath, state, prop, name, 'its key is computed', 'read `props[key]` where it is used');
|
|
1135
|
+
if (counts.get(key) !== 1) return warnReadOnce(fnPath, state, prop, name, `\`${key}\` is destructured twice`, 'destructure it once');
|
|
1136
|
+
if (t.isAssignmentPattern(prop.value)) {
|
|
1137
|
+
return warnReadOnce(fnPath, state, prop, name, 'its default reads a name of the component or calls something', `read \`props.${key} ?? <default>\` where it is used, or make the default a constant at module scope`);
|
|
1138
|
+
}
|
|
1139
|
+
if (t.isObjectPattern(value) || t.isArrayPattern(value)) {
|
|
1140
|
+
return warnReadOnce(fnPath, state, prop, name, 'its pattern holds a rest element, an array, a computed key or a default that is not a literal', `read \`props.${key}\` where it is used`);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
const warnedReadOnce = new Set();
|
|
1145
|
+
|
|
1146
|
+
// The names of `fnPath`'s props, for a test that reads one: the names its
|
|
1147
|
+
// pattern binds, or `props.<key>` of a props parameter. Each as
|
|
1148
|
+
// [the name to report, a predicate over a node].
|
|
1149
|
+
function propReader(fnPath) {
|
|
1150
|
+
const param = fnPath.node.params[0];
|
|
1151
|
+
if (t.isIdentifier(param)) {
|
|
1152
|
+
return (node) => (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) && t.isIdentifier(node.object, { name: param.name })
|
|
1153
|
+
&& !node.computed && t.isIdentifier(node.property) && fnPath.scope.getBinding(param.name)?.kind === 'param' ? `props.${node.property.name}` : null;
|
|
1154
|
+
}
|
|
1155
|
+
if (!t.isObjectPattern(param)) return null;
|
|
1156
|
+
const names = collectNames(param);
|
|
1157
|
+
return (node) => t.isIdentifier(node) && names.has(node.name) && fnPath.scope.getBinding(node.name)?.kind === 'param' ? node.name : null;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
/**
|
|
1161
|
+
* The first read `read` names in `node`, outside a function written in it.
|
|
1162
|
+
* @template T
|
|
1163
|
+
* @param {any} node
|
|
1164
|
+
* @param {(n: any) => T | null} read
|
|
1165
|
+
* @returns {T | null}
|
|
1166
|
+
*/
|
|
1167
|
+
function propReadIn(node, read) {
|
|
1168
|
+
/** @type {T | null} */
|
|
1169
|
+
let found = null;
|
|
1170
|
+
const visit = (n) => {
|
|
1171
|
+
if (found !== null || !n || typeof n !== 'object') return;
|
|
1172
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
1173
|
+
if (typeof n.type !== 'string' || t.isFunction(n)) return;
|
|
1174
|
+
found = read(n);
|
|
1175
|
+
if (found !== null) return;
|
|
1176
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
1177
|
+
};
|
|
1178
|
+
visit(node);
|
|
1179
|
+
return found;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// A component that decides what it returns from a prop (`return on ? <a /> :
|
|
1183
|
+
// <b />`, `if (!open) return null;`, `value ? h('i') : null`) decides once,
|
|
1184
|
+
// when it runs: the parent's later state does not change which branch it
|
|
1185
|
+
// shows, where React renders the other one.
|
|
1186
|
+
function warnBranchedReturn(fnPath, state) {
|
|
1187
|
+
if (process.env.NODE_ENV === 'production' || state.ssr || !isComponentFunction(fnPath)) return;
|
|
1188
|
+
const read = propReader(fnPath);
|
|
1189
|
+
if (read === null) return;
|
|
1190
|
+
for (const test of returnTests(fnPath.node.body)) {
|
|
1191
|
+
const name = propReadIn(test, read);
|
|
1192
|
+
if (name === null) continue;
|
|
1193
|
+
warnReadOnce(fnPath, state, test, name, 'it decides what the component returns, and the component runs once',
|
|
1194
|
+
'branch where it renders, `<>{() => (cond ? <A /> : <B />)}</>` or `<Show when={…}>`, with h() `() => (cond ? h(…) : null)`');
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
// --- A branch a component returns ---
|
|
1200
|
+
// `function Badge({ value }) { if (!value) return null; return <i>{value}</i>; }`
|
|
1201
|
+
// and `return value ? <i>{value}</i> : null` decide what the component returns
|
|
1202
|
+
// from a prop, as React code does. A component runs once, so the branch it
|
|
1203
|
+
// took first would stay. So the body, from the first statement whose return
|
|
1204
|
+
// depends on a prop or on the component's own state (liveReader), is
|
|
1205
|
+
// lowered to the branch it means, the one `<>{value ? <i>{value}</i> : null}</>`
|
|
1206
|
+
// is: `if (T) return A; …; return B` reads `T ? A : B`, with the statements
|
|
1207
|
+
// between two returns in their branch. The condition is memoized and a branch
|
|
1208
|
+
// is built when it is shown, as <Show> builds its children, so an update
|
|
1209
|
+
// inside the shown branch is fine-grained. The code before that statement
|
|
1210
|
+
// runs once, when the component does; the statements of a branch run each time
|
|
1211
|
+
// it is shown, untracked, so their hooks and signals are made again then, and
|
|
1212
|
+
// a value they compute is that moment's. A `switch` whose cases all return is
|
|
1213
|
+
// lowered the same way. A shape this cannot lower keeps ERR_PROP_READ_ONCE or
|
|
1214
|
+
// ERR_STATE_READ_ONCE: a return in a loop or a `try`, a `var`, a `break` out
|
|
1215
|
+
// of a `switch` or of a labeled block, an arm that runs on into code another
|
|
1216
|
+
// arm runs too, and h() code, which does not compile.
|
|
1217
|
+
//
|
|
1218
|
+
// A component with no JSX that the module renders as one and returns text
|
|
1219
|
+
// (rendersText: `if (!n) return 'none'; return n + ' items'`) is lowered the
|
|
1220
|
+
// same way, and a text it returns that reads a live value is a fragment's
|
|
1221
|
+
// hole (`return <>{n + ' items'}</>`), so the text follows it.
|
|
1222
|
+
|
|
1223
|
+
/** Lower the branch the component `fnPath` returns, when it depends on a prop or on its state. */
|
|
1224
|
+
export function lowerLiveReturns(fnPath, state) {
|
|
1225
|
+
if (state.frameworkFile || fnPath.node.async || fnPath.node.generator || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
1226
|
+
const output = componentOutput(fnPath, state);
|
|
1227
|
+
if (output === null) return;
|
|
1228
|
+
const text = output === TEXT;
|
|
1229
|
+
const live = returnReader(fnPath);
|
|
1230
|
+
const body = fnPath.node.body;
|
|
1231
|
+
// Each condition the branch is decided on, and each text shown, that reads
|
|
1232
|
+
// a live value is marked (_whatLive) for the JSX compiler (reactivity.js
|
|
1233
|
+
// isPotentiallyReactive), which follows only the reads it sees made: a
|
|
1234
|
+
// store's field off a hook another module exports (`const todos =
|
|
1235
|
+
// useTodos(); if (todos.remaining === 0)`) is a property of an imported
|
|
1236
|
+
// function's result, which it reads once, unless the module hands `todos`
|
|
1237
|
+
// where it cannot follow (a branch's `{() => todos.remaining}`). Marked,
|
|
1238
|
+
// the condition is a memo on both targets, as for a store of the module.
|
|
1239
|
+
if (!t.isBlockStatement(body)) {
|
|
1240
|
+
const expr = unwrapExpr(body);
|
|
1241
|
+
if (text ? readsLive(expr, live) : isBranch(expr) && liveTest(expr, live)) {
|
|
1242
|
+
(text ? expr : t.isConditionalExpression(expr) ? expr.test : expr.left)._whatLive = true;
|
|
1243
|
+
fnPath.node.body = branchFragment(body);
|
|
1244
|
+
fnPath.scope.crawl();
|
|
1245
|
+
}
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
if (!state.ssr && !state.opts?.production && process.env.NODE_ENV !== 'production') warnHookSnapshots(fnPath, state);
|
|
1249
|
+
const start = body.body.findIndex((s) => holdsReturn(s) && branchTests(s).some((test) => readsLive(test, live)));
|
|
1250
|
+
if (start !== -1) {
|
|
1251
|
+
for (const stmt of body.body.slice(start)) for (const test of branchTests(stmt)) if (readsLive(test, live)) test._whatLive = true;
|
|
1252
|
+
lowerBody(fnPath, state, start, text);
|
|
1253
|
+
}
|
|
1254
|
+
if (text) showText(fnPath, live);
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
|
|
1258
|
+
function lowerBody(fnPath, state, start, text) {
|
|
1259
|
+
const body = fnPath.node.body;
|
|
1260
|
+
const prefix = body.body.slice(0, start);
|
|
1261
|
+
const tail = body.body.slice(start);
|
|
1262
|
+
// A function declared after a return is hoisted: it stays where the code
|
|
1263
|
+
// before the branch can call it.
|
|
1264
|
+
const hoisted = tail.filter((s) => t.isFunctionDeclaration(s));
|
|
1265
|
+
const moved = tail.filter((s) => !t.isFunctionDeclaration(s));
|
|
1266
|
+
if (!movable(fnPath, moved)) return;
|
|
1267
|
+
const arm = state.ssr
|
|
1268
|
+
? (stmts) => t.callExpression(t.arrowFunctionExpression([], t.blockStatement(stmts)), [])
|
|
1269
|
+
: (stmts) => t.callExpression(helper(state, '_$untrack'), [t.arrowFunctionExpression([], t.blockStatement(stmts))]);
|
|
1270
|
+
const lowered = lowerTail(moved, arm, state);
|
|
1271
|
+
if (lowered === null) return;
|
|
1272
|
+
body.body = [...prefix, ...hoisted, t.returnStatement((text && !t.isJSXFragment(lowered) && lowered._whatSwitch !== true) || isBranch(lowered) ? branchFragment(lowered) : lowered)];
|
|
1273
|
+
fnPath.scope.crawl();
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// Each text the component returns, outside a fragment the lowering made,
|
|
1277
|
+
// that reads a live value, as a fragment's hole.
|
|
1278
|
+
function showText(fnPath, live) {
|
|
1279
|
+
let changed = false;
|
|
1280
|
+
fnPath.traverse({
|
|
1281
|
+
Function(inner) { inner.skip(); },
|
|
1282
|
+
ReturnStatement(ret) {
|
|
1283
|
+
const arg = ret.node.argument;
|
|
1284
|
+
if (!arg || t.isJSXFragment(arg) || !readsLive(arg, live)) return;
|
|
1285
|
+
arg._whatLive = true;
|
|
1286
|
+
ret.node.argument = branchFragment(arg);
|
|
1287
|
+
changed = true;
|
|
1288
|
+
},
|
|
1289
|
+
});
|
|
1290
|
+
if (changed) fnPath.scope.crawl();
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// What a component's run builds, for the passes that follow a value it reads:
|
|
1294
|
+
// JSX (anywhere in it), or text a component with no JSX returns (rendersText),
|
|
1295
|
+
// else null. Kept on the function, since a lowering adds JSX to it.
|
|
1296
|
+
const TEXT = 'text';
|
|
1297
|
+
function componentOutput(fnPath, state) {
|
|
1298
|
+
const node = fnPath.node;
|
|
1299
|
+
if (node._whatOutput === undefined) node._whatOutput = containsJsx(node) ? JSX : rendersText(fnPath, state) ? TEXT : null;
|
|
1300
|
+
return node._whatOutput;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
// A function with no JSX that the module renders as a component (`<Count n={…} />`)
|
|
1304
|
+
// and uses nowhere else: what it returns is the text it shows, as a React
|
|
1305
|
+
// component's string is. A function called as one (`Count({ n })`), exported
|
|
1306
|
+
// only, or rendering by other means (What's h(), a prop it returns as it is,
|
|
1307
|
+
// a JSX helper it returns the call of) is not.
|
|
1308
|
+
function rendersText(fnPath, state) {
|
|
1309
|
+
const params = fnPath.node.params;
|
|
1310
|
+
if (state.frameworkFile || params.length === 0 || params.length > 2 || !(t.isObjectPattern(params[0]) || t.isIdentifier(params[0]))) return false;
|
|
1311
|
+
if (callsWhatH(fnPath) || returnsProp(fnPath) || returnedCalls(fnPath).some((call) => callsHelper(fnPath, call))) return false;
|
|
1312
|
+
const name = componentName(fnPath);
|
|
1313
|
+
const binding = fnPath.scope.parent?.getBinding(name);
|
|
1314
|
+
if (!binding || binding.constantViolations.length > 0) return false;
|
|
1315
|
+
if (binding.path.node !== fnPath.node && !(binding.path.isVariableDeclarator() && binding.path.node.init === fnPath.node)) return false;
|
|
1316
|
+
let tag = false;
|
|
1317
|
+
for (const ref of binding.referencePaths) {
|
|
1318
|
+
if (ref.isJSXIdentifier() && (ref.parentPath.isJSXOpeningElement() || ref.parentPath.isJSXClosingElement())) tag = true;
|
|
1319
|
+
else if (!(ref.isExportNamedDeclaration() || ref.isExportDefaultDeclaration() || ref.parentPath.isExportSpecifier() || ref.parentPath.isExportDefaultDeclaration())) return false;
|
|
1320
|
+
}
|
|
1321
|
+
return tag;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// A `const` of the body derived from a prop or from the component's state
|
|
1325
|
+
// that its return is decided on (`const empty = items.length === 0; if
|
|
1326
|
+
// (empty) return <Empty />`) was read once, so the branch it chose stayed.
|
|
1327
|
+
// It is a lazy memo read where it is used instead, `const empty =
|
|
1328
|
+
// _$lazyMemo(() => items.length === 0)` with `if (empty())`, and so is each
|
|
1329
|
+
// such `const` it reads: lowerLiveReturns then lowers the branch on it, and a
|
|
1330
|
+
// read of it in JSX or in a handler sees its current value. The server reads
|
|
1331
|
+
// it once anyway: there the names only count as live, so both targets lower
|
|
1332
|
+
// the same branch. An initializer that calls a hook or a What primitive, or
|
|
1333
|
+
// builds JSX, is not moved into a memo. Two more are, for the same reason:
|
|
1334
|
+
// - a pattern destructured from such a value (`const { length } = value`),
|
|
1335
|
+
// read as a field of one memo of it (`_value().length`);
|
|
1336
|
+
// - a context's value (`const theme = useContext(Theme)`, `const { user } =
|
|
1337
|
+
// useContext(Auth)`), and one computed from it with no other hook (`const
|
|
1338
|
+
// isDark = useContext(Theme) === 'dark'`): useContext reads the provider's
|
|
1339
|
+
// signal, so the memo follows the provider's value.
|
|
1340
|
+
// A component that returns text (rendersText) has each `const` its returned
|
|
1341
|
+
// text reads chosen too: there the returned value is what it shows.
|
|
1342
|
+
export function memoBranchValues(fnPath, state) {
|
|
1343
|
+
if (state.frameworkFile || fnPath.node.async || fnPath.node.generator || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
1344
|
+
const output = componentOutput(fnPath, state);
|
|
1345
|
+
const body = fnPath.node.body;
|
|
1346
|
+
if (output === null || !t.isBlockStatement(body)) return;
|
|
1347
|
+
const live = liveReader(fnPath);
|
|
1348
|
+
/** @type {Map<string, { decl: any, reads: Set<string>, bound: { name: string, key: string | null }[] }>} */
|
|
1349
|
+
const derived = new Map();
|
|
1350
|
+
const ownConst = (node) => t.isIdentifier(node) && derived.has(node.name) && fnPath.scope.getBinding(node.name)?.scope === fnPath.scope;
|
|
1351
|
+
for (const stmt of fnPath.get('body.body')) {
|
|
1352
|
+
if (!stmt.isVariableDeclaration({ kind: 'const' })) continue;
|
|
1353
|
+
for (const decl of stmt.get('declarations')) {
|
|
1354
|
+
const { id, init } = decl.node;
|
|
1355
|
+
if (!init || t.isFunction(init)) continue;
|
|
1356
|
+
const context = callsHookOrWhat(fnPath, init) && !callsHookOrWhat(fnPath, init, true);
|
|
1357
|
+
if (!context && (seedsOnce(fnPath, init) || callsHookOrWhat(fnPath, init))) continue;
|
|
1358
|
+
const bound = t.isIdentifier(id) ? [{ name: id.name, key: null }] : plainPattern(id);
|
|
1359
|
+
// A name used as a tag (`const Icon = useContext(Icons)`, `<Icon />`) names a component.
|
|
1360
|
+
if (bound === null || bound.some(({ name }) => fnPath.scope.getBinding(name)?.referencePaths.some((ref) => ref.isJSXIdentifier()))) continue;
|
|
1361
|
+
const reads = new Set();
|
|
1362
|
+
propReadIn(init, (n) => { if (ownConst(n)) reads.add(n.name); return null; });
|
|
1363
|
+
if (context || reads.size > 0 || readsLive(init, live)) for (const { name } of bound) derived.set(name, { decl, reads, bound });
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
if (derived.size === 0) return;
|
|
1367
|
+
// The consts the return is decided on, and the consts they read.
|
|
1368
|
+
const chosen = new Set();
|
|
1369
|
+
const choose = (name) => {
|
|
1370
|
+
if (chosen.has(name)) return;
|
|
1371
|
+
const entry = /** @type {any} */ (derived.get(name));
|
|
1372
|
+
for (const { name: other } of entry.bound) chosen.add(other);
|
|
1373
|
+
for (const read of entry.reads) choose(read);
|
|
1374
|
+
};
|
|
1375
|
+
const decided = [...returnTests(body), ...(output === TEXT ? returnedValues(body) : [])];
|
|
1376
|
+
for (const node of decided) propReadIn(node, (n) => { if (ownConst(n)) choose(n.name); return null; });
|
|
1377
|
+
if (chosen.size === 0) return;
|
|
1378
|
+
const memos = (fnPath.node._whatLiveMemos ??= { names: new Set(), called: !state.ssr });
|
|
1379
|
+
if (state.ssr) {
|
|
1380
|
+
for (const name of chosen) memos.names.add(name);
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
const done = new Set();
|
|
1384
|
+
for (const name of chosen) {
|
|
1385
|
+
const { decl, bound } = /** @type {any} */ (derived.get(name));
|
|
1386
|
+
if (done.has(decl)) continue;
|
|
1387
|
+
done.add(decl);
|
|
1388
|
+
const memo = bound[0].key === null ? t.identifier(name) : fnPath.scope.generateUidIdentifier(bound[0].name);
|
|
1389
|
+
memos.names.add(memo.name);
|
|
1390
|
+
for (const { name: local, key } of bound) {
|
|
1391
|
+
const binding = fnPath.scope.getBinding(local);
|
|
1392
|
+
for (const ref of binding ? binding.referencePaths : []) {
|
|
1393
|
+
if (ref.parentPath.isObjectProperty({ shorthand: true }) && ref.key === 'value') ref.parent.shorthand = false;
|
|
1394
|
+
const value = t.callExpression(t.identifier(memo.name), []);
|
|
1395
|
+
ref.replaceWith(key === null ? value : t.memberExpression(value, propKey(key), !t.isIdentifier(propKey(key))));
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
if (bound[0].key !== null) decl.get('id').replaceWith(memo);
|
|
1399
|
+
decl.get('init').replaceWith(t.callExpression(helper(state, '_$lazyMemo'), [t.arrowFunctionExpression([], decl.node.init)]));
|
|
1400
|
+
}
|
|
1401
|
+
fnPath.scope.crawl();
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// The names a pattern of static keys binds, each with its key (`{ length, a: b }`),
|
|
1405
|
+
// else null: a default, a rest element, a nested pattern or a computed key
|
|
1406
|
+
// would need more than a field read.
|
|
1407
|
+
function plainPattern(pattern) {
|
|
1408
|
+
if (!t.isObjectPattern(pattern) || pattern.properties.length === 0) return null;
|
|
1409
|
+
const bound = [];
|
|
1410
|
+
for (const p of pattern.properties) {
|
|
1411
|
+
const key = t.isObjectProperty(p) ? propertyName(p.key, p.computed) : null;
|
|
1412
|
+
if (key === null || !t.isIdentifier(p.value)) return null;
|
|
1413
|
+
bound.push({ name: p.value.name, key });
|
|
1414
|
+
}
|
|
1415
|
+
return bound;
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
// --- A `let` the body computes from a prop or from state ---
|
|
1419
|
+
// `let cls = 'btn'; if (primary) cls += ' primary'; return <button class={cls} />`
|
|
1420
|
+
// computes `cls` from a prop, as React code does on every render. A component
|
|
1421
|
+
// runs once, so `cls` kept the class of the first `primary`. It is a lazy
|
|
1422
|
+
// memo of the statements that compute it instead, read where it is used:
|
|
1423
|
+
// `const cls = _$lazyMemo(() => { let cls = 'btn'; if (primary) cls += ' primary'; return cls; })`
|
|
1424
|
+
// with `class={cls()}`, so it follows the prop in JSX, in a handler and in a
|
|
1425
|
+
// return decided on it. The statements that assign it (statements of the body
|
|
1426
|
+
// after the `let`) move into the memo, so they may do nothing else that the
|
|
1427
|
+
// component would see done again: assign no other name of the component and
|
|
1428
|
+
// no property, call no hook or What primitive, build no JSX (built again on
|
|
1429
|
+
// each change, it would lose its state: a ternary where it is shown keeps
|
|
1430
|
+
// it), and return or jump out of nowhere. It is read only after the last of
|
|
1431
|
+
// them, outside a function declaration (which may run before it), and every
|
|
1432
|
+
// name of the component they read is assigned nowhere. The server reads it
|
|
1433
|
+
// once anyway: there the name only counts as live (liveReader), so both
|
|
1434
|
+
// targets lower the same branch. A `let` the body assigns from a prop or from
|
|
1435
|
+
// state that cannot be moved, and that JSX shows, keeps its first value:
|
|
1436
|
+
// development reports ERR_PROP_READ_ONCE or ERR_STATE_READ_ONCE.
|
|
1437
|
+
|
|
1438
|
+
/** Make each `let` the component `fnPath` computes from a live value a memo of its statements (see above). */
|
|
1439
|
+
export function memoLiveLets(fnPath, state) {
|
|
1440
|
+
if (state.frameworkFile || fnPath.node.async || fnPath.node.generator || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
1441
|
+
const body = fnPath.node.body;
|
|
1442
|
+
if (componentOutput(fnPath, state) === null || !t.isBlockStatement(body)) return;
|
|
1443
|
+
const live = liveReader(fnPath);
|
|
1444
|
+
const stmts = fnPath.get('body.body');
|
|
1445
|
+
/** @type {{ name: string, at: number, writers: number[] }[]} */
|
|
1446
|
+
const lowered = [];
|
|
1447
|
+
for (let i = 0; i < stmts.length; i++) {
|
|
1448
|
+
const stmt = stmts[i];
|
|
1449
|
+
if (!stmt.isVariableDeclaration({ kind: 'let' }) || stmt.node.declarations.length !== 1 || !t.isIdentifier(stmt.node.declarations[0].id)) continue;
|
|
1450
|
+
const name = stmt.node.declarations[0].id.name;
|
|
1451
|
+
const binding = fnPath.scope.getBinding(name);
|
|
1452
|
+
if (!binding || binding.scope !== fnPath.scope || binding.constantViolations.length === 0) continue;
|
|
1453
|
+
const { writers, elsewhere } = assigningStatements(fnPath, stmts, i, binding);
|
|
1454
|
+
const read = [stmt, ...writers.map((j) => stmts[j])].map((s) => propReadIn(s.node, live)).find((r) => r !== null) ?? null;
|
|
1455
|
+
if (read === null) continue;
|
|
1456
|
+
if (!elsewhere && movableLet(fnPath, stmts, i, writers, binding)) {
|
|
1457
|
+
lowered.push({ name, at: i, writers });
|
|
1458
|
+
continue;
|
|
1459
|
+
}
|
|
1460
|
+
// A read in the initializer is reported as a value derived in the body
|
|
1461
|
+
// (warnDerivedPropOnce, warnStateReadOnce), and one in a statement that
|
|
1462
|
+
// also returns as the branch it decides.
|
|
1463
|
+
const late = writers.map((j) => stmts[j]).find((s) => !holdsReturn(s.node) && propReadIn(s.node, live) !== null);
|
|
1464
|
+
if (late === undefined || !binding.referencePaths.some((ref) => shownValue(ref, fnPath))) continue;
|
|
1465
|
+
const lateRead = /** @type {{ name: string, prop: boolean }} */ (propReadIn(late.node, live));
|
|
1466
|
+
const why = `\`${name}\` is assigned from it in the component body and shown in JSX, so it keeps the value of the first run`;
|
|
1467
|
+
const fix = `compute it in the JSX where it is shown (\`{${lateRead.name} ? … : …}\`), or make it a function of the body and call it there (\`const ${name} = () => …\`, then \`${name}()\`)`;
|
|
1468
|
+
if (lateRead.prop) warnReadOnce(fnPath, state, late.node, lateRead.name, why, fix);
|
|
1469
|
+
else if (process.env.NODE_ENV !== 'production' && !state.ssr) warnStateOnce(fnPath, state, late.node, lateRead.name, why, fix);
|
|
1470
|
+
}
|
|
1471
|
+
if (lowered.length === 0) return;
|
|
1472
|
+
const memos = (fnPath.node._whatLiveMemos ??= { names: new Set(), called: !state.ssr });
|
|
1473
|
+
for (const { name } of lowered) memos.names.add(name);
|
|
1474
|
+
if (state.ssr) return;
|
|
1475
|
+
const removed = new Set();
|
|
1476
|
+
const placed = new Map();
|
|
1477
|
+
for (const { name, at, writers } of lowered) {
|
|
1478
|
+
const binding = /** @type {any} */ (fnPath.scope.getBinding(name));
|
|
1479
|
+
const inside = [at, ...writers].map((j) => stmts[j]);
|
|
1480
|
+
for (const ref of binding.referencePaths) {
|
|
1481
|
+
if (inside.some((s) => ref.isDescendant(s))) continue;
|
|
1482
|
+
if (ref.parentPath.isObjectProperty({ shorthand: true }) && ref.key === 'value') ref.parent.shorthand = false;
|
|
1483
|
+
ref.replaceWith(t.callExpression(t.identifier(name), []));
|
|
1484
|
+
}
|
|
1485
|
+
const run = [...inside.map((s) => s.node), t.returnStatement(t.identifier(name))];
|
|
1486
|
+
const memo = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(name),
|
|
1487
|
+
t.callExpression(helper(state, '_$lazyMemo'), [t.arrowFunctionExpression([], t.blockStatement(run))]))]);
|
|
1488
|
+
for (const s of inside) removed.add(s.node);
|
|
1489
|
+
placed.set(stmts[writers[writers.length - 1]].node, memo);
|
|
1490
|
+
}
|
|
1491
|
+
body.body = body.body.flatMap((s) => (placed.has(s) ? [placed.get(s)] : removed.has(s) ? [] : [s]));
|
|
1492
|
+
fnPath.scope.crawl();
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
// The indexes of the body's statements after the `let` declared at `at` that
|
|
1496
|
+
// assign it in the component's run, in order, and whether it is assigned
|
|
1497
|
+
// anywhere else too (a function written in the body, a handler).
|
|
1498
|
+
function assigningStatements(fnPath, stmts, at, binding) {
|
|
1499
|
+
const found = new Set();
|
|
1500
|
+
let elsewhere = false;
|
|
1501
|
+
for (const violation of binding.constantViolations) {
|
|
1502
|
+
const index = violation.getFunctionParent() === fnPath ? stmts.findIndex((s) => violation === s || violation.isDescendant(s)) : -1;
|
|
1503
|
+
if (index > at) found.add(index);
|
|
1504
|
+
else elsewhere = true;
|
|
1505
|
+
}
|
|
1506
|
+
return { writers: [...found].sort((a, b) => a - b), elsewhere };
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
// Whether the `let` at `at` and the statements `writers` that assign it can
|
|
1510
|
+
// move into a memo (see above).
|
|
1511
|
+
function movableLet(fnPath, stmts, at, writers, binding) {
|
|
1512
|
+
const last = writers[writers.length - 1];
|
|
1513
|
+
const moved = [stmts[at], ...writers.map((j) => stmts[j])];
|
|
1514
|
+
for (const ref of binding.referencePaths) {
|
|
1515
|
+
// A tag (`<Tag />`) names a component, read where the component runs.
|
|
1516
|
+
if (ref.isJSXIdentifier()) return false;
|
|
1517
|
+
if (moved.some((s) => ref.isDescendant(s))) continue;
|
|
1518
|
+
const index = stmts.findIndex((s) => ref.isDescendant(s));
|
|
1519
|
+
if (index <= last || ref.findParent((p) => p.isFunctionDeclaration() && p.isDescendant(fnPath)) !== null) return false;
|
|
1520
|
+
}
|
|
1521
|
+
for (const s of moved) {
|
|
1522
|
+
if (s !== stmts[at] && (s.isDeclaration() || holdsReturn(s.node))) return false;
|
|
1523
|
+
let ok = true;
|
|
1524
|
+
s.traverse({
|
|
1525
|
+
Function(inner) { inner.skip(); },
|
|
1526
|
+
'JSXElement|JSXFragment|YieldExpression|AwaitExpression|ThrowStatement'(p) { ok = false; p.stop(); },
|
|
1527
|
+
'BreakStatement|ContinueStatement'(p) {
|
|
1528
|
+
const target = p.node.label ? p.findParent((q) => q.isLabeledStatement() && q.node.label.name === p.node.label.name)
|
|
1529
|
+
: p.findParent((q) => q.isLoop() || (p.isBreakStatement() && q.isSwitchStatement()));
|
|
1530
|
+
if (target === null || !target.isDescendant(s)) { ok = false; p.stop(); }
|
|
1531
|
+
},
|
|
1532
|
+
CallExpression(call) {
|
|
1533
|
+
if (seedsOnce(fnPath, call.node)) { ok = false; call.stop(); }
|
|
1534
|
+
},
|
|
1535
|
+
'AssignmentExpression|UpdateExpression'(p) {
|
|
1536
|
+
const target = p.isAssignmentExpression() ? p.node.left : p.node.argument;
|
|
1537
|
+
const written = t.isIdentifier(target) ? p.scope.getBinding(target.name) : null;
|
|
1538
|
+
if (written === binding || (written != null && written.path.isDescendant(s))) return;
|
|
1539
|
+
ok = false;
|
|
1540
|
+
p.stop();
|
|
1541
|
+
},
|
|
1542
|
+
UnaryExpression(p) {
|
|
1543
|
+
if (p.node.operator === 'delete') { ok = false; p.stop(); }
|
|
1544
|
+
},
|
|
1545
|
+
// Children are built where they are read: a memo would build them again.
|
|
1546
|
+
MemberExpression(p) {
|
|
1547
|
+
if (propertyName(p.node.property, p.node.computed) === 'children') { ok = false; p.stop(); }
|
|
1548
|
+
},
|
|
1549
|
+
ReferencedIdentifier(ref) {
|
|
1550
|
+
const read = ref.scope.getBinding(ref.node.name);
|
|
1551
|
+
if (read && read.scope === fnPath.scope && ref.node.name === 'children') { ok = false; ref.stop(); return; }
|
|
1552
|
+
if (read && read !== binding && read.scope === fnPath.scope && read.constantViolations.length > 0) { ok = false; ref.stop(); }
|
|
1553
|
+
},
|
|
1554
|
+
});
|
|
1555
|
+
if (!ok) return false;
|
|
1556
|
+
}
|
|
1557
|
+
return true;
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
// What the statements of a body return, outside the functions written in them.
|
|
1561
|
+
function returnedValues(body) {
|
|
1562
|
+
const out = [];
|
|
1563
|
+
const visit = (n) => {
|
|
1564
|
+
if (!n || typeof n !== 'object') return;
|
|
1565
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
1566
|
+
if (typeof n.type !== 'string' || t.isFunction(n)) return;
|
|
1567
|
+
if (t.isReturnStatement(n)) { if (n.argument) out.push(n.argument); return; }
|
|
1568
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
1569
|
+
};
|
|
1570
|
+
visit(body.body);
|
|
1571
|
+
return out;
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
// Whether `node` calls a hook (`useX()`), a What primitive or builds JSX,
|
|
1575
|
+
// outside the functions written in it: work a memo must not repeat. With
|
|
1576
|
+
// `context`, What's useContext does not count: it reads the provider's
|
|
1577
|
+
// signal, which a memo may read again.
|
|
1578
|
+
function callsHookOrWhat(fnPath, node, context = false) {
|
|
1579
|
+
let found = false;
|
|
1580
|
+
const visit = (n) => {
|
|
1581
|
+
if (found || !n || typeof n !== 'object') return;
|
|
1582
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
1583
|
+
if (typeof n.type !== 'string' || t.isFunction(n)) return;
|
|
1584
|
+
if (context && t.isCallExpression(n) && importedWhatName(fnPath, n.callee) === 'useContext') { visit(n.arguments); return; }
|
|
1585
|
+
if (t.isJSXElement(n) || t.isJSXFragment(n) || (t.isCallExpression(n) && seedsOnce(fnPath, n))) { found = true; return; }
|
|
1586
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
1587
|
+
};
|
|
1588
|
+
visit(node);
|
|
1589
|
+
return found;
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
// What's hooks whose result the component does not read as live state: a
|
|
1593
|
+
// ref, a callback, an id, an effect, and the route's, as a page's `params`
|
|
1594
|
+
// and `route` props are not (UNREPORTED_PROPS: a page is built again for
|
|
1595
|
+
// other params; what-router reports a query read once itself). Its state
|
|
1596
|
+
// hooks are STATE_SOURCES, and a useContext value is memoBranchValues'.
|
|
1597
|
+
const UNLIVE_HOOKS = new Set(['useRef', 'useCallback', 'useId', 'useEffect', 'useContext', 'useParams', 'useSearch', 'useRoute', 'useNavigate']);
|
|
1598
|
+
|
|
1599
|
+
// The hook the expression calls, `useAuth(…)` (a name that starts with `use`
|
|
1600
|
+
// and a capital, as React's rules of hooks name one): its name, What's when
|
|
1601
|
+
// What exports it, whether What's it is, and whether the app's own it is
|
|
1602
|
+
// (declared in the module, or imported from a relative path). Null for any
|
|
1603
|
+
// other expression.
|
|
1604
|
+
function hookCall(fnPath, init) {
|
|
1605
|
+
const call = unwrapExpr(init);
|
|
1606
|
+
if (!t.isCallExpression(call) || !t.isIdentifier(call.callee) || !/^use[A-Z0-9]/.test(call.callee.name)) return null;
|
|
1607
|
+
const what = importedWhatName(fnPath, call.callee);
|
|
1608
|
+
const binding = fnPath.scope.getBinding(call.callee.name);
|
|
1609
|
+
const own = binding !== undefined && (binding.kind !== 'module' || (t.isImportDeclaration(binding.path.parent) && binding.path.parent.source.value.startsWith('.')));
|
|
1610
|
+
return { name: what ?? call.callee.name, local: call.callee.name, what: what !== null, own };
|
|
1611
|
+
}
|
|
1612
|
+
|
|
1613
|
+
// The names of the component's body that hold what a hook returned
|
|
1614
|
+
// (`const auth = useAuth()`, `const { user } = useAuth()`, `const [on] =
|
|
1615
|
+
// useToggle()`), What's state hooks and the stateless ones left out:
|
|
1616
|
+
// `results` hold what it returned as it is (`auth`, `isMobile`), `parts` the
|
|
1617
|
+
// names destructured from it, each with the hook it came from, and `own`
|
|
1618
|
+
// tells a hook of the app's.
|
|
1619
|
+
function hookNames(fnPath) {
|
|
1620
|
+
/** @type {Map<string, { hook: string, local: string, own: boolean, keys: string[] }>} */
|
|
1621
|
+
const results = new Map();
|
|
1622
|
+
/** @type {Map<string, { hook: string, local: string, own: boolean, keys: string[] }>} */
|
|
1623
|
+
const parts = new Map();
|
|
1624
|
+
for (const stmt of t.isBlockStatement(fnPath.node.body) ? fnPath.node.body.body : []) {
|
|
1625
|
+
if (!t.isVariableDeclaration(stmt, { kind: 'const' })) continue;
|
|
1626
|
+
for (const decl of stmt.declarations) {
|
|
1627
|
+
const hook = hookCall(fnPath, decl.init);
|
|
1628
|
+
if (hook === null || (hook.what && (UNLIVE_HOOKS.has(hook.name) || STATE_SOURCES.has(hook.name)))) continue;
|
|
1629
|
+
const part = { hook: hook.name, local: hook.local, own: hook.own, keys: [] };
|
|
1630
|
+
if (t.isIdentifier(decl.id)) results.set(decl.id.name, part);
|
|
1631
|
+
else if (t.isObjectPattern(decl.id)) {
|
|
1632
|
+
for (const p of decl.id.properties) {
|
|
1633
|
+
if (!t.isObjectProperty(p) || !t.isIdentifier(p.value)) continue;
|
|
1634
|
+
const key = propertyName(p.key, p.computed);
|
|
1635
|
+
parts.set(p.value.name, { ...part, own: part.own && key !== null, keys: key === null ? [] : [key] });
|
|
1636
|
+
}
|
|
1637
|
+
} else if (t.isArrayPattern(decl.id)) {
|
|
1638
|
+
for (const [i, e] of decl.id.elements.entries()) if (t.isIdentifier(e)) parts.set(e.name, { ...part, keys: [String(i)] });
|
|
1639
|
+
}
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
return { results, parts };
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
// --- What a hook returns, read in JSX ---
|
|
1646
|
+
// `const todos = useTodos()`, then `{todos.remaining}` or `class={todos.filter
|
|
1647
|
+
// === 'all' ? 'on' : ''}`: a store's fields are getters, and a field or a
|
|
1648
|
+
// method of any hook's object (the app's or a package's) may read state. The
|
|
1649
|
+
// JSX compiler reads a property of an imported function's result once
|
|
1650
|
+
// (reactivity.js), so the text kept its first value, unless the store was
|
|
1651
|
+
// made in the same module, where the walk sees the getters. The declarator of
|
|
1652
|
+
// each name holding what a hook returned (hookNames: What's state hooks, its
|
|
1653
|
+
// ref, effect, context and route hooks left out) is marked, so a property
|
|
1654
|
+
// read or a method call off it is reactive in JSX (reactivity.js
|
|
1655
|
+
// isHookResultRead), on both targets, as a return decided on it is
|
|
1656
|
+
// (liveReader). An object whose fields are plain costs one effect that runs
|
|
1657
|
+
// once.
|
|
1658
|
+
|
|
1659
|
+
/** Mark what the function's hooks return as read live in JSX (see above). */
|
|
1660
|
+
export function markHookResults(fnPath, state) {
|
|
1661
|
+
if (state.frameworkFile) return;
|
|
1662
|
+
for (const name of hookNames(fnPath).results.keys()) {
|
|
1663
|
+
const binding = fnPath.scope.getBinding(name);
|
|
1664
|
+
if (binding !== undefined && binding.scope === fnPath.scope && binding.path.isVariableDeclarator()) binding.path.node._whatHookResult = true;
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
// A name of the module whose call reads state the component does not own: a
|
|
1669
|
+
// `const` at module scope made by one of What's state primitives (`const
|
|
1670
|
+
// session = signal(null)`), or a function imported from a module that is not
|
|
1671
|
+
// What's, which may be a store's accessor (`import { session } from
|
|
1672
|
+
// './auth'`), as compiled JSX takes `{session()}` to be.
|
|
1673
|
+
function moduleAccessor(binding) {
|
|
1674
|
+
if (!binding) return false;
|
|
1675
|
+
if (binding.kind === 'module') {
|
|
1676
|
+
const spec = binding.path.node;
|
|
1677
|
+
return (t.isImportSpecifier(spec) || t.isImportDefaultSpecifier(spec)) && t.isImportDeclaration(binding.path.parent)
|
|
1678
|
+
&& !isWhatModuleSource(binding.path.parent.source.value);
|
|
1679
|
+
}
|
|
1680
|
+
return binding.kind === 'const' && binding.scope.path.isProgram() && binding.path.isVariableDeclarator()
|
|
1681
|
+
&& t.isIdentifier(binding.path.node.id) && isStateSource(binding.path, binding.path.node.init);
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
// An object imported from a module that is not What's (`import * as auth`,
|
|
1685
|
+
// `import auth`, `import { auth }`), whose methods may read a store.
|
|
1686
|
+
function importedObject(binding) {
|
|
1687
|
+
return binding?.kind === 'module' && t.isImportDeclaration(binding.path.parent) && !isWhatModuleSource(binding.path.parent.source.value);
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
// The function a name of the module or of the component holds, written once:
|
|
1691
|
+
// `function isAdmin() { … }`, `const isEmpty = () => …`. Else null.
|
|
1692
|
+
function declaredFunction(fnPath, binding) {
|
|
1693
|
+
if (!binding || binding.constantViolations.length > 0 || (binding.scope !== fnPath.scope && !binding.scope.path.isProgram())) return null;
|
|
1694
|
+
const path = binding.path;
|
|
1695
|
+
const fn = path.isFunctionDeclaration() ? path : path.isVariableDeclarator() && binding.kind === 'const' ? path.get('init') : null;
|
|
1696
|
+
return fn?.isFunction() && !fn.node.async && !fn.node.generator ? fn : null;
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
// What the component reads as live, the way compiled JSX reads it: a read of
|
|
1700
|
+
// a prop (a name the parameter list or the body destructures from the props,
|
|
1701
|
+
// `props.<key>`, an alias `const v = props.value`), and a read of state:
|
|
1702
|
+
// - a call of one of the component's state accessors (STATE_SOURCES);
|
|
1703
|
+
// - a call of a module's state: a signal or computed of the module, a
|
|
1704
|
+
// function imported from outside What (moduleAccessor), a method of an
|
|
1705
|
+
// object imported so (`auth.session()`);
|
|
1706
|
+
// - what a hook returned (hookNames): a call of it, an accessor (`const
|
|
1707
|
+
// isMobile = useMediaQuery(q)` with `isMobile()`), a call of a name
|
|
1708
|
+
// destructured from it (`const { user } = useAuth()` with `user()`), and a
|
|
1709
|
+
// call of a method or a read of a field of the object (`auth.user()`,
|
|
1710
|
+
// `todos.remaining`: a store's fields are getters);
|
|
1711
|
+
// - a call of a function of the module or of the component whose body reads
|
|
1712
|
+
// any of these (`const isEmpty = () => items().length === 0`).
|
|
1713
|
+
// `children`, a route's `params` and `route` are not live: reading children
|
|
1714
|
+
// builds them, and a page is built again for other params. The reader returns
|
|
1715
|
+
// the read as { name, prop }, else null.
|
|
1716
|
+
function liveReader(fnPath) {
|
|
1717
|
+
const param = fnPath.node.params[0];
|
|
1718
|
+
const props = t.isIdentifier(param) && fnPath.scope.getBinding(param.name)?.kind === 'param' ? param.name : null;
|
|
1719
|
+
const names = new Set();
|
|
1720
|
+
const accessors = stateAccessors(fnPath);
|
|
1721
|
+
const { results, parts } = hookNames(fnPath);
|
|
1722
|
+
for (const name of [...results.keys(), ...parts.keys()]) accessors.add(name);
|
|
1723
|
+
const add = (pattern) => {
|
|
1724
|
+
for (const p of pattern.properties) {
|
|
1725
|
+
const key = t.isRestElement(p) ? null : propertyName(p.key, p.computed);
|
|
1726
|
+
if (key === null || UNREPORTED_PROPS.has(key)) continue;
|
|
1727
|
+
for (const name of collectNames(p.value)) names.add(name);
|
|
1728
|
+
}
|
|
1729
|
+
};
|
|
1730
|
+
if (t.isObjectPattern(param)) add(param);
|
|
1731
|
+
// The values memoLiveLets and memoBranchValues made memos (called) or, on
|
|
1732
|
+
// the server, kept as names.
|
|
1733
|
+
const memos = fnPath.node._whatLiveMemos;
|
|
1734
|
+
if (memos !== undefined) for (const name of memos.names) (memos.called ? accessors : names).add(name);
|
|
1735
|
+
for (const stmt of t.isBlockStatement(fnPath.node.body) ? fnPath.node.body.body : []) {
|
|
1736
|
+
if (!t.isVariableDeclaration(stmt, { kind: 'const' })) continue;
|
|
1737
|
+
for (const decl of stmt.declarations) {
|
|
1738
|
+
if (props !== null && t.isObjectPattern(decl.id) && t.isIdentifier(decl.init, { name: props })) add(decl.id);
|
|
1739
|
+
else if (props !== null && t.isIdentifier(decl.id) && (t.isMemberExpression(decl.init) || t.isOptionalMemberExpression(decl.init))) {
|
|
1740
|
+
let root = decl.init;
|
|
1741
|
+
while (t.isMemberExpression(root) || t.isOptionalMemberExpression(root)) root = root.object;
|
|
1742
|
+
const first = firstKey(decl.init);
|
|
1743
|
+
if (t.isIdentifier(root, { name: props }) && first !== null && !UNREPORTED_PROPS.has(first)) names.add(decl.id.name);
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
/** @type {Map<any, boolean>} */
|
|
1748
|
+
const functions = new Map();
|
|
1749
|
+
const callsLive = (binding) => {
|
|
1750
|
+
const fn = declaredFunction(fnPath, binding);
|
|
1751
|
+
if (fn === null) return false;
|
|
1752
|
+
if (!functions.has(binding)) {
|
|
1753
|
+
functions.set(binding, false);
|
|
1754
|
+
const body = fn.get('body');
|
|
1755
|
+
let found = read(body.node, body.scope) !== null;
|
|
1756
|
+
if (!found && !body.isFunction()) body.traverse({
|
|
1757
|
+
enter(path) {
|
|
1758
|
+
if (path.isFunction()) path.skip();
|
|
1759
|
+
else if (read(path.node, path.scope) !== null) { found = true; path.stop(); }
|
|
1760
|
+
},
|
|
1761
|
+
});
|
|
1762
|
+
functions.set(binding, found);
|
|
1763
|
+
}
|
|
1764
|
+
return /** @type {boolean} */ (functions.get(binding));
|
|
1765
|
+
};
|
|
1766
|
+
const read = (node, scope = fnPath.scope) => {
|
|
1767
|
+
const own = (name) => scope.getBinding(name)?.scope === fnPath.scope;
|
|
1768
|
+
if (t.isIdentifier(node)) return names.has(node.name) && own(node.name) ? { name: node.name, prop: true } : null;
|
|
1769
|
+
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
|
1770
|
+
if (!t.isIdentifier(node.object)) return null;
|
|
1771
|
+
const key = propertyName(node.property, node.computed);
|
|
1772
|
+
if (key === null || !own(node.object.name)) return null;
|
|
1773
|
+
if (node.object.name === props && !UNREPORTED_PROPS.has(key)) return { name: `props.${key}`, prop: true };
|
|
1774
|
+
return results.has(node.object.name) ? { name: `${node.object.name}.${key}`, prop: false } : null;
|
|
1775
|
+
}
|
|
1776
|
+
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) return null;
|
|
1777
|
+
const callee = node.callee;
|
|
1778
|
+
if (t.isIdentifier(callee)) {
|
|
1779
|
+
const binding = scope.getBinding(callee.name);
|
|
1780
|
+
const accessor = node.arguments.length === 0 && ((accessors.has(callee.name) && own(callee.name)) || moduleAccessor(binding));
|
|
1781
|
+
return accessor || callsLive(binding) ? { name: `${callee.name}()`, prop: false } : null;
|
|
1782
|
+
}
|
|
1783
|
+
if ((!t.isMemberExpression(callee) && !t.isOptionalMemberExpression(callee)) || !t.isIdentifier(callee.object)) return null;
|
|
1784
|
+
const key = propertyName(callee.property, callee.computed);
|
|
1785
|
+
if (key === null) return null;
|
|
1786
|
+
const live = (results.has(callee.object.name) && own(callee.object.name)) || importedObject(scope.getBinding(callee.object.name));
|
|
1787
|
+
return live ? { name: `${callee.object.name}.${key}()`, prop: false } : null;
|
|
1788
|
+
};
|
|
1789
|
+
return read;
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
// What a return is decided on: what liveReader reads, and a context's value
|
|
1793
|
+
// read in the condition itself (`if (useContext(Theme) === 'dark')`). The
|
|
1794
|
+
// lowered condition is a memo, which calls What's useContext again when the
|
|
1795
|
+
// provider's value changes, as the memo of `const theme = useContext(Theme)`
|
|
1796
|
+
// does (memoBranchValues).
|
|
1797
|
+
function returnReader(fnPath) {
|
|
1798
|
+
const live = liveReader(fnPath);
|
|
1799
|
+
return (node) => live(node) ?? (t.isCallExpression(node) && importedWhatName(fnPath, node.callee) === 'useContext'
|
|
1800
|
+
? { name: `useContext(${t.isIdentifier(node.arguments[0]) ? node.arguments[0].name : '…'})`, prop: false } : null);
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
function readsLive(node, live) {
|
|
1804
|
+
return propReadIn(node, (n) => (live(n) ? '' : null)) !== null;
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
function unwrapExpr(expr) {
|
|
1808
|
+
while (t.isParenthesizedExpression(expr) || t.isTSAsExpression(expr) || t.isTSSatisfiesExpression(expr) || t.isTSNonNullExpression(expr)) expr = expr.expression;
|
|
1809
|
+
return expr;
|
|
1810
|
+
}
|
|
1811
|
+
|
|
1812
|
+
// Whether the conditional or logical expression decides on a live value.
|
|
1813
|
+
function liveTest(expr, live) {
|
|
1814
|
+
return readsLive(t.isConditionalExpression(expr) ? expr.test : expr.left, live);
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
function isBranch(expr) {
|
|
1818
|
+
const inner = unwrapExpr(expr);
|
|
1819
|
+
return t.isConditionalExpression(inner) || t.isLogicalExpression(inner);
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
function branchFragment(expr) {
|
|
1823
|
+
return t.jsxFragment(t.jsxOpeningFragment(), t.jsxClosingFragment(), [t.jsxExpressionContainer(expr)]);
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
// Whether the node holds a return statement outside the functions written in it.
|
|
1827
|
+
function holdsReturn(node) {
|
|
1828
|
+
let found = false;
|
|
1829
|
+
const visit = (n) => {
|
|
1830
|
+
if (found || !n || typeof n !== 'object') return;
|
|
1831
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
1832
|
+
if (typeof n.type !== 'string' || t.isFunction(n) || t.isClass(n)) return;
|
|
1833
|
+
if (t.isReturnStatement(n)) { found = true; return; }
|
|
1834
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
1835
|
+
};
|
|
1836
|
+
visit(node);
|
|
1837
|
+
return found;
|
|
1838
|
+
}
|
|
1839
|
+
|
|
1840
|
+
// The conditions the statement decides its return on: an `if`'s and a
|
|
1841
|
+
// `switch`'s that hold a return, a loop's (what it iterates, its test), an
|
|
1842
|
+
// `if`'s that leaves a labeled block holding a return (`out: { if (!v) break
|
|
1843
|
+
// out; return <b />; }`), and the test of a returned conditional or logical
|
|
1844
|
+
// expression, in the statement and in its branches.
|
|
1845
|
+
function branchTests(stmt, out = []) {
|
|
1846
|
+
if (!stmt) return out;
|
|
1847
|
+
if (t.isReturnStatement(stmt)) {
|
|
1848
|
+
const expr = unwrapExpr(stmt.argument);
|
|
1849
|
+
if (t.isConditionalExpression(expr)) out.push(expr.test);
|
|
1850
|
+
else if (t.isLogicalExpression(expr)) out.push(expr.left);
|
|
1851
|
+
} else if (t.isIfStatement(stmt)) {
|
|
1852
|
+
if (holdsReturn(stmt)) out.push(stmt.test);
|
|
1853
|
+
branchTests(stmt.consequent, out);
|
|
1854
|
+
branchTests(stmt.alternate, out);
|
|
1855
|
+
} else if (t.isBlockStatement(stmt)) {
|
|
1856
|
+
for (const s of stmt.body) branchTests(s, out);
|
|
1857
|
+
} else if (t.isSwitchStatement(stmt) && holdsReturn(stmt)) {
|
|
1858
|
+
out.push(stmt.discriminant);
|
|
1859
|
+
for (const c of stmt.cases) for (const s of c.consequent) branchTests(s, out);
|
|
1860
|
+
} else if (t.isLoop(stmt) && holdsReturn(stmt)) {
|
|
1861
|
+
out.push(t.isForXStatement(stmt) ? stmt.right : stmt.test);
|
|
1862
|
+
branchTests(stmt.body, out);
|
|
1863
|
+
} else if (t.isTryStatement(stmt)) {
|
|
1864
|
+
branchTests(stmt.block, out);
|
|
1865
|
+
branchTests(stmt.handler?.body, out);
|
|
1866
|
+
branchTests(stmt.finalizer, out);
|
|
1867
|
+
} else if (t.isLabeledStatement(stmt)) {
|
|
1868
|
+
branchTests(stmt.body, out);
|
|
1869
|
+
if (holdsReturn(stmt.body)) leavingTests(stmt.body, stmt.label.name, out);
|
|
1870
|
+
}
|
|
1871
|
+
return out;
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
// The tests of the `if`s in `node` that hold a `break` out of the label.
|
|
1875
|
+
function leavingTests(node, label, out) {
|
|
1876
|
+
const visit = (n) => {
|
|
1877
|
+
if (!n || typeof n !== 'object') return;
|
|
1878
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
1879
|
+
if (typeof n.type !== 'string' || t.isFunction(n)) return;
|
|
1880
|
+
if (t.isIfStatement(n) && !out.includes(n.test) && breaksTo(n, label)) out.push(n.test);
|
|
1881
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
1882
|
+
};
|
|
1883
|
+
visit(node);
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
function breaksTo(node, label) {
|
|
1887
|
+
let found = false;
|
|
1888
|
+
t.traverseFast(node, (n) => {
|
|
1889
|
+
if (t.isBreakStatement(n) && n.label?.name === label) found = true;
|
|
1890
|
+
});
|
|
1891
|
+
return found;
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
// The conditions a component's body decides its return on (branchTests), in
|
|
1895
|
+
// every statement of it that holds a return.
|
|
1896
|
+
function returnTests(body) {
|
|
1897
|
+
if (!t.isBlockStatement(body)) return branchTests(t.returnStatement(body));
|
|
1898
|
+
return body.body.flatMap((stmt) => (t.isReturnStatement(stmt) || holdsReturn(stmt) ? branchTests(stmt) : []));
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
// Whether the statement always ends the component's run.
|
|
1902
|
+
function exits(stmt) {
|
|
1903
|
+
if (t.isReturnStatement(stmt) || t.isThrowStatement(stmt)) return true;
|
|
1904
|
+
if (t.isBlockStatement(stmt)) return stmt.body.some(exits);
|
|
1905
|
+
return t.isIfStatement(stmt) && stmt.alternate != null && exits(stmt.consequent) && exits(stmt.alternate);
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
// Whether the statements after the branch can move into functions: no `var`
|
|
1909
|
+
// (it belongs to the component's scope), and no name they declare read or
|
|
1910
|
+
// written by the code that stays (the code before them, a hoisted function).
|
|
1911
|
+
function movable(fnPath, moved) {
|
|
1912
|
+
let declaresVar = false;
|
|
1913
|
+
const visit = (n) => {
|
|
1914
|
+
if (declaresVar || !n || typeof n !== 'object') return;
|
|
1915
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
1916
|
+
if (typeof n.type !== 'string' || t.isFunction(n)) return;
|
|
1917
|
+
if (t.isVariableDeclaration(n, { kind: 'var' })) { declaresVar = true; return; }
|
|
1918
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
1919
|
+
};
|
|
1920
|
+
visit(moved);
|
|
1921
|
+
if (declaresVar) return false;
|
|
1922
|
+
const stays = (path) => !moved.some((s) => path.node === s || path.findParent((p) => p.node === s) !== null);
|
|
1923
|
+
for (const stmt of moved) {
|
|
1924
|
+
const names = t.isVariableDeclaration(stmt) ? stmt.declarations.flatMap((d) => [...collectNames(d.id)])
|
|
1925
|
+
: t.isClassDeclaration(stmt) && stmt.id ? [stmt.id.name] : [];
|
|
1926
|
+
for (const name of names) {
|
|
1927
|
+
const binding = fnPath.scope.getBinding(name);
|
|
1928
|
+
if (binding && (binding.referencePaths.some(stays) || binding.constantViolations.some(stays))) return false;
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
return true;
|
|
1932
|
+
}
|
|
1933
|
+
|
|
1934
|
+
const VOID = () => t.unaryExpression('void', t.numericLiteral(0));
|
|
1935
|
+
|
|
1936
|
+
// The output of the statements `list`, which end the component, as one
|
|
1937
|
+
// expression (`arm(stmts)` builds a branch that runs statements), or null
|
|
1938
|
+
// when their shape is not one this lowers.
|
|
1939
|
+
function lowerTail(list, arm, state) {
|
|
1940
|
+
const at = list.findIndex(holdsReturn);
|
|
1941
|
+
const head = at === -1 ? list : list.slice(0, at);
|
|
1942
|
+
let core = null;
|
|
1943
|
+
if (at !== -1) {
|
|
1944
|
+
core = lowerStatement(list[at], list.slice(at + 1), arm, state);
|
|
1945
|
+
if (core === null) return null;
|
|
1946
|
+
}
|
|
1947
|
+
if (head.length === 0) return core ?? VOID();
|
|
1948
|
+
return arm(core === null ? head : [...head, t.returnStatement(isBranch(core) ? branchFragment(core) : core)]);
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
// A statement that holds a return, followed by `rest`, as one expression.
|
|
1952
|
+
// Code is never written twice: an `if` neither arm of which ends the run, with
|
|
1953
|
+
// code after it, is not lowered.
|
|
1954
|
+
function lowerStatement(stmt, rest, arm, state) {
|
|
1955
|
+
if (t.isReturnStatement(stmt)) return stmt.argument ?? VOID();
|
|
1956
|
+
if (t.isBlockStatement(stmt)) {
|
|
1957
|
+
if (exits(stmt)) return lowerTail(stmt.body, arm, state);
|
|
1958
|
+
return declaresNames(stmt.body) && rest.length > 0 ? null : lowerTail([...stmt.body, ...rest], arm, state);
|
|
1959
|
+
}
|
|
1960
|
+
if (t.isIfStatement(stmt)) {
|
|
1961
|
+
const runsOn = !exits(stmt.consequent);
|
|
1962
|
+
if (runsOn && rest.length > 0 && !(stmt.alternate && exits(stmt.alternate))) return null;
|
|
1963
|
+
const yes = lowerTail(branchList(stmt.consequent, rest), arm, state);
|
|
1964
|
+
const no = lowerTail(stmt.alternate ? branchList(stmt.alternate, rest) : rest, arm, state);
|
|
1965
|
+
return yes === null || no === null ? null : t.conditionalExpression(stmt.test, yes, no);
|
|
1966
|
+
}
|
|
1967
|
+
if (t.isSwitchStatement(stmt)) return lowerSwitch(stmt, rest, arm, state);
|
|
1968
|
+
return null;
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
// The statements an arm of an `if` runs: its own, then, when it can run on
|
|
1972
|
+
// past the `if`, the code after it, which must not read a name the arm's
|
|
1973
|
+
// block declares.
|
|
1974
|
+
function branchList(arm, rest) {
|
|
1975
|
+
const own = t.isBlockStatement(arm) ? arm.body : [arm];
|
|
1976
|
+
if (exits(arm) || rest.length === 0) return own;
|
|
1977
|
+
return t.isBlockStatement(arm) && declaresNames(own) ? [t.blockStatement(own), ...rest] : [...own, ...rest];
|
|
1978
|
+
}
|
|
1979
|
+
|
|
1980
|
+
function declaresNames(stmts) {
|
|
1981
|
+
return stmts.some((s) => t.isVariableDeclaration(s) || t.isFunctionDeclaration(s) || t.isClassDeclaration(s));
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
// The switch selects a branch index, using JS's own discriminant and
|
|
1985
|
+
// case evaluation order. The DOM memo keeps a shown branch when the index
|
|
1986
|
+
// stays equal. The server selects once inside the corresponding region.
|
|
1987
|
+
function lowerSwitch(stmt, rest, arm, state) {
|
|
1988
|
+
const plainRead = (node) => t.isIdentifier(node)
|
|
1989
|
+
|| ((t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) && (!node.computed || t.isStringLiteral(node.property) || t.isNumericLiteral(node.property)) && plainRead(node.object))
|
|
1990
|
+
|| (t.isCallExpression(node) && node.arguments.length === 0 && t.isIdentifier(node.callee));
|
|
1991
|
+
const constant = (node) => t.isStringLiteral(node) || t.isNumericLiteral(node) || t.isBooleanLiteral(node) || t.isNullLiteral(node)
|
|
1992
|
+
|| (t.isTemplateLiteral(node) && node.expressions.length === 0) || (!t.isCallExpression(node) && plainRead(node));
|
|
1993
|
+
const cases = stmt.cases;
|
|
1994
|
+
const last = cases.findIndex((c) => c.test === null);
|
|
1995
|
+
if ((last !== -1 && last !== cases.length - 1) || cases.some((c) => c.test !== null && !constant(c.test)) || breaksOut(stmt)) return null;
|
|
1996
|
+
const end = last === -1 ? cases.length : last;
|
|
1997
|
+
if (cases.slice(0, end).some((c) => c.consequent.length > 0 && !c.consequent.some(exits))) return null;
|
|
1998
|
+
|
|
1999
|
+
const branches = [];
|
|
2000
|
+
const tests = [];
|
|
2001
|
+
for (const c of cases.slice(0, end)) {
|
|
2002
|
+
const body = [];
|
|
2003
|
+
if (c.consequent.length > 0) {
|
|
2004
|
+
const branch = lowerTail(c.consequent, arm, state);
|
|
2005
|
+
if (branch === null) return null;
|
|
2006
|
+
body.push(t.returnStatement(t.numericLiteral(branches.length)));
|
|
2007
|
+
branches.push(branch);
|
|
2008
|
+
}
|
|
2009
|
+
tests.push(t.switchCase(c.test, body));
|
|
2010
|
+
}
|
|
2011
|
+
let output = lowerTail(last === -1 ? rest : branchList(t.blockStatement(cases[last].consequent), rest), arm, state);
|
|
2012
|
+
if (output === null) return null;
|
|
2013
|
+
if (isBranch(output)) output = branchFragment(output);
|
|
2014
|
+
const selector = t.arrowFunctionExpression([], t.blockStatement([t.switchStatement(stmt.discriminant, tests)]));
|
|
2015
|
+
const selected = uniqueName(state, '_switch$');
|
|
2016
|
+
for (let i = branches.length - 1; i >= 0; i--) {
|
|
2017
|
+
const index = state.ssr ? t.identifier(selected) : t.callExpression(t.identifier(selected), []);
|
|
2018
|
+
const branch = branches[i];
|
|
2019
|
+
output = t.conditionalExpression(t.binaryExpression('===', index, t.numericLiteral(i)),
|
|
2020
|
+
isBranch(branch) ? branchFragment(branch) : branch, output);
|
|
2021
|
+
}
|
|
2022
|
+
const declaration = t.variableDeclaration('const', [t.variableDeclarator(t.identifier(selected), state.ssr
|
|
2023
|
+
? t.callExpression(selector, [])
|
|
2024
|
+
: t.callExpression(helper(state, '_$lazyMemo'), [selector]))]);
|
|
2025
|
+
const region = branchFragment(state.ssr
|
|
2026
|
+
? t.arrowFunctionExpression([], t.blockStatement([declaration, t.returnStatement(output)]))
|
|
2027
|
+
: t.arrowFunctionExpression([], output));
|
|
2028
|
+
if (state.ssr) return region;
|
|
2029
|
+
const result = t.callExpression(t.arrowFunctionExpression([], t.blockStatement([declaration, t.returnStatement(region)])), []);
|
|
2030
|
+
result._whatSwitch = true;
|
|
2031
|
+
return result;
|
|
2032
|
+
}
|
|
2033
|
+
|
|
2034
|
+
// Whether a `break` in the switch leaves it (one outside a loop or a switch
|
|
2035
|
+
// written in it, or one with a label).
|
|
2036
|
+
function breaksOut(stmt) {
|
|
2037
|
+
let found = false;
|
|
2038
|
+
const visit = (n, nested) => {
|
|
2039
|
+
if (found || !n || typeof n !== 'object') return;
|
|
2040
|
+
if (Array.isArray(n)) { n.forEach((c) => visit(c, nested)); return; }
|
|
2041
|
+
if (typeof n.type !== 'string' || t.isFunction(n)) return;
|
|
2042
|
+
if (t.isBreakStatement(n) && (!nested || n.label)) { found = true; return; }
|
|
2043
|
+
if (t.isContinueStatement(n) && !nested) { found = true; return; }
|
|
2044
|
+
const inner = nested || (n !== stmt && (t.isLoop(n) || t.isSwitchStatement(n)));
|
|
2045
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key], inner);
|
|
2046
|
+
};
|
|
2047
|
+
for (const c of stmt.cases) visit(c.consequent, false);
|
|
2048
|
+
return found;
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
// --- State a component reads once ---
|
|
2052
|
+
// A component runs once, so state it reads in its body, outside JSX and
|
|
2053
|
+
// outside a function, is read once: React re-renders and reads it again.
|
|
2054
|
+
// Two shapes do something else than they would in React, silently:
|
|
2055
|
+
// - its return decided by the state (`if (loading()) return <Spinner />`,
|
|
2056
|
+
// `return open() ? <Dialog /> : null`) keeps the branch it took first;
|
|
2057
|
+
// - a value derived from it in the body and shown in JSX (`const valid =
|
|
2058
|
+
// name().length > 0; … <button disabled={!valid}>`) keeps its first value.
|
|
2059
|
+
// Both are reported at build time in development as ERR_STATE_READ_ONCE.
|
|
2060
|
+
// State is what a What hook or primitive returns, declared in the body: the
|
|
2061
|
+
// accessor `const x = signal()`, or the first element of `const [x, setX] =
|
|
2062
|
+
// useState()`. A read inside a function written there (`untrack(() => x())`,
|
|
2063
|
+
// a handler) is not one.
|
|
2064
|
+
|
|
2065
|
+
const STATE_SOURCES = new Set(['signal', 'computed', 'useState', 'useReducer', 'useSignal', 'useComputed', 'useMemo', 'useTransition', 'useOptimistic', 'useActionState', 'createResource']);
|
|
2066
|
+
|
|
2067
|
+
function stateAccessors(fnPath) {
|
|
2068
|
+
const names = new Set();
|
|
2069
|
+
const body = fnPath.node.body;
|
|
2070
|
+
if (!t.isBlockStatement(body)) return names;
|
|
2071
|
+
for (const stmt of body.body) {
|
|
2072
|
+
if (!t.isVariableDeclaration(stmt)) continue;
|
|
2073
|
+
for (const decl of stmt.declarations) {
|
|
2074
|
+
if (!isStateSource(fnPath, decl.init)) continue;
|
|
2075
|
+
const id = t.isArrayPattern(decl.id) ? decl.id.elements[0] : decl.id;
|
|
2076
|
+
if (t.isIdentifier(id)) names.add(id.name);
|
|
2077
|
+
}
|
|
2078
|
+
}
|
|
2079
|
+
return names;
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
function isStateSource(fnPath, init) {
|
|
2083
|
+
if (!t.isCallExpression(init) || !t.isIdentifier(init.callee)) return false;
|
|
2084
|
+
const binding = fnPath.scope.getBinding(init.callee.name);
|
|
2085
|
+
if (!binding || binding.kind !== 'module' || !t.isImportSpecifier(binding.path.node)) return false;
|
|
2086
|
+
const imported = binding.path.node.imported;
|
|
2087
|
+
const name = t.isIdentifier(imported) ? imported.name : imported.value;
|
|
2088
|
+
return STATE_SOURCES.has(name) && importedFrom(binding, t.isImportSpecifier, name);
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
// The first state accessor `node` calls (`x()`), outside a function written in it.
|
|
2092
|
+
function stateReadIn(node, names) {
|
|
2093
|
+
return propReadIn(node, (n) => (t.isCallExpression(n) && n.arguments.length === 0 && t.isIdentifier(n.callee) && names.has(n.callee.name) ? `${n.callee.name}()` : null));
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
// A return the lowering left is decided by any state the component reads
|
|
2097
|
+
// (returnReader: its own, a module's, a hook's result, a context's value).
|
|
2098
|
+
export function warnStateReadOnce(fnPath, state) {
|
|
2099
|
+
if (process.env.NODE_ENV === 'production' || state.ssr || state.frameworkFile || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
2100
|
+
const body = fnPath.node.body;
|
|
2101
|
+
if (!t.isBlockStatement(body) || !(containsJsx(fnPath.node) || componentWithoutJsx(fnPath, state) !== null)) return;
|
|
2102
|
+
const live = returnReader(fnPath);
|
|
2103
|
+
const stateRead = (n) => {
|
|
2104
|
+
const read = live(n);
|
|
2105
|
+
return read !== null && !read.prop ? read.name : null;
|
|
2106
|
+
};
|
|
2107
|
+
const code = state.file?.code;
|
|
2108
|
+
for (const test of returnTests(body)) {
|
|
2109
|
+
const read = propReadIn(test, stateRead);
|
|
2110
|
+
if (read !== null) {
|
|
2111
|
+
const text = typeof code === 'string' && test.start != null && test.end - test.start <= 60 ? code.slice(test.start, test.end) : read;
|
|
2112
|
+
warnStateOnce(fnPath, state, test, read, 'it decides what the component returns',
|
|
2113
|
+
`branch where it renders, \`<>{() => (${text} ? <A /> : <B />)}</>\` or \`<Show when={${text}}>\``);
|
|
2114
|
+
break;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
warnStoreHookRead(fnPath, state);
|
|
2118
|
+
const names = stateAccessors(fnPath);
|
|
2119
|
+
// A derived value the return is decided on (memoBranchValues) is read as state is.
|
|
2120
|
+
for (const name of fnPath.node._whatLiveMemos?.names ?? []) names.add(name);
|
|
2121
|
+
if (names.size === 0) return;
|
|
2122
|
+
for (const stmt of body.body) {
|
|
2123
|
+
if (!t.isVariableDeclaration(stmt)) continue;
|
|
2124
|
+
for (const decl of stmt.declarations) {
|
|
2125
|
+
if (!t.isIdentifier(decl.id) || !decl.init || isStateSource(fnPath, decl.init)) continue;
|
|
2126
|
+
const read = stateReadIn(decl.init, names);
|
|
2127
|
+
if (read === null) continue;
|
|
2128
|
+
const binding = fnPath.scope.getBinding(decl.id.name);
|
|
2129
|
+
const shown = binding && binding.referencePaths.some((ref) => ref.findParent((p) => p.isJSXExpressionContainer() || p.isJSXSpreadAttribute() || p === fnPath) !== fnPath);
|
|
2130
|
+
if (!shown) continue;
|
|
2131
|
+
warnStateOnce(fnPath, state, decl, read, `\`${decl.id.name}\` is computed from it in the component body and shown in JSX, so it keeps its first value`,
|
|
2132
|
+
`write the expression in the JSX where it is shown, or derive it with \`computed(() => …)\` (\`useMemo\`) and call it there (\`${decl.id.name}()\`); \`untrack(() => ${read})\` keeps the first value on purpose`);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
|
|
2137
|
+
// A hook ran during setup, so a field computed then can be a snapshot even
|
|
2138
|
+
// if the lowered guard reads it reactively. Inspect the original guard and
|
|
2139
|
+
// warn only when the hook's return can be traced to a state read.
|
|
2140
|
+
function warnHookSnapshots(fnPath, state) {
|
|
2141
|
+
const { results, parts } = hookNames(fnPath);
|
|
2142
|
+
const hooks = new Map([...results, ...parts].filter(([, part]) => part.own));
|
|
2143
|
+
if (hooks.size === 0) return;
|
|
2144
|
+
for (const test of returnTests(fnPath.node.body)) {
|
|
2145
|
+
const snapshot = snapshotGuardRead(test, (node) => {
|
|
2146
|
+
let root = node;
|
|
2147
|
+
const path = [];
|
|
2148
|
+
while (t.isMemberExpression(root) || t.isOptionalMemberExpression(root)) {
|
|
2149
|
+
const key = propertyName(root.property, root.computed);
|
|
2150
|
+
if (key === null) return null;
|
|
2151
|
+
path.unshift(key);
|
|
2152
|
+
root = root.object;
|
|
2153
|
+
}
|
|
2154
|
+
if (!t.isIdentifier(root)) return null;
|
|
2155
|
+
const part = hooks.get(root.name);
|
|
2156
|
+
if (!part || fnPath.scope.getBinding(root.name)?.scope !== fnPath.scope) return null;
|
|
2157
|
+
// The result of calling an accessor is live. The traversal also sees
|
|
2158
|
+
// its callee, so filter that use by the identifier's binding references.
|
|
2159
|
+
const ref = fnPath.scope.getBinding(root.name).referencePaths.find((ref) => ref.node === root);
|
|
2160
|
+
if (!ref || ((ref.parentPath.isCallExpression() || ref.parentPath.isOptionalCallExpression()) && ref.key === 'callee')) return null;
|
|
2161
|
+
const hook = snapshotHook(fnPath.scope.getBinding(part.local), state);
|
|
2162
|
+
if (!hook || !snapshotReturn(hook, [...part.keys, ...path], part.keys.length > 0, 0, { remaining: 1000 })) return null;
|
|
2163
|
+
return { part, name: [root.name, ...path].join('.'), member: path.length > 0 };
|
|
2164
|
+
});
|
|
2165
|
+
if (snapshot === null) continue;
|
|
2166
|
+
const { name, part, member } = snapshot;
|
|
2167
|
+
const keep = part.keys.length > 0
|
|
2168
|
+
? `have it return an accessor, or keep its result and read a getter where it is used`
|
|
2169
|
+
: `have it return an accessor (\`return () => …\`, or the signal or \`computed\` itself) and call it here (\`${name}()\`)`;
|
|
2170
|
+
const fix = member
|
|
2171
|
+
? `return a getter or an accessor for \`${name}\` from \`${part.hook}()\`, so reading it can follow the state`
|
|
2172
|
+
: `if \`${name}\` is an accessor, call it (\`${name}()\`), and the return follows it; if \`${part.hook}()\` returns the value itself, ${keep}`;
|
|
2173
|
+
warnStateOnce(fnPath, state, test, name, `\`${name}\` is what \`${part.hook}()\` returned when the component ran, and it decides what the component returns`, fix);
|
|
2174
|
+
return;
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
function snapshotGuardRead(node, read) {
|
|
2179
|
+
if (!node || t.isFunction(node)) return null;
|
|
2180
|
+
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
|
2181
|
+
return read(node) ?? (node.computed ? snapshotGuardRead(node.property, read) : null);
|
|
2182
|
+
}
|
|
2183
|
+
if (t.isIdentifier(node)) return read(node);
|
|
2184
|
+
for (const key of t.VISITOR_KEYS[node.type] || []) {
|
|
2185
|
+
const children = Array.isArray(node[key]) ? node[key] : [node[key]];
|
|
2186
|
+
for (const child of children) {
|
|
2187
|
+
const result = snapshotGuardRead(child, read);
|
|
2188
|
+
if (result !== null) return result;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
return null;
|
|
2192
|
+
}
|
|
2193
|
+
|
|
2194
|
+
function snapshotFunction(path) {
|
|
2195
|
+
return path?.isFunction() ? path : path?.isVariableDeclarator() && path.get('init').isFunction() ? path.get('init') : null;
|
|
2196
|
+
}
|
|
2197
|
+
|
|
2198
|
+
function snapshotHook(binding, state) {
|
|
2199
|
+
if (!binding?.constant) return null;
|
|
2200
|
+
const path = binding.path;
|
|
2201
|
+
if (!path.isImportSpecifier() && !path.isImportDefaultSpecifier()) return snapshotFunction(path);
|
|
2202
|
+
const source = path.parent.source.value;
|
|
2203
|
+
if (!source.startsWith('./') && !source.startsWith('../')) return null;
|
|
2204
|
+
const filename = state.file?.opts.filename;
|
|
2205
|
+
const host = /** @type {any} */ (globalThis).process;
|
|
2206
|
+
if (!filename || typeof host?.getBuiltinModule !== 'function') return null;
|
|
2207
|
+
const builtin = host.getBuiltinModule.bind(host);
|
|
2208
|
+
const paths = builtin('node:path');
|
|
2209
|
+
const target = paths.resolve(paths.dirname(filename), source);
|
|
2210
|
+
const modules = state._whatHookModules ??= new Map();
|
|
2211
|
+
if (!modules.has(target)) modules.set(target, snapshotExports(target, paths, builtin));
|
|
2212
|
+
const name = path.isImportDefaultSpecifier() ? 'default' : path.node.imported.name ?? path.node.imported.value;
|
|
2213
|
+
return modules.get(target).get(name) ?? null;
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
function snapshotExports(target, paths, builtin) {
|
|
2217
|
+
const exports = new Map();
|
|
2218
|
+
const { readFileSync } = builtin('node:fs');
|
|
2219
|
+
const candidates = paths.extname(target) ? [target] : [target, ...['.js', '.mjs', '.jsx', '.ts', '.tsx'].map((ext) => target + ext)];
|
|
2220
|
+
for (const filename of candidates) {
|
|
2221
|
+
try {
|
|
2222
|
+
const source = readFileSync(filename, 'utf8');
|
|
2223
|
+
const load = builtin('node:module').createRequire(import.meta.url);
|
|
2224
|
+
const { parseSync, traverse } = load('@babel/core');
|
|
2225
|
+
const ext = paths.extname(filename);
|
|
2226
|
+
const plugins = ext === '.ts' || ext === '.mts' ? ['typescript'] : ext === '.tsx' ? ['typescript', 'jsx'] : ['jsx'];
|
|
2227
|
+
const ast = parseSync(source, {
|
|
2228
|
+
filename, configFile: false, babelrc: false, parserOpts: { plugins },
|
|
2229
|
+
});
|
|
2230
|
+
traverse(ast, {
|
|
2231
|
+
ExportNamedDeclaration(path) {
|
|
2232
|
+
if (path.node.source) return;
|
|
2233
|
+
const declaration = path.get('declaration');
|
|
2234
|
+
for (const name of Object.keys(declaration.getOuterBindingIdentifiers())) {
|
|
2235
|
+
exports.set(name, snapshotFunction(path.scope.getBinding(name)?.path));
|
|
2236
|
+
}
|
|
2237
|
+
for (const spec of path.node.specifiers) {
|
|
2238
|
+
if (t.isExportSpecifier(spec)) exports.set(spec.exported.name ?? spec.exported.value, snapshotFunction(path.scope.getBinding(spec.local.name)?.path));
|
|
2239
|
+
}
|
|
2240
|
+
},
|
|
2241
|
+
ExportDefaultDeclaration(path) {
|
|
2242
|
+
const declaration = path.get('declaration');
|
|
2243
|
+
exports.set('default', snapshotFunction(declaration.isIdentifier() ? declaration.scope.getBinding(declaration.node.name)?.path : declaration));
|
|
2244
|
+
},
|
|
2245
|
+
});
|
|
2246
|
+
break;
|
|
2247
|
+
} catch {
|
|
2248
|
+
// Virtual modules and source this parser cannot read carry no evidence.
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
return exports;
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
function snapshotReturn(fn, keys, readGetter, depth, budget) {
|
|
2255
|
+
if (budget.remaining <= 0 || depth > 50 || fn.node.async || fn.node.generator) return false;
|
|
2256
|
+
const body = fn.get('body');
|
|
2257
|
+
if (!body.isBlockStatement()) return snapshotValue(body, keys, readGetter, depth + 1, budget);
|
|
2258
|
+
let found = false;
|
|
2259
|
+
body.traverse({
|
|
2260
|
+
Function(path) { path.skip(); },
|
|
2261
|
+
ReturnStatement(path) {
|
|
2262
|
+
if (snapshotValue(path.get('argument'), keys, readGetter, depth + 1, budget)) { found = true; path.stop(); }
|
|
2263
|
+
},
|
|
2264
|
+
});
|
|
2265
|
+
return found;
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
// Follow the used field through object and tuple literals and const
|
|
2269
|
+
// aliases. A getter is read during setup only when it was destructured.
|
|
2270
|
+
function snapshotValue(value, keys, readGetter, depth, budget) {
|
|
2271
|
+
if (!value.node || depth > 50 || budget.remaining-- <= 0) return false;
|
|
2272
|
+
const next = (path, rest = keys) => snapshotValue(path, rest, readGetter, depth + 1, budget);
|
|
2273
|
+
if (value.isIdentifier()) {
|
|
2274
|
+
const binding = value.scope.getBinding(value.node.name);
|
|
2275
|
+
const declaration = binding?.path;
|
|
2276
|
+
if (!declaration?.isVariableDeclarator()) return false;
|
|
2277
|
+
if (isStateSource(declaration, declaration.node.init)) {
|
|
2278
|
+
const id = declaration.node.id;
|
|
2279
|
+
return keys.length === 0 && (t.isIdentifier(id) || t.isArrayPattern(id) && id.elements[0] === binding.identifier);
|
|
2280
|
+
}
|
|
2281
|
+
return binding.constant && t.isIdentifier(declaration.node.id) && next(declaration.get('init'));
|
|
2282
|
+
}
|
|
2283
|
+
if (value.isObjectExpression()) {
|
|
2284
|
+
if (keys.length === 0) return false;
|
|
2285
|
+
for (const prop of value.get('properties').reverse()) {
|
|
2286
|
+
if (prop.isSpreadElement()) continue;
|
|
2287
|
+
if (propertyName(prop.node.key, prop.node.computed) !== keys[0]) continue;
|
|
2288
|
+
return prop.isObjectProperty() ? next(prop.get('value'), keys.slice(1))
|
|
2289
|
+
: readGetter && prop.node.kind === 'get' && snapshotReturn(prop, keys.slice(1), false, depth + 1, budget);
|
|
2290
|
+
}
|
|
2291
|
+
return false;
|
|
2292
|
+
}
|
|
2293
|
+
if (value.isArrayExpression()) {
|
|
2294
|
+
const element = /^\d+$/.test(keys[0]) ? value.get('elements')[Number(keys[0])] : null;
|
|
2295
|
+
return element != null && next(element, keys.slice(1));
|
|
2296
|
+
}
|
|
2297
|
+
if (value.isConditionalExpression()) {
|
|
2298
|
+
return next(value.get('test'), []) || next(value.get('consequent')) || next(value.get('alternate'));
|
|
2299
|
+
}
|
|
2300
|
+
if (value.isCallExpression() || value.isOptionalCallExpression()) {
|
|
2301
|
+
const callee = value.node.callee;
|
|
2302
|
+
const what = importedWhatName(value, callee);
|
|
2303
|
+
if (what === 'untrack' || STATE_SOURCES.has(what)) return false;
|
|
2304
|
+
if (what === 'useContext') return true;
|
|
2305
|
+
if (t.isIdentifier(callee)) {
|
|
2306
|
+
if (next(value.get('callee'), [])) return true;
|
|
2307
|
+
const binding = value.scope.getBinding(callee.name);
|
|
2308
|
+
const fn = binding?.constant ? snapshotFunction(binding.path) : null;
|
|
2309
|
+
if (fn && snapshotReturn(fn, keys, readGetter, depth + 1, budget)) return true;
|
|
2310
|
+
}
|
|
2311
|
+
return value.get('arguments').some((arg) => next(arg, []));
|
|
2312
|
+
}
|
|
2313
|
+
if (value.isFunction() || value.isClass()) return false;
|
|
2314
|
+
for (const key of t.VISITOR_KEYS[value.node.type] || []) {
|
|
2315
|
+
const child = value.get(key);
|
|
2316
|
+
if (Array.isArray(child) ? child.some((path) => next(path)) : next(child)) return true;
|
|
2317
|
+
}
|
|
2318
|
+
return false;
|
|
2319
|
+
}
|
|
2320
|
+
|
|
2321
|
+
// `const auth = createStore({ user: null })` makes a hook: what the hook
|
|
2322
|
+
// returns holds the store's fields (`const state = auth()`, `state.user`). A
|
|
2323
|
+
// field read off the hook itself (`auth.user`) is a property of the function,
|
|
2324
|
+
// which no write to the store changes. Reported once per component, for a
|
|
2325
|
+
// read in its body or its JSX (a call, `auth.login()`, throws by itself).
|
|
2326
|
+
function warnStoreHookRead(fnPath, state) {
|
|
2327
|
+
/** @type {any} */
|
|
2328
|
+
let found = null;
|
|
2329
|
+
fnPath.traverse({
|
|
2330
|
+
Function(inner) { if (isComponentFunction(inner)) inner.skip(); },
|
|
2331
|
+
MemberExpression(member) {
|
|
2332
|
+
const { object, property } = member.node;
|
|
2333
|
+
if (found !== null || member.node.computed || !t.isIdentifier(object) || !t.isIdentifier(property) || (member.parentPath.isCallExpression() && member.key === 'callee')) return;
|
|
2334
|
+
const binding = member.scope.getBinding(object.name);
|
|
2335
|
+
const init = binding?.kind === 'const' && binding.scope.path.isProgram() && binding.path.isVariableDeclarator() ? binding.path.node.init : null;
|
|
2336
|
+
if (t.isCallExpression(init) && importedWhatName(fnPath, init.callee) === 'createStore') found = member.node;
|
|
2337
|
+
},
|
|
2338
|
+
});
|
|
2339
|
+
if (found === null) return;
|
|
2340
|
+
const hook = found.object.name;
|
|
2341
|
+
const name = `${hook}.${found.property.name}`;
|
|
2342
|
+
warnStateOnce(fnPath, state, found, name, `\`${hook}\` is the hook createStore() made, not the store's state, so \`${name}\` is a property of that function, which no write to the store changes`,
|
|
2343
|
+
`call the hook in the component and read the field from what it returns (\`const state = ${hook}();\`, then \`state.${found.property.name}\`), which follows the store`);
|
|
2344
|
+
}
|
|
2345
|
+
|
|
2346
|
+
// --- A value derived from a prop in the body ---
|
|
2347
|
+
// `function Title({ name }) { const label = name.toUpperCase(); return
|
|
2348
|
+
// <h1>{label}</h1>; }`: the component runs once, so `label` is computed once,
|
|
2349
|
+
// from the first `name`, and the JSX keeps showing it when the parent's state
|
|
2350
|
+
// changes, where React computes it again on every render. Reported at build
|
|
2351
|
+
// time in development as ERR_PROP_READ_ONCE: a name declared in the body
|
|
2352
|
+
// (`const label = …`, `const { title } = post`) whose initializer reads a
|
|
2353
|
+
// prop outside a function and outside JSX written in it, and that JSX reads.
|
|
2354
|
+
// Not reported:
|
|
2355
|
+
// - an alias the compiler reads where it is used (`const label = props.name`,
|
|
2356
|
+
// inlinePropAliases) and a pattern destructured from the props or from
|
|
2357
|
+
// their rest element (`const { name } = props`);
|
|
2358
|
+
// - a value read only outside JSX (an effect, a handler declared in the body);
|
|
2359
|
+
// - a function (`const label = () => name.toUpperCase()`), a read inside a
|
|
2360
|
+
// function (`untrack(() => name)`) and a read inside JSX (`const title =
|
|
2361
|
+
// <h1>{name}</h1>`), which are live;
|
|
2362
|
+
// - what a hook or a What primitive is handed (`useState(initial)`,
|
|
2363
|
+
// `signal(props.value)`), which seeds state once, as React's hooks do;
|
|
2364
|
+
// - what a function prop returns, called in the body (`const header =
|
|
2365
|
+
// renderHeader()`): the parent's code built it, usually JSX whose bindings
|
|
2366
|
+
// follow its own state;
|
|
2367
|
+
// - `children`, which is JSX built where it is read, and a route's `params`
|
|
2368
|
+
// and `route`: a page is built again for other params, and a layout's read
|
|
2369
|
+
// in the body is documented as read once (packages/router/README.md). A
|
|
2370
|
+
// route's `query` is reported: a change of query alone keeps the page;
|
|
2371
|
+
// - a name used as a tag (`const Icon = icons[kind]`, docs/GOTCHAS.md).
|
|
2372
|
+
// A value derived only from fields of props (`item.title.toUpperCase()`) is
|
|
2373
|
+
// left to the page in a build with devMetadata (fieldReads): a keyed row
|
|
2374
|
+
// handed its item builds the row again when such a field changes, so the
|
|
2375
|
+
// read reports it (what-core _propField) only where the component renders
|
|
2376
|
+
// outside such a row.
|
|
2377
|
+
const UNREPORTED_PROPS = new Set(['children', 'params', 'route']);
|
|
2378
|
+
|
|
2379
|
+
export function warnDerivedPropOnce(fnPath, state) {
|
|
2380
|
+
if (process.env.NODE_ENV === 'production' || state.ssr || state.frameworkFile || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
2381
|
+
const params = fnPath.node.params;
|
|
2382
|
+
if (params.length === 0 || params.length > 2) return;
|
|
2383
|
+
const body = fnPath.node.body;
|
|
2384
|
+
if (!t.isBlockStatement(body) || !(containsJsx(fnPath.node) || componentWithoutJsx(fnPath, state) !== null)) return;
|
|
2385
|
+
const props = derivedPropReader(fnPath);
|
|
2386
|
+
if (props === null) return;
|
|
2387
|
+
const code = state.file?.code;
|
|
2388
|
+
for (const stmt of fnPath.get('body.body')) {
|
|
2389
|
+
if (!stmt.isVariableDeclaration()) continue;
|
|
2390
|
+
for (const decl of stmt.get('declarations')) {
|
|
2391
|
+
const { id, init } = decl.node;
|
|
2392
|
+
if (!init || seedsOnce(fnPath, init) || props.live(decl) || props.callsProp(decl.get('init'))) continue;
|
|
2393
|
+
const read = firstPropRead(decl.get('init'), props.read);
|
|
2394
|
+
if (read === null) continue;
|
|
2395
|
+
const shown = [...collectNames(id)].find((name) => {
|
|
2396
|
+
const binding = decl.scope.getBinding(name);
|
|
2397
|
+
return binding !== undefined && !binding.referencePaths.some((ref) => ref.isJSXIdentifier() || isCalled(ref))
|
|
2398
|
+
&& binding.referencePaths.some((ref) => shownValue(ref, fnPath));
|
|
2399
|
+
});
|
|
2400
|
+
if (shown === undefined) continue;
|
|
2401
|
+
const source = typeof code === 'string' && init.start != null && init.end - init.start <= 60 ? code.slice(init.start, init.end) : null;
|
|
2402
|
+
const text = source !== null && !/[`\n]/.test(source) ? source : null;
|
|
2403
|
+
const fix = t.isIdentifier(id)
|
|
2404
|
+
? `write the expression in the JSX where it is shown${text === null ? '' : ` (\`{${text}}\`)`}, or make \`${shown}\` a function (\`const ${shown} = () => ${text ?? '…'}\`) and call it there (\`{${shown}()}\`); \`untrack(() => ${read})\` keeps the first value on purpose`
|
|
2405
|
+
: `read it where it is shown${text === null ? '' : ` (\`{${text}.${shown}}\`)`} instead of destructuring it in the body, or make it a function (\`const ${shown} = () => …\`) and call it there (\`{${shown}()}\`)`;
|
|
2406
|
+
const why = `\`${shown}\` is computed from it in the component body and shown in JSX`;
|
|
2407
|
+
const warn = () => warnReadOnce(fnPath, state, decl.node, read, why, fix);
|
|
2408
|
+
const fields = fieldReads(decl.get('init'), props.read);
|
|
2409
|
+
const record = fields === null ? null : diagnosticOf(state, 'ERR_PROP_READ_ONCE', { name: read, component: componentName(fnPath), reason: why }, decl.node);
|
|
2410
|
+
if (fields === null || record === null) {
|
|
2411
|
+
warn();
|
|
2412
|
+
continue;
|
|
2413
|
+
}
|
|
2414
|
+
const check = { warn, record, nodes: fields, id: null };
|
|
2415
|
+
for (const node of fields) node._whatReadOnce = check;
|
|
2416
|
+
(state._readOnceChecks ??= []).push(check);
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
// The member reads of props in `path` (outside functions and JSX written in
|
|
2422
|
+
// it) when every prop it reads is read for one field (`item.title`,
|
|
2423
|
+
// `props.item.title`), which readPropFields rewrites as `_$propField` reads,
|
|
2424
|
+
// else null. A keyed row component handed its item records such a field,
|
|
2425
|
+
// and its row is built again when the field changes: whether the component
|
|
2426
|
+
// is a row is known only where it renders, so the page decides.
|
|
2427
|
+
function fieldReads(path, read) {
|
|
2428
|
+
/** @type {any[]} */
|
|
2429
|
+
const fields = [];
|
|
2430
|
+
let other = false;
|
|
2431
|
+
const visit = (inner) => {
|
|
2432
|
+
if (read(inner) === null) return false;
|
|
2433
|
+
const parent = inner.parentPath;
|
|
2434
|
+
if ((parent.isMemberExpression() && inner.key === 'object' && propertyName(parent.node.property, parent.node.computed) !== null && isReadOnly(parent))) fields.push(parent.node);
|
|
2435
|
+
else other = true;
|
|
2436
|
+
return true;
|
|
2437
|
+
};
|
|
2438
|
+
if (!visit(path)) {
|
|
2439
|
+
path.traverse({
|
|
2440
|
+
enter(inner) {
|
|
2441
|
+
if (inner.isFunction() || inner.isJSXElement() || inner.isJSXFragment() || visit(inner)) inner.skip();
|
|
2442
|
+
if (other) inner.stop();
|
|
2443
|
+
},
|
|
2444
|
+
});
|
|
2445
|
+
}
|
|
2446
|
+
return other || fields.length === 0 ? null : fields;
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
// The props of the component `fnPath`, for derived values: `read` names the
|
|
2450
|
+
// prop a path reads (a destructured name, or `props.<key>` of a props
|
|
2451
|
+
// parameter), else null; `live` tells a declarator the compiler reads where
|
|
2452
|
+
// it is used. Null when the component has no props to read.
|
|
2453
|
+
function derivedPropReader(fnPath) {
|
|
2454
|
+
const param = fnPath.node.params[0];
|
|
2455
|
+
const bindings = new Set();
|
|
2456
|
+
const rests = new Set();
|
|
2457
|
+
const add = (pattern) => {
|
|
2458
|
+
for (const p of pattern.properties) {
|
|
2459
|
+
const key = t.isRestElement(p) ? null : propertyName(p.key, p.computed);
|
|
2460
|
+
if (key !== null && UNREPORTED_PROPS.has(key)) continue;
|
|
2461
|
+
for (const name of collectNames(t.isRestElement(p) ? p : p.value)) {
|
|
2462
|
+
const binding = fnPath.scope.getBinding(name);
|
|
2463
|
+
if (!binding) continue;
|
|
2464
|
+
bindings.add(binding);
|
|
2465
|
+
if (t.isRestElement(p)) rests.add(binding);
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
};
|
|
2469
|
+
const propsBinding = t.isIdentifier(param) ? fnPath.scope.getBinding(param.name) ?? null : null;
|
|
2470
|
+
if (t.isObjectPattern(param)) add(param);
|
|
2471
|
+
else if (propsBinding === null || propsBinding.kind !== 'param') return null;
|
|
2472
|
+
else {
|
|
2473
|
+
const name = propsBinding.identifier.name;
|
|
2474
|
+
for (const stmt of fnPath.node.body.body) {
|
|
2475
|
+
if (!t.isVariableDeclaration(stmt)) continue;
|
|
2476
|
+
for (const decl of stmt.declarations) if (t.isObjectPattern(decl.id) && t.isIdentifier(decl.init, { name })) add(decl.id);
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
const isProps = (node, scope) => propsBinding !== null && t.isIdentifier(node) && scope.getBinding(node.name) === propsBinding;
|
|
2480
|
+
return {
|
|
2481
|
+
read(path) {
|
|
2482
|
+
if (path.isIdentifier() && path.isReferencedIdentifier()) {
|
|
2483
|
+
const binding = path.scope.getBinding(path.node.name);
|
|
2484
|
+
return binding && bindings.has(binding) ? path.node.name : null;
|
|
2485
|
+
}
|
|
2486
|
+
if ((path.isMemberExpression() || path.isOptionalMemberExpression()) && isProps(path.node.object, path.scope)) {
|
|
2487
|
+
const key = propertyName(path.node.property, path.node.computed);
|
|
2488
|
+
return key !== null && !UNREPORTED_PROPS.has(key) ? `props.${key}` : null;
|
|
2489
|
+
}
|
|
2490
|
+
return null;
|
|
2491
|
+
},
|
|
2492
|
+
callsProp(path) {
|
|
2493
|
+
while (path.isTSAsExpression() || path.isTSSatisfiesExpression() || path.isTSNonNullExpression() || path.isParenthesizedExpression()) path = path.get('expression');
|
|
2494
|
+
return (path.isCallExpression() || path.isOptionalCallExpression()) && this.read(path.get('callee')) !== null;
|
|
2495
|
+
},
|
|
2496
|
+
live(decl) {
|
|
2497
|
+
const { id, init } = decl.node;
|
|
2498
|
+
if (!t.isIdentifier(id)) {
|
|
2499
|
+
if (isProps(init, decl.scope)) return true;
|
|
2500
|
+
const binding = t.isIdentifier(init) ? decl.scope.getBinding(init.name) : null;
|
|
2501
|
+
return binding != null && rests.has(binding);
|
|
2502
|
+
}
|
|
2503
|
+
if (decl.parent.kind !== 'const') return false;
|
|
2504
|
+
let node = init;
|
|
2505
|
+
while (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
|
2506
|
+
if (propertyName(node.property, node.computed) === null) return false;
|
|
2507
|
+
node = node.object;
|
|
2508
|
+
}
|
|
2509
|
+
return node !== init && isProps(node, decl.scope);
|
|
2510
|
+
},
|
|
2511
|
+
};
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
// A name called anywhere in the component (`draft()`, `register(name)`) holds
|
|
2515
|
+
// a function or an accessor the body fetched once, whose value follows by
|
|
2516
|
+
// itself: it is not a value read once.
|
|
2517
|
+
function isCalled(ref) {
|
|
2518
|
+
const parent = ref.parentPath;
|
|
2519
|
+
return (parent.isCallExpression() || parent.isOptionalCallExpression() || parent.isTaggedTemplateExpression()) && (ref.key === 'callee' || ref.key === 'tag');
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2522
|
+
// Whether the reference `ref` shows its value in JSX: it stands in JSX (a
|
|
2523
|
+
// child, an attribute, or a function written there such as a thunk child or
|
|
2524
|
+
// a render prop) as a value. Not when it is:
|
|
2525
|
+
// - in an event handler, a ref or a key, which are read once by design (a
|
|
2526
|
+
// handler written directly too) or read when they run;
|
|
2527
|
+
// - spread (`{...field}`): props a helper made once;
|
|
2528
|
+
// - only read for a field (`card.title`): the field is read where it is shown.
|
|
2529
|
+
function shownValue(ref, fnPath) {
|
|
2530
|
+
const parent = ref.parentPath;
|
|
2531
|
+
if (parent.isSpreadElement() || parent.isJSXSpreadAttribute() || parent.isJSXSpreadChild()) return false;
|
|
2532
|
+
if ((parent.isMemberExpression() || parent.isOptionalMemberExpression()) && ref.key === 'object' && !parent.node.computed) {
|
|
2533
|
+
const use = parent.parentPath;
|
|
2534
|
+
if (!((use.isCallExpression() || use.isOptionalCallExpression()) && parent.key === 'callee')) return false;
|
|
2535
|
+
}
|
|
2536
|
+
for (let p = parent; p !== null && p !== fnPath; p = p.parentPath) {
|
|
2537
|
+
if (p.isJSXSpreadAttribute() || p.isJSXSpreadChild()) return true;
|
|
2538
|
+
if (!p.isJSXExpressionContainer()) continue;
|
|
2539
|
+
const attr = p.parentPath;
|
|
2540
|
+
if (!attr.isJSXAttribute()) return true;
|
|
2541
|
+
const name = getAttrName(attr.node);
|
|
2542
|
+
const element = attr.parentPath.node.name;
|
|
2543
|
+
const onDomElement = t.isJSXIdentifier(element) && /^[a-z]/.test(element.name);
|
|
2544
|
+
return name !== 'ref' && name !== 'key' && !/^on[A-Z:]/.test(name) && !(onDomElement && /^on[a-z]+$/.test(name));
|
|
2545
|
+
}
|
|
2546
|
+
return false;
|
|
2547
|
+
}
|
|
2548
|
+
|
|
2549
|
+
// A call that hands its arguments to a hook (`useState(initial)`) or to a
|
|
2550
|
+
// What primitive (`signal(props.value)`), which reads them once by design.
|
|
2551
|
+
function seedsOnce(fnPath, init) {
|
|
2552
|
+
while (t.isTSAsExpression(init) || t.isTSSatisfiesExpression(init) || t.isTSNonNullExpression(init) || t.isParenthesizedExpression(init)) init = init.expression;
|
|
2553
|
+
if (!t.isCallExpression(init)) return false;
|
|
2554
|
+
const callee = t.isMemberExpression(init.callee) && !init.callee.computed ? init.callee.property : init.callee;
|
|
2555
|
+
if (!t.isIdentifier(callee)) return false;
|
|
2556
|
+
return /^use[A-Z0-9]/.test(callee.name) || (callee === init.callee && importedWhatName(fnPath, callee) !== null);
|
|
2557
|
+
}
|
|
2558
|
+
|
|
2559
|
+
// The first prop `read` names in the expression at `path`, outside the
|
|
2560
|
+
// functions and the JSX written in it.
|
|
2561
|
+
function firstPropRead(path, read) {
|
|
2562
|
+
if (path.isFunction() || path.isJSXElement() || path.isJSXFragment()) return null;
|
|
2563
|
+
let found = read(path);
|
|
2564
|
+
if (found !== null) return found;
|
|
2565
|
+
path.traverse({
|
|
2566
|
+
enter(inner) {
|
|
2567
|
+
if (inner.isFunction() || inner.isJSXElement() || inner.isJSXFragment()) {
|
|
2568
|
+
inner.skip();
|
|
2569
|
+
return;
|
|
2570
|
+
}
|
|
2571
|
+
found = read(inner);
|
|
2572
|
+
if (found !== null) inner.stop();
|
|
2573
|
+
},
|
|
2574
|
+
});
|
|
2575
|
+
return found;
|
|
2576
|
+
}
|
|
2577
|
+
|
|
2578
|
+
// --- What a useEffect cleanup reads ---
|
|
2579
|
+
// `useEffect(() => { join(roomId); return () => leave(roomId); })`: React's
|
|
2580
|
+
// cleanup closes over the render that made it, so when `roomId` changes it
|
|
2581
|
+
// leaves the old room. A component runs once, so `roomId` read in the
|
|
2582
|
+
// cleanup would be read when the cleanup runs, after the change, and leave
|
|
2583
|
+
// the new room. So each prop (`props.<key>`, a destructured prop) and each
|
|
2584
|
+
// call of one of the component's state accessors that a cleanup reads is
|
|
2585
|
+
// read when the run that returns the cleanup starts, into a local the
|
|
2586
|
+
// cleanup reads instead: the cleanup sees the values of the run that made
|
|
2587
|
+
// it, with a dependency array or without. A value only the cleanup reads is
|
|
2588
|
+
// read untracked there, so the effect does not come to depend on it. A
|
|
2589
|
+
// cleanup is a function the callback returns (a function the component
|
|
2590
|
+
// declares and hands to useEffect counts as its callback); reads in the
|
|
2591
|
+
// functions written inside it are kept the same way. What's own effect() is
|
|
2592
|
+
// not changed: it is not React's API, and its cleanup reads what it reads
|
|
2593
|
+
// when it runs (docs/GOTCHAS.md, section 27).
|
|
2594
|
+
|
|
2595
|
+
/** Keep the props and the state a useEffect cleanup of the component `fnPath` reads, as its run saw them. */
|
|
2596
|
+
export function keepCleanupValues(fnPath, state) {
|
|
2597
|
+
if (state.ssr || state.frameworkFile || !isComponentFunction(fnPath) || isRowFunction(fnPath, state) || !t.isBlockStatement(fnPath.node.body)) return;
|
|
2598
|
+
const param = fnPath.node.params[0];
|
|
2599
|
+
const props = t.isIdentifier(param) ? fnPath.scope.getBinding(param.name) ?? null : null;
|
|
2600
|
+
const accessors = stateAccessors(fnPath);
|
|
2601
|
+
// A value of the body made a memo (memoLiveLets, memoBranchValues) is read as state is.
|
|
2602
|
+
for (const name of fnPath.node._whatLiveMemos?.names ?? []) accessors.add(name);
|
|
2603
|
+
if ((props === null || props.kind !== 'param') && accessors.size === 0) return;
|
|
2604
|
+
const reads = (path) => {
|
|
2605
|
+
if ((path.isMemberExpression() || path.isOptionalMemberExpression()) && props !== null && props.kind === 'param'
|
|
2606
|
+
&& t.isIdentifier(path.node.object) && path.scope.getBinding(path.node.object.name) === props && notWritten(path)) {
|
|
2607
|
+
const key = propertyName(path.node.property, path.node.computed);
|
|
2608
|
+
return key === null ? null : { key: `props.${key}`, name: key };
|
|
2609
|
+
}
|
|
2610
|
+
if (path.isCallExpression() && path.node.arguments.length === 0 && t.isIdentifier(path.node.callee) && accessors.has(path.node.callee.name)
|
|
2611
|
+
&& path.scope.getBinding(path.node.callee.name) === fnPath.scope.getBinding(path.node.callee.name)) {
|
|
2612
|
+
return { key: `${path.node.callee.name}()`, name: path.node.callee.name };
|
|
2613
|
+
}
|
|
2614
|
+
return null;
|
|
2615
|
+
};
|
|
2616
|
+
for (const stmt of fnPath.get('body.body')) {
|
|
2617
|
+
const call = stmt.isExpressionStatement() ? stmt.get('expression') : null;
|
|
2618
|
+
if (call === null || !call.isCallExpression() || importedWhatName(fnPath, call.node.callee) !== 'useEffect') continue;
|
|
2619
|
+
const callback = effectCallback(fnPath, call.get('arguments.0'));
|
|
2620
|
+
if (callback !== null) keepRunValues(callback, state, call.node.arguments.length < 2, reads);
|
|
2621
|
+
}
|
|
2622
|
+
}
|
|
2623
|
+
|
|
2624
|
+
// The function a useEffect call is handed: written there, or declared in the
|
|
2625
|
+
// component (`function subscribe() { … }`, `const subscribe = () => …`).
|
|
2626
|
+
function effectCallback(fnPath, arg) {
|
|
2627
|
+
if (!arg.node || arg.node.async) return null;
|
|
2628
|
+
if (arg.isFunction()) return arg;
|
|
2629
|
+
if (!arg.isIdentifier()) return null;
|
|
2630
|
+
const binding = fnPath.scope.getBinding(arg.node.name);
|
|
2631
|
+
if (!binding || binding.scope !== fnPath.scope || binding.constantViolations.length > 0) return null;
|
|
2632
|
+
if (binding.path.isFunctionDeclaration()) return binding.path.node.async ? null : binding.path;
|
|
2633
|
+
const init = binding.path.isVariableDeclarator() ? binding.path.get('init') : null;
|
|
2634
|
+
return init !== null && init.isFunction() && !init.node.async ? init : null;
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
// A member read that is not written through: not an assignment's target, an
|
|
2638
|
+
// update, a delete.
|
|
2639
|
+
function notWritten(path) {
|
|
2640
|
+
const parent = path.parentPath;
|
|
2641
|
+
if ((parent.isAssignmentExpression() && path.key === 'left') || parent.isUpdateExpression() || parent.isUnaryExpression({ operator: 'delete' })) return false;
|
|
2642
|
+
return !((parent.isForInStatement() || parent.isForOfStatement()) && path.key === 'left');
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
function keepRunValues(callback, state, tracked, reads) {
|
|
2646
|
+
const body = callback.get('body');
|
|
2647
|
+
const cleanups = [];
|
|
2648
|
+
if (body.isFunction()) cleanups.push(body);
|
|
2649
|
+
else if (body.isBlockStatement()) {
|
|
2650
|
+
body.traverse({
|
|
2651
|
+
Function(inner) { inner.skip(); },
|
|
2652
|
+
ReturnStatement(ret) {
|
|
2653
|
+
const arg = ret.get('argument');
|
|
2654
|
+
if (arg.node && arg.isFunction()) cleanups.push(arg);
|
|
2655
|
+
},
|
|
2656
|
+
});
|
|
2657
|
+
}
|
|
2658
|
+
if (cleanups.length === 0) return;
|
|
2659
|
+
const kept = new Map();
|
|
2660
|
+
for (const cleanup of cleanups) {
|
|
2661
|
+
cleanup.traverse({
|
|
2662
|
+
'MemberExpression|OptionalMemberExpression|CallExpression'(path) {
|
|
2663
|
+
const read = reads(path);
|
|
2664
|
+
if (read === null) return;
|
|
2665
|
+
let entry = kept.get(read.key);
|
|
2666
|
+
if (entry === undefined) {
|
|
2667
|
+
entry = { id: callback.scope.generateUidIdentifier(read.name), value: t.cloneNode(path.node, true) };
|
|
2668
|
+
kept.set(read.key, entry);
|
|
2669
|
+
}
|
|
2670
|
+
path.replaceWith(t.identifier(entry.id.name));
|
|
2671
|
+
},
|
|
2672
|
+
});
|
|
2673
|
+
}
|
|
2674
|
+
if (kept.size === 0) return;
|
|
2675
|
+
// The reads the run makes itself, which it follows already.
|
|
2676
|
+
const inRun = new Set();
|
|
2677
|
+
if (tracked && body.isBlockStatement()) {
|
|
2678
|
+
body.traverse({
|
|
2679
|
+
Function(inner) { inner.skip(); },
|
|
2680
|
+
'MemberExpression|OptionalMemberExpression|CallExpression'(path) {
|
|
2681
|
+
const read = reads(path);
|
|
2682
|
+
if (read !== null) inRun.add(read.key);
|
|
2683
|
+
},
|
|
2684
|
+
});
|
|
2685
|
+
}
|
|
2686
|
+
const declarators = [...kept].map(([key, { id, value }]) => t.variableDeclarator(id, tracked && !inRun.has(key)
|
|
2687
|
+
? t.callExpression(helper(state, '_$untrack'), [t.arrowFunctionExpression([], value)])
|
|
2688
|
+
: value));
|
|
2689
|
+
const declaration = t.variableDeclaration('const', declarators);
|
|
2690
|
+
if (body.isBlockStatement()) body.unshiftContainer('body', declaration);
|
|
2691
|
+
else body.replaceWith(t.blockStatement([declaration, t.returnStatement(body.node)]));
|
|
2692
|
+
}
|
|
2693
|
+
|
|
2694
|
+
// A useEffect cleanup the component made once, outside the effect, and the
|
|
2695
|
+
// effect returns (`const stop = () => leave(roomId); useEffect(() => {
|
|
2696
|
+
// join(roomId); return stop; })`), still reads the values of when it runs.
|
|
2697
|
+
// Reported at build time in development (ERR_CLEANUP_READS_LIVE) when it
|
|
2698
|
+
// reads a prop or calls a state accessor that the run reads too, and the
|
|
2699
|
+
// effect can run again (no `[]` dependency array). Reads inside functions
|
|
2700
|
+
// written in either are not counted.
|
|
2701
|
+
|
|
2702
|
+
function importedWhatName(fnPath, callee) {
|
|
2703
|
+
if (!t.isIdentifier(callee)) return null;
|
|
2704
|
+
const binding = fnPath.scope.getBinding(callee.name);
|
|
2705
|
+
if (!binding || binding.kind !== 'module' || !t.isImportSpecifier(binding.path.node)) return null;
|
|
2706
|
+
const imported = binding.path.node.imported;
|
|
2707
|
+
const name = t.isIdentifier(imported) ? imported.name : imported.value;
|
|
2708
|
+
return importedFrom(binding, t.isImportSpecifier, name) ? name : null;
|
|
2709
|
+
}
|
|
2710
|
+
|
|
2711
|
+
// Every name `read` gives for a node of `node`, outside a function written in it.
|
|
2712
|
+
function readsIn(node, read) {
|
|
2713
|
+
const found = new Set();
|
|
2714
|
+
const visit = (n) => {
|
|
2715
|
+
if (!n || typeof n !== 'object') return;
|
|
2716
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
2717
|
+
if (typeof n.type !== 'string' || t.isFunction(n)) return;
|
|
2718
|
+
const name = read(n);
|
|
2719
|
+
if (name !== null) found.add(name);
|
|
2720
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
2721
|
+
};
|
|
2722
|
+
visit(node);
|
|
2723
|
+
return found;
|
|
2724
|
+
}
|
|
2725
|
+
|
|
2726
|
+
export function warnLiveCleanup(fnPath, state) {
|
|
2727
|
+
if (process.env.NODE_ENV === 'production' || state.ssr || state.frameworkFile || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
2728
|
+
if (!t.isBlockStatement(fnPath.node.body)) return;
|
|
2729
|
+
const props = propReader(fnPath);
|
|
2730
|
+
const names = stateAccessors(fnPath);
|
|
2731
|
+
if (props === null && names.size === 0) return;
|
|
2732
|
+
const read = (n) => (props !== null ? props(n) : null)
|
|
2733
|
+
?? (names.size !== 0 && t.isCallExpression(n) && n.arguments.length === 0 && t.isIdentifier(n.callee) && names.has(n.callee.name) ? `${n.callee.name}()` : null);
|
|
2734
|
+
for (const stmt of fnPath.node.body.body) {
|
|
2735
|
+
const call = t.isExpressionStatement(stmt) ? stmt.expression : null;
|
|
2736
|
+
if (!t.isCallExpression(call) || importedWhatName(fnPath, call.callee) !== 'useEffect') continue;
|
|
2737
|
+
const [callback, deps] = call.arguments;
|
|
2738
|
+
if (!t.isFunction(callback) || (t.isArrayExpression(deps) && deps.elements.length === 0)) continue;
|
|
2739
|
+
const returned = t.isBlockStatement(callback.body)
|
|
2740
|
+
? callback.body.body.filter((s) => t.isReturnStatement(s) && t.isIdentifier(s.argument)).map((s) => s.argument)
|
|
2741
|
+
: t.isIdentifier(callback.body) ? [callback.body] : [];
|
|
2742
|
+
const inRun = readsIn(callback.body, read);
|
|
2743
|
+
for (const ref of returned) {
|
|
2744
|
+
const cleanup = componentFunction(fnPath, ref.name);
|
|
2745
|
+
const name = cleanup === null ? undefined : [...readsIn(cleanup.body, read)].find((n) => inRun.has(n));
|
|
2746
|
+
if (name === undefined) continue;
|
|
2747
|
+
const hook = 'useEffect';
|
|
2748
|
+
recordBuildDiagnostic(state, 'ERR_CLEANUP_READS_LIVE', { name, component: componentName(fnPath), hook }, ref);
|
|
2749
|
+
const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
|
|
2750
|
+
const at = `${fileName}${ref.loc ? `:${ref.loc.start.line}:${ref.loc.start.column + 1}` : ''}`;
|
|
2751
|
+
if (warnedReadOnce.has(`${at}::cleanup`)) break;
|
|
2752
|
+
warnedReadOnce.add(`${at}::cleanup`);
|
|
2753
|
+
console.warn(
|
|
2754
|
+
`[what-compiler] ERR_CLEANUP_READS_LIVE: the ${hook} cleanup in <${componentName(fnPath)}> at ${at}, \`${ref.name}\`, reads \`${name}\`, which its run reads too. ` +
|
|
2755
|
+
`\`${ref.name}\` is made once, when the component runs, so when \`${name}\` changes and the effect runs again, it reads the new value, where React's cleanup sees the value of the render that made it. ` +
|
|
2756
|
+
`Fix: write the cleanup in the effect and return it there (\`return () => …\`): the compiler keeps the values a cleanup written there reads as its run saw them. Run what_fix({ error: 'ERR_CLEANUP_READS_LIVE' }) for the worked example.`
|
|
2757
|
+
);
|
|
2758
|
+
break;
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
}
|
|
2762
|
+
|
|
2763
|
+
// The function the component's body declares under `name`
|
|
2764
|
+
// (`function stop() { … }`, `const stop = () => …`), else null.
|
|
2765
|
+
function componentFunction(fnPath, name) {
|
|
2766
|
+
const binding = fnPath.scope.getBinding(name);
|
|
2767
|
+
if (!binding || binding.scope !== fnPath.scope || binding.constantViolations.length > 0) return null;
|
|
2768
|
+
if (t.isFunctionDeclaration(binding.path.node)) return binding.path.node;
|
|
2769
|
+
const init = t.isVariableDeclarator(binding.path.node) ? binding.path.node.init : null;
|
|
2770
|
+
return t.isFunction(init) ? init : null;
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
function warnStateOnce(fnPath, state, node, read, why, fix) {
|
|
2774
|
+
const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
|
|
2775
|
+
const at = `${fileName}${node.loc ? `:${node.loc.start.line}:${node.loc.start.column + 1}` : ''}`;
|
|
2776
|
+
recordBuildDiagnostic(state, 'ERR_STATE_READ_ONCE', { name: read, component: componentName(fnPath), reason: why }, node);
|
|
2777
|
+
if (warnedReadOnce.has(`${at}::${read}`)) return;
|
|
2778
|
+
warnedReadOnce.add(`${at}::${read}`);
|
|
2779
|
+
console.warn(
|
|
2780
|
+
`[what-compiler] ERR_STATE_READ_ONCE: \`${read}\`, state of <${componentName(fnPath)}> at ${at}, is read once, when the component runs, ` +
|
|
2781
|
+
`because ${why}; the component runs once, so it does not follow the state as a React render would. ` +
|
|
2782
|
+
`Fix: ${fix}. Run what_fix({ error: 'ERR_STATE_READ_ONCE' }) for the worked example.`
|
|
2783
|
+
);
|
|
2784
|
+
}
|
|
2785
|
+
|
|
2786
|
+
// --- A JSX helper handed props ---
|
|
2787
|
+
// `function Helper({ value }) { return mk({ value }); }`: the component
|
|
2788
|
+
// renders what `mk` makes of the object it hands it. A component runs once,
|
|
2789
|
+
// so the object held the values its props had then, and `mk`'s JSX kept the
|
|
2790
|
+
// first `value`, wherever `mk` is declared. So a property of an object
|
|
2791
|
+
// literal handed to the call a component returns, whose value reads a prop
|
|
2792
|
+
// or calls one of the component's state accessors outside a function and
|
|
2793
|
+
// outside JSX, is a getter, and the object is marked as compiled JSX marks
|
|
2794
|
+
// props (`_$marked({ get value() { return props.value; } })`): `mk`'s JSX
|
|
2795
|
+
// reads it where it shows it, as a live prop, and updates there, in place.
|
|
2796
|
+
// The callee is one that can render JSX: a function the module imports from
|
|
2797
|
+
// outside What (its own module may render JSX; nothing here can tell), a
|
|
2798
|
+
// member of an object imported so, a function of the module that renders
|
|
2799
|
+
// JSX, or a method that renders JSX of an object literal the module or the
|
|
2800
|
+
// component declares (`const ui = { row({ value }) { return <i>{value}</i>; } }`,
|
|
2801
|
+
// `ui.row({ value })`). A global (`fetch`, `JSON.stringify`), any other
|
|
2802
|
+
// method call, What's own API and a function of the module that renders no
|
|
2803
|
+
// JSX are called as written, and so is every call in the body (`fetch(url, {
|
|
2804
|
+
// body })` runs once, with the values of then, as the component does). What
|
|
2805
|
+
// the callee sees differs from a plain literal in one way: writing a property
|
|
2806
|
+
// that is a getter throws, as writing a prop does.
|
|
2807
|
+
// The props handed on in such a literal (`mk({ ...props })`, a rest element
|
|
2808
|
+
// of them, `mk({ ...rest, extra })`) are merged with their getters kept
|
|
2809
|
+
// (render.js _$merge), as a component's spread props are, where an object
|
|
2810
|
+
// spread would copy the values of then.
|
|
2811
|
+
// A prop handed another way (`mk(value)`, `mk([value])`) is read once,
|
|
2812
|
+
// reported in development as ERR_PROP_READ_ONCE (warnDelegatedRender).
|
|
2813
|
+
|
|
2814
|
+
// The calls the component returns (`return mk(…)`, `() => mk(…)`).
|
|
2815
|
+
function returnedCalls(fnPath) {
|
|
2816
|
+
const body = fnPath.node.body;
|
|
2817
|
+
return (t.isBlockStatement(body) ? returnedValues(body) : [body]).map(unwrapExpr).filter((expr) => t.isCallExpression(expr));
|
|
2818
|
+
}
|
|
2819
|
+
|
|
2820
|
+
// Whether the call's callee may render JSX: see above.
|
|
2821
|
+
function callsHelper(fnPath, call) {
|
|
2822
|
+
const callee = call.callee;
|
|
2823
|
+
const imported = (binding, isSpecifier) => binding?.kind === 'module' && isSpecifier(binding.path.node)
|
|
2824
|
+
&& t.isImportDeclaration(binding.path.parent) && !isWhatModuleSource(binding.path.parent.source.value);
|
|
2825
|
+
if (t.isMemberExpression(callee) && !callee.computed && t.isIdentifier(callee.object) && t.isIdentifier(callee.property)) {
|
|
2826
|
+
const binding = fnPath.scope.getBinding(callee.object.name);
|
|
2827
|
+
return importedObject(binding) || rendersMethod(binding, callee.property.name);
|
|
2828
|
+
}
|
|
2829
|
+
if (!t.isIdentifier(callee)) return false;
|
|
2830
|
+
const binding = fnPath.scope.getBinding(callee.name);
|
|
2831
|
+
if (!binding) return false;
|
|
2832
|
+
if (binding.kind === 'module' && !t.isFunctionDeclaration(binding.path.node) && !t.isVariableDeclarator(binding.path.node)) {
|
|
2833
|
+
return imported(binding, (n) => t.isImportSpecifier(n) || t.isImportDefaultSpecifier(n));
|
|
2834
|
+
}
|
|
2835
|
+
const fn = t.isVariableDeclarator(binding.path.node) ? binding.path.node.init : binding.path.node;
|
|
2836
|
+
return t.isFunction(fn) && binding.constantViolations.length === 0 && containsJsx(fn);
|
|
2837
|
+
}
|
|
2838
|
+
|
|
2839
|
+
// Whether the object literal a `const` holds (`const ui = { row(…) { … } }`),
|
|
2840
|
+
// written through nowhere (`ui.row = …`), has as its `name` a function that
|
|
2841
|
+
// renders JSX.
|
|
2842
|
+
function rendersMethod(binding, name) {
|
|
2843
|
+
if (!binding || binding.kind !== 'const' || !binding.path.isVariableDeclarator() || !t.isObjectExpression(binding.path.node.init)) return false;
|
|
2844
|
+
if (binding.referencePaths.some((ref) => ref.parentPath.isMemberExpression() && ref.key === 'object' && !notWritten(ref.parentPath))) return false;
|
|
2845
|
+
let fn = null;
|
|
2846
|
+
for (const p of binding.path.node.init.properties) {
|
|
2847
|
+
if (t.isSpreadElement(p)) fn = null;
|
|
2848
|
+
else if (propertyName(p.key, p.computed) === name) fn = t.isObjectMethod(p, { kind: 'method' }) ? p : t.isObjectProperty(p) && t.isFunction(p.value) ? p.value : null;
|
|
2849
|
+
}
|
|
2850
|
+
return fn !== null && containsJsx(fn);
|
|
2851
|
+
}
|
|
2852
|
+
|
|
2853
|
+
// Whether `node` reads a live value outside the functions and the JSX written
|
|
2854
|
+
// in it: JSX follows what it reads itself, and a getter would build it again
|
|
2855
|
+
// at each read.
|
|
2856
|
+
function readsLiveValue(node, live) {
|
|
2857
|
+
let found = false;
|
|
2858
|
+
const visit = (n) => {
|
|
2859
|
+
if (found || !n || typeof n !== 'object') return;
|
|
2860
|
+
if (Array.isArray(n)) { n.forEach(visit); return; }
|
|
2861
|
+
if (typeof n.type !== 'string' || t.isFunction(n) || t.isJSXElement(n) || t.isJSXFragment(n)) return;
|
|
2862
|
+
if (live(n)) { found = true; return; }
|
|
2863
|
+
for (const key of t.VISITOR_KEYS[n.type] || []) visit(n[key]);
|
|
2864
|
+
};
|
|
2865
|
+
visit(node);
|
|
2866
|
+
return found;
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
/** Hand the JSX helper the component `fnPath` returns the live props of an object literal as getters (see above). */
|
|
2870
|
+
export function liveHelperArgs(fnPath, state) {
|
|
2871
|
+
if (state.ssr || state.frameworkFile || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
2872
|
+
const live = liveReader(fnPath);
|
|
2873
|
+
for (const call of returnedCalls(fnPath)) {
|
|
2874
|
+
if (!callsHelper(fnPath, call)) continue;
|
|
2875
|
+
call.arguments = call.arguments.map((arg) => {
|
|
2876
|
+
if (!t.isObjectExpression(arg)) return arg;
|
|
2877
|
+
let getters = false;
|
|
2878
|
+
arg.properties = arg.properties.map((p) => {
|
|
2879
|
+
// `__proto__: x` sets the prototype; a getter of that name would not.
|
|
2880
|
+
const key = t.isObjectProperty(p) ? propertyName(p.key, p.computed) : null;
|
|
2881
|
+
if (key === null || (key === '__proto__' && !p.computed) || !readsLiveValue(p.value, live)) return p;
|
|
2882
|
+
getters = true;
|
|
2883
|
+
return t.objectMethod('get', p.key, [], t.blockStatement([t.returnStatement(p.value)]), p.computed);
|
|
2884
|
+
});
|
|
2885
|
+
if (!arg.properties.some((p) => t.isSpreadElement(p) && isPropsObject(fnPath, p.argument))) return getters ? t.callExpression(helper(state, '_$marked'), [arg]) : arg;
|
|
2886
|
+
// The sources in order: each spread's, and the literal's own properties
|
|
2887
|
+
// between them, marked when they hold a getter.
|
|
2888
|
+
const parts = [];
|
|
2889
|
+
const own = new Set();
|
|
2890
|
+
for (const p of arg.properties) {
|
|
2891
|
+
const last = parts[parts.length - 1];
|
|
2892
|
+
if (t.isSpreadElement(p)) parts.push(p.argument);
|
|
2893
|
+
else if (own.has(last)) last.properties.push(p);
|
|
2894
|
+
else {
|
|
2895
|
+
const literal = t.objectExpression([p]);
|
|
2896
|
+
own.add(literal);
|
|
2897
|
+
parts.push(literal);
|
|
2898
|
+
}
|
|
2899
|
+
}
|
|
2900
|
+
return t.callExpression(helper(state, '_$merge'), parts.map((part) => (own.has(part) && part.properties.some((p) => t.isObjectMethod(p, { kind: 'get' }))
|
|
2901
|
+
? t.callExpression(helper(state, '_$marked'), [part]) : part)));
|
|
2902
|
+
});
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
|
|
2906
|
+
// Whether `node`, spread into an object, is the component's props: the props
|
|
2907
|
+
// parameter, or a rest element of them (in the parameter list, or one the
|
|
2908
|
+
// body destructures from them, before or after deferPlacedProps names it).
|
|
2909
|
+
function isPropsObject(fnPath, node) {
|
|
2910
|
+
if (!t.isIdentifier(node)) return false;
|
|
2911
|
+
const binding = fnPath.scope.getBinding(node.name);
|
|
2912
|
+
if (!binding || binding.scope !== fnPath.scope || binding.constantViolations.length > 0) return false;
|
|
2913
|
+
const param = fnPath.node.params[0];
|
|
2914
|
+
const restOf = (pattern) => t.isObjectPattern(pattern) && pattern.properties.some((p) => t.isRestElement(p) && t.isIdentifier(p.argument, { name: node.name }));
|
|
2915
|
+
if (binding.kind === 'param') return t.isIdentifier(param, { name: node.name }) || restOf(param);
|
|
2916
|
+
if (!binding.path.isVariableDeclarator()) return false;
|
|
2917
|
+
if (binding.path.node._whatPropsRest === true) return true;
|
|
2918
|
+
const { id, init } = binding.path.node;
|
|
2919
|
+
return restOf(id) && t.isIdentifier(init) && isPropsObject(fnPath, init);
|
|
2920
|
+
}
|
|
2921
|
+
|
|
2922
|
+
// Whether the component returns a call of a JSX helper that it hands, in an
|
|
2923
|
+
// object literal, a prop or its state, or its props: it renders as a
|
|
2924
|
+
// component does.
|
|
2925
|
+
function handsHelperProps(fnPath, state) {
|
|
2926
|
+
if (state.ssr || !namedAsComponent(fnPath)) return false;
|
|
2927
|
+
const read = propReader(fnPath);
|
|
2928
|
+
const accessors = stateAccessors(fnPath);
|
|
2929
|
+
const live = (n) => (read !== null && read(n) !== null)
|
|
2930
|
+
|| (t.isCallExpression(n) && n.arguments.length === 0 && t.isIdentifier(n.callee) && accessors.has(n.callee.name));
|
|
2931
|
+
return returnedCalls(fnPath).some((call) => callsHelper(fnPath, call) && call.arguments.some((arg) => t.isObjectExpression(arg)
|
|
2932
|
+
&& arg.properties.some((p) => (t.isObjectProperty(p) && propertyName(p.key, p.computed) !== null && readsLiveValue(p.value, live))
|
|
2933
|
+
|| (t.isSpreadElement(p) && isPropsObject(fnPath, p.argument)))));
|
|
2934
|
+
}
|
|
2935
|
+
|
|
2936
|
+
// A prop a component hands the JSX helper it returns other than as a
|
|
2937
|
+
// property of an object literal or the props spread into one (`mk(value)`,
|
|
2938
|
+
// `mk([value])`, `mk({ ...props.style })`) is read once, when the component
|
|
2939
|
+
// runs, wherever the helper is declared: what the helper made of it stays.
|
|
2940
|
+
function warnDelegatedRender(fnPath, state) {
|
|
2941
|
+
if (process.env.NODE_ENV === 'production' || state.ssr || state.frameworkFile || !namedAsComponent(fnPath) || !isComponentFunction(fnPath) || isRowFunction(fnPath, state)) return;
|
|
2942
|
+
const read = propReader(fnPath);
|
|
2943
|
+
if (read === null) return;
|
|
2944
|
+
for (const call of returnedCalls(fnPath)) {
|
|
2945
|
+
if (!callsHelper(fnPath, call)) continue;
|
|
2946
|
+
/** @type {string | null} */
|
|
2947
|
+
let name = null;
|
|
2948
|
+
for (const arg of call.arguments) {
|
|
2949
|
+
if (name !== null) break;
|
|
2950
|
+
if (!t.isObjectExpression(arg)) { name = propReadIn(arg, read); continue; }
|
|
2951
|
+
for (const p of arg.properties) {
|
|
2952
|
+
if (name !== null) break;
|
|
2953
|
+
if (t.isSpreadElement(p)) name = isPropsObject(fnPath, p.argument) ? null : propReadIn(p.argument, read);
|
|
2954
|
+
else if (t.isObjectProperty(p) && propertyName(p.key, p.computed) === null) name = propReadIn(p, read);
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
if (name === null) continue;
|
|
2958
|
+
const callee = t.isIdentifier(call.callee) ? call.callee.name : `${call.callee.object.name}.${call.callee.property.name}`;
|
|
2959
|
+
const key = name.replace(/^props\./, '');
|
|
2960
|
+
warnReadOnce(fnPath, state, call, name, `it is handed to \`${callee}()\` as a value, so what \`${callee}()\` makes of it is made from the value it had when the component ran`,
|
|
2961
|
+
`hand it in an object literal (\`${callee}({ ${key === name ? key : `${key}: ${name}`} })\`), whose props the compiler keeps live, or hand the props on (\`${callee}(props)\`)`);
|
|
2962
|
+
return;
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2965
|
+
|
|
2966
|
+
function collectNames(pattern, out = new Set()) {
|
|
2967
|
+
if (t.isIdentifier(pattern)) out.add(pattern.name);
|
|
2968
|
+
else if (t.isAssignmentPattern(pattern)) collectNames(pattern.left, out);
|
|
2969
|
+
else if (t.isRestElement(pattern)) collectNames(pattern.argument, out);
|
|
2970
|
+
else if (t.isObjectPattern(pattern)) for (const p of pattern.properties) collectNames(t.isRestElement(p) ? p : p.value, out);
|
|
2971
|
+
else if (t.isArrayPattern(pattern)) for (const e of pattern.elements) if (e) collectNames(e, out);
|
|
2972
|
+
return out;
|
|
2973
|
+
}
|
|
2974
|
+
|
|
2975
|
+
function warnReadOnce(fnPath, state, node, name, why, fix) {
|
|
2976
|
+
if (process.env.NODE_ENV === 'production' || state.ssr || !isComponentFunction(fnPath)) return;
|
|
2977
|
+
const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
|
|
2978
|
+
const loc = node.loc ? `:${node.loc.start.line}:${node.loc.start.column + 1}` : '';
|
|
2979
|
+
const at = `${fileName}${loc}`;
|
|
2980
|
+
recordBuildDiagnostic(state, 'ERR_PROP_READ_ONCE', { name, component: componentName(fnPath), reason: why }, node);
|
|
2981
|
+
if (warnedReadOnce.has(`${at}::${name}`)) return;
|
|
2982
|
+
warnedReadOnce.add(`${at}::${name}`);
|
|
2983
|
+
console.warn(
|
|
2984
|
+
`[what-compiler] ERR_PROP_READ_ONCE: \`${name}\`, ${name.startsWith('props.') ? 'read from' : 'destructured from'} the props of <${componentName(fnPath)}> at ${at}, ` +
|
|
2985
|
+
`is read once, when the component runs, because ${why}: it keeps that value when the parent's state changes. ` +
|
|
2986
|
+
`Fix: ${fix}. Run what_fix({ error: 'ERR_PROP_READ_ONCE' }) for the worked example.`
|
|
2987
|
+
);
|
|
2988
|
+
}
|
|
2989
|
+
|
|
2990
|
+
// A development DOM build also hands what it warns about to the page
|
|
2991
|
+
// (dom.js finishDomProgram emits `_$buildDiagnostics([...])`), with the
|
|
2992
|
+
// location in the project's terms ("src/App.jsx:12:5", the source as
|
|
2993
|
+
// written), on every compile of the module: the console warning above is
|
|
2994
|
+
// printed once per process.
|
|
2995
|
+
function recordBuildDiagnostic(state, code, data, node) {
|
|
2996
|
+
const record = diagnosticOf(state, code, data, node);
|
|
2997
|
+
if (record !== null) (state._buildDiagnostics ??= []).push(record);
|
|
2998
|
+
}
|
|
2999
|
+
|
|
3000
|
+
// What a development DOM build hands the page for `code` at `node`, or null
|
|
3001
|
+
// when it hands nothing (no devMetadata, a production build, no location).
|
|
3002
|
+
function diagnosticOf(state, code, data, node) {
|
|
3003
|
+
if (state.opts?.devMetadata !== true || state.opts?.production === true || state.ssr || !node.loc) return null;
|
|
3004
|
+
const file = String(state.file?.opts?.filename || '').replace(/\\/g, '/').replace(/[?#].*$/, '');
|
|
3005
|
+
const root = String(state.opts?.projectRoot || state.file?.opts?.cwd || '').replace(/\\/g, '/').replace(/\/+$/, '');
|
|
3006
|
+
const path = root && file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file;
|
|
3007
|
+
const start = node.loc.start;
|
|
3008
|
+
const at = typeof state.opts?.sourceLoc === 'function' ? state.opts.sourceLoc(start.line, start.column) ?? start : start;
|
|
3009
|
+
return { code, data, loc: `${path}:${at.line}:${at.column + 1}` };
|
|
3010
|
+
}
|
|
3011
|
+
|
|
3012
|
+
/** A diagnostic record (diagnosticOf) as an object literal: `{ code, data, loc }`. */
|
|
3013
|
+
export function diagnosticRecord({ code, data, loc }) {
|
|
3014
|
+
return t.objectExpression([
|
|
3015
|
+
t.objectProperty(t.identifier('code'), t.stringLiteral(code)),
|
|
3016
|
+
t.objectProperty(t.identifier('data'), t.objectExpression(Object.entries(data).map(([k, v]) => t.objectProperty(t.identifier(k), t.stringLiteral(String(v)))))),
|
|
3017
|
+
t.objectProperty(t.identifier('loc'), t.stringLiteral(loc)),
|
|
3018
|
+
]);
|
|
3019
|
+
}
|
|
3020
|
+
|
|
3021
|
+
// A function named as a component is (`function Card`, `const Card = …`).
|
|
3022
|
+
function isComponentFunction(fnPath) {
|
|
3023
|
+
return /^[A-Z]/.test(componentName(fnPath));
|
|
3024
|
+
}
|
|
3025
|
+
|
|
3026
|
+
function componentName(fnPath) {
|
|
3027
|
+
if (fnPath.node.id) return fnPath.node.id.name;
|
|
3028
|
+
let at = fnPath.parentPath;
|
|
3029
|
+
// `const Card = memo((props) => …)`, `forwardRef(...)`.
|
|
3030
|
+
while (at && at.isCallExpression()) at = at.parentPath;
|
|
3031
|
+
return at && at.isVariableDeclarator() && t.isIdentifier(at.node.id) ? at.node.id.name : 'anonymous';
|
|
3032
|
+
}
|
|
3033
|
+
|
|
3034
|
+
// A destructured prop that can be read where it is used: a static key bound
|
|
3035
|
+
// to a name that is never reassigned, with no default or a plain literal one.
|
|
3036
|
+
function readProp(fnPath, prop, scope) {
|
|
3037
|
+
const key = propertyName(prop.key, prop.computed);
|
|
3038
|
+
if (key === null) return null;
|
|
3039
|
+
let local = prop.value;
|
|
3040
|
+
let fallback = null;
|
|
3041
|
+
let hoist = false;
|
|
3042
|
+
if (t.isAssignmentPattern(local)) {
|
|
3043
|
+
fallback = local.right;
|
|
3044
|
+
local = local.left;
|
|
3045
|
+
// Evaluated where each read stands now, so only a value that is the
|
|
3046
|
+
// same wherever and however often it is evaluated: a plain literal, or
|
|
3047
|
+
// one that reads nothing of the component and calls nothing
|
|
3048
|
+
// (`items = []`, `onChange = () => {}`, `size = SIZES.md`), made once
|
|
3049
|
+
// when the component runs and kept (readAtUse).
|
|
3050
|
+
if (!isPlainLiteral(fallback, fnPath.scope)) {
|
|
3051
|
+
if (!isClosedValue(fallback, fnPath)) return null;
|
|
3052
|
+
hoist = true;
|
|
3053
|
+
}
|
|
3054
|
+
}
|
|
3055
|
+
if (!t.isIdentifier(local)) return null;
|
|
3056
|
+
const binding = scope.getBinding(local.name);
|
|
3057
|
+
if (!binding || binding.constantViolations.length > 0) return null;
|
|
3058
|
+
return { key, binding, fallback, hoist };
|
|
3059
|
+
}
|
|
3060
|
+
|
|
3061
|
+
// A value that evaluated once when the component starts is the value its
|
|
3062
|
+
// default would have been: literals, arrays and objects of them, functions
|
|
3063
|
+
// (evaluated when called), and names and member reads from outside the
|
|
3064
|
+
// component. No call, no `new`, no `this`.
|
|
3065
|
+
function isClosedValue(node, fnPath) {
|
|
3066
|
+
switch (node.type) {
|
|
3067
|
+
case 'StringLiteral': case 'NumericLiteral': case 'BooleanLiteral': case 'NullLiteral': case 'BigIntLiteral':
|
|
3068
|
+
case 'ArrowFunctionExpression': case 'FunctionExpression':
|
|
3069
|
+
return true;
|
|
3070
|
+
case 'TemplateLiteral':
|
|
3071
|
+
return node.expressions.every((e) => isClosedValue(e, fnPath));
|
|
3072
|
+
case 'ArrayExpression':
|
|
3073
|
+
return node.elements.every((e) => e === null || isClosedValue(t.isSpreadElement(e) ? e.argument : e, fnPath));
|
|
3074
|
+
case 'ObjectExpression':
|
|
3075
|
+
return node.properties.every((p) => (t.isObjectMethod(p) ? !p.computed
|
|
3076
|
+
: t.isSpreadElement(p) ? isClosedValue(p.argument, fnPath)
|
|
3077
|
+
: (!p.computed || isClosedValue(p.key, fnPath)) && isClosedValue(p.value, fnPath)));
|
|
3078
|
+
case 'Identifier': {
|
|
3079
|
+
const binding = fnPath.scope.getBinding(node.name);
|
|
3080
|
+
return !binding || !(binding.path === fnPath || binding.path.isDescendant(fnPath));
|
|
3081
|
+
}
|
|
3082
|
+
case 'MemberExpression':
|
|
3083
|
+
return isClosedValue(node.object, fnPath) && (!node.computed || isClosedValue(node.property, fnPath));
|
|
3084
|
+
case 'UnaryExpression':
|
|
3085
|
+
return node.operator !== 'delete' && isClosedValue(node.argument, fnPath);
|
|
3086
|
+
case 'BinaryExpression': case 'LogicalExpression':
|
|
3087
|
+
return isClosedValue(node.left, fnPath) && isClosedValue(node.right, fnPath);
|
|
3088
|
+
case 'ConditionalExpression':
|
|
3089
|
+
return isClosedValue(node.test, fnPath) && isClosedValue(node.consequent, fnPath) && isClosedValue(node.alternate, fnPath);
|
|
3090
|
+
default:
|
|
3091
|
+
return false;
|
|
3092
|
+
}
|
|
3093
|
+
}
|
|
3094
|
+
|
|
3095
|
+
// The names of a nested pattern of prop `prop` (`style: { color, size = 1 }`,
|
|
3096
|
+
// `style: { color } = {}`, nested further), each as a live read of its path
|
|
3097
|
+
// (`{ key, path, optional, binding, fallback }`), or null when one cannot be:
|
|
3098
|
+
// a computed key, a rest element, a default that is not a plain literal (an
|
|
3099
|
+
// empty object for the pattern itself, read as `props.style?.color`), a name
|
|
3100
|
+
// that is reassigned.
|
|
3101
|
+
function nestedProps(fnPath, prop, scope) {
|
|
3102
|
+
const key = propertyName(prop.key, prop.computed);
|
|
3103
|
+
if (key === null) return null;
|
|
3104
|
+
const out = [];
|
|
3105
|
+
const visit = (value, path, optional) => {
|
|
3106
|
+
if (t.isAssignmentPattern(value) && t.isObjectPattern(value.left)) {
|
|
3107
|
+
if (!t.isObjectExpression(value.right) || value.right.properties.length > 0) return false;
|
|
3108
|
+
return visit(value.left, path, true);
|
|
3109
|
+
}
|
|
3110
|
+
if (!t.isObjectPattern(value) || value.properties.length === 0) return false;
|
|
3111
|
+
for (const inner of value.properties) {
|
|
3112
|
+
if (!t.isObjectProperty(inner)) return false;
|
|
3113
|
+
const name = propertyName(inner.key, inner.computed);
|
|
3114
|
+
if (name === null) return false;
|
|
3115
|
+
const at = [...path, { name, optional }];
|
|
3116
|
+
if (t.isObjectPattern(inner.value) || (t.isAssignmentPattern(inner.value) && t.isObjectPattern(inner.value.left))) {
|
|
3117
|
+
if (!visit(inner.value, at, false)) return false;
|
|
3118
|
+
continue;
|
|
3119
|
+
}
|
|
3120
|
+
const entry = readProp(fnPath, { ...inner, key: t.identifier('x'), computed: false }, scope);
|
|
3121
|
+
if (entry === null) return false;
|
|
3122
|
+
out.push({ key, path: at, binding: entry.binding, fallback: entry.fallback });
|
|
3123
|
+
}
|
|
3124
|
+
return true;
|
|
3125
|
+
};
|
|
3126
|
+
return visit(prop.value, [], false) ? out : null;
|
|
3127
|
+
}
|
|
3128
|
+
|
|
3129
|
+
function propertyName(key, computed) {
|
|
3130
|
+
if (t.isIdentifier(key) && !computed) return key.name;
|
|
3131
|
+
if (t.isStringLiteral(key)) return key.value;
|
|
3132
|
+
return t.isNumericLiteral(key) ? String(key.value) : null;
|
|
3133
|
+
}
|
|
3134
|
+
|
|
3135
|
+
function isPlainLiteral(node, scope) {
|
|
3136
|
+
if (t.isNullLiteral(node) || t.isBooleanLiteral(node) || t.isNumericLiteral(node) || t.isStringLiteral(node) || t.isBigIntLiteral(node)) return true;
|
|
3137
|
+
if (t.isTemplateLiteral(node)) return node.expressions.length === 0;
|
|
3138
|
+
if (t.isIdentifier(node, { name: 'undefined' })) return !scope.hasBinding('undefined');
|
|
3139
|
+
return t.isUnaryExpression(node, { operator: 'void' }) && t.isNumericLiteral(node.argument);
|
|
3140
|
+
}
|
|
3141
|
+
|
|
3142
|
+
// Whether the value at `path` is rendered where it stands: a child of an
|
|
3143
|
+
// element, a fragment or a component, a prop handed on to a component
|
|
3144
|
+
// (isSlotAttribute), what the component returns, or a branch of a
|
|
3145
|
+
// conditional, a logical expression or an array that is one of those. A
|
|
3146
|
+
// function written in such a place is a reactive child, so what it returns
|
|
3147
|
+
// is placed too. The child of <For> is its row function, not content.
|
|
3148
|
+
function placesValue(path, fnPath, state, fnValue = false) {
|
|
3149
|
+
let child = path;
|
|
3150
|
+
let parent = path.parentPath;
|
|
3151
|
+
while ((parent.isConditionalExpression() && child.key !== 'test')
|
|
3152
|
+
|| (parent.isLogicalExpression() && child.key === 'right')
|
|
3153
|
+
|| parent.isArrayExpression()
|
|
3154
|
+
|| parent.isTSAsExpression() || parent.isTSSatisfiesExpression() || parent.isTSNonNullExpression()) {
|
|
3155
|
+
child = parent;
|
|
3156
|
+
parent = parent.parentPath;
|
|
3157
|
+
}
|
|
3158
|
+
if (parent.isJSXExpressionContainer()) {
|
|
3159
|
+
const owner = parent.parentPath;
|
|
3160
|
+
// A function handed to a component in a prop is a callback it calls
|
|
3161
|
+
// (`read={() => props.project}`), not JSX it places: what the callback
|
|
3162
|
+
// returns is the value, read where it is called.
|
|
3163
|
+
if (owner.isJSXAttribute()) return !(fnValue && isSlotAttribute(owner.parentPath.parent, owner.node, state)) && placingAttribute(owner.parentPath.parent, owner.node, state);
|
|
3164
|
+
if (parent.listKey !== 'children') return false;
|
|
3165
|
+
return owner.isJSXFragment() || !isLoweredTag(owner.node, 'For', state);
|
|
3166
|
+
}
|
|
3167
|
+
/** @type {any} */
|
|
3168
|
+
let fn = null;
|
|
3169
|
+
if (parent.isReturnStatement()) fn = parent.getFunctionParent();
|
|
3170
|
+
else if (parent.isArrowFunctionExpression() && child.key === 'body') fn = parent;
|
|
3171
|
+
if (fn === null) return false;
|
|
3172
|
+
if (fn === fnPath) return true;
|
|
3173
|
+
return (fn.isArrowFunctionExpression() || fn.isFunctionExpression()) && placesValue(fn, fnPath, state, true);
|
|
3174
|
+
}
|
|
3175
|
+
|
|
3176
|
+
// An attribute whose value is rendered where it stands: one a component
|
|
3177
|
+
// takes as a lazy prop, or the fallback of a <Show> or a <Switch>, which the
|
|
3178
|
+
// compiler places in the conditional it lowers them to.
|
|
3179
|
+
function placingAttribute(el, attr, state) {
|
|
3180
|
+
if (isLoweredTag(el, 'Show', state) || isLoweredTag(el, 'Switch', state)) return getAttrName(attr) === 'fallback';
|
|
3181
|
+
return isSlotAttribute(el, attr, state);
|
|
3182
|
+
}
|
|
3183
|
+
|
|
3184
|
+
// A built-in the DOM back end lowers (dom.js transformElementFineGrained):
|
|
3185
|
+
// What's own <For>, <Show> or <Switch>, never a third party's of that name.
|
|
3186
|
+
function isLoweredTag(el, tag, state) {
|
|
3187
|
+
return controlFlowTag(el, state) === tag;
|
|
3188
|
+
}
|
|
3189
|
+
|
|
3190
|
+
/**
|
|
3191
|
+
* Whether the attribute `attr` of the JSX element `el` hands its value to a
|
|
3192
|
+
* component as a lazy prop (dom.js transformComponentFineGrained, _$slots):
|
|
3193
|
+
* any attribute of a component after its last spread, but `key`, `ref`,
|
|
3194
|
+
* `children`, an event handler, a namespaced name (`bind:`, `client:`) and
|
|
3195
|
+
* any attribute of an island or of a built-in the DOM back end lowers.
|
|
3196
|
+
*/
|
|
3197
|
+
export function isSlotAttribute(el, attr, state) {
|
|
3198
|
+
if (!isComponentElement(el) || controlFlowTag(el, state) !== null) return false;
|
|
3199
|
+
const attrs = el.openingElement.attributes;
|
|
3200
|
+
const name = getAttrName(attr);
|
|
3201
|
+
// A later spread or a later attribute of the same name decides the value.
|
|
3202
|
+
for (let i = attrs.indexOf(attr) + 1; i < attrs.length; i++) {
|
|
3203
|
+
if (t.isJSXSpreadAttribute(attrs[i]) || getAttrName(attrs[i]) === name) return false;
|
|
3204
|
+
}
|
|
3205
|
+
if (attrs.some((a) => t.isJSXAttribute(a) && getAttrName(a).startsWith('client:'))) return false;
|
|
3206
|
+
return name !== 'key' && name !== 'ref' && name !== 'children' && !name.includes(':') && !isEventAttrName(name);
|
|
3207
|
+
}
|
|
3208
|
+
|
|
3209
|
+
// `props[key]` read where it is placed: `_$place(props, "key")` for the DOM
|
|
3210
|
+
// back end (the reactivity analysis reads it as `props.key`), `props.key` for
|
|
3211
|
+
// the server's.
|
|
3212
|
+
function placingRead(propsId, key, state, fallback = null) {
|
|
3213
|
+
if (state.ssr) return t.memberExpression(t.cloneNode(propsId), propKey(key), !t.isIdentifier(propKey(key)));
|
|
3214
|
+
const callee = helper(state, '_$place');
|
|
3215
|
+
callee._whatPlace = true;
|
|
3216
|
+
const args = [t.cloneNode(propsId), t.stringLiteral(key)];
|
|
3217
|
+
// `({ label = 'x' })`: the default, applied where the value is undefined.
|
|
3218
|
+
if (fallback !== null) args.push(t.unaryExpression('void', t.numericLiteral(0)), t.cloneNode(fallback));
|
|
3219
|
+
return t.callExpression(callee, args);
|
|
3220
|
+
}
|
|
3221
|
+
|
|
3222
|
+
// --- A spread through React's host rules ---
|
|
3223
|
+
// what-react's translate mode writes a spread on a host element of a React
|
|
3224
|
+
// component it made native as `{..._$hostProps(rest)}` (react-compat
|
|
3225
|
+
// translated.js): the element is handed the props by React's rules for a
|
|
3226
|
+
// host element (style numbers in pixels, onFocus that bubbles, SVG names).
|
|
3227
|
+
// Everything the compiler decides from a spread's object is the argument's:
|
|
3228
|
+
// whether it is read again, the children it holds, the reads it keeps live.
|
|
3229
|
+
// So the spread is compiled as `{...rest}`, and the element is handed the
|
|
3230
|
+
// call (hostSpreadArgument).
|
|
3231
|
+
|
|
3232
|
+
/** Each such spread of the program as the spread of its argument, its call kept on the attribute. `names`: the local names of what-react/translated's `_$hostProps`. */
|
|
3233
|
+
export function unwrapHostSpreads(programPath, names) {
|
|
3234
|
+
if (names.size === 0) return;
|
|
3235
|
+
let unwrapped = false;
|
|
3236
|
+
t.traverseFast(programPath.node, (node) => {
|
|
3237
|
+
if (node.type !== 'JSXSpreadAttribute') return;
|
|
3238
|
+
const call = node.argument;
|
|
3239
|
+
if (!t.isCallExpression(call) || !t.isIdentifier(call.callee) || !names.has(call.callee.name) || call.arguments.length === 0) return;
|
|
3240
|
+
node._whatHostProps = call;
|
|
3241
|
+
node.argument = call.arguments[0];
|
|
3242
|
+
unwrapped = true;
|
|
3243
|
+
});
|
|
3244
|
+
// The references in the arguments now stand in the spreads: a rewrite of
|
|
3245
|
+
// one (a destructured prop read as `props.<key>`) is made there.
|
|
3246
|
+
if (unwrapped) programPath.scope.crawl();
|
|
3247
|
+
}
|
|
3248
|
+
|
|
3249
|
+
/** What the spread attribute `attr` hands its element: its argument, through translate mode's call where it was written in one. */
|
|
3250
|
+
export function hostSpreadArgument(attr) {
|
|
3251
|
+
const call = attr._whatHostProps;
|
|
3252
|
+
return call === undefined ? attr.argument : t.callExpression(t.cloneNode(call.callee), [attr.argument, ...call.arguments.slice(1)]);
|
|
3253
|
+
}
|
|
3254
|
+
|
|
3255
|
+
// --- A spread's children ---
|
|
3256
|
+
// `<a {...props} />` with `props.children` renders the children in React:
|
|
3257
|
+
// the element's props are the spread, children included. An element with no
|
|
3258
|
+
// children of its own is given the spread's as its content, read where they
|
|
3259
|
+
// are placed (`{_$place(props, "children")}` for the DOM back end, the read
|
|
3260
|
+
// `props.children` for the server's), so lazy children are built in the
|
|
3261
|
+
// element and live ones stay live; the setters never write `children` as an
|
|
3262
|
+
// attribute (render.js spread). Several spreads: the last that holds children,
|
|
3263
|
+
// as their merge would. Only a spread of a name or a member chain is read
|
|
3264
|
+
// again; any other argument is evaluated once by the spread (its children,
|
|
3265
|
+
// if any, are not rendered). Not for a void element, a <textarea> (its
|
|
3266
|
+
// children are its default, React's warning) or an element that names
|
|
3267
|
+
// `children` itself.
|
|
3268
|
+
const NO_SPREAD_CHILDREN = new Set(['textarea', 'noscript', 'template']);
|
|
3269
|
+
|
|
3270
|
+
export function spreadChildren(elPath, state) {
|
|
3271
|
+
const node = elPath.node;
|
|
3272
|
+
const name = node.openingElement.name;
|
|
3273
|
+
if (!t.isJSXIdentifier(name)) return;
|
|
3274
|
+
// A tag held in a binding may name an element (`<Tag {...rest} />`), which
|
|
3275
|
+
// what-core renders with the props' children (render.js tagComponent). The
|
|
3276
|
+
// server renders it as the vnode `h(Tag, props, ...children)`, so it is
|
|
3277
|
+
// handed them as its children too; a component given them that way gets
|
|
3278
|
+
// the same `props.children`.
|
|
3279
|
+
if (isComponent(name.name) ? !state.ssr || !mayHoldTag(elPath.scope.getBinding(name.name))
|
|
3280
|
+
: isVoidHtmlElement(name.name) || NO_SPREAD_CHILDREN.has(name.name)) return;
|
|
3281
|
+
const attrs = node.openingElement.attributes;
|
|
3282
|
+
// An object literal with no spread and no `children` in it holds no
|
|
3283
|
+
// children (`{...{ title: 'last' }}`): the other spreads' are placed. One
|
|
3284
|
+
// that names them (`{...{ children: 'last' }}`) is read again for them,
|
|
3285
|
+
// in its place among the spreads, so the last that holds children wins.
|
|
3286
|
+
const plain = (arg) => t.isObjectExpression(arg) && arg.properties.every((p) => t.isObjectProperty(p) && !p.computed);
|
|
3287
|
+
const names = (arg) => arg.properties.some((p) => propertyName(p.key, false) === 'children');
|
|
3288
|
+
const spreads = attrs.filter((a) => t.isJSXSpreadAttribute(a) && !(plain(a.argument) && !names(a.argument)));
|
|
3289
|
+
if (spreads.length === 0 || attrs.some((a) => t.isJSXAttribute(a) && getAttrName(a) === 'children')) return;
|
|
3290
|
+
if (node.children.some((c) => !t.isJSXText(c) || /[^ \t\r\n]/.test(c.value))) return;
|
|
3291
|
+
if (!spreads.every((s) => isNameChain(s.argument) || plain(s.argument))) return;
|
|
3292
|
+
const source = spreads.length === 1 ? spreads[0].argument
|
|
3293
|
+
: state.ssr ? t.objectExpression(spreads.map((s) => t.spreadElement(t.cloneNode(s.argument))))
|
|
3294
|
+
: t.callExpression(helper(state, '_$merge'), spreads.map((s) => t.cloneNode(s.argument)));
|
|
3295
|
+
node.children = [t.jsxExpressionContainer(placingRead(source, 'children', state))];
|
|
3296
|
+
if (node.openingElement.selfClosing) {
|
|
3297
|
+
node.openingElement.selfClosing = false;
|
|
3298
|
+
node.closingElement = t.jsxClosingElement(t.jsxIdentifier(name.name));
|
|
3299
|
+
}
|
|
3300
|
+
}
|
|
3301
|
+
|
|
3302
|
+
// A binding that may hold an element's name: not a function, a class or an
|
|
3303
|
+
// import, which name components.
|
|
3304
|
+
function mayHoldTag(binding) {
|
|
3305
|
+
if (!binding || binding.kind === 'module' || binding.kind === 'hoisted') return false;
|
|
3306
|
+
const node = binding.path.node;
|
|
3307
|
+
if (t.isClassDeclaration(node) || t.isFunction(node)) return false;
|
|
3308
|
+
const init = t.isVariableDeclarator(node) ? node.init : null;
|
|
3309
|
+
return !(t.isFunction(init) || t.isClassExpression(init));
|
|
3310
|
+
}
|
|
3311
|
+
|
|
3312
|
+
// `a`, `this`, `a.b.c`, `a['b']`: read again with no side effect.
|
|
3313
|
+
function isNameChain(node) {
|
|
3314
|
+
while (t.isMemberExpression(node) && (!node.computed || t.isStringLiteral(node.property))) node = node.object;
|
|
3315
|
+
return t.isIdentifier(node) || t.isThisExpression(node);
|
|
3316
|
+
}
|
|
3317
|
+
|
|
3318
|
+
// Moving a parameter pattern into the body changes what its defaults and
|
|
3319
|
+
// computed keys see: a name the body declares, which they could not see
|
|
3320
|
+
// before.
|
|
3321
|
+
function movesIntoBody(fnPath, others) {
|
|
3322
|
+
let safe = true;
|
|
3323
|
+
for (const prop of fnPath.get('params.0.properties')) {
|
|
3324
|
+
if (!others.includes(prop.node)) continue;
|
|
3325
|
+
prop.traverse({
|
|
3326
|
+
ReferencedIdentifier(ref) {
|
|
3327
|
+
const binding = fnPath.scope.getOwnBinding(ref.node.name);
|
|
3328
|
+
if (binding && binding.kind !== 'param') safe = false;
|
|
3329
|
+
},
|
|
3330
|
+
});
|
|
3331
|
+
}
|
|
3332
|
+
return safe;
|
|
3333
|
+
}
|
|
3334
|
+
|
|
3335
|
+
// Each read of a placed binding becomes a placing read of `props.<key>`
|
|
3336
|
+
// where it stands, and each read of a live one the read `props.<key>`. With
|
|
3337
|
+
// a default, one read into a temporary: a read once the component has
|
|
3338
|
+
// returned builds the value again.
|
|
3339
|
+
function readAtUse(fnPath, found, propsId, state) {
|
|
3340
|
+
const entries = [
|
|
3341
|
+
...found.placed.map((entry) => [entry, () => placingRead(propsId, entry.key, state)]),
|
|
3342
|
+
...found.live.map((entry) => [entry, () => pathRead(propRead(propsId, entry.key), entry.path)]),
|
|
3343
|
+
];
|
|
3344
|
+
for (const [entry, read] of entries) {
|
|
3345
|
+
const { key, binding } = entry;
|
|
3346
|
+
let fallback = entry.fallback;
|
|
3347
|
+
if (entry.hoist) {
|
|
3348
|
+
// The default, made once when the component runs.
|
|
3349
|
+
const made = fnPath.scope.generateUidIdentifier(`${key}Default`);
|
|
3350
|
+
fnPath.scope.push({ id: made, init: fallback, kind: 'const' });
|
|
3351
|
+
fallback = made;
|
|
3352
|
+
}
|
|
3353
|
+
for (const ref of binding.referencePaths) {
|
|
3354
|
+
// `{ id }` in an object literal names the prop's value.
|
|
3355
|
+
if (ref.parentPath.isObjectProperty({ shorthand: true }) && ref.key === 'value') ref.parent.shorthand = false;
|
|
3356
|
+
}
|
|
3357
|
+
if (fallback === null) {
|
|
3358
|
+
for (const ref of binding.referencePaths) ref.replaceWith(read());
|
|
3359
|
+
continue;
|
|
3360
|
+
}
|
|
3361
|
+
if (!state.ssr && found.placed.some((entry) => entry.binding === binding)) {
|
|
3362
|
+
// The DOM back end's placing read takes the default (dom.js _place),
|
|
3363
|
+
// which a live prop applies at each read.
|
|
3364
|
+
for (const ref of binding.referencePaths) ref.replaceWith(placingRead(propsId, key, state, fallback));
|
|
3365
|
+
continue;
|
|
3366
|
+
}
|
|
3367
|
+
const temp = fnPath.scope.generateUidIdentifier(key);
|
|
3368
|
+
for (const ref of binding.referencePaths) {
|
|
3369
|
+
ref.replaceWith(t.conditionalExpression(
|
|
3370
|
+
t.binaryExpression('===', t.assignmentExpression('=', t.cloneNode(temp), read()), t.unaryExpression('void', t.numericLiteral(0))),
|
|
3371
|
+
t.cloneNode(fallback),
|
|
3372
|
+
t.cloneNode(temp),
|
|
3373
|
+
));
|
|
3374
|
+
}
|
|
3375
|
+
fnPath.scope.push({ id: temp });
|
|
3376
|
+
}
|
|
3377
|
+
}
|
|
3378
|
+
|
|
3379
|
+
// `read.a.b` for a nested pattern's path, `read?.a` where the pattern
|
|
3380
|
+
// defaults to `{}`.
|
|
3381
|
+
function pathRead(read, path) {
|
|
3382
|
+
if (path === undefined) return read;
|
|
3383
|
+
for (const { name, optional } of path) {
|
|
3384
|
+
const k = propKey(name);
|
|
3385
|
+
read = optional ? t.optionalMemberExpression(read, k, !t.isIdentifier(k), true) : t.memberExpression(read, k, !t.isIdentifier(k));
|
|
3386
|
+
}
|
|
3387
|
+
return read;
|
|
3388
|
+
}
|
|
3389
|
+
|
|
3390
|
+
// `props.<key>`, a live read (not a placing one).
|
|
3391
|
+
function propRead(propsId, key) {
|
|
3392
|
+
const k = propKey(key);
|
|
3393
|
+
return t.memberExpression(t.cloneNode(propsId), k, !t.isIdentifier(k));
|
|
3394
|
+
}
|
|
3395
|
+
|
|
3396
|
+
// Declarators for the pattern's other properties, read from `source`. The
|
|
3397
|
+
// rest object names the keys it leaves out instead: destructuring a placed
|
|
3398
|
+
// prop into nothing would read it.
|
|
3399
|
+
function otherProps(fnPath, found, source, state) {
|
|
3400
|
+
const named = found.rest === null ? found.others : found.others.slice(0, -1);
|
|
3401
|
+
const declarators = [];
|
|
3402
|
+
if (named.length > 0) declarators.push(t.variableDeclarator(t.objectPattern(named), t.cloneNode(source)));
|
|
3403
|
+
if (found.rest !== null) {
|
|
3404
|
+
const excluded = [...new Set([...found.placed.map((p) => p.key), ...found.live.map((p) => p.key), ...named.map((p) => propertyName(p.key, p.computed))])].map((name) => t.stringLiteral(name));
|
|
3405
|
+
// The DOM back end's rest keeps live props live (render.js _$omit); the
|
|
3406
|
+
// server renders once and reads them.
|
|
3407
|
+
const omit = state.ssr ? fnPath.hub.addHelper('objectWithoutProperties') : helper(state, '_$omit');
|
|
3408
|
+
const without = t.callExpression(omit, [t.cloneNode(source), t.arrayExpression(excluded)]);
|
|
3409
|
+
const rest = t.variableDeclarator(found.rest.argument, without);
|
|
3410
|
+
// It holds the props' getters: its reads are props reads (readRestsWhereUsed).
|
|
3411
|
+
rest._whatPropsRest = true;
|
|
3412
|
+
(fnPath.node._whatPropsRests ||= []).push(found.rest.argument.name);
|
|
3413
|
+
declarators.push(rest);
|
|
3414
|
+
}
|
|
3415
|
+
return declarators;
|
|
3416
|
+
}
|
|
3417
|
+
|
|
3418
|
+
export function isVoidHtmlElement(name) {
|
|
3419
|
+
return VOID_ELEMENTS.has(String(name).toLowerCase());
|
|
3420
|
+
}
|
|
3421
|
+
|
|
3422
|
+
export function getAttributeValue(value) {
|
|
3423
|
+
if (!value) return t.booleanLiteral(true);
|
|
3424
|
+
if (t.isJSXExpressionContainer(value)) return value.expression;
|
|
3425
|
+
if (t.isStringLiteral(value)) return value;
|
|
3426
|
+
return t.stringLiteral(value.value || '');
|
|
3427
|
+
}
|
|
3428
|
+
|
|
3429
|
+
// Is this attribute overwritten by a later one naming the same DOM property?
|
|
3430
|
+
//
|
|
3431
|
+
// `<div id={a} id="b"/>` is legal JSX and means id="b": the last writer of a
|
|
3432
|
+
// name wins, exactly as it does in the object literal the h() spelling
|
|
3433
|
+
// builds. The template could not express that, because a repeated attribute
|
|
3434
|
+
// in an HTML string keeps the FIRST value and a dynamic attribute is applied
|
|
3435
|
+
// after the template regardless of where it was written. Dropping the
|
|
3436
|
+
// shadowed one leaves a single writer per name, so written order decides.
|
|
3437
|
+
//
|
|
3438
|
+
// A later SPREAD never shadows: it overrides only the names it actually
|
|
3439
|
+
// carries, which is not knowable here and is handled by ordering instead.
|
|
3440
|
+
export function isShadowedAttr(attributes, index) {
|
|
3441
|
+
const name = writerName(getAttrName(attributes[index]));
|
|
3442
|
+
for (let i = index + 1; i < attributes.length; i += 1) {
|
|
3443
|
+
const later = attributes[i];
|
|
3444
|
+
if (t.isJSXSpreadAttribute(later)) continue;
|
|
3445
|
+
if (writerName(getAttrName(later)) === name) return true;
|
|
3446
|
+
}
|
|
3447
|
+
return false;
|
|
3448
|
+
}
|
|
3449
|
+
|
|
3450
|
+
// The DOM property an attribute writes: its alias's (`className` is
|
|
3451
|
+
// `class`), an event's in lower case (`onClick` and `onclick` are one
|
|
3452
|
+
// listener, as the runtime binds them).
|
|
3453
|
+
function writerName(name) {
|
|
3454
|
+
return isEventAttrName(name) && !name.includes('|') ? name.toLowerCase() : attributeName(name);
|
|
3455
|
+
}
|
|
3456
|
+
|
|
3457
|
+
// Safely extract attribute name, handling JSXNamespacedName (e.g., client:idle, bind:value)
|
|
3458
|
+
export function getAttrName(attr) {
|
|
3459
|
+
if (t.isJSXNamespacedName(attr.name)) {
|
|
3460
|
+
return `${attr.name.namespace.name}:${attr.name.name.name}`;
|
|
3461
|
+
}
|
|
3462
|
+
return typeof attr.name.name === 'string' ? attr.name.name : String(attr.name.name);
|
|
3463
|
+
}
|
|
3464
|
+
|
|
3465
|
+
// The key half of a prop in an emitted object literal. A JSX attribute name is
|
|
3466
|
+
// frequently NOT a valid JavaScript identifier — `data-x`, `aria-label` and
|
|
3467
|
+
// every namespaced name contain characters an identifier cannot — so anything
|
|
3468
|
+
// that does not match has to be quoted.
|
|
3469
|
+
//
|
|
3470
|
+
// Shared rather than inlined because babel's builders do not validate: handing
|
|
3471
|
+
// t.identifier() a name with a dash produces `{data-x: "1"}` in the output and
|
|
3472
|
+
// no error anywhere, so the mistake surfaces as a parse failure in generated
|
|
3473
|
+
// code. Two call sites had their own copy of this test and one of them was
|
|
3474
|
+
// missing it entirely.
|
|
3475
|
+
export function propKey(name) {
|
|
3476
|
+
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name) ? t.identifier(name) : t.stringLiteral(name);
|
|
3477
|
+
}
|
|
3478
|
+
|
|
3479
|
+
// Handler-shaped attribute name, case-insensitive. Mirrors _isEventProp in
|
|
3480
|
+
// what-core's dom.js.
|
|
3481
|
+
export function isEventAttrName(name) {
|
|
3482
|
+
return !!name && name.length > 2 && /^on/i.test(name);
|
|
3483
|
+
}
|
|
3484
|
+
|
|
3485
|
+
export function createEventHandler(handler, modifiers) {
|
|
3486
|
+
if (modifiers.length === 0) return handler;
|
|
3487
|
+
|
|
3488
|
+
let wrappedHandler = handler;
|
|
3489
|
+
|
|
3490
|
+
for (const mod of modifiers) {
|
|
3491
|
+
switch (mod) {
|
|
3492
|
+
case 'preventDefault':
|
|
3493
|
+
wrappedHandler = t.arrowFunctionExpression(
|
|
3494
|
+
[t.identifier('e')],
|
|
3495
|
+
t.blockStatement([
|
|
3496
|
+
t.expressionStatement(
|
|
3497
|
+
t.callExpression(
|
|
3498
|
+
t.memberExpression(t.identifier('e'), t.identifier('preventDefault')),
|
|
3499
|
+
[]
|
|
3500
|
+
)
|
|
3501
|
+
),
|
|
3502
|
+
t.expressionStatement(
|
|
3503
|
+
t.callExpression(wrappedHandler, [t.identifier('e')])
|
|
3504
|
+
)
|
|
3505
|
+
])
|
|
3506
|
+
);
|
|
3507
|
+
break;
|
|
3508
|
+
|
|
3509
|
+
case 'stopPropagation':
|
|
3510
|
+
wrappedHandler = t.arrowFunctionExpression(
|
|
3511
|
+
[t.identifier('e')],
|
|
3512
|
+
t.blockStatement([
|
|
3513
|
+
t.expressionStatement(
|
|
3514
|
+
t.callExpression(
|
|
3515
|
+
t.memberExpression(t.identifier('e'), t.identifier('stopPropagation')),
|
|
3516
|
+
[]
|
|
3517
|
+
)
|
|
3518
|
+
),
|
|
3519
|
+
t.expressionStatement(
|
|
3520
|
+
t.callExpression(wrappedHandler, [t.identifier('e')])
|
|
3521
|
+
)
|
|
3522
|
+
])
|
|
3523
|
+
);
|
|
3524
|
+
break;
|
|
3525
|
+
|
|
3526
|
+
case 'self':
|
|
3527
|
+
wrappedHandler = t.arrowFunctionExpression(
|
|
3528
|
+
[t.identifier('e')],
|
|
3529
|
+
t.blockStatement([
|
|
3530
|
+
t.ifStatement(
|
|
3531
|
+
t.binaryExpression(
|
|
3532
|
+
'===',
|
|
3533
|
+
t.memberExpression(t.identifier('e'), t.identifier('target')),
|
|
3534
|
+
t.memberExpression(t.identifier('e'), t.identifier('currentTarget'))
|
|
3535
|
+
),
|
|
3536
|
+
t.expressionStatement(
|
|
3537
|
+
t.callExpression(wrappedHandler, [t.identifier('e')])
|
|
3538
|
+
)
|
|
3539
|
+
)
|
|
3540
|
+
])
|
|
3541
|
+
);
|
|
3542
|
+
break;
|
|
3543
|
+
|
|
3544
|
+
case 'once':
|
|
3545
|
+
case 'capture':
|
|
3546
|
+
case 'passive':
|
|
3547
|
+
break;
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
|
|
3551
|
+
return wrappedHandler;
|
|
3552
|
+
}
|
|
3553
|
+
|
|
3554
|
+
// =====================================================
|
|
3555
|
+
// Fine-Grained Mode (template + insert + effect)
|
|
3556
|
+
// =====================================================
|
|
3557
|
+
|
|
3558
|
+
// Whether the attribute at `index` is a form field's value, checked or
|
|
3559
|
+
// default (an input's, a textarea's or a select's). The template's attribute
|
|
3560
|
+
// is the field's default, which no value is written to, and a textarea's or a
|
|
3561
|
+
// select's default is no attribute at all, so these are set by the runtime's
|
|
3562
|
+
// field setters (render.js setValue, setChecked, setProp). An input whose
|
|
3563
|
+
// static type makes its value an attribute (a checkbox, a button) keeps it.
|
|
3564
|
+
export function isFieldProp(tagName, attributes, index) {
|
|
3565
|
+
if (!FIELD_TAGS.has(tagName)) return false;
|
|
3566
|
+
const name = getAttrName(attributes[index]);
|
|
3567
|
+
if (!FIELD_PROPS.has(name)) return false;
|
|
3568
|
+
if (tagName !== 'input' || (name !== 'value' && name !== 'defaultValue')) return true;
|
|
3569
|
+
const type = attributes.find((a) => !t.isJSXSpreadAttribute(a) && getAttrName(a) === 'type');
|
|
3570
|
+
return !(type && t.isStringLiteral(type.value) && ATTRIBUTE_VALUE_TYPES.has(type.value.value.toLowerCase()));
|
|
3571
|
+
}
|
|
3572
|
+
|
|
3573
|
+
// Check if a JSX child is static (no expressions, nothing a runtime setter writes)
|
|
3574
|
+
export function isStaticChild(child) {
|
|
3575
|
+
if (t.isJSXText(child)) return true;
|
|
3576
|
+
if (t.isJSXExpressionContainer(child)) return false;
|
|
3577
|
+
if (t.isJSXElement(child)) {
|
|
3578
|
+
const el = child.openingElement;
|
|
3579
|
+
if (isComponentElement(child)) return false;
|
|
3580
|
+
for (const [i, attr] of el.attributes.entries()) {
|
|
3581
|
+
if (t.isJSXSpreadAttribute(attr)) return false;
|
|
3582
|
+
const value = attr.value;
|
|
3583
|
+
if (t.isJSXExpressionContainer(value)) return false;
|
|
3584
|
+
if (isFieldProp(el.name.name, el.attributes, i)) return false;
|
|
3585
|
+
}
|
|
3586
|
+
return child.children.every(isStaticChild);
|
|
3587
|
+
}
|
|
3588
|
+
return false;
|
|
3589
|
+
}
|
|
3590
|
+
|
|
3591
|
+
// Check if an attribute value is dynamic
|
|
3592
|
+
export function isDynamicAttr(attr) {
|
|
3593
|
+
if (t.isJSXSpreadAttribute(attr)) return true;
|
|
3594
|
+
if (!attr.value) return false;
|
|
3595
|
+
return t.isJSXExpressionContainer(attr.value);
|
|
3596
|
+
}
|
|
3597
|
+
|
|
3598
|
+
// --- Element namespaces ---
|
|
3599
|
+
//
|
|
3600
|
+
// What a template parses as depends on where its root sits: under <svg> an
|
|
3601
|
+
// element is SVG and under <math> it is MathML, except where the HTML parser
|
|
3602
|
+
// switches back to HTML (its integration points):
|
|
3603
|
+
// - the children of SVG <foreignObject>, <desc> and <title>;
|
|
3604
|
+
// - the children of MathML <annotation-xml> whose encoding is text/html or
|
|
3605
|
+
// application/xhtml+xml;
|
|
3606
|
+
// - the children of the MathML token elements <mi>, <mo>, <mn>, <ms> and
|
|
3607
|
+
// <mtext>, apart from <mglyph> and <malignmark>, which stay MathML.
|
|
3608
|
+
// A JSX tree is split into several templates (each dynamic child's JSX becomes
|
|
3609
|
+
// a root of its own), and by the time a nested root is lowered its enclosing
|
|
3610
|
+
// JSX is gone, so every element of a tree is annotated with its namespace
|
|
3611
|
+
// (`_whatNs`) before the tree is lowered.
|
|
3612
|
+
//
|
|
3613
|
+
// A root with no JSX around it is placed by its tag: an element that exists
|
|
3614
|
+
// only in SVG or only in MathML is in that namespace; anything else,
|
|
3615
|
+
// including the names both share with HTML (a, title, script, style), is HTML.
|
|
3616
|
+
const SVG_ONLY_TAGS = new Set([
|
|
3617
|
+
'animate', 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'defs', 'desc',
|
|
3618
|
+
'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite',
|
|
3619
|
+
'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight',
|
|
3620
|
+
'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur',
|
|
3621
|
+
'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight',
|
|
3622
|
+
'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter', 'foreignObject',
|
|
3623
|
+
'g', 'image', 'line', 'linearGradient', 'marker', 'mask', 'metadata', 'mpath', 'path',
|
|
3624
|
+
'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'stop', 'switch',
|
|
3625
|
+
'symbol', 'text', 'textPath', 'tspan', 'use', 'view',
|
|
3626
|
+
]);
|
|
3627
|
+
const MATHML_ONLY_TAGS = new Set([
|
|
3628
|
+
'annotation', 'annotation-xml', 'maction', 'menclose', 'merror', 'mfenced', 'mfrac', 'mi',
|
|
3629
|
+
'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mprescripts', 'mroot', 'mrow',
|
|
3630
|
+
'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr',
|
|
3631
|
+
'munder', 'munderover', 'semantics',
|
|
3632
|
+
]);
|
|
3633
|
+
|
|
3634
|
+
|
|
3635
|
+
// The context an element's children are parsed in. 'mathtext' is the inside of
|
|
3636
|
+
// a MathML token element: HTML, except for the two MathML-only names above.
|
|
3637
|
+
function childContext(own, tag, attributes) {
|
|
3638
|
+
if (own === 'svg') return SVG_HTML_INTEGRATION_POINTS.has(tag) ? 'html' : 'svg';
|
|
3639
|
+
if (own !== 'math') return own;
|
|
3640
|
+
if (MATHML_TEXT_INTEGRATION_POINTS.has(tag)) return 'mathtext';
|
|
3641
|
+
if (tag === 'annotation-xml') {
|
|
3642
|
+
const encoding = attributes.find(a => t.isJSXAttribute(a) && getAttrName(a) === 'encoding');
|
|
3643
|
+
if (encoding && t.isStringLiteral(encoding.value) && HTML_ENCODINGS.has(encoding.value.value.toLowerCase())) {
|
|
3644
|
+
return 'html';
|
|
3645
|
+
}
|
|
3646
|
+
}
|
|
3647
|
+
return 'math';
|
|
3648
|
+
}
|
|
3649
|
+
|
|
3650
|
+
// A component placed in SVG or MathML, or in HTML inside one of them (an
|
|
3651
|
+
// integration point), also gets `_whatPlacedNs` (1 SVG, 2 MathML, 0 HTML):
|
|
3652
|
+
// what-core creates a tag held in a binding below it that SVG and HTML both
|
|
3653
|
+
// name in that namespace (render.js _$inNs).
|
|
3654
|
+
export function annotateNamespaces(root) {
|
|
3655
|
+
const visit = (node, ns, foreign = false) => {
|
|
3656
|
+
if (!node || typeof node !== 'object') return;
|
|
3657
|
+
if (Array.isArray(node)) {
|
|
3658
|
+
for (const item of node) visit(item, ns, foreign);
|
|
3659
|
+
return;
|
|
3660
|
+
}
|
|
3661
|
+
if (node.type === 'JSXElement') {
|
|
3662
|
+
const name = node.openingElement.name;
|
|
3663
|
+
if (t.isJSXIdentifier(name) && !isComponent(name.name)) {
|
|
3664
|
+
const tag = name.name;
|
|
3665
|
+
const own = tag === 'svg' ? 'svg'
|
|
3666
|
+
: tag === 'math' ? 'math'
|
|
3667
|
+
: ns === 'mathtext' ? (MATHML_IN_TEXT_POINTS.has(tag) ? 'math' : 'html')
|
|
3668
|
+
: ns !== null ? ns
|
|
3669
|
+
: SVG_ONLY_TAGS.has(tag) ? 'svg'
|
|
3670
|
+
: MATHML_ONLY_TAGS.has(tag) ? 'math'
|
|
3671
|
+
: 'html';
|
|
3672
|
+
node._whatNs = own;
|
|
3673
|
+
const inner = childContext(own, tag, node.openingElement.attributes);
|
|
3674
|
+
const within = foreign || own === 'svg' || own === 'math';
|
|
3675
|
+
visit(node.openingElement.attributes, inner, within);
|
|
3676
|
+
visit(node.children, inner, within);
|
|
3677
|
+
} else {
|
|
3678
|
+
// A component renders its children where it stands.
|
|
3679
|
+
node._whatNs = ns;
|
|
3680
|
+
if (ns === 'svg' || ns === 'math') node._whatPlacedNs = ns === 'svg' ? 1 : 2;
|
|
3681
|
+
else if (foreign) node._whatPlacedNs = 0;
|
|
3682
|
+
visit(node.openingElement.attributes, ns, foreign);
|
|
3683
|
+
visit(node.children, ns, foreign);
|
|
3684
|
+
}
|
|
3685
|
+
return;
|
|
3686
|
+
}
|
|
3687
|
+
if (node.type === 'JSXFragment') {
|
|
3688
|
+
node._whatNs = ns;
|
|
3689
|
+
visit(node.children, ns, foreign);
|
|
3690
|
+
return;
|
|
3691
|
+
}
|
|
3692
|
+
for (const key of t.VISITOR_KEYS[node.type] || []) visit(node[key], ns, foreign);
|
|
3693
|
+
};
|
|
3694
|
+
visit(root, null);
|
|
3695
|
+
}
|
|
3696
|
+
|
|
3697
|
+
// Does `path` sit in a slot its parent only evaluates SOMETIMES?
|
|
3698
|
+
//
|
|
3699
|
+
// Used to decide whether a JSX root's setup statements may be hoisted out to
|
|
3700
|
+
// the enclosing statement. Anything in one of these slots must not be: the
|
|
3701
|
+
// source deliberately said "only build this when the guard opens", and the
|
|
3702
|
+
// hoist turns that into "always build this".
|
|
3703
|
+
//
|
|
3704
|
+
// Only the slots that are genuinely skipped count. A logical expression's
|
|
3705
|
+
// LEFT operand and a ternary's TEST always run, so JSX there is not guarded
|
|
3706
|
+
// and keeps the cheaper hoist.
|
|
3707
|
+
export function isConditionallyEvaluated(path) {
|
|
3708
|
+
const parent = path.parent;
|
|
3709
|
+
if (!parent) return false;
|
|
3710
|
+
if (t.isLogicalExpression(parent)) return path.key === 'right';
|
|
3711
|
+
if (t.isConditionalExpression(parent)) {
|
|
3712
|
+
return path.key === 'consequent' || path.key === 'alternate';
|
|
3713
|
+
}
|
|
3714
|
+
// `maybe?.render(<jsx/>)` skips its whole argument list when the chain
|
|
3715
|
+
// short-circuits, so an argument is guarded; the callee/object is not.
|
|
3716
|
+
if (t.isOptionalCallExpression(parent) || t.isOptionalMemberExpression(parent)) {
|
|
3717
|
+
return path.key !== 'callee' && path.key !== 'object';
|
|
3718
|
+
}
|
|
3719
|
+
return false;
|
|
3720
|
+
}
|
|
3721
|
+
|
|
3722
|
+
|
|
3723
|
+
// --- <Switch> arms ---
|
|
3724
|
+
//
|
|
3725
|
+
// <Switch fallback={alt}><Match when={a}>A</Match><Match when={b}>B</Match></Switch>
|
|
3726
|
+
// is read statically by both back ends. A <Switch> is provably What's when
|
|
3727
|
+
// either its binding was imported from What or it has literal <Match> arms;
|
|
3728
|
+
// anything else with the same tag name is somebody else's component, and this
|
|
3729
|
+
// returns null so it goes to the component path untouched. Once it is provably
|
|
3730
|
+
// ours, a shape whose arms cannot be read statically has nowhere to go, since
|
|
3731
|
+
// the runtime component would render its fallback and nothing else forever:
|
|
3732
|
+
// that is a compile error rather than a silent blank.
|
|
3733
|
+
export function readSwitch(path, state) {
|
|
3734
|
+
const { node } = path;
|
|
3735
|
+
// A <Switch> that got here on its arms alone came from the same foreign
|
|
3736
|
+
// specifier its arms did, so its <Match> is ours by the same reasoning.
|
|
3737
|
+
const armsProveIt = isForeignTag(node.openingElement.name.name, state);
|
|
3738
|
+
const isMatch = (child) => t.isJSXElement(child) && (controlFlowTag(child, state) === 'Match'
|
|
3739
|
+
|| (armsProveIt && t.isJSXIdentifier(child.openingElement.name, { name: 'Match' })));
|
|
3740
|
+
if (!node.children.some(isMatch) && !isWhatTag(node.openingElement.name.name, state)) return null;
|
|
3741
|
+
|
|
3742
|
+
const unsupported = (why) => {
|
|
3743
|
+
throw compileError(
|
|
3744
|
+
path,
|
|
3745
|
+
state,
|
|
3746
|
+
`<Switch> ${why}. The compiler needs to read its arms statically. ` +
|
|
3747
|
+
'Write them out: <Switch fallback={...}><Match when={a}>…</Match><Match when={b}>…</Match></Switch>'
|
|
3748
|
+
);
|
|
3749
|
+
};
|
|
3750
|
+
|
|
3751
|
+
let fallback = null;
|
|
3752
|
+
for (const attr of node.openingElement.attributes) {
|
|
3753
|
+
if (t.isJSXSpreadAttribute(attr)) unsupported('cannot take a spread attribute');
|
|
3754
|
+
if (getAttrName(attr) === 'fallback') fallback = getAttributeValue(attr.value);
|
|
3755
|
+
}
|
|
3756
|
+
|
|
3757
|
+
const arms = [];
|
|
3758
|
+
for (const child of node.children) {
|
|
3759
|
+
if (t.isJSXText(child)) {
|
|
3760
|
+
if (normalizeJsxText(child.value)) unsupported('cannot mix text with its <Match> arms');
|
|
3761
|
+
continue;
|
|
3762
|
+
}
|
|
3763
|
+
if (t.isJSXExpressionContainer(child)) {
|
|
3764
|
+
if (t.isJSXEmptyExpression(child.expression)) continue;
|
|
3765
|
+
unsupported('cannot read its arms from an expression child');
|
|
3766
|
+
}
|
|
3767
|
+
if (!isMatch(child)) unsupported('cannot mix other elements with its <Match> arms');
|
|
3768
|
+
let when = null;
|
|
3769
|
+
for (const attr of child.openingElement.attributes) {
|
|
3770
|
+
if (t.isJSXAttribute(attr) && getAttrName(attr) === 'when') when = getAttributeValue(attr.value);
|
|
3771
|
+
}
|
|
3772
|
+
if (!when) unsupported('has a <Match> with no "when" prop');
|
|
3773
|
+
arms.push({ when, children: child.children });
|
|
3774
|
+
}
|
|
3775
|
+
if (arms.length === 0) unsupported('has no <Match> arms');
|
|
3776
|
+
return { fallback, arms };
|
|
3777
|
+
}
|
|
3778
|
+
|
|
3779
|
+
// Add specifiers to the file's first import from one of `sources`, or to a new
|
|
3780
|
+
// import of `fallback`. A specifier whose local name is already imported there
|
|
3781
|
+
// is the same binding and is not repeated.
|
|
3782
|
+
export function addImports(path, specifiers, sources, fallback) {
|
|
3783
|
+
if (specifiers.length === 0) return;
|
|
3784
|
+
/** @type {any} */
|
|
3785
|
+
let existing = null;
|
|
3786
|
+
for (const node of path.node.body) {
|
|
3787
|
+
if (t.isImportDeclaration(node) && sources.includes(node.source.value)) {
|
|
3788
|
+
existing = node;
|
|
3789
|
+
break;
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
3792
|
+
if (!existing) {
|
|
3793
|
+
path.unshiftContainer('body', t.importDeclaration(specifiers, t.stringLiteral(fallback)));
|
|
3794
|
+
return;
|
|
3795
|
+
}
|
|
3796
|
+
const locals = new Set(existing.specifiers.map(s => s.local.name));
|
|
3797
|
+
for (const spec of specifiers) {
|
|
3798
|
+
if (!locals.has(spec.local.name)) existing.specifiers.push(spec);
|
|
3799
|
+
}
|
|
3800
|
+
}
|