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