@octanejs/codemod 0.2.1 → 0.2.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/dist/project.js CHANGED
@@ -10,14 +10,15 @@ import { DATA } from '@octanejs/cli/data';
10
10
  import { parseSync } from '@tsrx/oxc/parser';
11
11
  import ts from 'typescript';
12
12
  import { finding, loadCompiler, thrown } from './compiler.js';
13
+ import { skipWrappers } from './expression-wrappers.js';
13
14
  import { isReactMotion, PORTED_PACKAGES } from './mappings.js';
14
15
  import { strengthen } from './strong.js';
15
- import { bind, CONTEXT_ALIAS, CONTEXT_PROVIDER_GETTER, MAP_CALLBACK_SCOPE, MAP_PARAMETER_TDZ, MAP_PARAMETER_WRITE, projectTypeAt, textKind, transformModule, } from './transform.js';
16
- import { directRendererCalls, nativeExternalStore } from './local-react-hook.js';
17
- import { forwardedProps } from './forwarded-props.js';
18
- import { importsReactBridge, islandComponents, executableImports, hostedServerComponents, intrinsicReactExports, octaneRootComponents, reactServerComponents, retainedReactComponentReturns, reverseIslandExports, } from './react-island-sources.js';
16
+ import { bind, BUFFERED_SSR_OPTIONS, BUFFERED_SSR_REACT_COMPONENT, CONTEXT_ALIAS, CONTEXT_PROVIDER_GETTER, ELEMENT_CHILD_ALIAS, INTL_PROVIDER_DEFAULTS, MAP_CALLBACK_SCOPE, MAP_PARAMETER_TDZ, MAP_PARAMETER_WRITE, projectTypeAt, REACT_TYPE_PROJECTION, textKind, transformModule, } from './transform.js';
17
+ import { directRendererCalls, namedRuntimeImport, nativeExternalStore, } from './local-react-hook.js';
18
+ import { contains, forwardedProps } from './forwarded-props.js';
19
+ import { importsReactBridge, islandComponents, executableImports, hostedComponents, directReactExports, migratedJsxFactories, octaneRootComponents, reactClientComponents, reactClassExports, reactServerComponents, retainedReactComponentReturns, retainedReactContextExports, retainedReactElementReturns, reverseIslandExports, } from './react-island-sources.js';
19
20
  const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
20
- const ADAPTER_OCTANE_VERSION = /^0\.(?:16\.(?:[7-9]|[1-9]\d+)|1[78]\.(?:0|[1-9]\d*))$/;
21
+ const ADAPTER_OCTANE_VERSION = /^0\.(?:16\.(?:[7-9]|[1-9]\d+)|1[789]\.(?:0|[1-9]\d*))$/;
21
22
  // React Intl 7.1.14. Both entry points re-export a hook that calls React.useContext.
22
23
  const INTL_HOOK_FILES = {
23
24
  'index.js': '8f5854dadcd055f066234e13a344bd0b102aea2d50ddfd2f0cf12e9f48116059',
@@ -49,6 +50,9 @@ export async function runCodemod(paths, options = {}) {
49
50
  findRoot(fs.statSync(first, { throwIfNoEntry: false })?.isFile() ? path.dirname(first) : first));
50
51
  const known = new Set(paths.flatMap((entry) => collect(path.resolve(entry))));
51
52
  const files = [...known];
53
+ const config = tsconfigOptions(root);
54
+ const rootProject = ts.findConfigFile(root, ts.sys.fileExists);
55
+ let selectedRealpaths;
52
56
  const renames = new Map();
53
57
  const exports = new Map();
54
58
  const owners = new Map();
@@ -101,7 +105,31 @@ export async function runCodemod(paths, options = {}) {
101
105
  });
102
106
  for (const file of files) {
103
107
  const source = fs.readFileSync(file, 'utf8');
104
- const result = transformModule(source, file, { target });
108
+ const result = transformModule(source, file, {
109
+ target,
110
+ mutableExports() {
111
+ const options = bindingOptions(file);
112
+ if (!options)
113
+ return false;
114
+ const kind = options.module;
115
+ if (kind === undefined) {
116
+ return (!options.noEmit &&
117
+ options.moduleResolution !== ts.ModuleResolutionKind.Bundler &&
118
+ (options.target ?? ts.ScriptTarget.ES5) < ts.ScriptTarget.ES2015);
119
+ }
120
+ if (kind === ts.ModuleKind.CommonJS ||
121
+ kind === ts.ModuleKind.AMD ||
122
+ kind === ts.ModuleKind.UMD)
123
+ return true;
124
+ if (kind !== ts.ModuleKind.Node16 &&
125
+ kind !== ts.ModuleKind.Node18 &&
126
+ kind !== ts.ModuleKind.Node20 &&
127
+ kind !== ts.ModuleKind.NodeNext)
128
+ return false;
129
+ return (ts.getImpliedNodeFormatForFile(file, undefined, ts.sys, options) ===
130
+ ts.ModuleKind.CommonJS);
131
+ },
132
+ });
105
133
  exports.set(file, result.exports);
106
134
  if (!result.template)
107
135
  continue;
@@ -133,11 +161,21 @@ export async function runCodemod(paths, options = {}) {
133
161
  }
134
162
  renames.set(file, output);
135
163
  }
164
+ const routerEntries = renames.size ? reactRouterEntries(root) : undefined;
165
+ const protectedEntries = new Set(routerEntries?.map(outputKey));
166
+ for (const entry of renames.keys()) {
167
+ if (!protectedEntries.has(outputKey(entry)))
168
+ continue;
169
+ const conflict = conflictFor(entry, fs.readFileSync(entry, 'utf8'), renames.get(entry), 'is an implicit React Router entry that must keep its original extension');
170
+ if (write)
171
+ return blockedWrite(root, conflict);
172
+ conflicts.set(entry, conflict);
173
+ renames.delete(entry);
174
+ }
136
175
  // A colliding source remains in place, so its imports and export contracts
137
176
  // must not participate in the preview as if it had been migrated.
138
177
  for (const file of conflicts.keys())
139
178
  exports.delete(file);
140
- const config = tsconfigOptions(root);
141
179
  const strictConfig = (config?.strictNullChecks ?? config?.strict) ? config : null;
142
180
  let program;
143
181
  function typesOf(file) {
@@ -151,11 +189,18 @@ export async function runCodemod(paths, options = {}) {
151
189
  }
152
190
  const contextsOf = contextIndex(exports, known);
153
191
  const contextPaths = Object.keys(config?.paths ?? {}).map((pattern) => pattern.split('*'));
154
- const renamed = renamedImports(root, config, renames);
192
+ const moduleKind = config?.module;
193
+ const esmContextProject = (moduleKind === ts.ModuleKind.ES2015 ||
194
+ moduleKind === ts.ModuleKind.ES2020 ||
195
+ moduleKind === ts.ModuleKind.ES2022 ||
196
+ moduleKind === ts.ModuleKind.ESNext) &&
197
+ !config?.moduleSuffixes &&
198
+ !config?.rootDirs;
199
+ const renamed = renamedImports(root, config, renames, bindingOptions, linkedRename);
155
200
  const foldNames = process.platform === 'darwin';
156
201
  const leafKey = (file) => {
157
202
  const name = path.basename(file);
158
- return foldNames ? name.toLowerCase() : name;
203
+ return foldNames ? name.normalize('NFC').toLowerCase() : name;
159
204
  };
160
205
  const sourceNames = new Set([...renames.keys()].map(leafKey));
161
206
  const sourceEntries = new Map([...renames.keys()].map((file) => [entryKey(file), file]));
@@ -214,7 +259,7 @@ export async function runCodemod(paths, options = {}) {
214
259
  }
215
260
  return inspect(destination, name, prop, ordinaryCaller, depth);
216
261
  }
217
- // resolveRename returns only an on-disk source that actually won import resolution.
262
+ // Index the exports of selected source modules by their planned output.
218
263
  const elementExports = new Map();
219
264
  const descriptorExports = new Map();
220
265
  for (const [from, to] of renames) {
@@ -229,10 +274,18 @@ export async function runCodemod(paths, options = {}) {
229
274
  const compiler = verify || strong ? await loadCompiler(root) : null;
230
275
  const packages = new Map();
231
276
  const missing = new Map();
232
- // `ReactCompat` hosts a component from a package with no port in a React
277
+ // `ReactCompat` hosts a component from a retained package import in a React
233
278
  // root, from 19.2 within the React 19 series it supports.
234
279
  const reactCompat = ['react', 'react-dom'].every((name) => /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''));
235
- const rootProject = ts.findConfigFile(root, ts.sys.fileExists);
280
+ const reactExports = new Map();
281
+ function originalReactExports(file) {
282
+ let exports = reactExports.get(file);
283
+ if (!exports) {
284
+ exports = directReactExports(file, fs.readFileSync(file, 'utf8'));
285
+ reactExports.set(file, exports);
286
+ }
287
+ return exports;
288
+ }
236
289
  function automaticReactJsx(file) {
237
290
  // A nested project can compile the same file with another JSX factory.
238
291
  return (config?.jsx === ts.JsxEmit.ReactJSX &&
@@ -283,6 +336,13 @@ export async function runCodemod(paths, options = {}) {
283
336
  fs.realpathSync(target.resolvedFileName).split(path.sep).includes('node_modules'));
284
337
  }
285
338
  let physicalRoot;
339
+ function isPlainFile(file) {
340
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
341
+ return (!!stat?.isFile() &&
342
+ stat.nlink === 1 &&
343
+ fs.realpathSync(file) ===
344
+ path.join((physicalRoot ??= fs.realpathSync(root)), path.relative(root, file)));
345
+ }
286
346
  const retainedStoreArguments = new Map();
287
347
  const descriptorModules = new Map();
288
348
  function retainedStoreArgument(file, source, name) {
@@ -482,8 +542,7 @@ export async function runCodemod(paths, options = {}) {
482
542
  adapterError = 'The project compiler cannot compile the React Intl adapter.';
483
543
  }
484
544
  }
485
- const specifier = path.relative(dir, adapter).split(path.sep).join('/');
486
- return specifier.startsWith('.') ? specifier : './' + specifier;
545
+ return relativeImport(file, adapter);
487
546
  };
488
547
  const helperDir = path.dirname(adapter);
489
548
  const storeBridge = path.join(helperDir, 'octane-store-context.tsrx');
@@ -516,8 +575,86 @@ export async function runCodemod(paths, options = {}) {
516
575
  }).changed;
517
576
  }
518
577
  const { inputFactory, changedJsxExport, helperFunction, localFile, exportsConstObject } = storeSources(root, config, unchangedStoreInput, (file) => renames.has(file));
578
+ function localReactTemplateComponent(from, module, name) {
579
+ if (!/^\.{1,2}\//.test(module) ||
580
+ /[!%?#\\]/.test(module) ||
581
+ !automaticReactJsx(from) ||
582
+ config?.rootDirs?.length ||
583
+ config?.moduleSuffixes?.some(Boolean))
584
+ return false;
585
+ const file = localFile(from, module, true);
586
+ const requested = path.resolve(path.dirname(from), module);
587
+ if (!file?.endsWith('.tsx') ||
588
+ (file !== requested &&
589
+ (file !== requested + '.tsx' || !unambiguousJsxPath(file, requested))) ||
590
+ known.has(file) ||
591
+ !automaticReactJsx(file))
592
+ return false;
593
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
594
+ if (!stat?.isFile() || stat.nlink !== 1)
595
+ return false;
596
+ selectedRealpaths ??= new Set(files.map((input) => fs.realpathSync.native(input)));
597
+ if (selectedRealpaths.has(fs.realpathSync.native(file)))
598
+ return false;
599
+ const exported = originalReactExports(file);
600
+ return ((exported.intrinsics.has(name) || exported.wrappers.has(name)) &&
601
+ originalReactEntry(file, 'react/jsx-runtime'));
602
+ }
603
+ let selectedInPlace;
604
+ function writesSelectedInput(file) {
605
+ // An in-place write through a symlink changes its physical target.
606
+ selectedInPlace ??= new Set([...known].filter((f) => !renames.has(f) && !conflicts.has(f)).map((f) => fs.realpathSync(f)));
607
+ return selectedInPlace.has(fs.realpathSync(file));
608
+ }
609
+ const noClasses = new Set();
610
+ const localClasses = new Map();
611
+ function localReactClass(from, module, name) {
612
+ if (/[!%?#\\]/.test(module))
613
+ return;
614
+ const file = localFile(from, module, true);
615
+ if (!file || !file.endsWith('.tsx') || conflicts.has(file))
616
+ return;
617
+ let classes = localClasses.get(file);
618
+ if (classes === undefined) {
619
+ const source = fs.readFileSync(file, 'utf8');
620
+ classes =
621
+ /\bclass\b/.test(source) && installedReact(file)
622
+ ? reactClassExports(file, source)
623
+ : noClasses;
624
+ localClasses.set(file, classes);
625
+ }
626
+ if (classes.has(name) &&
627
+ ts.findConfigFile(path.dirname(from), ts.sys.fileExists) === rootProject)
628
+ return renamed(from, module)?.file === file ? 'error' : 'warning';
629
+ }
630
+ const retainedContexts = new Map();
631
+ function localReactContext(from, module, name, member) {
632
+ if (/[!%?#\\]/.test(module) || catalogName(module) !== null || resolveRename(from, module))
633
+ return false;
634
+ const file = localFile(from, module, true);
635
+ if (!file || known.has(file))
636
+ return false;
637
+ let contexts = retainedContexts.get(file);
638
+ if (contexts === undefined) {
639
+ const source = fs.readFileSync(file, 'utf8');
640
+ contexts = new Map();
641
+ if (source.includes('createContext') || source.includes('\\')) {
642
+ const stat = fs.lstatSync(file);
643
+ if (stat.isFile() &&
644
+ stat.nlink === 1 &&
645
+ fs.realpathSync(file) ===
646
+ path.join((physicalRoot ??= fs.realpathSync(root)), path.relative(root, file)) &&
647
+ !writesSelectedInput(file) &&
648
+ installedReact(file))
649
+ contexts = retainedReactContextExports(file, source);
650
+ }
651
+ retainedContexts.set(file, contexts);
652
+ }
653
+ return ((member ? contexts.get(name) === true : contexts.has(name)) &&
654
+ ts.findConfigFile(path.dirname(from), ts.sys.fileExists) === rootProject);
655
+ }
519
656
  const localHints = new Map();
520
- function initializerResourceHint(from, module, name) {
657
+ function initializerResourceHint(from, module, name, retainedOnly = false) {
521
658
  const file = localFile(from, module);
522
659
  if (!file ||
523
660
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
@@ -534,7 +671,9 @@ export async function runCodemod(paths, options = {}) {
534
671
  }
535
672
  localHints.set(file, calls);
536
673
  }
537
- return calls.get(name);
674
+ const hint = calls.get(name);
675
+ if (hint && (!retainedOnly || (fs.statSync(file).nlink === 1 && !writesSelectedInput(file))))
676
+ return hint;
538
677
  }
539
678
  const localHooks = new Map();
540
679
  const intlHookPackages = new Map();
@@ -586,7 +725,6 @@ export async function runCodemod(paths, options = {}) {
586
725
  return false;
587
726
  }
588
727
  }
589
- let selectedInPlace;
590
728
  function localReactHook(from, module, name, nativeOnly) {
591
729
  if (catalogName(module) !== null ||
592
730
  resolveRename(from, module) ||
@@ -594,11 +732,13 @@ export async function runCodemod(paths, options = {}) {
594
732
  ts.findConfigFile(path.dirname(from), ts.sys.fileExists) !== rootProject)
595
733
  return;
596
734
  const file = localFile(from, module);
735
+ const jsSpecifier = module.endsWith('.js') && (module.startsWith('./') || module.startsWith('../'));
597
736
  if (!file ||
737
+ (jsSpecifier && path.resolve(path.dirname(from), module.slice(0, -3) + '.ts') !== file) ||
598
738
  known.has(file) ||
599
739
  path.basename(file) === 'index.ts' ||
600
740
  fs.existsSync(file.slice(0, -3) + '.tsrx') ||
601
- (path.extname(module) && !module.endsWith('.ts')) ||
741
+ (path.extname(module) && !module.endsWith('.ts') && !jsSpecifier) ||
602
742
  fs.realpathSync(file) !== path.join(fs.realpathSync(root), path.relative(root, file)) ||
603
743
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
604
744
  return;
@@ -613,11 +753,15 @@ export async function runCodemod(paths, options = {}) {
613
753
  originalModule(file, 'react') &&
614
754
  readInstalled(path.dirname(file), 'react')?.manifest.name === 'react';
615
755
  const intl = (source.includes('useIntl') || escaped) && originalIntlHook(file);
616
- if (react || intl) {
756
+ const store = planStoreHook && /\buse[A-Z]|\\u/.test(source);
757
+ if (react || intl || store) {
617
758
  const existing = program?.getSourceFile(file);
618
759
  const bound = existing && program
619
760
  ? { sf: existing, checker: program.getTypeChecker() }
620
761
  : bind(file, source);
762
+ if (planStoreHook && store)
763
+ hooks.retainedStores = directRendererCalls(bound.sf, bound.checker, (specifier, exported) => !!unportedName(specifier, file) &&
764
+ planStoreHook(specifier, exported, file)?.requiresReact() === true);
621
765
  if (react)
622
766
  hooks.direct = directRendererCalls(bound.sf, bound.checker, 'react', (name) => name === 'useCallback' ||
623
767
  name === 'useContext' ||
@@ -629,15 +773,18 @@ export async function runCodemod(paths, options = {}) {
629
773
  }
630
774
  localHooks.set(file, hooks);
631
775
  }
632
- const hook = hooks.direct.get(name);
633
- if ((!hook && !hooks.privateContexts.has(name)) || fs.statSync(file).nlink > 1)
776
+ // Keep TS substitution advisory. A loader may select a different executable.
777
+ const hook = jsSpecifier ? undefined : hooks.direct.get(name);
778
+ const retainedStore = !jsSpecifier && hooks.retainedStores?.has(name) && automaticReactJsx(from);
779
+ if ((!hook && !retainedStore && !hooks.privateContexts.has(name)) ||
780
+ fs.statSync(file).nlink > 1)
634
781
  return;
635
- // Writing an unrenamed selection through a symlink changes its physical target.
636
- selectedInPlace ??= new Set([...known].filter((f) => !renames.has(f) && !conflicts.has(f)).map((f) => fs.realpathSync(f)));
637
- if (selectedInPlace.has(fs.realpathSync(file)))
782
+ if (writesSelectedInput(file))
638
783
  return;
639
784
  if (!hook)
640
- return { privateContext: true };
785
+ return retainedStore
786
+ ? { retainedStore: true }
787
+ : { privateContext: true };
641
788
  if (nativeOnly &&
642
789
  compiler &&
643
790
  hook === 'useSyncExternalStore' &&
@@ -662,12 +809,11 @@ export async function runCodemod(paths, options = {}) {
662
809
  return;
663
810
  return bind(leaf, fs.readFileSync(leaf, 'utf8'));
664
811
  });
665
- const output = file.slice(0, -3) + '.octane.ts';
666
- if (code &&
667
- !compile(compiler, code, output, true).some((finding) => finding.severity === 'error') &&
668
- !checkHelper(output, code)) {
812
+ // The hook needs the same client and server compiler as its caller.
813
+ const output = file.slice(0, -3) + '.octane.tsrx';
814
+ if (code && !checkHelper(output, code)) {
669
815
  generatedHelpers.set(output, code);
670
- return { from: relativeTsImport(from, output) };
816
+ return { from: relativeImport(from, output) };
671
817
  }
672
818
  }
673
819
  return hook;
@@ -779,6 +925,52 @@ export async function runCodemod(paths, options = {}) {
779
925
  checkedHelpers.set(output, { code, state, error });
780
926
  return error;
781
927
  }
928
+ function selectedContextReexport(file, name) {
929
+ const seen = new Set();
930
+ for (;;) {
931
+ const selected = exports.get(file);
932
+ if (!selected ||
933
+ seen.has(file) ||
934
+ !isPlainFile(file) ||
935
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
936
+ return false;
937
+ const hasContext = selected.contexts.includes(name);
938
+ if (!hasContext && !selected.reexports.length)
939
+ return false;
940
+ // TypeScript's source lookup omits these competing bundler targets.
941
+ const stem = file.slice(0, -path.extname(file).length);
942
+ if (['.json', '.tsrx'].some((ext) => fs.lstatSync(stem + ext, { throwIfNoEntry: false })))
943
+ return false;
944
+ const source = fs.readFileSync(file, 'utf8');
945
+ if (hasContext)
946
+ return installedReact(file) && retainedReactContextExports(file, source).has(name);
947
+ seen.add(file);
948
+ const { statements } = ts.createSourceFile(file, source, ts.ScriptTarget.Latest);
949
+ const [statement] = statements;
950
+ // A pure named forwarding module has no competing value export.
951
+ if (statements.length !== 1 ||
952
+ !ts.isExportDeclaration(statement) ||
953
+ statement.isTypeOnly ||
954
+ statement.attributes ||
955
+ !statement.exportClause ||
956
+ !ts.isNamedExports(statement.exportClause) ||
957
+ !statement.moduleSpecifier ||
958
+ !ts.isStringLiteral(statement.moduleSpecifier))
959
+ return false;
960
+ const specifier = statement.moduleSpecifier.text;
961
+ if (!/^\.{1,2}\//.test(specifier) || /[!%?#\\]/.test(specifier))
962
+ return false;
963
+ const bindings = statement.exportClause.elements.filter((element) => !element.isTypeOnly && element.name.text === name);
964
+ if (bindings.length !== 1)
965
+ return false;
966
+ const next = localFile(file, specifier, true);
967
+ const direct = path.resolve(path.dirname(file), specifier);
968
+ if (!next || (next !== direct && next !== direct + path.extname(next)))
969
+ return false;
970
+ file = next;
971
+ name = (bindings[0].propertyName ?? bindings[0].name).text;
972
+ }
973
+ }
782
974
  const results = [];
783
975
  const storeHookComponents = new Map();
784
976
  if (options.svgPaths && target === 'tsrx') {
@@ -813,23 +1005,23 @@ export async function runCodemod(paths, options = {}) {
813
1005
  const reactStoreComponents = new Map();
814
1006
  let installedClsx;
815
1007
  let reactJsx;
816
- const isContext = (specifier, name, local) => {
1008
+ const isContext = (specifier, name, local, attributed) => {
817
1009
  if (!specifier.startsWith('.')) {
818
1010
  if (!contextPaths.length ||
819
- config?.module !== ts.ModuleKind.ESNext ||
820
- config.moduleSuffixes ||
821
- config.rootDirs ||
1011
+ !esmContextProject ||
822
1012
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
823
1013
  !contextPaths.some(([start, end]) => end === undefined
824
1014
  ? specifier === start
825
1015
  : specifier.startsWith(start) && specifier.endsWith(end)))
826
1016
  return null;
827
1017
  const source = localFile(file, specifier, true);
1018
+ const selected = source && exports.get(source);
828
1019
  return source &&
829
- exports.has(source) &&
1020
+ selected &&
830
1021
  ts.findConfigFile(path.dirname(source), ts.sys.fileExists) === rootProject &&
831
- (exports.get(source)?.contexts.includes(name) ||
832
- (name === 'default' ? local : name).endsWith('Context'))
1022
+ (selected.contexts.includes(name) ||
1023
+ (name === 'default' ? local : name).endsWith('Context') ||
1024
+ (!attributed && selected.reexports.length > 0 && selectedContextReexport(source, name)))
833
1025
  ? 'review-alias'
834
1026
  : null;
835
1027
  }
@@ -837,9 +1029,7 @@ export async function runCodemod(paths, options = {}) {
837
1029
  if (target)
838
1030
  return contextsOf(target.file).has(name);
839
1031
  if (!name.endsWith('Context') ||
840
- config?.module !== ts.ModuleKind.ESNext ||
841
- config.moduleSuffixes ||
842
- config.rootDirs ||
1032
+ !esmContextProject ||
843
1033
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
844
1034
  return null;
845
1035
  const source = localFile(file, specifier, true);
@@ -870,7 +1060,7 @@ export async function runCodemod(paths, options = {}) {
870
1060
  : (module, name, safeUses) => {
871
1061
  if (!unportedName(module, file))
872
1062
  return null;
873
- const plan = planStoreHook(module, name, file);
1063
+ const plan = planStoreHook(module, name, file)?.plan;
874
1064
  if (!plan ||
875
1065
  !safeUses((source, name, selection) => {
876
1066
  if (selection)
@@ -915,6 +1105,7 @@ export async function runCodemod(paths, options = {}) {
915
1105
  .replace(/\.ts$/, '');
916
1106
  return { from: relative.startsWith('.') ? relative : './' + relative, name: plan.name };
917
1107
  };
1108
+ let originalSvgServer;
918
1109
  const svgAdapter = options.svgPaths && renames.has(file)
919
1110
  ? (specifier, color) => pathSvgAdapter(file, specifier, svgErrors, color)
920
1111
  : undefined;
@@ -930,15 +1121,68 @@ export async function runCodemod(paths, options = {}) {
930
1121
  reactIntlAdapter: intl,
931
1122
  forwardedText: (module, name, prop, ordinaryCaller, through) => forwardedProp(file, module, name, prop, through ? 'forwarded-text' : 'text', ordinaryCaller),
932
1123
  resolveStoreHook,
1124
+ retainedRegistry: files.length === 1 && /\.tsx?$/.test(file) && esmContextProject
1125
+ ? (specifier) => {
1126
+ if (!specifier.startsWith('./') && !specifier.startsWith('../'))
1127
+ return;
1128
+ const registry = localFile(file, specifier, true);
1129
+ if (!registry || known.has(registry))
1130
+ return;
1131
+ const request = path.resolve(path.dirname(file), specifier);
1132
+ if (registry !== request && registry !== request + path.extname(registry))
1133
+ return;
1134
+ if (ts.findConfigFile(path.dirname(registry), ts.sys.fileExists) === rootProject)
1135
+ return program?.getSourceFile(registry);
1136
+ }
1137
+ : undefined,
933
1138
  get originalReact() {
934
1139
  return installedReact(file);
935
1140
  },
1141
+ retainedReactBridgeComponent: (bridge, module, name) => {
1142
+ if (!reactCompat ||
1143
+ !module.startsWith('.') ||
1144
+ !module.endsWith('.tsx') ||
1145
+ bindingOptions(file)?.rootDirs?.length ||
1146
+ bindingOptions(file)?.moduleSuffixes?.some(Boolean) ||
1147
+ resolveRename(file, module) ||
1148
+ !originalOctaneBridge(file, bridge) ||
1149
+ !originalReactEntry(file, 'react', bindingOptions(file)))
1150
+ return false;
1151
+ const owner = localFile(file, module, true);
1152
+ if (!owner?.endsWith('.tsx') || owner !== path.resolve(path.dirname(file), module))
1153
+ return false;
1154
+ const stat = fs.lstatSync(owner, { throwIfNoEntry: false });
1155
+ if (!stat?.isFile() ||
1156
+ stat.nlink !== 1 ||
1157
+ known.has(owner) ||
1158
+ !automaticReactJsx(owner) ||
1159
+ !originalReactEntry(owner, 'react/jsx-runtime'))
1160
+ return false;
1161
+ // An alternate spelling or parent symlink can reach a selected source.
1162
+ selectedRealpaths ??= new Set(files.map((file) => fs.realpathSync.native(file)));
1163
+ if (selectedRealpaths.has(fs.realpathSync.native(owner)))
1164
+ return false;
1165
+ const source = fs.readFileSync(owner, 'utf8');
1166
+ return (/^\s*\/\*\*\s*@jsxImportSource\s+react\s*\*\//.test(source) &&
1167
+ directReactExports(owner, source).intrinsics.has(name));
1168
+ },
1169
+ originalReactServerEntry: (module) => originalReactEntry(file, module, bindingOptions(file)) &&
1170
+ originalOctaneBridge(file, 'octane/server'),
936
1171
  initializerResourceHint: renames.has(file)
937
- ? (module, name) => initializerResourceHint(file, module, name)
1172
+ ? (module, name, retainedOnly) => initializerResourceHint(file, module, name, retainedOnly)
938
1173
  : undefined,
939
1174
  localReactHook: renames.has(file)
940
1175
  ? (module, name, nativeOnly) => localReactHook(file, module, name, nativeOnly)
941
1176
  : undefined,
1177
+ localReactTemplateComponent: renames.has(file)
1178
+ ? (module, name) => localReactTemplateComponent(file, module, name)
1179
+ : undefined,
1180
+ localReactClass: renames.has(file)
1181
+ ? (module, name) => localReactClass(file, module, name)
1182
+ : undefined,
1183
+ localReactContext: renames.has(file)
1184
+ ? (module, name, member) => localReactContext(file, module, name, member)
1185
+ : undefined,
942
1186
  localReactRootComponent: renames.has(file)
943
1187
  ? (module, name) => {
944
1188
  const hook = localReactHook(file, module, name, false);
@@ -962,9 +1206,19 @@ export async function runCodemod(paths, options = {}) {
962
1206
  isContext,
963
1207
  elementChild: !elementExports.size
964
1208
  ? undefined
965
- : (binding) => typeof binding === 'number'
966
- ? (exports.get(file)?.elementChildren?.some((x) => x.start === binding) ?? false)
967
- : matchesExport(elementExports, binding),
1209
+ : (binding) => {
1210
+ if (typeof binding === 'number')
1211
+ return (exports.get(file)?.elementChildren?.some((x) => x.start === binding) ?? false);
1212
+ if (binding.module.startsWith('.'))
1213
+ return matchesExport(elementExports, binding);
1214
+ if (ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
1215
+ return false;
1216
+ const match = renamed(file, binding.module);
1217
+ const output = match && renames.get(match.file);
1218
+ return output && elementExports.get(output)?.has(binding.imported)
1219
+ ? 'review-alias'
1220
+ : false;
1221
+ },
968
1222
  descriptorChild: descriptorExports.size
969
1223
  ? (binding) => matchesExport(descriptorExports, binding)
970
1224
  : undefined,
@@ -1005,6 +1259,12 @@ export async function runCodemod(paths, options = {}) {
1005
1259
  return real.endsWith('.module.css') ? real : undefined;
1006
1260
  },
1007
1261
  pathSvgAdapter: svgAdapter,
1262
+ get originalSvgServer() {
1263
+ return (originalSvgServer ??=
1264
+ !!svgAdapter &&
1265
+ originalOctaneRuntime(file, 'octane/server', bindingOptions(file)) &&
1266
+ originalOctaneRuntime(svgHelper, 'octane', bindingOptions(svgHelper)));
1267
+ },
1008
1268
  fixedColorSvgAdapter: svgAdapter,
1009
1269
  reactStoreComponent: (specifier) => {
1010
1270
  if (!reactStoreComponents.has(specifier))
@@ -1032,11 +1292,16 @@ export async function runCodemod(paths, options = {}) {
1032
1292
  const result = transform();
1033
1293
  if (result.exports.storeHookComponents)
1034
1294
  storeHookComponents.set(file, result.exports.storeHookComponents);
1035
- const blockedTransform = result.notes.find((note) => note.rule === MAP_PARAMETER_WRITE ||
1295
+ const blockedTransform = result.notes.find((note) => note.rule === BUFFERED_SSR_OPTIONS ||
1296
+ note.rule === BUFFERED_SSR_REACT_COMPONENT ||
1297
+ note.rule === MAP_PARAMETER_WRITE ||
1036
1298
  note.rule === MAP_PARAMETER_TDZ ||
1037
1299
  note.rule === MAP_CALLBACK_SCOPE ||
1038
1300
  note.rule === CONTEXT_ALIAS ||
1039
- note.rule === CONTEXT_PROVIDER_GETTER);
1301
+ note.rule === CONTEXT_PROVIDER_GETTER ||
1302
+ note.rule === INTL_PROVIDER_DEFAULTS ||
1303
+ note.rule === ELEMENT_CHILD_ALIAS ||
1304
+ note.rule === REACT_TYPE_PROJECTION);
1040
1305
  if (write && blockedTransform)
1041
1306
  return blockedWrite(root, unchangedFile(path.relative(root, file), source, blockedTransform), compiler?.from);
1042
1307
  for (const message of [...storeErrors, ...svgErrors]) {
@@ -1133,9 +1398,9 @@ export async function runCodemod(paths, options = {}) {
1133
1398
  module?.packageId?.name === 'octane' &&
1134
1399
  fs.realpathSync(module.resolvedFileName).startsWith(fs.realpathSync(installed.dir) + path.sep));
1135
1400
  }
1136
- function originalOctaneRuntime(file, specifier) {
1401
+ function originalOctaneRuntime(file, specifier, options = config) {
1137
1402
  const installed = readInstalled(path.dirname(file), 'octane');
1138
- const module = originalModule(file, specifier);
1403
+ const module = originalModule(file, specifier, options);
1139
1404
  const adapterRuntime = readInstalled(helperDir, 'octane');
1140
1405
  if (installed?.manifest.name !== 'octane' ||
1141
1406
  module?.packageId?.name !== 'octane' ||
@@ -1166,9 +1431,9 @@ export async function runCodemod(paths, options = {}) {
1166
1431
  : `If the migrated ${component}'s store hook reads context, this standalone Octane root needs NativeStoreProvider with its original store context and value.`,
1167
1432
  };
1168
1433
  }
1169
- function originalReactEntry(file, name) {
1170
- const packageRoot = name === 'react/jsx-runtime' ? 'react' : 'react-dom';
1171
- const types = originalModule(file, name)?.packageId?.name;
1434
+ function originalReactEntry(file, name, options = config) {
1435
+ const packageRoot = packageName(name);
1436
+ const types = originalModule(file, name, options)?.packageId?.name;
1172
1437
  if (types !== packageRoot && types !== `@types/${packageRoot}`)
1173
1438
  return false;
1174
1439
  const installed = readInstalled(path.dirname(file), packageRoot);
@@ -1183,14 +1448,165 @@ export async function runCodemod(paths, options = {}) {
1183
1448
  }
1184
1449
  }
1185
1450
  const reverseIslands = new Map();
1186
- const intrinsicExports = new Map();
1187
- const linkedConflicts = new Map();
1451
+ const templateExports = new Map();
1452
+ function hasTemplateExport(file, name) {
1453
+ let names = templateExports.get(file.output);
1454
+ if (!names) {
1455
+ names = new Set();
1456
+ const { program, errors } = parseSync(file.output, file.code);
1457
+ if (program && !errors.length) {
1458
+ let defaultLocal;
1459
+ const templateLocals = new Set();
1460
+ const isTemplateBody = (body) => isRecord(body) && body.type === 'JSXCodeBlock';
1461
+ // The TSRX parser does not expose the type-only flag on local export lists.
1462
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.JSX, file.code);
1463
+ for (const statement of program.body) {
1464
+ const defaultExport = statement.type === 'ExportDefaultDeclaration';
1465
+ let fn = defaultExport || statement.type === 'ExportNamedDeclaration'
1466
+ ? statement.declaration
1467
+ : statement;
1468
+ if (defaultExport) {
1469
+ while (fn?.type === 'ParenthesizedExpression')
1470
+ fn = fn.expression;
1471
+ if (fn?.type === 'Identifier')
1472
+ defaultLocal = fn.name;
1473
+ }
1474
+ else if (statement.type === 'ExportNamedDeclaration' &&
1475
+ !statement.source &&
1476
+ statement.specifiers.length) {
1477
+ scanner.setTextPos(statement.start);
1478
+ scanner.scan();
1479
+ const typeOnly = scanner.scan() === ts.SyntaxKind.TypeKeyword;
1480
+ for (const specifier of statement.specifiers) {
1481
+ if (!typeOnly &&
1482
+ (specifier.exported.type === 'Identifier'
1483
+ ? specifier.exported.name === 'default'
1484
+ : specifier.exported.value === 'default') &&
1485
+ specifier.local.type === 'Identifier' &&
1486
+ specifier.start === specifier.local.start)
1487
+ defaultLocal = specifier.local.name;
1488
+ }
1489
+ }
1490
+ if (fn?.type === 'FunctionDeclaration' && isTemplateBody(fn.body)) {
1491
+ if (defaultExport)
1492
+ names.add('default');
1493
+ else if (fn.id)
1494
+ names.add(fn.id.name);
1495
+ }
1496
+ else if (defaultExport &&
1497
+ fn?.type === 'ArrowFunctionExpression' &&
1498
+ isTemplateBody(fn.body)) {
1499
+ names.add('default');
1500
+ }
1501
+ else if (fn?.type === 'VariableDeclaration' && fn.kind === 'const') {
1502
+ for (const declaration of fn.declarations) {
1503
+ if (declaration.id.type === 'Identifier' &&
1504
+ declaration.init?.type === 'ArrowFunctionExpression' &&
1505
+ isTemplateBody(declaration.init.body))
1506
+ templateLocals.add(declaration.id.name);
1507
+ }
1508
+ }
1509
+ }
1510
+ if (defaultLocal !== undefined &&
1511
+ (names.has(defaultLocal) || templateLocals.has(defaultLocal)))
1512
+ names.add('default');
1513
+ }
1514
+ templateExports.set(file.output, names);
1515
+ }
1516
+ return names.has(name);
1517
+ }
1518
+ const jsxFactories = new Map();
1519
+ const renamedJsx = [...renames.keys()].some((file) => file.endsWith('.tsx'));
1520
+ const namedReexports = new Map();
1521
+ function canResolveExtensionlessJsx(specifier) {
1522
+ return (/^\.{1,2}\//.test(specifier) &&
1523
+ !/[!%?#\\]/.test(specifier) &&
1524
+ !/\.(?:[cm]?[jt]sx?|tsrx)$/.test(specifier) &&
1525
+ (config?.moduleResolution === undefined ||
1526
+ config.moduleResolution === ts.ModuleResolutionKind.Bundler) &&
1527
+ !config?.rootDirs &&
1528
+ !config?.moduleSuffixes?.some(Boolean));
1529
+ }
1530
+ function isExtensionlessJsxTarget(file, original) {
1531
+ return file.endsWith('.tsx') && unambiguousJsxPath(file, original) && isPlainFile(file);
1532
+ }
1533
+ function retainedJsxTarget(from, specifier, name) {
1534
+ if (!/^\.{1,2}\//.test(specifier) ||
1535
+ /[!%?#\\]/.test(specifier) ||
1536
+ config?.rootDirs ||
1537
+ config?.moduleSuffixes?.some(Boolean))
1538
+ return;
1539
+ const direct = (issuer, spec) => {
1540
+ if (!/^\.{1,2}\//.test(spec) || /[!%?#\\]/.test(spec))
1541
+ return;
1542
+ const original = path.resolve(path.dirname(issuer), spec);
1543
+ const resolved = renamed(issuer, spec);
1544
+ if (!resolved?.file.endsWith('.tsx') || !isPlainFile(resolved.file))
1545
+ return;
1546
+ if (resolved.file === original && spec.endsWith('.tsx'))
1547
+ return resolved.file;
1548
+ if (spec.endsWith('.js') && resolved.file === original.slice(0, -3) + '.tsx') {
1549
+ if (!fs.lstatSync(original, { throwIfNoEntry: false }) && !hasModuleSibling(resolved.file))
1550
+ return resolved.file;
1551
+ }
1552
+ else if (unambiguousJsxPath(resolved.file, original))
1553
+ return resolved.file;
1554
+ };
1555
+ const leaf = direct(from, specifier);
1556
+ if (leaf)
1557
+ return { file: leaf, name, indirect: false };
1558
+ const barrel = localFile(from, specifier);
1559
+ const original = path.resolve(path.dirname(from), specifier);
1560
+ const substituted = specifier.endsWith('.js')
1561
+ ? original.slice(0, -3) + '.ts'
1562
+ : original + '.ts';
1563
+ if (!barrel ||
1564
+ !(barrel === original || (barrel === substituted && !hasModuleSibling(barrel))) ||
1565
+ !isPlainFile(barrel) ||
1566
+ ts.findConfigFile(path.dirname(barrel), ts.sys.fileExists) !== rootProject)
1567
+ return;
1568
+ let exports = namedReexports.get(barrel);
1569
+ if (!exports) {
1570
+ exports = new Map();
1571
+ const { statements } = ts.createSourceFile(barrel, fs.readFileSync(barrel, 'utf8'), ts.ScriptTarget.Latest);
1572
+ for (const statement of statements) {
1573
+ if (!ts.isExportDeclaration(statement) ||
1574
+ statement.isTypeOnly ||
1575
+ statement.attributes ||
1576
+ !statement.moduleSpecifier ||
1577
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
1578
+ !statement.exportClause ||
1579
+ !ts.isNamedExports(statement.exportClause))
1580
+ continue;
1581
+ for (const binding of statement.exportClause.elements) {
1582
+ if (!binding.isTypeOnly)
1583
+ exports.set(binding.name.text, {
1584
+ module: statement.moduleSpecifier.text,
1585
+ name: (binding.propertyName ?? binding.name).text,
1586
+ });
1587
+ }
1588
+ }
1589
+ namedReexports.set(barrel, exports);
1590
+ }
1591
+ const exported = exports.get(name);
1592
+ const target = exported && direct(barrel, exported.module);
1593
+ if (target)
1594
+ return { file: target, name: exported.name, indirect: true };
1595
+ }
1596
+ const renameConflicts = new Map();
1188
1597
  function checkLinkedRename(file, issuer) {
1189
1598
  const selected = linkedRename(file);
1190
- if (selected && !linkedConflicts.has(selected))
1191
- linkedConflicts.set(selected, issuer);
1599
+ if (selected && !renameConflicts.has(selected)) {
1600
+ renameConflicts.set(selected, `would leave a reference in ${path.relative(root, issuer)} pointing to its original name`);
1601
+ }
1192
1602
  }
1193
- const scanRename = (from, specifier) => renamed(from, specifier, (winner) => checkLinkedRename(winner, from))?.specifier ?? null;
1603
+ const scanRename = (from, specifier, commonJs) => renamed(from, specifier, commonJs ? undefined : (winner) => checkLinkedRename(winner, from), (file) => {
1604
+ if (!renameConflicts.has(file)) {
1605
+ renameConflicts.set(file, file.endsWith('.tsx')
1606
+ ? `supplies types for ${JSON.stringify(specifier)} in ${path.relative(root, from)}, where that JavaScript path exists on disk`
1607
+ : `is the JavaScript path for ${JSON.stringify(specifier)} in ${path.relative(root, from)}, where TypeScript resolves to a different file`);
1608
+ }
1609
+ }, commonJs)?.specifier ?? null;
1194
1610
  function protectIslandModule(issuer, specifier, owner) {
1195
1611
  const file = ts.resolveModuleName(specifier, issuer, { moduleResolution: ts.ModuleResolutionKind.Bundler, ...bindingOptions(issuer) }, ts.sys).resolvedModule?.resolvedFileName;
1196
1612
  if (!file || /\.d\.[cm]?ts$/.test(file) || !SOURCE.test(file))
@@ -1225,6 +1641,7 @@ export async function runCodemod(paths, options = {}) {
1225
1641
  for (const module of executableImports(file, fs.readFileSync(file, 'utf8'), !!bindingOptions(file)?.verbatimModuleSyntax))
1226
1642
  protectIslandModule(file, module, owner);
1227
1643
  }
1644
+ const routesEntry = routerEntries?.[1];
1228
1645
  for (const file of edited.size || renames.size
1229
1646
  ? new Set([...collect(root, (name) => SOURCE.test(name) || isTsrx(name)), ...files])
1230
1647
  : []) {
@@ -1239,19 +1656,19 @@ export async function runCodemod(paths, options = {}) {
1239
1656
  continue;
1240
1657
  const result = byFile.get(file);
1241
1658
  const selected = renames.has(file);
1242
- const specifier = 'octane/react/server';
1243
- const originalServerHost = () => automaticReactJsx(file) &&
1244
- originalOctaneBridge(file, specifier) &&
1659
+ const serverBridge = 'octane/react/server';
1660
+ const originalHost = (bridge) => automaticReactJsx(file) &&
1661
+ originalOctaneBridge(file, bridge) &&
1245
1662
  originalReactEntry(file, 'react/jsx-runtime');
1246
- const hasServerImport = source.includes(specifier);
1247
- if (selected &&
1248
- result &&
1249
- (hasServerImport ||
1250
- (source.includes('\\') &&
1251
- ts.preProcessFile(source).importedFiles.some((entry) => entry.fileName === specifier))) &&
1252
- originalServerHost()) {
1253
- const [edge] = hostedServerComponents(file, source);
1254
- if (edge) {
1663
+ const hasServerImport = source.includes(serverBridge);
1664
+ if (selected && result && (source.includes('octane/react') || source.includes('\\'))) {
1665
+ const imports = ts.preProcessFile(source).importedFiles;
1666
+ for (const bridge of [serverBridge, 'octane/react']) {
1667
+ if (!imports.some(({ fileName }) => fileName === bridge) || !originalHost(bridge))
1668
+ continue;
1669
+ const [edge] = hostedComponents(file, source, bridge, true);
1670
+ if (!edge)
1671
+ continue;
1255
1672
  const note = {
1256
1673
  rule: 'react-compat',
1257
1674
  severity: 'error',
@@ -1261,16 +1678,16 @@ export async function runCodemod(paths, options = {}) {
1261
1678
  if (write)
1262
1679
  return blockedWrite(root, unchangedFile(result.file, source, note), compiler?.from);
1263
1680
  result.notes.push(note);
1681
+ break;
1264
1682
  }
1265
1683
  }
1266
1684
  if (selected &&
1267
1685
  storeHookComponents.size &&
1268
1686
  result?.rules['server-render'] &&
1269
- result.rules['root-render'] &&
1270
1687
  automaticReactJsx(file) &&
1271
1688
  originalReactEntry(file, 'react-dom/server') &&
1272
1689
  originalOctaneBridge(file, 'octane/server')) {
1273
- for (const edge of reactServerComponents(file, source, (module) => module === 'react/jsx-runtime' && originalReactEntry(file, module), true)) {
1690
+ for (const edge of reactServerComponents(file, source, (module) => originalReactEntry(file, module), true)) {
1274
1691
  const leaf = renamed(file, edge.module)?.file;
1275
1692
  if (!leaf ||
1276
1693
  leaf !== path.resolve(path.dirname(file), edge.module) ||
@@ -1280,10 +1697,12 @@ export async function runCodemod(paths, options = {}) {
1280
1697
  }
1281
1698
  }
1282
1699
  const paths = rewriteModulePaths(selected ? source : (result?.code ?? source), file, root, renames, scanRename, selected ? undefined : checkLinkedRename);
1283
- if (!paths)
1700
+ const retainedJsx = (paths || renamedJsx) && !known.has(file) && /\.[jt]sx$/.test(file) && source.includes('<');
1701
+ if (!paths && !retainedJsx)
1284
1702
  continue;
1285
1703
  const storeNotes = result?.notes ?? [];
1286
- if (storeHookComponents.size &&
1704
+ if (paths &&
1705
+ storeHookComponents.size &&
1287
1706
  SOURCE.test(file) &&
1288
1707
  ((source.includes('octane') &&
1289
1708
  (source.includes('createRoot') ||
@@ -1307,29 +1726,91 @@ export async function runCodemod(paths, options = {}) {
1307
1726
  }
1308
1727
  if (selected)
1309
1728
  continue;
1310
- const rules = { ...result?.rules, 'module-paths': paths.count };
1729
+ const rules = paths ? { ...result?.rules, 'module-paths': paths.count } : {};
1311
1730
  const name = path.relative(root, file);
1312
1731
  const host = result ?? {
1313
1732
  file: name,
1314
1733
  output: name,
1315
- changed: true,
1734
+ changed: !!paths,
1316
1735
  rules,
1317
1736
  notes: storeNotes,
1318
1737
  strong: null,
1319
1738
  strongFixes: [],
1320
1739
  diagnostics: [],
1321
- code: paths.code,
1740
+ code: paths?.code ?? source,
1322
1741
  };
1323
- if (result)
1324
- Object.assign(result, { code: paths.code, changed: true, rules });
1325
- else
1326
- results.push(host);
1327
- const retainedJsx = !known.has(file) &&
1328
- /\.[jt]sx$/.test(file) &&
1329
- (source.includes('.tsx') || source.includes('.jsx') || source.includes('\\'));
1330
- const retainedServer = !isTsrx(file) && (source.includes('react-dom/server') || source.includes('\\'));
1742
+ if (paths) {
1743
+ if (result)
1744
+ Object.assign(result, { code: paths.code, changed: true, rules });
1745
+ else
1746
+ results.push(host);
1747
+ }
1748
+ if (paths &&
1749
+ file === routesEntry &&
1750
+ originalReactEntry(file, '@react-router/dev/routes', bindingOptions(file))) {
1751
+ for (const { target, line } of registeredReactRoutes(file, source)) {
1752
+ const leaf = byFile.get(target);
1753
+ if (!renames.has(target) || !leaf || !hasTemplateExport(leaf, 'default'))
1754
+ continue;
1755
+ const note = {
1756
+ rule: 'react-compat',
1757
+ severity: 'warning',
1758
+ line,
1759
+ message: `The React Router registration in ${name} points to ${leaf.file}. The standard React Router renderer cannot render its migrated Octane default export. Keep a React route component that owns an Octane boundary or use an Octane router.`,
1760
+ };
1761
+ host.notes.push(note);
1762
+ if (!leaf.notes.some((existing) => existing.message === note.message))
1763
+ leaf.notes.push({ ...note, line: 1 });
1764
+ }
1765
+ }
1766
+ if (paths &&
1767
+ !edited.has(file) &&
1768
+ !isTsrx(file) &&
1769
+ (source.includes('react-dom/client') || source.includes('\\')) &&
1770
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject &&
1771
+ originalReactEntry(file, 'react-dom/client')) {
1772
+ for (const edge of reactClientComponents(file, source, (module) => module === 'react'
1773
+ ? originalReactEntry(file, module)
1774
+ : automaticReactJsx(file) && originalReactEntry(file, module))) {
1775
+ const explicit = edge.module.endsWith('.tsx');
1776
+ if (!explicit && !canResolveExtensionlessJsx(edge.module))
1777
+ continue;
1778
+ const original = path.resolve(path.dirname(file), edge.module);
1779
+ const match = explicit
1780
+ ? retainedJsxTarget(file, edge.module, edge.name)
1781
+ : renamed(file, edge.module);
1782
+ if (!match ||
1783
+ ('indirect' in match && match.indirect) ||
1784
+ (explicit ? match.file !== original : !isExtensionlessJsxTarget(match.file, original)) ||
1785
+ !automaticReactJsx(match.file) ||
1786
+ !originalReactEntry(match.file, 'react/jsx-runtime'))
1787
+ continue;
1788
+ const leaf = byFile.get(match.file);
1789
+ if (!leaf?.output.endsWith('.tsrx'))
1790
+ continue;
1791
+ const { intrinsics, wrappers } = originalReactExports(match.file);
1792
+ if ((!intrinsics.has(edge.name) && !wrappers.has(edge.name)) ||
1793
+ !hasTemplateExport(leaf, edge.name))
1794
+ continue;
1795
+ const note = {
1796
+ rule: 'react-compat',
1797
+ severity: 'error',
1798
+ line: edge.line,
1799
+ message: `The retained React DOM client root in ${name} renders ${leaf.file}. Migrate the root too or keep this component in React.`,
1800
+ };
1801
+ if (write)
1802
+ return blockedWrite(root, unchangedFile(name, source, note), compiler?.from);
1803
+ host.notes.push(note);
1804
+ leaf.notes.push({ ...note, line: 1 });
1805
+ }
1806
+ }
1807
+ const retainedServer = paths && !isTsrx(file) && (source.includes('react-dom/server') || source.includes('\\'));
1808
+ const retainedElement = paths &&
1809
+ !known.has(file) &&
1810
+ file.endsWith('.ts') &&
1811
+ ((source.includes('react') && source.includes('createElement')) || source.includes('\\'));
1331
1812
  if (!edited.has(file) &&
1332
- (retainedJsx || retainedServer) &&
1813
+ (retainedJsx || retainedServer || retainedElement) &&
1333
1814
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject) {
1334
1815
  const edges = [];
1335
1816
  if (retainedJsx && automaticReactJsx(file) && originalReactEntry(file, 'react/jsx-runtime'))
@@ -1340,37 +1821,102 @@ export async function runCodemod(paths, options = {}) {
1340
1821
  ? installedReact(file)
1341
1822
  : automaticReactJsx(file) && originalReactEntry(file, module)))
1342
1823
  edges.push({ ...edge, renderer: 'server render' });
1824
+ if (retainedElement && installedReact(file))
1825
+ for (const edge of retainedReactElementReturns(file, source))
1826
+ edges.push({ ...edge, renderer: 'createElement' });
1827
+ let installedLazy;
1343
1828
  for (const edge of edges) {
1344
- const match = renamed(file, edge.module);
1345
- if (!match ||
1346
- match.file !== path.resolve(path.dirname(file), edge.module) ||
1347
- !automaticReactJsx(match.file) ||
1348
- !originalReactEntry(match.file, 'react/jsx-runtime'))
1829
+ const factory = 'factory' in edge && edge.factory;
1830
+ const inferredServerPath = edge.renderer === 'server render' && !/\.[jt]sx$/.test(edge.module);
1831
+ if (inferredServerPath && !canResolveExtensionlessJsx(edge.module))
1832
+ continue;
1833
+ const original = path.resolve(path.dirname(file), edge.module);
1834
+ const direct = edge.renderer === 'createElement' ? null : renamed(file, edge.module);
1835
+ const proven = edge.renderer === 'createElement' ||
1836
+ (edge.renderer === 'JSX' &&
1837
+ !factory &&
1838
+ !edge.lazy &&
1839
+ (!direct || /\.js$/.test(edge.module)))
1840
+ ? retainedJsxTarget(file, edge.module, edge.name)
1841
+ : undefined;
1842
+ const match = proven ?? direct;
1843
+ if (!match || (edge.renderer === 'createElement' && proven?.indirect))
1844
+ continue;
1845
+ const exportName = proven?.name ?? edge.name;
1846
+ const extensionlessServer = inferredServerPath && isExtensionlessJsxTarget(match.file, original);
1847
+ const explicit = match.file === original && (edge.renderer !== 'JSX' || /\.[jt]sx$/.test(edge.module));
1848
+ if (!explicit &&
1849
+ !extensionlessServer &&
1850
+ !proven &&
1851
+ (factory ||
1852
+ edge.renderer !== 'JSX' ||
1853
+ !/^\.{1,2}\//.test(edge.module) ||
1854
+ /[!%?#\\]/.test(edge.module) ||
1855
+ config?.rootDirs ||
1856
+ config?.moduleSuffixes?.some(Boolean) ||
1857
+ !unambiguousJsxPath(match.file, original)))
1858
+ continue;
1859
+ if (!automaticReactJsx(match.file) || !originalReactEntry(match.file, 'react/jsx-runtime'))
1860
+ continue;
1861
+ if (edge.lazy && !(installedLazy ??= originalReactEntry(file, 'react')))
1349
1862
  continue;
1350
1863
  const leaf = byFile.get(match.file);
1351
1864
  if (!leaf?.output.endsWith('.tsrx'))
1352
1865
  continue;
1353
- let names = intrinsicExports.get(match.file);
1354
- if (!names) {
1355
- names = intrinsicReactExports(match.file, fs.readFileSync(match.file, 'utf8'));
1356
- intrinsicExports.set(match.file, names);
1866
+ if (factory) {
1867
+ let names = jsxFactories.get(match.file);
1868
+ if (!names) {
1869
+ names = migratedJsxFactories(match.file, fs.readFileSync(match.file, 'utf8'), leaf.code);
1870
+ jsxFactories.set(match.file, names);
1871
+ }
1872
+ if (!names.has(edge.name))
1873
+ continue;
1874
+ }
1875
+ else {
1876
+ const originalExports = originalReactExports(match.file);
1877
+ if (edge.lazy && originalExports.mayExportThen)
1878
+ continue;
1879
+ if (!originalExports.intrinsics.has(exportName)) {
1880
+ const extensionlessJsx = edge.renderer === 'JSX' &&
1881
+ !!direct &&
1882
+ canResolveExtensionlessJsx(edge.module) &&
1883
+ isExtensionlessJsxTarget(match.file, original);
1884
+ const splitIntrinsicDefault = edge.renderer === 'createElement' &&
1885
+ exportName === 'default' &&
1886
+ originalExports.splitIntrinsicDefault;
1887
+ if ((!explicit &&
1888
+ !extensionlessServer &&
1889
+ !extensionlessJsx &&
1890
+ edge.renderer !== 'createElement') ||
1891
+ edge.lazy ||
1892
+ (!splitIntrinsicDefault && !originalExports.wrappers.has(edge.name)) ||
1893
+ !hasTemplateExport(leaf, edge.name))
1894
+ continue;
1895
+ }
1357
1896
  }
1358
- if (!names.has(edge.name))
1359
- continue;
1360
1897
  const note = {
1361
1898
  rule: 'react-compat',
1362
1899
  severity: 'warning',
1363
1900
  line: edge.line,
1364
- message: edge.renderer === 'JSX'
1365
- ? `The retained React JSX in ${name} renders ${leaf.file} directly. With standard package resolution, migrate the caller too or keep this component in React.`
1366
- : `The retained React server render in ${name} imports ${leaf.file} directly. With standard package resolution, migrate the server entry too or keep this component in React.`,
1901
+ message: factory
1902
+ ? `The retained React JSX in ${name} uses ${leaf.file}'s ${edge.name} as a JSX child. With standard package resolution, migrate the caller too or keep this factory in React.`
1903
+ : edge.renderer === 'JSX'
1904
+ ? `The retained React JSX in ${name} renders ${leaf.file} ${edge.lazy ? 'through React.lazy' : proven?.indirect ? 'through a re-export' : 'directly'}. With standard package resolution, migrate the caller too or keep this component in React.`
1905
+ : edge.renderer === 'createElement'
1906
+ ? `The retained React createElement call in ${name} uses ${leaf.file}. With standard package resolution, migrate the caller too or keep this component in React.`
1907
+ : `The retained React server render in ${name} imports ${leaf.file} directly. With standard package resolution, migrate the server entry too or keep this component in React.`,
1367
1908
  };
1368
1909
  host.notes.push(note);
1369
1910
  leaf.notes.push({ ...note, line: 1 });
1370
1911
  }
1371
1912
  }
1372
- if (!edited.has(file) && hasServerImport && originalServerHost()) {
1373
- for (const edge of hostedServerComponents(file, source)) {
1913
+ if (!paths) {
1914
+ if (host.notes.length && !result)
1915
+ results.push(host);
1916
+ continue;
1917
+ }
1918
+ if (!edited.has(file) && hasServerImport && originalHost(serverBridge)) {
1919
+ for (const edge of hostedComponents(file, source, serverBridge)) {
1374
1920
  const match = edge.module.startsWith('.') && renamed(file, edge.module);
1375
1921
  if (!match)
1376
1922
  continue;
@@ -1401,11 +1947,9 @@ export async function runCodemod(paths, options = {}) {
1401
1947
  }
1402
1948
  }
1403
1949
  }
1404
- const pages = planEntryPages(root, paths.map((entry) => path.resolve(entry)), renames, checkLinkedRename);
1405
- for (const [file, issuer] of linkedConflicts) {
1406
- const conflict = conflictFor(file, fs.readFileSync(file, 'utf8'), renames.get(file), 'would leave a reference in ' +
1407
- path.relative(root, issuer) +
1408
- ' pointing to its original name');
1950
+ const pages = await planEntryPages(root, paths.map((entry) => path.resolve(entry)), renames, checkLinkedRename);
1951
+ for (const [file, reason] of renameConflicts) {
1952
+ const conflict = conflictFor(file, fs.readFileSync(file, 'utf8'), renames.get(file), reason);
1409
1953
  if (write)
1410
1954
  return blockedWrite(root, conflict, compiler?.from);
1411
1955
  byFile.get(file)?.notes.push(...conflict.notes);
@@ -1523,7 +2067,12 @@ export async function runCodemod(paths, options = {}) {
1523
2067
  };
1524
2068
  }
1525
2069
  // Hash only previously shipped helpers. A locally edited file belongs to the application.
1526
- const PREVIOUS_INTL_HASHES = ['07ec8e00847ebc6f0bd5ffeb14bc064aa23df42d1d3db5102344c739f54dca98'];
2070
+ const PREVIOUS_INTL_HASHES = [
2071
+ '07ec8e00847ebc6f0bd5ffeb14bc064aa23df42d1d3db5102344c739f54dca98',
2072
+ '9cd8a44e85984cab413e73e63999156ac8508518c109cf53c26449c54a973043',
2073
+ 'b2c10462518bfabfd9aecc774696c8a594b456b4752b6e753cd6311f889fba0e',
2074
+ '37cdc7e5d0f17d4d0504bf4a948b724559c584650af441e000563f8ebe7e33e6',
2075
+ ];
1527
2076
  const PREVIOUS_SVG_HASHES = [
1528
2077
  '90bc12d849bbed4f1932e9e7ab5b939242237a4b8876d4c0f01e093a7d5b8c80',
1529
2078
  '9068d68b34a68b8dd4199764d16c174f1cf9cbf79172396b1f8960ddf5217916',
@@ -1535,6 +2084,7 @@ const PREVIOUS_SVG_HASHES = [
1535
2084
  '3becf859871f17914f6f0631e8db8058aa4932fd4a9817718b98eb247a902b24',
1536
2085
  '1dbf34eea75c07c21c8ab3814d54e58115e833aa140fc5f34b5f2cba91d018c3',
1537
2086
  'b53641cfbe77205a174179b4d0de60989b34cf4073690fc98536c22a68ee844a',
2087
+ 'febbdb7b04b5240afe5b417d134e52d963aa077780e54f5ef0582bc581f4dc70',
1538
2088
  ];
1539
2089
  function inspectAdapter(file, source, previous) {
1540
2090
  const stat = fs.lstatSync(file, { throwIfNoEntry: false });
@@ -1663,6 +2213,118 @@ function collect(entry, test = isSource) {
1663
2213
  function isTsrx(name) {
1664
2214
  return name.endsWith('.tsrx');
1665
2215
  }
2216
+ // React Router 7's file discovery does not consider .tsrx to be an entry extension.
2217
+ const REACT_ROUTER_ENTRY_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.mts'];
2218
+ function reactRouterEntries(root) {
2219
+ const pkg = readInstalled(root, '@react-router/dev');
2220
+ if (pkg?.manifest.name !== '@react-router/dev' ||
2221
+ !pkg.version.startsWith('7.') ||
2222
+ !record(pkg.manifest.exports)['./routes'])
2223
+ return;
2224
+ const findEntry = (dir, name) => REACT_ROUTER_ENTRY_EXTENSIONS.map((ext) => path.join(dir, name + ext)).find((file) => fs.existsSync(file));
2225
+ const config = findEntry(root, 'react-router.config');
2226
+ if (!config)
2227
+ return;
2228
+ let app = 'app';
2229
+ const source = ts.createSourceFile(config, fs.readFileSync(config, 'utf8'), ts.ScriptTarget.Latest);
2230
+ const exported = source.statements.find(ts.isExportAssignment);
2231
+ const value = exported && !exported.isExportEquals && skipWrappers(exported.expression);
2232
+ if (!value || !ts.isObjectLiteralExpression(value))
2233
+ return;
2234
+ let hasAppDirectory = false;
2235
+ for (const property of value.properties) {
2236
+ if (!property.name || (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name)))
2237
+ return;
2238
+ if (property.name.text === '__proto__' || property.name.text === 'presets')
2239
+ return;
2240
+ if (property.name.text !== 'appDirectory')
2241
+ continue;
2242
+ const directory = ts.isPropertyAssignment(property) && skipWrappers(property.initializer);
2243
+ if (hasAppDirectory || !directory || !ts.isStringLiteralLike(directory))
2244
+ return;
2245
+ app = directory.text || app;
2246
+ hasAppDirectory = true;
2247
+ }
2248
+ const dir = path.resolve(root, app);
2249
+ const relative = path.relative(root, dir);
2250
+ if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative))
2251
+ return;
2252
+ const rootEntry = findEntry(dir, 'root');
2253
+ const routesEntry = findEntry(dir, 'routes');
2254
+ if (rootEntry && routesEntry)
2255
+ return [rootEntry, routesEntry];
2256
+ }
2257
+ /** Direct registrations in the framework's exported routes array and its literal child groups. */
2258
+ function registeredReactRoutes(file, source) {
2259
+ const { sf, checker } = bind(file, source);
2260
+ const paths = [];
2261
+ const exported = sf.statements.find(ts.isExportAssignment);
2262
+ if (!exported || exported.isExportEquals)
2263
+ return paths;
2264
+ const dir = path.dirname(file);
2265
+ function visit(node) {
2266
+ const value = skipWrappers(node);
2267
+ if (ts.isArrayLiteralExpression(value)) {
2268
+ for (const element of value.elements) {
2269
+ if (!ts.isSpreadElement(element)) {
2270
+ visit(element);
2271
+ continue;
2272
+ }
2273
+ const group = skipWrappers(element.expression);
2274
+ if (!ts.isCallExpression(group) ||
2275
+ ts.isOptionalChain(group) ||
2276
+ !ts.isIdentifier(group.expression) ||
2277
+ group.arguments.length !== 2)
2278
+ continue;
2279
+ const helper = namedRuntimeImport(group.expression, checker);
2280
+ if (helper?.module !== '@react-router/dev/routes' || helper.name !== 'prefix')
2281
+ continue;
2282
+ const children = skipWrappers(group.arguments[1]);
2283
+ if (!ts.isSpreadElement(group.arguments[0]) && ts.isArrayLiteralExpression(children))
2284
+ visit(children);
2285
+ }
2286
+ return;
2287
+ }
2288
+ if (!ts.isCallExpression(value) ||
2289
+ ts.isOptionalChain(value) ||
2290
+ !ts.isIdentifier(value.expression))
2291
+ return;
2292
+ const callee = namedRuntimeImport(value.expression, checker);
2293
+ if (callee?.module !== '@react-router/dev/routes')
2294
+ return;
2295
+ const position = callee.name === 'route' ? 1 : callee.name === 'index' || callee.name === 'layout' ? 0 : -1;
2296
+ if (position < 0)
2297
+ return;
2298
+ const raw = value.arguments[position];
2299
+ if ((position === 1 && value.arguments[0] && ts.isSpreadElement(value.arguments[0])) ||
2300
+ (raw && ts.isSpreadElement(raw)))
2301
+ return;
2302
+ const literal = raw && skipWrappers(raw);
2303
+ if (literal &&
2304
+ ts.isStringLiteralLike(literal) &&
2305
+ !path.isAbsolute(literal.text) &&
2306
+ !/[!%?#\\]/.test(literal.text)) {
2307
+ paths.push({
2308
+ target: path.resolve(dir, literal.text),
2309
+ line: sf.getLineAndCharacterOfPosition(literal.getStart(sf)).line + 1,
2310
+ });
2311
+ }
2312
+ if (callee.name === 'index')
2313
+ return;
2314
+ const options = value.arguments[position + 1];
2315
+ if (!options)
2316
+ return;
2317
+ const argument = skipWrappers(options);
2318
+ const next = value.arguments[position + 2];
2319
+ const children = ts.isObjectLiteralExpression(argument) && next ? skipWrappers(next) : argument;
2320
+ if (ts.isArrayLiteralExpression(children))
2321
+ visit(children);
2322
+ }
2323
+ const routes = skipWrappers(exported.expression);
2324
+ if (ts.isArrayLiteralExpression(routes))
2325
+ visit(routes);
2326
+ return paths;
2327
+ }
1666
2328
  /** The compiler options of the tsconfig that governs `root`, or null. */
1667
2329
  function tsconfigOptions(root) {
1668
2330
  const file = ts.findConfigFile(root, ts.sys.fileExists);
@@ -1696,8 +2358,11 @@ function resolveModule(from, specifier, files) {
1696
2358
  return null;
1697
2359
  }
1698
2360
  function relativeTsImport(from, to) {
1699
- const specifier = path.relative(path.dirname(from), to).split(path.sep).join('/').slice(0, -3);
1700
- return specifier.startsWith('.') ? specifier : './' + specifier;
2361
+ return relativeImport(from, to.slice(0, -3));
2362
+ }
2363
+ function relativeImport(from, to) {
2364
+ const specifier = path.relative(path.dirname(from), to).split(path.sep).join('/');
2365
+ return specifier.startsWith('../') ? specifier : './' + specifier;
1701
2366
  }
1702
2367
  /** Only relative assets and unambiguous directory aliases have a local file to inspect. */
1703
2368
  function svgAsset(root, dir, specifier, config) {
@@ -1727,7 +2392,7 @@ function svgAsset(root, dir, specifier, config) {
1727
2392
  * Resolve against the files on disk before any rename, including modules
1728
2393
  * outside the selected paths that could win an extensionless lookup.
1729
2394
  */
1730
- function renamedImports(root, config, renames) {
2395
+ function renamedImports(root, config, renames, issuerOptions, linkedRename) {
1731
2396
  const options = {
1732
2397
  moduleResolution: ts.ModuleResolutionKind.Bundler,
1733
2398
  ...config,
@@ -1742,7 +2407,18 @@ function renamedImports(root, config, renames) {
1742
2407
  : null;
1743
2408
  return { start, end, directory };
1744
2409
  });
1745
- return (from, specifier, unmatched) => {
2410
+ const runtimeImports = new Map();
2411
+ function runtimeImport(from, specifier) {
2412
+ if (/\.d\.[cm]?ts$/.test(from))
2413
+ return false;
2414
+ let imports = runtimeImports.get(from);
2415
+ if (!imports && !isTsrx(from)) {
2416
+ imports = new Set(executableImports(from, fs.readFileSync(from, 'utf8'), !!issuerOptions(from)?.verbatimModuleSyntax));
2417
+ runtimeImports.set(from, imports);
2418
+ }
2419
+ return !imports || imports.has(specifier);
2420
+ }
2421
+ return (from, specifier, unmatched, separateRuntime, commonJs) => {
1746
2422
  const matches = specifier.startsWith('.')
1747
2423
  ? []
1748
2424
  : aliases.filter(({ start, end }) => end === undefined
@@ -1750,15 +2426,35 @@ function renamedImports(root, config, renames) {
1750
2426
  : specifier.startsWith(start) && specifier.endsWith(end));
1751
2427
  if (!renames.size || (!specifier.startsWith('.') && !matches.length))
1752
2428
  return null;
1753
- const resolved = ts.resolveModuleName(specifier, from, options, ts.sys, cache).resolvedModule;
2429
+ const resolved = ts.resolveModuleName(specifier, from, options, ts.sys, cache, undefined, commonJs ? ts.ModuleKind.CommonJS : undefined).resolvedModule;
1754
2430
  // TypeScript returns slash-delimited names, including on Windows.
1755
2431
  const file = resolved && path.normalize(resolved.resolvedFileName);
2432
+ const runtime = /^\.{1,2}\/.*\.jsx?$/.test(specifier)
2433
+ ? path.resolve(path.dirname(from), specifier)
2434
+ : null;
2435
+ if (file && runtime && file !== runtime) {
2436
+ const selectedRuntime = renames.has(runtime) ? runtime : linkedRename(runtime);
2437
+ if (selectedRuntime &&
2438
+ selectedRuntime !== file &&
2439
+ (commonJs?.() ?? runtimeImport(from, specifier))) {
2440
+ separateRuntime?.(selectedRuntime);
2441
+ return null;
2442
+ }
2443
+ }
1756
2444
  const target = file && renames.get(file);
1757
2445
  if (!target) {
1758
2446
  if (file)
1759
2447
  unmatched?.(file);
1760
2448
  return null;
1761
2449
  }
2450
+ if (runtime &&
2451
+ file.endsWith('.tsx') &&
2452
+ ts.sys.fileExists(runtime) &&
2453
+ (commonJs?.() ?? runtimeImport(from, specifier))) {
2454
+ // Preserve the runtime path and the TypeScript source it uses for types.
2455
+ separateRuntime?.(file);
2456
+ return null;
2457
+ }
1762
2458
  // Only a single directory alias preserves the specifier's suffix.
1763
2459
  // A fixed alias or fallback list may resolve elsewhere after a rename.
1764
2460
  const alias = matches.length === 1 ? matches[0] : null;
@@ -1775,12 +2471,31 @@ function renamedImports(root, config, renames) {
1775
2471
  };
1776
2472
  };
1777
2473
  }
1778
- function propsOf(file, importedRender, hostText, types) {
2474
+ /** TS can prefer a source file over a separate JS sibling or directory entry. */
2475
+ function hasModuleSibling(file) {
1779
2476
  const stem = file.slice(0, -path.extname(file).length);
1780
2477
  const dir = path.dirname(stem);
1781
2478
  const stems = path.basename(stem) === 'index' ? [stem, dir] : [stem, path.join(stem, 'index')];
1782
- if (stems.some((base) => ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts'].some((ext) => base + ext !== file && fs.existsSync(base + ext))) ||
1783
- fs.existsSync(path.join(path.basename(stem) === 'index' ? dir : stem, 'package.json')))
2479
+ return (stems.some((base) => ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts'].some((ext) => base + ext !== file && fs.existsSync(base + ext))) || fs.existsSync(path.join(path.basename(stem) === 'index' ? dir : stem, 'package.json')));
2480
+ }
2481
+ /** Accept only a direct JSX file or directory index without a competing entry. */
2482
+ function unambiguousJsxPath(file, original) {
2483
+ if (!/\.[jt]sx$/.test(file))
2484
+ return false;
2485
+ const stem = file.slice(0, -4);
2486
+ const index = stem === path.join(original, 'index');
2487
+ if (stem !== original && !index)
2488
+ return false;
2489
+ const exists = (name) => fs.lstatSync(name, { throwIfNoEntry: false });
2490
+ if (index ? !exists(original)?.isDirectory() : exists(original))
2491
+ return false;
2492
+ return (!hasModuleSibling(file) &&
2493
+ !exists(original + '.json') &&
2494
+ !exists(original + '.tsrx') &&
2495
+ (!index || (!exists(stem) && !exists(stem + '.json') && !exists(stem + '.tsrx'))));
2496
+ }
2497
+ function propsOf(file, importedRender, hostText, types) {
2498
+ if (hasModuleSibling(file))
1784
2499
  return () => false;
1785
2500
  const { sf, checker } = bind(file, fs.readFileSync(file, 'utf8'));
1786
2501
  const module = checker.getSymbolAtLocation(sf);
@@ -2004,8 +2719,7 @@ function catalogName(specifier) {
2004
2719
  return null;
2005
2720
  }
2006
2721
  /**
2007
- * The React package a specifier names when Octane has no binding for it, or
2008
- * null.
2722
+ * The React package a specifier names when the codemod keeps it on React, or null.
2009
2723
  * @param from the importing module
2010
2724
  */
2011
2725
  function unportedName(specifier, from) {
@@ -2146,25 +2860,158 @@ function rendersWithReact(name, from) {
2146
2860
  * Point `<script src>` in HTML entry pages at renamed modules.
2147
2861
  * @param targets the paths being migrated
2148
2862
  */
2149
- function planEntryPages(root, targets, renames, unmatched) {
2863
+ async function planEntryPages(root, targets, renames, unmatched) {
2150
2864
  const updated = new Map();
2151
- for (const page of findHtml(root, targets)) {
2152
- const html = fs.readFileSync(page, 'utf8');
2153
- const next = html.replace(/(<script\b[^>]*\bsrc=)(["'])([^"']+)\2/g, (match, open, quote, src) => {
2154
- // Vite serves `/` from the page's own directory, as it does `./`.
2155
- const file = path.join(path.dirname(page), src);
2156
- const renamed = renames.get(file);
2157
- if (!renamed) {
2865
+ const pages = renames.size ? findHtml(root, targets) : [];
2866
+ if (!pages.length)
2867
+ return updated;
2868
+ const { parse, html: { NS }, } = await import('parse5');
2869
+ function elements(source, scriptingEnabled) {
2870
+ const nodes = [
2871
+ parse(source, { sourceCodeLocationInfo: !scriptingEnabled, scriptingEnabled }),
2872
+ ];
2873
+ const result = [];
2874
+ for (const node of nodes) {
2875
+ if ('childNodes' in node)
2876
+ for (const child of node.childNodes)
2877
+ nodes.push(child);
2878
+ if (!scriptingEnabled && 'content' in node)
2879
+ nodes.push(node.content);
2880
+ if ('attrs' in node)
2881
+ result.push(node);
2882
+ }
2883
+ return result;
2884
+ }
2885
+ for (const page of pages) {
2886
+ const source = fs.readFileSync(page, 'utf8');
2887
+ let hasBase;
2888
+ const edits = [];
2889
+ // Vite loads scripts in templates and noscript.
2890
+ for (const script of elements(source, false)) {
2891
+ if (script.tagName !== 'script')
2892
+ continue;
2893
+ const src = script.sourceCodeLocation?.attrs?.src;
2894
+ if (!src)
2895
+ continue;
2896
+ const raw = source.slice(src.startOffset, src.endOffset);
2897
+ const quoted = /^src\s*=\s*(["'])([\s\S]*)\1$/i.exec(raw);
2898
+ if (!quoted)
2899
+ continue;
2900
+ const value = quoted[2];
2901
+ const pathname = value.split(/[?#]/, 1)[0];
2902
+ const extension = /\.[jt]sx?$/.exec(pathname);
2903
+ if (!extension)
2904
+ continue;
2905
+ if (pathname !== value) {
2906
+ const parsedPath = script.attrs
2907
+ .find(({ name, prefix }) => !prefix && name === 'src')
2908
+ ?.value.split(/[?#]/, 1)[0];
2909
+ if (!script.attrs.some(({ name, prefix, value }) => !prefix && name === 'type' && value === 'module') ||
2910
+ script.attrs.some(({ name, prefix }) => !prefix && name === 'vite-ignore') ||
2911
+ !/^\.{1,2}\//.test(pathname) ||
2912
+ /[\u0000-\u0020%\\]/.test(pathname) ||
2913
+ parsedPath !== pathname)
2914
+ continue;
2915
+ // Only an active document base changes resolution in the browser.
2916
+ hasBase ??=
2917
+ /<base\b/i.test(source) &&
2918
+ elements(source, true).some((node) => node.namespaceURI === NS.HTML &&
2919
+ node.tagName === 'base' &&
2920
+ node.attrs.some(({ name }) => name === 'href'));
2921
+ if (hasBase)
2922
+ continue;
2923
+ }
2924
+ const file = path.join(path.dirname(page), pathname);
2925
+ if (!renames.has(file)) {
2158
2926
  unmatched(file, page);
2159
- return match;
2927
+ continue;
2160
2928
  }
2161
- return open + quote + src.replace(/\.[jt]sx?$/, '.tsrx') + quote;
2162
- });
2163
- if (next !== html)
2929
+ const end = src.endOffset - 1 - (value.length - pathname.length);
2930
+ edits.push({ start: end - extension[0].length, end });
2931
+ }
2932
+ let next = source;
2933
+ for (const { start, end } of edits.sort((a, b) => b.start - a.start)) {
2934
+ next = next.slice(0, start) + '.tsrx' + next.slice(end);
2935
+ }
2936
+ if (next !== source)
2164
2937
  updated.set(page, next);
2165
2938
  }
2166
2939
  return updated;
2167
2940
  }
2941
+ /** A strict identity test observes the loader's main module without exposing it. */
2942
+ function comparesMainModule(node) {
2943
+ const test = node.parent;
2944
+ if (!ts.isBinaryExpression(test) ||
2945
+ (test.operatorToken.kind !== ts.SyntaxKind.EqualsEqualsEqualsToken &&
2946
+ test.operatorToken.kind !== ts.SyntaxKind.ExclamationEqualsEqualsToken))
2947
+ return false;
2948
+ const [main, module] = ts.isIdentifier(test.left)
2949
+ ? [test.right, test.left]
2950
+ : [test.left, test.right];
2951
+ return (ts.isIdentifier(module) &&
2952
+ module.text === 'module' &&
2953
+ ts.isPropertyAccessExpression(main) &&
2954
+ main.name.text === 'main' &&
2955
+ ts.isIdentifier(main.expression) &&
2956
+ main.expression.text === 'require');
2957
+ }
2958
+ function observesRequire(member) {
2959
+ const use = member.parent;
2960
+ if (member.name.text === 'main')
2961
+ return comparesMainModule(member);
2962
+ if (member.name.text === 'resolve')
2963
+ return ts.isCallExpression(use) && use.expression === member;
2964
+ if (member.name.text !== 'cache')
2965
+ return false;
2966
+ // Cache entries are mutable Module objects. A presence test or deleting the
2967
+ // map entry does not expose an object that can replace the wrapper's loader.
2968
+ const entry = ts.isElementAccessExpression(use) && use.expression === member ? use : member;
2969
+ const parent = entry.parent;
2970
+ return ((ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken) ||
2971
+ (ts.isIfStatement(parent) && parent.expression === entry) ||
2972
+ (entry !== member && ts.isDeleteExpression(parent)));
2973
+ }
2974
+ /** Positions of calls to the CommonJS wrapper's own `require`. */
2975
+ function commonJsRequires(file, code) {
2976
+ const calls = new Set();
2977
+ const format = ts.getImpliedNodeFormatForFile(file, undefined, ts.sys, {
2978
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
2979
+ });
2980
+ if (format !== ts.ModuleKind.CommonJS)
2981
+ return calls;
2982
+ const { sf, checker } = bind(file, code);
2983
+ const opaque = contains(sf, (node) => {
2984
+ if (ts.isWithStatement(node))
2985
+ return true;
2986
+ if (!ts.isIdentifier(node))
2987
+ return false;
2988
+ const parent = node.parent;
2989
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node)
2990
+ return false;
2991
+ // Dynamic scope and the wrapper's arguments can change the loader.
2992
+ if (node.text === 'eval' || node.text === 'arguments')
2993
+ return true;
2994
+ // Node's wrapper delegates to module.require. Allow ordinary exports assignments.
2995
+ if (node.text === 'module' &&
2996
+ !comparesMainModule(node) &&
2997
+ !(ts.isPropertyAccessExpression(parent) &&
2998
+ parent.expression === node &&
2999
+ parent.name.text === 'exports'))
3000
+ return true;
3001
+ if (node.text !== 'require' ||
3002
+ checker.resolveName(node.text, node, ts.SymbolFlags.Value, false)?.declarations?.length)
3003
+ return false;
3004
+ if (ts.isPropertyAccessExpression(parent))
3005
+ return !observesRequire(parent);
3006
+ if (!ts.isCallExpression(parent) || parent.expression !== node)
3007
+ return true;
3008
+ calls.add(node.end);
3009
+ return false;
3010
+ });
3011
+ if (opaque)
3012
+ calls.clear();
3013
+ return calls;
3014
+ }
2168
3015
  /**
2169
3016
  * Follow imports outside the migrated paths as well as exact path strings
2170
3017
  * in scripts and configs. Parse TSRX importers with their own grammar so
@@ -2227,9 +3074,30 @@ function rewriteModulePaths(code, file, root, renames, resolveRename, unmatched)
2227
3074
  }
2228
3075
  else {
2229
3076
  const sf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
3077
+ const mayRequire = file.endsWith('.js') && !ts.isExternalModule(sf);
3078
+ let requires;
2230
3079
  const visit = (node) => {
2231
3080
  if (ts.isStringLiteralLike(node)) {
2232
3081
  const p = node.parent;
3082
+ if (mayRequire &&
3083
+ ts.isCallExpression(p) &&
3084
+ p.arguments[0] === node &&
3085
+ p.arguments.length === 1 &&
3086
+ !p.questionDotToken &&
3087
+ ts.isIdentifier(p.expression) &&
3088
+ p.expression.text === 'require' &&
3089
+ /^\.{1,2}\/.*\.js$/.test(node.text)) {
3090
+ const callee = p.expression;
3091
+ let preservesRequire = false;
3092
+ resolveRename(file, node.text, () => {
3093
+ requires ??= commonJsRequires(file, code);
3094
+ preservesRequire = requires.has(callee.end);
3095
+ return preservesRequire;
3096
+ });
3097
+ // A split blocks the rename and keeps this call intact in preview.
3098
+ if (preservesRequire)
3099
+ return;
3100
+ }
2233
3101
  const moduleSource = ((ts.isImportDeclaration(p) || ts.isExportDeclaration(p)) &&
2234
3102
  p.moduleSpecifier === node) ||
2235
3103
  ts.isExternalModuleReference(p) ||