@tsrx/vue 0.3.5 → 0.4.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/src/transform.js CHANGED
@@ -4,25 +4,52 @@
4
4
 
5
5
  import { walk } from 'zimmerframe';
6
6
  import is_reference from 'is-reference';
7
+ import { find_deferred_template_yields } from './template-yield.js';
7
8
  import {
8
9
  builders as b,
9
10
  addJsxSetupDeclaration,
10
11
  clone_ast_node,
11
12
  clone_identifier,
12
- contains_component_jsx,
13
13
  createHookSafeHelper,
14
14
  create_generated_identifier,
15
15
  createJsxTransform,
16
- DIAGNOSTIC_CODES,
16
+ ERROR_BOUNDARY_INTERNAL_NAME,
17
17
  error,
18
18
  has_location,
19
+ IDENTIFIER_OBFUSCATION_PREFIX,
20
+ insertAfterDirectives,
19
21
  is_component_like_element,
22
+ JOIN_SCOPE_CLASS_INTERNAL_NAME,
20
23
  MERGE_REFS_INTERNAL_NAME,
21
24
  NORMALIZE_SPREAD_PROPS_FOR_REF_ATTR_INTERNAL_NAME,
22
25
  NORMALIZE_SPREAD_PROPS_INTERNAL_NAME,
23
26
  setLocation,
27
+ SUSPENSE_INTERNAL_NAME,
28
+ TSRX_ERRORS,
24
29
  } from '@tsrx/core';
25
30
 
31
+ /** The local name of Vue's `computed` in a keyed slot that destructures its item. */
32
+ const VUE_COMPUTED_INTERNAL_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'vapor_computed';
33
+ /** The `computed` such a slot destructures its item in, numbered per slot. */
34
+ const VAPOR_BINDINGS_NAME = IDENTIFIER_OBFUSCATION_PREFIX + 'vapor_bindings';
35
+ /**
36
+ * How many slots each compile has given a bindings `computed`, so each slot's
37
+ * has its own name and a nested slot's can't capture the outer slot's names.
38
+ * @type {WeakMap<TransformContext, number>}
39
+ */
40
+ const vapor_bindings_counts = new WeakMap();
41
+
42
+ /**
43
+ * Local name for the `VaporFor` the transform imports for `@for`, so an
44
+ * authored binding named `VaporFor` neither collides with the import nor
45
+ * replaces the loop. `defineVaporComponent` keeps its public name:
46
+ * vue-jsx-vapor finds components by that callee name for its macros, HMR,
47
+ * SSR and interop output.
48
+ */
49
+ const VAPOR_FOR_INTERNAL_NAME = '__VaporFor';
50
+
51
+ const DEFINE_VAPOR_COMPONENT = 'defineVaporComponent';
52
+
26
53
  /**
27
54
  * Minimal Vue platform descriptor consumed by `createJsxTransform`.
28
55
  *
@@ -53,8 +80,17 @@ const vue_platform = {
53
80
  },
54
81
  jsx: {
55
82
  rewriteClassAttr: false,
83
+ // `class` also takes an object or a list.
84
+ classValue: 'list',
85
+ // A static `className` renders as a `classname` attribute.
86
+ rewriteClassNameAttr: true,
56
87
  multiRefStrategy: 'merge-refs',
57
88
  hostSpreadRefStrategy: 'explicit-ref-attr',
89
+ // vue-jsx-vapor evaluates a spread inside the element's render effect and
90
+ // sets its template ref after the props, so a bag bound in place is read
91
+ // again when its expression changes and is assigned before its `ref`.
92
+ hostSpreadRefBinding: 'in-place',
93
+ refAfterProps: true,
58
94
  // vue-jsx-vapor escapes a string child into its HTML template, where a
59
95
  // `<script>` element's text isn't decoded, and writes a string
60
96
  // `innerHTML` there as an attribute. `v-html` sets the body as written
@@ -69,13 +105,17 @@ const vue_platform = {
69
105
  initialState: () => ({
70
106
  needs_define_vapor_component: false,
71
107
  needs_vapor_for: false,
108
+ needs_use_slots: false,
72
109
  }),
73
110
  wrapHelperComponent(helper_fn, helper_id, ctx, source_node) {
74
111
  ctx.needs_define_vapor_component = true;
75
112
  return wrap_helper_component(helper_fn, helper_id, source_node);
76
113
  },
77
- canHoistStaticNode(node) {
78
- return !contains_component_jsx(node);
114
+ canHoistStaticNode() {
115
+ // Vapor JSX evaluates to a DOM node, so a module-level static would be
116
+ // one node that every use moves into place. vue-jsx-vapor already
117
+ // hoists the parsed template and clones it per evaluation.
118
+ return false;
79
119
  },
80
120
  preprocessElementAttributes(attrs, ctx) {
81
121
  return preprocess_ref_attributes(attrs, ctx);
@@ -88,8 +128,8 @@ const vue_platform = {
88
128
  },
89
129
  renderForOf: (node, loop_params, body_statements, ctx) =>
90
130
  render_for_of_as_vapor_for(node, loop_params, body_statements, ctx),
91
- createPendingBoundary(try_content, fallback_content) {
92
- return create_vapor_pending_boundary(try_content, fallback_content);
131
+ createPendingBoundary(try_content, fallback_content, ctx) {
132
+ return create_vapor_pending_boundary(try_content, fallback_content, ctx);
93
133
  },
94
134
  createErrorFallbackComponent(catch_body_nodes, catch_params, ctx, node) {
95
135
  // Only the runtime `@pending` boundary renders the component (see
@@ -113,16 +153,11 @@ const vue_platform = {
113
153
  const fallback_component = info?.fallbackComponent ?? null;
114
154
  const default_slot = ctx.typeOnly
115
155
  ? b.arrow([], jsx_child_to_expression(raw_try_content))
116
- : create_sync_error_boundary_slot(
117
- raw_try_content,
118
- fallback_fn,
119
- fallback_component,
120
- node.block,
121
- node,
122
- );
156
+ : create_error_boundary_slot(raw_try_content, fallback_fn, node);
123
157
  const suspense = create_vapor_pending_boundary_from_default_slot(
124
158
  default_slot,
125
159
  fallback_content,
160
+ ctx,
126
161
  );
127
162
  const boundary = create_vapor_error_boundary(suspense, fallback_fn);
128
163
  for (const statement of fallback_component?.setup_statements ?? []) {
@@ -136,14 +171,14 @@ const vue_platform = {
136
171
  transformElementChildren(node, walked_children, raw_children, attributes, ctx) {
137
172
  return rewrite_host_text_children(node, walked_children, raw_children, attributes);
138
173
  },
174
+ findDeferredTemplateYields: find_deferred_template_yields,
139
175
  validateComponentAwait(await_expression, _component, ctx) {
140
176
  error(
141
- '`await` is not yet supported in Vue TSRX components.',
177
+ TSRX_ERRORS.TARGET_COMPONENT_AWAIT_UNSUPPORTED(ctx.platform.name),
142
178
  ctx?.filename ?? null,
143
179
  await_expression,
144
180
  ctx?.errors,
145
181
  ctx?.comments,
146
- DIAGNOSTIC_CODES.TARGET_AWAIT_UNSUPPORTED,
147
182
  );
148
183
  },
149
184
  injectImports(program, ctx) {
@@ -158,23 +193,29 @@ export const transform = createJsxTransform(vue_platform);
158
193
  /**
159
194
  * @param {ESTreeJSX.JSXRenderNode} try_content
160
195
  * @param {ESTreeJSX.JSXRenderNode} fallback_content
196
+ * @param {TransformContext} ctx
161
197
  * @returns {AST.TSRXJSXElement}
162
198
  */
163
- function create_vapor_pending_boundary(try_content, fallback_content) {
199
+ function create_vapor_pending_boundary(try_content, fallback_content, ctx) {
164
200
  return create_vapor_pending_boundary_from_default_slot(
165
201
  b.arrow([], jsx_child_to_expression(try_content)),
166
202
  fallback_content,
203
+ ctx,
167
204
  );
168
205
  }
169
206
 
170
207
  /**
171
208
  * @param {AST.ArrowFunctionExpression} default_slot
172
209
  * @param {ESTreeJSX.JSXRenderNode} fallback_content
210
+ * @param {TransformContext} ctx
173
211
  * @returns {AST.TSRXJSXElement}
174
212
  */
175
- function create_vapor_pending_boundary_from_default_slot(default_slot, fallback_content) {
213
+ function create_vapor_pending_boundary_from_default_slot(default_slot, fallback_content, ctx) {
176
214
  const fallback_expression = jsx_child_to_expression(fallback_content);
177
- const slots_properties = [b.init('_', b.literal(1)), b.init('default', default_slot)];
215
+ const slots_properties = [b.init('default', default_slot)];
216
+ // Vue's stable-slots flag isn't a slot, so `Suspense`'s JSX slot types reject
217
+ // it in the type-only output.
218
+ if (!ctx.typeOnly) slots_properties.unshift(b.init('_', b.literal(1)));
178
219
 
179
220
  if (fallback_expression.type !== 'Literal' || fallback_expression.value !== null) {
180
221
  slots_properties.push(b.init('fallback', b.arrow([], fallback_expression)));
@@ -184,7 +225,7 @@ function create_vapor_pending_boundary_from_default_slot(default_slot, fallback_
184
225
 
185
226
  const boundary = b.jsx_element_fresh(
186
227
  b.jsx_opening_element(
187
- b.jsx_id('Suspense'),
228
+ b.jsx_id(SUSPENSE_INTERNAL_NAME),
188
229
  [b.jsx_attribute(b.jsx_id('v-slots'), to_jsx_expression_container(slots))],
189
230
  true,
190
231
  ),
@@ -210,78 +251,23 @@ function create_module_scoped_error_fallback_component(catch_body_nodes, catch_p
210
251
  }
211
252
 
212
253
  /**
213
- * Catch synchronous setup errors directly in the Suspense default slot so
214
- * Suspense can still observe async children while `catch` handles immediate
215
- * render failures.
254
+ * Render the try body in the Suspense default slot through its own error
255
+ * boundary. Suspense mounts its default content after the outer boundary has
256
+ * rendered, so an error thrown there, while setting up or from a rejected
257
+ * async child, has to be caught inside the slot. A boundary there, unlike a
258
+ * plain `try`, also gives `@catch` a `reset` that renders the body again.
216
259
  *
217
260
  * @param {ESTreeJSX.JSXRenderNode} content
218
261
  * @param {AST.ArrowFunctionExpression} fallback_fn
219
- * @param {JsxHelperComponent | null} fallback_component
220
- * @param {AST.BlockStatement} source_block
221
262
  * @param {AST.TryStatement} source_try
222
263
  * @returns {AST.ArrowFunctionExpression}
223
264
  */
224
- function create_sync_error_boundary_slot(
225
- content,
226
- fallback_fn,
227
- fallback_component,
228
- source_block,
229
- source_try,
230
- ) {
231
- const error_id = create_generated_identifier('_error');
232
- const content_expression = jsx_child_to_expression(content);
233
- const fallback_expression = fallback_component
234
- ? create_fallback_component_element(fallback_component, fallback_fn, [
235
- error_id,
236
- b.arrow([], b.block([])),
237
- ])
238
- : b.call(b.parenthesized(fallback_fn), clone_identifier(error_id), b.arrow([], b.block([])));
239
- const try_block = setLocation(
240
- b.block([b.return(content_expression)]),
241
- has_location(source_block) ? source_block : undefined,
242
- true,
243
- );
244
- const try_statement = setLocation(
245
- b.try(
246
- try_block,
247
- b.catch_clause(error_id, null, b.block([b.return(fallback_expression)])),
248
- null,
249
- null,
250
- ),
251
- has_location(source_try) ? source_try : undefined,
252
- true,
265
+ function create_error_boundary_slot(content, fallback_fn, source_try) {
266
+ const boundary = create_vapor_error_boundary(content, clone_ast_node(fallback_fn, false));
267
+ return b.arrow(
268
+ [],
269
+ setLocation(boundary, has_location(source_try) ? source_try : undefined, true),
253
270
  );
254
- return b.arrow([], b.block([try_statement]));
255
- }
256
-
257
- /**
258
- * @param {JsxHelperComponent} fallback_component
259
- * @param {AST.ArrowFunctionExpression} fallback_fn
260
- * @param {AST.Expression[]} [replacement_args]
261
- * @returns {AST.TSRXJSXElement}
262
- */
263
- function create_fallback_component_element(fallback_component, fallback_fn, replacement_args = []) {
264
- const element = clone_ast_node(fallback_component.component_element, false);
265
- /** @type {Map<string, AST.Expression>} */
266
- const replacements = new Map();
267
- for (let i = 0; i < fallback_fn.params.length && i < replacement_args.length; i += 1) {
268
- const param = fallback_fn.params[i];
269
- if (param?.type === 'Identifier') {
270
- replacements.set(param.name, replacement_args[i]);
271
- }
272
- }
273
-
274
- for (const attr of element.openingElement?.attributes ?? []) {
275
- if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier') continue;
276
- const attr_name = attr.name.name;
277
- if (!attr_name || !replacements.has(attr_name)) continue;
278
- attr.value = to_jsx_expression_container(
279
- /** @type {AST.Expression} */ (replacements.get(attr_name)),
280
- attr.value ?? attr,
281
- );
282
- }
283
-
284
- return element;
285
271
  }
286
272
 
287
273
  /**
@@ -314,7 +300,7 @@ function jsx_child_to_expression(child) {
314
300
  function create_vapor_error_boundary(content, fallback_fn) {
315
301
  return b.jsx_element_fresh(
316
302
  b.jsx_opening_element(
317
- b.jsx_id('TsrxErrorBoundary'),
303
+ b.jsx_id(ERROR_BOUNDARY_INTERNAL_NAME),
318
304
  [
319
305
  b.jsx_attribute(b.jsx_id('fallback'), to_jsx_expression_container(fallback_fn)),
320
306
  b.jsx_attribute(
@@ -354,98 +340,1377 @@ function mark_type_only_host_ref_attribute(attr) {
354
340
  }
355
341
 
356
342
  /**
357
- * @param {AST.FunctionDeclaration} helper_fn
358
- * @param {AST.Identifier} helper_id
359
- * @param {AST.NodeWithLocation | undefined} source_node
360
- * @returns {AST.VariableDeclaration}
343
+ * @param {AST.FunctionDeclaration} helper_fn
344
+ * @param {AST.Identifier} helper_id
345
+ * @param {AST.NodeWithLocation | undefined} source_node
346
+ * @returns {AST.VariableDeclaration}
347
+ */
348
+ function wrap_helper_component(helper_fn, helper_id, source_node) {
349
+ return setLocation(
350
+ b.declaration('const', [
351
+ b.declarator(
352
+ clone_identifier(helper_id),
353
+ create_define_vapor_component_call(function_declaration_to_expression(helper_fn), [], []),
354
+ ),
355
+ ]),
356
+ source_node,
357
+ );
358
+ }
359
+
360
+ /**
361
+ * @param {AST.Program} program
362
+ * @param {TransformContext} ctx
363
+ * @returns {void}
364
+ */
365
+ function wrap_native_function_components(program, ctx) {
366
+ const wrapped = walk(program, ctx, {
367
+ FunctionDeclaration: visit_function_component,
368
+ FunctionExpression: visit_function_component,
369
+ ArrowFunctionExpression: visit_function_component,
370
+ Program: visit_statement_list_owner,
371
+ BlockStatement: visit_statement_list_owner,
372
+ StaticBlock: visit_statement_list_owner,
373
+ });
374
+ program.body = /** @type {AST.Program} */ (wrapped).body;
375
+ }
376
+
377
+ /**
378
+ * @param {AST.Program | AST.BlockStatement | AST.StaticBlock} node
379
+ * @param {import('zimmerframe').Context<AST.Node, TransformContext>} context
380
+ * @returns {AST.Node | void}
381
+ */
382
+ function visit_statement_list_owner(node, { next, state }) {
383
+ const walked = /** @type {typeof node} */ (next() ?? node);
384
+ const statements = split_default_exported_components(/** @type {AST.Node[]} */ (walked.body));
385
+ const hoisted = hoist_component_bindings(statements, state);
386
+ if (hoisted === walked.body) {
387
+ return walked === node ? undefined : walked;
388
+ }
389
+ return /** @type {AST.Node} */ ({ ...walked, body: hoisted });
390
+ }
391
+
392
+ /**
393
+ * `export default function Card` binds `Card` in the module too, so a wrapped
394
+ * one becomes `const Card = defineVaporComponent(…); export default Card;`.
395
+ *
396
+ * @param {AST.Node[]} statements
397
+ * @returns {AST.Node[]}
398
+ */
399
+ function split_default_exported_components(statements) {
400
+ if (!statements.some((statement) => get_default_exported_component(statement))) {
401
+ return statements;
402
+ }
403
+ return statements.flatMap((statement) => {
404
+ const declaration = get_default_exported_component(statement);
405
+ if (!declaration) return [statement];
406
+ const name = /** @type {string} */ (declaration.metadata.vue_component_binding);
407
+ return [declaration, b.export_default(b.id(name))];
408
+ });
409
+ }
410
+
411
+ /**
412
+ * @param {AST.Node} statement
413
+ * @returns {AST.VariableDeclaration | null}
414
+ */
415
+ function get_default_exported_component(statement) {
416
+ const declaration = /** @type {AST.Node | null} */ (
417
+ statement.type === 'ExportDefaultDeclaration' ? statement.declaration : null
418
+ );
419
+ return declaration?.type === 'VariableDeclaration' && declaration.metadata?.vue_component_binding
420
+ ? declaration
421
+ : null;
422
+ }
423
+
424
+ /**
425
+ * Wrapping turns a component's function declaration into a `const`, which,
426
+ * unlike the declaration, is not hoisted. When a statement above the
427
+ * component reads it while its scope runs, such as
428
+ * `const registry = { inner: Inner }` above `function Inner`, move the
429
+ * component above that statement, but only when that changes nothing else:
430
+ * vue-jsx-vapor evaluates a destructured prop default that names a binding
431
+ * (`{ label = PREFIX }`) when the component is defined, so a default that
432
+ * reads a binding declared, assigned or mutated in the statements the
433
+ * component would move past is reported instead (TSRX2028).
434
+ *
435
+ * Reads that run later or not at all do not count: inside a function, a class
436
+ * instance field or method, a type, an `export { … }` specifier, a branch a
437
+ * constant condition skips, or a scope with its own binding of the name.
438
+ * Calls are not followed, so these still go wrong: a call or IIFE that runs a
439
+ * function reading the component during module evaluation hits the constant
440
+ * before it is initialized, and a call in the skipped statements to a
441
+ * function that assigns a binding a default reads (`bump()` setting `size`)
442
+ * runs after the moved component has captured the old value. So do a read
443
+ * from another `case` of the `switch` that declares the component and a
444
+ * circular import that reads it before this module finishes.
445
+ *
446
+ * @param {AST.Node[]} statements
447
+ * @param {TransformContext} ctx
448
+ * @returns {AST.Node[]}
449
+ */
450
+ function hoist_component_bindings(statements, ctx) {
451
+ let result = statements;
452
+ /** @type {Map<string, AST.Literal['value']> | null} */
453
+ let constants = null;
454
+ for (const statement of statements) {
455
+ const declaration = get_component_declaration(statement);
456
+ if (!declaration) continue;
457
+ const name = /** @type {string} */ (declaration.metadata.vue_component_binding);
458
+
459
+ const index = result.indexOf(statement);
460
+ constants ??= collect_literal_constants(statements);
461
+ let first_read = -1;
462
+ /** @type {AST.Node | null} */
463
+ let read = null;
464
+ for (let i = 0; i < index && !read; i += 1) {
465
+ read = find_eager_read(result[i], name, /** @type {Map<string, any>} */ (constants));
466
+ if (read) first_read = i;
467
+ }
468
+ if (!read) continue;
469
+
470
+ const passed = result.slice(first_read, index);
471
+ if (initializer_reads_declared(declaration, passed)) {
472
+ error(
473
+ TSRX_ERRORS.TARGET_COMPONENT_READ_BEFORE_DECLARATION(ctx.platform.name, name),
474
+ ctx.filename,
475
+ read,
476
+ ctx.errors,
477
+ ctx.comments,
478
+ );
479
+ continue;
480
+ }
481
+
482
+ result = [...result.slice(0, first_read), statement, ...passed, ...result.slice(index + 1)];
483
+ }
484
+ return result;
485
+ }
486
+
487
+ /**
488
+ * @param {AST.Node} statement
489
+ * @returns {(AST.VariableDeclaration & { metadata: { vue_component_binding: string } }) | null}
490
+ */
491
+ function get_component_declaration(statement) {
492
+ const declaration =
493
+ statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
494
+ return declaration?.type === 'VariableDeclaration' && declaration.metadata?.vue_component_binding
495
+ ? /** @type {any} */ (declaration)
496
+ : null;
497
+ }
498
+
499
+ /**
500
+ * `const NAME = <literal>` declarations in a statement list, for skipping the
501
+ * branches a constant condition never takes (`const DEBUG = false; if (DEBUG)`).
502
+ *
503
+ * @param {AST.Node[]} statements
504
+ * @returns {Map<string, AST.Literal['value']>}
505
+ */
506
+ function collect_literal_constants(statements) {
507
+ /** @type {Map<string, AST.Literal['value']>} */
508
+ const constants = new Map();
509
+ for (const statement of statements) {
510
+ const declaration =
511
+ statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
512
+ if (declaration?.type !== 'VariableDeclaration' || declaration.kind !== 'const') continue;
513
+ for (const declarator of declaration.declarations) {
514
+ if (declarator.id.type === 'Identifier' && declarator.init?.type === 'Literal') {
515
+ constants.set(declarator.id.name, declarator.init.value);
516
+ }
517
+ }
518
+ }
519
+ return constants;
520
+ }
521
+
522
+ /**
523
+ * @param {AST.Node | null | undefined} node
524
+ * @param {Map<string, AST.Literal['value']>} constants
525
+ * @returns {boolean | null} the condition's truthiness, or null when unknown
526
+ */
527
+ function constant_truthiness(node, constants) {
528
+ if (node?.type === 'Literal') return !!node.value || 'regex' in node;
529
+ if (node?.type === 'Identifier') {
530
+ if (node.name === 'undefined') return false;
531
+ return constants.has(node.name) ? !!constants.get(node.name) : null;
532
+ }
533
+ if (node?.type === 'UnaryExpression' && node.operator === '!') {
534
+ const value = constant_truthiness(node.argument, constants);
535
+ return value === null ? null : !value;
536
+ }
537
+ return null;
538
+ }
539
+
540
+ /**
541
+ * TypeScript nodes that hold runtime code. Every other `TS*` node is a type,
542
+ * which is erased and never reads a binding.
543
+ */
544
+ const RUNTIME_TS_NODE_TYPES = new Set([
545
+ 'TSAsExpression',
546
+ 'TSSatisfiesExpression',
547
+ 'TSNonNullExpression',
548
+ 'TSInstantiationExpression',
549
+ 'TSTypeAssertion',
550
+ 'TSEnumDeclaration',
551
+ 'TSEnumMember',
552
+ 'TSModuleDeclaration',
553
+ 'TSModuleBlock',
554
+ 'TSExportAssignment',
555
+ 'TSParameterProperty',
556
+ ]);
557
+
558
+ /**
559
+ * The first read of `name` that evaluating `root` performs: not inside a
560
+ * function, a class instance field or method, a type or an `export { … }`
561
+ * specifier, not in a branch a constant condition skips, and not in a scope
562
+ * with its own binding of `name`.
563
+ *
564
+ * @param {AST.Node} root
565
+ * @param {string} name
566
+ * @param {Map<string, AST.Literal['value']>} constants
567
+ * @returns {AST.Node | null}
568
+ */
569
+ function find_eager_read(root, name, constants) {
570
+ /** @type {AST.Node | null} */
571
+ let found = null;
572
+ // The literal constants visible where the walk is: a scope that declares
573
+ // its own binding of a name forgets that name's value.
574
+ let visible = constants;
575
+
576
+ /**
577
+ * @param {AST.Node[]} bindings patterns or declarations a scope introduces
578
+ * @param {() => void} walk_scope
579
+ */
580
+ const in_scope = (bindings, walk_scope) => {
581
+ const saved = visible;
582
+ visible = forget_declared(visible, bindings);
583
+ walk_scope();
584
+ visible = saved;
585
+ };
586
+
587
+ /**
588
+ * @param {unknown} value
589
+ * @param {AST.Node | undefined} parent
590
+ */
591
+ const visit = (value, parent) => {
592
+ if (found || !value || typeof value !== 'object') return;
593
+ if (Array.isArray(value)) {
594
+ for (const child of value) visit(child, parent);
595
+ return;
596
+ }
597
+ const node = /** @type {AST.Node} */ (value);
598
+ if (typeof node.type !== 'string') return;
599
+
600
+ switch (node.type) {
601
+ case 'FunctionDeclaration':
602
+ case 'FunctionExpression':
603
+ case 'ArrowFunctionExpression':
604
+ case 'ExportSpecifier':
605
+ return;
606
+ case 'Identifier':
607
+ if (node.name === name && parent && is_reference(node, parent)) found = node;
608
+ return;
609
+ case 'JSXIdentifier':
610
+ if (
611
+ node.name === name &&
612
+ ((parent?.type === 'JSXOpeningElement' && parent.name === node) ||
613
+ (parent?.type === 'JSXMemberExpression' && parent.object === node))
614
+ ) {
615
+ found = node;
616
+ }
617
+ return;
618
+ case 'BlockStatement':
619
+ case 'StaticBlock':
620
+ if (declares_lexically(node.body, name)) return;
621
+ in_scope(node.body, () => visit(node.body, node));
622
+ return;
623
+ case 'SwitchStatement': {
624
+ visit(node.discriminant, node);
625
+ const declarations = node.cases.flatMap((c) => c.consequent);
626
+ if (!declares_lexically(declarations, name)) {
627
+ in_scope(declarations, () => visit(node.cases, node));
628
+ }
629
+ return;
630
+ }
631
+ case 'ForStatement':
632
+ case 'ForInStatement':
633
+ case 'ForOfStatement': {
634
+ const head = node.type === 'ForStatement' ? node.init : node.left;
635
+ if (head?.type === 'VariableDeclaration' && head.kind !== 'var') {
636
+ if (declares_lexically([head], name)) return;
637
+ in_scope([head], () => visit_children(node));
638
+ return;
639
+ }
640
+ break;
641
+ }
642
+ case 'CatchClause':
643
+ if (node.param && get_pattern_names([node.param]).has(name)) return;
644
+ if (node.param) {
645
+ in_scope([node.param], () => visit(node.body, node));
646
+ return;
647
+ }
648
+ break;
649
+ case 'IfStatement': {
650
+ visit(node.test, node);
651
+ const truthy = constant_truthiness(node.test, visible);
652
+ if (truthy !== false) visit(node.consequent, node);
653
+ if (truthy !== true) visit(node.alternate, node);
654
+ return;
655
+ }
656
+ case 'ConditionalExpression': {
657
+ visit(node.test, node);
658
+ const truthy = constant_truthiness(node.test, visible);
659
+ if (truthy !== false) visit(node.consequent, node);
660
+ if (truthy !== true) visit(node.alternate, node);
661
+ return;
662
+ }
663
+ case 'LogicalExpression': {
664
+ visit(node.left, node);
665
+ const truthy = constant_truthiness(node.left, visible);
666
+ if (
667
+ !(node.operator === '&&' && truthy === false) &&
668
+ !(node.operator === '||' && truthy === true)
669
+ ) {
670
+ visit(node.right, node);
671
+ }
672
+ return;
673
+ }
674
+ case 'PropertyDefinition':
675
+ case 'MethodDefinition':
676
+ // An instance field runs when an instance is created, and a method
677
+ // when it is called; only a computed key, a decorator or a static
678
+ // field runs with the class.
679
+ if (node.computed) visit(node.key, node);
680
+ visit(/** @type {{ decorators?: AST.Node[] }} */ (node).decorators, node);
681
+ if (node.type === 'PropertyDefinition' && node.static) visit(node.value, node);
682
+ return;
683
+ }
684
+
685
+ if (node.type.startsWith('TS') && !RUNTIME_TS_NODE_TYPES.has(node.type)) return;
686
+ visit_children(node);
687
+ };
688
+
689
+ /** @param {AST.Node} node */
690
+ const visit_children = (node) => {
691
+ const record = /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (node));
692
+ for (const key of Object.keys(record)) {
693
+ if (key === 'metadata' || key === 'loc' || key === 'start' || key === 'end') continue;
694
+ visit(record[key], node);
695
+ }
696
+ };
697
+
698
+ visit(root, undefined);
699
+ return found;
700
+ }
701
+
702
+ /**
703
+ * `constants` without the names `bindings` declare, which a nested scope
704
+ * shadows with values this pass does not know.
705
+ *
706
+ * @param {Map<string, AST.Literal['value']>} constants
707
+ * @param {AST.Node[]} bindings statements, declarations or patterns
708
+ * @returns {Map<string, AST.Literal['value']>}
709
+ */
710
+ function forget_declared(constants, bindings) {
711
+ if (constants.size === 0) return constants;
712
+ /** @type {Set<string>} */
713
+ const declared = new Set();
714
+ for (const binding of bindings) {
715
+ const node =
716
+ binding.type === 'ExportNamedDeclaration' && binding.declaration
717
+ ? binding.declaration
718
+ : binding;
719
+ if (node.type === 'VariableDeclaration') {
720
+ for (const declarator of node.declarations) collect_pattern_names(declarator.id, declared);
721
+ } else if (
722
+ (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') &&
723
+ node.id
724
+ ) {
725
+ declared.add(node.id.name);
726
+ } else {
727
+ collect_pattern_names(node, declared);
728
+ }
729
+ }
730
+ if (![...declared].some((name) => constants.has(name))) return constants;
731
+ const visible = new Map(constants);
732
+ for (const name of declared) visible.delete(name);
733
+ return visible;
734
+ }
735
+
736
+ /**
737
+ * Whether a statement list declares `name` in its own scope.
738
+ *
739
+ * @param {AST.Node[]} statements
740
+ * @param {string} name
741
+ * @returns {boolean}
742
+ */
743
+ function declares_lexically(statements, name) {
744
+ for (const statement of statements) {
745
+ const declaration =
746
+ statement.type === 'ExportNamedDeclaration' && statement.declaration
747
+ ? statement.declaration
748
+ : statement;
749
+ if (declaration.type === 'VariableDeclaration' && declaration.kind !== 'var') {
750
+ if (get_pattern_names(declaration.declarations.map((d) => d.id)).has(name)) return true;
751
+ } else if (
752
+ (declaration.type === 'FunctionDeclaration' || declaration.type === 'ClassDeclaration') &&
753
+ declaration.id?.name === name
754
+ ) {
755
+ return true;
756
+ }
757
+ }
758
+ return false;
759
+ }
760
+
761
+ /**
762
+ * Whether defining the component reads a binding that `passed`, the
763
+ * statements it would move above, declares, assigns or mutates. vue-jsx-vapor evaluates a
764
+ * destructured prop default that names a binding when the component is
765
+ * defined; every name read in the props pattern's defaults is counted.
766
+ *
767
+ * @param {AST.VariableDeclaration} declaration
768
+ * @param {AST.Node[]} passed
769
+ * @returns {boolean}
770
+ */
771
+ function initializer_reads_declared(declaration, passed) {
772
+ const call = /** @type {AST.CallExpression} */ (declaration.declarations[0]?.init);
773
+ const fn = /** @type {AST.Function | undefined} */ (call?.arguments?.[0]);
774
+ const reads = new Set();
775
+ collect_default_reads(fn?.params?.[0], undefined, reads);
776
+ if (reads.size === 0) return false;
777
+
778
+ /** @type {Set<string>} */
779
+ const declared = new Set();
780
+ for (const statement of passed) {
781
+ const node =
782
+ (statement.type === 'ExportNamedDeclaration' ||
783
+ statement.type === 'ExportDefaultDeclaration') &&
784
+ statement.declaration
785
+ ? statement.declaration
786
+ : statement;
787
+ if (node.type === 'VariableDeclaration') {
788
+ for (const declarator of node.declarations) collect_pattern_names(declarator.id, declared);
789
+ } else if (
790
+ (node.type === 'FunctionDeclaration' || node.type === 'ClassDeclaration') &&
791
+ node.id
792
+ ) {
793
+ declared.add(node.id.name);
794
+ } else if (
795
+ // An enum, a namespace or an `import x = …` alias compiles to a binding
796
+ // it sets when it runs; an ambient or type-only one has no code.
797
+ (node.type === 'TSEnumDeclaration' ||
798
+ node.type === 'TSModuleDeclaration' ||
799
+ (node.type === 'TSImportEqualsDeclaration' && node.importKind !== 'type')) &&
800
+ !('declare' in node && node.declare) &&
801
+ node.id.type === 'Identifier'
802
+ ) {
803
+ declared.add(node.id.name);
804
+ }
805
+ collect_function_var_names(statement, declared);
806
+ collect_assigned_names(statement, declared);
807
+ }
808
+ for (const read of reads) {
809
+ if (declared.has(read)) return true;
810
+ }
811
+ return false;
812
+ }
813
+
814
+ /**
815
+ * The bindings `node` assigns, updates or mutates the properties of, at any
816
+ * depth: a default that reads one of them could see a different value once
817
+ * the component moves above the assignment.
818
+ *
819
+ * @param {unknown} value
820
+ * @param {Set<string>} names
821
+ * @returns {void}
822
+ */
823
+ function collect_assigned_names(value, names) {
824
+ if (!value || typeof value !== 'object') return;
825
+ if (Array.isArray(value)) {
826
+ for (const child of value) collect_assigned_names(child, names);
827
+ return;
828
+ }
829
+ const node = /** @type {AST.Node} */ (value);
830
+ if (typeof node.type !== 'string') return;
831
+ if (node.type === 'AssignmentExpression') collect_assigned_target(node.left, names);
832
+ else if (node.type === 'UpdateExpression') collect_assigned_target(node.argument, names);
833
+ else if (node.type === 'UnaryExpression' && node.operator === 'delete') {
834
+ collect_assigned_target(node.argument, names);
835
+ } else if (
836
+ (node.type === 'ForInStatement' || node.type === 'ForOfStatement') &&
837
+ node.left.type !== 'VariableDeclaration'
838
+ ) {
839
+ collect_assigned_target(node.left, names);
840
+ }
841
+ const record = /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (node));
842
+ for (const key of Object.keys(record)) {
843
+ if (key === 'metadata' || key === 'loc' || key === 'start' || key === 'end') continue;
844
+ collect_assigned_names(record[key], names);
845
+ }
846
+ }
847
+
848
+ /**
849
+ * The bindings an assignment target writes or mutates: each name in a
850
+ * pattern, and the object a member target belongs to, seen through
851
+ * parentheses, optional chains and TypeScript wrappers such as
852
+ * `(cfg as any).size` and `cfg!.size`.
853
+ *
854
+ * @param {AST.Node | null | undefined} target
855
+ * @param {Set<string>} names
856
+ * @returns {void}
857
+ */
858
+ function collect_assigned_target(target, names) {
859
+ if (!target) return;
860
+ switch (target.type) {
861
+ case 'Identifier':
862
+ names.add(target.name);
863
+ return;
864
+ case 'MemberExpression':
865
+ collect_assigned_target(/** @type {AST.Node} */ (target.object), names);
866
+ return;
867
+ case 'RestElement':
868
+ collect_assigned_target(target.argument, names);
869
+ return;
870
+ case 'AssignmentPattern':
871
+ collect_assigned_target(target.left, names);
872
+ return;
873
+ case 'ArrayPattern':
874
+ for (const element of target.elements) collect_assigned_target(element, names);
875
+ return;
876
+ case 'ObjectPattern':
877
+ for (const property of target.properties) {
878
+ collect_assigned_target(property.type === 'Property' ? property.value : property, names);
879
+ }
880
+ return;
881
+ }
882
+ if (
883
+ (target.type === 'ParenthesizedExpression' ||
884
+ target.type === 'ChainExpression' ||
885
+ RUNTIME_TS_NODE_TYPES.has(target.type)) &&
886
+ 'expression' in target
887
+ ) {
888
+ collect_assigned_target(/** @type {AST.Node} */ (target.expression), names);
889
+ }
890
+ }
891
+
892
+ /**
893
+ * The names read by the default values in a parameter pattern, outside
894
+ * nested functions.
895
+ *
896
+ * @param {unknown} value
897
+ * @param {AST.Node | undefined} parent
898
+ * @param {Set<string>} reads
899
+ * @param {boolean} [in_default]
900
+ * @returns {void}
901
+ */
902
+ function collect_default_reads(value, parent, reads, in_default = false) {
903
+ if (!value || typeof value !== 'object') return;
904
+ if (Array.isArray(value)) {
905
+ for (const child of value) collect_default_reads(child, parent, reads, in_default);
906
+ return;
907
+ }
908
+ const node = /** @type {AST.Node} */ (value);
909
+ if (typeof node.type !== 'string') return;
910
+ if (
911
+ node.type === 'FunctionExpression' ||
912
+ node.type === 'ArrowFunctionExpression' ||
913
+ (node.type.startsWith('TS') && !RUNTIME_TS_NODE_TYPES.has(node.type))
914
+ ) {
915
+ return;
916
+ }
917
+ if (node.type === 'AssignmentPattern') {
918
+ collect_default_reads(node.left, node, reads, in_default);
919
+ collect_default_reads(node.right, node, reads, true);
920
+ return;
921
+ }
922
+ if (node.type === 'Identifier') {
923
+ if (in_default && parent && is_reference(node, parent)) reads.add(node.name);
924
+ return;
925
+ }
926
+ const record = /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (node));
927
+ for (const key of Object.keys(record)) {
928
+ if (key === 'metadata' || key === 'loc' || key === 'start' || key === 'end') continue;
929
+ collect_default_reads(record[key], node, reads, in_default);
930
+ }
931
+ }
932
+
933
+ /**
934
+ * @param {AST.Function} node
935
+ * @param {import('zimmerframe').Context<AST.Node, TransformContext>} context
936
+ * @returns {AST.Node}
937
+ */
938
+ function visit_function_component(node, { next, path, state }) {
939
+ const inner = /** @type {AST.Function} */ (next() ?? node);
940
+ return wrap_native_function_component(inner, node, state, path) ?? inner;
941
+ }
942
+
943
+ /**
944
+ * @param {AST.Function} fn the walked function, which is a copy of `source`
945
+ * when the walk replaced something inside it
946
+ * @param {AST.Function} source the function as it appears in `path`
947
+ * @param {TransformContext} ctx
948
+ * @param {AST.Node[]} path
949
+ * @returns {AST.Expression | AST.VariableDeclaration | null}
950
+ */
951
+ function wrap_native_function_component(fn, source, ctx, path) {
952
+ const parent = path.at(-1);
953
+ const name = get_function_component_name(source, parent);
954
+ if (!name || !/^[A-Z]/.test(name)) {
955
+ return null;
956
+ }
957
+
958
+ if (!fn.metadata?.native_tsrx_function && !returns_local_jsx_binding(fn)) {
959
+ return null;
960
+ }
961
+
962
+ ctx.needs_define_vapor_component = true;
963
+ validate_prop_defaults(fn, ctx);
964
+ validate_props_param(fn, ctx);
965
+ if (!ctx.typeOnly) {
966
+ fn = read_children_from_default_slot(fn, name, ctx);
967
+ }
968
+
969
+ const call = setLocation(
970
+ create_define_vapor_component_call(
971
+ function_declaration_to_expression(fn),
972
+ fn.metadata?.generated_helpers || [],
973
+ fn.metadata?.generated_statics || [],
974
+ ),
975
+ has_location(fn) ? fn : undefined,
976
+ true,
977
+ );
978
+
979
+ if (fn.type !== 'FunctionDeclaration') {
980
+ return call;
981
+ }
982
+
983
+ if (!fn.id) {
984
+ return call;
985
+ }
986
+
987
+ const declaration = setLocation(
988
+ b.declaration('const', [b.declarator(create_generated_identifier(fn.id.name), call)]),
989
+ has_location(fn) ? fn : undefined,
990
+ true,
991
+ );
992
+ declaration.metadata = { ...declaration.metadata, vue_component_binding: fn.id.name };
993
+ return declaration;
994
+ }
995
+
996
+ /**
997
+ * vue-jsx-vapor turns the defaults in a component's destructured props
998
+ * (`{ size = 1 }`) into prop options, and keeps only a string, number, boolean
999
+ * or `null` literal, an identifier, an object or array literal, or a function,
1000
+ * seen through `as` and `!`. It drops any other default, such as `cfg.size`,
1001
+ * `-1`, `SIZE + 1` or a template literal, so the prop is `undefined` when the
1002
+ * caller leaves it out. Report each one (TSRX2029).
1003
+ *
1004
+ * @param {AST.Function} fn
1005
+ * @param {TransformContext} ctx
1006
+ * @returns {void}
1007
+ */
1008
+ function validate_prop_defaults(fn, ctx) {
1009
+ const param = fn.params[0];
1010
+ if (param?.type !== 'ObjectPattern') return;
1011
+ for (const property of param.properties) {
1012
+ if (
1013
+ property.type !== 'Property' ||
1014
+ property.computed ||
1015
+ property.key.type !== 'Identifier' ||
1016
+ // A `children` default moves out of the props pattern into its reads
1017
+ // (see `read_children_from_default_slot`), so the macro never sees it.
1018
+ property.key.name === 'children' ||
1019
+ property.value.type !== 'AssignmentPattern' ||
1020
+ is_kept_prop_default(property.value.right)
1021
+ ) {
1022
+ continue;
1023
+ }
1024
+ const name = property.key.name;
1025
+ error(
1026
+ TSRX_ERRORS.TARGET_PROP_DEFAULT_UNSUPPORTED(
1027
+ ctx.platform.name,
1028
+ name,
1029
+ get_prop_read_example(property.value, `props.${name}`, ctx),
1030
+ ),
1031
+ ctx.filename,
1032
+ property.value.right,
1033
+ ctx.errors,
1034
+ ctx.comments,
1035
+ );
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * Check a component's props parameter the way vue-jsx-vapor's props macro
1041
+ * reads it (TSRX2031, and TSRX2029 for a default inside a prop):
1042
+ *
1043
+ * - It skips a props parameter with a default (`{ s } = {}`), so the
1044
+ * component gets no prop options and Vue passes it no props.
1045
+ * - It reads destructured props by name, and reads only keys that are names:
1046
+ * it reads `{ [k]: v }` as the prop `k`, whatever `k` holds, and leaves out
1047
+ * any other key (`{ 'a-b': v }`, `{ [1]: v }`), so its binding never gets
1048
+ * the prop. That holds at every level, and a pattern with no key it reads
1049
+ * also gets no prop options.
1050
+ * - Inside a prop, it applies a default only when the whole prop is missing.
1051
+ * - It doesn't keep a rest element inside a prop as the rest of that prop:
1052
+ * the pattern's last rest element gets the component's attrs, an array's
1053
+ * gets the whole array, and any other gets the rest as it was at setup.
1054
+ *
1055
+ * @param {AST.Function} fn
1056
+ * @param {TransformContext} ctx
1057
+ * @returns {void}
1058
+ */
1059
+ function validate_props_param(fn, ctx) {
1060
+ const param = fn.params[0];
1061
+ if (param?.type === 'AssignmentPattern') {
1062
+ error(
1063
+ TSRX_ERRORS.TARGET_PROPS_PARAM_DEFAULT(ctx.platform.name, get_inline_text(param.right, ctx)),
1064
+ ctx.filename,
1065
+ param.right,
1066
+ ctx.errors,
1067
+ ctx.comments,
1068
+ );
1069
+ return;
1070
+ }
1071
+ if (param?.type === 'ObjectPattern') validate_prop_keys(param, 'props', false, ctx);
1072
+ }
1073
+
1074
+ /**
1075
+ * @param {AST.RestElement} rest a rest element inside a prop
1076
+ * @param {string} object how the body reads the value it destructures
1077
+ * @param {TransformContext} ctx
1078
+ * @returns {void}
1079
+ */
1080
+ function report_prop_rest(rest, object, ctx) {
1081
+ error(
1082
+ TSRX_ERRORS.TARGET_PROP_NESTED_REST(ctx.platform.name, get_prop_path(object)),
1083
+ ctx.filename,
1084
+ rest,
1085
+ ctx.errors,
1086
+ ctx.comments,
1087
+ );
1088
+ }
1089
+
1090
+ /**
1091
+ * @param {AST.ObjectPattern} pattern
1092
+ * @param {string} object how the body reads the value the pattern destructures
1093
+ * @param {boolean} nested whether the pattern is inside a prop
1094
+ * @param {TransformContext} ctx
1095
+ * @returns {void}
1096
+ */
1097
+ function validate_prop_keys(pattern, object, nested, ctx) {
1098
+ for (const property of pattern.properties) {
1099
+ if (property.type === 'RestElement') {
1100
+ // The pattern's own rest element gets the attrs: the props it doesn't
1101
+ // declare.
1102
+ if (nested) report_prop_rest(property, object, ctx);
1103
+ continue;
1104
+ }
1105
+ const key = property.key;
1106
+ if (!property.computed && key.type === 'Identifier') {
1107
+ validate_prop_value(
1108
+ property.value,
1109
+ join_prop_member(object, `.${key.name}`, nested),
1110
+ nested,
1111
+ ctx,
1112
+ );
1113
+ continue;
1114
+ }
1115
+ const written = get_inline_text(key, ctx);
1116
+ const example = get_prop_read_example(
1117
+ property.value,
1118
+ join_prop_member(object, get_prop_member_access(key, written, !nested), nested),
1119
+ ctx,
1120
+ );
1121
+ error(
1122
+ property.computed && key.type === 'Identifier'
1123
+ ? TSRX_ERRORS.TARGET_PROP_KEY_COMPUTED(ctx.platform.name, key.name, example)
1124
+ : TSRX_ERRORS.TARGET_PROP_KEY_UNSUPPORTED(
1125
+ ctx.platform.name,
1126
+ property.computed ? `[${written}]` : written,
1127
+ example,
1128
+ ),
1129
+ ctx.filename,
1130
+ key,
1131
+ ctx.errors,
1132
+ ctx.comments,
1133
+ );
1134
+ }
1135
+ }
1136
+
1137
+ /**
1138
+ * Check the pattern a prop, or a value inside one, is destructured with. A
1139
+ * prop's own default is checked as TSRX2029 by `validate_prop_defaults`.
1140
+ *
1141
+ * @param {AST.Pattern} pattern
1142
+ * @param {string} object how the body reads the value
1143
+ * @param {boolean} nested whether the value is inside a prop
1144
+ * @param {TransformContext} ctx
1145
+ * @returns {void}
1146
+ */
1147
+ function validate_prop_value(pattern, object, nested, ctx) {
1148
+ if (pattern.type === 'AssignmentPattern') {
1149
+ if (nested) {
1150
+ error(
1151
+ TSRX_ERRORS.TARGET_PROP_NESTED_DEFAULT_UNSUPPORTED(
1152
+ ctx.platform.name,
1153
+ get_prop_path(object),
1154
+ get_prop_read_example(pattern, object, ctx),
1155
+ ),
1156
+ ctx.filename,
1157
+ pattern.right,
1158
+ ctx.errors,
1159
+ ctx.comments,
1160
+ );
1161
+ }
1162
+ validate_prop_value(pattern.left, object, nested, ctx);
1163
+ } else if (pattern.type === 'ObjectPattern') {
1164
+ validate_prop_keys(pattern, object, true, ctx);
1165
+ } else if (pattern.type === 'ArrayPattern') {
1166
+ pattern.elements.forEach((element, index) => {
1167
+ if (element?.type === 'RestElement') {
1168
+ report_prop_rest(element, object, ctx);
1169
+ } else if (element) {
1170
+ validate_prop_value(element, join_prop_member(object, `[${index}]`, true), true, ctx);
1171
+ }
1172
+ });
1173
+ }
1174
+ }
1175
+
1176
+ /**
1177
+ * Read a member of a prop's value with optional chaining, since the prop
1178
+ * itself can be missing.
1179
+ *
1180
+ * @param {string} object
1181
+ * @param {string} member `.name` or `[key]`
1182
+ * @param {boolean} nested whether `object` is a prop's value, not the props
1183
+ * @returns {string}
1184
+ */
1185
+ function join_prop_member(object, member, nested) {
1186
+ return nested
1187
+ ? `${object}?.${member.startsWith('.') ? member.slice(1) : member}`
1188
+ : object + member;
1189
+ }
1190
+
1191
+ /**
1192
+ * A value's path in the props as the messages show it, such as `s.a`.
1193
+ *
1194
+ * @param {string} object
1195
+ * @returns {string}
1196
+ */
1197
+ function get_prop_path(object) {
1198
+ return object.slice('props.'.length).replace(/\?\.(\[)?/g, (_, bracket) => bracket ?? '.');
1199
+ }
1200
+
1201
+ /**
1202
+ * How the body reads the member at `key`. Vue camelizes a prop's name, so a
1203
+ * top-level `'a-b'` prop is `props.aB`.
1204
+ *
1205
+ * @param {AST.Expression | AST.PrivateIdentifier} key
1206
+ * @param {string} written the key as written
1207
+ * @param {boolean} top whether the key names a prop
1208
+ * @returns {string}
1209
+ */
1210
+ function get_prop_member_access(key, written, top) {
1211
+ const name =
1212
+ key.type === 'Literal' && typeof key.value === 'string'
1213
+ ? key.value
1214
+ : key.type === 'TemplateLiteral' && key.expressions.length === 0
1215
+ ? key.quasis[0].value.cooked
1216
+ : null;
1217
+ if (name == null) return `[${written}]`;
1218
+ const member = top ? name.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()) : name;
1219
+ return /^[A-Za-z_$][\w$]*$/.test(member) ? `.${member}` : `[${JSON.stringify(member)}]`;
1220
+ }
1221
+
1222
+ /**
1223
+ * An expression that reads the value at `access` where it is used, with the
1224
+ * pattern's default, or an empty string when the pattern binds more than a
1225
+ * name or its default spans lines.
1226
+ *
1227
+ * @param {AST.Pattern} value
1228
+ * @param {string} access
1229
+ * @param {TransformContext} ctx
1230
+ * @returns {string}
1231
+ */
1232
+ function get_prop_read_example(value, access, ctx) {
1233
+ if (value.type === 'Identifier') return `{${access}}`;
1234
+ if (value.type !== 'AssignmentPattern' || value.left.type !== 'Identifier') return '';
1235
+ const fallback = get_source_text(value.right, ctx);
1236
+ // A default replaces only `undefined`, so `??`, which also replaces `null`,
1237
+ // would not read the same.
1238
+ return fallback === null ? '' : `{${access} === undefined ? ${fallback} : ${access}}`;
1239
+ }
1240
+
1241
+ /**
1242
+ * A node's source text, on one line.
1243
+ *
1244
+ * @param {AST.Node} node
1245
+ * @param {TransformContext} ctx
1246
+ * @returns {string}
1247
+ */
1248
+ function get_inline_text(node, ctx) {
1249
+ if (ctx.source && node.start != null && node.end != null) {
1250
+ return ctx.source.slice(node.start, node.end).replace(/\s*\n\s*/g, ' ');
1251
+ }
1252
+ return node.type === 'Identifier'
1253
+ ? node.name
1254
+ : node.type === 'Literal'
1255
+ ? String(node.value)
1256
+ : '…';
1257
+ }
1258
+
1259
+ /**
1260
+ * @param {AST.Node} node
1261
+ * @param {TransformContext} ctx
1262
+ * @returns {string | null} the node's source text, when it is on one line
1263
+ */
1264
+ function get_source_text(node, ctx) {
1265
+ const text =
1266
+ ctx.source && node.start != null && node.end != null
1267
+ ? ctx.source.slice(node.start, node.end)
1268
+ : null;
1269
+ return text && !text.includes('\n') ? text : null;
1270
+ }
1271
+
1272
+ /**
1273
+ * @param {AST.Node} node
1274
+ * @returns {boolean}
1275
+ */
1276
+ function is_kept_prop_default(node) {
1277
+ switch (node.type) {
1278
+ case 'TSAsExpression':
1279
+ case 'TSNonNullExpression':
1280
+ case 'ParenthesizedExpression':
1281
+ return is_kept_prop_default(/** @type {AST.Node} */ (node.expression));
1282
+ case 'Literal':
1283
+ // vue-jsx-vapor parses a regular expression or a bigint as its own
1284
+ // literal kind, which it drops.
1285
+ return !('regex' in node && node.regex) && !('bigint' in node && node.bigint);
1286
+ case 'Identifier':
1287
+ case 'ObjectExpression':
1288
+ case 'ArrayExpression':
1289
+ case 'ArrowFunctionExpression':
1290
+ case 'FunctionExpression':
1291
+ return true;
1292
+ default:
1293
+ return false;
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * Whether `fn` builds its output in a local binding and returns that binding
1299
+ * (`const element = <div />; return element;`). The core transform marks only
1300
+ * functions that return JSX directly or have an `@{ … }` body as components.
1301
+ *
1302
+ * @param {AST.Function} fn
1303
+ * @returns {boolean}
1304
+ */
1305
+ function returns_local_jsx_binding(fn) {
1306
+ if (fn.body?.type !== 'BlockStatement') {
1307
+ return false;
1308
+ }
1309
+
1310
+ /** @type {{ jsx_bindings: Set<string>, returned: Set<string> }} */
1311
+ const state = { jsx_bindings: new Set(), returned: new Set() };
1312
+ walk(/** @type {AST.Node} */ (fn.body), state, {
1313
+ FunctionDeclaration() {},
1314
+ FunctionExpression() {},
1315
+ ArrowFunctionExpression() {},
1316
+ VariableDeclarator(node, { state, next }) {
1317
+ if (node.id.type === 'Identifier' && contains_jsx(node.init)) {
1318
+ state.jsx_bindings.add(node.id.name);
1319
+ }
1320
+ next();
1321
+ },
1322
+ AssignmentExpression(node, { state, next }) {
1323
+ if (node.left.type === 'Identifier' && contains_jsx(node.right)) {
1324
+ state.jsx_bindings.add(node.left.name);
1325
+ }
1326
+ next();
1327
+ },
1328
+ ReturnStatement(node, { state, next }) {
1329
+ if (node.argument?.type === 'Identifier') {
1330
+ state.returned.add(node.argument.name);
1331
+ }
1332
+ next();
1333
+ },
1334
+ });
1335
+
1336
+ for (const name of state.returned) {
1337
+ if (state.jsx_bindings.has(name)) {
1338
+ return true;
1339
+ }
1340
+ }
1341
+ return false;
1342
+ }
1343
+
1344
+ /**
1345
+ * @param {AST.Node | null | undefined} node
1346
+ * @returns {boolean}
1347
+ */
1348
+ function contains_jsx(node) {
1349
+ if (!node) {
1350
+ return false;
1351
+ }
1352
+
1353
+ let found = false;
1354
+ walk(node, null, {
1355
+ FunctionDeclaration() {},
1356
+ FunctionExpression() {},
1357
+ ArrowFunctionExpression() {},
1358
+ JSXElement() {
1359
+ found = true;
1360
+ },
1361
+ JSXFragment() {
1362
+ found = true;
1363
+ },
1364
+ });
1365
+ return found;
1366
+ }
1367
+
1368
+ /** Local name of the `useSlots` import a component reads its children through. */
1369
+ const USE_SLOTS_INTERNAL_NAME = `${IDENTIFIER_OBFUSCATION_PREFIX}useSlots`;
1370
+
1371
+ /**
1372
+ * vue-jsx-vapor passes a component's nested children as its default slot, not
1373
+ * as a `children` prop. Read `props.children`, or a `children` binding
1374
+ * destructured from the props parameter or from `props` at the top of the
1375
+ * body, as the default slot when the caller passes nested children and as the
1376
+ * `children` prop otherwise, so the same source renders its children on every
1377
+ * target. Nested children win over a `children` prop, as on React.
1378
+ *
1379
+ * Each place that renders the children renders the slot there
1380
+ * (`_$_Card_slots.default?.() ?? props.children`), so the children are set up
1381
+ * when that place shows them and torn down when it hides them, as React
1382
+ * mounts and unmounts them. A read that only tests the children (the
1383
+ * condition of `?:` or `if`, an operand of `!`, the left side of `&&`) checks
1384
+ * whether the slot exists instead (`_$_Card_slots.default ?? props.children`),
1385
+ * so `props.children ? <div>{props.children}</div> : …` sets them up once.
1386
+ * A slot exists whenever the caller writes nested children, even when they
1387
+ * render nothing.
1388
+ *
1389
+ * @param {AST.Function} fn
1390
+ * @param {string} name the component's name
1391
+ * @param {TransformContext} ctx
1392
+ * @returns {AST.Function}
1393
+ */
1394
+ function read_children_from_default_slot(fn, name, ctx) {
1395
+ const param = fn.params[0];
1396
+ /** @type {ChildrenReadState} */
1397
+ const state = {
1398
+ props_name: param?.type === 'Identifier' ? param.name : null,
1399
+ children_names: new Set(),
1400
+ children_defaults: new Map(),
1401
+ shadowed_names: new Set(),
1402
+ slots_id: create_generated_identifier(
1403
+ `${IDENTIFIER_OBFUSCATION_PREFIX}${name.replace(/[^\w$]/g, '_')}_slots`,
1404
+ ),
1405
+ // Shared by reference: the scope visitors copy the state for each scope.
1406
+ rewrites: { count: 0 },
1407
+ };
1408
+ let params = fn.params;
1409
+ if (param?.type === 'ObjectPattern') {
1410
+ add_children_binding_names(param, state.children_names);
1411
+ const without_defaults = remove_children_defaults(param, state.children_defaults);
1412
+ if (without_defaults !== param) params = [without_defaults, ...fn.params.slice(1)];
1413
+ }
1414
+ // `const { children } = props;` at the top of the component body.
1415
+ for (const statement of fn.body.type === 'BlockStatement' ? fn.body.body : []) {
1416
+ if (statement.type !== 'VariableDeclaration') continue;
1417
+ for (const declarator of statement.declarations) {
1418
+ if (
1419
+ declarator.id.type === 'ObjectPattern' &&
1420
+ declarator.init?.type === 'Identifier' &&
1421
+ declarator.init.name === state.props_name
1422
+ ) {
1423
+ add_children_binding_names(declarator.id, state.children_names);
1424
+ }
1425
+ }
1426
+ }
1427
+ if (!state.props_name && state.children_names.size === 0) {
1428
+ return fn;
1429
+ }
1430
+
1431
+ /**
1432
+ * @param {AST.Node} node
1433
+ * @param {import('zimmerframe').Context<AST.Node, ChildrenReadState>} context
1434
+ */
1435
+ const shadow_head = (node, { state, next }) => {
1436
+ /** @type {AST.Node[]} */
1437
+ const bindings = [];
1438
+ if (node.type === 'CatchClause' && node.param) bindings.push(node.param);
1439
+ const head =
1440
+ node.type === 'ForStatement'
1441
+ ? node.init
1442
+ : node.type === 'ForInStatement' || node.type === 'ForOfStatement'
1443
+ ? node.left
1444
+ : null;
1445
+ if (head?.type === 'VariableDeclaration') {
1446
+ for (const declarator of head.declarations) bindings.push(declarator.id);
1447
+ }
1448
+ if (bindings.length === 0) return next();
1449
+ const shadowed_names = new Set(state.shadowed_names);
1450
+ for (const binding of bindings) collect_pattern_names(binding, shadowed_names);
1451
+ return next({ ...state, shadowed_names });
1452
+ };
1453
+
1454
+ const body = /** @type {AST.BlockStatement | AST.Expression} */ (
1455
+ walk(/** @type {AST.Node} */ (fn.body), state, {
1456
+ ChainExpression(node, { path, state, next }) {
1457
+ if (
1458
+ node.expression.type === 'MemberExpression' &&
1459
+ is_props_children_read(node.expression, path.at(-1), state)
1460
+ ) {
1461
+ return read_children_or_default_slot(node, path.at(-1), state);
1462
+ }
1463
+ return next();
1464
+ },
1465
+ MemberExpression(node, { path, state, next }) {
1466
+ if (is_props_children_read(node, path.at(-1), state)) {
1467
+ return read_children_or_default_slot(node, path.at(-1), state);
1468
+ }
1469
+ return next();
1470
+ },
1471
+ Property(node, { path, state, next }) {
1472
+ const value = node.value;
1473
+ if (
1474
+ node.shorthand &&
1475
+ path.at(-1)?.type === 'ObjectExpression' &&
1476
+ value.type === 'Identifier' &&
1477
+ is_children_binding(value, state)
1478
+ ) {
1479
+ return {
1480
+ ...node,
1481
+ shorthand: false,
1482
+ value: read_children_or_default_slot(value, node, state),
1483
+ };
1484
+ }
1485
+ return next();
1486
+ },
1487
+ Identifier(node, { path, state, next }) {
1488
+ const parent = path.at(-1);
1489
+ if (
1490
+ is_children_binding(node, state) &&
1491
+ parent &&
1492
+ is_runtime_reference(node, parent) &&
1493
+ !is_assignment_target(node, parent) &&
1494
+ !is_binding_position(node, parent, path.at(-2))
1495
+ ) {
1496
+ return read_children_or_default_slot(node, parent, state);
1497
+ }
1498
+ return next();
1499
+ },
1500
+ FunctionDeclaration: rewrite_function_shadowed_refs,
1501
+ FunctionExpression: rewrite_function_shadowed_refs,
1502
+ ArrowFunctionExpression: rewrite_function_shadowed_refs,
1503
+ CatchClause: shadow_head,
1504
+ ForStatement: shadow_head,
1505
+ ForInStatement: shadow_head,
1506
+ ForOfStatement: shadow_head,
1507
+ BlockStatement(node, context) {
1508
+ // The component body declares the destructured `children` binding;
1509
+ // it cannot redeclare the props parameter or its bindings.
1510
+ if (context.path.length === 0) return context.next();
1511
+ return rewrite_block_shadowed_refs(node, context);
1512
+ },
1513
+ })
1514
+ );
1515
+ if (state.rewrites.count === 0) {
1516
+ return fn;
1517
+ }
1518
+
1519
+ ctx.needs_use_slots = true;
1520
+ // `const _$_Card_slots = _$_useSlots();`
1521
+ const slot_declaration = b.const(state.slots_id, b.call(USE_SLOTS_INTERNAL_NAME));
1522
+ const statements =
1523
+ body.type === 'BlockStatement' ? body.body : [b.return(/** @type {AST.Expression} */ (body))];
1524
+ return /** @type {AST.Function} */ ({
1525
+ ...fn,
1526
+ params,
1527
+ body: b.block(
1528
+ [slot_declaration, ...statements],
1529
+ body.type === 'BlockStatement' && has_location(body) ? body : undefined,
1530
+ ),
1531
+ ...(fn.type === 'ArrowFunctionExpression' ? { expression: false } : null),
1532
+ });
1533
+ }
1534
+
1535
+ /**
1536
+ * @typedef {{
1537
+ * props_name: string | null,
1538
+ * children_names: Set<string>,
1539
+ * children_defaults: Map<string, AST.Expression>,
1540
+ * shadowed_names: Set<string>,
1541
+ * slots_id: AST.Identifier,
1542
+ * rewrites: { count: number },
1543
+ * }} ChildrenReadState
1544
+ */
1545
+
1546
+ /**
1547
+ * @param {AST.ObjectPattern} pattern
1548
+ * @param {Set<string>} names
1549
+ * @returns {void}
1550
+ */
1551
+ function add_children_binding_names(pattern, names) {
1552
+ for (const property of pattern.properties) {
1553
+ if (property.type !== 'Property' || property.computed) continue;
1554
+ if (get_static_name(property.key) !== 'children') continue;
1555
+ const value =
1556
+ property.value.type === 'AssignmentPattern' ? property.value.left : property.value;
1557
+ if (value.type === 'Identifier') names.add(value.name);
1558
+ }
1559
+ }
1560
+
1561
+ /**
1562
+ * Drop the default of a destructured `children` parameter (`{ children = x }`)
1563
+ * and record it, so a read can fall back from the slot to the prop to the
1564
+ * default. Left in place, vue-jsx-vapor would turn it into the prop's default,
1565
+ * which would hide the slot.
1566
+ *
1567
+ * @param {AST.ObjectPattern} pattern
1568
+ * @param {Map<string, AST.Expression>} defaults
1569
+ * @returns {AST.ObjectPattern}
1570
+ */
1571
+ function remove_children_defaults(pattern, defaults) {
1572
+ let changed = false;
1573
+ const properties = pattern.properties.map((property) => {
1574
+ if (
1575
+ property.type !== 'Property' ||
1576
+ property.computed ||
1577
+ get_static_name(property.key) !== 'children' ||
1578
+ property.value.type !== 'AssignmentPattern' ||
1579
+ property.value.left.type !== 'Identifier'
1580
+ ) {
1581
+ return property;
1582
+ }
1583
+ changed = true;
1584
+ defaults.set(property.value.left.name, property.value.right);
1585
+ return { ...property, value: property.value.left };
1586
+ });
1587
+ return changed ? { ...pattern, properties } : pattern;
1588
+ }
1589
+
1590
+ /**
1591
+ * @param {AST.Identifier} node
1592
+ * @param {AST.Node} parent
1593
+ * @param {AST.Node | undefined} grandparent
1594
+ * @returns {boolean}
361
1595
  */
362
- function wrap_helper_component(helper_fn, helper_id, source_node) {
363
- return setLocation(
364
- b.declaration('const', [
365
- b.declarator(
366
- clone_identifier(helper_id),
367
- create_define_vapor_component_call(function_declaration_to_expression(helper_fn), [], []),
368
- ),
369
- ]),
370
- source_node,
1596
+ function is_binding_position(node, parent, grandparent) {
1597
+ return (
1598
+ (parent.type === 'VariableDeclarator' && parent.id === node) ||
1599
+ (parent.type === 'Property' && grandparent?.type === 'ObjectPattern') ||
1600
+ parent.type === 'ArrayPattern' ||
1601
+ parent.type === 'RestElement' ||
1602
+ parent.type === 'CatchClause' ||
1603
+ (parent.type === 'AssignmentPattern' && parent.left === node)
371
1604
  );
372
1605
  }
373
1606
 
374
1607
  /**
375
- * @param {AST.Program} program
376
- * @param {TransformContext} ctx
377
- * @returns {void}
1608
+ * @param {AST.MemberExpression} node
1609
+ * @param {AST.Node | undefined} parent
1610
+ * @param {ChildrenReadState} state
1611
+ * @returns {boolean}
378
1612
  */
379
- function wrap_native_function_components(program, ctx) {
380
- const wrapped = walk(program, ctx, {
381
- FunctionDeclaration(node, { next, path, state }) {
382
- const inner = next() ?? node;
383
- return (
384
- wrap_native_function_component(/** @type {AST.Function} */ (inner), state, path) ?? inner
385
- );
386
- },
387
- FunctionExpression(node, { next, path, state }) {
388
- const inner = next() ?? node;
389
- return (
390
- wrap_native_function_component(/** @type {AST.Function} */ (inner), state, path) ?? inner
391
- );
392
- },
393
- ArrowFunctionExpression(node, { next, path, state }) {
394
- const inner = next() ?? node;
395
- return (
396
- wrap_native_function_component(/** @type {AST.Function} */ (inner), state, path) ?? inner
397
- );
398
- },
399
- });
400
- program.body = /** @type {AST.Program} */ (wrapped).body;
1613
+ function is_props_children_read(node, parent, state) {
1614
+ return (
1615
+ !!state.props_name &&
1616
+ !state.shadowed_names.has(state.props_name) &&
1617
+ node.object.type === 'Identifier' &&
1618
+ node.object.name === state.props_name &&
1619
+ (node.computed
1620
+ ? node.property.type === 'Literal' && node.property.value === 'children'
1621
+ : node.property.type === 'Identifier' && node.property.name === 'children') &&
1622
+ !is_assignment_target(node, parent) &&
1623
+ !(parent?.type === 'UnaryExpression' && parent.operator === 'delete')
1624
+ );
401
1625
  }
402
1626
 
403
1627
  /**
404
- * @param {AST.Function} fn
405
- * @param {TransformContext} ctx
406
- * @param {AST.Node[]} path
407
- * @returns {AST.Expression | AST.VariableDeclaration | null}
1628
+ * @param {AST.Identifier} node
1629
+ * @param {ChildrenReadState} state
1630
+ * @returns {boolean}
408
1631
  */
409
- function wrap_native_function_component(fn, ctx, path) {
410
- if (!fn.metadata?.native_tsrx_function) {
411
- return null;
412
- }
413
-
414
- const parent = path.at(-1);
415
- const name = get_function_component_name(fn, parent);
416
- if (!name || !/^[A-Z]/.test(name)) {
417
- return null;
418
- }
419
-
420
- ctx.needs_define_vapor_component = true;
1632
+ function is_children_binding(node, state) {
1633
+ return state.children_names.has(node.name) && !state.shadowed_names.has(node.name);
1634
+ }
421
1635
 
422
- const call = setLocation(
423
- create_define_vapor_component_call(
424
- function_declaration_to_expression(fn),
425
- fn.metadata?.generated_helpers || [],
426
- fn.metadata?.generated_statics || [],
427
- ),
428
- has_location(fn) ? fn : undefined,
429
- true,
1636
+ /**
1637
+ * @param {AST.Node} node
1638
+ * @param {AST.Node | undefined} parent
1639
+ * @returns {boolean}
1640
+ */
1641
+ function is_assignment_target(node, parent) {
1642
+ return (
1643
+ (parent?.type === 'AssignmentExpression' && parent.left === node) ||
1644
+ parent?.type === 'UpdateExpression'
430
1645
  );
1646
+ }
431
1647
 
432
- if (fn.type !== 'FunctionDeclaration') {
433
- return call;
434
- }
435
-
436
- if (parent?.type === 'ExportDefaultDeclaration' && parent.declaration === fn) {
437
- return call;
438
- }
1648
+ /**
1649
+ * `_$_Card_slots.default?.() ?? <read>` where the read renders the children,
1650
+ * `_$_Card_slots.default ?? <read>` where it only tests them. A destructured
1651
+ * default applies to the prop as it did in the pattern, only when the prop is
1652
+ * `undefined` (`children === void 0 ? <default> : children`), so an explicit
1653
+ * `children={null}` stays `null`.
1654
+ *
1655
+ * @param {AST.Expression} read
1656
+ * @param {AST.Node | undefined} parent
1657
+ * @param {ChildrenReadState} state
1658
+ * @returns {AST.Expression}
1659
+ */
1660
+ function read_children_or_default_slot(read, parent, state) {
1661
+ state.rewrites.count += 1;
1662
+ const slot = b.member(clone_identifier(state.slots_id), 'default');
1663
+ const fallback = read.type === 'Identifier' ? state.children_defaults.get(read.name) : undefined;
1664
+ const prop =
1665
+ read.type === 'Identifier' && fallback
1666
+ ? b.conditional(
1667
+ b.binary('===', read, b.unary('void', b.literal(0))),
1668
+ clone_ast_node(fallback),
1669
+ clone_identifier(read),
1670
+ )
1671
+ : read;
1672
+ return b.logical('??', is_test_position(read, parent) ? slot : b.maybe_call(slot), prop);
1673
+ }
439
1674
 
440
- if (!fn.id) {
441
- return call;
1675
+ /**
1676
+ * Whether only the truthiness or presence of `node` is used: the condition of
1677
+ * `?:`, `if` or a loop, the operand of `!`, the left side of `&&` (whose value
1678
+ * is used only when it is falsy, and a slot never is), the argument of
1679
+ * `Boolean(…)`, or a side of an equality with `null` or `undefined`.
1680
+ *
1681
+ * @param {AST.Node} node
1682
+ * @param {AST.Node | undefined} parent
1683
+ * @returns {boolean}
1684
+ */
1685
+ function is_test_position(node, parent) {
1686
+ switch (parent?.type) {
1687
+ case 'BinaryExpression': {
1688
+ if (!['==', '!=', '===', '!=='].includes(parent.operator)) return false;
1689
+ const other = parent.left === node ? parent.right : parent.left;
1690
+ return (
1691
+ (other.type === 'Literal' && other.value === null && !('regex' in other)) ||
1692
+ (other.type === 'Identifier' && other.name === 'undefined')
1693
+ );
1694
+ }
1695
+ case 'CallExpression':
1696
+ return (
1697
+ parent.callee.type === 'Identifier' &&
1698
+ parent.callee.name === 'Boolean' &&
1699
+ parent.arguments[0] === node
1700
+ );
1701
+ case 'ConditionalExpression':
1702
+ case 'IfStatement':
1703
+ case 'WhileStatement':
1704
+ case 'DoWhileStatement':
1705
+ case 'ForStatement':
1706
+ return parent.test === node;
1707
+ case 'UnaryExpression':
1708
+ return parent.operator === '!';
1709
+ case 'LogicalExpression':
1710
+ return parent.operator === '&&' && parent.left === node;
1711
+ default:
1712
+ return false;
442
1713
  }
443
-
444
- return setLocation(
445
- b.declaration('const', [b.declarator(create_generated_identifier(fn.id.name), call)]),
446
- has_location(fn) ? fn : undefined,
447
- true,
448
- );
449
1714
  }
450
1715
 
451
1716
  /**
@@ -536,7 +1801,7 @@ function render_for_of_as_vapor_for(node, loop_params, body_statements, transfor
536
1801
  : (find_jsx_key_expression(rendered) ?? (node.index ? clone_ast_node(node.index) : null));
537
1802
 
538
1803
  const slot = key_expression
539
- ? create_keyed_vapor_for_slot(loop_params, rendered)
1804
+ ? create_keyed_vapor_for_slot(loop_params, rendered, transform_context)
540
1805
  : { params: loop_params, body: rendered, expression: true };
541
1806
  if (!slot) {
542
1807
  return null;
@@ -545,7 +1810,7 @@ function render_for_of_as_vapor_for(node, loop_params, body_statements, transfor
545
1810
  transform_context.needs_vapor_for = true;
546
1811
 
547
1812
  if (key_expression) {
548
- strip_top_level_jsx_keys(slot.body);
1813
+ strip_top_level_jsx_keys(slot.rendered ?? slot.body);
549
1814
  }
550
1815
 
551
1816
  const attributes = [
@@ -563,8 +1828,8 @@ function render_for_of_as_vapor_for(node, loop_params, body_statements, transfor
563
1828
 
564
1829
  return to_jsx_expression_container(
565
1830
  b.jsx_element_fresh(
566
- b.jsx_opening_element(b.jsx_id('VaporFor'), attributes),
567
- b.jsx_closing_element(b.jsx_id('VaporFor')),
1831
+ b.jsx_opening_element(b.jsx_id(VAPOR_FOR_INTERNAL_NAME), attributes),
1832
+ b.jsx_closing_element(b.jsx_id(VAPOR_FOR_INTERNAL_NAME)),
568
1833
  [to_jsx_expression_container(create_loop_callback(slot.params, slot.body, slot.expression))],
569
1834
  ),
570
1835
  );
@@ -693,7 +1958,7 @@ function strip_top_level_jsx_keys(node) {
693
1958
 
694
1959
  /**
695
1960
  * @param {AST.Pattern[]} loop_params
696
- * @param {AST.Expression} body
1961
+ * @param {AST.Expression | AST.BlockStatement} body
697
1962
  * @param {boolean} expression
698
1963
  * @returns {AST.ArrowFunctionExpression}
699
1964
  */
@@ -709,9 +1974,10 @@ function create_loop_callback(loop_params, body, expression) {
709
1974
  /**
710
1975
  * @param {AST.Pattern[]} loop_params
711
1976
  * @param {AST.Expression} rendered
712
- * @returns {{ params: AST.Pattern[], body: AST.Expression, expression: boolean } | null}
1977
+ * @param {TransformContext} transform_context
1978
+ * @returns {{ params: AST.Pattern[], body: AST.Expression | AST.BlockStatement, expression: boolean, rendered?: AST.Expression } | null}
713
1979
  */
714
- function create_keyed_vapor_for_slot(loop_params, rendered) {
1980
+ function create_keyed_vapor_for_slot(loop_params, rendered, transform_context) {
715
1981
  if (loop_params[0]?.type === 'Identifier') {
716
1982
  return {
717
1983
  params: loop_params,
@@ -721,6 +1987,16 @@ function create_keyed_vapor_for_slot(loop_params, rendered) {
721
1987
  }
722
1988
 
723
1989
  const item_ref = create_generated_identifier('__vapor_item');
1990
+ if (contains_array_pattern(loop_params[0])) {
1991
+ transform_context.needs_vapor_computed = true;
1992
+ return create_destructured_keyed_vapor_for_slot(
1993
+ loop_params,
1994
+ rendered,
1995
+ item_ref,
1996
+ transform_context,
1997
+ );
1998
+ }
1999
+
724
2000
  const item_ref_value = create_value_member_expression(item_ref);
725
2001
  const replacements = create_pattern_replacements(loop_params[0], item_ref_value);
726
2002
  if (!replacements) {
@@ -741,15 +2017,106 @@ function create_keyed_vapor_for_slot(loop_params, rendered) {
741
2017
  };
742
2018
  }
743
2019
 
2020
+ /**
2021
+ * A keyed slot for an item pattern that property reads can't stand in for:
2022
+ * an array pattern destructures through the item's iterator, so `[a, b]` of
2023
+ * a `Set` or a string is not `item[0]` and `item[1]`. The slot destructures
2024
+ * the item with the authored pattern in a `computed`, which runs once per
2025
+ * item value and keeps the row's reads reactive, and reads each name from it.
2026
+ *
2027
+ * @param {AST.Pattern[]} loop_params
2028
+ * @param {AST.Expression} rendered
2029
+ * @param {AST.Identifier} item_ref
2030
+ * @param {TransformContext} transform_context
2031
+ * @returns {{ params: AST.Pattern[], body: AST.BlockStatement, expression: boolean, rendered: AST.Expression }}
2032
+ */
2033
+ function create_destructured_keyed_vapor_for_slot(
2034
+ loop_params,
2035
+ rendered,
2036
+ item_ref,
2037
+ transform_context,
2038
+ ) {
2039
+ const count = (vapor_bindings_counts.get(transform_context) ?? 0) + 1;
2040
+ vapor_bindings_counts.set(transform_context, count);
2041
+ const bindings_ref = create_generated_identifier(`${VAPOR_BINDINGS_NAME}_${count}`);
2042
+ /** @type {Set<string>} */
2043
+ const names = new Set();
2044
+ collect_pattern_names(loop_params[0], names);
2045
+
2046
+ /** @type {Map<string, AST.Expression>} */
2047
+ const replacements = new Map();
2048
+ for (const name of names) {
2049
+ replacements.set(
2050
+ name,
2051
+ b.member(create_value_member_expression(bindings_ref), create_generated_identifier(name)),
2052
+ );
2053
+ }
2054
+
2055
+ const bindings = b.const(
2056
+ bindings_ref,
2057
+ b.call(
2058
+ VUE_COMPUTED_INTERNAL_NAME,
2059
+ b.arrow(
2060
+ [],
2061
+ b.block([
2062
+ // A default in the pattern reads the index through its ref too.
2063
+ b.const(
2064
+ rewrite_vapor_for_keyed_slot_refs(loop_params[0], loop_params.slice(1)),
2065
+ create_value_member_expression(item_ref),
2066
+ ),
2067
+ b.return(
2068
+ b.object([...names].map((name) => b.prop('init', b.id(name), b.id(name), false, true))),
2069
+ ),
2070
+ ]),
2071
+ ),
2072
+ ),
2073
+ );
2074
+ const rewritten_rendered = rewrite_vapor_for_keyed_slot_refs(
2075
+ rendered,
2076
+ loop_params.slice(1),
2077
+ replacements,
2078
+ );
2079
+
2080
+ return {
2081
+ params: [item_ref, ...loop_params.slice(1)],
2082
+ body: b.block([bindings, b.return(rewritten_rendered)]),
2083
+ expression: false,
2084
+ rendered: rewritten_rendered,
2085
+ };
2086
+ }
2087
+
2088
+ /**
2089
+ * @param {AST.Node | null} node
2090
+ * @returns {boolean}
2091
+ */
2092
+ function contains_array_pattern(node) {
2093
+ if (!node) return false;
2094
+ switch (node.type) {
2095
+ case 'ArrayPattern':
2096
+ return true;
2097
+ case 'ObjectPattern':
2098
+ return node.properties.some((property) =>
2099
+ contains_array_pattern(property.type === 'RestElement' ? property : property.value),
2100
+ );
2101
+ case 'AssignmentPattern':
2102
+ return contains_array_pattern(node.left);
2103
+ case 'RestElement':
2104
+ return contains_array_pattern(node.argument);
2105
+ default:
2106
+ return false;
2107
+ }
2108
+ }
2109
+
744
2110
  /**
745
2111
  * Vue's `VaporFor` passes plain item values to unkeyed slots, but keyed slots
746
2112
  * receive shallow refs so row instances can update in place. Match that runtime
747
2113
  * shape by reading loop params through `.value` inside the slot body.
748
2114
  *
749
- * @param {AST.Expression} node
2115
+ * @template {AST.Node} T
2116
+ * @param {T} node
750
2117
  * @param {AST.Pattern[]} loop_params
751
2118
  * @param {Map<string, AST.Expression>} [replacements]
752
- * @returns {AST.Expression}
2119
+ * @returns {T}
753
2120
  */
754
2121
  function rewrite_vapor_for_keyed_slot_refs(node, loop_params, replacements = new Map()) {
755
2122
  const loop_param_names = new Set();
@@ -761,14 +2128,29 @@ function rewrite_vapor_for_keyed_slot_refs(node, loop_params, replacements = new
761
2128
  return node;
762
2129
  }
763
2130
 
764
- return /** @type {AST.Expression} */ (
2131
+ return /** @type {T} */ (
765
2132
  walk(
766
2133
  node,
767
- { loop_param_names, shadowed_names: new Set() },
2134
+ { loop_param_names, shadowed_names: new Set(), in_type: false },
768
2135
  {
2136
+ _(child, { state, next }) {
2137
+ // A type names no runtime value, so a type parameter or type
2138
+ // reference spelled like a loop param stays as written; only a
2139
+ // `typeof` in a type reads the param.
2140
+ if (child.type === 'TSTypeQuery') {
2141
+ next({ ...state, in_type: false });
2142
+ } else if (is_type_only_node(child)) {
2143
+ next({ ...state, in_type: true });
2144
+ } else {
2145
+ next();
2146
+ }
2147
+ },
769
2148
  Identifier(identifier, { path, state, next }) {
770
2149
  const parent = path.at(-1);
771
2150
  if (
2151
+ !state.in_type &&
2152
+ // `typeof Types.item` reads `Types`; `item` is a member name.
2153
+ !(parent?.type === 'TSQualifiedName' && parent.right === identifier) &&
772
2154
  (state.loop_param_names.has(identifier.name) || replacements.has(identifier.name)) &&
773
2155
  !state.shadowed_names.has(identifier.name) &&
774
2156
  parent &&
@@ -792,6 +2174,28 @@ function rewrite_vapor_for_keyed_slot_refs(node, loop_params, replacements = new
792
2174
  );
793
2175
  }
794
2176
 
2177
+ /**
2178
+ * Whether `node` is TypeScript type syntax: a type annotation, type parameters
2179
+ * or arguments, the type of an `as`, `satisfies`, or `<T>` assertion, or a
2180
+ * type alias or interface declaration.
2181
+ *
2182
+ * @param {AST.Node} node
2183
+ * @returns {boolean}
2184
+ */
2185
+ function is_type_only_node(node) {
2186
+ return (
2187
+ node.type === 'TSTypeAnnotation' ||
2188
+ node.type === 'TSTypeAliasDeclaration' ||
2189
+ node.type === 'TSInterfaceDeclaration' ||
2190
+ node.type === 'TSTypeParameterDeclaration' ||
2191
+ node.type === 'TSTypeParameterInstantiation' ||
2192
+ node.type === 'TSTypeReference' ||
2193
+ node.type === 'TSTypeLiteral' ||
2194
+ node.type === 'TSTypeOperator' ||
2195
+ /^TS[A-Za-z]*(Type|Keyword)$/.test(node.type)
2196
+ );
2197
+ }
2198
+
795
2199
  /**
796
2200
  * @param {AST.Identifier} identifier
797
2201
  * @param {AST.Node} parent
@@ -871,8 +2275,9 @@ function collect_pattern_replacements(pattern, source, replacements) {
871
2275
  }
872
2276
 
873
2277
  /**
2278
+ * @template {{ shadowed_names: Set<string> }} S
874
2279
  * @param {AST.Function} node
875
- * @param {import('zimmerframe').Context<AST.Node, { loop_param_names: Set<string>, shadowed_names: Set<string> }>} context
2280
+ * @param {import('zimmerframe').Context<AST.Node, S>} context
876
2281
  * @returns {AST.Node | void}
877
2282
  */
878
2283
  function rewrite_function_shadowed_refs(node, { state, next }) {
@@ -888,8 +2293,9 @@ function rewrite_function_shadowed_refs(node, { state, next }) {
888
2293
  }
889
2294
 
890
2295
  /**
2296
+ * @template {{ shadowed_names: Set<string> }} S
891
2297
  * @param {AST.BlockStatement} node
892
- * @param {import('zimmerframe').Context<AST.Node, { loop_param_names: Set<string>, shadowed_names: Set<string> }>} context
2298
+ * @param {import('zimmerframe').Context<AST.Node, S>} context
893
2299
  * @returns {AST.Node | void}
894
2300
  */
895
2301
  function rewrite_block_shadowed_refs(node, { state, next }) {
@@ -941,7 +2347,9 @@ function collect_function_var_names(node, names) {
941
2347
  node.type === 'FunctionExpression' ||
942
2348
  node.type === 'ArrowFunctionExpression' ||
943
2349
  node.type === 'ClassDeclaration' ||
944
- node.type === 'ClassExpression'
2350
+ node.type === 'ClassExpression' ||
2351
+ // A namespace's `var`s are its own.
2352
+ node.type === 'TSModuleDeclaration'
945
2353
  ) {
946
2354
  return;
947
2355
  }
@@ -1189,6 +2597,217 @@ function to_jsx_expression_container(expression, source_node = expression) {
1189
2597
  );
1190
2598
  }
1191
2599
 
2600
+ /**
2601
+ * Whether `specifier` of `declaration` imports `defineVaporComponent` from
2602
+ * `vue-jsx-vapor` under its own name, as a value or as a type.
2603
+ *
2604
+ * @param {AST.ImportDeclaration | AST.TSRXImportDeclaration} declaration
2605
+ * @param {AST.ImportDeclaration['specifiers'][number]} specifier
2606
+ * @returns {boolean}
2607
+ */
2608
+ function imports_define_vapor_component(declaration, specifier) {
2609
+ return (
2610
+ declaration.source.type === 'Literal' &&
2611
+ declaration.source.value === 'vue-jsx-vapor' &&
2612
+ specifier.type === 'ImportSpecifier' &&
2613
+ imported_name(specifier) === DEFINE_VAPOR_COMPONENT &&
2614
+ specifier.local.name === DEFINE_VAPOR_COMPONENT
2615
+ );
2616
+ }
2617
+
2618
+ /**
2619
+ * The name an import specifier imports, written as an identifier or quoted
2620
+ * (`import { "a" as a }`).
2621
+ *
2622
+ * @param {AST.ImportSpecifier} specifier
2623
+ * @returns {string | undefined}
2624
+ */
2625
+ function imported_name(specifier) {
2626
+ const imported = specifier.imported;
2627
+ if (imported?.type === 'Identifier') return imported.name;
2628
+ if (imported?.type === 'Literal' && typeof imported.value === 'string') return imported.value;
2629
+ return undefined;
2630
+ }
2631
+
2632
+ /**
2633
+ * Turn an authored type-only import of `defineVaporComponent` from
2634
+ * `vue-jsx-vapor` into the value import the generated components need. The
2635
+ * specifier is replaced by one without a location, as for a name the compiler
2636
+ * adds, so the editor maps no edit of the whole import back to the source.
2637
+ *
2638
+ * @param {AST.Program} program
2639
+ * @returns {void}
2640
+ */
2641
+ function promote_type_only_define_vapor_component_import(program) {
2642
+ for (const statement of program.body) {
2643
+ if (statement.type !== 'ImportDeclaration') continue;
2644
+ const index = statement.specifiers.findIndex(
2645
+ (specifier) =>
2646
+ imports_define_vapor_component(statement, specifier) &&
2647
+ (statement.importKind === 'type' ||
2648
+ /** @type {AST.ImportSpecifier} */ (specifier).importKind === 'type'),
2649
+ );
2650
+ if (index === -1) continue;
2651
+ if (statement.importKind === 'type') {
2652
+ statement.importKind = 'value';
2653
+ for (const specifier of statement.specifiers) {
2654
+ if (specifier.type === 'ImportSpecifier') specifier.importKind = 'type';
2655
+ }
2656
+ }
2657
+ statement.specifiers[index] = create_import_specifier(DEFINE_VAPOR_COMPONENT);
2658
+ return;
2659
+ }
2660
+ }
2661
+
2662
+ /**
2663
+ * Report each authored binding named `defineVaporComponent`. vue-jsx-vapor
2664
+ * finds components by calls to that name, and the compiler wraps each
2665
+ * component in the one from `vue-jsx-vapor`, so the module can't declare or
2666
+ * shadow it. An import of it from `vue-jsx-vapor` itself is the binding the
2667
+ * compiler needs.
2668
+ *
2669
+ * @param {AST.Program} program
2670
+ * @param {TransformContext} transform_context
2671
+ * @returns {boolean} whether it reported one
2672
+ */
2673
+ function report_define_vapor_component_bindings(program, transform_context) {
2674
+ /** @type {Set<number>} */
2675
+ const reported = new Set();
2676
+
2677
+ /** @param {AST.Node | null | undefined} pattern */
2678
+ const check = (pattern) => {
2679
+ for (const id of pattern_identifiers(pattern)) {
2680
+ if (id.name !== DEFINE_VAPOR_COMPONENT || !has_location(id)) continue;
2681
+ // The transform can carry one authored node to more than one place.
2682
+ if (reported.has(id.start)) continue;
2683
+ reported.add(id.start);
2684
+ error(
2685
+ TSRX_ERRORS.DEFINE_VAPOR_COMPONENT_BINDING,
2686
+ transform_context.filename,
2687
+ id,
2688
+ transform_context.errors,
2689
+ transform_context.comments,
2690
+ );
2691
+ }
2692
+ };
2693
+
2694
+ /** @param {AST.Function} node */
2695
+ const check_function = (node) => {
2696
+ if (node.type !== 'ArrowFunctionExpression') check(node.id);
2697
+ for (const param of node.params) check(param);
2698
+ };
2699
+
2700
+ walk(/** @type {AST.Node} */ (program), null, {
2701
+ ImportDeclaration(node) {
2702
+ for (const specifier of node.specifiers) {
2703
+ if (!imports_define_vapor_component(node, specifier)) check(specifier.local);
2704
+ }
2705
+ },
2706
+ VariableDeclarator(node, { next }) {
2707
+ check(node.id);
2708
+ next();
2709
+ },
2710
+ FunctionDeclaration(node, { next }) {
2711
+ check_function(node);
2712
+ next();
2713
+ },
2714
+ FunctionExpression(node, { next }) {
2715
+ check_function(node);
2716
+ next();
2717
+ },
2718
+ ArrowFunctionExpression(node, { next }) {
2719
+ check_function(node);
2720
+ next();
2721
+ },
2722
+ // `declare function`: its parameters only name types.
2723
+ TSDeclareFunction(node) {
2724
+ check(node.id);
2725
+ },
2726
+ ClassDeclaration(node, { next }) {
2727
+ check(node.id);
2728
+ next();
2729
+ },
2730
+ ClassExpression(node, { next }) {
2731
+ check(node.id);
2732
+ next();
2733
+ },
2734
+ CatchClause(node, { next }) {
2735
+ check(node.param);
2736
+ next();
2737
+ },
2738
+ TSEnumDeclaration(node, { next }) {
2739
+ check(node.id);
2740
+ next();
2741
+ },
2742
+ TSModuleDeclaration(node, { next }) {
2743
+ if (is_instantiated_namespace(node)) check(node.id);
2744
+ next();
2745
+ },
2746
+ TSImportEqualsDeclaration(node, { next }) {
2747
+ check(node.id);
2748
+ next();
2749
+ },
2750
+ });
2751
+
2752
+ return reported.size > 0;
2753
+ }
2754
+
2755
+ /**
2756
+ * Whether a namespace declares a value, as TypeScript decides: a namespace of
2757
+ * interfaces, type aliases and namespaces of those binds only a type.
2758
+ *
2759
+ * @param {AST.TSModuleDeclaration} node
2760
+ * @returns {boolean}
2761
+ */
2762
+ function is_instantiated_namespace(node) {
2763
+ const body = node.body;
2764
+ if (!body) return false;
2765
+ if (body.type === 'TSModuleDeclaration') return is_instantiated_namespace(body);
2766
+ return body.body.some((statement) => {
2767
+ const declaration = /** @type {AST.Node} */ (
2768
+ statement.type === 'ExportNamedDeclaration' && statement.declaration
2769
+ ? statement.declaration
2770
+ : statement
2771
+ );
2772
+ switch (declaration.type) {
2773
+ case 'TSInterfaceDeclaration':
2774
+ case 'TSTypeAliasDeclaration':
2775
+ return false;
2776
+ case 'TSModuleDeclaration':
2777
+ return is_instantiated_namespace(declaration);
2778
+ default:
2779
+ return true;
2780
+ }
2781
+ });
2782
+ }
2783
+
2784
+ /**
2785
+ * The identifiers a binding pattern declares.
2786
+ *
2787
+ * @param {AST.Node | null | undefined} node
2788
+ * @returns {AST.Identifier[]}
2789
+ */
2790
+ function pattern_identifiers(node) {
2791
+ switch (node?.type) {
2792
+ case 'Identifier':
2793
+ return [node];
2794
+ case 'RestElement':
2795
+ return pattern_identifiers(node.argument);
2796
+ case 'AssignmentPattern':
2797
+ return pattern_identifiers(node.left);
2798
+ case 'ArrayPattern':
2799
+ return node.elements.flatMap(pattern_identifiers);
2800
+ case 'ObjectPattern':
2801
+ return node.properties.flatMap((property) =>
2802
+ pattern_identifiers(property.type === 'Property' ? property.value : property),
2803
+ );
2804
+ case 'TSParameterProperty':
2805
+ return pattern_identifiers(/** @type {AST.Node} */ (/** @type {unknown} */ (node.parameter)));
2806
+ default:
2807
+ return [];
2808
+ }
2809
+ }
2810
+
1192
2811
  /**
1193
2812
  * @param {import('estree').Program} program
1194
2813
  * @param {TransformContext} transform_context
@@ -1199,15 +2818,37 @@ function inject_vue_imports(program, transform_context) {
1199
2818
  const ref_prop_source = transform_context.platform.imports.refProp;
1200
2819
 
1201
2820
  if (transform_context.needs_define_vapor_component) {
1202
- ensure_named_import(program, 'vue-jsx-vapor', 'defineVaporComponent');
2821
+ promote_type_only_define_vapor_component_import(program);
2822
+ }
2823
+ const reported_define_vapor_component = report_define_vapor_component_bindings(
2824
+ program,
2825
+ transform_context,
2826
+ );
2827
+
2828
+ // After the error the authored binding keeps the name, and an import could
2829
+ // only declare it a second time.
2830
+ if (transform_context.needs_define_vapor_component && !reported_define_vapor_component) {
2831
+ ensure_named_import(program, 'vue-jsx-vapor', DEFINE_VAPOR_COMPONENT);
1203
2832
  }
1204
2833
 
1205
2834
  if (transform_context.needs_vapor_for) {
1206
- ensure_named_import(program, 'vue-jsx-vapor', 'VaporFor');
2835
+ ensure_named_import(program, 'vue-jsx-vapor', 'VaporFor', VAPOR_FOR_INTERNAL_NAME);
2836
+ }
2837
+
2838
+ if (transform_context.needs_vapor_computed) {
2839
+ // Its own declaration: an authored `import type` or `import * as` from
2840
+ // 'vue' can't take a value specifier.
2841
+ insertAfterDirectives(program, [
2842
+ b.imports([['computed', VUE_COMPUTED_INTERNAL_NAME, 'value']], 'vue'),
2843
+ ]);
2844
+ }
2845
+
2846
+ if (transform_context.needs_use_slots) {
2847
+ ensure_named_import(program, 'vue', 'useSlots', USE_SLOTS_INTERNAL_NAME);
1207
2848
  }
1208
2849
 
1209
2850
  if (transform_context.needs_suspense) {
1210
- ensure_named_import(program, 'vue', 'Suspense');
2851
+ ensure_named_import(program, 'vue', 'Suspense', SUSPENSE_INTERNAL_NAME);
1211
2852
  }
1212
2853
 
1213
2854
  if (transform_context.needs_error_boundary) {
@@ -1215,6 +2856,7 @@ function inject_vue_imports(program, transform_context) {
1215
2856
  program,
1216
2857
  transform_context.platform.imports.errorBoundary,
1217
2858
  'TsrxErrorBoundary',
2859
+ ERROR_BOUNDARY_INTERNAL_NAME,
1218
2860
  );
1219
2861
  }
1220
2862
 
@@ -1222,6 +2864,15 @@ function inject_vue_imports(program, transform_context) {
1222
2864
  ensure_named_import(program, merge_refs_source, 'mergeRefs', MERGE_REFS_INTERNAL_NAME);
1223
2865
  }
1224
2866
 
2867
+ if (transform_context.needs_join_scope_class && ref_prop_source) {
2868
+ ensure_named_import(
2869
+ program,
2870
+ ref_prop_source,
2871
+ 'join_scope_class',
2872
+ JOIN_SCOPE_CLASS_INTERNAL_NAME,
2873
+ );
2874
+ }
2875
+
1225
2876
  if (transform_context.needs_normalize_spread_props && ref_prop_source) {
1226
2877
  ensure_named_import(
1227
2878
  program,
@@ -1242,6 +2893,12 @@ function inject_vue_imports(program, transform_context) {
1242
2893
  }
1243
2894
 
1244
2895
  /**
2896
+ * Import `name` as `local` from `source` unless a named value import of
2897
+ * `source` already has it, in any declaration: an authored
2898
+ * `import { Suspense } from 'vue'` can follow the keyed slot's `computed`
2899
+ * import. Otherwise add it to the first named value import of `source`, or
2900
+ * give it an import of its own.
2901
+ *
1245
2902
  * @param {import('estree').Program} program
1246
2903
  * @param {string} source
1247
2904
  * @param {string} name
@@ -1249,27 +2906,42 @@ function inject_vue_imports(program, transform_context) {
1249
2906
  * @returns {void}
1250
2907
  */
1251
2908
  function ensure_named_import(program, source, name, local = name) {
2909
+ /** @type {import('estree').ImportDeclaration | undefined} */
2910
+ let first;
1252
2911
  for (const statement of program.body) {
1253
2912
  if (statement.type !== 'ImportDeclaration' || statement.source?.value !== source) {
1254
2913
  continue;
1255
2914
  }
2915
+ // A type-only import is erased from the build, and a namespace import
2916
+ // takes no named specifiers: the helper gets an import of its own.
2917
+ if (
2918
+ statement.importKind === 'type' ||
2919
+ statement.specifiers.some((specifier) => specifier.type === 'ImportNamespaceSpecifier')
2920
+ ) {
2921
+ continue;
2922
+ }
1256
2923
 
1257
2924
  const has_specifier = statement.specifiers.some(
1258
2925
  (specifier) =>
1259
2926
  specifier.type === 'ImportSpecifier' &&
1260
- specifier.imported?.type === 'Identifier' &&
1261
- specifier.imported.name === name &&
2927
+ specifier.importKind !== 'type' &&
2928
+ imported_name(specifier) === name &&
1262
2929
  specifier.local?.name === local,
1263
2930
  );
1264
2931
 
1265
- if (!has_specifier) {
1266
- statement.specifiers.push(create_import_specifier(name, local));
2932
+ if (has_specifier) {
2933
+ return;
1267
2934
  }
1268
2935
 
2936
+ first ??= statement;
2937
+ }
2938
+
2939
+ if (first) {
2940
+ first.specifiers.push(create_import_specifier(name, local));
1269
2941
  return;
1270
2942
  }
1271
2943
 
1272
- program.body.unshift(b.imports([[name, local, 'value']], source));
2944
+ insertAfterDirectives(program, [b.imports([[name, local, 'value']], source)]);
1273
2945
  }
1274
2946
 
1275
2947
  /**