@octanejs/codemod 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +295 -4
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +162 -0
  4. package/dist/compiler.d.ts +11 -0
  5. package/dist/compiler.js +48 -0
  6. package/dist/effect-receivers.d.ts +11 -0
  7. package/dist/effect-receivers.js +315 -0
  8. package/dist/expression-wrappers.d.ts +6 -0
  9. package/dist/expression-wrappers.js +16 -0
  10. package/dist/forwarded-props.d.ts +27 -0
  11. package/dist/forwarded-props.js +489 -0
  12. package/dist/index.d.ts +6 -0
  13. package/{src → dist}/index.js +1 -0
  14. package/dist/linked-state.d.ts +17 -0
  15. package/dist/linked-state.js +126 -0
  16. package/dist/local-calls.d.ts +20 -0
  17. package/dist/local-calls.js +143 -0
  18. package/dist/local-react-hook.d.ts +15 -0
  19. package/dist/local-react-hook.js +353 -0
  20. package/dist/local-uses.d.ts +13 -0
  21. package/dist/local-uses.js +987 -0
  22. package/dist/mappings.d.ts +57 -0
  23. package/dist/mappings.js +343 -0
  24. package/dist/path-svg.d.ts +60 -0
  25. package/dist/path-svg.js +207 -0
  26. package/dist/project.d.ts +9 -0
  27. package/dist/project.js +1568 -0
  28. package/dist/react-intl.d.ts +4 -0
  29. package/dist/react-intl.js +389 -0
  30. package/dist/react-renderer.d.ts +9 -0
  31. package/dist/react-renderer.js +106 -0
  32. package/dist/scoped-signal.d.ts +4 -0
  33. package/dist/scoped-signal.js +480 -0
  34. package/dist/scoped-store-contract.d.ts +13 -0
  35. package/dist/scoped-store-contract.js +741 -0
  36. package/dist/store-hook-uses.d.ts +18 -0
  37. package/dist/store-hook-uses.js +403 -0
  38. package/dist/store-inputs.d.ts +16 -0
  39. package/dist/store-inputs.js +391 -0
  40. package/dist/strong.d.ts +24 -0
  41. package/dist/strong.js +142 -0
  42. package/dist/transform.d.ts +27 -0
  43. package/dist/transform.js +4890 -0
  44. package/dist/types.d.ts +203 -0
  45. package/dist/types.js +1 -0
  46. package/package.json +18 -6
  47. package/src/path-svg.ts +218 -0
  48. package/templates/octane-path-svg.ts +56 -0
  49. package/templates/octane-store-context.tsrx +49 -0
  50. package/templates/octane-store-hooks.ts +61 -0
  51. package/templates/react-intl.tsrx +116 -0
  52. package/src/bin.js +0 -151
  53. package/src/compiler.js +0 -61
  54. package/src/index.d.ts +0 -95
  55. package/src/mappings.js +0 -429
  56. package/src/project.js +0 -738
  57. package/src/strong.js +0 -149
  58. package/src/transform.js +0 -3455
package/src/transform.js DELETED
@@ -1,3455 +0,0 @@
1
- import ts from 'typescript';
2
- import {
3
- DEPENDENCY_HOOKS,
4
- RADIX_TYPES,
5
- REACT_MODULES,
6
- TEXT_FIELD_COMPONENTS,
7
- TEXT_INPUT_TYPES,
8
- UNSUPPORTED_VALUES,
9
- mapPackageExport,
10
- mapQualifiedType,
11
- mapReactImport,
12
- missingExport,
13
- radixNamespace,
14
- } from './mappings.js';
15
-
16
- /**
17
- * @typedef {'info' | 'warning' | 'error'} Severity
18
- * @typedef {{ rule: string, severity: Severity, line: number, message: string }} Note
19
- *
20
- * @typedef {Object} TransformOptions
21
- * @property {'tsrx' | 'tsx'} [target] `tsrx` (default) rewrites component
22
- * bodies as templates; `tsx` keeps JSX and only ports the React APIs.
23
- * @property {boolean} [strong] emit Strong-mode source: add `"use strong"` and
24
- * leave omitted dependency lists to the compiler.
25
- * @property {boolean} [strictNullChecks] the project checks with
26
- * `strictNullChecks`, so a TypeScript module's own types may prove a child
27
- * hole is text
28
- * @property {{ sourceFile: ts.SourceFile, checker: ts.TypeChecker }} [types]
29
- * this module in a program over the whole project, whose resolved imports
30
- * type what the module's own program cannot
31
- * @property {(specifier: string) => string | null} [resolveSpecifier] the new
32
- * spelling of an import specifier (a renamed module, a binding package), or
33
- * null to keep it.
34
- * @property {(specifier: string, name: string) => boolean | null} [isContext]
35
- * whether an imported name is a context, or null when it cannot be known
36
- * @property {(specifier: string) => string | null} [unported] the React package
37
- * an import specifier names when that package has no Octane port, or null
38
- * @property {boolean} [reactCompat] the project has React and React DOM 19.2 or
39
- * newer in the React 19 series, so `ReactCompat` can host an unported
40
- * package's components
41
- *
42
- * @typedef {Object} Unported A React package with no Octane port, as this
43
- * module uses it
44
- * @property {string} name
45
- * @property {number} islands elements now rendered in a `ReactCompat` island
46
- * @property {number} blocked uses that only a port can support
47
- *
48
- * @typedef {Object} TransformResult
49
- * @property {string} code
50
- * @property {boolean} changed
51
- * @property {boolean} template whether the module becomes `.tsrx`: it holds a
52
- * template, keeps JSX, or was a JSX module, so no `.tsx` module is left
53
- * outside Strong mode's reach
54
- * @property {Note[]} notes
55
- * @property {Record<string, number>} rules how often each rule fired
56
- * @property {ModuleExports} exports what the module exports that other modules'
57
- * rewrites depend on
58
- * @property {Unported[]} unported
59
- *
60
- * @typedef {Object} ModuleExports
61
- * @property {string[]} contexts exported names whose value is a context this
62
- * module creates
63
- * @property {{ specifier: string, names: [string, string][] | null }[]} reexports
64
- * `export … from` declarations: [imported, exported] pairs, or null for `*`
65
- */
66
-
67
- /**
68
- * @typedef {{ template: boolean }} Context
69
- * @typedef {{ module: string, local: string, imported: string, namespace: boolean, typeOnly: boolean, port: Unported | null }} Import
70
- */
71
-
72
- /** Marks emitted text whose whole line should go. */
73
- const DROP = '\u0000DROP\u0000';
74
- /**
75
- * Stands in for a newline inside a string or template literal while arms are
76
- * re-indented, so moving a literal never changes its value.
77
- */
78
- const LITERAL_NEWLINE = '\u0000NL\u0000';
79
-
80
- const TEMPLATE = { template: true };
81
- const PLAIN = { template: false };
82
- /** The local component that wraps an element no island can host and throws its `error`. */
83
- const NO_PORT = 'NoOctanePort';
84
-
85
- /** Rule names, as reported. */
86
- const RULE = {
87
- binding: 'bindings',
88
- classComponent: 'class-component',
89
- consumer: 'context-consumer',
90
- defaultProps: 'default-props',
91
- descriptorChildren: 'descriptor-children',
92
- deps: 'hook-dependencies',
93
- eventObject: 'event-object',
94
- forwardRef: 'forward-ref',
95
- import: 'imports',
96
- legacyRoot: 'legacy-root',
97
- rootRender: 'root-render',
98
- serverRender: 'server-render',
99
- flushSync: 'flush-sync',
100
- renderProp: 'render-prop-children',
101
- documentShell: 'document-shell',
102
- nativeChange: 'native-text-change',
103
- className: 'class-attribute',
104
- provider: 'context-provider',
105
- strictMode: 'strict-mode',
106
- component: 'template-component',
107
- if: 'template-if',
108
- for: 'template-for',
109
- text: 'template-text',
110
- try: 'template-try',
111
- unsupported: 'unsupported-api',
112
- strong: 'strong',
113
- bindings: 'bindings',
114
- reactCompat: 'react-compat',
115
- };
116
-
117
- /**
118
- * Rewrite one React module as Octane.
119
- *
120
- * @param {string} source
121
- * @param {string} filename
122
- * @param {TransformOptions} [options]
123
- * @returns {TransformResult}
124
- */
125
- export function transformModule(source, filename, options = {}) {
126
- return new ModuleTransform(source, filename, options).run();
127
- }
128
-
129
- /**
130
- * Parse and bind one module on its own, with only the ES5 library and no
131
- * module resolution. Binding is enough to map every name to the declaration it
132
- * refers to, so a shadowed `useState` or event parameter is never mistaken for
133
- * another; the library gives the module's own types their array and string
134
- * members.
135
- *
136
- * @param {string} filename
137
- * @param {string} source
138
- */
139
- function bind(filename, source) {
140
- const lib = esLib();
141
- const sf = ts.createSourceFile(
142
- filename,
143
- source,
144
- ts.ScriptTarget.Latest,
145
- true,
146
- scriptKind(filename),
147
- );
148
- /** @type {ts.CompilerHost} */
149
- const host = {
150
- getSourceFile: (name) => (name === filename ? sf : name === lib.fileName ? lib : undefined),
151
- getDefaultLibFileName: () => lib.fileName,
152
- writeFile: () => {},
153
- getCurrentDirectory: () => '',
154
- getCanonicalFileName: (name) => name,
155
- useCaseSensitiveFileNames: () => true,
156
- getNewLine: () => '\n',
157
- fileExists: (name) => name === filename || name === lib.fileName,
158
- readFile: () => undefined,
159
- };
160
- const program = ts.createProgram({
161
- rootNames: [filename, lib.fileName],
162
- options: {
163
- noLib: true,
164
- noResolve: true,
165
- allowJs: true,
166
- jsx: ts.JsxEmit.Preserve,
167
- types: [],
168
- // As the compiler's typed-text proof requires: a `string` excludes
169
- // null, and an indexed read may be missing.
170
- strictNullChecks: true,
171
- noUncheckedIndexedAccess: true,
172
- },
173
- host,
174
- });
175
- return { sf, checker: program.getTypeChecker() };
176
- }
177
-
178
- /** @type {ts.SourceFile | undefined} */
179
- let es5;
180
-
181
- /**
182
- * The ES5 library, parsed once and shared by every module's program, so
183
- * array and string members have types.
184
- */
185
- function esLib() {
186
- const file = ts.getDefaultLibFilePath({}).replace(/[^/\\]+$/, 'lib.es5.d.ts');
187
- es5 ??= ts.createSourceFile(
188
- 'lib.es5.d.ts',
189
- /** @type {string} */ (ts.sys.readFile(file)),
190
- ts.ScriptTarget.Latest,
191
- true,
192
- );
193
- return es5;
194
- }
195
-
196
- /** @param {string} filename */
197
- function scriptKind(filename) {
198
- if (filename.endsWith('.tsx')) return ts.ScriptKind.TSX;
199
- if (filename.endsWith('.jsx')) return ts.ScriptKind.JSX;
200
- if (/\.[cm]?ts$/.test(filename)) return ts.ScriptKind.TS;
201
- // Plain .js files often hold JSX in React projects.
202
- return ts.ScriptKind.JSX;
203
- }
204
-
205
- /**
206
- * @param {ts.Expression} node
207
- * @returns {ts.Expression}
208
- */
209
- function skipParens(node) {
210
- while (ts.isParenthesizedExpression(node)) node = node.expression;
211
- return node;
212
- }
213
-
214
- /**
215
- * Whether `node` wraps an expression only for grouping or the type checker.
216
- *
217
- * @param {ts.Node} node
218
- * @returns {node is ts.ParenthesizedExpression | ts.AsExpression | ts.SatisfiesExpression | ts.NonNullExpression | ts.TypeAssertion}
219
- */
220
- function isWrapper(node) {
221
- return (
222
- ts.isParenthesizedExpression(node) ||
223
- ts.isAsExpression(node) ||
224
- ts.isSatisfiesExpression(node) ||
225
- ts.isNonNullExpression(node) ||
226
- ts.isTypeAssertionExpression(node)
227
- );
228
- }
229
-
230
- /**
231
- * @param {ts.Expression} node
232
- * @returns {ts.Expression}
233
- */
234
- function skipWrappers(node) {
235
- while (isWrapper(node)) node = node.expression;
236
- return node;
237
- }
238
-
239
- /**
240
- * The declaration as a rest binding, `rest` in `{ a, ...rest }`, or null.
241
- *
242
- * @param {ts.Declaration | null} declaration
243
- */
244
- function asRest(declaration) {
245
- return declaration &&
246
- ts.isBindingElement(declaration) &&
247
- declaration.dotDotDotToken &&
248
- ts.isObjectBindingPattern(declaration.parent)
249
- ? declaration
250
- : null;
251
- }
252
-
253
- /** @param {ts.Node} node */
254
- function isJsx(node) {
255
- return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
256
- }
257
-
258
- /**
259
- * What a module's import of a package with no Octane port leaves to do.
260
- *
261
- * @param {Unported} port
262
- */
263
- function portComment({ name, islands, blocked }) {
264
- const missing = `No Octane port of \`${name}\` exists`;
265
- if (blocked > 0) {
266
- return `${missing}, and this module needs one: Octane cannot call its hooks, read its contexts, or pass Octane content to its components.`;
267
- }
268
- return islands > 0
269
- ? `${missing}, so its components render in React through ReactCompat.`
270
- : `${missing}; React stays a dependency for it.`;
271
- }
272
-
273
- /**
274
- * Whether a hole is already spelled as text, or as a literal the cast would
275
- * only clutter.
276
- *
277
- * @param {ts.Expression} node
278
- */
279
- function isTextSpelling(node) {
280
- node = skipParens(node);
281
- return (
282
- ts.isNumericLiteral(node) ||
283
- ts.isBigIntLiteral(node) ||
284
- ts.isAsExpression(node) ||
285
- isStringSpelling(node)
286
- );
287
- }
288
-
289
- /**
290
- * Whether the compiler proves `node` a string by its spelling: a string
291
- * literal, a `String()` call, or a concatenation with one.
292
- *
293
- * @param {ts.Expression} node
294
- * @returns {boolean}
295
- */
296
- function isStringSpelling(node) {
297
- node = skipParens(node);
298
- if (ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) return true;
299
- if (ts.isCallExpression(node)) {
300
- return ts.isIdentifier(node.expression) && node.expression.text === 'String';
301
- }
302
- return (
303
- ts.isBinaryExpression(node) &&
304
- node.operatorToken.kind === ts.SyntaxKind.PlusToken &&
305
- (isStringSpelling(node.left) || isStringSpelling(node.right))
306
- );
307
- }
308
-
309
- /**
310
- * What a type renders as: 1 when every member is a string, 2 when every
311
- * member is a string, number, or bigint and one is not a string, else 0. The
312
- * compiler's typed-text proof applies the same test.
313
- *
314
- * @param {ts.Type} type
315
- * @returns {0 | 1 | 2}
316
- */
317
- function textKind(type) {
318
- const { TypeFlags } = ts;
319
- const opaque =
320
- TypeFlags.Any | TypeFlags.Unknown | TypeFlags.Never | TypeFlags.VoidLike | TypeFlags.Null;
321
- if (type.flags & opaque) return 0;
322
- if (type.flags & TypeFlags.StringLike) return 1;
323
- if (type.flags & (TypeFlags.NumberLike | TypeFlags.BigIntLike)) return 2;
324
- if (!type.isUnion()) return 0;
325
- /** @type {0 | 1 | 2} */
326
- let kind = 1;
327
- for (const member of type.types) {
328
- const each = textKind(member);
329
- if (each === 0) return 0;
330
- if (each === 2) kind = 2;
331
- }
332
- return kind;
333
- }
334
-
335
- /**
336
- * The outermost node of `sf` spanning exactly `[start, end)`.
337
- *
338
- * @param {ts.SourceFile} sf
339
- * @param {number} start
340
- * @param {number} end
341
- * @returns {ts.Node | null}
342
- */
343
- function nodeSpanning(sf, start, end) {
344
- /** @type {ts.Node} */
345
- let node = sf;
346
- for (;;) {
347
- const child = ts.forEachChild(node, (c) => (c.pos <= start && c.end >= end ? c : undefined));
348
- if (!child) return null;
349
- if (child.getStart(sf) === start && child.end === end) return child;
350
- node = child;
351
- }
352
- }
353
-
354
- /**
355
- * The attribute an element sets by `name`.
356
- *
357
- * @param {ts.JsxOpeningLikeElement} element
358
- * @param {string} name
359
- */
360
- function attributeOf(element, name) {
361
- return /** @type {ts.JsxAttribute | undefined} */ (
362
- element.attributes.properties.find(
363
- (a) => ts.isJsxAttribute(a) && ts.isIdentifier(a.name) && a.name.text === name,
364
- )
365
- );
366
- }
367
-
368
- /**
369
- * The elements a list row can render: the row itself, or each arm of a
370
- * conditional row. Null when an arm renders anything else.
371
- *
372
- * @param {ts.Expression} node
373
- * @returns {(ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment)[] | null}
374
- */
375
- function rowElements(node) {
376
- node = skipParens(node);
377
- if (isJsx(node))
378
- return [/** @type {ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment} */ (node)];
379
- if (isNullish(node)) return [];
380
- if (!ts.isConditionalExpression(node)) return null;
381
- const whenTrue = rowElements(node.whenTrue);
382
- const whenFalse = rowElements(node.whenFalse);
383
- return whenTrue && whenFalse && [...whenTrue, ...whenFalse];
384
- }
385
-
386
- /**
387
- * The element an `if (c) return <A />;` guard returns, or null for any other
388
- * statement.
389
- *
390
- * @param {ts.Statement} statement
391
- * @returns {ts.Expression | null}
392
- */
393
- function guardReturn(statement) {
394
- if (!ts.isIfStatement(statement) || statement.elseStatement) return null;
395
- let then = statement.thenStatement;
396
- if (ts.isBlock(then)) {
397
- if (then.statements.length !== 1) return null;
398
- then = then.statements[0];
399
- }
400
- if (!ts.isReturnStatement(then) || !then.expression) return null;
401
- return isJsx(skipParens(then.expression)) ? then.expression : null;
402
- }
403
-
404
- /**
405
- * Whether any `return` in `statements`, outside nested functions, returns
406
- * JSX.
407
- *
408
- * @param {readonly ts.Statement[]} statements
409
- */
410
- function returnsJsx(statements) {
411
- /** @type {(node: ts.Node) => boolean} */
412
- const hasJsx = (node) => isJsx(node) || (ts.forEachChild(node, hasJsx) ?? false);
413
- /** @type {(node: ts.Node) => boolean} */
414
- const visit = (node) => {
415
- if (isFunctionLike(node)) return false;
416
- if (ts.isReturnStatement(node) && node.expression && hasJsx(node.expression)) return true;
417
- return ts.forEachChild(node, visit) ?? false;
418
- };
419
- return statements.some(visit);
420
- }
421
-
422
- /** Document tags a router shell renders through `@octanejs/tanstack-router`. */
423
- const DOCUMENT_TAGS = /** @type {Record<string, string>} */ ({
424
- html: 'Html',
425
- head: 'Head',
426
- body: 'Body',
427
- });
428
-
429
- /**
430
- * Whether an identifier is read in a type, where an import needs no value.
431
- * A `typeof X` query is a type, which `import type` serves; `extends Base`
432
- * reads a value, so heritage counts as one.
433
- *
434
- * @param {ts.Identifier} node
435
- */
436
- function inTypeNode(node) {
437
- let parent = node.parent;
438
- while (ts.isQualifiedName(parent)) parent = parent.parent;
439
- return ts.isTypeNode(parent) && !ts.isExpressionWithTypeArguments(parent);
440
- }
441
-
442
- /** @param {ts.Node} node */
443
- function isNullish(node) {
444
- return (
445
- node.kind === ts.SyntaxKind.NullKeyword ||
446
- node.kind === ts.SyntaxKind.FalseKeyword ||
447
- (ts.isIdentifier(node) && node.text === 'undefined')
448
- );
449
- }
450
-
451
- /** @param {ts.Node} node */
452
- function isFunctionLike(node) {
453
- return (
454
- ts.isFunctionDeclaration(node) ||
455
- ts.isFunctionExpression(node) ||
456
- ts.isArrowFunction(node) ||
457
- ts.isMethodDeclaration(node) ||
458
- ts.isGetAccessor(node) ||
459
- ts.isSetAccessor(node) ||
460
- ts.isConstructorDeclaration(node)
461
- );
462
- }
463
-
464
- /**
465
- * Whether evaluating `node` can only produce a boolean, so `node && <X />`
466
- * renders nothing when it is falsy, exactly as `@if` does. React renders `0`
467
- * and `NaN` from a numeric left side, so anything unproven stays a hole.
468
- * `valueOf` gives the initializer a `const` name is bound to, if any.
469
- *
470
- * @param {ts.Expression} node
471
- * @param {(name: ts.Identifier) => ts.Expression | null} valueOf
472
- * @returns {boolean}
473
- */
474
- function isBoolean(node, valueOf) {
475
- node = skipParens(node);
476
- if (ts.isIdentifier(node)) {
477
- const value = valueOf(node);
478
- return value !== null && isBoolean(value, valueOf);
479
- }
480
- if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) {
481
- return true;
482
- }
483
- if (ts.isPrefixUnaryExpression(node)) {
484
- return node.operator === ts.SyntaxKind.ExclamationToken;
485
- }
486
- if (ts.isBinaryExpression(node)) {
487
- switch (node.operatorToken.kind) {
488
- case ts.SyntaxKind.EqualsEqualsEqualsToken:
489
- case ts.SyntaxKind.ExclamationEqualsEqualsToken:
490
- case ts.SyntaxKind.EqualsEqualsToken:
491
- case ts.SyntaxKind.ExclamationEqualsToken:
492
- case ts.SyntaxKind.LessThanToken:
493
- case ts.SyntaxKind.LessThanEqualsToken:
494
- case ts.SyntaxKind.GreaterThanToken:
495
- case ts.SyntaxKind.GreaterThanEqualsToken:
496
- case ts.SyntaxKind.InstanceOfKeyword:
497
- case ts.SyntaxKind.InKeyword:
498
- return true;
499
- case ts.SyntaxKind.AmpersandAmpersandToken:
500
- case ts.SyntaxKind.BarBarToken:
501
- return isBoolean(node.left, valueOf) && isBoolean(node.right, valueOf);
502
- }
503
- return false;
504
- }
505
- if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
506
- return node.expression.text === 'Boolean';
507
- }
508
- return false;
509
- }
510
-
511
- /**
512
- * Modules whose exports the codemod knows by name: React's, and Octane's own
513
- * for code already partly migrated.
514
- *
515
- * @param {string} module
516
- */
517
- function isApiModule(module) {
518
- return module in REACT_MODULES || module === 'octane';
519
- }
520
-
521
- /**
522
- * Whether an identifier names a property rather than a binding.
523
- *
524
- * @param {ts.Identifier} node
525
- */
526
- function isPropertyName(node) {
527
- const parent = /** @type {ts.Node & { name?: ts.Node }} */ (node.parent);
528
- if (ts.isPropertyAccessExpression(parent)) return parent.name === node;
529
- if (ts.isQualifiedName(parent)) return parent.right === node;
530
- return (
531
- parent.name === node &&
532
- (ts.isPropertyAssignment(parent) ||
533
- ts.isPropertySignature(parent) ||
534
- ts.isPropertyDeclaration(parent) ||
535
- ts.isMethodDeclaration(parent) ||
536
- ts.isMethodSignature(parent) ||
537
- ts.isJsxAttribute(parent))
538
- );
539
- }
540
-
541
- /**
542
- * Whether an identifier is the name a declaration introduces.
543
- *
544
- * @param {ts.Identifier} node
545
- */
546
- function declaresName(node) {
547
- const parent = /** @type {ts.Node & { name?: ts.Node }} */ (node.parent);
548
- if (parent.name !== node) return false;
549
- return (
550
- ts.isVariableDeclaration(parent) ||
551
- ts.isFunctionDeclaration(parent) ||
552
- ts.isFunctionExpression(parent) ||
553
- ts.isClassDeclaration(parent) ||
554
- ts.isClassExpression(parent) ||
555
- ts.isParameter(parent) ||
556
- ts.isBindingElement(parent) ||
557
- ts.isImportSpecifier(parent) ||
558
- ts.isImportClause(parent) ||
559
- ts.isNamespaceImport(parent) ||
560
- ts.isTypeAliasDeclaration(parent) ||
561
- ts.isInterfaceDeclaration(parent) ||
562
- ts.isEnumDeclaration(parent) ||
563
- ts.isTypeParameterDeclaration(parent)
564
- );
565
- }
566
-
567
- /**
568
- * The names a binding pattern introduces.
569
- *
570
- * @param {ts.BindingName} name
571
- * @returns {string[]}
572
- */
573
- function bindingNames(name) {
574
- if (ts.isIdentifier(name)) return [name.text];
575
- return name.elements.flatMap((element) =>
576
- ts.isOmittedExpression(element) ? [] : bindingNames(element.name),
577
- );
578
- }
579
-
580
- /**
581
- * Whether `node` reads a name `test` accepts.
582
- *
583
- * @param {ts.Node} node
584
- * @param {(name: string) => boolean} test
585
- * @returns {boolean}
586
- */
587
- function reads(node, test) {
588
- if (ts.isIdentifier(node)) return test(node.text);
589
- return ts.forEachChild(node, (child) => reads(child, test) || undefined) === true;
590
- }
591
-
592
- /**
593
- * Whether a `function` body reads its own `this` or `arguments`.
594
- *
595
- * @param {ts.Node} node
596
- * @returns {boolean}
597
- */
598
- function usesOwnThis(node) {
599
- if (node.kind === ts.SyntaxKind.ThisKeyword) return true;
600
- if (ts.isIdentifier(node) && node.text === 'arguments') return true;
601
- if (isFunctionLike(node) && !ts.isArrowFunction(node)) return false;
602
- return ts.forEachChild(node, (child) => usesOwnThis(child) || undefined) === true;
603
- }
604
-
605
- /**
606
- * The children of an element that are more than layout whitespace.
607
- *
608
- * @param {ts.JsxElement | ts.JsxFragment} node
609
- */
610
- function contentOf(node) {
611
- return node.children.filter(
612
- (child) => !(ts.isJsxText(child) && child.containsOnlyTriviaWhiteSpaces),
613
- );
614
- }
615
-
616
- /**
617
- * A comment's text without its delimiters, to wrap as a JSX comment.
618
- *
619
- * @param {string} comment
620
- */
621
- function commentText(comment) {
622
- const body = comment.startsWith('//') ? comment.slice(2) : comment.slice(2, -2);
623
- return body.trim().replaceAll('*/', '* /');
624
- }
625
-
626
- /** @param {string} name */
627
- function isComponentName(name) {
628
- return /^[A-Z]/.test(name);
629
- }
630
-
631
- class ModuleTransform {
632
- /**
633
- * @param {string} source
634
- * @param {string} filename
635
- * @param {TransformOptions} options
636
- */
637
- constructor(source, filename, options) {
638
- this.source = source;
639
- this.filename = filename;
640
- this.options = options;
641
- this.target = options.target ?? 'tsrx';
642
- this.strong = options.strong === true;
643
- /** @type {Set<string>} React imports read as values, not only as types. */
644
- this.valueUses = new Set();
645
- this.routerShell = false;
646
- this.textTypes = options.strictNullChecks === true && /\.[cm]?tsx?$/.test(filename);
647
- const { sf, checker } = bind(filename, source);
648
- this.sf = sf;
649
- this.checker = checker;
650
- /** @type {Note[]} */
651
- this.notes = [];
652
- /** @type {Record<string, number>} */
653
- this.rules = {};
654
- this.template = false;
655
- this.indentUnit = /^\t/m.test(source) ? '\t' : ' ';
656
-
657
- /** @type {Map<ts.Node, Import>} Every import, keyed by its declaration. */
658
- this.imports = new Map();
659
- /** @type {Map<string, Import>} React and Octane imports, by local name. */
660
- this.apiLocals = new Map();
661
- /** React-module locals that are still referenced after the rewrite. */
662
- this.used = new Set();
663
- /** Imports the rewrite needs from Octane: module -> name -> { local, typeOnly } */
664
- this.added = new Map();
665
- /** Every name the module declares, to keep added imports from colliding. */
666
- this.declared = new Set();
667
- /** Attributes a parent rule has already consumed, such as a row key. */
668
- this.removed = new Set();
669
- /** `<Fragment key>` rows whose key moved to the `@for` header. */
670
- this.bare = new Set();
671
- /** Functions whose parameter list a rule replaced. */
672
- this.parameters = new Map();
673
- /** @type {Set<ts.BindingElement>} Rest props that give up `onChange` to a text field. */
674
- this.restChange = new Set();
675
- /** @type {Set<ts.JsxSpreadAttribute>} Spreads of those rest props, which pass it as `onInput`. */
676
- this.changeSpreads = new Set();
677
- /** @type {Set<ts.VariableDeclaration | ts.FunctionDeclaration>} Components to mark `descriptorChildren`. */
678
- this.descriptorComponents = new Set();
679
- /** Whether a `declare module` now augments `octane/jsx-runtime`. */
680
- this.augments = false;
681
- /** @type {Map<string, Unported | null>} Each import specifier's unported package. */
682
- this.ports = new Map();
683
- /** @type {Map<string, Unported>} Unported packages, by name. */
684
- this.unported = new Map();
685
- /** @type {Set<ts.JsxElement | ts.JsxSelfClosingElement>} Elements to host in a `ReactCompat` island. */
686
- this.islands = new Set();
687
- /** @type {Map<ts.Node, string>} Elements no island can host, with the error each throws where it renders. */
688
- this.unrenderable = new Map();
689
- /** @type {ts.ImportDeclaration[]} Placeholder index -> import declaration. */
690
- this.importSlots = [];
691
- this.hasJsx = false;
692
- /** Whether the module imports React, rather than already being Octane. */
693
- this.fromReact = false;
694
- /** @type {Map<string, string | null>} Each specifier's new spelling, or null to keep it. */
695
- this.resolved = new Map();
696
- }
697
-
698
- /** @returns {TransformResult} */
699
- run() {
700
- this.analyze();
701
- let code = this.emit(this.sf, PLAIN, 0);
702
- code = this.finishImports(code);
703
- code = code.replace(/^[ \t]*\u0000DROP\u0000[ \t]*\r?\n/gm, '').replaceAll(DROP, '');
704
- code = code.replaceAll(LITERAL_NEWLINE, '\n');
705
- if (this.unrenderable.size > 0) {
706
- const [props, result] = this.isTypeScript()
707
- ? [': { error: string; children?: unknown }', ': never']
708
- : ['', ''];
709
- code = `${code.trimEnd()}\n\nfunction ${NO_PORT}({ error }${props})${result} {\n${this.indentUnit}throw new Error(error);\n}\n`;
710
- }
711
- const tsrx =
712
- this.template || (this.target === 'tsrx' && (this.hasJsx || /\.[jt]sx$/.test(this.filename)));
713
- if (tsrx) code = code.replace(/^\/\*\*\s*@jsxImportSource\s+\S+\s*\*\/[ \t]*\r?\n/m, '');
714
- // A JavaScript module was never type-checked; as TSRX it stays unchecked.
715
- if (tsrx && /\.[cm]?jsx?$/.test(this.filename)) {
716
- code = code.replace(/^(#![^\n]*\n)?/, '$1// @ts-nocheck\n');
717
- }
718
- if (this.strong && tsrx) code = this.addStrongDirective(code);
719
- if (!tsrx && this.fromReact && this.hasJsx && /\.(?:[jt]sx|js)$/.test(this.filename)) {
720
- code = this.addJsxPragma(code);
721
- }
722
- return {
723
- code,
724
- changed: code !== this.source,
725
- template: tsrx,
726
- notes: this.notes.sort((a, b) => a.line - b.line),
727
- rules: this.rules,
728
- exports: this.exportsOf(),
729
- unported: [...this.unported.values()],
730
- };
731
- }
732
-
733
- /** @returns {ModuleExports} */
734
- exportsOf() {
735
- /** @type {Set<string>} */
736
- const contexts = new Set();
737
- /** @type {Set<string>} */
738
- const exported = new Set();
739
- /** @type {ModuleExports['reexports']} */
740
- const reexports = [];
741
- const isExported = (/** @type {ts.Statement} */ statement) =>
742
- ts.canHaveModifiers(statement) &&
743
- ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
744
- for (const statement of this.sf.statements) {
745
- if (ts.isVariableStatement(statement)) {
746
- for (const declaration of statement.declarationList.declarations) {
747
- if (!ts.isIdentifier(declaration.name) || !this.isContext(declaration.name)) continue;
748
- contexts.add(declaration.name.text);
749
- if (isExported(statement)) exported.add(declaration.name.text);
750
- }
751
- } else if (
752
- ts.isExportDeclaration(statement) &&
753
- statement.exportClause &&
754
- ts.isNamedExports(statement.exportClause)
755
- ) {
756
- const pairs = statement.exportClause.elements.map(
757
- (element) =>
758
- /** @type {[string, string]} */ ([
759
- (element.propertyName ?? element.name).text,
760
- element.name.text,
761
- ]),
762
- );
763
- if (statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)) {
764
- reexports.push({ specifier: statement.moduleSpecifier.text, names: pairs });
765
- } else {
766
- for (const [local, name] of pairs) if (contexts.has(local)) exported.add(name);
767
- }
768
- } else if (
769
- ts.isExportDeclaration(statement) &&
770
- statement.moduleSpecifier &&
771
- ts.isStringLiteral(statement.moduleSpecifier)
772
- ) {
773
- reexports.push({ specifier: statement.moduleSpecifier.text, names: null });
774
- } else if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {
775
- if (contexts.has(statement.expression.text)) exported.add('default');
776
- }
777
- }
778
- return { contexts: [...exported], reexports };
779
- }
780
-
781
- // ---------------------------------------------------------------- analysis
782
-
783
- analyze() {
784
- // Added imports quote their module as the module's own imports do.
785
- const first = this.sf.statements.find(ts.isImportDeclaration);
786
- this.quote = first ? first.moduleSpecifier.getText(this.sf)[0] : "'";
787
- /** Locals imported from a package with no Octane port. */
788
- const portLocals = new Set();
789
- for (const statement of this.sf.statements) {
790
- if (
791
- ts.isExportDeclaration(statement) &&
792
- !statement.isTypeOnly &&
793
- statement.moduleSpecifier &&
794
- ts.isStringLiteral(statement.moduleSpecifier)
795
- ) {
796
- const port = this.portOf(statement.moduleSpecifier.text);
797
- if (port) {
798
- this.note(
799
- RULE.bindings,
800
- 'warning',
801
- statement,
802
- `\`${port.name}\` has no Octane port: import its components from it where they render, so they can render in a \`ReactCompat\` island.`,
803
- );
804
- }
805
- }
806
- if (!ts.isImportDeclaration(statement) || !statement.importClause) continue;
807
- const module = /** @type {ts.StringLiteral} */ (statement.moduleSpecifier).text;
808
- if (module in REACT_MODULES) this.fromReact = true;
809
- if (/^@tanstack\/react-(?:router|start)(?:\/|$)/.test(module)) this.routerShell = true;
810
- const clause = statement.importClause;
811
- const record = (
812
- /** @type {ts.Node} */ declaration,
813
- /** @type {ts.Identifier} */ name,
814
- /** @type {string} */ imported,
815
- /** @type {boolean} */ typeOnly,
816
- ) => {
817
- const port = typeOnly ? null : this.portOf(module);
818
- const entry = {
819
- module,
820
- local: name.text,
821
- imported,
822
- namespace: imported === '*',
823
- typeOnly,
824
- port,
825
- };
826
- this.imports.set(declaration, entry);
827
- if (port) portLocals.add(name.text);
828
- if (isApiModule(module)) this.apiLocals.set(name.text, entry);
829
- };
830
- // A default import of React is the namespace in practice; any other
831
- // module's default import is its `default` export.
832
- if (clause.name) {
833
- record(clause, clause.name, isApiModule(module) ? '*' : 'default', clause.isTypeOnly);
834
- }
835
- const bindings = clause.namedBindings;
836
- if (bindings && ts.isNamespaceImport(bindings)) {
837
- record(bindings, bindings.name, '*', clause.isTypeOnly);
838
- }
839
- if (bindings && ts.isNamedImports(bindings)) {
840
- for (const element of bindings.elements) {
841
- const imported = (element.propertyName ?? element.name).text;
842
- record(element, element.name, imported, clause.isTypeOnly || element.isTypeOnly);
843
- }
844
- }
845
- }
846
- /** @type {ts.JsxOpeningLikeElement[]} */
847
- const fields = [];
848
- /** @type {ts.Expression[]} Values read as an element: cloned, inspected, or a `render` prop. */
849
- const elements = [];
850
- const visit = (/** @type {ts.Node} */ node) => {
851
- if (ts.isIdentifier(node) && declaresName(node)) this.declared.add(node.text);
852
- if (ts.isIdentifier(node) && portLocals.has(node.text)) this.planUnported(node);
853
- if (isJsx(node)) this.hasJsx = true;
854
- if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) fields.push(node);
855
- if (
856
- ts.isJsxAttribute(node) &&
857
- node.name.getText(this.sf) === 'render' &&
858
- node.initializer &&
859
- ts.isJsxExpression(node.initializer) &&
860
- node.initializer.expression
861
- ) {
862
- elements.push(node.initializer.expression);
863
- }
864
- if (ts.isCallExpression(node) && node.arguments[0] && this.readsElement(node.expression)) {
865
- elements.push(node.arguments[0]);
866
- }
867
- ts.forEachChild(node, visit);
868
- };
869
- visit(this.sf);
870
- for (const field of fields) if (this.takesChange(field)) this.planRestChange(field);
871
- for (const element of elements) this.planDescriptorChildren(element);
872
- }
873
-
874
- /**
875
- * The package with no Octane port that a specifier names, or null. It
876
- * still runs on React, which only the codemod's report and a comment say.
877
- *
878
- * @param {string} module
879
- */
880
- portOf(module) {
881
- let port = this.ports.get(module);
882
- if (port === undefined) {
883
- const name = isApiModule(module) ? null : (this.options.unported?.(module) ?? null);
884
- port = name === null ? null : (this.unported.get(name) ?? { name, islands: 0, blocked: 0 });
885
- if (port) this.unported.set(port.name, port);
886
- this.ports.set(module, port);
887
- }
888
- return port;
889
- }
890
-
891
- /**
892
- * A component from a package with no Octane port renders in React, inside
893
- * a `ReactCompat` island, when its element hands React nothing Octane
894
- * renders. Its hooks and contexts cannot run in an Octane component, so
895
- * they are reported.
896
- *
897
- * @param {ts.Identifier} node
898
- */
899
- planUnported(node) {
900
- const port = this.inImport(node) ? null : this.importOf(node)?.port;
901
- if (!port) return;
902
- // `Toast.Bar`, through a namespace or default import, is the member.
903
- const member =
904
- ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node
905
- ? node.parent
906
- : node;
907
- const name = ts.isPropertyAccessExpression(member) ? member.name.text : node.text;
908
- const text = member.getText(this.sf);
909
- const parent = member.parent;
910
- const block = (/** @type {string} */ message) => {
911
- port.blocked++;
912
- const error = `${message} \`${port.name}\` has no Octane port.`;
913
- this.note(RULE.bindings, 'error', member, error);
914
- return error;
915
- };
916
- if (
917
- (ts.isJsxOpeningElement(parent) || ts.isJsxSelfClosingElement(parent)) &&
918
- parent.tagName === member
919
- ) {
920
- const element = ts.isJsxOpeningElement(parent) ? parent.parent : parent;
921
- if (this.inIsland(element)) return;
922
- const reason = !this.hostsInReact(element)
923
- ? `\`<${text}>\` takes children or props that Octane renders, which cannot cross into a React island.`
924
- : this.options.reactCompat
925
- ? null
926
- : `\`<${text}>\` can render in a \`ReactCompat\` island only with React and React DOM 19.2 or newer in the React 19 series.`;
927
- if (reason === null) {
928
- port.islands++;
929
- this.islands.add(element);
930
- } else {
931
- // Octane fails on a React component deep in its renderer, naming
932
- // neither it nor its package, so it throws this error there instead.
933
- this.unrenderable.set(element, block(reason));
934
- }
935
- } else if (ts.isCallExpression(parent) && parent.expression === member) {
936
- if (/^use[A-Z0-9]/.test(name))
937
- block(`\`${text}\` is a React hook, which Octane cannot call.`);
938
- } else if (
939
- ts.isCallExpression(parent) &&
940
- /^(?:use|useContext)$/.test(this.calleeName(parent.expression) ?? '')
941
- ) {
942
- block(`\`${text}\` is a React context, which Octane cannot read.`);
943
- }
944
- }
945
-
946
- /**
947
- * Whether a React component's element can be the root of a `ReactCompat`
948
- * island: React renders all of it, so its children are text and no prop
949
- * holds an element, as JSX here, through a value this module declares, or
950
- * by its type.
951
- *
952
- * @param {ts.JsxElement | ts.JsxSelfClosingElement} element
953
- */
954
- hostsInReact(element) {
955
- // By type: a cast to `any` or `ReactNode` proves nothing.
956
- const text = (/** @type {ts.JsxChild} */ child) =>
957
- ts.isJsxText(child) ||
958
- (ts.isJsxExpression(child) &&
959
- (!child.expression || textKind(this.typeOf(child.expression)) !== 0));
960
- if (ts.isJsxElement(element) && !element.children.every(text)) return false;
961
- const seen = new Set();
962
- /** @type {(node: ts.Node) => boolean} */
963
- const rendersOctane = (node) => {
964
- if (isJsx(node)) return true;
965
- if (ts.isIdentifier(node)) {
966
- const project = this.projectType(node);
967
- const type = (project?.checker ?? this.checker).typeToString(
968
- project?.type ?? this.checker.getTypeAtLocation(node),
969
- undefined,
970
- ts.TypeFormatFlags.NoTruncation,
971
- );
972
- if (/\b(?:React(?:Node|Element)|JSX\.Element)\b/.test(type)) return true;
973
- const declaration = this.declarationOf(node);
974
- if (declaration?.getSourceFile() === this.sf && !seen.has(declaration)) {
975
- seen.add(declaration);
976
- if (rendersOctane(declaration)) return true;
977
- }
978
- }
979
- return ts.forEachChild(node, rendersOctane) ?? false;
980
- };
981
- return !rendersOctane(
982
- ts.isJsxElement(element) ? element.openingElement.attributes : element.attributes,
983
- );
984
- }
985
-
986
- /**
987
- * Whether an element is already the child of a `ReactCompat` island.
988
- *
989
- * @param {ts.JsxElement | ts.JsxSelfClosingElement} element
990
- */
991
- inIsland(element) {
992
- const parent = element.parent;
993
- if (!ts.isJsxElement(parent)) return false;
994
- const entry = this.importOf(parent.openingElement.tagName);
995
- return entry?.module === 'octane/react' && entry.imported === 'ReactCompat';
996
- }
997
-
998
- /**
999
- * Whether a callee reads its argument as an element: `cloneElement`,
1000
- * `isValidElement`, or a `Children` method.
1001
- *
1002
- * @param {ts.Expression} callee
1003
- */
1004
- readsElement(callee) {
1005
- const name = this.calleeName(callee);
1006
- if (name === 'cloneElement' || name === 'isValidElement') return true;
1007
- return (
1008
- ts.isPropertyAccessExpression(callee) && this.calleeName(callee.expression) === 'Children'
1009
- );
1010
- }
1011
-
1012
- /**
1013
- * React passes a component its JSX children as elements, which
1014
- * `render={children}` and `cloneElement(children)` rely on. Octane passes a
1015
- * compiled render body unless the component is marked `descriptorChildren`,
1016
- * so mark the component whose own `children` this reads.
1017
- *
1018
- * @param {ts.Expression} expression
1019
- */
1020
- planDescriptorChildren(expression) {
1021
- const value = skipWrappers(expression);
1022
- const component = this.childrenOwner(value);
1023
- if (!component) return;
1024
- // `memo(…)` and `forwardRef(…)` wrap it; the declaration holds the call.
1025
- let holder = component.parent;
1026
- while (
1027
- ts.isCallExpression(holder) &&
1028
- /^(?:memo|forwardRef)$/.test(this.calleeName(holder.expression) ?? '')
1029
- ) {
1030
- holder = holder.parent;
1031
- }
1032
- if (ts.isCallExpression(holder) && this.calleeName(holder.expression) === 'descriptorChildren')
1033
- return;
1034
- // The compiler reads the marker from module-level `const` bindings only.
1035
- if (
1036
- ts.isVariableDeclaration(holder) &&
1037
- ts.isIdentifier(holder.name) &&
1038
- ts.getCombinedNodeFlags(holder) & ts.NodeFlags.Const &&
1039
- holder.parent.parent.parent === this.sf
1040
- ) {
1041
- this.descriptorComponents.add(holder);
1042
- } else if (
1043
- ts.isFunctionDeclaration(component) &&
1044
- component.parent === this.sf &&
1045
- component.name &&
1046
- !component.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword) &&
1047
- // Overload signatures would stay `function` declarations.
1048
- this.checker.getSymbolAtLocation(component.name)?.declarations?.length === 1 &&
1049
- this.declaredBeforeUse(component)
1050
- ) {
1051
- this.descriptorComponents.add(component);
1052
- } else {
1053
- this.note(
1054
- RULE.descriptorChildren,
1055
- 'warning',
1056
- expression,
1057
- 'This reads `children` as an element, which Octane passes as a compiled render body; mark the component with `descriptorChildren` so callers pass element descriptors.',
1058
- );
1059
- }
1060
- }
1061
-
1062
- /**
1063
- * The component whose own `children` prop `node` is: `children` from its
1064
- * props pattern, or `props.children`.
1065
- *
1066
- * @param {ts.Expression} node
1067
- * @returns {ts.SignatureDeclaration | null}
1068
- */
1069
- childrenOwner(node) {
1070
- /** @type {ts.Node | null} */
1071
- let props = null;
1072
- if (ts.isPropertyAccessExpression(node) && node.name.text === 'children') {
1073
- props = ts.isIdentifier(node.expression) ? this.declarationOf(node.expression) : null;
1074
- } else if (ts.isIdentifier(node)) {
1075
- const declaration = this.declarationOf(node);
1076
- if (
1077
- declaration &&
1078
- ts.isBindingElement(declaration) &&
1079
- (declaration.propertyName ?? declaration.name).getText(this.sf) === 'children'
1080
- ) {
1081
- props = declaration.parent.parent;
1082
- }
1083
- }
1084
- if (!props || !ts.isParameter(props)) return null;
1085
- const component = /** @type {ts.SignatureDeclaration} */ (props.parent);
1086
- return component.parameters[0] === props && isFunctionLike(component) ? component : null;
1087
- }
1088
-
1089
- /**
1090
- * Whether no code that runs while the module loads can reach `fn` before
1091
- * its declaration, so it can become a `const`, which is not hoisted. Any
1092
- * function there may run (an IIFE, a callback, a method an imported call
1093
- * invokes) except one it only defines: a declaration or a variable's value.
1094
- * Those run only when called or passed on, which counts as reaching `fn`
1095
- * for any binding the module declares.
1096
- *
1097
- * @param {ts.FunctionDeclaration} fn
1098
- */
1099
- declaredBeforeUse(fn) {
1100
- let safe = true;
1101
- const visit = (/** @type {ts.Node} */ node) => {
1102
- if (!safe) return;
1103
- if (isFunctionLike(node) && this.onlyDefines(node)) return;
1104
- if (ts.isIdentifier(node) && node !== fn.name) {
1105
- const declaration = this.declarationOf(node);
1106
- const call = node.parent;
1107
- const handed =
1108
- (ts.isCallExpression(call) || ts.isNewExpression(call)) &&
1109
- (call.expression === node || call.arguments?.includes(node));
1110
- if (
1111
- declaration === fn ||
1112
- (handed && declaration?.getSourceFile() === this.sf && !this.importOf(node))
1113
- ) {
1114
- safe = false;
1115
- }
1116
- }
1117
- ts.forEachChild(node, visit);
1118
- };
1119
- for (const statement of this.sf.statements) {
1120
- if (statement === fn) break;
1121
- visit(statement);
1122
- }
1123
- return safe;
1124
- }
1125
-
1126
- /**
1127
- * Whether a function is only defined where it stands: a declaration, or a
1128
- * variable's value, also through `memo` or `forwardRef`, which do not call it.
1129
- *
1130
- * @param {ts.Node} fn
1131
- */
1132
- onlyDefines(fn) {
1133
- if (ts.isFunctionDeclaration(fn)) return true;
1134
- let parent = fn.parent;
1135
- while (
1136
- ts.isParenthesizedExpression(parent) ||
1137
- (ts.isCallExpression(parent) &&
1138
- /^(?:memo|forwardRef)$/.test(this.calleeName(parent.expression) ?? ''))
1139
- ) {
1140
- parent = parent.parent;
1141
- }
1142
- return ts.isVariableDeclaration(parent);
1143
- }
1144
-
1145
- /**
1146
- * Whether an `onChange` a spread passes this element fires per edit in
1147
- * React: a text field with no `onChange` or `onInput` of its own.
1148
- *
1149
- * @param {ts.JsxOpeningLikeElement} element
1150
- */
1151
- takesChange(element) {
1152
- if (
1153
- !/^(?:input|textarea)$/.test(element.tagName.getText(this.sf)) &&
1154
- !this.isTextFieldComponent(element)
1155
- )
1156
- return false;
1157
- if (attributeOf(element, 'onChange') || attributeOf(element, 'onInput')) return false;
1158
- const type = attributeOf(element, 'type')?.initializer;
1159
- return !type || !ts.isStringLiteral(type) || TEXT_INPUT_TYPES.has(type.text);
1160
- }
1161
-
1162
- /**
1163
- * A text field that spreads a component's rest props passes on any
1164
- * `onChange` in them, which React fires per edit and Octane on commit. Take
1165
- * it out of the rest and pass it as `onInput`, before the spread, so a
1166
- * caller's own `onInput` still wins. Only when the rest is read nowhere
1167
- * else, since those reads would lose it.
1168
- *
1169
- * @param {ts.JsxOpeningLikeElement} field
1170
- */
1171
- planRestChange(field) {
1172
- for (const spread of field.attributes.properties) {
1173
- if (!ts.isJsxSpreadAttribute(spread)) continue;
1174
- // Props whose type has no `onChange` have none to pass on.
1175
- const type = this.projectType(spread.expression)?.type;
1176
- if (type && !(type.flags & ts.TypeFlags.Any) && !type.getProperty('onChange')) continue;
1177
- const expression = skipWrappers(spread.expression);
1178
- let rest = ts.isIdentifier(expression) ? asRest(this.declarationOf(expression)) : null;
1179
- // `const { style, ...native } = props` hands on what `props` holds:
1180
- // follow it to where the component receives `onChange`, so every field
1181
- // spread from it gets it.
1182
- while (rest && !this.namesChange(rest.parent)) {
1183
- const source = this.restSource(rest);
1184
- if (!source) break;
1185
- rest = source;
1186
- }
1187
- // A pattern that names `onChange` leaves none in the rest.
1188
- if (rest && this.namesChange(rest.parent)) continue;
1189
- if (
1190
- rest &&
1191
- !this.checker.resolveName('onChange', spread, ts.SymbolFlags.Value, false) &&
1192
- this.onlySpreadOntoFields(rest)
1193
- ) {
1194
- this.restChange.add(rest);
1195
- this.changeSpreads.add(spread);
1196
- } else {
1197
- this.note(
1198
- RULE.nativeChange,
1199
- 'warning',
1200
- spread,
1201
- `An \`onChange\` in this spread fires on commit (blur) in Octane, not per edit; pass it to the \`<${field.tagName.getText(this.sf)}>\` as \`onInput\`.`,
1202
- );
1203
- }
1204
- }
1205
- }
1206
-
1207
- /**
1208
- * Whether no read of a rest binding but its spreads onto text fields can
1209
- * see an `onChange` in it: other reads name another member (`props.type`).
1210
- *
1211
- * @param {ts.BindingElement} rest
1212
- */
1213
- onlySpreadOntoFields(rest) {
1214
- let only = true;
1215
- const visit = (/** @type {ts.Node} */ node) => {
1216
- if (!only) return;
1217
- if (ts.isIdentifier(node) && node !== rest.name && this.declarationOf(node) === rest) {
1218
- /** @type {ts.Node} */
1219
- let read = node;
1220
- while (isWrapper(read.parent)) read = read.parent;
1221
- const parent = read.parent;
1222
- if (ts.isJsxSpreadAttribute(parent)) {
1223
- only = this.takesChange(parent.parent.parent);
1224
- } else if (
1225
- ts.isVariableDeclaration(parent) &&
1226
- parent.initializer === read &&
1227
- ts.isObjectBindingPattern(parent.name)
1228
- ) {
1229
- // A destructuring hands `onChange` on to its own rest, if it has one.
1230
- const inner = asRest(parent.name.elements.find((e) => e.dotDotDotToken) ?? null);
1231
- only = !this.namesChange(parent.name) && (!inner || this.onlySpreadOntoFields(inner));
1232
- } else {
1233
- only =
1234
- ts.isPropertyAccessExpression(parent) &&
1235
- parent.expression === read &&
1236
- parent.name.text !== 'onChange';
1237
- }
1238
- }
1239
- ts.forEachChild(node, visit);
1240
- };
1241
- visit(ts.findAncestor(rest, ts.isFunctionLike) ?? this.sf);
1242
- return only;
1243
- }
1244
-
1245
- /**
1246
- * The rest binding a destructuring into `rest`'s pattern reads, or null:
1247
- * `props` for `native` in `const { style, ...native } = props`.
1248
- *
1249
- * @param {ts.BindingElement} rest
1250
- */
1251
- restSource(rest) {
1252
- const declaration = rest.parent.parent;
1253
- if (!ts.isVariableDeclaration(declaration) || !declaration.initializer) return null;
1254
- const source = skipWrappers(declaration.initializer);
1255
- return ts.isIdentifier(source) ? asRest(this.declarationOf(source)) : null;
1256
- }
1257
-
1258
- /**
1259
- * Whether a destructuring takes `onChange` out by name.
1260
- *
1261
- * @param {ts.ObjectBindingPattern | ts.ArrayBindingPattern} pattern
1262
- */
1263
- namesChange(pattern) {
1264
- return pattern.elements.some(
1265
- (e) => ts.isBindingElement(e) && (e.propertyName ?? e.name).getText(this.sf) === 'onChange',
1266
- );
1267
- }
1268
-
1269
- /**
1270
- * Whether `element` is a library component that renders a text `<input>`,
1271
- * such as Base UI's `Input`, imported by name or through a namespace.
1272
- *
1273
- * @param {ts.JsxOpeningLikeElement} element
1274
- */
1275
- isTextFieldComponent(element) {
1276
- /** @type {ts.Node} */
1277
- let root = element.tagName;
1278
- while (ts.isPropertyAccessExpression(root)) root = root.expression;
1279
- const entry = this.importOf(root);
1280
- if (!entry) return false;
1281
- const [, ...members] = element.tagName.getText(this.sf).split('.');
1282
- const name = (entry.namespace ? members : [entry.imported, ...members]).join('.');
1283
- return TEXT_FIELD_COMPONENTS[entry.module]?.includes(name) ?? false;
1284
- }
1285
-
1286
- /**
1287
- * The declaration a name refers to.
1288
- *
1289
- * @param {ts.Identifier} node
1290
- * @returns {ts.Declaration | null}
1291
- */
1292
- declarationOf(node) {
1293
- const parent = node.parent;
1294
- const symbol =
1295
- ts.isShorthandPropertyAssignment(parent) && parent.name === node
1296
- ? this.checker.getShorthandAssignmentValueSymbol(parent)
1297
- : this.checker.getSymbolAtLocation(node);
1298
- return symbol?.declarations?.[0] ?? null;
1299
- }
1300
-
1301
- /**
1302
- * The initializer of the `const` a name refers to, or null.
1303
- *
1304
- * @param {ts.Identifier} node
1305
- * @returns {ts.Expression | null}
1306
- */
1307
- constValue(node) {
1308
- const declaration = this.declarationOf(node);
1309
- if (
1310
- !declaration ||
1311
- !ts.isVariableDeclaration(declaration) ||
1312
- !declaration.initializer ||
1313
- !(ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const)
1314
- ) {
1315
- return null;
1316
- }
1317
- return declaration.initializer;
1318
- }
1319
-
1320
- /**
1321
- * The import a name refers to, or null when it refers to anything else,
1322
- * such as a local that shadows the import.
1323
- *
1324
- * @param {ts.Node} node
1325
- * @returns {Import | null}
1326
- */
1327
- importOf(node) {
1328
- if (!ts.isIdentifier(node)) return null;
1329
- const declaration = this.declarationOf(node);
1330
- return declaration ? (this.imports.get(declaration) ?? null) : null;
1331
- }
1332
-
1333
- /**
1334
- * The React or Octane export a callee names, through a named import or a
1335
- * namespace.
1336
- *
1337
- * @param {ts.Node} node
1338
- * @returns {string | null}
1339
- */
1340
- calleeName(node) {
1341
- return this.callee(node)?.name ?? null;
1342
- }
1343
-
1344
- /**
1345
- * @param {ts.Node} node
1346
- * @returns {{ name: string, module: string } | null}
1347
- */
1348
- callee(node) {
1349
- if (ts.isIdentifier(node)) {
1350
- const entry = this.importOf(node);
1351
- if (!entry || entry.namespace || entry.typeOnly || !isApiModule(entry.module)) return null;
1352
- return { name: entry.imported, module: entry.module };
1353
- }
1354
- if (ts.isPropertyAccessExpression(node)) {
1355
- const entry = this.importOf(node.expression);
1356
- if (!entry?.namespace || !isApiModule(entry.module)) return null;
1357
- return { name: node.name.text, module: entry.module };
1358
- }
1359
- return null;
1360
- }
1361
-
1362
- /** @param {ts.Node} node */
1363
- line(node) {
1364
- return this.sf.getLineAndCharacterOfPosition(node.getStart(this.sf)).line + 1;
1365
- }
1366
-
1367
- /**
1368
- * @param {string} rule
1369
- * @param {Severity} severity
1370
- * @param {ts.Node} node
1371
- * @param {string} message
1372
- */
1373
- note(rule, severity, node, message) {
1374
- this.notes.push({ rule, severity, line: this.line(node), message });
1375
- }
1376
-
1377
- /** @param {string} rule */
1378
- count(rule) {
1379
- this.rules[rule] = (this.rules[rule] ?? 0) + 1;
1380
- }
1381
-
1382
- /**
1383
- * Request an import from Octane and return the local name to use.
1384
- *
1385
- * @param {string} module
1386
- * @param {string} name
1387
- * @param {boolean} typeOnly
1388
- */
1389
- require(module, name, typeOnly) {
1390
- let names = this.added.get(module);
1391
- if (!names) this.added.set(module, (names = new Map()));
1392
- const existing = names.get(name);
1393
- if (existing) {
1394
- if (!typeOnly) existing.typeOnly = false;
1395
- return existing.local;
1396
- }
1397
- // A React import of the same name becomes this import.
1398
- const prior = this.apiLocals.get(name);
1399
- const collides =
1400
- (this.declared.has(name) || this.readsGlobal(name)) &&
1401
- !(prior && mapReactImport(prior.module, prior.imported, prior.typeOnly)?.name === name);
1402
- const local = collides ? `Octane${name[0].toUpperCase()}${name.slice(1)}` : name;
1403
- names.set(name, { local, typeOnly });
1404
- return local;
1405
- }
1406
-
1407
- /**
1408
- * Whether this module declares `symbol`, rather than the library or
1409
- * nothing at all.
1410
- *
1411
- * @param {ts.Symbol | undefined} symbol
1412
- */
1413
- declaresHere(symbol) {
1414
- return symbol?.declarations?.some((d) => d.getSourceFile() === this.sf) ?? false;
1415
- }
1416
-
1417
- /**
1418
- * Whether the module reads `name` as a global, such as the DOM's
1419
- * `MouseEvent`, which an import of the same name would shadow.
1420
- *
1421
- * @param {string} name
1422
- */
1423
- readsGlobal(name) {
1424
- /** @type {(node: ts.Node) => boolean} */
1425
- const visit = (node) => {
1426
- if (
1427
- ts.isIdentifier(node) &&
1428
- node.text === name &&
1429
- !isPropertyName(node) &&
1430
- !declaresName(node) &&
1431
- !this.declaresHere(this.checker.getSymbolAtLocation(node))
1432
- ) {
1433
- return true;
1434
- }
1435
- return ts.forEachChild(node, visit) ?? false;
1436
- };
1437
- return visit(this.sf) === true;
1438
- }
1439
-
1440
- // ---------------------------------------------------------------- emission
1441
-
1442
- /**
1443
- * The new text of `node`: a rule's replacement, or the original text with
1444
- * its children emitted in place.
1445
- *
1446
- * @param {ts.Node} node
1447
- * @param {Context} ctx
1448
- * @param {number} [start]
1449
- * @returns {string}
1450
- */
1451
- emit(node, ctx, start) {
1452
- if (ts.isIdentifier(node) && this.apiLocals.has(node.text) && !this.inImport(node)) {
1453
- const entry = this.importOf(node);
1454
- if (entry) {
1455
- this.used.add(entry.local);
1456
- if (!inTypeNode(node)) this.valueUses.add(entry.local);
1457
- }
1458
- }
1459
- const replaced = this.rewrite(node, ctx);
1460
- if (replaced !== null) return replaced;
1461
- const text = this.span(node, start ?? node.getStart(this.sf), node.end, ctx);
1462
- if ((ts.isStringLiteral(node) || ts.isTemplateLiteral(node)) && text.includes('\n')) {
1463
- return text.replaceAll('\n', LITERAL_NEWLINE);
1464
- }
1465
- return text;
1466
- }
1467
-
1468
- /** @param {ts.Node} node */
1469
- inImport(node) {
1470
- for (let current = node.parent; current; current = current.parent) {
1471
- if (ts.isImportDeclaration(current)) return true;
1472
- }
1473
- return false;
1474
- }
1475
-
1476
- /**
1477
- * The text of `node` between `from` and `to`, with every child inside that
1478
- * range emitted.
1479
- *
1480
- * @param {ts.Node} node
1481
- * @param {number} from
1482
- * @param {number} to
1483
- * @param {Context} ctx
1484
- */
1485
- span(node, from, to, ctx) {
1486
- let out = '';
1487
- let cursor = from;
1488
- const childCtx = ts.isJsxElement(node) || ts.isJsxFragment(node) ? ctx : PLAIN;
1489
- node.forEachChild((child) => {
1490
- if (child.pos === child.end) return;
1491
- const start = child.getStart(this.sf);
1492
- if (start < from || child.end > to) return;
1493
- out += this.source.slice(cursor, start);
1494
- if (ts.isJsxAttributes(child) && child.properties.every((a) => this.removed.has(a))) {
1495
- out = out.replace(/[ \t]+$/, '');
1496
- cursor = child.end;
1497
- return;
1498
- }
1499
- const jsxChild =
1500
- ts.isJsxElement(child) ||
1501
- ts.isJsxSelfClosingElement(child) ||
1502
- ts.isJsxFragment(child) ||
1503
- ts.isJsxExpression(child) ||
1504
- ts.isJsxText(child);
1505
- out += this.emit(child, jsxChild ? childCtx : PLAIN);
1506
- cursor = child.end;
1507
- });
1508
- return out + this.source.slice(cursor, to);
1509
- }
1510
-
1511
- /**
1512
- * @param {ts.Node} node
1513
- * @param {Context} ctx
1514
- * @returns {string | null}
1515
- */
1516
- rewrite(node, ctx) {
1517
- if (ts.isImportDeclaration(node)) return this.rewriteImport(node);
1518
- if (ts.isExportDeclaration(node) && node.moduleSpecifier) return this.rewriteReexport(node);
1519
- if (ts.isCallExpression(node)) return this.rewriteCall(node);
1520
- if (ts.isPropertyAccessExpression(node)) return this.rewriteMember(node);
1521
- if (ts.isQualifiedName(node)) return this.rewriteQualifiedType(node);
1522
- if (ts.isImportTypeNode(node)) return this.rewriteImportType(node);
1523
- if (ts.isTypeReferenceNode(node)) return this.rewriteTypeReference(node);
1524
- if (ts.isExpressionStatement(node)) return this.rewriteStatement(node);
1525
- if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) this.checkClass(node);
1526
- if (ts.isBinaryExpression(node)) {
1527
- const guarded = this.rewriteRenderProp(node);
1528
- if (guarded !== null) return guarded;
1529
- this.checkDefaultProps(node);
1530
- }
1531
- if (ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
1532
- return node.name.text in REACT_MODULES
1533
- ? this.rewriteAugmentation(node, node.name)
1534
- : this.rewriteSpecifier(node, node.name);
1535
- }
1536
- if (ts.isBindingElement(node) && this.restChange.has(node)) {
1537
- return 'onChange, ' + node.getText(this.sf);
1538
- }
1539
- if (ts.isVariableDeclaration(node) && this.descriptorComponents.has(node) && node.initializer) {
1540
- this.count(RULE.descriptorChildren);
1541
- return (
1542
- this.span(node, node.getStart(this.sf), node.initializer.getStart(this.sf), PLAIN) +
1543
- `${this.require('octane', 'descriptorChildren', false)}(${this.emit(node.initializer, PLAIN)})`
1544
- );
1545
- }
1546
- if (ts.isJsxText(node) && this.target === 'tsrx' && /\/[/*]/.test(node.text)) {
1547
- // TSRX reads `//` and `/*` in element text as comments, as JavaScript does.
1548
- return node.getText(this.sf).replace(/\/(?=[/*])/g, "{'/'}");
1549
- }
1550
- if (
1551
- ts.isIdentifier(node) &&
1552
- this.routerShell &&
1553
- Object.hasOwn(DOCUMENT_TAGS, node.text) &&
1554
- (ts.isJsxOpeningElement(node.parent) ||
1555
- ts.isJsxClosingElement(node.parent) ||
1556
- ts.isJsxSelfClosingElement(node.parent)) &&
1557
- node.parent.tagName === node
1558
- ) {
1559
- // The router's document components own the hydration root.
1560
- if (!ts.isJsxClosingElement(node.parent)) this.count(RULE.documentShell);
1561
- return this.require('@octanejs/tanstack-router', DOCUMENT_TAGS[node.text], false);
1562
- }
1563
- if (ts.isJsxAttributes(node)) return this.rewriteAttributes(node);
1564
- if ((ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node)) && this.islands.has(node)) {
1565
- this.count(RULE.reactCompat);
1566
- const island = this.require('octane/react', 'ReactCompat', false);
1567
- return `<${island}>${this.span(node, node.getStart(this.sf), node.end, PLAIN)}</${island}>`;
1568
- }
1569
- // An earlier run's wrapper goes: each run decides again whether its
1570
- // element throws or renders in an island.
1571
- if (ts.isJsxElement(node) && node.openingElement.tagName.getText(this.sf) === NO_PORT) {
1572
- const element = node.children.find(
1573
- (child) => ts.isJsxElement(child) || ts.isJsxSelfClosingElement(child),
1574
- );
1575
- if (element) return this.emit(element, ctx);
1576
- }
1577
- const error = this.unrenderable.get(node);
1578
- if (error !== undefined) {
1579
- const element =
1580
- (ts.isJsxElement(node) ? this.rewriteElement(node, ctx) : null) ??
1581
- this.span(node, node.getStart(this.sf), node.end, ctx);
1582
- return `<${NO_PORT} error="${error}">${element}</${NO_PORT}>`;
1583
- }
1584
- if (ts.isJsxElement(node)) return this.rewriteElement(node, ctx);
1585
- if (ts.isJsxExpression(node) && ctx.template) return this.rewriteHole(node);
1586
- // So does its `NoOctanePort`, which `run` adds back while one still throws.
1587
- if (ts.isFunctionDeclaration(node) && node.name?.text === NO_PORT) return DROP;
1588
- if (
1589
- ts.isFunctionDeclaration(node) ||
1590
- ts.isFunctionExpression(node) ||
1591
- ts.isArrowFunction(node)
1592
- ) {
1593
- const component = this.target === 'tsrx' ? this.rewriteComponent(node) : null;
1594
- const text =
1595
- component ??
1596
- (this.parameters.has(node) && node.body
1597
- ? this.head(node, node.body.getStart(this.sf)) + this.emit(node.body, PLAIN)
1598
- : null);
1599
- if (!ts.isFunctionDeclaration(node) || !this.descriptorComponents.has(node)) return text;
1600
- // A marked binding is a `const`; the function keeps its name.
1601
- this.count(RULE.descriptorChildren);
1602
- const fn = (text ?? this.span(node, node.getStart(this.sf), node.end, ctx)).replace(
1603
- /^export\s+/,
1604
- '',
1605
- );
1606
- const exported = node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword);
1607
- return `${exported ? 'export ' : ''}const ${node.name?.text} = ${this.require('octane', 'descriptorChildren', false)}(${fn});`;
1608
- }
1609
- return null;
1610
- }
1611
-
1612
- // ---------------------------------------------------------------- imports
1613
-
1614
- /** @param {ts.ImportDeclaration} node */
1615
- rewriteImport(node) {
1616
- const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
1617
- if (module === 'octane') return null;
1618
- if (module === '@react-three/fiber' && this.hasJsx) {
1619
- this.note(
1620
- RULE.unsupported,
1621
- 'error',
1622
- node,
1623
- "Three.js elements compile only in a `.three.tsrx` module, Octane's three renderer: move the scene components there and mount them with `root.render(Scene, props)`.",
1624
- );
1625
- }
1626
- if (module in REACT_MODULES) {
1627
- this.importSlots.push(node);
1628
- return `\u0000IMPORT${this.importSlots.length - 1}\u0000`;
1629
- }
1630
- const text =
1631
- this.rewritePackageNames(node, module) ?? this.rewriteSpecifier(node, node.moduleSpecifier);
1632
- // Analysis recorded the packages this module imports values from.
1633
- const port = node.importClause?.isTypeOnly === false ? (this.ports.get(module) ?? null) : null;
1634
- if (
1635
- !port ||
1636
- ts
1637
- .getLeadingCommentRanges(this.source, node.pos)
1638
- ?.some((range) => this.source.slice(range.pos, range.end).includes('No Octane port of'))
1639
- )
1640
- return text;
1641
- return `// ${portComment(port)}\n${text ?? node.getText(this.sf)}`;
1642
- }
1643
-
1644
- /**
1645
- * An import or re-export of a ported package whose port spells some of its
1646
- * names differently. A Radix package is a namespace of `@octanejs/radix`, so
1647
- * its namespace import becomes that namespace and its named imports read
1648
- * from it. Names the port lacks stay on the React package, for a person.
1649
- *
1650
- * @param {ts.ImportDeclaration | ts.ExportDeclaration} node
1651
- * @param {string} module
1652
- */
1653
- rewritePackageNames(node, module) {
1654
- const clause = ts.isImportDeclaration(node) ? node.importClause : node;
1655
- const namespace = radixNamespace(module);
1656
- const next = this.resolve(module);
1657
- // A default import; and a Radix package's re-export, which rewriteSpecifier reports.
1658
- if (!clause || next === null || (ts.isImportClause(clause) ? clause.name : namespace)) {
1659
- return null;
1660
- }
1661
- const keyword = ts.isImportClause(clause) ? 'import' : 'export';
1662
- const quote =
1663
- this.source[/** @type {ts.Expression} */ (node.moduleSpecifier).getStart(this.sf)];
1664
- const from = (/** @type {string} */ specifier) => `from ${quote}${specifier}${quote};`;
1665
- const type = clause.isTypeOnly ? 'type ' : '';
1666
- const bindings = ts.isImportClause(clause) ? clause.namedBindings : clause.exportClause;
1667
- if (bindings && ts.isNamespaceImport(bindings)) {
1668
- if (namespace === null) return null;
1669
- const local = bindings.name.text;
1670
- this.count(RULE.import);
1671
- return `import ${type}{ ${local === namespace ? local : `${namespace} as ${local}`} } ${from(next)}`;
1672
- }
1673
- if (!bindings || ts.isNamespaceExport(bindings)) return null;
1674
- /** @type {string[]} */
1675
- const kept = [];
1676
- /** @type {string[]} */
1677
- const values = [];
1678
- /** @type {string[]} */
1679
- const types = [];
1680
- let renamed = false;
1681
- for (const element of bindings.elements) {
1682
- const imported = (element.propertyName ?? element.name).text;
1683
- const local = element.name.text;
1684
- const name = mapPackageExport(module, imported);
1685
- if (name === null) {
1686
- this.note(RULE.binding, 'error', element, missingExport(module, imported));
1687
- kept.push(element.getText(this.sf));
1688
- continue;
1689
- }
1690
- renamed ||= name !== imported;
1691
- if (namespace === null) {
1692
- values.push(
1693
- `${element.isTypeOnly ? 'type ' : ''}${name === local ? name : `${name} as ${local}`}`,
1694
- );
1695
- } else if (RADIX_TYPES.has(name)) {
1696
- types.push(`type ${local} = ${this.require(next, namespace, true)}.${name};`);
1697
- } else {
1698
- values.push(name === local ? name : `${name}: ${local}`);
1699
- }
1700
- }
1701
- if (namespace === null && kept.length === 0 && !renamed) return null;
1702
- this.count(RULE.import);
1703
- const lines =
1704
- kept.length > 0 ? [`${keyword} ${type}{ ${kept.join(', ')} } ${from(module)}`] : [];
1705
- if (values.length > 0) {
1706
- lines.push(
1707
- namespace === null
1708
- ? `${keyword} ${type}{ ${values.join(', ')} } ${from(next)}`
1709
- : `const { ${values.join(', ')} } = ${this.require(next, namespace, false)};`,
1710
- );
1711
- }
1712
- return [...lines, ...types].join('\n');
1713
- }
1714
-
1715
- /**
1716
- * `DialogPrimitive.DialogTitle`, a member of a ported package's namespace
1717
- * import, as its port spells it.
1718
- *
1719
- * @param {ts.Node} namespace
1720
- * @param {ts.MemberName} member
1721
- * @param {Severity} severity of a member the port lacks
1722
- */
1723
- rewritePackageMember(namespace, member, severity) {
1724
- const entry = this.importOf(namespace);
1725
- if (!entry?.namespace) return null;
1726
- const name = mapPackageExport(entry.module, member.text);
1727
- if (name === member.text || this.resolve(entry.module) === null) return null;
1728
- if (name === null) {
1729
- if (!ts.isJsxClosingElement(member.parent.parent)) {
1730
- this.note(RULE.binding, severity, member, missingExport(entry.module, member.text));
1731
- }
1732
- return null;
1733
- }
1734
- this.count(RULE.import);
1735
- return `${entry.local}.${name}`;
1736
- }
1737
-
1738
- /** @param {ts.ExportDeclaration} node */
1739
- rewriteReexport(node) {
1740
- const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
1741
- const mapped = REACT_MODULES[module];
1742
- if (mapped) {
1743
- this.count(RULE.import);
1744
- return this.replaceSpecifier(
1745
- node,
1746
- /** @type {ts.Expression} */ (node.moduleSpecifier),
1747
- mapped,
1748
- );
1749
- }
1750
- return (
1751
- this.rewritePackageNames(node, module) ??
1752
- this.rewriteSpecifier(node, /** @type {ts.Expression} */ (node.moduleSpecifier))
1753
- );
1754
- }
1755
-
1756
- /**
1757
- * @param {ts.Node} node
1758
- * @param {ts.Expression} specifier
1759
- */
1760
- rewriteSpecifier(node, specifier) {
1761
- if (!ts.isStringLiteral(specifier)) return null;
1762
- const next = this.resolve(specifier.text);
1763
- if (next === null || next === specifier.text) return null;
1764
- const namespace = radixNamespace(specifier.text);
1765
- if (namespace !== null) {
1766
- // A re-export, `import()`, or type of the package would be the whole binding.
1767
- this.note(
1768
- RULE.binding,
1769
- 'error',
1770
- node,
1771
- `\`@octanejs/radix\` serves \`${specifier.text}\` as its \`${namespace}\` namespace; read it from \`import { ${namespace} } from '@octanejs/radix'\`.`,
1772
- );
1773
- return null;
1774
- }
1775
- this.count(RULE.import);
1776
- return this.replaceSpecifier(node, specifier, next);
1777
- }
1778
-
1779
- /**
1780
- * The new spelling of an import specifier, or null to keep it.
1781
- *
1782
- * @param {string} specifier
1783
- */
1784
- resolve(specifier) {
1785
- let next = this.resolved.get(specifier);
1786
- if (next === undefined) {
1787
- next = this.options.resolveSpecifier?.(specifier) ?? null;
1788
- this.resolved.set(specifier, next);
1789
- }
1790
- return next;
1791
- }
1792
-
1793
- /**
1794
- * `declare module 'react' { namespace JSX { … } }` types custom elements,
1795
- * which Octane reads from `octane/jsx-runtime`'s JSX namespace. Anything
1796
- * else it adds patches React's own types, which Octane does not use.
1797
- *
1798
- * @param {ts.ModuleDeclaration} node
1799
- * @param {ts.StringLiteral} specifier
1800
- */
1801
- rewriteAugmentation(node, specifier) {
1802
- const statements = node.body && ts.isModuleBlock(node.body) ? node.body.statements : [];
1803
- if (
1804
- statements.length > 0 &&
1805
- statements.every((s) => ts.isModuleDeclaration(s) && s.name.getText(this.sf) === 'JSX')
1806
- ) {
1807
- this.count(RULE.import);
1808
- this.augments = true;
1809
- return this.replaceSpecifier(node, specifier, 'octane/jsx-runtime');
1810
- }
1811
- this.note(
1812
- RULE.unsupported,
1813
- 'warning',
1814
- node,
1815
- `This augments React's own types, which Octane does not read; add what it declares to Octane's.`,
1816
- );
1817
- return null;
1818
- }
1819
-
1820
- /**
1821
- * @param {ts.Node} node
1822
- * @param {ts.Expression} specifier
1823
- * @param {string} next
1824
- */
1825
- replaceSpecifier(node, specifier, next) {
1826
- const quote = this.source[specifier.getStart(this.sf)];
1827
- return (
1828
- this.span(node, node.getStart(this.sf), specifier.getStart(this.sf), PLAIN) +
1829
- quote +
1830
- next +
1831
- quote +
1832
- // The rest is emitted, not copied: `import('./x').T<import('react').U>`
1833
- // has a nested specifier of its own.
1834
- this.span(node, specifier.end, node.end, PLAIN)
1835
- );
1836
- }
1837
-
1838
- /**
1839
- * `import('react').ReactNode` in a type: the module, and a React type name
1840
- * Octane spells differently, follow the same map as static imports.
1841
- *
1842
- * @param {ts.ImportTypeNode} node
1843
- */
1844
- rewriteImportType(node) {
1845
- const argument = node.argument;
1846
- if (!ts.isLiteralTypeNode(argument) || !ts.isStringLiteral(argument.literal)) return null;
1847
- const specifier = argument.literal;
1848
- const module = REACT_MODULES[specifier.text];
1849
- if (module === undefined) return this.rewriteSpecifier(node, specifier);
1850
- this.count(RULE.import);
1851
- const qualifier = node.qualifier;
1852
- const name = qualifier && ts.isIdentifier(qualifier) ? qualifier.text : null;
1853
- const renamed = name === null ? null : mapQualifiedType(name);
1854
- if (name !== null && renamed === null) {
1855
- this.note(RULE.unsupported, 'warning', node, `Octane has no type \`${name}\`.`);
1856
- }
1857
- const quote = this.source[specifier.getStart(this.sf)];
1858
- const head =
1859
- this.span(node, node.getStart(this.sf), specifier.getStart(this.sf), PLAIN) +
1860
- quote +
1861
- module +
1862
- quote;
1863
- if (!qualifier || renamed === null || renamed === name) {
1864
- return head + this.span(node, specifier.end, node.end, PLAIN);
1865
- }
1866
- return (
1867
- head +
1868
- this.source.slice(specifier.end, qualifier.getStart(this.sf)) +
1869
- renamed +
1870
- this.span(node, qualifier.end, node.end, PLAIN)
1871
- );
1872
- }
1873
-
1874
- /**
1875
- * Fill each React import placeholder. The first one carries every Octane
1876
- * import the module needs, the module's own specifiers first; the others
1877
- * disappear with their line.
1878
- *
1879
- * @param {string} code
1880
- */
1881
- finishImports(code) {
1882
- /** @type {Map<string, Map<string, { name: string, local: string, typeOnly: boolean }>>} */
1883
- const imports = new Map();
1884
- const add = (
1885
- /** @type {string} */ module,
1886
- /** @type {string} */ name,
1887
- /** @type {string} */ local,
1888
- /** @type {boolean} */ typeOnly,
1889
- ) => {
1890
- let names = imports.get(module);
1891
- if (!names) imports.set(module, (names = new Map()));
1892
- const existing = names.get(`${name} ${local}`);
1893
- if (existing) existing.typeOnly &&= typeOnly;
1894
- else names.set(`${name} ${local}`, { name, local, typeOnly });
1895
- };
1896
- /** React specifiers with no Octane export stay on React, for a person. */
1897
- const kept = new Map();
1898
- /** @type {string[]} Locals of React's `jsx` factories, which a JSX runtime consumer calls. */
1899
- const factories = [];
1900
- for (const node of this.importSlots) {
1901
- const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
1902
- const clause = node.importClause;
1903
- if (!clause) continue;
1904
- const bindings = clause.namedBindings;
1905
- const namespace =
1906
- clause.name?.text ??
1907
- (bindings && ts.isNamespaceImport(bindings) ? bindings.name.text : null);
1908
- // Members the rewrite could not map keep the namespace alive.
1909
- if (namespace && this.used.has(namespace)) add(REACT_MODULES[module], '*', namespace, false);
1910
- if (!bindings || !ts.isNamedImports(bindings)) continue;
1911
- for (const element of bindings.elements) {
1912
- const local = element.name.text;
1913
- if (!this.used.has(local)) continue;
1914
- const imported = (element.propertyName ?? element.name).text;
1915
- const typeOnly = clause.isTypeOnly || element.isTypeOnly;
1916
- const mapped = mapReactImport(module, imported, typeOnly);
1917
- if (mapped) {
1918
- // A name read only in types imports as a type, which bundlers elide.
1919
- add(mapped.module, mapped.name, local, typeOnly || !this.valueUses.has(local));
1920
- continue;
1921
- }
1922
- if (/^react\/jsx-(?:dev-)?runtime$/.test(module) && /^jsx(?:s|DEV)?$/.test(imported)) {
1923
- add('octane', 'createElement', 'createElement', false);
1924
- factories.push(local);
1925
- continue;
1926
- }
1927
- this.note(
1928
- RULE.unsupported,
1929
- 'error',
1930
- element,
1931
- UNSUPPORTED_VALUES[imported] ??
1932
- `\`${imported}\` from '${module}' has no Octane equivalent.`,
1933
- );
1934
- const spec =
1935
- (typeOnly ? 'type ' : '') + (imported === local ? local : `${imported} as ${local}`);
1936
- kept.set(module, [...(kept.get(module) ?? []), spec]);
1937
- }
1938
- }
1939
- for (const [module, names] of this.added) {
1940
- for (const [name, { local, typeOnly }] of names) add(module, name, local, typeOnly);
1941
- }
1942
-
1943
- /** @type {string[]} */
1944
- const lines = [];
1945
- const quote = (/** @type {string} */ module) => this.quote + module + this.quote;
1946
- for (const [module, names] of imports) {
1947
- const specs = [...names.values()];
1948
- for (const { name, local } of specs) {
1949
- if (name === '*') lines.push(`import * as ${local} from ${quote(module)};`);
1950
- }
1951
- const named = specs.filter(({ name }) => name !== '*');
1952
- if (named.length === 0) continue;
1953
- const allTypes = named.every(({ typeOnly }) => typeOnly);
1954
- const list = named.map(
1955
- ({ name, local, typeOnly }) =>
1956
- (typeOnly && !allTypes ? 'type ' : '') + (name === local ? name : `${name} as ${local}`),
1957
- );
1958
- lines.push(`import ${allTypes ? 'type ' : ''}{ ${list.join(', ')} } from ${quote(module)};`);
1959
- }
1960
- for (const [module, specs] of kept)
1961
- lines.push(`import { ${specs.join(', ')} } from ${quote(module)};`);
1962
- if (factories.length > 0) {
1963
- // React's runtime takes the key apart from the props; Octane's
1964
- // `createElement` reads it from them.
1965
- const params = this.isTypeScript()
1966
- ? 'type: Parameters<typeof createElement>[0], props: Record<string, unknown>, key?: string | number'
1967
- : 'type, props, key';
1968
- const [first, ...rest] = factories;
1969
- lines.push(
1970
- `function ${first}(${params}) {`,
1971
- `${this.indentUnit}return createElement(type, key === undefined ? props : { ...props, key });`,
1972
- '}',
1973
- ...rest.map((local) => `const ${local} = ${first};`),
1974
- );
1975
- }
1976
-
1977
- // In a script, `declare module` declares the module instead of adding to
1978
- // it: a module whose only import was `import 'react'` stays a module, and
1979
- // a script with a retargeted augmentation becomes one.
1980
- if (
1981
- lines.length === 0 &&
1982
- (this.importSlots.length > 0 || this.augments) &&
1983
- !this.otherModuleSyntax()
1984
- ) {
1985
- lines.push('export {};');
1986
- }
1987
- if (this.importSlots.length === 0) {
1988
- if (lines.length === 0) return code;
1989
- const at = this.insertionPoint(code);
1990
- return code.slice(0, at) + lines.join('\n') + '\n' + code.slice(at);
1991
- }
1992
- this.count(RULE.import);
1993
- return code.replace(/\u0000IMPORT(\d+)\u0000(\r?\n)?/g, (_, index, newline) =>
1994
- index === '0' && lines.length > 0 ? lines.join('\n') + (newline ?? '') : '',
1995
- );
1996
- }
1997
-
1998
- /** Whether the module has an import or export besides its React imports. */
1999
- otherModuleSyntax() {
2000
- return this.sf.statements.some(
2001
- (statement) =>
2002
- (ts.isImportDeclaration(statement) && !this.importSlots.includes(statement)) ||
2003
- ts.isImportEqualsDeclaration(statement) ||
2004
- ts.isExportDeclaration(statement) ||
2005
- ts.isExportAssignment(statement) ||
2006
- (ts.canHaveModifiers(statement) &&
2007
- ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)),
2008
- );
2009
- }
2010
-
2011
- /**
2012
- * Where new imports go when the module imported nothing from React: after
2013
- * the directive prologue and any leading comments.
2014
- *
2015
- * @param {string} code
2016
- */
2017
- insertionPoint(code) {
2018
- // Whole lines only: a shebang, blank lines, comments that end their
2019
- // line, and directive lines. Anything inserted here starts a line, so
2020
- // the Strong fallback can find its own directive line again. The
2021
- // comment on an unported package's import stays with it.
2022
- const prologue =
2023
- /^(?:#![^\n]*\n)?(?:[ \t]*(?:\/\/(?! No Octane port of)[^\n]*|\/\*[\s\S]*?\*\/[ \t]*|(['"])use [a-z ]+\1;?[^\n]*)?\r?\n)*/.exec(
2024
- code,
2025
- );
2026
- return prologue ? prologue[0].length : 0;
2027
- }
2028
-
2029
- /** @param {string} code */
2030
- addStrongDirective(code) {
2031
- this.count(RULE.strong);
2032
- const at = this.insertionPoint(code);
2033
- return code.slice(0, at) + '"use strong";\n' + (at === 0 ? '\n' : '') + code.slice(at);
2034
- }
2035
-
2036
- /** @param {string} code */
2037
- addJsxPragma(code) {
2038
- if (/@jsxImportSource\s+octane/.test(code)) return code;
2039
- const replaced = code.replace(/@jsxImportSource\s+\S+/, '@jsxImportSource octane');
2040
- return replaced !== code ? replaced : '/** @jsxImportSource octane */\n' + code;
2041
- }
2042
-
2043
- // ---------------------------------------------------------------- APIs
2044
-
2045
- /** @param {ts.PropertyAccessExpression} node */
2046
- rewriteMember(node) {
2047
- // `<Ctx.Provider value>` is `<Ctx value>` in Octane, as in React 19.
2048
- const tag = node.parent;
2049
- const isTag =
2050
- (ts.isJsxOpeningElement(tag) ||
2051
- ts.isJsxClosingElement(tag) ||
2052
- ts.isJsxSelfClosingElement(tag)) &&
2053
- tag.tagName === node;
2054
- // So is `const P = C.Provider`; a member of the provider (`C.Provider.x`)
2055
- // or a write to it stays.
2056
- const isValue =
2057
- !isTag &&
2058
- !(ts.isPropertyAccessExpression(tag) && tag.expression === node) &&
2059
- !(ts.isBinaryExpression(tag) && tag.left === node);
2060
- if (node.name.text === 'Provider' && (isTag || isValue) && this.isContext(node.expression)) {
2061
- if (!ts.isJsxClosingElement(tag)) this.count(RULE.provider);
2062
- return this.emit(node.expression, PLAIN);
2063
- }
2064
- const namespace = this.importOf(node.expression);
2065
- if (namespace?.namespace && namespace.module in REACT_MODULES) {
2066
- const name = node.name.text;
2067
- const mapped = mapReactImport(namespace.module, name, false);
2068
- if (!mapped) {
2069
- this.used.add(namespace.local);
2070
- this.note(
2071
- RULE.unsupported,
2072
- 'error',
2073
- node,
2074
- UNSUPPORTED_VALUES[name] ?? `\`${node.getText(this.sf)}\` has no Octane equivalent.`,
2075
- );
2076
- return null;
2077
- }
2078
- this.count(RULE.import);
2079
- return this.require(mapped.module, mapped.name, false);
2080
- }
2081
- const member = this.rewritePackageMember(node.expression, node.name, 'error');
2082
- if (member !== null) return member;
2083
- // event.nativeEvent: Octane events are already native.
2084
- if (node.name.text === 'nativeEvent' && this.isEventParameter(node.expression)) {
2085
- this.count(RULE.eventObject);
2086
- return this.emit(node.expression, PLAIN);
2087
- }
2088
- if (node.name.text === 'target' && this.targetsControl(node.expression)) {
2089
- this.count(RULE.eventObject);
2090
- return this.emit(node.expression, PLAIN) + '.currentTarget';
2091
- }
2092
- return null;
2093
- }
2094
-
2095
- /**
2096
- * Whether `node` names a global namespace React's types declare, such as
2097
- * `React` in `React.ReactNode` written without an import.
2098
- *
2099
- * @param {ts.EntityName} node
2100
- * @param {string} name
2101
- */
2102
- isGlobalNamespace(node, name) {
2103
- return (
2104
- ts.isIdentifier(node) &&
2105
- node.text === name &&
2106
- !this.checker.resolveName(name, node, ts.SymbolFlags.Namespace, false)
2107
- );
2108
- }
2109
-
2110
- /** @param {ts.QualifiedName} node */
2111
- rewriteQualifiedType(node) {
2112
- const member = this.rewritePackageMember(node.left, node.right, 'warning');
2113
- if (member !== null) return member;
2114
- const namespace = this.importOf(node.left);
2115
- if (
2116
- namespace
2117
- ? !namespace.namespace || !(namespace.module in REACT_MODULES)
2118
- : !this.isGlobalNamespace(node.left, 'React')
2119
- ) {
2120
- return null;
2121
- }
2122
- const name = mapQualifiedType(node.right.text);
2123
- if (!name) {
2124
- if (namespace) this.used.add(namespace.local);
2125
- this.note(
2126
- RULE.unsupported,
2127
- 'warning',
2128
- node,
2129
- `Octane has no type \`${node.getText(this.sf)}\`.`,
2130
- );
2131
- return null;
2132
- }
2133
- this.count(RULE.import);
2134
- return this.require('octane', name, true);
2135
- }
2136
-
2137
- /** @param {ts.TypeReferenceNode} node */
2138
- rewriteTypeReference(node) {
2139
- // The global `JSX` namespace React's types declared is Octane's export.
2140
- const name = node.typeName;
2141
- if (ts.isQualifiedName(name) && this.isGlobalNamespace(name.left, 'JSX')) {
2142
- this.require('octane', 'JSX', true);
2143
- }
2144
- return null;
2145
- }
2146
-
2147
- /** @param {ts.CallExpression} node */
2148
- rewriteCall(node) {
2149
- if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0]) {
2150
- const [specifier] = node.arguments;
2151
- const mapped = ts.isStringLiteral(specifier) ? REACT_MODULES[specifier.text] : undefined;
2152
- if (mapped === undefined) return this.rewriteSpecifier(node, specifier);
2153
- this.count(RULE.import);
2154
- return this.replaceSpecifier(node, specifier, mapped);
2155
- }
2156
- if (
2157
- ts.isPropertyAccessExpression(node.expression) &&
2158
- node.expression.name.text === 'render' &&
2159
- node.arguments.length === 1 &&
2160
- this.isRoot(node.expression.expression)
2161
- ) {
2162
- return this.rewriteRootRender(node, node.arguments[0]);
2163
- }
2164
- const callee = this.callee(node.expression);
2165
- // An Octane hook without a list already means "inferred".
2166
- if (!callee || callee.module === 'octane') return null;
2167
- const name = callee.name;
2168
- if (name === 'forwardRef') return this.rewriteForwardRef(node);
2169
- if (name === 'render' || name === 'hydrate') return this.rewriteLegacyRoot(node, name);
2170
- if (name === 'hydrateRoot' && node.arguments.length === 2) {
2171
- return this.rewriteRootRender(node, node.arguments[1]);
2172
- }
2173
- if (
2174
- (name === 'renderToString' || name === 'renderToStaticMarkup') &&
2175
- callee.module.startsWith('react-dom/server') &&
2176
- node.arguments.length === 1
2177
- ) {
2178
- // React returns the HTML; Octane returns `{ html, css }`.
2179
- this.count(RULE.serverRender);
2180
- return (
2181
- (this.rewriteRootRender(node, node.arguments[0]) ??
2182
- this.span(node, node.getStart(this.sf), node.end, PLAIN)) + '.html'
2183
- );
2184
- }
2185
- if (name === 'flushSync') {
2186
- this.note(
2187
- RULE.flushSync,
2188
- 'warning',
2189
- node,
2190
- "Octane's `flushSync` commits synchronously but leaves the commit's `useEffect`s queued, where React runs them before returning. If code after it reads what an effect did, use `useLayoutEffect` for that effect.",
2191
- );
2192
- return null;
2193
- }
2194
- if (name in DEPENDENCY_HOOKS) return this.rewriteDependencies(node, name);
2195
- return null;
2196
- }
2197
-
2198
- /**
2199
- * React runs an effect or memo without a dependency list on every render.
2200
- * Octane infers the list instead, so compatibility output passes `null` to
2201
- * keep React's behavior. Strong output leaves it to the compiler, which is
2202
- * what Strong asks for.
2203
- *
2204
- * @param {ts.CallExpression} node
2205
- * @param {string} name
2206
- */
2207
- rewriteDependencies(node, name) {
2208
- if (node.arguments.length !== DEPENDENCY_HOOKS[name]) return null;
2209
- if (this.strong) {
2210
- this.note(
2211
- RULE.deps,
2212
- 'info',
2213
- node,
2214
- `\`${name}\` had no dependency list, so React ran it on every render; Strong infers its dependencies.`,
2215
- );
2216
- return null;
2217
- }
2218
- this.count(RULE.deps);
2219
- const last = node.arguments[node.arguments.length - 1];
2220
- return (
2221
- this.span(node, node.getStart(this.sf), last.end, PLAIN) +
2222
- ', null' +
2223
- this.source.slice(last.end, node.end)
2224
- );
2225
- }
2226
-
2227
- /**
2228
- * `forwardRef((props, ref) => …)` becomes the inner function with `ref`
2229
- * read from props.
2230
- *
2231
- * @param {ts.CallExpression} node
2232
- */
2233
- rewriteForwardRef(node) {
2234
- const [render] = node.arguments;
2235
- if (
2236
- node.arguments.length !== 1 ||
2237
- !(ts.isArrowFunction(render) || ts.isFunctionExpression(render)) ||
2238
- render.parameters.length > 2
2239
- ) {
2240
- this.note(
2241
- RULE.forwardRef,
2242
- 'error',
2243
- node,
2244
- 'Unwrap this `forwardRef`: refs are ordinary props in Octane.',
2245
- );
2246
- return null;
2247
- }
2248
- this.count(RULE.forwardRef);
2249
- const [props, ref] = render.parameters;
2250
- const typeArgs = node.typeArguments;
2251
- const refType = typeArgs?.[0] ? this.emit(typeArgs[0], PLAIN) : this.refTypeOf(ref);
2252
- const propsNode = typeArgs?.[1] ?? props?.type;
2253
- const propsType = propsNode ? this.emit(propsNode, PLAIN) : null;
2254
- const refName = ref && ts.isIdentifier(ref.name) ? ref.name.text : null;
2255
- const refBinding = refName === null ? null : refName === 'ref' ? 'ref' : `ref: ${refName}`;
2256
-
2257
- // Splice `ref` into the props pattern in the pattern's own layout.
2258
- let pattern;
2259
- if (!props) pattern = refBinding ? `{ ${refBinding} }` : null;
2260
- else if (refBinding === null) pattern = this.emit(props.name, PLAIN);
2261
- else if (ts.isObjectBindingPattern(props.name)) {
2262
- const elements = props.name.elements;
2263
- const rest = elements.find((element) => element.dotDotDotToken);
2264
- const last = elements[elements.length - 1];
2265
- const multiline = this.source
2266
- .slice(props.name.getStart(this.sf), props.name.end)
2267
- .includes('\n');
2268
- if (rest) {
2269
- const separator = multiline ? `,\n${this.indentOf(rest)}` : ', ';
2270
- pattern =
2271
- this.span(props.name, props.name.getStart(this.sf), rest.getStart(this.sf), PLAIN) +
2272
- refBinding +
2273
- separator +
2274
- this.span(props.name, rest.getStart(this.sf), props.name.end, PLAIN);
2275
- } else if (last) {
2276
- const separator = multiline ? `,\n${this.indentOf(last)}` : ', ';
2277
- pattern =
2278
- this.span(props.name, props.name.getStart(this.sf), last.end, PLAIN) +
2279
- separator +
2280
- refBinding +
2281
- this.source.slice(last.end, props.name.end);
2282
- } else pattern = `{ ${refBinding} }`;
2283
- } else if (ts.isIdentifier(props.name) && props.name.text !== '_') {
2284
- pattern = `{ ${refBinding}, ...${props.name.text} }`;
2285
- } else {
2286
- pattern = `{ ${refBinding} }`;
2287
- }
2288
-
2289
- let annotation = '';
2290
- if (this.isTypeScript() && (propsType || refType)) {
2291
- const refProp = refType ? `{ ref?: ${this.require('octane', 'Ref', true)}<${refType}> }` : '';
2292
- annotation = ': ' + [propsType, refProp].filter(Boolean).join(' & ');
2293
- }
2294
- // Keep the parameter list's layout: the props parameter is replaced in
2295
- // place and the ref parameter goes with the comma before it.
2296
- const list = render.parameters;
2297
- let parameters;
2298
- if (pattern === null) parameters = '';
2299
- else if (!props) parameters = pattern + annotation;
2300
- else {
2301
- parameters =
2302
- this.source.slice(list.pos, props.getStart(this.sf)) +
2303
- pattern +
2304
- annotation +
2305
- this.source.slice(ref ? ref.end : props.end, list.end);
2306
- }
2307
- this.parameters.set(render, parameters);
2308
- return this.emit(render, PLAIN);
2309
- }
2310
-
2311
- /**
2312
- * A function's text up to its body, with any parameters a rule replaced.
2313
- *
2314
- * @param {ts.SignatureDeclaration & { body?: ts.Node }} node
2315
- * @param {number} end
2316
- */
2317
- head(node, end) {
2318
- const parameters = this.parameters.get(node);
2319
- if (parameters === undefined) return this.span(node, node.getStart(this.sf), end, PLAIN);
2320
- return (
2321
- this.span(node, node.getStart(this.sf), node.parameters.pos, PLAIN) +
2322
- parameters +
2323
- this.span(node, node.parameters.end, end, PLAIN)
2324
- );
2325
- }
2326
-
2327
- /** @param {ts.ParameterDeclaration | undefined} ref */
2328
- refTypeOf(ref) {
2329
- const type = ref?.type;
2330
- if (type && ts.isTypeReferenceNode(type) && type.typeArguments?.length === 1) {
2331
- return this.emit(type.typeArguments[0], PLAIN);
2332
- }
2333
- return null;
2334
- }
2335
-
2336
- isTypeScript() {
2337
- return /\.[cm]?tsx?$/.test(this.filename);
2338
- }
2339
-
2340
- /**
2341
- * @param {ts.CallExpression} node
2342
- * @param {'render' | 'hydrate'} name
2343
- */
2344
- rewriteLegacyRoot(node, name) {
2345
- const [element, container, callback] = node.arguments;
2346
- if (!element || !container) return null;
2347
- if (callback) {
2348
- this.note(
2349
- RULE.legacyRoot,
2350
- 'warning',
2351
- node,
2352
- 'The legacy render callback was dropped; run it from an effect.',
2353
- );
2354
- }
2355
- this.count(RULE.legacyRoot);
2356
- const elementText = this.rootComponent(element) ?? this.emit(element, PLAIN);
2357
- const containerText = this.emit(container, PLAIN);
2358
- return name === 'render'
2359
- ? `${this.require('octane', 'createRoot', false)}(${containerText}).render(${elementText})`
2360
- : `${this.require('octane', 'hydrateRoot', false)}(${containerText}, ${elementText})`;
2361
- }
2362
-
2363
- /**
2364
- * Whether `node` is a root `createRoot` made: the call itself, or a
2365
- * `const` bound to it.
2366
- *
2367
- * @param {ts.Expression} node
2368
- */
2369
- isRoot(node) {
2370
- node = skipParens(node);
2371
- const value = ts.isIdentifier(node) ? this.constValue(node) : node;
2372
- return (
2373
- !!value && ts.isCallExpression(value) && this.calleeName(value.expression) === 'createRoot'
2374
- );
2375
- }
2376
-
2377
- /**
2378
- * `root.render(<App a={1} />)` and `root.render(createElement(App, props))`
2379
- * are `root.render(App, props)`, which mounts the component without an
2380
- * element: the generic element renderer stays out of the bundle. So are
2381
- * `hydrateRoot(c, <App />)` and the server renderers' element argument.
2382
- *
2383
- * @param {ts.CallExpression} node
2384
- * @param {ts.Expression} argument the element, the call's last argument
2385
- */
2386
- rewriteRootRender(node, argument) {
2387
- const component = this.rootComponent(argument);
2388
- if (component === null) return null;
2389
- this.count(RULE.rootRender);
2390
- return (
2391
- this.span(node, node.getStart(this.sf), argument.getStart(this.sf), PLAIN) +
2392
- component +
2393
- this.span(node, argument.end, node.end, PLAIN)
2394
- );
2395
- }
2396
-
2397
- /**
2398
- * `App` or `App, props` for an element of a component with no key, ref,
2399
- * or children, through a `<StrictMode>` wrapper, else null.
2400
- *
2401
- * @param {ts.Expression} expression
2402
- * @returns {string | null}
2403
- */
2404
- rootComponent(expression) {
2405
- let node = skipParens(expression);
2406
- if (ts.isJsxElement(node) && this.calleeName(node.openingElement.tagName) === 'StrictMode') {
2407
- const children = node.children.filter(
2408
- (child) => !(ts.isJsxText(child) && child.containsOnlyTriviaWhiteSpaces),
2409
- );
2410
- if (children.length !== 1 || !isJsx(children[0])) return null;
2411
- node = /** @type {ts.JsxElement | ts.JsxSelfClosingElement | ts.JsxFragment} */ (children[0]);
2412
- }
2413
- if (ts.isJsxSelfClosingElement(node)) {
2414
- const tag = node.tagName;
2415
- if (!ts.isIdentifier(tag) && !ts.isPropertyAccessExpression(tag)) return null;
2416
- if (!isComponentName(tag.getText(this.sf).split('.').pop() ?? '')) return null;
2417
- /** @type {string[]} */
2418
- const props = [];
2419
- for (const property of node.attributes.properties) {
2420
- if (ts.isJsxSpreadAttribute(property)) {
2421
- props.push(`...${this.emit(property.expression, PLAIN)}`);
2422
- continue;
2423
- }
2424
- const name = property.name.getText(this.sf);
2425
- if (name === 'key' || name === 'ref') return null;
2426
- const key = /^[A-Za-z_$][\w$]*$/.test(name) ? name : JSON.stringify(name);
2427
- const value = property.initializer;
2428
- if (!value) props.push(`${key}: true`);
2429
- else if (ts.isStringLiteral(value)) props.push(`${key}: ${value.getText(this.sf)}`);
2430
- else if (ts.isJsxExpression(value) && value.expression)
2431
- props.push(`${key}: ${this.emit(value.expression, PLAIN)}`);
2432
- else return null;
2433
- }
2434
- const type = this.emit(tag, PLAIN);
2435
- return props.length === 0 ? type : `${type}, { ${props.join(', ')} }`;
2436
- }
2437
- if (ts.isCallExpression(node) && this.calleeName(node.expression) === 'createElement') {
2438
- const [type, props, ...children] = node.arguments;
2439
- if (!type || children.length > 0) return null;
2440
- if (!(ts.isIdentifier(type) || ts.isPropertyAccessExpression(type))) return null;
2441
- if (!isComponentName(type.getText(this.sf).split('.').pop() ?? '')) return null;
2442
- const text = this.emit(type, PLAIN);
2443
- return !props || isNullish(props) ? text : `${text}, ${this.emit(props, PLAIN)}`;
2444
- }
2445
- return null;
2446
- }
2447
-
2448
- /** @param {ts.ExpressionStatement} node */
2449
- rewriteStatement(node) {
2450
- const call = node.expression;
2451
- if (
2452
- ts.isCallExpression(call) &&
2453
- call.arguments.length === 0 &&
2454
- ts.isPropertyAccessExpression(call.expression) &&
2455
- call.expression.name.text === 'persist' &&
2456
- this.isEventParameter(call.expression.expression)
2457
- ) {
2458
- // Octane never pools events, so there is nothing to persist.
2459
- this.count(RULE.eventObject);
2460
- return DROP;
2461
- }
2462
- return null;
2463
- }
2464
-
2465
- /**
2466
- * The parameter `node` refers to, with its function.
2467
- *
2468
- * @param {ts.Node} node
2469
- * @returns {{ fn: ts.SignatureDeclaration, param: ts.ParameterDeclaration } | null}
2470
- */
2471
- parameterOf(node) {
2472
- if (!ts.isIdentifier(node)) return null;
2473
- const param = this.declarationOf(node);
2474
- if (!param || !ts.isParameter(param)) return null;
2475
- return { fn: /** @type {ts.SignatureDeclaration} */ (param.parent), param };
2476
- }
2477
-
2478
- /** @param {ts.Node} node */
2479
- isEventParameter(node) {
2480
- const found = this.parameterOf(node);
2481
- if (!found) return false;
2482
- const type = found.param.type;
2483
- if (type && ts.isTypeReferenceNode(type) && /Event$/.test(type.typeName.getText(this.sf))) {
2484
- return true;
2485
- }
2486
- return this.handlerAttribute(found.fn) !== null;
2487
- }
2488
-
2489
- /**
2490
- * The `on*` attribute an inline handler is passed to.
2491
- *
2492
- * @param {ts.Node} fn
2493
- */
2494
- handlerAttribute(fn) {
2495
- const container = fn.parent;
2496
- if (!container || !ts.isJsxExpression(container)) return null;
2497
- const attribute = container.parent;
2498
- return ts.isJsxAttribute(attribute) && /^on[A-Z]/.test(attribute.name.getText(this.sf))
2499
- ? attribute
2500
- : null;
2501
- }
2502
-
2503
- /**
2504
- * Whether `event.target` is the form control the handler is attached to, so
2505
- * it can read Octane's typed `currentTarget` instead. Octane types events as
2506
- * the native `Event`, whose `target` is an untyped `EventTarget`.
2507
- *
2508
- * @param {ts.Node} node
2509
- */
2510
- targetsControl(node) {
2511
- const found = this.parameterOf(node);
2512
- if (!found) return false;
2513
- // Unannotated, the project's types still name a handler a component
2514
- // passes on to a control: `<Input onChange={(e) => …}>`. A library may
2515
- // wrap the event (Base UI's `BaseUIEvent<ChangeEvent<…>>`); its first
2516
- // type argument is still the element the handler is attached to.
2517
- const inferred = found.param.type ? null : this.projectType(found.param);
2518
- const type =
2519
- found.param.type?.getText(this.sf) ??
2520
- (inferred ? inferred.checker.typeToString(inferred.type) : '');
2521
- if (
2522
- /\b(?:Change|Form|Focus)Event<\s*(?:HTML(?:Input|TextArea|Select)Element\s*\|?\s*)+[,>]/.test(
2523
- type,
2524
- )
2525
- )
2526
- return true;
2527
- const attribute = this.handlerAttribute(found.fn);
2528
- if (!attribute || !/^on(Change|Input|Focus|Blur)/.test(attribute.name.getText(this.sf)))
2529
- return false;
2530
- const tag = attribute.parent.parent.tagName.getText(this.sf);
2531
- return tag === 'input' || tag === 'textarea' || tag === 'select';
2532
- }
2533
-
2534
- /** @param {ts.ClassDeclaration | ts.ClassExpression} node */
2535
- checkClass(node) {
2536
- const base = node.heritageClauses?.find(
2537
- (clause) => clause.token === ts.SyntaxKind.ExtendsKeyword,
2538
- )?.types[0]?.expression;
2539
- const name = base && this.calleeName(base);
2540
- if (name !== 'Component' && name !== 'PureComponent') return;
2541
- const boundary = node.members.some(
2542
- (member) =>
2543
- member.name &&
2544
- /^(componentDidCatch|getDerivedStateFromError)$/.test(member.name.getText(this.sf)),
2545
- );
2546
- this.note(
2547
- RULE.classComponent,
2548
- 'error',
2549
- node,
2550
- boundary
2551
- ? `Error boundary \`${node.name?.text ?? 'class'}\` needs a rewrite: use \`@try { … } @catch (error) { … }\` or Octane's \`ErrorBoundary\`.`
2552
- : `Class component \`${node.name?.text ?? 'class'}\` needs a rewrite as a function component.`,
2553
- );
2554
- }
2555
-
2556
- /** @param {ts.BinaryExpression} node */
2557
- checkDefaultProps(node) {
2558
- if (
2559
- node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
2560
- ts.isPropertyAccessExpression(node.left) &&
2561
- node.left.name.text === 'defaultProps'
2562
- ) {
2563
- this.note(
2564
- RULE.defaultProps,
2565
- 'warning',
2566
- node,
2567
- 'Function components ignore `defaultProps`; move the defaults into the props destructuring.',
2568
- );
2569
- }
2570
- }
2571
-
2572
- // ---------------------------------------------------------------- JSX
2573
-
2574
- /** @param {ts.JsxAttributes} node */
2575
- rewriteAttributes(node) {
2576
- const element = node.parent;
2577
- const tag = element.tagName.getText(this.sf);
2578
- const intrinsic = /^[a-z]/.test(tag);
2579
- // A library text field takes `onInput` for `onChange` as `<input>` does;
2580
- // its other props are its own.
2581
- const textField = !intrinsic && this.isTextFieldComponent(element);
2582
- const spread = node.properties.some(ts.isJsxSpreadAttribute);
2583
- const attributes = node.properties;
2584
-
2585
- let out = '';
2586
- let cursor = node.getStart(this.sf);
2587
- for (const attribute of attributes) {
2588
- const start = attribute.getStart(this.sf);
2589
- if (this.removed.has(attribute)) {
2590
- // Drop the attribute and the whitespace on one side of it.
2591
- if (out === '' && cursor === start) {
2592
- cursor =
2593
- attribute.end +
2594
- (this.source.slice(attribute.end).length -
2595
- this.source.slice(attribute.end).trimStart().length);
2596
- if (attribute === attributes[attributes.length - 1]) cursor = attribute.end;
2597
- } else {
2598
- out = out.replace(/\s+$/, '') + this.source.slice(cursor, start).replace(/\s+$/, '');
2599
- cursor = attribute.end;
2600
- }
2601
- continue;
2602
- }
2603
- out += this.source.slice(cursor, start);
2604
- cursor = attribute.end;
2605
- if (ts.isJsxSpreadAttribute(attribute) && this.changeSpreads.has(attribute)) {
2606
- // On the spread's own line when it has one.
2607
- this.count(RULE.nativeChange);
2608
- const line = this.source.slice(this.source.lastIndexOf('\n', start - 1), start);
2609
- out += 'onInput={onChange}' + (/^\n[ \t]*$/.test(line) ? line : ' ');
2610
- }
2611
- if (!ts.isJsxAttribute(attribute) || !(intrinsic || textField)) {
2612
- out += this.emit(attribute, PLAIN);
2613
- continue;
2614
- }
2615
- const name = attribute.name.getText(this.sf);
2616
- if (
2617
- name === 'className' &&
2618
- intrinsic &&
2619
- this.target === 'tsrx' &&
2620
- !attributeOf(element, 'class') &&
2621
- !spread
2622
- ) {
2623
- this.count(RULE.className);
2624
- out += 'class' + this.emitInitializer(attribute);
2625
- } else if ((name === 'onChange' || name === 'onChangeCapture') && this.isTextEntry(element)) {
2626
- const input = name === 'onChange' ? 'onInput' : 'onInputCapture';
2627
- if (attributeOf(element, input)) {
2628
- this.note(
2629
- RULE.nativeChange,
2630
- 'warning',
2631
- attribute,
2632
- `\`${name}\` beside \`${input}\` now fires on commit (blur), not per edit.`,
2633
- );
2634
- out += this.emit(attribute, PLAIN);
2635
- } else {
2636
- this.count(RULE.nativeChange);
2637
- out += input + this.emitInitializer(attribute);
2638
- }
2639
- } else {
2640
- out += this.emit(attribute, PLAIN);
2641
- }
2642
- }
2643
- return out + this.source.slice(cursor, node.end);
2644
- }
2645
-
2646
- /** @param {ts.JsxAttribute} attribute */
2647
- emitInitializer(attribute) {
2648
- if (!attribute.initializer) return '';
2649
- return (
2650
- this.source.slice(attribute.name.end, attribute.initializer.getStart(this.sf)) +
2651
- this.emit(attribute.initializer, PLAIN)
2652
- );
2653
- }
2654
-
2655
- /**
2656
- * Whether `element` is a text-entry control, where React's `onChange` fires
2657
- * per edit and the native `change` fires on commit.
2658
- *
2659
- * @param {ts.JsxOpeningLikeElement} element
2660
- */
2661
- isTextEntry(element) {
2662
- const tag = element.tagName.getText(this.sf);
2663
- if (tag === 'textarea') return true;
2664
- if (tag !== 'input' && !this.isTextFieldComponent(element)) return false;
2665
- const type = attributeOf(element, 'type');
2666
- if (!type) return true;
2667
- const value = type.initializer;
2668
- if (value && ts.isStringLiteral(value)) return TEXT_INPUT_TYPES.has(value.text);
2669
- this.note(
2670
- RULE.nativeChange,
2671
- 'warning',
2672
- element,
2673
- 'This `<input>` has a dynamic `type`; if it can be a text field, use `onInput` for per-edit updates.',
2674
- );
2675
- return false;
2676
- }
2677
-
2678
- /**
2679
- * @param {ts.JsxElement} node
2680
- * @param {Context} ctx
2681
- */
2682
- rewriteElement(node, ctx) {
2683
- if (this.bare.has(node)) {
2684
- return (
2685
- '<>' +
2686
- this.span(node, node.openingElement.end, node.closingElement.getStart(this.sf), ctx) +
2687
- '</>'
2688
- );
2689
- }
2690
- const tag = node.openingElement.tagName;
2691
- // A `descriptorChildren` component receives its children as elements, as
2692
- // in React; `@if` or `@for` there would hand it a fragment instead.
2693
- const declaration = ts.isIdentifier(tag) ? this.declarationOf(tag) : null;
2694
- if (
2695
- declaration &&
2696
- this.descriptorComponents.has(/** @type {ts.VariableDeclaration} */ (declaration))
2697
- ) {
2698
- return this.span(node, node.getStart(this.sf), node.end, PLAIN);
2699
- }
2700
- const name = this.calleeName(tag);
2701
- if (name === 'StrictMode') {
2702
- // Octane's StrictMode is a pass-through wrapper.
2703
- this.count(RULE.strictMode);
2704
- return this.emitChildren(node, ctx);
2705
- }
2706
- if (name === 'Suspense' && ctx.template) return this.rewriteSuspense(node);
2707
- if (ts.isPropertyAccessExpression(tag) && this.isContext(tag.expression)) {
2708
- if (tag.name.text === 'Consumer') return this.rewriteConsumer(node, ctx);
2709
- }
2710
- return null;
2711
- }
2712
-
2713
- /**
2714
- * Whether `node` is a React context, by where it comes from: a
2715
- * `createContext` call here, or an export the project knows is one. Only
2716
- * a package's export, which the codemod cannot see, is judged by its name.
2717
- *
2718
- * @param {ts.Expression} node
2719
- */
2720
- isContext(node) {
2721
- if (!ts.isIdentifier(node)) return false;
2722
- const declaration = this.declarationOf(node);
2723
- if (declaration && ts.isVariableDeclaration(declaration)) {
2724
- return !!declaration.initializer && this.createsContext(declaration.initializer);
2725
- }
2726
- const entry = declaration ? this.imports.get(declaration) : null;
2727
- if (!entry || entry.namespace) return false;
2728
- const name = entry.imported === 'default' ? entry.local : entry.imported;
2729
- return this.options.isContext?.(entry.module, entry.imported) ?? /Context$/.test(name);
2730
- }
2731
-
2732
- /**
2733
- * Whether `node` evaluates to a `createContext` result on every branch.
2734
- *
2735
- * @param {ts.Expression} node
2736
- * @returns {boolean}
2737
- */
2738
- createsContext(node) {
2739
- node = skipParens(node);
2740
- if (ts.isConditionalExpression(node)) {
2741
- return this.createsContext(node.whenTrue) && this.createsContext(node.whenFalse);
2742
- }
2743
- return ts.isCallExpression(node) && this.calleeName(node.expression) === 'createContext';
2744
- }
2745
-
2746
- /**
2747
- * `typeof children === 'function'` also holds for a compiled children
2748
- * block, which renders through Octane rather than being called, so the
2749
- * check also asks `isChildrenBlock`.
2750
- *
2751
- * @param {ts.BinaryExpression} node
2752
- */
2753
- rewriteRenderProp(node) {
2754
- const op = node.operatorToken.kind;
2755
- if (op !== ts.SyntaxKind.EqualsEqualsEqualsToken && op !== ts.SyntaxKind.EqualsEqualsToken) {
2756
- return null;
2757
- }
2758
- if (!ts.isTypeOfExpression(node.left) || !ts.isStringLiteral(node.right)) return null;
2759
- const operand = skipParens(node.left.expression);
2760
- const name = ts.isIdentifier(operand)
2761
- ? operand.text
2762
- : ts.isPropertyAccessExpression(operand)
2763
- ? operand.name.text
2764
- : null;
2765
- if (node.right.text !== 'function' || name !== 'children') return null;
2766
- const parent = node.parent;
2767
- if (ts.isBinaryExpression(parent) && /\bisChildrenBlock\(/.test(parent.getText(this.sf))) {
2768
- return null;
2769
- }
2770
- this.count(RULE.renderProp);
2771
- const check = this.require('octane', 'isChildrenBlock', false);
2772
- return `(${this.span(node, node.getStart(this.sf), node.end, PLAIN)} && !${check}(${this.emit(operand, PLAIN)}))`;
2773
- }
2774
-
2775
- /**
2776
- * The children of `node` as one renderable: the sole element, or a
2777
- * fragment around several.
2778
- *
2779
- * @param {ts.JsxElement | ts.JsxFragment} node
2780
- * @param {Context} ctx
2781
- */
2782
- emitChildren(node, ctx) {
2783
- const children = contentOf(node);
2784
- if (children.length === 1 && isJsx(children[0])) return this.emit(children[0], ctx);
2785
- const first = node.children[0];
2786
- const last = node.children[node.children.length - 1];
2787
- if (!first) return '<></>';
2788
- return '<>' + this.span(node, first.pos, last.end, ctx) + '</>';
2789
- }
2790
-
2791
- /**
2792
- * `<Ctx.Consumer>{(value) => …}</Ctx.Consumer>` reads the context in a
2793
- * nested template scope, where a hook is legal.
2794
- *
2795
- * @param {ts.JsxElement} node
2796
- * @param {Context} ctx
2797
- */
2798
- rewriteConsumer(node, ctx) {
2799
- const tag = /** @type {ts.PropertyAccessExpression} */ (node.openingElement.tagName);
2800
- const children = contentOf(node);
2801
- const render =
2802
- children.length === 1 && ts.isJsxExpression(children[0]) ? children[0].expression : null;
2803
- const fn = render && skipParens(render);
2804
- if (
2805
- !ctx.template ||
2806
- !fn ||
2807
- !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) ||
2808
- fn.parameters.length !== 1 ||
2809
- ts.isBlock(fn.body)
2810
- ) {
2811
- this.note(
2812
- RULE.consumer,
2813
- 'error',
2814
- node,
2815
- '`Context.Consumer` does not exist in Octane; read the context with `use(Context)`.',
2816
- );
2817
- return null;
2818
- }
2819
- this.count(RULE.consumer);
2820
- const useContext = this.require('octane', 'useContext', false);
2821
- const param = this.emit(fn.parameters[0].name, PLAIN);
2822
- const body = skipParens(fn.body);
2823
- const output = isJsx(body) ? this.emit(body, TEMPLATE) : `<>{${this.emit(body, PLAIN)}}</>`;
2824
- return `@{ const ${param} = ${useContext}(${this.emit(tag.expression, PLAIN)}); ${output} }`;
2825
- }
2826
-
2827
- /**
2828
- * `<Suspense fallback={f}>…</Suspense>` is the template boundary
2829
- * `@try { … } @pending { f }`.
2830
- *
2831
- * @param {ts.JsxElement} node
2832
- */
2833
- rewriteSuspense(node) {
2834
- const attributes = node.openingElement.attributes.properties.filter(
2835
- (a) => !this.removed.has(a),
2836
- );
2837
- const fallback = attributes[0];
2838
- if (
2839
- attributes.length !== 1 ||
2840
- !ts.isJsxAttribute(fallback) ||
2841
- fallback.name.getText(this.sf) !== 'fallback' ||
2842
- !fallback.initializer
2843
- ) {
2844
- return null;
2845
- }
2846
- let pending;
2847
- const value = fallback.initializer;
2848
- if (ts.isStringLiteral(value)) pending = `<>{${value.getText(this.sf)}}</>`;
2849
- else if (ts.isJsxExpression(value) && value.expression) {
2850
- const expression = skipParens(value.expression);
2851
- if (isJsx(expression)) pending = this.relative(this.emit(expression, TEMPLATE), expression);
2852
- else if (isNullish(expression)) pending = '<></>';
2853
- else pending = `<>{${this.emit(expression, PLAIN)}}</>`;
2854
- } else return null;
2855
- this.count(RULE.try);
2856
- const body = this.relative(this.emitChildren(node, TEMPLATE), node, this.indentUnit);
2857
- return this.absolute(this.block('@try', body) + ' ' + this.block('@pending', pending), node);
2858
- }
2859
-
2860
- // Directive text is built relative to its first line: line 1 carries no
2861
- // indentation and every later line is indented from that line's level.
2862
- // `absolute` re-anchors it where it lands in the module.
2863
-
2864
- /**
2865
- * Source text emitted for `node`, re-based so `node`'s own line is level 0.
2866
- *
2867
- * @param {string} text
2868
- * @param {ts.Node} node
2869
- * @param {string} [deeper] how far inside `node`'s line the text's own
2870
- * first line sat, such as the children of an element
2871
- */
2872
- relative(text, node, deeper = '') {
2873
- const from = this.indentOf(node) + deeper;
2874
- return text
2875
- .split('\n')
2876
- .map((line, i) => {
2877
- if (i === 0) return line;
2878
- if (line.trim() === '') return '';
2879
- return line.startsWith(from) ? line.slice(from.length) : line.trimStart();
2880
- })
2881
- .join('\n');
2882
- }
2883
-
2884
- /**
2885
- * @param {string} text relative text
2886
- * @param {ts.Node} node the node it replaces
2887
- */
2888
- absolute(text, node) {
2889
- const indent = this.indentOf(node);
2890
- return text
2891
- .split('\n')
2892
- .map((line, i) => (i === 0 || line === '' ? line : indent + line))
2893
- .join('\n');
2894
- }
2895
-
2896
- /**
2897
- * `head { body }` on one line when the body fits on one, else with the body
2898
- * on its own lines one level in.
2899
- *
2900
- * @param {string} head
2901
- * @param {string} body relative text
2902
- */
2903
- block(head, body) {
2904
- if (!body.includes('\n') && !body.startsWith('@') && head.length + body.length < 80) {
2905
- return `${head} { ${body} }`;
2906
- }
2907
- const unit = this.indentUnit;
2908
- const lines = body.split('\n').map((line) => (line === '' ? '' : unit + line));
2909
- return `${head} {\n${lines.join('\n')}\n}`;
2910
- }
2911
-
2912
- /**
2913
- * The text before `node` on its line.
2914
- *
2915
- * @param {ts.Node} node
2916
- */
2917
- linePrefix(node) {
2918
- const start = node.getStart(this.sf);
2919
- return this.source.slice(this.source.lastIndexOf('\n', start - 1) + 1, start);
2920
- }
2921
-
2922
- /** @param {ts.Node} node */
2923
- indentOf(node) {
2924
- const prefix = this.linePrefix(node);
2925
- return prefix.slice(0, prefix.length - prefix.trimStart().length);
2926
- }
2927
-
2928
- /**
2929
- * Template control flow for a JSX child hole.
2930
- *
2931
- * @param {ts.JsxExpression} node
2932
- */
2933
- rewriteHole(node) {
2934
- if (!node.expression || node.dotDotDotToken) return null;
2935
- const directive = this.directive(node.expression);
2936
- if (directive === null) return this.textHole(node);
2937
- // Comments the directive did not carry over sit before it, as JSX
2938
- // comments, since this is a children position.
2939
- const lost = this.lostComments(node.getStart(this.sf) + 1, node.end - 1, directive)
2940
- .map((comment) => `{/* ${commentText(comment)} */}\n`)
2941
- .join('');
2942
- return this.absolute(lost + directive, node);
2943
- }
2944
-
2945
- /**
2946
- * A child hole the module's types prove is a string, number, or bigint,
2947
- * spelled as text so it compiles to a text binding rather than a
2948
- * renderable hole. React renders those values as text too.
2949
- *
2950
- * @param {ts.JsxExpression} node
2951
- */
2952
- textHole(node) {
2953
- const expression = /** @type {ts.Expression} */ (node.expression);
2954
- if (!this.textTypes || isTextSpelling(expression)) return null;
2955
- const kind = textKind(this.typeOf(expression));
2956
- if (kind === 0) return null;
2957
- this.count(RULE.text);
2958
- const value = this.emit(expression, PLAIN);
2959
- let text;
2960
- if (kind === 1) {
2961
- const bare =
2962
- ts.isIdentifier(expression) ||
2963
- ts.isPropertyAccessExpression(expression) ||
2964
- ts.isElementAccessExpression(expression) ||
2965
- ts.isCallExpression(expression) ||
2966
- ts.isParenthesizedExpression(expression) ||
2967
- ts.isNonNullExpression(expression);
2968
- text = `${bare ? value : `(${value})`} as string`;
2969
- } else if (
2970
- this.declaresHere(this.checker.resolveName('String', node, ts.SymbolFlags.Value, false))
2971
- ) {
2972
- text = `\`\${${value}}\``;
2973
- } else {
2974
- text = `String(${value})`;
2975
- }
2976
- return (
2977
- this.span(node, node.getStart(this.sf), expression.getStart(this.sf), PLAIN) +
2978
- text +
2979
- this.span(node, expression.end, node.end, PLAIN)
2980
- );
2981
- }
2982
-
2983
- /**
2984
- * The type of `node` in the project's program, which resolves imports and
2985
- * packages, or null when the program does not have this module.
2986
- *
2987
- * @param {ts.Node} node
2988
- * @returns {{ type: ts.Type, checker: ts.TypeChecker } | null}
2989
- */
2990
- projectType(node) {
2991
- const types = this.options.types;
2992
- if (types?.sourceFile.text !== this.source) return null;
2993
- const same = nodeSpanning(types.sourceFile, node.getStart(this.sf), node.end);
2994
- if (same?.kind !== node.kind) return null;
2995
- return { type: types.checker.getTypeAtLocation(same), checker: types.checker };
2996
- }
2997
-
2998
- /**
2999
- * The type of `expression`, from the project's program when it has this
3000
- * module, else from the module's own.
3001
- *
3002
- * @param {ts.Expression} expression
3003
- */
3004
- typeOf(expression) {
3005
- return this.projectType(expression)?.type ?? this.checker.getTypeAtLocation(expression);
3006
- }
3007
-
3008
- /**
3009
- * Comments in `[from, to)` whose text `kept` does not already carry.
3010
- *
3011
- * @param {number} from
3012
- * @param {number} to
3013
- * @param {string} kept
3014
- */
3015
- lostComments(from, to, kept) {
3016
- const scanner = ts.createScanner(
3017
- ts.ScriptTarget.Latest,
3018
- false,
3019
- ts.LanguageVariant.Standard,
3020
- this.source,
3021
- undefined,
3022
- from,
3023
- to - from,
3024
- );
3025
- /** @type {string[]} */
3026
- const lost = [];
3027
- for (
3028
- let token = scanner.scan();
3029
- token !== ts.SyntaxKind.EndOfFileToken;
3030
- token = scanner.scan()
3031
- ) {
3032
- if (
3033
- token !== ts.SyntaxKind.SingleLineCommentTrivia &&
3034
- token !== ts.SyntaxKind.MultiLineCommentTrivia
3035
- ) {
3036
- continue;
3037
- }
3038
- const text = scanner.getTokenText();
3039
- if (!kept.includes(text.replaceAll('\n', LITERAL_NEWLINE)) && !kept.includes(text))
3040
- lost.push(text);
3041
- }
3042
- return lost;
3043
- }
3044
-
3045
- /**
3046
- * The template directive equivalent to a renderable expression, as
3047
- * relative text, or null.
3048
- *
3049
- * @param {ts.Expression} expression
3050
- * @returns {string | null}
3051
- */
3052
- directive(expression) {
3053
- const node = skipParens(expression);
3054
- if (ts.isConditionalExpression(node)) return this.ifDirective(node);
3055
- if (
3056
- ts.isBinaryExpression(node) &&
3057
- node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken &&
3058
- isBoolean(node.left, (name) => this.constValue(name))
3059
- ) {
3060
- const arm = this.arm(node.right);
3061
- if (arm === null || arm === '') return null;
3062
- this.count(RULE.if);
3063
- return this.block(`@if (${this.emit(node.left, PLAIN)})`, arm);
3064
- }
3065
- if (ts.isCallExpression(node)) return this.forDirective(node);
3066
- return null;
3067
- }
3068
-
3069
- /**
3070
- * The relative template text for one directive arm: an element, a nested
3071
- * directive, or '' for nothing. An arm that is only a value is null; the
3072
- * caller decides whether it may become a `{value}` hole.
3073
- *
3074
- * @param {ts.Expression} expression
3075
- * @returns {string | null}
3076
- */
3077
- arm(expression) {
3078
- const node = skipParens(expression);
3079
- if (isJsx(node)) return this.relative(this.emit(node, TEMPLATE), node);
3080
- if (isNullish(node)) return '';
3081
- return this.directive(node);
3082
- }
3083
-
3084
- /** @param {ts.ConditionalExpression} node */
3085
- ifDirective(node) {
3086
- let whenTrue = this.arm(node.whenTrue);
3087
- let whenFalse = this.arm(node.whenFalse);
3088
- // A ternary between two values is a value; one with an element on
3089
- // either side is control flow, and a value arm is a hole in a fragment:
3090
- // a bare `{value}` arm is a JavaScript block, not a hole.
3091
- if (whenTrue === null && whenFalse === null) return null;
3092
- if ((whenTrue ?? '') === '' && (whenFalse ?? '') === '') return null;
3093
- whenTrue ??= `<>{${this.emit(skipParens(node.whenTrue), PLAIN)}}</>`;
3094
- whenFalse ??= `<>{${this.emit(skipParens(node.whenFalse), PLAIN)}}</>`;
3095
- this.count(RULE.if);
3096
- const condition = this.emit(node.condition, PLAIN);
3097
- if (whenTrue === '') {
3098
- const negated = /^[\w$.]+$/.test(condition) ? `!${condition}` : `!(${condition})`;
3099
- return this.block(`@if (${negated})`, whenFalse);
3100
- }
3101
- const then = this.block(`@if (${condition})`, whenTrue);
3102
- return whenFalse === '' ? then : then + ' ' + this.block('@else', whenFalse);
3103
- }
3104
-
3105
- /**
3106
- * `items.map((item, i) => <Row key={item.id} />)` is
3107
- * `@for (const item of items; index i; key item.id) { <Row /> }`.
3108
- *
3109
- * @param {ts.CallExpression} node
3110
- */
3111
- forDirective(node) {
3112
- const callee = node.expression;
3113
- if (
3114
- !ts.isPropertyAccessExpression(callee) ||
3115
- callee.name.text !== 'map' ||
3116
- node.arguments.length !== 1
3117
- ) {
3118
- return null;
3119
- }
3120
- const fn = node.arguments[0];
3121
- if (!(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return null;
3122
- if (fn.parameters.length === 0 || fn.parameters.length > 2) return null;
3123
- if (fn.parameters.some((p) => p.initializer || p.dotDotDotToken)) return null;
3124
- const [item, index] = fn.parameters;
3125
- if (index && !ts.isIdentifier(index.name)) return null;
3126
- // `@for (const items of items)` would read `items` in its own TDZ.
3127
- const bound = new Set([...bindingNames(item.name), ...(index ? bindingNames(index.name) : [])]);
3128
- if (reads(callee.expression, (name) => bound.has(name))) return null;
3129
- // A `function` row sees its own `this` and `arguments`; an arm does not.
3130
- if (ts.isFunctionExpression(fn) && usesOwnThis(fn.body)) return null;
3131
- // A row that writes an outer variable (`n++`) needs every row to run in
3132
- // order; an `@for` row can be skipped.
3133
- if (this.writesOuter(fn)) return null;
3134
-
3135
- /** @type {ts.Statement[]} */
3136
- let setup = [];
3137
- /** @type {ts.Expression} */
3138
- let output;
3139
- if (ts.isBlock(fn.body)) {
3140
- const statements = fn.body.statements;
3141
- const last = statements[statements.length - 1];
3142
- if (!last || !ts.isReturnStatement(last) || !last.expression) return null;
3143
- setup = statements.slice(0, -1);
3144
- if (!this.armReturnsOnlyEmpty(setup)) return null;
3145
- output = last.expression;
3146
- } else output = fn.body;
3147
- const root = skipParens(output);
3148
- if (!isJsx(root) && !ts.isConditionalExpression(root)) return null;
3149
-
3150
- // Every element the row can render carries the item's key, so it moves
3151
- // to the header once: the same key on each arm of a conditional row.
3152
- const elements = (rowElements(root) ?? []).filter((element) => !ts.isJsxFragment(element));
3153
- const keys = elements.map((element) => {
3154
- return attributeOf(ts.isJsxElement(element) ? element.openingElement : element, 'key');
3155
- });
3156
- let key = null;
3157
- if (keys.some(Boolean)) {
3158
- const values = keys.map((attribute) => {
3159
- const value = attribute?.initializer;
3160
- return value && ts.isJsxExpression(value) ? value.expression : value;
3161
- });
3162
- const text = values[0]?.getText(this.sf);
3163
- if (!values[0] || values.some((value) => value?.getText(this.sf) !== text)) return null;
3164
- key = values[0];
3165
- if (this.readsLocals(key, setup)) {
3166
- this.note(
3167
- RULE.for,
3168
- 'warning',
3169
- /** @type {ts.JsxAttribute} */ (keys[0]),
3170
- 'This row key reads a value computed in the row, so the list stays a `.map()`.',
3171
- );
3172
- return null;
3173
- }
3174
- }
3175
- const hoisted = key ? /** @type {ts.JsxAttribute[]} */ (keys) : [];
3176
- /** @type {ts.JsxElement[]} A keyed `<Fragment>` is a bare row. */
3177
- const fragments = [];
3178
- for (const attribute of hoisted) {
3179
- this.removed.add(attribute);
3180
- const opening = attribute.parent.parent;
3181
- if (
3182
- ts.isJsxOpeningElement(opening) &&
3183
- opening.attributes.properties.length === 1 &&
3184
- this.calleeName(opening.tagName) === 'Fragment'
3185
- ) {
3186
- fragments.push(opening.parent);
3187
- this.bare.add(opening.parent);
3188
- }
3189
- }
3190
- const arm = ts.isConditionalExpression(root)
3191
- ? this.ifDirective(root)
3192
- : this.relative(this.emit(root, TEMPLATE), root);
3193
- if (arm === null) {
3194
- for (const attribute of hoisted) this.removed.delete(attribute);
3195
- for (const fragment of fragments) this.bare.delete(fragment);
3196
- return null;
3197
- }
3198
- this.count(RULE.for);
3199
- let source = this.emit(callee.expression, PLAIN);
3200
- if (callee.questionDotToken) source = `${source} ?? []`;
3201
- let header = `@for (const ${this.emit(item.name, PLAIN)} of ${source}`;
3202
- if (index) header += `; index ${index.name.getText(this.sf)}`;
3203
- if (key) header += `; key ${this.emit(key, PLAIN)}`;
3204
- else if (this.strong) {
3205
- this.note(
3206
- RULE.for,
3207
- 'warning',
3208
- node,
3209
- 'Strong mode needs a keyed `@for`; add `key <item id>` to the header.',
3210
- );
3211
- }
3212
- header += ')';
3213
- if (setup.length === 0) return this.block(header, arm);
3214
- const statements = this.relative(
3215
- this.span(fn.body, setup[0].getStart(this.sf), setup[setup.length - 1].end, PLAIN),
3216
- setup[0],
3217
- );
3218
- return this.block(header, statements + '\n' + arm);
3219
- }
3220
-
3221
- /**
3222
- * Whether `fn` assigns a variable declared outside it.
3223
- *
3224
- * @param {ts.ArrowFunction | ts.FunctionExpression} fn
3225
- */
3226
- writesOuter(fn) {
3227
- /** @type {(node: ts.Node) => boolean} */
3228
- const visit = (node) => {
3229
- let target = null;
3230
- if (
3231
- ts.isBinaryExpression(node) &&
3232
- node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
3233
- node.operatorToken.kind <= ts.SyntaxKind.LastAssignment
3234
- ) {
3235
- target = node.left;
3236
- } else if (
3237
- (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
3238
- (node.operator === ts.SyntaxKind.PlusPlusToken ||
3239
- node.operator === ts.SyntaxKind.MinusMinusToken)
3240
- ) {
3241
- target = node.operand;
3242
- }
3243
- if (target && ts.isIdentifier(skipParens(target))) {
3244
- const declaration = this.declarationOf(/** @type {ts.Identifier} */ (skipParens(target)));
3245
- if (declaration && (declaration.pos < fn.pos || declaration.end > fn.end)) return true;
3246
- }
3247
- return ts.forEachChild(node, visit) ?? false;
3248
- };
3249
- return visit(fn.body);
3250
- }
3251
-
3252
- /**
3253
- * Whether every `return` in a list row's setup leaves the row empty, the
3254
- * only early exit a directive arm allows.
3255
- *
3256
- * @param {ts.Statement[]} statements
3257
- */
3258
- armReturnsOnlyEmpty(statements) {
3259
- let ok = true;
3260
- const visit = (/** @type {ts.Node} */ node) => {
3261
- if (isFunctionLike(node)) return;
3262
- if (ts.isReturnStatement(node) && node.expression && !isNullish(node.expression)) ok = false;
3263
- node.forEachChild(visit);
3264
- };
3265
- statements.forEach(visit);
3266
- return ok;
3267
- }
3268
-
3269
- /**
3270
- * @param {ts.Node} expression
3271
- * @param {ts.Statement[]} statements
3272
- */
3273
- readsLocals(expression, statements) {
3274
- const declared = new Set(
3275
- statements
3276
- .filter(ts.isVariableStatement)
3277
- .flatMap((statement) => statement.declarationList.declarations)
3278
- .flatMap((declaration) => bindingNames(declaration.name)),
3279
- );
3280
- return reads(expression, (name) => declared.has(name));
3281
- }
3282
-
3283
- // ---------------------------------------------------------------- components
3284
-
3285
- /**
3286
- * Rewrite a component whose last statement returns JSX as a template body:
3287
- * `function C() { setup; return <div /> }` is `function C() @{ setup; <div /> }`.
3288
- *
3289
- * @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
3290
- */
3291
- rewriteComponent(node) {
3292
- if (!node.body || !this.isComponent(node)) return null;
3293
- if (node.asteriskToken || node.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword))
3294
- return null;
3295
- const body = node.body;
3296
-
3297
- if (!ts.isBlock(body)) {
3298
- const inner = skipParens(body);
3299
- const output = this.output(inner);
3300
- if (output === null) return null;
3301
- const head = this.head(node, body.getStart(this.sf));
3302
- this.markTemplate();
3303
- if (inner !== body && this.startsLine(inner)) {
3304
- // `=> (\n\t<div />\n)` keeps its layout with the parens as braces.
3305
- return (
3306
- head +
3307
- '@{' +
3308
- this.source.slice(body.getStart(this.sf) + 1, inner.getStart(this.sf)) +
3309
- output +
3310
- this.source.slice(inner.end, body.end - 1).replace(/\)\s*$/, '') +
3311
- '}'
3312
- );
3313
- }
3314
- return head + '@{ ' + output + ' }';
3315
- }
3316
-
3317
- const statements = body.statements;
3318
- const last = statements[statements.length - 1];
3319
- if (!last || !ts.isReturnStatement(last) || !last.expression) return null;
3320
- const guard = statements.findIndex((s, i) => i < statements.length - 1 && guardReturn(s));
3321
- if (guard !== -1) return this.rewriteGuards(node, body, guard);
3322
- // A template body has one output; any other early `return <A />` would
3323
- // render through runtime descriptors, so the plain function stays.
3324
- if (returnsJsx(statements.slice(0, -1))) return null;
3325
- const inner = skipParens(last.expression);
3326
- let output = this.output(inner);
3327
- if (output === null) return null;
3328
- const head = this.head(node, body.getStart(this.sf));
3329
- this.markTemplate();
3330
-
3331
- if (this.startsLine(inner)) {
3332
- // `return (\n\t\t<div>…` sits one level deeper than the statements.
3333
- output = this.absolute(this.relative(output, inner), last);
3334
- }
3335
- // A comment inside `return ( … )` becomes a setup comment.
3336
- const indent = this.indentOf(last);
3337
- const lost = [
3338
- ...this.lostComments(last.getStart(this.sf), inner.getStart(this.sf), output),
3339
- ...this.lostComments(inner.end, last.end, output),
3340
- ];
3341
- output =
3342
- lost.map((comment) => comment.replaceAll('\n', '\n' + indent) + '\n' + indent).join('') +
3343
- output;
3344
- const previous = statements[statements.length - 2];
3345
- const setup = previous ? this.span(body, body.getStart(this.sf) + 1, previous.end, PLAIN) : '';
3346
- const gap = this.source.slice(
3347
- previous ? previous.end : body.getStart(this.sf) + 1,
3348
- last.getStart(this.sf),
3349
- );
3350
- return head + '@{' + setup + gap + output + this.source.slice(last.end, body.end - 1) + '}';
3351
- }
3352
-
3353
- /**
3354
- * A component with `if (c) return <A />;` guards: each becomes
3355
- * `@if (c) { <A /> } @else { …the rest }`, since a template body has one
3356
- * output. The setup before the first guard stays as it was.
3357
- *
3358
- * @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
3359
- * @param {ts.Block} body
3360
- * @param {number} first the index of the first guard
3361
- */
3362
- rewriteGuards(node, body, first) {
3363
- const statements = body.statements;
3364
- const last = /** @type {ts.ReturnStatement} */ (statements[statements.length - 1]);
3365
- // Setup before the first guard stays in the body, which may return a
3366
- // value early; the rest moves into arms, which may only return nothing.
3367
- const rest = statements.slice(first + 1, -1).filter((statement) => !guardReturn(statement));
3368
- if (returnsJsx(statements.slice(0, first)) || !this.armReturnsOnlyEmpty(rest)) return null;
3369
- const output = this.arm(/** @type {ts.Expression} */ (last.expression));
3370
- if (output === null) return null;
3371
- /** @type {(from: number) => string} */
3372
- const chain = (from) => {
3373
- let at = from;
3374
- while (at < statements.length - 1 && !guardReturn(statements[at])) at++;
3375
- // Comments before the first guard stay in the body's own text.
3376
- const lead =
3377
- from > first
3378
- ? this.lostComments(statements[from - 1].end, statements[from].getStart(this.sf), '')
3379
- : [];
3380
- const prefix =
3381
- lead.map((comment) => comment + '\n').join('') +
3382
- (at > from
3383
- ? this.relative(
3384
- this.span(body, statements[from].getStart(this.sf), statements[at - 1].end, PLAIN),
3385
- statements[from],
3386
- ) + '\n'
3387
- : '');
3388
- if (at === statements.length - 1) return prefix + output;
3389
- const guard = /** @type {ts.IfStatement} */ (statements[at]);
3390
- this.count(RULE.if);
3391
- const then = this.block(
3392
- `@if (${this.emit(guard.expression, PLAIN)})`,
3393
- /** @type {string} */ (this.arm(/** @type {ts.Expression} */ (guardReturn(guard)))),
3394
- );
3395
- const rest = chain(at + 1);
3396
- return prefix + (rest === '' ? then : then + ' ' + this.block('@else', rest));
3397
- };
3398
- const directive = this.absolute(chain(first), statements[first]);
3399
- const head = this.head(node, body.getStart(this.sf));
3400
- this.markTemplate();
3401
- const previous = statements[first - 1];
3402
- const before = previous ? this.span(body, body.getStart(this.sf) + 1, previous.end, PLAIN) : '';
3403
- const gap = this.source.slice(
3404
- previous ? previous.end : body.getStart(this.sf) + 1,
3405
- statements[first].getStart(this.sf),
3406
- );
3407
- return head + '@{' + before + gap + directive + this.source.slice(last.end, body.end - 1) + '}';
3408
- }
3409
-
3410
- markTemplate() {
3411
- this.template = true;
3412
- this.count(RULE.component);
3413
- }
3414
-
3415
- /**
3416
- * A component's returned expression as template output, at the position
3417
- * and indentation `node` had, or null when it is not a single renderable.
3418
- *
3419
- * @param {ts.Expression} node
3420
- */
3421
- output(node) {
3422
- if (isJsx(node)) return this.emit(node, TEMPLATE);
3423
- if (ts.isConditionalExpression(node) || ts.isCallExpression(node)) {
3424
- const directive = this.directive(node);
3425
- return directive === null ? null : this.absolute(directive, node);
3426
- }
3427
- return null;
3428
- }
3429
-
3430
- /** @param {ts.Node} node */
3431
- startsLine(node) {
3432
- return this.linePrefix(node).trim() === '';
3433
- }
3434
-
3435
- /**
3436
- * Whether `node` is a component definition: a capitalized function, or the
3437
- * function passed to `memo` / `forwardRef`, or a default-exported one.
3438
- *
3439
- * @param {ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction} node
3440
- */
3441
- isComponent(node) {
3442
- if (node.name && isComponentName(node.name.text)) return true;
3443
- const parent = node.parent;
3444
- if (ts.isVariableDeclaration(parent) && ts.isIdentifier(parent.name)) {
3445
- return isComponentName(parent.name.text);
3446
- }
3447
- if (ts.isCallExpression(parent) && parent.arguments[0] === node) {
3448
- const name = this.calleeName(parent.expression);
3449
- if (name === 'memo' || name === 'forwardRef') return true;
3450
- }
3451
- if (ts.isExportAssignment(parent)) return true;
3452
- if (ts.isFunctionDeclaration(node) && !node.name) return true;
3453
- return false;
3454
- }
3455
- }