@octanejs/codemod 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -4
- package/package.json +3 -3
- package/src/bin.js +18 -2
- package/src/index.d.ts +4 -0
- package/src/mappings.js +13 -0
- package/src/project.js +142 -10
- package/src/transform.js +150 -36
package/README.md
CHANGED
|
@@ -10,8 +10,9 @@ npx @octanejs/codemod src --dry-run # report only
|
|
|
10
10
|
npx @octanejs/codemod src --strong # also make modules Strong where possible
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
The codemod adds each binding the migrated code imports to `package.json`, at
|
|
14
|
+
the version in its catalog. Then run `npx @octanejs/cli init` to swap the
|
|
15
|
+
bundler plugin and `tsconfig` over to Octane and install the dependencies.
|
|
15
16
|
|
|
16
17
|
> **Prototype.** The rewrites below are tested, and every migrated module is
|
|
17
18
|
> compiled by the Octane compiler before it is written, but the rule set is
|
|
@@ -27,6 +28,7 @@ dependencies over to Octane.
|
|
|
27
28
|
| `imports` | React libraries with a binding (`@tanstack/react-query`, ...) | `@octanejs/*` |
|
|
28
29
|
| `imports` | `@radix-ui/react-<primitive>` (`import * as DialogPrimitive from '@radix-ui/react-dialog'`) | that primitive's namespace of `@octanejs/radix` (`import { Dialog as DialogPrimitive } from '@octanejs/radix'`) |
|
|
29
30
|
| `imports` | `@tanstack/react-table`, `@tanstack/react-hotkeys`, `@tanstack/react-pacer` | TanStack's own `@tanstack/octane-*` adapters, with `Octane` for `React` in type names |
|
|
31
|
+
| `imports` | `jsx`, `jsxs` from `react/jsx-runtime`, passed to a JSX runtime consumer such as `hast-util-to-jsx-runtime` | a local `jsx` that calls `createElement` with the key in its props |
|
|
30
32
|
| `template-component` | `function C() { …; return <div /> }` | `function C() @{ …; <div /> }` |
|
|
31
33
|
| `template-if` | `{a ? <A /> : <B />}`, `{a > 0 && <A />}` (also through a `const`) | `@if (a) { <A /> } @else { <B /> }` |
|
|
32
34
|
| `template-if` | `if (a) return <A />; …; return <B />` in a component | `@if (a) { <A /> } @else { …; <B /> }` |
|
|
@@ -38,8 +40,8 @@ dependencies over to Octane.
|
|
|
38
40
|
| `descriptor-children` | a component that clones or inspects `children` (`render={children}`, `cloneElement`, `Children.only`) | `descriptorChildren(…)`, so callers pass elements as React does |
|
|
39
41
|
| `context-provider` | `<Ctx.Provider value>` | `<Ctx value>` |
|
|
40
42
|
| `context-consumer` | `<Ctx.Consumer>{(v) => …}</Ctx.Consumer>` | `@{ const v = useContext(Ctx); … }` |
|
|
41
|
-
| `native-text-change` | `onChange` on a text `<input>` / `<textarea
|
|
42
|
-
| `native-text-change` | `function Input({ ...props }) { return <input {...props} /> }` | `function Input({ onChange, ...props }) @{ <input onInput={onChange} {...props} /> }` |
|
|
43
|
+
| `native-text-change` | `onChange` on a text `<input>` / `<textarea>`, or on Base UI's `Input` / `Field.Control`, which render one | `onInput` (native `change` fires on blur) |
|
|
44
|
+
| `native-text-change` | `function Input({ ...props }) { return <input {...props} /> }`, also when a nested `const { a, ...rest } = props` reaches the field | `function Input({ onChange, ...props }) @{ <input onInput={onChange} {...props} /> }` |
|
|
43
45
|
| `event-object` | `e.nativeEvent`, `e.persist()`, `e.target` on a control, also through a component typed for one | `e`, removed, `e.currentTarget` |
|
|
44
46
|
| `class-attribute` | `className` on an HTML element | `class` |
|
|
45
47
|
| `legacy-root` | `ReactDOM.render(el, c)` | `createRoot(c).render(el)` |
|
|
@@ -92,6 +94,11 @@ callbacks, are reported where they are used. **No Octane port** lists each such
|
|
|
92
94
|
package with the modules that import it, the elements hosted in islands, and
|
|
93
95
|
the uses that need a port.
|
|
94
96
|
|
|
97
|
+
A patch the project applies to a React package the codemod replaces, through
|
|
98
|
+
`patchedDependencies` (pnpm, Bun) or `patches/` (patch-package), patches the
|
|
99
|
+
React package, not its binding. **Dependencies** names each one, to port by
|
|
100
|
+
hand.
|
|
101
|
+
|
|
95
102
|
## Options
|
|
96
103
|
|
|
97
104
|
| Flag | |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@octanejs/codemod",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=22.22.2"
|
|
@@ -39,8 +39,8 @@
|
|
|
39
39
|
"./package.json": "./package.json"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@octanejs/cli": "0.3.
|
|
43
|
-
"octane": "0.16.
|
|
42
|
+
"@octanejs/cli": "0.3.3",
|
|
43
|
+
"octane": "0.16.7",
|
|
44
44
|
"picocolors": "^1.1.1",
|
|
45
45
|
"typescript": "^5.9.3"
|
|
46
46
|
},
|
package/src/bin.js
CHANGED
|
@@ -99,7 +99,21 @@ if (findings.length > 0) {
|
|
|
99
99
|
}
|
|
100
100
|
if (result.packages.length > 0) {
|
|
101
101
|
process.stdout.write(`\n${colors.bold('Dependencies')}\n`);
|
|
102
|
-
|
|
102
|
+
const ranges = new Map(result.dependencies.map(({ name, range }) => [name, range]));
|
|
103
|
+
for (const { from, to } of result.packages) {
|
|
104
|
+
const range = ranges.get(to);
|
|
105
|
+
process.stdout.write(` ${from} → ${to}${range ? colors.dim(` ${range}`) : ''}\n`);
|
|
106
|
+
}
|
|
107
|
+
if (ranges.size > 0) {
|
|
108
|
+
process.stdout.write(
|
|
109
|
+
colors.dim(` ${dryRun ? 'Would add' : 'Added'} ${ranges.size} to package.json\n`),
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
for (const { name, patch } of result.patched) {
|
|
113
|
+
process.stdout.write(
|
|
114
|
+
` ${colors.yellow('warning')} ${name} is patched by ${patch}, which does not apply to its binding: port the patch there.\n`,
|
|
115
|
+
);
|
|
116
|
+
}
|
|
103
117
|
}
|
|
104
118
|
if (result.missing.length > 0) {
|
|
105
119
|
process.stdout.write(
|
|
@@ -127,7 +141,9 @@ const summary = [
|
|
|
127
141
|
].filter(Boolean);
|
|
128
142
|
process.stdout.write(`\n${summary.join(', ')}${dryRun ? colors.dim(' (dry run)') : ''}\n`);
|
|
129
143
|
if (changed.length > 0 && !dryRun) {
|
|
130
|
-
|
|
144
|
+
// A project outside this directory is named in full, not by `../` steps.
|
|
145
|
+
const relative = path.relative(process.cwd(), result.root);
|
|
146
|
+
const root = relative.startsWith('..') ? result.root : relative || '.';
|
|
131
147
|
process.stdout.write(
|
|
132
148
|
colors.dim(`Next: run \`npx @octanejs/cli init\` in ${root} to wire Octane into the build.\n`),
|
|
133
149
|
);
|
package/src/index.d.ts
CHANGED
|
@@ -69,6 +69,10 @@ interface CodemodResult {
|
|
|
69
69
|
root: string;
|
|
70
70
|
files: FileResult[];
|
|
71
71
|
packages: { from: string; to: string }[];
|
|
72
|
+
/** Bindings added to package.json, which the project did not declare. */
|
|
73
|
+
dependencies: { name: string; range: string }[];
|
|
74
|
+
/** Patches of replaced React packages, which do not reach their bindings. */
|
|
75
|
+
patched: { name: string; patch: string }[];
|
|
72
76
|
missing: (Unported & { modules: number })[];
|
|
73
77
|
html: string[];
|
|
74
78
|
compiler: string | null;
|
package/src/mappings.js
CHANGED
|
@@ -414,3 +414,16 @@ export const TEXT_INPUT_TYPES = new Set([
|
|
|
414
414
|
'email',
|
|
415
415
|
'number',
|
|
416
416
|
]);
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* Library components that render a text `<input>` and hand it the `onChange`
|
|
420
|
+
* they receive, by the module that exports each: React fires that per edit, as
|
|
421
|
+
* on the element itself.
|
|
422
|
+
*
|
|
423
|
+
* @type {Record<string, string[]>}
|
|
424
|
+
*/
|
|
425
|
+
export const TEXT_FIELD_COMPONENTS = {
|
|
426
|
+
'@base-ui/react': ['Input', 'Field.Control'],
|
|
427
|
+
'@base-ui/react/input': ['Input'],
|
|
428
|
+
'@base-ui/react/field': ['Field.Control'],
|
|
429
|
+
};
|
package/src/project.js
CHANGED
|
@@ -40,6 +40,10 @@ import { transformModule } from './transform.js';
|
|
|
40
40
|
* @property {FileResult[]} files
|
|
41
41
|
* @property {{ from: string, to: string }[]} packages React packages the
|
|
42
42
|
* migrated code now imports as Octane bindings
|
|
43
|
+
* @property {{ name: string, range: string }[]} dependencies the bindings
|
|
44
|
+
* added to package.json, which the project did not declare yet
|
|
45
|
+
* @property {{ name: string, patch: string }[]} patched patches the project
|
|
46
|
+
* applies to replaced React packages, which do not reach their bindings
|
|
43
47
|
* @property {Missing[]} missing React packages the code imports that have no
|
|
44
48
|
* Octane port, and how it uses them
|
|
45
49
|
* @property {string[]} html entry pages whose script reference was updated
|
|
@@ -201,6 +205,7 @@ export async function runCodemod(paths, options = {}) {
|
|
|
201
205
|
renames,
|
|
202
206
|
options.write !== false,
|
|
203
207
|
);
|
|
208
|
+
const dependencies = addBindings(root, packages, options.write !== false);
|
|
204
209
|
if (options.write !== false) {
|
|
205
210
|
for (const result of results) {
|
|
206
211
|
if (!result.changed) continue;
|
|
@@ -213,6 +218,8 @@ export async function runCodemod(paths, options = {}) {
|
|
|
213
218
|
root,
|
|
214
219
|
files: results,
|
|
215
220
|
packages: [...packages].map(([from, to]) => ({ from, to })),
|
|
221
|
+
dependencies,
|
|
222
|
+
patched: patchedPackages(root, packages),
|
|
216
223
|
missing: [...missing.values()].sort((a, b) => a.name.localeCompare(b.name)),
|
|
217
224
|
html,
|
|
218
225
|
compiler: compiler?.from ?? null,
|
|
@@ -415,26 +422,50 @@ function resolveBinding(specifier, packages, notes) {
|
|
|
415
422
|
if (name === null) return null;
|
|
416
423
|
const binding = CATALOG[name];
|
|
417
424
|
packages.set(name, binding);
|
|
425
|
+
const entry = DATA.bindings.find((candidate) => candidate.name === binding);
|
|
418
426
|
// An aggregate binding (`@octanejs/visx`, for `@visx/visx`) serves each
|
|
419
427
|
// package of its scope from a subpath: `@visx/hierarchy` is
|
|
420
428
|
// `@octanejs/visx/hierarchy`.
|
|
421
|
-
const upstream =
|
|
429
|
+
const upstream = entry?.upstream?.package;
|
|
422
430
|
const aggregate = upstream?.match(/^@([^/]+)\/\1$/);
|
|
423
431
|
if (aggregate && name !== upstream && name.startsWith(`@${aggregate[1]}/`)) {
|
|
424
432
|
return `${binding}/${name.slice(aggregate[1].length + 2)}${specifier.slice(name.length)}`;
|
|
425
433
|
}
|
|
426
434
|
const subpath = specifier.slice(name.length);
|
|
427
|
-
if (subpath
|
|
428
|
-
|
|
429
|
-
rule: 'bindings',
|
|
430
|
-
severity: 'warning',
|
|
431
|
-
line: 1,
|
|
432
|
-
message: `Check that \`${binding}${subpath}\` exists; the binding may export it from its root.`,
|
|
433
|
-
});
|
|
435
|
+
if (subpath === '' || entry?.exports.some((key) => serves(key, `.${subpath}`))) {
|
|
436
|
+
return binding + subpath;
|
|
434
437
|
}
|
|
438
|
+
// A binding outside the catalog has exports the codemod cannot see.
|
|
439
|
+
notes.push(
|
|
440
|
+
entry
|
|
441
|
+
? {
|
|
442
|
+
rule: 'bindings',
|
|
443
|
+
severity: 'error',
|
|
444
|
+
line: 1,
|
|
445
|
+
message: `\`${binding}\` has no \`.${subpath}\` export. Import these names from its root if it exports them there.`,
|
|
446
|
+
}
|
|
447
|
+
: {
|
|
448
|
+
rule: 'bindings',
|
|
449
|
+
severity: 'warning',
|
|
450
|
+
line: 1,
|
|
451
|
+
message: `Check that \`${binding}${subpath}\` exists; the binding may export it from its root.`,
|
|
452
|
+
},
|
|
453
|
+
);
|
|
435
454
|
return binding + subpath;
|
|
436
455
|
}
|
|
437
456
|
|
|
457
|
+
/**
|
|
458
|
+
* Whether a package `exports` key serves a subpath, directly or through a
|
|
459
|
+
* `*` pattern such as `./locale/*`.
|
|
460
|
+
*
|
|
461
|
+
* @param {string} key
|
|
462
|
+
* @param {string} subpath
|
|
463
|
+
*/
|
|
464
|
+
function serves(key, subpath) {
|
|
465
|
+
const [head, tail] = key.split('*');
|
|
466
|
+
return tail === undefined ? key === subpath : subpath.startsWith(head) && subpath.endsWith(tail);
|
|
467
|
+
}
|
|
468
|
+
|
|
438
469
|
/**
|
|
439
470
|
* The catalog entry for a package specifier, or null. The catalog keys some
|
|
440
471
|
* bindings by subpath (`better-auth/react`), so the longest matching prefix
|
|
@@ -462,13 +493,114 @@ function catalogName(specifier) {
|
|
|
462
493
|
function unportedName(specifier, from) {
|
|
463
494
|
if (specifier.startsWith('.') || specifier.startsWith('/') || catalogName(specifier) !== null)
|
|
464
495
|
return null;
|
|
465
|
-
const
|
|
466
|
-
const root = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
|
|
496
|
+
const root = packageName(specifier);
|
|
467
497
|
// Any package's `/react` entry renders with React (`@tanstack/markdown/react`).
|
|
468
498
|
if (/\/react(?:\/|$)/.test(specifier.slice(root.length))) return specifier;
|
|
469
499
|
return rendersWithReact(root, from) ? root : null;
|
|
470
500
|
}
|
|
471
501
|
|
|
502
|
+
/**
|
|
503
|
+
* The package a bare specifier imports from: `@pierre/diffs` for
|
|
504
|
+
* `@pierre/diffs/react`.
|
|
505
|
+
*
|
|
506
|
+
* @param {string} specifier
|
|
507
|
+
*/
|
|
508
|
+
function packageName(specifier) {
|
|
509
|
+
return specifier
|
|
510
|
+
.split('/')
|
|
511
|
+
.slice(0, specifier.startsWith('@') ? 2 : 1)
|
|
512
|
+
.join('/');
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Add the bindings the migrated code imports to the project's package.json,
|
|
517
|
+
* each at its catalog version and in the field that lists the React package it
|
|
518
|
+
* replaces. TanStack publishes its Octane adapters outside the catalog, so
|
|
519
|
+
* those take `latest`.
|
|
520
|
+
*
|
|
521
|
+
* @param {string} root
|
|
522
|
+
* @param {Map<string, string>} packages
|
|
523
|
+
* @param {boolean} write
|
|
524
|
+
* @returns {CodemodResult['dependencies']}
|
|
525
|
+
*/
|
|
526
|
+
function addBindings(root, packages, write) {
|
|
527
|
+
const file = path.join(root, 'package.json');
|
|
528
|
+
if (!fs.existsSync(file)) return [];
|
|
529
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
530
|
+
const manifest = JSON.parse(text);
|
|
531
|
+
const fields = ['dependencies', 'devDependencies', 'peerDependencies'];
|
|
532
|
+
/** @type {CodemodResult['dependencies']} */
|
|
533
|
+
const added = [];
|
|
534
|
+
for (const [from, to] of packages) {
|
|
535
|
+
if (fields.some((field) => manifest[field]?.[to] !== undefined)) continue;
|
|
536
|
+
const version = DATA.bindings.find((binding) => binding.name === to)?.version;
|
|
537
|
+
const range = version ? `^${version}` : 'latest';
|
|
538
|
+
const field = manifest.devDependencies?.[packageName(from)]
|
|
539
|
+
? 'devDependencies'
|
|
540
|
+
: 'dependencies';
|
|
541
|
+
manifest[field] = Object.fromEntries(
|
|
542
|
+
Object.entries({ ...manifest[field], [to]: range }).sort(([a], [b]) => a.localeCompare(b)),
|
|
543
|
+
);
|
|
544
|
+
added.push({ name: to, range });
|
|
545
|
+
}
|
|
546
|
+
if (write && added.length > 0) {
|
|
547
|
+
const indent = /^[ \t]+/m.exec(text)?.[0] ?? ' ';
|
|
548
|
+
fs.writeFileSync(file, JSON.stringify(manifest, null, indent) + '\n');
|
|
549
|
+
}
|
|
550
|
+
return added;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* The patches a project applies to the React packages the migration replaces,
|
|
555
|
+
* which stop applying once the code imports the binding instead: pnpm's and
|
|
556
|
+
* Bun's `patchedDependencies`, in package.json or pnpm-workspace.yaml, and
|
|
557
|
+
* patch-package's `patches/name+version.patch`. They live where the project
|
|
558
|
+
* installs, so each directory up from `root` is read until a lockfile.
|
|
559
|
+
*
|
|
560
|
+
* @param {string} root
|
|
561
|
+
* @param {Map<string, string>} packages
|
|
562
|
+
* @returns {CodemodResult['patched']}
|
|
563
|
+
*/
|
|
564
|
+
function patchedPackages(root, packages) {
|
|
565
|
+
const replaced = new Set([...packages.keys()].map(packageName));
|
|
566
|
+
/** @type {CodemodResult['patched']} */
|
|
567
|
+
const patched = [];
|
|
568
|
+
for (let dir = root; ; dir = path.dirname(dir)) {
|
|
569
|
+
const read = (/** @type {string} */ name) => {
|
|
570
|
+
const file = path.join(dir, name);
|
|
571
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
|
|
572
|
+
};
|
|
573
|
+
const manifest = JSON.parse(read('package.json') ?? '{}');
|
|
574
|
+
/** @type {[string, string][]} `name@version` and its patch */
|
|
575
|
+
const declared = Object.entries({
|
|
576
|
+
...manifest.pnpm?.patchedDependencies,
|
|
577
|
+
...manifest.patchedDependencies,
|
|
578
|
+
});
|
|
579
|
+
const workspace =
|
|
580
|
+
/^patchedDependencies:[ \t]*\r?\n((?:[ \t]+.*\r?\n?)*)/m.exec(
|
|
581
|
+
read('pnpm-workspace.yaml') ?? '',
|
|
582
|
+
)?.[1] ?? '';
|
|
583
|
+
for (const [, , key, , patch] of workspace.matchAll(
|
|
584
|
+
/^[ \t]+(["']?)(.+?)\1:[ \t]*(["']?)(.+?)\3[ \t]*$/gm,
|
|
585
|
+
)) {
|
|
586
|
+
declared.push([key, patch]);
|
|
587
|
+
}
|
|
588
|
+
const patches = path.join(dir, 'patches');
|
|
589
|
+
for (const name of fs.existsSync(patches) ? fs.readdirSync(patches) : []) {
|
|
590
|
+
const match = /^((?:@[^+]+\+)?[^+]+)\+[^+]+\.patch$/.exec(name);
|
|
591
|
+
if (match) declared.push([match[1].replace('+', '/'), `patches/${name}`]);
|
|
592
|
+
}
|
|
593
|
+
for (const [key, patch] of declared) {
|
|
594
|
+
const name = key.replace(/(?!^)@[^@]*$/, '');
|
|
595
|
+
if (replaced.has(name))
|
|
596
|
+
patched.push({ name, patch: path.relative(root, path.join(dir, patch)) });
|
|
597
|
+
}
|
|
598
|
+
const installed = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb'];
|
|
599
|
+
if (installed.some((name) => fs.existsSync(path.join(dir, name))) || path.dirname(dir) === dir)
|
|
600
|
+
return patched;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
472
604
|
/**
|
|
473
605
|
* Whether a package renders through React: it declares `react` as a peer or
|
|
474
606
|
* dependency when installed, or its name says so when it is not. A package
|
package/src/transform.js
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
DEPENDENCY_HOOKS,
|
|
4
4
|
RADIX_TYPES,
|
|
5
5
|
REACT_MODULES,
|
|
6
|
+
TEXT_FIELD_COMPONENTS,
|
|
6
7
|
TEXT_INPUT_TYPES,
|
|
7
8
|
UNSUPPORTED_VALUES,
|
|
8
9
|
mapPackageExport,
|
|
@@ -208,6 +209,45 @@ function skipParens(node) {
|
|
|
208
209
|
return node;
|
|
209
210
|
}
|
|
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
|
+
|
|
211
251
|
/** @param {ts.Node} node */
|
|
212
252
|
function isJsx(node) {
|
|
213
253
|
return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);
|
|
@@ -965,16 +1005,7 @@ class ModuleTransform {
|
|
|
965
1005
|
* @param {ts.Expression} expression
|
|
966
1006
|
*/
|
|
967
1007
|
planDescriptorChildren(expression) {
|
|
968
|
-
|
|
969
|
-
while (
|
|
970
|
-
ts.isParenthesizedExpression(value) ||
|
|
971
|
-
ts.isAsExpression(value) ||
|
|
972
|
-
ts.isSatisfiesExpression(value) ||
|
|
973
|
-
ts.isNonNullExpression(value) ||
|
|
974
|
-
ts.isTypeAssertionExpression(value)
|
|
975
|
-
) {
|
|
976
|
-
value = value.expression;
|
|
977
|
-
}
|
|
1008
|
+
const value = skipWrappers(expression);
|
|
978
1009
|
const component = this.childrenOwner(value);
|
|
979
1010
|
if (!component) return;
|
|
980
1011
|
// `memo(…)` and `forwardRef(…)` wrap it; the declaration holds the call.
|
|
@@ -1105,7 +1136,11 @@ class ModuleTransform {
|
|
|
1105
1136
|
* @param {ts.JsxOpeningLikeElement} element
|
|
1106
1137
|
*/
|
|
1107
1138
|
takesChange(element) {
|
|
1108
|
-
if (
|
|
1139
|
+
if (
|
|
1140
|
+
!/^(?:input|textarea)$/.test(element.tagName.getText(this.sf)) &&
|
|
1141
|
+
!this.isTextFieldComponent(element)
|
|
1142
|
+
)
|
|
1143
|
+
return false;
|
|
1109
1144
|
if (attributeOf(element, 'onChange') || attributeOf(element, 'onInput')) return false;
|
|
1110
1145
|
const type = attributeOf(element, 'type')?.initializer;
|
|
1111
1146
|
return !type || !ts.isStringLiteral(type) || TEXT_INPUT_TYPES.has(type.text);
|
|
@@ -1126,23 +1161,18 @@ class ModuleTransform {
|
|
|
1126
1161
|
// Props whose type has no `onChange` have none to pass on.
|
|
1127
1162
|
const type = this.projectType(spread.expression)?.type;
|
|
1128
1163
|
if (type && !(type.flags & ts.TypeFlags.Any) && !type.getProperty('onChange')) continue;
|
|
1129
|
-
const
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
: null;
|
|
1139
|
-
// A pattern that names `onChange` leaves none in the rest.
|
|
1140
|
-
const pattern = /** @type {ts.ObjectBindingPattern | undefined} */ (rest?.parent);
|
|
1141
|
-
if (
|
|
1142
|
-
pattern?.elements.some((e) => (e.propertyName ?? e.name).getText(this.sf) === 'onChange')
|
|
1143
|
-
) {
|
|
1144
|
-
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;
|
|
1145
1173
|
}
|
|
1174
|
+
// A pattern that names `onChange` leaves none in the rest.
|
|
1175
|
+
if (rest && this.namesChange(rest.parent)) continue;
|
|
1146
1176
|
if (
|
|
1147
1177
|
rest &&
|
|
1148
1178
|
!this.checker.resolveName('onChange', spread, ts.SymbolFlags.Value, false) &&
|
|
@@ -1172,12 +1202,26 @@ class ModuleTransform {
|
|
|
1172
1202
|
const visit = (/** @type {ts.Node} */ node) => {
|
|
1173
1203
|
if (!only) return;
|
|
1174
1204
|
if (ts.isIdentifier(node) && node !== rest.name && this.declarationOf(node) === rest) {
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
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 &&
|
|
1180
1223
|
parent.name.text !== 'onChange';
|
|
1224
|
+
}
|
|
1181
1225
|
}
|
|
1182
1226
|
ts.forEachChild(node, visit);
|
|
1183
1227
|
};
|
|
@@ -1185,6 +1229,47 @@ class ModuleTransform {
|
|
|
1185
1229
|
return only;
|
|
1186
1230
|
}
|
|
1187
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
|
+
|
|
1188
1273
|
/**
|
|
1189
1274
|
* The declaration a name refers to.
|
|
1190
1275
|
*
|
|
@@ -1780,6 +1865,8 @@ class ModuleTransform {
|
|
|
1780
1865
|
};
|
|
1781
1866
|
/** React specifiers with no Octane export stay on React, for a person. */
|
|
1782
1867
|
const kept = new Map();
|
|
1868
|
+
/** @type {string[]} Locals of React's `jsx` factories, which a JSX runtime consumer calls. */
|
|
1869
|
+
const factories = [];
|
|
1783
1870
|
for (const node of this.importSlots) {
|
|
1784
1871
|
const module = /** @type {ts.StringLiteral} */ (node.moduleSpecifier).text;
|
|
1785
1872
|
const clause = node.importClause;
|
|
@@ -1802,6 +1889,11 @@ class ModuleTransform {
|
|
|
1802
1889
|
add(mapped.module, mapped.name, local, typeOnly || !this.valueUses.has(local));
|
|
1803
1890
|
continue;
|
|
1804
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
|
+
}
|
|
1805
1897
|
this.note(
|
|
1806
1898
|
RULE.unsupported,
|
|
1807
1899
|
'error',
|
|
@@ -1837,6 +1929,20 @@ class ModuleTransform {
|
|
|
1837
1929
|
}
|
|
1838
1930
|
for (const [module, specs] of kept)
|
|
1839
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
|
+
}
|
|
1840
1946
|
|
|
1841
1947
|
// In a script, `declare module` declares the module instead of adding to
|
|
1842
1948
|
// it: a module whose only import was `import 'react'` stays a module, and
|
|
@@ -2375,13 +2481,17 @@ class ModuleTransform {
|
|
|
2375
2481
|
const found = this.parameterOf(node);
|
|
2376
2482
|
if (!found) return false;
|
|
2377
2483
|
// Unannotated, the project's types still name a handler a component
|
|
2378
|
-
// passes on to a control: `<Input onChange={(e) => …}>`.
|
|
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.
|
|
2379
2487
|
const inferred = found.param.type ? null : this.projectType(found.param);
|
|
2380
2488
|
const type =
|
|
2381
2489
|
found.param.type?.getText(this.sf) ??
|
|
2382
2490
|
(inferred ? inferred.checker.typeToString(inferred.type) : '');
|
|
2383
2491
|
if (
|
|
2384
|
-
|
|
2492
|
+
/\b(?:Change|Form|Focus)Event<\s*(?:HTML(?:Input|TextArea|Select)Element\s*\|?\s*)+[,>]/.test(
|
|
2493
|
+
type,
|
|
2494
|
+
)
|
|
2385
2495
|
)
|
|
2386
2496
|
return true;
|
|
2387
2497
|
const attribute = this.handlerAttribute(found.fn);
|
|
@@ -2436,6 +2546,9 @@ class ModuleTransform {
|
|
|
2436
2546
|
const element = node.parent;
|
|
2437
2547
|
const tag = element.tagName.getText(this.sf);
|
|
2438
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);
|
|
2439
2552
|
const spread = node.properties.some(ts.isJsxSpreadAttribute);
|
|
2440
2553
|
const attributes = node.properties;
|
|
2441
2554
|
|
|
@@ -2465,13 +2578,14 @@ class ModuleTransform {
|
|
|
2465
2578
|
const line = this.source.slice(this.source.lastIndexOf('\n', start - 1), start);
|
|
2466
2579
|
out += 'onInput={onChange}' + (/^\n[ \t]*$/.test(line) ? line : ' ');
|
|
2467
2580
|
}
|
|
2468
|
-
if (!ts.isJsxAttribute(attribute) || !intrinsic) {
|
|
2581
|
+
if (!ts.isJsxAttribute(attribute) || !(intrinsic || textField)) {
|
|
2469
2582
|
out += this.emit(attribute, PLAIN);
|
|
2470
2583
|
continue;
|
|
2471
2584
|
}
|
|
2472
2585
|
const name = attribute.name.getText(this.sf);
|
|
2473
2586
|
if (
|
|
2474
2587
|
name === 'className' &&
|
|
2588
|
+
intrinsic &&
|
|
2475
2589
|
this.target === 'tsrx' &&
|
|
2476
2590
|
!attributeOf(element, 'class') &&
|
|
2477
2591
|
!spread
|
|
@@ -2517,7 +2631,7 @@ class ModuleTransform {
|
|
|
2517
2631
|
isTextEntry(element) {
|
|
2518
2632
|
const tag = element.tagName.getText(this.sf);
|
|
2519
2633
|
if (tag === 'textarea') return true;
|
|
2520
|
-
if (tag !== 'input') return false;
|
|
2634
|
+
if (tag !== 'input' && !this.isTextFieldComponent(element)) return false;
|
|
2521
2635
|
const type = attributeOf(element, 'type');
|
|
2522
2636
|
if (!type) return true;
|
|
2523
2637
|
const value = type.initializer;
|