what-compiler 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/babel.d.ts +78 -2
  4. package/dist/babel/auto-selector.min.js +94 -0
  5. package/dist/babel/common.min.js +2053 -0
  6. package/dist/babel/dev-metadata.min.js +106 -0
  7. package/dist/babel/dom.min.js +1669 -0
  8. package/dist/babel/jsx-root.min.js +13 -0
  9. package/dist/babel/lists.min.js +492 -0
  10. package/dist/babel/nesting.min.js +328 -0
  11. package/dist/babel/reactivity.min.js +1218 -0
  12. package/dist/babel/server-actions.min.js +85 -0
  13. package/dist/babel/ssr.min.js +496 -0
  14. package/dist/babel/types.min.js +9 -0
  15. package/dist/babel-plugin.min.js +101 -1
  16. package/dist/file-router.min.js +368 -12
  17. package/dist/framework-files.min.js +62 -0
  18. package/dist/hot.min.js +315 -0
  19. package/dist/index.min.js +13 -414
  20. package/dist/release.min.js +78 -0
  21. package/dist/runtime.min.js +9 -1
  22. package/dist/tables/import-changes.min.js +272 -0
  23. package/dist/tables/markup-rules.min.js +213 -0
  24. package/dist/vite-plugin.min.js +432 -399
  25. package/file-router.d.ts +3 -1
  26. package/index.d.ts +1 -1
  27. package/package.json +11 -2
  28. package/runtime.d.ts +2 -1
  29. package/src/babel/auto-selector.js +248 -0
  30. package/src/babel/common.js +3800 -0
  31. package/src/babel/dev-metadata.js +167 -0
  32. package/src/babel/dom.js +3386 -0
  33. package/src/babel/jsx-root.js +27 -0
  34. package/src/babel/lists.js +704 -0
  35. package/src/babel/nesting.js +260 -0
  36. package/src/babel/reactivity.js +1998 -0
  37. package/src/babel/server-actions.js +144 -0
  38. package/src/babel/ssr.js +870 -0
  39. package/src/babel/types.js +10 -0
  40. package/src/babel-plugin.js +185 -3598
  41. package/src/file-router.js +58 -38
  42. package/src/framework-files.js +106 -0
  43. package/src/hot.js +523 -0
  44. package/src/release.js +127 -0
  45. package/src/runtime.js +7 -7
  46. package/src/tables/import-changes.js +157 -0
  47. package/src/tables/markup-rules.js +388 -0
  48. package/src/vite-plugin.js +460 -175
  49. package/vite.d.ts +47 -3
  50. package/src/error-overlay.js +0 -428
@@ -0,0 +1,870 @@
1
+ // The server back end (`generate: "ssr"`): JSX lowered to server markup.
2
+ //
3
+ // An element becomes a module-level array of static strings, escaped and
4
+ // validated at build time, and one `_$ssr(template, ...holes)` call made where
5
+ // the JSX expression runs, as the h() call it stands for would be:
6
+ //
7
+ // <div class="card" id={props.id} title={t()} onClick={go}>Hello {name}!{count()}</div>
8
+ // const _tmpl$0 = _$ssrTemplate(['<div class="card"', '', '>Hello ', '!', '</div>'],
9
+ // [['plain', 'id'], ['plain', 'title'], null, null]);
10
+ // _$ssr(_tmpl$0, props.id, () => t(), _$ssrText(name), () => count())
11
+ //
12
+ // Every hole is what h() would be handed in its place, in source order (an
13
+ // attribute hole's kind and name are declared once, with the template):
14
+ // - a value written as itself (`{label}`, `{props.children}`, a literal, a
15
+ // non-reactive expression) is read now (_$ssrText for a child);
16
+ // - a reactive expression (`{count()}`, `title={t()}`) is the thunk h() gets
17
+ // from the DOM back end's auto-thunk, `() => count()`, rendered where the
18
+ // markup is placed;
19
+ // - a component, a fragment, <Show>, <Switch> and <For> are the vnode or the
20
+ // reactive child they are with h() and the DOM back end;
21
+ // - `{src.map(item => <li/>)}` renders its rows into one hole (_$ssrList).
22
+ // A reactive attribute of a row template is one function of the row's
23
+ // item, made once for the list (rowAttributes): the list hands its
24
+ // functions to the row's callback, the row hands them to its template
25
+ // and passes its item, and the function is called with the item where
26
+ // the thunk would have been.
27
+ // what-server's ssr-runtime renders the result (Markup) with h()'s rules, so
28
+ // the compiled string equals the h()-rendered string byte for byte, side
29
+ // effects in the same order (lowering-parity-fuzz.test.js). Event handlers,
30
+ // refs and keys are dropped.
31
+ //
32
+ // Compile-time checks (common.js applies the same static rules for the DOM
33
+ // back end; the run-time half is in ssr-runtime.js): tag and attribute names
34
+ // must be safe to emit verbatim, a static URL attribute must not use a
35
+ // javascript:/vbscript:/data: scheme, a static srcdoc or outerHTML is refused,
36
+ // innerHTML / dangerouslySetInnerHTML take { __html } values, never a string,
37
+ // static <script>/<style> text cannot end its element, and JSX is not an
38
+ // island prop.
39
+
40
+ import {
41
+ RAW_TEXT_ELEMENTS, TEXT_ONLY_ELEMENTS, LEADING_NEWLINE_ELEMENTS, SAFE_ATTR_NAME, SAFE_TAG_NAME, VOID_ELEMENTS, escapeHtml,
42
+ FIELD_PROPS, FIELD_TAGS, isEnumeratedAttr, isNamespaceNeutralText, isRefusedAttr, isUrlAttr, markupName,
43
+ } from '../tables/markup-rules.js';
44
+ import { t } from './types.js';
45
+ import {
46
+ addImports, checkElementName, checkStaticAttribute, checkStaticRawText, compileError,
47
+ componentCallee, createEventHandler, getAttrName, getAttributeValue, getBindingProperty, hasEventModifiers,
48
+ controlFlowTag, helper, helperLocals, isBindingAttribute, isComponentElement, isEventAttrName,
49
+ isSlotAttribute, normalizeJsxText, parseEventModifiers, propKey, readSwitch, uniqueName, unsafeMarkup,
50
+ checkIslandProp, directiveValue, islandOptions, renderFunctionChild, hostSpreadArgument,
51
+ } from './common.js';
52
+ import { buildWhenCondition, isPotentiallyReactive } from './reactivity.js';
53
+ import { findMappedJsx, isKeyedRow, islandKey, keyIndex, listSlot, liveKey, markRowItemReads, readsRowItem, rowField } from './lists.js';
54
+ import { enterJsxRoot } from './jsx-root.js';
55
+ import { componentMetadata } from './dev-metadata.js';
56
+
57
+ const RUNTIME_ATTRS = new Set(['classList', 'innerHTML', 'dangerouslySetInnerHTML']);
58
+
59
+ export function initSsrState(state) {
60
+ state.ssrTemplates = [];
61
+ state.ssrTemplateMap = new Map();
62
+ }
63
+
64
+ function call(state, name, args) {
65
+ return t.callExpression(helper(state, name), args);
66
+ }
67
+
68
+ function thunk(expr) {
69
+ return t.arrowFunctionExpression([], expr);
70
+ }
71
+
72
+ // A plain reference (`label`, `props.children`, `a.b.c`): h() is handed the
73
+ // value itself, whatever it holds.
74
+ function isReference(expr) {
75
+ let node = expr;
76
+ while (t.isMemberExpression(node) && !node.computed) node = node.object;
77
+ return t.isIdentifier(node) || t.isThisExpression(node);
78
+ }
79
+
80
+ // What h() gets from the DOM back end's auto-thunk: a reactive expression
81
+ // that is not a plain reference, or one that reads a keyed row's item, which
82
+ // the DOM back end binds (lists.js markRowItemReads).
83
+ function isReactive(expr, state) {
84
+ return readsRowItem(expr) || (!isReference(expr) && isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers));
85
+ }
86
+
87
+ // The value h() would be handed: the expression, or its thunk when reactive.
88
+ function asH(expr, state) {
89
+ return isReactive(expr, state) ? thunk(expr) : expr;
90
+ }
91
+
92
+ // --- Markup builder ----------------------------------------------------------
93
+
94
+ // Static strings and the holes between them; strings.length === holes.length + 1.
95
+ // `foreign` records an SVG or MathML element, which decides how what the
96
+ // markup defers is placed (ssr-runtime's ssrForeign).
97
+ // `slots` declares each hole: null for a child, [kind, name] for an
98
+ // attribute, and [kind, name, index] for a row's hoisted attribute, whose
99
+ // hole is the row's item (ssr-runtime's ssrTemplate).
100
+ // `row` is set on a `.map()` row's template: what its reactive attributes are
101
+ // hoisted with (rowAttributes). A template that hoists one is filled with its
102
+ // list's row functions before its holes.
103
+ /** @returns {{ strings: string[], holes: any[], slots: Array<any[] | null>, foreign: boolean, row: any }} */
104
+ function createMarkup(foreign = false) {
105
+ return { strings: [''], holes: [], slots: [], foreign, row: null };
106
+ }
107
+
108
+ function addText(markup, text) {
109
+ markup.strings[markup.strings.length - 1] += text;
110
+ }
111
+
112
+ /** @param {any[] | null} [slot] */
113
+ function addHole(markup, expr, slot = null) {
114
+ markup.holes.push(expr);
115
+ markup.slots.push(slot);
116
+ markup.strings.push('');
117
+ }
118
+
119
+ /** @param {Array<any[] | null>} [slots] */
120
+ function templateId(state, strings, isStatic, slots = []) {
121
+ const key = (isStatic ? 'static:' : '') + JSON.stringify([strings, slots]);
122
+ let id = state.ssrTemplateMap.get(key);
123
+ if (id === undefined) {
124
+ id = uniqueName(state, '_tmpl$');
125
+ state.ssrTemplateMap.set(key, id);
126
+ state.ssrTemplates.push({ id, strings, isStatic, slots });
127
+ }
128
+ return id;
129
+ }
130
+
131
+ // The expression that produces the markup: a module-level Markup when it has
132
+ // no holes (it is the same every time), the hole itself when it is all there
133
+ // is and already markup (a run-time element), else a call that fills a
134
+ // hoisted template. A `.map()` row is written straight into its list
135
+ // (ssr-runtime's ssrRow).
136
+ function markupExpression(markup, state, row = false) {
137
+ if (markup.holes.length === 0) return t.identifier(templateId(state, markup.strings, true));
138
+ if (markup.holes.length === 1 && markup.strings[0] === '' && markup.strings[1] === '' && markup.holes[0]._whatHtml) {
139
+ return markup.holes[0];
140
+ }
141
+ const fill = markup.foreign ? '_$ssrForeign' : row ? '_$ssrRow' : '_$ssr';
142
+ const slots = markup.slots.some(Boolean) ? markup.slots : [];
143
+ // The list's row functions, which the row's callback takes (rowAttributes).
144
+ const fns = markup.row !== null && markup.row.fns.length > 0 ? [t.identifier(markup.row.param)] : [];
145
+ return call(state, fill, [t.identifier(templateId(state, markup.strings, false, slots)), ...fns, ...markup.holes]);
146
+ }
147
+
148
+ // --- Roots -------------------------------------------------------------------
149
+
150
+ export function transformSsrRoot(path, state) {
151
+ enterJsxRoot(path, state);
152
+ path.replaceWith(jsxValue(path.node, path, state));
153
+ }
154
+
155
+ // Any JSX as a value: Markup for an element, a vnode for a component or a
156
+ // fragment, a reactive child for control flow.
157
+ function jsxValue(node, path, state) {
158
+ if (t.isJSXFragment(node)) return fragmentValue(node, state);
159
+ // What's control flow, under the name the file imported it as
160
+ // (common.js controlFlowTag), as the DOM back end dispatches it.
161
+ const flow = controlFlowTag(node, state);
162
+ if (flow === 'For') return forValue(node, path, state);
163
+ if (flow === 'Show') return showValue(node, path, state);
164
+ if (flow === 'Switch') {
165
+ const value = switchValue(node, path, state);
166
+ if (value) return value;
167
+ }
168
+ if (isComponentElement(node)) return componentValue(node, state);
169
+ const markup = createMarkup();
170
+ if (node._whatRowList) markup.row = rowAttributes(node, path, state);
171
+ appendElement(node, markup, state);
172
+ const value = markupExpression(markup, state, node._whatRow === true);
173
+ if (markup.row !== null) passRowAttributes(markup.row);
174
+ // A key outside a list that can change: the function child the DOM target
175
+ // builds the element in (lists.js liveKey), as for a component.
176
+ return liveKey(node, state) !== null ? thunk(value) : value;
177
+ }
178
+
179
+ // --- A row's reactive attributes ---------------------------------------------
180
+ //
181
+ // `{rows.map(row => <tr class={sel() === row.id ? 'on' : ''}>…</tr>)}`: the
182
+ // class is a reactive attribute, which h() is handed as a thunk made for each
183
+ // row. The server calls it once, where the row is placed, so the row's
184
+ // template takes it as a function of the row's item instead, written once
185
+ // beside the list:
186
+ //
187
+ // _$ssrList(rows, (_f$0, row) => _$ssrRow(_tmpl$, _f$0, row, …), true, row => row.id, 12,
188
+ // [row => sel() === row.id ? 'on' : ''])
189
+ //
190
+ // with the slot declared ['class', 'class', 0]. The list calls the row's
191
+ // callback with its functions before the item (what-server's ssrList), and
192
+ // the row hands them to its template before its holes, so a row takes them
193
+ // from the call that renders it, whenever that call is made, and nothing is
194
+ // kept between calls. The row passes its item as the hole, and what-server
195
+ // calls the list's function 0 with it when it places the row: the same
196
+ // expression runs at the same point with the same item, and no closure is
197
+ // made per row.
198
+ //
199
+ // An attribute is hoisted only where that holds by construction, and stays the
200
+ // thunk of its row everywhere else:
201
+ // - the row is the whole result of an arrow function (not async) that is
202
+ // the callback argument of its list's call, where the functions go;
203
+ // - the arrow's first parameter is a plain name that nothing assigns, so
204
+ // the item the row passes is the item the thunk would have read;
205
+ // - the callback holds no `eval`, which could assign that name unseen;
206
+ // - the expression names nothing else the callback binds (its index, its
207
+ // array, a destructured or defaulted parameter), in any position: a read,
208
+ // an assignment, a property of the same name. A name that does not occur
209
+ // cannot be reached, and one that does is not worth telling apart;
210
+ // - the expression holds no `this`, `super`, `arguments`, `eval`,
211
+ // `new.target`, `await` or `yield`.
212
+ // A function and its parameter are added through Babel's own path methods,
213
+ // which queue them: every plugin of the build visits the function, so JSX
214
+ // inside it is lowered as JSX anywhere else is.
215
+
216
+ const NOT_HOISTED = new Set(['ThisExpression', 'Super', 'AwaitExpression', 'YieldExpression', 'MetaProperty']);
217
+ const NOT_HOISTED_NAMES = new Set(['arguments', 'eval']);
218
+
219
+ // Whether `node` holds a node `test` accepts, at any depth.
220
+ function holds(node, test) {
221
+ if (!node || typeof node !== 'object') return false;
222
+ if (Array.isArray(node)) return node.some((child) => holds(child, test));
223
+ if (typeof node.type !== 'string') return false;
224
+ if (test(node)) return true;
225
+ for (const field of t.VISITOR_KEYS[node.type] || []) {
226
+ if (holds(node[field], test)) return true;
227
+ }
228
+ return false;
229
+ }
230
+
231
+ function isNamed(node) {
232
+ return node.type === 'Identifier' || node.type === 'JSXIdentifier';
233
+ }
234
+
235
+ // What a row's template (`node`, at `path`) hoists its reactive attributes
236
+ // with: where its list's call and its callback stand, its item's name, the
237
+ // attribute expressions that can be hoisted, and those that are (`fns`, which
238
+ // the callback takes as `param`). Null when none can.
239
+ function rowAttributes(node, path, state) {
240
+ const { call: listCall, mapFn } = node._whatRowList;
241
+ const item = mapFn.params[0];
242
+ if (!path || typeof path.traverse !== 'function' || !path.scope || path.scope.block !== mapFn) return null;
243
+ // The callback where ssrListOf wrote it: its list's call takes the functions.
244
+ const fnPath = path.parentPath;
245
+ if (!fnPath || fnPath.node !== mapFn || mapFn.body !== node || fnPath.listKey !== 'arguments') return null;
246
+ const listPath = fnPath.parentPath;
247
+ if (!listPath || listPath.node !== listCall || listCall.arguments[1] !== mapFn) return null;
248
+ const binding = path.scope.getOwnBinding(item.name);
249
+ if (!binding || binding.identifier !== item || !binding.constant) return null;
250
+ if (holds(mapFn, (inner) => inner.type === 'Identifier' && inner.name === 'eval')) return null;
251
+ // Every other name the callback binds: its parameters', and what its scope
252
+ // holds.
253
+ const bound = new Set([...Object.keys(t.getBindingIdentifiers(mapFn.params)), ...Object.keys(path.scope.bindings)]);
254
+ bound.delete(item.name);
255
+ const unsafe = (inner) => NOT_HOISTED.has(inner.type) || (isNamed(inner) && (bound.has(inner.name) || NOT_HOISTED_NAMES.has(inner.name)));
256
+ const hoistable = new Set();
257
+ // The attributes written in the callback itself: those of JSX inside a
258
+ // function inside the row belong to that JSX.
259
+ path.traverse({
260
+ Function(inner) {
261
+ inner.skip();
262
+ },
263
+ JSXAttribute(attr) {
264
+ const value = attr.node.value;
265
+ if (t.isJSXExpressionContainer(value) && !holds(value.expression, unsafe)) hoistable.add(value.expression);
266
+ },
267
+ });
268
+ if (hoistable.size === 0) return null;
269
+ return { fnPath, listPath, item: item.name, hoistable, fns: [], param: null, state };
270
+ }
271
+
272
+ // The index of `expr` among its list's row functions, which the callback is
273
+ // called with.
274
+ function hoistRowAttribute(row, expr) {
275
+ if (row.param === null) row.param = uniqueName(row.state, '_f$');
276
+ row.fns.push(t.arrowFunctionExpression([t.identifier(row.item)], expr));
277
+ return row.fns.length - 1;
278
+ }
279
+
280
+ // Once the row's template is written: the functions it hoisted as the last
281
+ // argument of its list's call, and the parameter its callback takes them in,
282
+ // before the item.
283
+ function passRowAttributes(row) {
284
+ if (row.fns.length === 0) return;
285
+ const { fnPath, listPath } = row;
286
+ const [param] = fnPath.unshiftContainer('params', t.identifier(row.param));
287
+ fnPath.scope.registerBinding('param', param);
288
+ // (list, fn, asArray, keyFn, slot, rowFns): an unkeyed list has no key
289
+ // function and no number.
290
+ const args = [];
291
+ const count = listPath.node.arguments.length;
292
+ if (count < 4) args.push(t.nullLiteral());
293
+ if (count < 5) args.push(t.unaryExpression('void', t.numericLiteral(0)));
294
+ args.push(t.arrayExpression(row.fns));
295
+ listPath.pushContainer('arguments', args);
296
+ }
297
+
298
+ // --- Elements ----------------------------------------------------------------
299
+
300
+ function isForeignNs(node) {
301
+ return node._whatNs === 'svg' || node._whatNs === 'math';
302
+ }
303
+
304
+ function appendElement(node, markup, state) {
305
+ checkElementName(node, state);
306
+ const tag = node.openingElement.name.name;
307
+ if (!SAFE_TAG_NAME.test(tag)) {
308
+ throw unsafeMarkup(node, state, `<${tag}> is not a tag name what-server can emit.`);
309
+ }
310
+ if (isForeignNs(node)) markup.foreign = true;
311
+ // An <option> is marked by the select it is placed in (what-server's html.js
312
+ // Options), so it is decided at run time. When its text is its value, the
313
+ // renderer has to write that text as text: its children, and the elements
314
+ // inside it, are the h() children they would be handed.
315
+ const option = tag === 'option' && !isForeignNs(node);
316
+ const asText = state._whatOptionText === true || (option && !hasAttribute(node, 'value'));
317
+ const attributes = readAttributes(node, state, option || asText);
318
+ if (attributes.runtime) {
319
+ let children = t.nullLiteral();
320
+ if (node.children.length > 0 && !VOID_ELEMENTS.has(tag)) {
321
+ if (asText) {
322
+ const outer = state._whatOptionText;
323
+ state._whatOptionText = true;
324
+ try {
325
+ children = t.arrayExpression(childValues(node.children, state));
326
+ } finally {
327
+ state._whatOptionText = outer;
328
+ }
329
+ } else {
330
+ // The element's own namespace decides where its children sit.
331
+ const content = createMarkup(isForeignNs(node));
332
+ appendChildren(node, content, state);
333
+ children = markupExpression(content, state);
334
+ }
335
+ }
336
+ const element = call(state, '_$ssrElement', [t.stringLiteral(tag), attributes.props, children]);
337
+ element._whatHtml = true;
338
+ addHole(markup, element);
339
+ return;
340
+ }
341
+ addText(markup, `<${tag}`);
342
+ for (const attr of attributes.list) appendAttribute(attr, markup, state);
343
+ addText(markup, '>');
344
+ if (VOID_ELEMENTS.has(tag)) return;
345
+ // The newline the parser drops after this start tag (markup-rules.js).
346
+ if (!isForeignNs(node) && LEADING_NEWLINE_ELEMENTS.has(tag)) addText(markup, '\n');
347
+ appendChildren(node, markup, state);
348
+ addText(markup, `</${tag}>`);
349
+ }
350
+
351
+ // The value of an attribute when the source fixes it: true for a valueless
352
+ // attribute, else a string, number, boolean or null literal (or a template
353
+ // literal with no expressions). Undefined when it is only known at run time.
354
+ function staticValue(attr) {
355
+ if (!attr.value) return true;
356
+ if (t.isStringLiteral(attr.value)) return attr.value.value;
357
+ const expr = t.isJSXExpressionContainer(attr.value) ? attr.value.expression : null;
358
+ if (t.isStringLiteral(expr) || t.isNumericLiteral(expr) || t.isBooleanLiteral(expr)) return expr.value;
359
+ if (t.isNullLiteral(expr)) return null;
360
+ if (t.isTemplateLiteral(expr) && expr.expressions.length === 0) return expr.quasis[0].value.cooked;
361
+ return undefined;
362
+ }
363
+
364
+ // Whether the form field `tag` with props `names` shows a value decided at
365
+ // render time: a <textarea>'s or a <select>'s value or default (its text, its
366
+ // options' marks), an <input>'s value next to its default. An <input>'s value
367
+ // or default alone is its attribute, which a template slot writes.
368
+ function isRuntimeField(tag, names) {
369
+ if (tag !== 'input') return [...FIELD_PROPS].some((name) => names.has(name));
370
+ return (names.has('value') && names.has('defaultValue')) || (names.has('checked') && names.has('defaultChecked'));
371
+ }
372
+
373
+ // The attributes in the order the h() spelling's props object holds them: a
374
+ // name written twice keeps its first position and its last value. Events,
375
+ // refs and keys are not markup. A spread, a classList or innerHTML make the
376
+ // whole element a run-time element whose props object is built exactly as
377
+ // h() would build it; so does a form field whose value and default share
378
+ // the markup (isRuntimeField): which one it shows is decided where the values
379
+ // are known (what-server's _field), by the rule every server renderer applies.
380
+ /** @returns {{ runtime: boolean, props: any, list: any[] }} */
381
+ function readAttributes(node, state, force = false) {
382
+ const attrs = node.openingElement.attributes;
383
+ const nameNode = node.openingElement.name;
384
+ const field = t.isJSXIdentifier(nameNode) && FIELD_TAGS.has(nameNode.name);
385
+ const entries = [];
386
+ let runtime = force;
387
+ for (const attr of attrs) {
388
+ if (t.isJSXSpreadAttribute(attr)) {
389
+ runtime = true;
390
+ entries.push({ spread: hostSpreadArgument(attr) });
391
+ continue;
392
+ }
393
+ let name = getAttrName(attr);
394
+ if (name === 'key' || name === 'ref' || name === 'children' || isEventAttrName(name)) continue;
395
+ let expr = null;
396
+ if (isBindingAttribute(name)) {
397
+ const prop = getBindingProperty(name);
398
+ if (prop !== 'value' && prop !== 'checked') continue;
399
+ name = prop;
400
+ expr = t.callExpression(t.cloneNode(attr.value.expression), []);
401
+ }
402
+ if (RUNTIME_ATTRS.has(name)) runtime = true;
403
+ const key = markupName(name);
404
+ if (!SAFE_ATTR_NAME.test(key)) {
405
+ throw unsafeMarkup(attr, state, `"${key}" is not an attribute name what-server can emit.`);
406
+ }
407
+ const fixed = expr ? undefined : staticValue(attr);
408
+ checkStaticAttribute(attr, key, name, fixed, state);
409
+ entries.push({ name, key, attr, fixed, expr: expr || (fixed === undefined ? getAttributeValue(attr.value) : null) });
410
+ }
411
+
412
+ if (field && !runtime) runtime = isRuntimeField(nameNode.name, new Set(entries.map((e) => e.name)));
413
+ if (runtime) {
414
+ const properties = entries.map(e => (e.spread
415
+ ? t.spreadElement(e.spread)
416
+ : t.objectProperty(propKey(e.name), e.fixed !== undefined ? literal(e.fixed) : asH(e.expr, state))));
417
+ return { runtime: true, props: t.objectExpression(properties), list: [] };
418
+ }
419
+
420
+ const byName = new Map();
421
+ for (const entry of entries) {
422
+ const first = byName.get(entry.name);
423
+ if (first) Object.assign(first, { fixed: entry.fixed, expr: entry.expr, attr: entry.attr });
424
+ else byName.set(entry.name, entry);
425
+ }
426
+ return { runtime: false, props: null, list: [...byName.values()] };
427
+ }
428
+
429
+ // Whether the element names attribute `name` itself (not through a spread).
430
+ function hasAttribute(node, name) {
431
+ return node.openingElement.attributes.some((attr) => t.isJSXAttribute(attr) && getAttrName(attr) === name);
432
+ }
433
+
434
+ function literal(value) {
435
+ if (value === true || value === false) return t.booleanLiteral(value);
436
+ if (value === null) return t.nullLiteral();
437
+ if (typeof value === 'number') return t.numericLiteral(value);
438
+ return t.stringLiteral(value);
439
+ }
440
+
441
+ function kindOf(key) {
442
+ if (isRefusedAttr(key)) return 'refused';
443
+ if (key === 'class') return 'class';
444
+ if (key === 'style') return 'style';
445
+ if (isEnumeratedAttr(key)) return 'enum';
446
+ if (isUrlAttr(key)) return 'url';
447
+ return 'plain';
448
+ }
449
+
450
+ // One attribute, as what-server's renderAttrs writes it.
451
+ function appendAttribute({ key, fixed, expr }, markup, state) {
452
+ const kind = kindOf(key);
453
+ if (fixed === undefined) {
454
+ const row = markup.row;
455
+ if (row !== null && row.hoistable.has(expr) && isReactive(expr, state)) {
456
+ addHole(markup, t.identifier(row.item), [kind, key, hoistRowAttribute(row, expr)]);
457
+ return;
458
+ }
459
+ addHole(markup, asH(expr, state), [kind, key]);
460
+ return;
461
+ }
462
+ if (fixed === null || kind === 'refused') return;
463
+ if (fixed === false) {
464
+ if (kind === 'enum') addText(markup, ` ${key}="false"`);
465
+ return;
466
+ }
467
+ if (fixed === true && kind !== 'class' && kind !== 'enum') {
468
+ addText(markup, ` ${key}`);
469
+ return;
470
+ }
471
+ addText(markup, ` ${key}="${escapeHtml(String(fixed))}"`);
472
+ }
473
+
474
+ // --- Children ------------------------------------------------------------------
475
+
476
+ function appendChildren(node, markup, state) {
477
+ const tag = node.openingElement.name.name;
478
+ if (RAW_TEXT_ELEMENTS.has(tag) || (TEXT_ONLY_ELEMENTS.has(tag) && !isForeignNs(node))) {
479
+ appendRawText(node, tag, markup, state);
480
+ return;
481
+ }
482
+ appendChildList(node.children, markup, state);
483
+ }
484
+
485
+ // An element's children; a fragment among them is its children, in its place,
486
+ // as the DOM target lays them out (dom.js layoutChildren).
487
+ function appendChildList(children, markup, state) {
488
+ for (const child of children) {
489
+ if (t.isJSXText(child)) {
490
+ const text = normalizeJsxText(child.value);
491
+ if (text) addText(markup, escapeHtml(text));
492
+ } else if (t.isJSXExpressionContainer(child)) {
493
+ const expr = child.expression;
494
+ if (t.isJSXEmptyExpression(expr)) continue;
495
+ if (t.isStringLiteral(expr) || t.isNumericLiteral(expr)) {
496
+ addText(markup, escapeHtml(String(expr.value)));
497
+ continue;
498
+ }
499
+ addHole(markup, childHole(expr, state));
500
+ } else if (t.isJSXElement(child) && !isComponentElement(child) && liveKey(child, state) === null) {
501
+ appendElement(child, markup, state);
502
+ } else if (t.isJSXFragment(child)) {
503
+ appendChildList(child.children, markup, state);
504
+ } else if (t.isJSXElement(child)) {
505
+ addHole(markup, jsxValue(child, { node: child }, state));
506
+ }
507
+ }
508
+ }
509
+
510
+ // The children of a <script> or <style>: text written as it is. Static text
511
+ // that reads the same in every namespace goes into the template; anything else
512
+ // (an expression, text holding `&` or `<`) makes one hole for all of them,
513
+ // because the encoding that keeps the element from ending applies to the text
514
+ // as a whole, and whether the element holds raw text at all depends on the
515
+ // namespace it is placed in (ssr-runtime's ssrRawText). The children of a
516
+ // <textarea> or <title> in HTML are text too: escaped, and with no hydration
517
+ // markers, which the parser would read as text.
518
+ function appendRawText(node, tag, markup, state) {
519
+ const textOnly = !RAW_TEXT_ELEMENTS.has(tag);
520
+ const pieces = [];
521
+ let fixed = true;
522
+ for (const child of node.children) {
523
+ /** @type {string | null | undefined} */
524
+ let text;
525
+ if (t.isJSXText(child)) text = normalizeJsxText(child.value);
526
+ else if (t.isJSXExpressionContainer(child)) {
527
+ const expr = child.expression;
528
+ if (t.isJSXEmptyExpression(expr)) continue;
529
+ if (t.isStringLiteral(expr) || t.isNumericLiteral(expr)) text = String(expr.value);
530
+ else if (t.isTemplateLiteral(expr) && expr.expressions.length === 0) text = expr.quasis[0].value.cooked;
531
+ else {
532
+ fixed = false;
533
+ pieces.push(asH(expr, state));
534
+ continue;
535
+ }
536
+ } else {
537
+ fixed = false;
538
+ pieces.push(jsxValue(child, { node: child }, state));
539
+ continue;
540
+ }
541
+ if (!text) continue;
542
+ if (!textOnly) {
543
+ checkStaticRawText(child, tag, text, state);
544
+ if (!isNamespaceNeutralText(text)) fixed = false;
545
+ }
546
+ pieces.push(t.stringLiteral(text));
547
+ }
548
+ if (pieces.length === 0) return;
549
+ if (fixed) {
550
+ for (const piece of pieces) addText(markup, textOnly ? escapeHtml(piece.value) : piece.value);
551
+ return;
552
+ }
553
+ addHole(markup, call(state, '_$ssrRawText', [t.stringLiteral(tag), t.arrayExpression(pieces)]));
554
+ }
555
+
556
+ function childHole(expr, state) {
557
+ const list = listHole(expr, state);
558
+ if (list) return list;
559
+ // A plain field of a keyed row's item is a text binding on the client
560
+ // (lists.js rowField): written as text, with no markers.
561
+ if (rowField(expr) !== null) return call(state, '_$ssrText', [expr]);
562
+ return isReactive(expr, state) ? thunk(expr) : call(state, '_$ssrText', [expr]);
563
+ }
564
+
565
+ // `{src.map(item => <li/>)}`: the rows rendered into one hole. A plain call
566
+ // is read now and its rows flattened into the parent, as h() flattens an
567
+ // array child; written as a reactive child (`{src().map(...)}`,
568
+ // `{() => src.map(...)}`, or a list of a keyed row's item, `{row.children.map(...)}`,
569
+ // which the DOM target reads through the row's item cell) it is the thunk,
570
+ // and its rows are a list, as they are inside the content a control-flow arm
571
+ // returns (`inArray`). The call may stand where the DOM target finds it
572
+ // (dom.js tryLowerMapToMapArray): in either arm of a ternary, or on the right
573
+ // of `&&` or `||`.
574
+ function listHole(expr, state, inArray = false) {
575
+ let body = expr;
576
+ let reactive;
577
+ if (t.isArrowFunctionExpression(expr) && expr.params.length === 0 && t.isExpression(expr.body)) {
578
+ body = expr.body;
579
+ reactive = true;
580
+ } else {
581
+ reactive = isReactive(expr, state);
582
+ }
583
+ const asArray = reactive || inArray;
584
+ let list;
585
+ if (t.isConditionalExpression(body)) {
586
+ const consequent = ssrListOf(body.consequent, state, asArray);
587
+ const alternate = ssrListOf(body.alternate, state, asArray);
588
+ list = consequent || alternate ? t.conditionalExpression(body.test, consequent || body.consequent, alternate || body.alternate) : null;
589
+ } else if (t.isLogicalExpression(body) && (body.operator === '&&' || body.operator === '||')) {
590
+ const right = ssrListOf(body.right, state, asArray);
591
+ list = right && t.logicalExpression(body.operator, body.left, right);
592
+ } else {
593
+ list = ssrListOf(body, state, asArray);
594
+ }
595
+ if (!list) return null;
596
+ return reactive ? thunk(list) : list;
597
+ }
598
+
599
+ // `src.map(fn)` (or `src?.map(fn)`) as the _$ssrList that renders its rows,
600
+ // or null for anything else.
601
+ function ssrListOf(mapCall, state, asArray) {
602
+ const found = findMappedJsx(mapCall, state, false);
603
+ if (!found) return null;
604
+ const keyed = isKeyedRow(found);
605
+ if (keyed) markRowItemReads(found.mapFn, found.keyValue);
606
+ // A row that is the callback's whole result goes straight into the list.
607
+ if (found.mapFn.body === found.returnExpr && !isComponentElement(found.returnExpr)) found.returnExpr._whatRow = true;
608
+ // A keyed list is the DOM target's keyed list wherever it stands (dom.js
609
+ // tryLowerMapToMapArray), which hydrates between its own markers: it is
610
+ // bracketed as an array even where a plain child's rows are flattened.
611
+ const args = [mapCall.callee.object, found.mapFn, t.booleanLiteral(asArray || keyed)];
612
+ // The key function the DOM target's list keys its rows with (dom.js
613
+ // tryLowerMapCall), for the keys the hydratable markup carries, and the
614
+ // list's number, the DOM target's too (lists.js listSlot).
615
+ if (keyed) {
616
+ const item = found.mapFn.params[0] ? t.cloneNode(found.mapFn.params[0], true) : t.identifier('_item');
617
+ // A key that reads the index takes it too (lists.js keyIndex); ssrList
618
+ // hands every key function the item's index.
619
+ const index = keyIndex(found);
620
+ args.push(t.arrowFunctionExpression(index === null ? [item] : [item, t.identifier(index)], t.cloneNode(found.keyValue, true)));
621
+ const slot = listSlot(mapCall);
622
+ if (slot !== null) args.push(slot);
623
+ }
624
+ const list = call(state, '_$ssrList', args);
625
+ // A row written straight into the list by an arrow function of a plainly
626
+ // named item, the callback argument of this call: its reactive attributes
627
+ // can be the list's (rowAttributes).
628
+ if (found.returnExpr._whatRow === true && t.isArrowFunctionExpression(found.mapFn) && !found.mapFn.async && t.isIdentifier(found.mapFn.params[0])) {
629
+ found.returnExpr._whatRowList = { call: list, mapFn: found.mapFn };
630
+ }
631
+ return list;
632
+ }
633
+
634
+ // The children of a component, a fragment or a control-flow arm, as the
635
+ // values h() would be handed: text, the expression (or its thunk when it is
636
+ // reactive), Markup per element, a vnode per component. A component's and a
637
+ // fragment's children are h()'s arguments, which it flattens; an arm's are
638
+ // the content its thunk returns (`inArray`), which it does not.
639
+ function childValues(children, state, inArray = false) {
640
+ const values = [];
641
+ for (const child of children) {
642
+ if (t.isJSXText(child)) {
643
+ const text = normalizeJsxText(child.value);
644
+ if (text) values.push(t.stringLiteral(text));
645
+ } else if (t.isJSXExpressionContainer(child)) {
646
+ const expr = child.expression;
647
+ if (t.isJSXEmptyExpression(expr)) continue;
648
+ values.push(listHole(expr, state, inArray) || asH(expr, state));
649
+ } else if (t.isJSXElement(child) || t.isJSXFragment(child)) {
650
+ values.push(jsxValue(child, { node: child }, state));
651
+ }
652
+ }
653
+ return values;
654
+ }
655
+
656
+ function fragmentValue(node, state) {
657
+ return call(state, '_$ssrFragment', [t.arrayExpression(childValues(node.children, state))]);
658
+ }
659
+
660
+ // --- Components ------------------------------------------------------------------
661
+
662
+ function componentValue(node, state) {
663
+ const opening = node.openingElement;
664
+ /** @type {{ mode: string, mediaQuery: any } | null} */
665
+ let directive = null;
666
+ for (const attr of opening.attributes) {
667
+ if (t.isJSXAttribute(attr) && getAttrName(attr).startsWith('client:')) {
668
+ directive = { mode: getAttrName(attr).slice(7), mediaQuery: directiveValue(attr) };
669
+ }
670
+ }
671
+ const properties = [];
672
+ for (const attr of opening.attributes) {
673
+ if (t.isJSXSpreadAttribute(attr)) {
674
+ if (directive && t.isObjectExpression(attr.argument)) {
675
+ for (const prop of attr.argument.properties) {
676
+ if (t.isObjectProperty(prop)) checkIslandProp(t.isIdentifier(prop.key) ? prop.key.name : String(prop.key.value), prop.value, node, state);
677
+ }
678
+ }
679
+ properties.push(t.spreadElement(attr.argument));
680
+ continue;
681
+ }
682
+ const name = getAttrName(attr);
683
+ if (name.startsWith('client:') || name === 'key') continue;
684
+ if (isBindingAttribute(name)) {
685
+ properties.push(...bindingProps(getBindingProperty(name), attr.value.expression));
686
+ continue;
687
+ }
688
+ if (name.startsWith('on') && (name.includes('|') || hasEventModifiers(name, state))) {
689
+ const { eventName, modifiers } = parseEventModifiers(name);
690
+ properties.push(t.objectProperty(t.identifier(eventName), createEventHandler(getAttributeValue(attr.value), modifiers)));
691
+ continue;
692
+ }
693
+ if (directive) checkIslandProp(name, attr.value, node, state);
694
+ properties.push(t.objectProperty(propKey(name), slotValue(node, attr, getAttributeValue(attr.value), state)));
695
+ }
696
+ const children = t.arrayExpression(childValues(node.children, state));
697
+ const meta = componentMetadata(node, state);
698
+
699
+ if (directive) {
700
+ // The props travel apart from the island's own options, as on the DOM
701
+ // target (common.js islandOptions).
702
+ const props = properties.length ? t.objectExpression(properties) : null;
703
+ const args = [islandOptions(opening.name, directive.mode, directive.mediaQuery, props), children];
704
+ if (meta) args.push(meta);
705
+ const island = call(state, '_$ssrIsland', args);
706
+ // The function child the DOM target builds an island with a key that can
707
+ // change in (lists.js islandKey).
708
+ return islandKey(node, directive.mode, state) !== null ? thunk(island) : island;
709
+ }
710
+
711
+ // No children and no spread: the props literal is the call's own object
712
+ // and holds no `key` (skipped above), so ssrLeaf hands it over uncopied.
713
+ const leaf = children.elements.length === 0 && properties.every((prop) => t.isObjectProperty(prop));
714
+ const args = [componentCallee(opening.name), properties.length ? t.objectExpression(properties) : t.nullLiteral()];
715
+ if (!leaf) args.push(children);
716
+ // The number of the JSX, the DOM target's too (lists.js listSlot): the
717
+ // component's place among the keyed rows (what-core hydration-data.js).
718
+ const site = listSlot(node);
719
+ if (site !== null || meta) args.push(site ?? t.unaryExpression('void', t.numericLiteral(0)));
720
+ if (meta) args.push(meta);
721
+ const component = call(state, leaf ? '_$ssrLeaf' : '_$ssrComponent', args);
722
+ // A key outside a list that can change: the function child the DOM target
723
+ // builds it in (lists.js liveKey), which a hydratable render brackets.
724
+ return liveKey(node, state) !== null ? thunk(component) : component;
725
+ }
726
+
727
+ // A ternary with a reactive test handed to a component as JSX
728
+ // (`header={b() ? <X /> : <Y />}`): a function child, as the DOM back end
729
+ // hands it (dom.js slotFactory), so the component places a region the
730
+ // hydratable renderers bracket and hydration adopts the client's.
731
+ function slotValue(node, attr, value, state) {
732
+ if (!t.isConditionalExpression(value) || !isSlotAttribute(node, attr, state) || !everyArmIsJsx(value)) return value;
733
+ const tests = [];
734
+ const leaves = [];
735
+ (function walk(e) {
736
+ if (t.isConditionalExpression(e)) {
737
+ tests.push(e.test);
738
+ walk(e.consequent);
739
+ walk(e.alternate);
740
+ } else leaves.push(e);
741
+ })(value);
742
+ if (!tests.some((test) => isPotentiallyReactive(test, state.signalNames, state.importedIdentifiers))) return value;
743
+ return t.arrowFunctionExpression([], value);
744
+ }
745
+
746
+ function everyArmIsJsx(expr) {
747
+ if (t.isConditionalExpression(expr)) return everyArmIsJsx(expr.consequent) && everyArmIsJsx(expr.alternate);
748
+ return t.isJSXElement(expr) || t.isJSXFragment(expr);
749
+ }
750
+
751
+ // bind:value / bind:checked on a component: the value and its change handler,
752
+ // as the DOM back end passes them.
753
+ function bindingProps(prop, signalExpr) {
754
+ const target = (field) => t.memberExpression(t.memberExpression(t.identifier('e'), t.identifier('target')), t.identifier(field));
755
+ const setter = (field) => t.arrowFunctionExpression([t.identifier('e')],
756
+ t.callExpression(t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')), [target(field)]));
757
+ if (prop === 'value') {
758
+ return [
759
+ t.objectProperty(t.identifier('value'), t.callExpression(t.cloneNode(signalExpr), [])),
760
+ t.objectProperty(t.identifier('onInput'), setter('value')),
761
+ ];
762
+ }
763
+ if (prop === 'checked') {
764
+ return [
765
+ t.objectProperty(t.identifier('checked'), t.callExpression(t.cloneNode(signalExpr), [])),
766
+ t.objectProperty(t.identifier('onChange'), setter('checked')),
767
+ ];
768
+ }
769
+ return [];
770
+ }
771
+
772
+ // --- Control flow ----------------------------------------------------------------
773
+ //
774
+ // The same reactive children the DOM back end lowers <Show>, <Switch> and
775
+ // <For> to, minus the memos: a server render evaluates each one once.
776
+
777
+ function attributeOf(node, name) {
778
+ for (const attr of node.openingElement.attributes) {
779
+ if (t.isJSXAttribute(attr) && getAttrName(attr) === name) return getAttributeValue(attr.value);
780
+ }
781
+ return null;
782
+ }
783
+
784
+ function contentOf(values) {
785
+ return values.length === 0 ? t.nullLiteral() : values.length === 1 ? values[0] : t.arrayExpression(values);
786
+ }
787
+
788
+ function showValue(node, path, state) {
789
+ const when = attributeOf(node, 'when');
790
+ if (!when) {
791
+ throw compileError(path, state, '<Show> requires a "when" prop. Example: <Show when={isOpen} fallback={null}>...</Show>');
792
+ }
793
+ const fallback = attributeOf(node, 'fallback') || t.nullLiteral();
794
+ const renderFn = renderFunctionChild(node.children);
795
+ const v = t.identifier(uniqueName(state, '_v$'));
796
+ const content = renderFn
797
+ ? t.callExpression(renderFn, [t.cloneNode(v)])
798
+ : contentOf(childValues(node.children, state, true));
799
+ return thunk(t.blockStatement([
800
+ t.variableDeclaration('const', [t.variableDeclarator(v, buildWhenCondition(when, state))]),
801
+ t.returnStatement(t.conditionalExpression(t.cloneNode(v), content, fallback)),
802
+ ]));
803
+ }
804
+
805
+ function switchValue(node, path, state) {
806
+ const read = readSwitch(path, state);
807
+ if (read === null) return null;
808
+ let expr = read.fallback || t.nullLiteral();
809
+ for (let i = read.arms.length - 1; i >= 0; i--) {
810
+ expr = t.conditionalExpression(buildWhenCondition(read.arms[i].when, state), contentOf(childValues(read.arms[i].children, state, true)), expr);
811
+ }
812
+ return thunk(expr);
813
+ }
814
+
815
+ function forValue(node, path, state) {
816
+ const each = attributeOf(node, 'each');
817
+ const key = attributeOf(node, 'key');
818
+ const fallback = attributeOf(node, 'fallback');
819
+ const renderFn = node.children.find(c => t.isJSXExpressionContainer(c) && !t.isJSXEmptyExpression(c.expression));
820
+ if (!each || !renderFn) {
821
+ throw compileError(path, state, '<For> needs an "each" prop and a render function child: <For each={items}>{(item) => <li>{item}</li>}</For>');
822
+ }
823
+ const args = [each, renderFn.expression, key || t.booleanLiteral(false), fallback || t.nullLiteral()];
824
+ const slot = key ? listSlot(node) : null;
825
+ if (slot !== null) args.push(slot);
826
+ return call(state, '_$ssrFor', args);
827
+ }
828
+
829
+ // --- Program teardown ------------------------------------------------------------
830
+
831
+ // The runtime helpers compiled server output imports, in specifier order.
832
+ const SSR_IMPORTS = [
833
+ ['_$ssr', 'ssr'],
834
+ ['_$ssrForeign', 'ssrForeign'],
835
+ ['_$ssrRow', 'ssrRow'],
836
+ ['_$ssrText', 'ssrText'],
837
+ ['_$ssrList', 'ssrList'],
838
+ ['_$ssrFor', 'ssrFor'],
839
+ ['_$ssrTemplate', 'ssrTemplate'],
840
+ ['_$ssrElement', 'ssrElement'],
841
+ ['_$ssrRawText', 'ssrRawText'],
842
+ ['_$ssrComponent', 'ssrComponent'],
843
+ ['_$ssrLeaf', 'ssrLeaf'],
844
+ ['_$ssrFragment', 'ssrFragment'],
845
+ ['_$ssrIsland', 'ssrIsland'],
846
+ ];
847
+
848
+ export function finishSsrProgram(path, state) {
849
+ for (const tmpl of state.ssrTemplates.reverse()) {
850
+ const strings = t.arrayExpression(tmpl.strings.map(s => t.stringLiteral(s)));
851
+ // A static element is one Markup for the whole module: it never changes.
852
+ // A template with attribute holes declares their kinds and names.
853
+ let init = strings;
854
+ if (tmpl.isStatic) init = call(state, '_$ssr', [strings]);
855
+ else if (tmpl.slots.length > 0) {
856
+ init = call(state, '_$ssrTemplate', [strings, t.arrayExpression(tmpl.slots.map(slot => (slot === null
857
+ ? t.nullLiteral()
858
+ : t.arrayExpression(slot.map(part => (typeof part === 'number' ? t.numericLiteral(part) : t.stringLiteral(part)))))))]);
859
+ }
860
+ if (init !== strings) t.addComment(init, 'leading', ' @__PURE__ ');
861
+ path.unshiftContainer('body', t.variableDeclaration('const', [t.variableDeclarator(t.identifier(tmpl.id), init)]));
862
+ }
863
+ const used = helperLocals(state);
864
+ const specifiers = [];
865
+ for (const [name, exported] of SSR_IMPORTS) {
866
+ const local = used.get(name);
867
+ if (local !== undefined) specifiers.push(t.importSpecifier(t.identifier(local), t.identifier(exported)));
868
+ }
869
+ addImports(path, specifiers, ['what-framework/ssr-runtime'], 'what-framework/ssr-runtime');
870
+ }