@tsrx/vue 0.4.5 → 0.4.7

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 (2) hide show
  1. package/package.json +2 -2
  2. package/src/transform.js +704 -33
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Vue compiler built on @tsrx/core",
4
4
  "license": "MIT",
5
5
  "author": "Dominic Gannaway",
6
- "version": "0.4.5",
6
+ "version": "0.4.7",
7
7
  "type": "module",
8
8
  "publishConfig": {
9
9
  "access": "public"
@@ -42,7 +42,7 @@
42
42
  "esrap": "^2.4.2",
43
43
  "is-reference": "^3.0.3",
44
44
  "zimmerframe": "^1.1.2",
45
- "@tsrx/core": "0.6.5",
45
+ "@tsrx/core": "0.6.7",
46
46
  "@tsrx/vue-runtime": "0.2.3"
47
47
  },
48
48
  "peerDependencies": {
package/src/transform.js CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  forOfPatternReadsIndex as for_of_pattern_reads_index,
22
22
  has_location,
23
23
  IDENTIFIER_OBFUSCATION_PREFIX,
24
+ ifStatementToJsxChild,
24
25
  insertAfterDirectives,
25
26
  is_component_like_element,
26
27
  isFunctionNode,
@@ -32,6 +33,7 @@ import {
32
33
  NORMALIZE_SPREAD_PROPS_INTERNAL_NAME,
33
34
  setLocation,
34
35
  SUSPENSE_INTERNAL_NAME,
36
+ switchStatementToJsxChild,
35
37
  TSRX_ERRORS,
36
38
  } from '@tsrx/core';
37
39
 
@@ -63,6 +65,27 @@ const VAPOR_FOR_INTERNAL_NAME = '__VaporFor';
63
65
  const FOR_ITEMS_INTERNAL_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'for_items';
64
66
  /** The `computed` that walks the source of a `VaporFor` loop with `@empty`. */
65
67
  const VAPOR_ITEMS_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'vapor_items';
68
+ /** The `computed` that picks the case of a `@switch` row, numbered per row. */
69
+ const SWITCH_CASE_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'case';
70
+ /** What a `@switch` row's `computed` caught. */
71
+ const SWITCH_ERROR_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'error';
72
+ /** The value a `@switch` row's `computed` held before it runs again. */
73
+ const SWITCH_PREVIOUS_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'previous';
74
+ /**
75
+ * How many `@switch` rows each compile has lowered, so a nested one's
76
+ * `computed` can't capture an outer one's name.
77
+ * @type {WeakMap<TransformContext, number>}
78
+ */
79
+ const switch_counts = new WeakMap();
80
+ /**
81
+ * The metadata flag on a `@switch`'s shared lowering, which survives the
82
+ * clones a `VaporFor` row goes through.
83
+ */
84
+ const VAPOR_SWITCH_METADATA = 'vapor_switch';
85
+ /** The metadata flag on an `@if`'s shared lowering. */
86
+ const VAPOR_IF_METADATA = 'vapor_if';
87
+ /** The most cases a `@switch` row turns into a chain of `createIf`s. */
88
+ const MAX_SWITCH_ROW_CASES = 64;
66
89
 
67
90
  const DEFINE_VAPOR_COMPONENT = 'defineVaporComponent';
68
91
 
@@ -147,6 +170,10 @@ const vue_platform = {
147
170
  },
148
171
  renderForOf: (node, loop_params, body_statements, ctx, get_empty_statements) =>
149
172
  render_for_of_as_vapor_for(node, loop_params, body_statements, ctx, get_empty_statements),
173
+ controlFlow: {
174
+ ifStatement: render_if_statement,
175
+ switchStatement: render_switch_statement,
176
+ },
150
177
  createPendingBoundary(try_content, fallback_content, ctx) {
151
178
  return create_vapor_pending_boundary(try_content, fallback_content, ctx);
152
179
  },
@@ -202,6 +229,7 @@ const vue_platform = {
202
229
  );
203
230
  },
204
231
  injectImports(program, ctx) {
232
+ if (!ctx.typeOnly) render_element_ifs_as_directives(program);
205
233
  wrap_native_function_components(program, ctx);
206
234
  inject_vue_imports(program, ctx);
207
235
  },
@@ -1486,29 +1514,6 @@ function read_children_from_default_slot(fn, name, ctx) {
1486
1514
  return fn;
1487
1515
  }
1488
1516
 
1489
- /**
1490
- * @param {AST.Node} node
1491
- * @param {import('zimmerframe').Context<AST.Node, ChildrenReadState>} context
1492
- */
1493
- const shadow_head = (node, { state, next }) => {
1494
- /** @type {AST.Node[]} */
1495
- const bindings = [];
1496
- if (node.type === 'CatchClause' && node.param) bindings.push(node.param);
1497
- const head =
1498
- node.type === 'ForStatement'
1499
- ? node.init
1500
- : node.type === 'ForInStatement' || node.type === 'ForOfStatement'
1501
- ? node.left
1502
- : null;
1503
- if (head?.type === 'VariableDeclaration') {
1504
- for (const declarator of head.declarations) bindings.push(declarator.id);
1505
- }
1506
- if (bindings.length === 0) return next();
1507
- const shadowed_names = new Set(state.shadowed_names);
1508
- for (const binding of bindings) collect_pattern_names(binding, shadowed_names);
1509
- return next({ ...state, shadowed_names });
1510
- };
1511
-
1512
1517
  const body = /** @type {AST.BlockStatement | AST.Expression} */ (
1513
1518
  walk(/** @type {AST.Node} */ (fn.body), state, {
1514
1519
  ChainExpression(node, { path, state, next }) {
@@ -1558,10 +1563,14 @@ function read_children_from_default_slot(fn, name, ctx) {
1558
1563
  FunctionDeclaration: rewrite_function_shadowed_refs,
1559
1564
  FunctionExpression: rewrite_function_shadowed_refs,
1560
1565
  ArrowFunctionExpression: rewrite_function_shadowed_refs,
1561
- CatchClause: shadow_head,
1562
- ForStatement: shadow_head,
1563
- ForInStatement: shadow_head,
1564
- ForOfStatement: shadow_head,
1566
+ CatchClause: rewrite_head_shadowed_refs,
1567
+ ForStatement: rewrite_head_shadowed_refs,
1568
+ ForInStatement: rewrite_head_shadowed_refs,
1569
+ ForOfStatement: rewrite_head_shadowed_refs,
1570
+ SwitchStatement: rewrite_switch_shadowed_refs,
1571
+ ClassExpression: rewrite_class_shadowed_refs,
1572
+ StaticBlock: rewrite_static_block_shadowed_refs,
1573
+ TSEnumDeclaration: rewrite_enum_shadowed_refs,
1565
1574
  BlockStatement(node, context) {
1566
1575
  // The component body declares the destructured `children` binding;
1567
1576
  // it cannot redeclare the props parameter or its bindings.
@@ -1870,7 +1879,10 @@ function render_for_of_as_vapor_for(
1870
1879
  (!key_expression ||
1871
1880
  suspends(node) ||
1872
1881
  destructuring_runs_code(loop_params[0]) ||
1873
- !is_vapor_for_row(rendered))
1882
+ !is_vapor_for_row(rendered) ||
1883
+ // A `@switch` row with `@empty` stays where #1378 left it, which
1884
+ // renders on the server.
1885
+ is_lowered_switch(rendered))
1874
1886
  ) {
1875
1887
  // A default in the head's pattern that reads the index can't be read in
1876
1888
  // the parameters, where the index comes second. The shared lowering
@@ -1881,7 +1893,7 @@ function render_for_of_as_vapor_for(
1881
1893
  return render_for_of_as_map_iterable(node, loop_params, rendered, transform_context);
1882
1894
  }
1883
1895
 
1884
- const row = to_vapor_for_row(rendered);
1896
+ const row = to_vapor_for_row(rendered, transform_context);
1885
1897
  const slot = key_expression
1886
1898
  ? create_keyed_vapor_for_slot(loop_params, row, transform_context)
1887
1899
  : { params: loop_params, body: row, expression: true };
@@ -1889,6 +1901,12 @@ function render_for_of_as_vapor_for(
1889
1901
  return null;
1890
1902
  }
1891
1903
 
1904
+ if (is_lowered_switch(rendered) && lowered_switch_statement(rendered).cases.length > 0) {
1905
+ // The name `switch_in_fragment` gave the row's `computed`.
1906
+ switch_counts.set(transform_context, (switch_counts.get(transform_context) ?? 0) + 1);
1907
+ transform_context.needs_vapor_computed = true;
1908
+ }
1909
+
1892
1910
  transform_context.needs_vapor_for = true;
1893
1911
  transform_context.needs_for_items = true;
1894
1912
 
@@ -2029,6 +2047,7 @@ function destructuring_runs_code(pattern) {
2029
2047
  */
2030
2048
  function is_vapor_for_row(node) {
2031
2049
  return (
2050
+ is_lowered_switch(node) ||
2032
2051
  node.type === 'JSXElement' ||
2033
2052
  node.type === 'JSXFragment' ||
2034
2053
  node.type === 'ConditionalExpression' ||
@@ -2056,12 +2075,17 @@ function yields(node) {
2056
2075
  * The row a `VaporFor` slot returns. The slot runs once per row, so a ternary
2057
2076
  * it returns would keep the branch it picked first: a row that picks a branch,
2058
2077
  * or can skip itself, is a fragment around the choice, which vue-jsx-vapor
2059
- * makes a `createIf` that follows its condition.
2078
+ * makes a `createIf` that follows its condition, and a `@switch` row is a
2079
+ * fragment around its cases (`switch_in_fragment`).
2060
2080
  *
2061
2081
  * @param {AST.Expression} node
2082
+ * @param {TransformContext} transform_context
2062
2083
  * @returns {AST.Expression}
2063
2084
  */
2064
- function to_vapor_for_row(node) {
2085
+ function to_vapor_for_row(node, transform_context) {
2086
+ if (is_lowered_switch(node)) {
2087
+ return switch_in_fragment(/** @type {AST.CallExpression} */ (node), transform_context);
2088
+ }
2065
2089
  if (
2066
2090
  node.type === 'ConditionalExpression' ||
2067
2091
  (node.type === 'LogicalExpression' && node.operator === '&&')
@@ -2104,6 +2128,466 @@ function to_vapor_branch(node) {
2104
2128
  return node;
2105
2129
  }
2106
2130
 
2131
+ /**
2132
+ * `@switch` on Vue: the shared lowering, an IIFE around a `switch`, marked so
2133
+ * a `VaporFor` row that is a `@switch` can render through
2134
+ * `switch_in_fragment`. A row slot runs once, so the shared IIFE would keep
2135
+ * the case it picked first and return `null` when no case matches, which
2136
+ * Vapor can't mount. Elsewhere vue-jsx-vapor evaluates the IIFE in an effect,
2137
+ * which follows the value.
2138
+ *
2139
+ * Not marked, so a row keeps the IIFE: the type-only output; a `@switch` that
2140
+ * awaits or yields; one whose case has setup statements or renders anything
2141
+ * but an element, a fragment or a choice of them (a nested `@switch`, a loop
2142
+ * through `map_iterable`), which as a branch of its own would render again,
2143
+ * components and all, whenever what it reads changes, such as the row's
2144
+ * item; and one with more than `MAX_SWITCH_ROW_CASES` cases, whose chain of
2145
+ * choices would nest as deep.
2146
+ *
2147
+ * @param {AST.SwitchStatement} node
2148
+ * @param {TransformContext} transform_context
2149
+ * @returns {ESTreeJSX.JSXRenderNode}
2150
+ */
2151
+ function render_switch_statement(node, transform_context) {
2152
+ const container = switchStatementToJsxChild(node, transform_context);
2153
+ const statement =
2154
+ container.type === 'JSXExpressionContainer' &&
2155
+ container.expression.type === 'CallExpression' &&
2156
+ container.expression.callee.type === 'ArrowFunctionExpression' &&
2157
+ container.expression.callee.body.type === 'BlockStatement'
2158
+ ? container.expression.callee.body.body[0]
2159
+ : null;
2160
+ if (
2161
+ !transform_context.typeOnly &&
2162
+ statement?.type === 'SwitchStatement' &&
2163
+ statement.cases.length <= MAX_SWITCH_ROW_CASES &&
2164
+ statement.cases.every(
2165
+ (switch_case) =>
2166
+ switch_case.consequent.length === 1 &&
2167
+ switch_case.consequent[0].type === 'ReturnStatement' &&
2168
+ renders_once(switch_case.consequent[0].argument),
2169
+ ) &&
2170
+ !suspends(node) &&
2171
+ container.type === 'JSXExpressionContainer'
2172
+ ) {
2173
+ /** @type {Record<string, unknown>} */ (
2174
+ /** @type {unknown} */ (container.expression.metadata ??= { path: [] })
2175
+ )[VAPOR_SWITCH_METADATA] = true;
2176
+ }
2177
+ return container;
2178
+ }
2179
+
2180
+ /**
2181
+ * `@if` on Vue: the shared lowering, marked so that an element's child
2182
+ * `@if` without `@else` can become `v-if` elements
2183
+ * (`render_element_ifs_as_directives`).
2184
+ *
2185
+ * @param {AST.IfStatement} node
2186
+ * @param {TransformContext} transform_context
2187
+ * @returns {ESTreeJSX.JSXRenderNode}
2188
+ */
2189
+ function render_if_statement(node, transform_context) {
2190
+ const container = ifStatementToJsxChild(node, transform_context);
2191
+ if (!transform_context.typeOnly && container.type === 'JSXExpressionContainer') {
2192
+ /** @type {Record<string, unknown>} */ (
2193
+ /** @type {unknown} */ (container.expression.metadata ??= { path: [] })
2194
+ )[VAPOR_IF_METADATA] = true;
2195
+ }
2196
+ return container;
2197
+ }
2198
+
2199
+ /**
2200
+ * Renders an element's child `@if` without `@else if` as a `v-if` element,
2201
+ * and its `@else` as a `v-else` element, when each branch is one element
2202
+ * (`if_directive_branches`).
2203
+ *
2204
+ * - Without `@else`, the shared lowering `cond ? <p /> : null` is a
2205
+ * `createIf` whose empty branch vue-jsx-vapor makes `createNodes(null)`,
2206
+ * which doesn't take the `<!---->` the server rendered for a false
2207
+ * condition: hydrating it throws. A `createIf` from `v-if` without
2208
+ * `v-else` hydrates both that `<!---->` and the rendered branch.
2209
+ * - With `@else`, `cond ? <p /> : <i />` is the same `createIf` as `v-if` /
2210
+ * `v-else` (the same flags) where the choice is alone. Beside another
2211
+ * expression child, though, vue-jsx-vapor evaluates the ternary in that
2212
+ * child's `setNodes` effect, which renders the branch again whenever what
2213
+ * the condition reads changes (#1402); `v-if` / `v-else` stays a `createIf`.
2214
+ * Only a host element's child: vue-jsx-vapor's server build passes
2215
+ * `v-if` / `v-else` to a component as two children, which `KeepAlive`
2216
+ * rejects ("expects exactly one child component").
2217
+ *
2218
+ * A choice followed by an element with its own `v-else` or `v-else-if`,
2219
+ * past any other children, keeps the shared lowering: that element would
2220
+ * join the new `v-if` instead of the one before it.
2221
+ *
2222
+ * @param {AST.Program} program
2223
+ * @returns {void}
2224
+ */
2225
+ function render_element_ifs_as_directives(program) {
2226
+ const walked = /** @type {AST.Program} */ (
2227
+ walk(/** @type {AST.Node} */ (program), null, {
2228
+ JSXElement(node, { next }) {
2229
+ const element = /** @type {ESTreeJSX.JSXElement} */ (
2230
+ /** @type {unknown} */ (next() ?? node)
2231
+ );
2232
+ let changed = false;
2233
+ /** @type {ESTreeJSX.JSXElement['children']} */
2234
+ const children = [];
2235
+ element.children.forEach((child, index) => {
2236
+ const branches =
2237
+ child.type === 'JSXExpressionContainer' &&
2238
+ child.expression.type !== 'JSXEmptyExpression' &&
2239
+ !continues_directive_chain(element.children.slice(index + 1))
2240
+ ? if_directive_branches(
2241
+ /** @type {AST.Expression} */ (child.expression),
2242
+ !is_component_like_element(/** @type {AST.TSRXJSXElement} */ (element)),
2243
+ )
2244
+ : null;
2245
+ if (!branches) {
2246
+ children.push(child);
2247
+ return;
2248
+ }
2249
+ changed = true;
2250
+ children.push(with_directive(branches.then, 'v-if', branches.test));
2251
+ if (branches.else) children.push(with_directive(branches.else, 'v-else'));
2252
+ });
2253
+ return changed
2254
+ ? /** @type {AST.Node} */ (/** @type {unknown} */ ({ ...element, children }))
2255
+ : undefined;
2256
+ },
2257
+ })
2258
+ );
2259
+ program.body = walked.body;
2260
+ }
2261
+
2262
+ /**
2263
+ * Whether the first element in `siblings`, the children after a choice, has
2264
+ * a `v-else` or `v-else-if`. Anything before it, an expression such as
2265
+ * `{null}` or text included, is passed over: the choice then keeps its
2266
+ * lowering even where vue-jsx-vapor wouldn't join that element to it.
2267
+ *
2268
+ * @param {ESTreeJSX.JSXElement['children']} siblings
2269
+ * @returns {boolean}
2270
+ */
2271
+ function continues_directive_chain(siblings) {
2272
+ const next = siblings.find((sibling) => sibling.type === 'JSXElement');
2273
+ return (
2274
+ next?.type === 'JSXElement' &&
2275
+ next.openingElement.attributes.some(
2276
+ (attribute) =>
2277
+ attribute.type === 'JSXAttribute' &&
2278
+ attribute.name.type === 'JSXIdentifier' &&
2279
+ (attribute.name.name === 'v-else' || attribute.name.name === 'v-else-if'),
2280
+ )
2281
+ );
2282
+ }
2283
+
2284
+ /**
2285
+ * The elements a marked `@if` without `@else if` renders and its condition,
2286
+ * when each element can take `v-if` / `v-else`: `else` is `null` without an
2287
+ * `@else` (or with an empty one).
2288
+ *
2289
+ * An `@else if` chain keeps the shared lowering: vue-jsx-vapor gives a
2290
+ * `v-else-if` branch an unkeyed `createIf`, which `VaporKeepAlive` doesn't
2291
+ * cache, where the nested ternary's `createIf` is keyed and is cached.
2292
+ *
2293
+ * @param {AST.Expression} node
2294
+ * @param {boolean} with_else Whether an `@else` branch can become `v-else`.
2295
+ * @returns {{ test: AST.Expression, then: ESTreeJSX.JSXElement, else: ESTreeJSX.JSXElement | null } | null}
2296
+ */
2297
+ function if_directive_branches(node, with_else) {
2298
+ if (
2299
+ node.type !== 'ConditionalExpression' ||
2300
+ !(
2301
+ /** @type {Record<string, unknown> | undefined} */ (/** @type {unknown} */ (node.metadata))?.[
2302
+ VAPOR_IF_METADATA
2303
+ ]
2304
+ )
2305
+ ) {
2306
+ return null;
2307
+ }
2308
+ const without_else = node.alternate.type === 'Literal' && node.alternate.value === null;
2309
+ if (
2310
+ !takes_directive(node.consequent) ||
2311
+ (!without_else && (!with_else || !takes_directive(node.alternate)))
2312
+ ) {
2313
+ return null;
2314
+ }
2315
+ return {
2316
+ test: node.test,
2317
+ then: /** @type {ESTreeJSX.JSXElement} */ (/** @type {unknown} */ (node.consequent)),
2318
+ else: without_else
2319
+ ? null
2320
+ : /** @type {ESTreeJSX.JSXElement} */ (/** @type {unknown} */ (node.alternate)),
2321
+ };
2322
+ }
2323
+
2324
+ /**
2325
+ * Whether `node` is one element that can take `v-if`: not a `<template>`,
2326
+ * `<slot>` or `<component>`, which vue-jsx-vapor renders itself (it
2327
+ * server-renders a `<template v-if>` empty), and without a `v-` attribute
2328
+ * of its own, plain or namespaced (`v-slot:name`), that `v-if` would combine
2329
+ * with. vue-jsx-vapor reads a component's only child with `v-if` and
2330
+ * `v-slot` as the parent's slot declaration and drops it.
2331
+ *
2332
+ * @param {AST.Node | null | undefined} node
2333
+ * @returns {boolean}
2334
+ */
2335
+ function takes_directive(node) {
2336
+ if (node?.type !== 'JSXElement') return false;
2337
+ const opening = /** @type {ESTreeJSX.JSXElement} */ (/** @type {unknown} */ (node))
2338
+ .openingElement;
2339
+ if (
2340
+ opening.name.type === 'JSXIdentifier' &&
2341
+ ['template', 'slot', 'component'].includes(opening.name.name)
2342
+ ) {
2343
+ return false;
2344
+ }
2345
+ return opening.attributes.every(
2346
+ (attribute) =>
2347
+ attribute.type !== 'JSXAttribute' ||
2348
+ !(
2349
+ attribute.name.type === 'JSXNamespacedName'
2350
+ ? attribute.name.namespace.name
2351
+ : attribute.name.name
2352
+ ).startsWith('v-'),
2353
+ );
2354
+ }
2355
+
2356
+ /**
2357
+ * `element` with `v-if={test}`, or `v-else`, first among its attributes.
2358
+ *
2359
+ * @param {ESTreeJSX.JSXElement} element
2360
+ * @param {'v-if' | 'v-else'} name
2361
+ * @param {AST.Expression} [test] For `v-if`.
2362
+ * @returns {ESTreeJSX.JSXElement}
2363
+ */
2364
+ function with_directive(element, name, test) {
2365
+ return {
2366
+ ...element,
2367
+ openingElement: {
2368
+ ...element.openingElement,
2369
+ attributes: [
2370
+ test
2371
+ ? b.jsx_attribute(b.jsx_id(name), to_jsx_expression_container(test))
2372
+ : b.jsx_attribute(b.jsx_id(name)),
2373
+ ...element.openingElement.attributes,
2374
+ ],
2375
+ },
2376
+ };
2377
+ }
2378
+
2379
+ /**
2380
+ * Whether a case's output, as a `createIf` branch, renders once while the
2381
+ * branch stays: an element, a fragment, nothing, or a choice of them, which
2382
+ * vue-jsx-vapor makes `createIf`s too. Anything else is evaluated in an
2383
+ * effect of its own, which renders it again when what it reads changes.
2384
+ *
2385
+ * @param {AST.Expression | null | undefined} node
2386
+ * @returns {boolean}
2387
+ */
2388
+ function renders_once(node) {
2389
+ if (!node) return true;
2390
+ switch (node.type) {
2391
+ case 'JSXElement':
2392
+ case 'JSXFragment':
2393
+ return true;
2394
+ case 'Literal':
2395
+ return node.value === null;
2396
+ case 'ConditionalExpression':
2397
+ return renders_once(node.consequent) && renders_once(node.alternate);
2398
+ case 'LogicalExpression':
2399
+ return node.operator === '&&' && renders_once(node.right);
2400
+ default:
2401
+ return false;
2402
+ }
2403
+ }
2404
+
2405
+ /**
2406
+ * Whether `node` is a `@switch` that `render_switch_statement` marked.
2407
+ *
2408
+ * @param {AST.Node} node
2409
+ * @returns {boolean}
2410
+ */
2411
+ function is_lowered_switch(node) {
2412
+ return (
2413
+ node.type === 'CallExpression' &&
2414
+ !!(
2415
+ /** @type {Record<string, unknown> | undefined} */ (/** @type {unknown} */ (node.metadata))?.[
2416
+ VAPOR_SWITCH_METADATA
2417
+ ]
2418
+ )
2419
+ );
2420
+ }
2421
+
2422
+ /**
2423
+ * The `switch` in the IIFE of a `@switch` that `render_switch_statement`
2424
+ * marked.
2425
+ *
2426
+ * @param {AST.Expression} node
2427
+ * @returns {AST.SwitchStatement}
2428
+ */
2429
+ function lowered_switch_statement(node) {
2430
+ return /** @type {AST.SwitchStatement} */ (
2431
+ /** @type {AST.BlockStatement} */ (
2432
+ /** @type {AST.ArrowFunctionExpression} */ (/** @type {AST.CallExpression} */ (node).callee)
2433
+ .body
2434
+ ).body[0]
2435
+ );
2436
+ }
2437
+
2438
+ /**
2439
+ * A `VaporFor` row that is a `@switch`. Its slot runs once, so a `computed`
2440
+ * runs the `switch` for the index of the case it picks, and the row is a
2441
+ * fragment around the case chosen by that index, which vue-jsx-vapor makes
2442
+ * `createIf`s: the row follows its value, keeps its case mounted while the
2443
+ * index stays the same, and renders an empty fragment when no case matches,
2444
+ * since a row can't be `null`. The `computed` is made once per row, so the
2445
+ * `switch` runs once for each change it reads.
2446
+ *
2447
+ * @param {AST.CallExpression} node
2448
+ * @param {TransformContext} transform_context
2449
+ * @returns {AST.Expression}
2450
+ */
2451
+ function switch_in_fragment(node, transform_context) {
2452
+ const statement = lowered_switch_statement(node);
2453
+ // Without cases there is nothing to choose: the fragment runs the
2454
+ // discriminant in an effect, as the `switch` ran it elsewhere.
2455
+ if (statement.cases.length === 0) {
2456
+ return /** @type {AST.Expression} */ (
2457
+ /** @type {unknown} */ (
2458
+ b.jsx_fragment([
2459
+ to_jsx_expression_container(
2460
+ b.call(b.arrow([], b.block([statement, b.return(b.literal(null))]))),
2461
+ ),
2462
+ ])
2463
+ )
2464
+ );
2465
+ }
2466
+
2467
+ // Named with the next number, which `render_for_of_as_vapor_for` takes
2468
+ // only if the loop renders through `VaporFor`.
2469
+ const case_ref = create_generated_identifier(
2470
+ `${SWITCH_CASE_NAME}_${(switch_counts.get(transform_context) ?? 0) + 1}`,
2471
+ );
2472
+ const error_ref = create_generated_identifier(SWITCH_ERROR_NAME);
2473
+ const previous_ref = create_generated_identifier(SWITCH_PREVIOUS_NAME);
2474
+ /** The index the `computed` holds, or the last one it picked while it holds a throw. */
2475
+ const held_index = () =>
2476
+ b.conditional(
2477
+ b.binary(
2478
+ '===',
2479
+ b.unary('typeof', create_value_member_expression(case_ref)),
2480
+ b.literal('object'),
2481
+ ),
2482
+ b.member(create_value_member_expression(case_ref), 'index'),
2483
+ create_value_member_expression(case_ref),
2484
+ );
2485
+
2486
+ /** @type {AST.Expression} */
2487
+ let chain = b.jsx_fragment();
2488
+ for (let index = statement.cases.length - 1; index >= 0; index--) {
2489
+ const output = /** @type {AST.ReturnStatement} */ (statement.cases[index].consequent[0]);
2490
+ chain = b.conditional(
2491
+ b.binary(
2492
+ '===',
2493
+ // The first choice throws what the `switch` threw, in its
2494
+ // `createIf`'s effect, which keeps following the `computed`;
2495
+ // the others keep the case picked before the throw.
2496
+ index === 0
2497
+ ? b.conditional(
2498
+ b.binary(
2499
+ '===',
2500
+ b.unary('typeof', create_value_member_expression(case_ref)),
2501
+ b.literal('object'),
2502
+ ),
2503
+ b.call(
2504
+ b.arrow(
2505
+ [],
2506
+ b.block([
2507
+ /** @type {AST.ThrowStatement} */ ({
2508
+ type: 'ThrowStatement',
2509
+ argument: b.member(create_value_member_expression(case_ref), 'error'),
2510
+ metadata: { path: [] },
2511
+ }),
2512
+ ]),
2513
+ ),
2514
+ ),
2515
+ create_value_member_expression(case_ref),
2516
+ )
2517
+ : held_index(),
2518
+ b.literal(index),
2519
+ ),
2520
+ to_vapor_branch(output.argument ?? b.literal(null)),
2521
+ chain,
2522
+ );
2523
+ }
2524
+
2525
+ return b.call(
2526
+ b.arrow(
2527
+ [],
2528
+ b.block([
2529
+ // Vue stops running an effect that read a `computed` whose getter
2530
+ // threw, so the `computed` returns what the `switch` threw, with
2531
+ // the index it held before.
2532
+ b.const(
2533
+ case_ref,
2534
+ b.call(
2535
+ VUE_COMPUTED_INTERNAL_NAME,
2536
+ b.arrow(
2537
+ [previous_ref],
2538
+ b.block([
2539
+ b.try(
2540
+ b.block([
2541
+ setLocation(
2542
+ b.switch(
2543
+ statement.discriminant,
2544
+ statement.cases.map((switch_case, index) =>
2545
+ setLocation(
2546
+ b.switch_case(switch_case.test, [b.return(b.literal(index))]),
2547
+ has_location(switch_case) ? switch_case : undefined,
2548
+ ),
2549
+ ),
2550
+ ),
2551
+ has_location(statement) ? statement : undefined,
2552
+ ),
2553
+ b.return(b.literal(-1)),
2554
+ ]),
2555
+ b.catch_clause(
2556
+ error_ref,
2557
+ null,
2558
+ b.block([
2559
+ b.return(
2560
+ b.object([
2561
+ b.prop('init', b.id('error'), clone_identifier(error_ref)),
2562
+ b.prop(
2563
+ 'init',
2564
+ b.id('index'),
2565
+ b.conditional(
2566
+ b.binary(
2567
+ '===',
2568
+ b.unary('typeof', clone_identifier(previous_ref)),
2569
+ b.literal('object'),
2570
+ ),
2571
+ b.member(clone_identifier(previous_ref), 'index'),
2572
+ b.logical('??', clone_identifier(previous_ref), b.literal(-1)),
2573
+ ),
2574
+ ),
2575
+ ]),
2576
+ ),
2577
+ ]),
2578
+ ),
2579
+ null,
2580
+ ),
2581
+ ]),
2582
+ ),
2583
+ ),
2584
+ ),
2585
+ b.return(b.jsx_fragment([to_jsx_expression_container(chain)])),
2586
+ ]),
2587
+ ),
2588
+ );
2589
+ }
2590
+
2107
2591
  /**
2108
2592
  * @param {AST.ForOfStatement} node
2109
2593
  * @param {AST.Pattern[]} loop_params
@@ -2443,6 +2927,14 @@ function rewrite_vapor_for_keyed_slot_refs(node, loop_params, replacements = new
2443
2927
  FunctionExpression: rewrite_function_shadowed_refs,
2444
2928
  ArrowFunctionExpression: rewrite_function_shadowed_refs,
2445
2929
  BlockStatement: rewrite_block_shadowed_refs,
2930
+ StaticBlock: rewrite_static_block_shadowed_refs,
2931
+ CatchClause: rewrite_head_shadowed_refs,
2932
+ ForStatement: rewrite_head_shadowed_refs,
2933
+ ForInStatement: rewrite_head_shadowed_refs,
2934
+ ForOfStatement: rewrite_head_shadowed_refs,
2935
+ SwitchStatement: rewrite_switch_shadowed_refs,
2936
+ ClassExpression: rewrite_class_shadowed_refs,
2937
+ TSEnumDeclaration: rewrite_enum_shadowed_refs,
2446
2938
  },
2447
2939
  )
2448
2940
  );
@@ -2554,7 +3046,7 @@ function collect_pattern_replacements(pattern, source, replacements) {
2554
3046
  * @param {import('zimmerframe').Context<AST.Node, S>} context
2555
3047
  * @returns {AST.Node | void}
2556
3048
  */
2557
- function rewrite_function_shadowed_refs(node, { state, next }) {
3049
+ function rewrite_function_shadowed_refs(node, { state, next, visit }) {
2558
3050
  const shadowed_names = new Set(state.shadowed_names);
2559
3051
  if (node.type !== 'ArrowFunctionExpression' && node.id) {
2560
3052
  collect_pattern_names(node.id, shadowed_names);
@@ -2563,7 +3055,59 @@ function rewrite_function_shadowed_refs(node, { state, next }) {
2563
3055
  collect_pattern_names(param, shadowed_names);
2564
3056
  }
2565
3057
  collect_function_var_names(node.body, shadowed_names);
2566
- return next({ ...state, shadowed_names });
3058
+ const inner = { ...state, shadowed_names };
3059
+
3060
+ // A parameter's decorators run in the enclosing scope, before the
3061
+ // parameters exist: they are walked with the outer names and put back.
3062
+ /** @typedef {AST.Node & { decorators?: AST.Node[] }} DecoratedNode */
3063
+ /** @param {AST.Node} param */
3064
+ const decorated = (param) =>
3065
+ /** @type {DecoratedNode} */ (
3066
+ param.type === 'TSParameterProperty'
3067
+ ? /** @type {{ parameter: AST.Node }} */ (/** @type {unknown} */ (param)).parameter
3068
+ : param
3069
+ );
3070
+ /** @type {Map<number, AST.Node[]>} */
3071
+ const decorators = new Map();
3072
+ const params = (node.params || []).map((param, index) => {
3073
+ const target = decorated(/** @type {AST.Node} */ (param));
3074
+ if (!target.decorators?.length) return param;
3075
+ decorators.set(
3076
+ index,
3077
+ target.decorators.map((decorator) => /** @type {AST.Node} */ (visit(decorator, state))),
3078
+ );
3079
+ return with_decorators(/** @type {AST.Node} */ (param), []);
3080
+ });
3081
+ if (decorators.size === 0) return next(inner);
3082
+
3083
+ const walked = /** @type {AST.Function} */ (
3084
+ visit(/** @type {AST.Node} */ ({ ...node, params }), inner)
3085
+ );
3086
+ return /** @type {AST.Node} */ ({
3087
+ ...walked,
3088
+ params: walked.params.map((param, index) => {
3089
+ const outer = decorators.get(index);
3090
+ return outer ? with_decorators(/** @type {AST.Node} */ (param), outer) : param;
3091
+ }),
3092
+ });
3093
+ }
3094
+
3095
+ /**
3096
+ * `param`, a parameter or a constructor's parameter property, with its
3097
+ * decorators replaced.
3098
+ *
3099
+ * @param {AST.Node} param
3100
+ * @param {AST.Node[]} decorators
3101
+ * @returns {AST.Pattern}
3102
+ */
3103
+ function with_decorators(param, decorators) {
3104
+ if (param.type === 'TSParameterProperty') {
3105
+ const property = /** @type {{ parameter: AST.Node }} */ (/** @type {unknown} */ (param));
3106
+ return /** @type {AST.Pattern} */ (
3107
+ /** @type {unknown} */ ({ ...param, parameter: { ...property.parameter, decorators } })
3108
+ );
3109
+ }
3110
+ return /** @type {AST.Pattern} */ (/** @type {unknown} */ ({ ...param, decorators }));
2567
3111
  }
2568
3112
 
2569
3113
  /**
@@ -2578,6 +3122,116 @@ function rewrite_block_shadowed_refs(node, { state, next }) {
2578
3122
  return next({ ...state, shadowed_names });
2579
3123
  }
2580
3124
 
3125
+ /**
3126
+ * A class `static` block is a function body: its `var`s are its own too.
3127
+ *
3128
+ * @template {{ shadowed_names: Set<string> }} S
3129
+ * @param {AST.StaticBlock} node
3130
+ * @param {import('zimmerframe').Context<AST.Node, S>} context
3131
+ * @returns {AST.Node | void}
3132
+ */
3133
+ function rewrite_static_block_shadowed_refs(node, { state, next }) {
3134
+ const shadowed_names = new Set(state.shadowed_names);
3135
+ collect_block_lexical_names(node.body, shadowed_names);
3136
+ collect_function_var_names(node.body, shadowed_names);
3137
+ return next({ ...state, shadowed_names });
3138
+ }
3139
+
3140
+ /**
3141
+ * The names a `catch` clause's parameter or a `for` head declares, which
3142
+ * shadow the outer ones in the whole statement. A `let` or `const` head's
3143
+ * names are in their temporal dead zone in the loop's own expressions, the
3144
+ * right-hand side of `for (const row of row.children)` included, which reads
3145
+ * the inner `row` and throws, so those stay as written too.
3146
+ *
3147
+ * @template {{ shadowed_names: Set<string> }} S
3148
+ * @param {AST.CatchClause | AST.ForStatement | AST.ForInStatement | AST.ForOfStatement} node
3149
+ * @param {import('zimmerframe').Context<AST.Node, S>} context
3150
+ * @returns {AST.Node | void}
3151
+ */
3152
+ function rewrite_head_shadowed_refs(node, { state, next }) {
3153
+ /** @type {AST.Node[]} */
3154
+ const bindings = [];
3155
+ if (node.type === 'CatchClause' && node.param) bindings.push(node.param);
3156
+ const head =
3157
+ node.type === 'ForStatement'
3158
+ ? node.init
3159
+ : node.type === 'ForInStatement' || node.type === 'ForOfStatement'
3160
+ ? node.left
3161
+ : null;
3162
+ if (head?.type === 'VariableDeclaration') {
3163
+ for (const declarator of head.declarations) bindings.push(declarator.id);
3164
+ }
3165
+ if (bindings.length === 0) return next();
3166
+ const shadowed_names = new Set(state.shadowed_names);
3167
+ for (const binding of bindings) collect_pattern_names(binding, shadowed_names);
3168
+ return next({ ...state, shadowed_names });
3169
+ }
3170
+
3171
+ /**
3172
+ * A `switch`'s cases share one block, which its discriminant is read outside of.
3173
+ *
3174
+ * @template {{ shadowed_names: Set<string> }} S
3175
+ * @param {AST.SwitchStatement} node
3176
+ * @param {import('zimmerframe').Context<AST.Node, S>} context
3177
+ * @returns {AST.SwitchStatement}
3178
+ */
3179
+ function rewrite_switch_shadowed_refs(node, { state, visit }) {
3180
+ const shadowed_names = new Set(state.shadowed_names);
3181
+ collect_block_lexical_names(
3182
+ node.cases.flatMap((switch_case) => switch_case.consequent),
3183
+ shadowed_names,
3184
+ );
3185
+ const inner = { ...state, shadowed_names };
3186
+ return {
3187
+ ...node,
3188
+ discriminant: /** @type {AST.Expression} */ (visit(node.discriminant, state)),
3189
+ cases: node.cases.map(
3190
+ (switch_case) => /** @type {AST.SwitchCase} */ (visit(switch_case, inner)),
3191
+ ),
3192
+ };
3193
+ }
3194
+
3195
+ /**
3196
+ * An `enum`'s members are bound inside it: a member's initializer reads an
3197
+ * earlier member by its name. (Members of another declaration of the same
3198
+ * `enum` are in scope too; those aren't collected.)
3199
+ *
3200
+ * @template {{ shadowed_names: Set<string> }} S
3201
+ * @param {AST.Node} node A `TSEnumDeclaration`.
3202
+ * @param {import('zimmerframe').Context<AST.Node, S>} context
3203
+ * @returns {AST.Node | void}
3204
+ */
3205
+ function rewrite_enum_shadowed_refs(node, { state, next }) {
3206
+ const members =
3207
+ /** @type {{ body?: { members?: { id: AST.Node }[] }, members?: { id: AST.Node }[] }} */ (
3208
+ /** @type {unknown} */ (node)
3209
+ );
3210
+ const shadowed_names = new Set(state.shadowed_names);
3211
+ for (const member of members.body?.members ?? members.members ?? []) {
3212
+ const id = /** @type {AST.Node} */ (member.id);
3213
+ if (id.type === 'Identifier') shadowed_names.add(id.name);
3214
+ // A quoted member (`"row" = 1`) is read by its name too.
3215
+ else if (id.type === 'Literal' && typeof id.value === 'string') shadowed_names.add(id.value);
3216
+ }
3217
+ return next({ ...state, shadowed_names });
3218
+ }
3219
+
3220
+ /**
3221
+ * A class expression's name is bound inside it, its heritage included.
3222
+ *
3223
+ * @template {{ shadowed_names: Set<string> }} S
3224
+ * @param {AST.ClassExpression} node
3225
+ * @param {import('zimmerframe').Context<AST.Node, S>} context
3226
+ * @returns {AST.Node | void}
3227
+ */
3228
+ function rewrite_class_shadowed_refs(node, { state, next }) {
3229
+ if (!node.id) return next();
3230
+ const shadowed_names = new Set(state.shadowed_names);
3231
+ collect_pattern_names(node.id, shadowed_names);
3232
+ return next({ ...state, shadowed_names });
3233
+ }
3234
+
2581
3235
  /**
2582
3236
  * @param {AST.Statement[]} statements
2583
3237
  * @param {Set<string>} names
@@ -2597,6 +3251,16 @@ function collect_block_lexical_names(statements, names) {
2597
3251
  statement.id
2598
3252
  ) {
2599
3253
  collect_pattern_names(statement.id, names);
3254
+ continue;
3255
+ }
3256
+
3257
+ // An `enum` or a namespace, which the statement types leave out.
3258
+ const declaration = /** @type {AST.Node} */ (statement);
3259
+ if (
3260
+ (declaration.type === 'TSEnumDeclaration' || declaration.type === 'TSModuleDeclaration') &&
3261
+ declaration.id.type === 'Identifier'
3262
+ ) {
3263
+ collect_pattern_names(declaration.id, names);
2600
3264
  }
2601
3265
  }
2602
3266
  }
@@ -2683,6 +3347,13 @@ function collect_pattern_names(node, names) {
2683
3347
  case 'Property':
2684
3348
  collect_pattern_names(node.value, names);
2685
3349
  break;
3350
+ // A constructor's parameter property (`constructor(public row)`).
3351
+ case 'TSParameterProperty':
3352
+ collect_pattern_names(
3353
+ /** @type {AST.Node} */ (/** @type {unknown} */ (node.parameter)),
3354
+ names,
3355
+ );
3356
+ break;
2686
3357
  }
2687
3358
  }
2688
3359