@octanejs/codemod 0.2.1 → 0.2.2

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, 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,7 @@ 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
+ let selectedRealpaths;
52
54
  const renames = new Map();
53
55
  const exports = new Map();
54
56
  const owners = new Map();
@@ -133,6 +135,17 @@ export async function runCodemod(paths, options = {}) {
133
135
  }
134
136
  renames.set(file, output);
135
137
  }
138
+ const routerEntries = renames.size ? reactRouterEntries(root) : undefined;
139
+ const protectedEntries = new Set(routerEntries?.map(outputKey));
140
+ for (const entry of renames.keys()) {
141
+ if (!protectedEntries.has(outputKey(entry)))
142
+ continue;
143
+ const conflict = conflictFor(entry, fs.readFileSync(entry, 'utf8'), renames.get(entry), 'is an implicit React Router entry that must keep its original extension');
144
+ if (write)
145
+ return blockedWrite(root, conflict);
146
+ conflicts.set(entry, conflict);
147
+ renames.delete(entry);
148
+ }
136
149
  // A colliding source remains in place, so its imports and export contracts
137
150
  // must not participate in the preview as if it had been migrated.
138
151
  for (const file of conflicts.keys())
@@ -151,11 +164,18 @@ export async function runCodemod(paths, options = {}) {
151
164
  }
152
165
  const contextsOf = contextIndex(exports, known);
153
166
  const contextPaths = Object.keys(config?.paths ?? {}).map((pattern) => pattern.split('*'));
154
- const renamed = renamedImports(root, config, renames);
167
+ const moduleKind = config?.module;
168
+ const esmContextProject = (moduleKind === ts.ModuleKind.ES2015 ||
169
+ moduleKind === ts.ModuleKind.ES2020 ||
170
+ moduleKind === ts.ModuleKind.ES2022 ||
171
+ moduleKind === ts.ModuleKind.ESNext) &&
172
+ !config?.moduleSuffixes &&
173
+ !config?.rootDirs;
174
+ const renamed = renamedImports(root, config, renames, bindingOptions, linkedRename);
155
175
  const foldNames = process.platform === 'darwin';
156
176
  const leafKey = (file) => {
157
177
  const name = path.basename(file);
158
- return foldNames ? name.toLowerCase() : name;
178
+ return foldNames ? name.normalize('NFC').toLowerCase() : name;
159
179
  };
160
180
  const sourceNames = new Set([...renames.keys()].map(leafKey));
161
181
  const sourceEntries = new Map([...renames.keys()].map((file) => [entryKey(file), file]));
@@ -214,7 +234,7 @@ export async function runCodemod(paths, options = {}) {
214
234
  }
215
235
  return inspect(destination, name, prop, ordinaryCaller, depth);
216
236
  }
217
- // resolveRename returns only an on-disk source that actually won import resolution.
237
+ // Index the exports of selected source modules by their planned output.
218
238
  const elementExports = new Map();
219
239
  const descriptorExports = new Map();
220
240
  for (const [from, to] of renames) {
@@ -229,10 +249,19 @@ export async function runCodemod(paths, options = {}) {
229
249
  const compiler = verify || strong ? await loadCompiler(root) : null;
230
250
  const packages = new Map();
231
251
  const missing = new Map();
232
- // `ReactCompat` hosts a component from a package with no port in a React
252
+ // `ReactCompat` hosts a component from a retained package import in a React
233
253
  // root, from 19.2 within the React 19 series it supports.
234
254
  const reactCompat = ['react', 'react-dom'].every((name) => /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''));
235
255
  const rootProject = ts.findConfigFile(root, ts.sys.fileExists);
256
+ const reactExports = new Map();
257
+ function originalReactExports(file) {
258
+ let exports = reactExports.get(file);
259
+ if (!exports) {
260
+ exports = directReactExports(file, fs.readFileSync(file, 'utf8'));
261
+ reactExports.set(file, exports);
262
+ }
263
+ return exports;
264
+ }
236
265
  function automaticReactJsx(file) {
237
266
  // A nested project can compile the same file with another JSX factory.
238
267
  return (config?.jsx === ts.JsxEmit.ReactJSX &&
@@ -482,8 +511,7 @@ export async function runCodemod(paths, options = {}) {
482
511
  adapterError = 'The project compiler cannot compile the React Intl adapter.';
483
512
  }
484
513
  }
485
- const specifier = path.relative(dir, adapter).split(path.sep).join('/');
486
- return specifier.startsWith('.') ? specifier : './' + specifier;
514
+ return relativeImport(file, adapter);
487
515
  };
488
516
  const helperDir = path.dirname(adapter);
489
517
  const storeBridge = path.join(helperDir, 'octane-store-context.tsrx');
@@ -516,8 +544,86 @@ export async function runCodemod(paths, options = {}) {
516
544
  }).changed;
517
545
  }
518
546
  const { inputFactory, changedJsxExport, helperFunction, localFile, exportsConstObject } = storeSources(root, config, unchangedStoreInput, (file) => renames.has(file));
547
+ function localReactTemplateComponent(from, module, name) {
548
+ if (!/^\.{1,2}\//.test(module) ||
549
+ /[!%?#\\]/.test(module) ||
550
+ !automaticReactJsx(from) ||
551
+ config?.rootDirs?.length ||
552
+ config?.moduleSuffixes?.some(Boolean))
553
+ return false;
554
+ const file = localFile(from, module, true);
555
+ const requested = path.resolve(path.dirname(from), module);
556
+ if (!file?.endsWith('.tsx') ||
557
+ (file !== requested &&
558
+ (file !== requested + '.tsx' || !unambiguousJsxPath(file, requested))) ||
559
+ known.has(file) ||
560
+ !automaticReactJsx(file))
561
+ return false;
562
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
563
+ if (!stat?.isFile() || stat.nlink !== 1)
564
+ return false;
565
+ selectedRealpaths ??= new Set(files.map((input) => fs.realpathSync.native(input)));
566
+ if (selectedRealpaths.has(fs.realpathSync.native(file)))
567
+ return false;
568
+ const exported = originalReactExports(file);
569
+ return ((exported.intrinsics.has(name) || exported.wrappers.has(name)) &&
570
+ originalReactEntry(file, 'react/jsx-runtime'));
571
+ }
572
+ let selectedInPlace;
573
+ function writesSelectedInput(file) {
574
+ // An in-place write through a symlink changes its physical target.
575
+ selectedInPlace ??= new Set([...known].filter((f) => !renames.has(f) && !conflicts.has(f)).map((f) => fs.realpathSync(f)));
576
+ return selectedInPlace.has(fs.realpathSync(file));
577
+ }
578
+ const noClasses = new Set();
579
+ const localClasses = new Map();
580
+ function localReactClass(from, module, name) {
581
+ if (/[!%?#\\]/.test(module))
582
+ return;
583
+ const file = localFile(from, module, true);
584
+ if (!file || !file.endsWith('.tsx') || conflicts.has(file))
585
+ return;
586
+ let classes = localClasses.get(file);
587
+ if (classes === undefined) {
588
+ const source = fs.readFileSync(file, 'utf8');
589
+ classes =
590
+ /\bclass\b/.test(source) && installedReact(file)
591
+ ? reactClassExports(file, source)
592
+ : noClasses;
593
+ localClasses.set(file, classes);
594
+ }
595
+ if (classes.has(name) &&
596
+ ts.findConfigFile(path.dirname(from), ts.sys.fileExists) === rootProject)
597
+ return renamed(from, module)?.file === file ? 'error' : 'warning';
598
+ }
599
+ const retainedContexts = new Map();
600
+ function localReactContext(from, module, name, member) {
601
+ if (/[!%?#\\]/.test(module) || catalogName(module) !== null || resolveRename(from, module))
602
+ return false;
603
+ const file = localFile(from, module, true);
604
+ if (!file || known.has(file))
605
+ return false;
606
+ let contexts = retainedContexts.get(file);
607
+ if (contexts === undefined) {
608
+ const source = fs.readFileSync(file, 'utf8');
609
+ contexts = new Map();
610
+ if (source.includes('createContext') || source.includes('\\')) {
611
+ const stat = fs.lstatSync(file);
612
+ if (stat.isFile() &&
613
+ stat.nlink === 1 &&
614
+ fs.realpathSync(file) ===
615
+ path.join((physicalRoot ??= fs.realpathSync(root)), path.relative(root, file)) &&
616
+ !writesSelectedInput(file) &&
617
+ installedReact(file))
618
+ contexts = retainedReactContextExports(file, source);
619
+ }
620
+ retainedContexts.set(file, contexts);
621
+ }
622
+ return ((member ? contexts.get(name) === true : contexts.has(name)) &&
623
+ ts.findConfigFile(path.dirname(from), ts.sys.fileExists) === rootProject);
624
+ }
519
625
  const localHints = new Map();
520
- function initializerResourceHint(from, module, name) {
626
+ function initializerResourceHint(from, module, name, retainedOnly = false) {
521
627
  const file = localFile(from, module);
522
628
  if (!file ||
523
629
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
@@ -534,7 +640,9 @@ export async function runCodemod(paths, options = {}) {
534
640
  }
535
641
  localHints.set(file, calls);
536
642
  }
537
- return calls.get(name);
643
+ const hint = calls.get(name);
644
+ if (hint && (!retainedOnly || (fs.statSync(file).nlink === 1 && !writesSelectedInput(file))))
645
+ return hint;
538
646
  }
539
647
  const localHooks = new Map();
540
648
  const intlHookPackages = new Map();
@@ -586,7 +694,6 @@ export async function runCodemod(paths, options = {}) {
586
694
  return false;
587
695
  }
588
696
  }
589
- let selectedInPlace;
590
697
  function localReactHook(from, module, name, nativeOnly) {
591
698
  if (catalogName(module) !== null ||
592
699
  resolveRename(from, module) ||
@@ -594,11 +701,13 @@ export async function runCodemod(paths, options = {}) {
594
701
  ts.findConfigFile(path.dirname(from), ts.sys.fileExists) !== rootProject)
595
702
  return;
596
703
  const file = localFile(from, module);
704
+ const jsSpecifier = module.endsWith('.js') && (module.startsWith('./') || module.startsWith('../'));
597
705
  if (!file ||
706
+ (jsSpecifier && path.resolve(path.dirname(from), module.slice(0, -3) + '.ts') !== file) ||
598
707
  known.has(file) ||
599
708
  path.basename(file) === 'index.ts' ||
600
709
  fs.existsSync(file.slice(0, -3) + '.tsrx') ||
601
- (path.extname(module) && !module.endsWith('.ts')) ||
710
+ (path.extname(module) && !module.endsWith('.ts') && !jsSpecifier) ||
602
711
  fs.realpathSync(file) !== path.join(fs.realpathSync(root), path.relative(root, file)) ||
603
712
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
604
713
  return;
@@ -613,11 +722,15 @@ export async function runCodemod(paths, options = {}) {
613
722
  originalModule(file, 'react') &&
614
723
  readInstalled(path.dirname(file), 'react')?.manifest.name === 'react';
615
724
  const intl = (source.includes('useIntl') || escaped) && originalIntlHook(file);
616
- if (react || intl) {
725
+ const store = planStoreHook && /\buse[A-Z]|\\u/.test(source);
726
+ if (react || intl || store) {
617
727
  const existing = program?.getSourceFile(file);
618
728
  const bound = existing && program
619
729
  ? { sf: existing, checker: program.getTypeChecker() }
620
730
  : bind(file, source);
731
+ if (planStoreHook && store)
732
+ hooks.retainedStores = directRendererCalls(bound.sf, bound.checker, (specifier, exported) => !!unportedName(specifier, file) &&
733
+ planStoreHook(specifier, exported, file)?.requiresReact() === true);
621
734
  if (react)
622
735
  hooks.direct = directRendererCalls(bound.sf, bound.checker, 'react', (name) => name === 'useCallback' ||
623
736
  name === 'useContext' ||
@@ -629,15 +742,18 @@ export async function runCodemod(paths, options = {}) {
629
742
  }
630
743
  localHooks.set(file, hooks);
631
744
  }
632
- const hook = hooks.direct.get(name);
633
- if ((!hook && !hooks.privateContexts.has(name)) || fs.statSync(file).nlink > 1)
745
+ // Keep TS substitution advisory. A loader may select a different executable.
746
+ const hook = jsSpecifier ? undefined : hooks.direct.get(name);
747
+ const retainedStore = !jsSpecifier && hooks.retainedStores?.has(name) && automaticReactJsx(from);
748
+ if ((!hook && !retainedStore && !hooks.privateContexts.has(name)) ||
749
+ fs.statSync(file).nlink > 1)
634
750
  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)))
751
+ if (writesSelectedInput(file))
638
752
  return;
639
753
  if (!hook)
640
- return { privateContext: true };
754
+ return retainedStore
755
+ ? { retainedStore: true }
756
+ : { privateContext: true };
641
757
  if (nativeOnly &&
642
758
  compiler &&
643
759
  hook === 'useSyncExternalStore' &&
@@ -662,12 +778,11 @@ export async function runCodemod(paths, options = {}) {
662
778
  return;
663
779
  return bind(leaf, fs.readFileSync(leaf, 'utf8'));
664
780
  });
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)) {
781
+ // The hook needs the same client and server compiler as its caller.
782
+ const output = file.slice(0, -3) + '.octane.tsrx';
783
+ if (code && !checkHelper(output, code)) {
669
784
  generatedHelpers.set(output, code);
670
- return { from: relativeTsImport(from, output) };
785
+ return { from: relativeImport(from, output) };
671
786
  }
672
787
  }
673
788
  return hook;
@@ -816,9 +931,7 @@ export async function runCodemod(paths, options = {}) {
816
931
  const isContext = (specifier, name, local) => {
817
932
  if (!specifier.startsWith('.')) {
818
933
  if (!contextPaths.length ||
819
- config?.module !== ts.ModuleKind.ESNext ||
820
- config.moduleSuffixes ||
821
- config.rootDirs ||
934
+ !esmContextProject ||
822
935
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
823
936
  !contextPaths.some(([start, end]) => end === undefined
824
937
  ? specifier === start
@@ -837,9 +950,7 @@ export async function runCodemod(paths, options = {}) {
837
950
  if (target)
838
951
  return contextsOf(target.file).has(name);
839
952
  if (!name.endsWith('Context') ||
840
- config?.module !== ts.ModuleKind.ESNext ||
841
- config.moduleSuffixes ||
842
- config.rootDirs ||
953
+ !esmContextProject ||
843
954
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
844
955
  return null;
845
956
  const source = localFile(file, specifier, true);
@@ -870,7 +981,7 @@ export async function runCodemod(paths, options = {}) {
870
981
  : (module, name, safeUses) => {
871
982
  if (!unportedName(module, file))
872
983
  return null;
873
- const plan = planStoreHook(module, name, file);
984
+ const plan = planStoreHook(module, name, file)?.plan;
874
985
  if (!plan ||
875
986
  !safeUses((source, name, selection) => {
876
987
  if (selection)
@@ -915,6 +1026,7 @@ export async function runCodemod(paths, options = {}) {
915
1026
  .replace(/\.ts$/, '');
916
1027
  return { from: relative.startsWith('.') ? relative : './' + relative, name: plan.name };
917
1028
  };
1029
+ let originalSvgServer;
918
1030
  const svgAdapter = options.svgPaths && renames.has(file)
919
1031
  ? (specifier, color) => pathSvgAdapter(file, specifier, svgErrors, color)
920
1032
  : undefined;
@@ -930,15 +1042,68 @@ export async function runCodemod(paths, options = {}) {
930
1042
  reactIntlAdapter: intl,
931
1043
  forwardedText: (module, name, prop, ordinaryCaller, through) => forwardedProp(file, module, name, prop, through ? 'forwarded-text' : 'text', ordinaryCaller),
932
1044
  resolveStoreHook,
1045
+ retainedRegistry: files.length === 1 && /\.tsx?$/.test(file) && esmContextProject
1046
+ ? (specifier) => {
1047
+ if (!specifier.startsWith('./') && !specifier.startsWith('../'))
1048
+ return;
1049
+ const registry = localFile(file, specifier, true);
1050
+ if (!registry || known.has(registry))
1051
+ return;
1052
+ const request = path.resolve(path.dirname(file), specifier);
1053
+ if (registry !== request && registry !== request + path.extname(registry))
1054
+ return;
1055
+ if (ts.findConfigFile(path.dirname(registry), ts.sys.fileExists) === rootProject)
1056
+ return program?.getSourceFile(registry);
1057
+ }
1058
+ : undefined,
933
1059
  get originalReact() {
934
1060
  return installedReact(file);
935
1061
  },
1062
+ retainedReactBridgeComponent: (bridge, module, name) => {
1063
+ if (!reactCompat ||
1064
+ !module.startsWith('.') ||
1065
+ !module.endsWith('.tsx') ||
1066
+ bindingOptions(file)?.rootDirs?.length ||
1067
+ bindingOptions(file)?.moduleSuffixes?.some(Boolean) ||
1068
+ resolveRename(file, module) ||
1069
+ !originalOctaneBridge(file, bridge) ||
1070
+ !originalReactEntry(file, 'react', bindingOptions(file)))
1071
+ return false;
1072
+ const owner = localFile(file, module, true);
1073
+ if (!owner?.endsWith('.tsx') || owner !== path.resolve(path.dirname(file), module))
1074
+ return false;
1075
+ const stat = fs.lstatSync(owner, { throwIfNoEntry: false });
1076
+ if (!stat?.isFile() ||
1077
+ stat.nlink !== 1 ||
1078
+ known.has(owner) ||
1079
+ !automaticReactJsx(owner) ||
1080
+ !originalReactEntry(owner, 'react/jsx-runtime'))
1081
+ return false;
1082
+ // An alternate spelling or parent symlink can reach a selected source.
1083
+ selectedRealpaths ??= new Set(files.map((file) => fs.realpathSync.native(file)));
1084
+ if (selectedRealpaths.has(fs.realpathSync.native(owner)))
1085
+ return false;
1086
+ const source = fs.readFileSync(owner, 'utf8');
1087
+ return (/^\s*\/\*\*\s*@jsxImportSource\s+react\s*\*\//.test(source) &&
1088
+ directReactExports(owner, source).intrinsics.has(name));
1089
+ },
1090
+ originalReactServerEntry: (module) => originalReactEntry(file, module, bindingOptions(file)) &&
1091
+ originalOctaneBridge(file, 'octane/server'),
936
1092
  initializerResourceHint: renames.has(file)
937
- ? (module, name) => initializerResourceHint(file, module, name)
1093
+ ? (module, name, retainedOnly) => initializerResourceHint(file, module, name, retainedOnly)
938
1094
  : undefined,
939
1095
  localReactHook: renames.has(file)
940
1096
  ? (module, name, nativeOnly) => localReactHook(file, module, name, nativeOnly)
941
1097
  : undefined,
1098
+ localReactTemplateComponent: renames.has(file)
1099
+ ? (module, name) => localReactTemplateComponent(file, module, name)
1100
+ : undefined,
1101
+ localReactClass: renames.has(file)
1102
+ ? (module, name) => localReactClass(file, module, name)
1103
+ : undefined,
1104
+ localReactContext: renames.has(file)
1105
+ ? (module, name, member) => localReactContext(file, module, name, member)
1106
+ : undefined,
942
1107
  localReactRootComponent: renames.has(file)
943
1108
  ? (module, name) => {
944
1109
  const hook = localReactHook(file, module, name, false);
@@ -962,9 +1127,19 @@ export async function runCodemod(paths, options = {}) {
962
1127
  isContext,
963
1128
  elementChild: !elementExports.size
964
1129
  ? undefined
965
- : (binding) => typeof binding === 'number'
966
- ? (exports.get(file)?.elementChildren?.some((x) => x.start === binding) ?? false)
967
- : matchesExport(elementExports, binding),
1130
+ : (binding) => {
1131
+ if (typeof binding === 'number')
1132
+ return (exports.get(file)?.elementChildren?.some((x) => x.start === binding) ?? false);
1133
+ if (binding.module.startsWith('.'))
1134
+ return matchesExport(elementExports, binding);
1135
+ if (ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
1136
+ return false;
1137
+ const match = renamed(file, binding.module);
1138
+ const output = match && renames.get(match.file);
1139
+ return output && elementExports.get(output)?.has(binding.imported)
1140
+ ? 'review-alias'
1141
+ : false;
1142
+ },
968
1143
  descriptorChild: descriptorExports.size
969
1144
  ? (binding) => matchesExport(descriptorExports, binding)
970
1145
  : undefined,
@@ -1005,6 +1180,12 @@ export async function runCodemod(paths, options = {}) {
1005
1180
  return real.endsWith('.module.css') ? real : undefined;
1006
1181
  },
1007
1182
  pathSvgAdapter: svgAdapter,
1183
+ get originalSvgServer() {
1184
+ return (originalSvgServer ??=
1185
+ !!svgAdapter &&
1186
+ originalOctaneRuntime(file, 'octane/server', bindingOptions(file)) &&
1187
+ originalOctaneRuntime(svgHelper, 'octane', bindingOptions(svgHelper)));
1188
+ },
1008
1189
  fixedColorSvgAdapter: svgAdapter,
1009
1190
  reactStoreComponent: (specifier) => {
1010
1191
  if (!reactStoreComponents.has(specifier))
@@ -1032,11 +1213,16 @@ export async function runCodemod(paths, options = {}) {
1032
1213
  const result = transform();
1033
1214
  if (result.exports.storeHookComponents)
1034
1215
  storeHookComponents.set(file, result.exports.storeHookComponents);
1035
- const blockedTransform = result.notes.find((note) => note.rule === MAP_PARAMETER_WRITE ||
1216
+ const blockedTransform = result.notes.find((note) => note.rule === BUFFERED_SSR_OPTIONS ||
1217
+ note.rule === BUFFERED_SSR_REACT_COMPONENT ||
1218
+ note.rule === MAP_PARAMETER_WRITE ||
1036
1219
  note.rule === MAP_PARAMETER_TDZ ||
1037
1220
  note.rule === MAP_CALLBACK_SCOPE ||
1038
1221
  note.rule === CONTEXT_ALIAS ||
1039
- note.rule === CONTEXT_PROVIDER_GETTER);
1222
+ note.rule === CONTEXT_PROVIDER_GETTER ||
1223
+ note.rule === INTL_PROVIDER_DEFAULTS ||
1224
+ note.rule === ELEMENT_CHILD_ALIAS ||
1225
+ note.rule === REACT_TYPE_PROJECTION);
1040
1226
  if (write && blockedTransform)
1041
1227
  return blockedWrite(root, unchangedFile(path.relative(root, file), source, blockedTransform), compiler?.from);
1042
1228
  for (const message of [...storeErrors, ...svgErrors]) {
@@ -1133,9 +1319,9 @@ export async function runCodemod(paths, options = {}) {
1133
1319
  module?.packageId?.name === 'octane' &&
1134
1320
  fs.realpathSync(module.resolvedFileName).startsWith(fs.realpathSync(installed.dir) + path.sep));
1135
1321
  }
1136
- function originalOctaneRuntime(file, specifier) {
1322
+ function originalOctaneRuntime(file, specifier, options = config) {
1137
1323
  const installed = readInstalled(path.dirname(file), 'octane');
1138
- const module = originalModule(file, specifier);
1324
+ const module = originalModule(file, specifier, options);
1139
1325
  const adapterRuntime = readInstalled(helperDir, 'octane');
1140
1326
  if (installed?.manifest.name !== 'octane' ||
1141
1327
  module?.packageId?.name !== 'octane' ||
@@ -1166,9 +1352,9 @@ export async function runCodemod(paths, options = {}) {
1166
1352
  : `If the migrated ${component}'s store hook reads context, this standalone Octane root needs NativeStoreProvider with its original store context and value.`,
1167
1353
  };
1168
1354
  }
1169
- function originalReactEntry(file, name) {
1170
- const packageRoot = name === 'react/jsx-runtime' ? 'react' : 'react-dom';
1171
- const types = originalModule(file, name)?.packageId?.name;
1355
+ function originalReactEntry(file, name, options = config) {
1356
+ const packageRoot = packageName(name);
1357
+ const types = originalModule(file, name, options)?.packageId?.name;
1172
1358
  if (types !== packageRoot && types !== `@types/${packageRoot}`)
1173
1359
  return false;
1174
1360
  const installed = readInstalled(path.dirname(file), packageRoot);
@@ -1183,14 +1369,160 @@ export async function runCodemod(paths, options = {}) {
1183
1369
  }
1184
1370
  }
1185
1371
  const reverseIslands = new Map();
1186
- const intrinsicExports = new Map();
1187
- const linkedConflicts = new Map();
1372
+ const templateExports = new Map();
1373
+ function hasTemplateExport(file, name) {
1374
+ let names = templateExports.get(file.output);
1375
+ if (!names) {
1376
+ names = new Set();
1377
+ const { program, errors } = parseSync(file.output, file.code);
1378
+ if (program && !errors.length) {
1379
+ let defaultLocal;
1380
+ const templateLocals = new Set();
1381
+ const isTemplateBody = (body) => isRecord(body) && body.type === 'JSXCodeBlock';
1382
+ // The TSRX parser does not expose the type-only flag on local export lists.
1383
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.JSX, file.code);
1384
+ for (const statement of program.body) {
1385
+ const defaultExport = statement.type === 'ExportDefaultDeclaration';
1386
+ let fn = defaultExport || statement.type === 'ExportNamedDeclaration'
1387
+ ? statement.declaration
1388
+ : statement;
1389
+ if (defaultExport) {
1390
+ while (fn?.type === 'ParenthesizedExpression')
1391
+ fn = fn.expression;
1392
+ if (fn?.type === 'Identifier')
1393
+ defaultLocal = fn.name;
1394
+ }
1395
+ else if (statement.type === 'ExportNamedDeclaration' &&
1396
+ !statement.source &&
1397
+ statement.specifiers.length) {
1398
+ scanner.setTextPos(statement.start);
1399
+ scanner.scan();
1400
+ const typeOnly = scanner.scan() === ts.SyntaxKind.TypeKeyword;
1401
+ for (const specifier of statement.specifiers) {
1402
+ if (!typeOnly &&
1403
+ (specifier.exported.type === 'Identifier'
1404
+ ? specifier.exported.name === 'default'
1405
+ : specifier.exported.value === 'default') &&
1406
+ specifier.local.type === 'Identifier' &&
1407
+ specifier.start === specifier.local.start)
1408
+ defaultLocal = specifier.local.name;
1409
+ }
1410
+ }
1411
+ if (fn?.type === 'FunctionDeclaration' && isTemplateBody(fn.body)) {
1412
+ if (defaultExport)
1413
+ names.add('default');
1414
+ else if (fn.id)
1415
+ names.add(fn.id.name);
1416
+ }
1417
+ else if (defaultExport &&
1418
+ fn?.type === 'ArrowFunctionExpression' &&
1419
+ isTemplateBody(fn.body)) {
1420
+ names.add('default');
1421
+ }
1422
+ else if (fn?.type === 'VariableDeclaration' && fn.kind === 'const') {
1423
+ for (const declaration of fn.declarations) {
1424
+ if (declaration.id.type === 'Identifier' &&
1425
+ declaration.init?.type === 'ArrowFunctionExpression' &&
1426
+ isTemplateBody(declaration.init.body))
1427
+ templateLocals.add(declaration.id.name);
1428
+ }
1429
+ }
1430
+ }
1431
+ if (defaultLocal !== undefined &&
1432
+ (names.has(defaultLocal) || templateLocals.has(defaultLocal)))
1433
+ names.add('default');
1434
+ }
1435
+ templateExports.set(file.output, names);
1436
+ }
1437
+ return names.has(name);
1438
+ }
1439
+ const jsxFactories = new Map();
1440
+ const renamedJsx = [...renames.keys()].some((file) => file.endsWith('.tsx'));
1441
+ const namedReexports = new Map();
1442
+ const isPlainFile = (file) => {
1443
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
1444
+ return (!!stat?.isFile() &&
1445
+ stat.nlink === 1 &&
1446
+ fs.realpathSync(file) ===
1447
+ path.join((physicalRoot ??= fs.realpathSync(root)), path.relative(root, file)));
1448
+ };
1449
+ function retainedJsxTarget(from, specifier, name) {
1450
+ if (!/^\.{1,2}\//.test(specifier) ||
1451
+ /[!%?#\\]/.test(specifier) ||
1452
+ config?.rootDirs ||
1453
+ config?.moduleSuffixes?.some(Boolean))
1454
+ return;
1455
+ const direct = (issuer, spec) => {
1456
+ if (!/^\.{1,2}\//.test(spec) || /[!%?#\\]/.test(spec))
1457
+ return;
1458
+ const original = path.resolve(path.dirname(issuer), spec);
1459
+ const resolved = renamed(issuer, spec);
1460
+ if (!resolved?.file.endsWith('.tsx') || !isPlainFile(resolved.file))
1461
+ return;
1462
+ if (resolved.file === original && spec.endsWith('.tsx'))
1463
+ return resolved.file;
1464
+ if (spec.endsWith('.js') && resolved.file === original.slice(0, -3) + '.tsx') {
1465
+ if (!fs.lstatSync(original, { throwIfNoEntry: false }) && !hasModuleSibling(resolved.file))
1466
+ return resolved.file;
1467
+ }
1468
+ else if (unambiguousJsxPath(resolved.file, original))
1469
+ return resolved.file;
1470
+ };
1471
+ const leaf = direct(from, specifier);
1472
+ if (leaf)
1473
+ return { file: leaf, name, indirect: false };
1474
+ const barrel = localFile(from, specifier);
1475
+ const original = path.resolve(path.dirname(from), specifier);
1476
+ const substituted = specifier.endsWith('.js')
1477
+ ? original.slice(0, -3) + '.ts'
1478
+ : original + '.ts';
1479
+ if (!barrel ||
1480
+ !(barrel === original || (barrel === substituted && !hasModuleSibling(barrel))) ||
1481
+ !isPlainFile(barrel) ||
1482
+ ts.findConfigFile(path.dirname(barrel), ts.sys.fileExists) !== rootProject)
1483
+ return;
1484
+ let exports = namedReexports.get(barrel);
1485
+ if (!exports) {
1486
+ exports = new Map();
1487
+ const { statements } = ts.createSourceFile(barrel, fs.readFileSync(barrel, 'utf8'), ts.ScriptTarget.Latest);
1488
+ for (const statement of statements) {
1489
+ if (!ts.isExportDeclaration(statement) ||
1490
+ statement.isTypeOnly ||
1491
+ statement.attributes ||
1492
+ !statement.moduleSpecifier ||
1493
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
1494
+ !statement.exportClause ||
1495
+ !ts.isNamedExports(statement.exportClause))
1496
+ continue;
1497
+ for (const binding of statement.exportClause.elements) {
1498
+ if (!binding.isTypeOnly)
1499
+ exports.set(binding.name.text, {
1500
+ module: statement.moduleSpecifier.text,
1501
+ name: (binding.propertyName ?? binding.name).text,
1502
+ });
1503
+ }
1504
+ }
1505
+ namedReexports.set(barrel, exports);
1506
+ }
1507
+ const exported = exports.get(name);
1508
+ const target = exported && direct(barrel, exported.module);
1509
+ if (target)
1510
+ return { file: target, name: exported.name, indirect: true };
1511
+ }
1512
+ const renameConflicts = new Map();
1188
1513
  function checkLinkedRename(file, issuer) {
1189
1514
  const selected = linkedRename(file);
1190
- if (selected && !linkedConflicts.has(selected))
1191
- linkedConflicts.set(selected, issuer);
1515
+ if (selected && !renameConflicts.has(selected)) {
1516
+ renameConflicts.set(selected, `would leave a reference in ${path.relative(root, issuer)} pointing to its original name`);
1517
+ }
1192
1518
  }
1193
- const scanRename = (from, specifier) => renamed(from, specifier, (winner) => checkLinkedRename(winner, from))?.specifier ?? null;
1519
+ const scanRename = (from, specifier, commonJs) => renamed(from, specifier, commonJs ? undefined : (winner) => checkLinkedRename(winner, from), (file) => {
1520
+ if (!renameConflicts.has(file)) {
1521
+ renameConflicts.set(file, file.endsWith('.tsx')
1522
+ ? `supplies types for ${JSON.stringify(specifier)} in ${path.relative(root, from)}, where that JavaScript path exists on disk`
1523
+ : `is the JavaScript path for ${JSON.stringify(specifier)} in ${path.relative(root, from)}, where TypeScript resolves to a different file`);
1524
+ }
1525
+ }, commonJs)?.specifier ?? null;
1194
1526
  function protectIslandModule(issuer, specifier, owner) {
1195
1527
  const file = ts.resolveModuleName(specifier, issuer, { moduleResolution: ts.ModuleResolutionKind.Bundler, ...bindingOptions(issuer) }, ts.sys).resolvedModule?.resolvedFileName;
1196
1528
  if (!file || /\.d\.[cm]?ts$/.test(file) || !SOURCE.test(file))
@@ -1225,6 +1557,7 @@ export async function runCodemod(paths, options = {}) {
1225
1557
  for (const module of executableImports(file, fs.readFileSync(file, 'utf8'), !!bindingOptions(file)?.verbatimModuleSyntax))
1226
1558
  protectIslandModule(file, module, owner);
1227
1559
  }
1560
+ const routesEntry = routerEntries?.[1];
1228
1561
  for (const file of edited.size || renames.size
1229
1562
  ? new Set([...collect(root, (name) => SOURCE.test(name) || isTsrx(name)), ...files])
1230
1563
  : []) {
@@ -1239,19 +1572,19 @@ export async function runCodemod(paths, options = {}) {
1239
1572
  continue;
1240
1573
  const result = byFile.get(file);
1241
1574
  const selected = renames.has(file);
1242
- const specifier = 'octane/react/server';
1243
- const originalServerHost = () => automaticReactJsx(file) &&
1244
- originalOctaneBridge(file, specifier) &&
1575
+ const serverBridge = 'octane/react/server';
1576
+ const originalHost = (bridge) => automaticReactJsx(file) &&
1577
+ originalOctaneBridge(file, bridge) &&
1245
1578
  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) {
1579
+ const hasServerImport = source.includes(serverBridge);
1580
+ if (selected && result && (source.includes('octane/react') || source.includes('\\'))) {
1581
+ const imports = ts.preProcessFile(source).importedFiles;
1582
+ for (const bridge of [serverBridge, 'octane/react']) {
1583
+ if (!imports.some(({ fileName }) => fileName === bridge) || !originalHost(bridge))
1584
+ continue;
1585
+ const [edge] = hostedComponents(file, source, bridge, true);
1586
+ if (!edge)
1587
+ continue;
1255
1588
  const note = {
1256
1589
  rule: 'react-compat',
1257
1590
  severity: 'error',
@@ -1261,16 +1594,16 @@ export async function runCodemod(paths, options = {}) {
1261
1594
  if (write)
1262
1595
  return blockedWrite(root, unchangedFile(result.file, source, note), compiler?.from);
1263
1596
  result.notes.push(note);
1597
+ break;
1264
1598
  }
1265
1599
  }
1266
1600
  if (selected &&
1267
1601
  storeHookComponents.size &&
1268
1602
  result?.rules['server-render'] &&
1269
- result.rules['root-render'] &&
1270
1603
  automaticReactJsx(file) &&
1271
1604
  originalReactEntry(file, 'react-dom/server') &&
1272
1605
  originalOctaneBridge(file, 'octane/server')) {
1273
- for (const edge of reactServerComponents(file, source, (module) => module === 'react/jsx-runtime' && originalReactEntry(file, module), true)) {
1606
+ for (const edge of reactServerComponents(file, source, (module) => originalReactEntry(file, module), true)) {
1274
1607
  const leaf = renamed(file, edge.module)?.file;
1275
1608
  if (!leaf ||
1276
1609
  leaf !== path.resolve(path.dirname(file), edge.module) ||
@@ -1280,10 +1613,12 @@ export async function runCodemod(paths, options = {}) {
1280
1613
  }
1281
1614
  }
1282
1615
  const paths = rewriteModulePaths(selected ? source : (result?.code ?? source), file, root, renames, scanRename, selected ? undefined : checkLinkedRename);
1283
- if (!paths)
1616
+ const retainedJsx = (paths || renamedJsx) && !known.has(file) && /\.[jt]sx$/.test(file) && source.includes('<');
1617
+ if (!paths && !retainedJsx)
1284
1618
  continue;
1285
1619
  const storeNotes = result?.notes ?? [];
1286
- if (storeHookComponents.size &&
1620
+ if (paths &&
1621
+ storeHookComponents.size &&
1287
1622
  SOURCE.test(file) &&
1288
1623
  ((source.includes('octane') &&
1289
1624
  (source.includes('createRoot') ||
@@ -1307,29 +1642,50 @@ export async function runCodemod(paths, options = {}) {
1307
1642
  }
1308
1643
  if (selected)
1309
1644
  continue;
1310
- const rules = { ...result?.rules, 'module-paths': paths.count };
1645
+ const rules = paths ? { ...result?.rules, 'module-paths': paths.count } : {};
1311
1646
  const name = path.relative(root, file);
1312
1647
  const host = result ?? {
1313
1648
  file: name,
1314
1649
  output: name,
1315
- changed: true,
1650
+ changed: !!paths,
1316
1651
  rules,
1317
1652
  notes: storeNotes,
1318
1653
  strong: null,
1319
1654
  strongFixes: [],
1320
1655
  diagnostics: [],
1321
- code: paths.code,
1656
+ code: paths?.code ?? source,
1322
1657
  };
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('\\'));
1658
+ if (paths) {
1659
+ if (result)
1660
+ Object.assign(result, { code: paths.code, changed: true, rules });
1661
+ else
1662
+ results.push(host);
1663
+ }
1664
+ if (paths &&
1665
+ file === routesEntry &&
1666
+ originalReactEntry(file, '@react-router/dev/routes', bindingOptions(file))) {
1667
+ for (const { target, line } of registeredReactRoutes(file, source)) {
1668
+ const leaf = byFile.get(target);
1669
+ if (!renames.has(target) || !leaf || !hasTemplateExport(leaf, 'default'))
1670
+ continue;
1671
+ const note = {
1672
+ rule: 'react-compat',
1673
+ severity: 'warning',
1674
+ line,
1675
+ 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.`,
1676
+ };
1677
+ host.notes.push(note);
1678
+ if (!leaf.notes.some((existing) => existing.message === note.message))
1679
+ leaf.notes.push({ ...note, line: 1 });
1680
+ }
1681
+ }
1682
+ const retainedServer = paths && !isTsrx(file) && (source.includes('react-dom/server') || source.includes('\\'));
1683
+ const retainedElement = paths &&
1684
+ !known.has(file) &&
1685
+ file.endsWith('.ts') &&
1686
+ ((source.includes('react') && source.includes('createElement')) || source.includes('\\'));
1331
1687
  if (!edited.has(file) &&
1332
- (retainedJsx || retainedServer) &&
1688
+ (retainedJsx || retainedServer || retainedElement) &&
1333
1689
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject) {
1334
1690
  const edges = [];
1335
1691
  if (retainedJsx && automaticReactJsx(file) && originalReactEntry(file, 'react/jsx-runtime'))
@@ -1340,37 +1696,105 @@ export async function runCodemod(paths, options = {}) {
1340
1696
  ? installedReact(file)
1341
1697
  : automaticReactJsx(file) && originalReactEntry(file, module)))
1342
1698
  edges.push({ ...edge, renderer: 'server render' });
1699
+ if (retainedElement && installedReact(file))
1700
+ for (const edge of retainedReactElementReturns(file, source))
1701
+ edges.push({ ...edge, renderer: 'createElement' });
1702
+ let installedLazy;
1343
1703
  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'))
1704
+ const factory = 'factory' in edge && edge.factory;
1705
+ const inferredServerPath = edge.renderer === 'server render' && !/\.[jt]sx$/.test(edge.module);
1706
+ if (inferredServerPath &&
1707
+ (/\.(?:[cm]?[jt]sx?|tsrx)$/.test(edge.module) ||
1708
+ (config?.moduleResolution !== undefined &&
1709
+ config.moduleResolution !== ts.ModuleResolutionKind.Bundler) ||
1710
+ !/^\.{1,2}\//.test(edge.module) ||
1711
+ /[!%?#\\]/.test(edge.module) ||
1712
+ config?.rootDirs ||
1713
+ config?.moduleSuffixes?.some(Boolean)))
1714
+ continue;
1715
+ const original = path.resolve(path.dirname(file), edge.module);
1716
+ const direct = edge.renderer === 'createElement' ? null : renamed(file, edge.module);
1717
+ const proven = edge.renderer === 'createElement' ||
1718
+ (edge.renderer === 'JSX' &&
1719
+ !factory &&
1720
+ !edge.lazy &&
1721
+ (!direct || /\.js$/.test(edge.module)))
1722
+ ? retainedJsxTarget(file, edge.module, edge.name)
1723
+ : undefined;
1724
+ const match = proven ?? direct;
1725
+ if (!match || (edge.renderer === 'createElement' && proven?.indirect))
1726
+ continue;
1727
+ const exportName = proven?.name ?? edge.name;
1728
+ const extensionlessServer = inferredServerPath &&
1729
+ match.file.endsWith('.tsx') &&
1730
+ unambiguousJsxPath(match.file, original) &&
1731
+ isPlainFile(match.file);
1732
+ const explicit = match.file === original && (edge.renderer !== 'JSX' || /\.[jt]sx$/.test(edge.module));
1733
+ if (!explicit &&
1734
+ !extensionlessServer &&
1735
+ !proven &&
1736
+ (factory ||
1737
+ edge.renderer !== 'JSX' ||
1738
+ !/^\.{1,2}\//.test(edge.module) ||
1739
+ /[!%?#\\]/.test(edge.module) ||
1740
+ config?.rootDirs ||
1741
+ config?.moduleSuffixes?.some(Boolean) ||
1742
+ !unambiguousJsxPath(match.file, original)))
1743
+ continue;
1744
+ if (!automaticReactJsx(match.file) || !originalReactEntry(match.file, 'react/jsx-runtime'))
1745
+ continue;
1746
+ if (edge.lazy && !(installedLazy ??= originalReactEntry(file, 'react')))
1349
1747
  continue;
1350
1748
  const leaf = byFile.get(match.file);
1351
1749
  if (!leaf?.output.endsWith('.tsrx'))
1352
1750
  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);
1751
+ if (factory) {
1752
+ let names = jsxFactories.get(match.file);
1753
+ if (!names) {
1754
+ names = migratedJsxFactories(match.file, fs.readFileSync(match.file, 'utf8'), leaf.code);
1755
+ jsxFactories.set(match.file, names);
1756
+ }
1757
+ if (!names.has(edge.name))
1758
+ continue;
1759
+ }
1760
+ else {
1761
+ const originalExports = originalReactExports(match.file);
1762
+ if (edge.lazy && originalExports.mayExportThen)
1763
+ continue;
1764
+ if (!originalExports.intrinsics.has(exportName)) {
1765
+ const splitIntrinsicDefault = edge.renderer === 'createElement' &&
1766
+ exportName === 'default' &&
1767
+ originalExports.splitIntrinsicDefault;
1768
+ if ((!explicit && !extensionlessServer && edge.renderer !== 'createElement') ||
1769
+ edge.lazy ||
1770
+ (!splitIntrinsicDefault && !originalExports.wrappers.has(edge.name)) ||
1771
+ !hasTemplateExport(leaf, edge.name))
1772
+ continue;
1773
+ }
1357
1774
  }
1358
- if (!names.has(edge.name))
1359
- continue;
1360
1775
  const note = {
1361
1776
  rule: 'react-compat',
1362
1777
  severity: 'warning',
1363
1778
  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.`,
1779
+ message: factory
1780
+ ? `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.`
1781
+ : edge.renderer === 'JSX'
1782
+ ? `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.`
1783
+ : edge.renderer === 'createElement'
1784
+ ? `The retained React createElement call in ${name} uses ${leaf.file}. With standard package resolution, migrate the caller too or keep this component in React.`
1785
+ : `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
1786
  };
1368
1787
  host.notes.push(note);
1369
1788
  leaf.notes.push({ ...note, line: 1 });
1370
1789
  }
1371
1790
  }
1372
- if (!edited.has(file) && hasServerImport && originalServerHost()) {
1373
- for (const edge of hostedServerComponents(file, source)) {
1791
+ if (!paths) {
1792
+ if (host.notes.length && !result)
1793
+ results.push(host);
1794
+ continue;
1795
+ }
1796
+ if (!edited.has(file) && hasServerImport && originalHost(serverBridge)) {
1797
+ for (const edge of hostedComponents(file, source, serverBridge)) {
1374
1798
  const match = edge.module.startsWith('.') && renamed(file, edge.module);
1375
1799
  if (!match)
1376
1800
  continue;
@@ -1401,11 +1825,9 @@ export async function runCodemod(paths, options = {}) {
1401
1825
  }
1402
1826
  }
1403
1827
  }
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');
1828
+ const pages = await planEntryPages(root, paths.map((entry) => path.resolve(entry)), renames, checkLinkedRename);
1829
+ for (const [file, reason] of renameConflicts) {
1830
+ const conflict = conflictFor(file, fs.readFileSync(file, 'utf8'), renames.get(file), reason);
1409
1831
  if (write)
1410
1832
  return blockedWrite(root, conflict, compiler?.from);
1411
1833
  byFile.get(file)?.notes.push(...conflict.notes);
@@ -1523,7 +1945,12 @@ export async function runCodemod(paths, options = {}) {
1523
1945
  };
1524
1946
  }
1525
1947
  // Hash only previously shipped helpers. A locally edited file belongs to the application.
1526
- const PREVIOUS_INTL_HASHES = ['07ec8e00847ebc6f0bd5ffeb14bc064aa23df42d1d3db5102344c739f54dca98'];
1948
+ const PREVIOUS_INTL_HASHES = [
1949
+ '07ec8e00847ebc6f0bd5ffeb14bc064aa23df42d1d3db5102344c739f54dca98',
1950
+ '9cd8a44e85984cab413e73e63999156ac8508518c109cf53c26449c54a973043',
1951
+ 'b2c10462518bfabfd9aecc774696c8a594b456b4752b6e753cd6311f889fba0e',
1952
+ '37cdc7e5d0f17d4d0504bf4a948b724559c584650af441e000563f8ebe7e33e6',
1953
+ ];
1527
1954
  const PREVIOUS_SVG_HASHES = [
1528
1955
  '90bc12d849bbed4f1932e9e7ab5b939242237a4b8876d4c0f01e093a7d5b8c80',
1529
1956
  '9068d68b34a68b8dd4199764d16c174f1cf9cbf79172396b1f8960ddf5217916',
@@ -1535,6 +1962,7 @@ const PREVIOUS_SVG_HASHES = [
1535
1962
  '3becf859871f17914f6f0631e8db8058aa4932fd4a9817718b98eb247a902b24',
1536
1963
  '1dbf34eea75c07c21c8ab3814d54e58115e833aa140fc5f34b5f2cba91d018c3',
1537
1964
  'b53641cfbe77205a174179b4d0de60989b34cf4073690fc98536c22a68ee844a',
1965
+ 'febbdb7b04b5240afe5b417d134e52d963aa077780e54f5ef0582bc581f4dc70',
1538
1966
  ];
1539
1967
  function inspectAdapter(file, source, previous) {
1540
1968
  const stat = fs.lstatSync(file, { throwIfNoEntry: false });
@@ -1663,6 +2091,118 @@ function collect(entry, test = isSource) {
1663
2091
  function isTsrx(name) {
1664
2092
  return name.endsWith('.tsrx');
1665
2093
  }
2094
+ // React Router 7's file discovery does not consider .tsrx to be an entry extension.
2095
+ const REACT_ROUTER_ENTRY_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.mts'];
2096
+ function reactRouterEntries(root) {
2097
+ const pkg = readInstalled(root, '@react-router/dev');
2098
+ if (pkg?.manifest.name !== '@react-router/dev' ||
2099
+ !pkg.version.startsWith('7.') ||
2100
+ !record(pkg.manifest.exports)['./routes'])
2101
+ return;
2102
+ const findEntry = (dir, name) => REACT_ROUTER_ENTRY_EXTENSIONS.map((ext) => path.join(dir, name + ext)).find((file) => fs.existsSync(file));
2103
+ const config = findEntry(root, 'react-router.config');
2104
+ if (!config)
2105
+ return;
2106
+ let app = 'app';
2107
+ const source = ts.createSourceFile(config, fs.readFileSync(config, 'utf8'), ts.ScriptTarget.Latest);
2108
+ const exported = source.statements.find(ts.isExportAssignment);
2109
+ const value = exported && !exported.isExportEquals && skipWrappers(exported.expression);
2110
+ if (!value || !ts.isObjectLiteralExpression(value))
2111
+ return;
2112
+ let hasAppDirectory = false;
2113
+ for (const property of value.properties) {
2114
+ if (!property.name || (!ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name)))
2115
+ return;
2116
+ if (property.name.text === '__proto__' || property.name.text === 'presets')
2117
+ return;
2118
+ if (property.name.text !== 'appDirectory')
2119
+ continue;
2120
+ const directory = ts.isPropertyAssignment(property) && skipWrappers(property.initializer);
2121
+ if (hasAppDirectory || !directory || !ts.isStringLiteralLike(directory))
2122
+ return;
2123
+ app = directory.text || app;
2124
+ hasAppDirectory = true;
2125
+ }
2126
+ const dir = path.resolve(root, app);
2127
+ const relative = path.relative(root, dir);
2128
+ if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative))
2129
+ return;
2130
+ const rootEntry = findEntry(dir, 'root');
2131
+ const routesEntry = findEntry(dir, 'routes');
2132
+ if (rootEntry && routesEntry)
2133
+ return [rootEntry, routesEntry];
2134
+ }
2135
+ /** Direct registrations in the framework's exported routes array and its literal child groups. */
2136
+ function registeredReactRoutes(file, source) {
2137
+ const { sf, checker } = bind(file, source);
2138
+ const paths = [];
2139
+ const exported = sf.statements.find(ts.isExportAssignment);
2140
+ if (!exported || exported.isExportEquals)
2141
+ return paths;
2142
+ const dir = path.dirname(file);
2143
+ function visit(node) {
2144
+ const value = skipWrappers(node);
2145
+ if (ts.isArrayLiteralExpression(value)) {
2146
+ for (const element of value.elements) {
2147
+ if (!ts.isSpreadElement(element)) {
2148
+ visit(element);
2149
+ continue;
2150
+ }
2151
+ const group = skipWrappers(element.expression);
2152
+ if (!ts.isCallExpression(group) ||
2153
+ ts.isOptionalChain(group) ||
2154
+ !ts.isIdentifier(group.expression) ||
2155
+ group.arguments.length !== 2)
2156
+ continue;
2157
+ const helper = namedRuntimeImport(group.expression, checker);
2158
+ if (helper?.module !== '@react-router/dev/routes' || helper.name !== 'prefix')
2159
+ continue;
2160
+ const children = skipWrappers(group.arguments[1]);
2161
+ if (!ts.isSpreadElement(group.arguments[0]) && ts.isArrayLiteralExpression(children))
2162
+ visit(children);
2163
+ }
2164
+ return;
2165
+ }
2166
+ if (!ts.isCallExpression(value) ||
2167
+ ts.isOptionalChain(value) ||
2168
+ !ts.isIdentifier(value.expression))
2169
+ return;
2170
+ const callee = namedRuntimeImport(value.expression, checker);
2171
+ if (callee?.module !== '@react-router/dev/routes')
2172
+ return;
2173
+ const position = callee.name === 'route' ? 1 : callee.name === 'index' || callee.name === 'layout' ? 0 : -1;
2174
+ if (position < 0)
2175
+ return;
2176
+ const raw = value.arguments[position];
2177
+ if ((position === 1 && value.arguments[0] && ts.isSpreadElement(value.arguments[0])) ||
2178
+ (raw && ts.isSpreadElement(raw)))
2179
+ return;
2180
+ const literal = raw && skipWrappers(raw);
2181
+ if (literal &&
2182
+ ts.isStringLiteralLike(literal) &&
2183
+ !path.isAbsolute(literal.text) &&
2184
+ !/[!%?#\\]/.test(literal.text)) {
2185
+ paths.push({
2186
+ target: path.resolve(dir, literal.text),
2187
+ line: sf.getLineAndCharacterOfPosition(literal.getStart(sf)).line + 1,
2188
+ });
2189
+ }
2190
+ if (callee.name === 'index')
2191
+ return;
2192
+ const options = value.arguments[position + 1];
2193
+ if (!options)
2194
+ return;
2195
+ const argument = skipWrappers(options);
2196
+ const next = value.arguments[position + 2];
2197
+ const children = ts.isObjectLiteralExpression(argument) && next ? skipWrappers(next) : argument;
2198
+ if (ts.isArrayLiteralExpression(children))
2199
+ visit(children);
2200
+ }
2201
+ const routes = skipWrappers(exported.expression);
2202
+ if (ts.isArrayLiteralExpression(routes))
2203
+ visit(routes);
2204
+ return paths;
2205
+ }
1666
2206
  /** The compiler options of the tsconfig that governs `root`, or null. */
1667
2207
  function tsconfigOptions(root) {
1668
2208
  const file = ts.findConfigFile(root, ts.sys.fileExists);
@@ -1696,8 +2236,11 @@ function resolveModule(from, specifier, files) {
1696
2236
  return null;
1697
2237
  }
1698
2238
  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;
2239
+ return relativeImport(from, to.slice(0, -3));
2240
+ }
2241
+ function relativeImport(from, to) {
2242
+ const specifier = path.relative(path.dirname(from), to).split(path.sep).join('/');
2243
+ return specifier.startsWith('../') ? specifier : './' + specifier;
1701
2244
  }
1702
2245
  /** Only relative assets and unambiguous directory aliases have a local file to inspect. */
1703
2246
  function svgAsset(root, dir, specifier, config) {
@@ -1727,7 +2270,7 @@ function svgAsset(root, dir, specifier, config) {
1727
2270
  * Resolve against the files on disk before any rename, including modules
1728
2271
  * outside the selected paths that could win an extensionless lookup.
1729
2272
  */
1730
- function renamedImports(root, config, renames) {
2273
+ function renamedImports(root, config, renames, issuerOptions, linkedRename) {
1731
2274
  const options = {
1732
2275
  moduleResolution: ts.ModuleResolutionKind.Bundler,
1733
2276
  ...config,
@@ -1742,7 +2285,18 @@ function renamedImports(root, config, renames) {
1742
2285
  : null;
1743
2286
  return { start, end, directory };
1744
2287
  });
1745
- return (from, specifier, unmatched) => {
2288
+ const runtimeImports = new Map();
2289
+ function runtimeImport(from, specifier) {
2290
+ if (/\.d\.[cm]?ts$/.test(from))
2291
+ return false;
2292
+ let imports = runtimeImports.get(from);
2293
+ if (!imports && !isTsrx(from)) {
2294
+ imports = new Set(executableImports(from, fs.readFileSync(from, 'utf8'), !!issuerOptions(from)?.verbatimModuleSyntax));
2295
+ runtimeImports.set(from, imports);
2296
+ }
2297
+ return !imports || imports.has(specifier);
2298
+ }
2299
+ return (from, specifier, unmatched, separateRuntime, commonJs) => {
1746
2300
  const matches = specifier.startsWith('.')
1747
2301
  ? []
1748
2302
  : aliases.filter(({ start, end }) => end === undefined
@@ -1750,15 +2304,35 @@ function renamedImports(root, config, renames) {
1750
2304
  : specifier.startsWith(start) && specifier.endsWith(end));
1751
2305
  if (!renames.size || (!specifier.startsWith('.') && !matches.length))
1752
2306
  return null;
1753
- const resolved = ts.resolveModuleName(specifier, from, options, ts.sys, cache).resolvedModule;
2307
+ const resolved = ts.resolveModuleName(specifier, from, options, ts.sys, cache, undefined, commonJs ? ts.ModuleKind.CommonJS : undefined).resolvedModule;
1754
2308
  // TypeScript returns slash-delimited names, including on Windows.
1755
2309
  const file = resolved && path.normalize(resolved.resolvedFileName);
2310
+ const runtime = /^\.{1,2}\/.*\.jsx?$/.test(specifier)
2311
+ ? path.resolve(path.dirname(from), specifier)
2312
+ : null;
2313
+ if (file && runtime && file !== runtime) {
2314
+ const selectedRuntime = renames.has(runtime) ? runtime : linkedRename(runtime);
2315
+ if (selectedRuntime &&
2316
+ selectedRuntime !== file &&
2317
+ (commonJs?.() ?? runtimeImport(from, specifier))) {
2318
+ separateRuntime?.(selectedRuntime);
2319
+ return null;
2320
+ }
2321
+ }
1756
2322
  const target = file && renames.get(file);
1757
2323
  if (!target) {
1758
2324
  if (file)
1759
2325
  unmatched?.(file);
1760
2326
  return null;
1761
2327
  }
2328
+ if (runtime &&
2329
+ file.endsWith('.tsx') &&
2330
+ ts.sys.fileExists(runtime) &&
2331
+ (commonJs?.() ?? runtimeImport(from, specifier))) {
2332
+ // Preserve the runtime path and the TypeScript source it uses for types.
2333
+ separateRuntime?.(file);
2334
+ return null;
2335
+ }
1762
2336
  // Only a single directory alias preserves the specifier's suffix.
1763
2337
  // A fixed alias or fallback list may resolve elsewhere after a rename.
1764
2338
  const alias = matches.length === 1 ? matches[0] : null;
@@ -1775,12 +2349,31 @@ function renamedImports(root, config, renames) {
1775
2349
  };
1776
2350
  };
1777
2351
  }
1778
- function propsOf(file, importedRender, hostText, types) {
2352
+ /** TS can prefer a source file over a separate JS sibling or directory entry. */
2353
+ function hasModuleSibling(file) {
1779
2354
  const stem = file.slice(0, -path.extname(file).length);
1780
2355
  const dir = path.dirname(stem);
1781
2356
  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')))
2357
+ 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')));
2358
+ }
2359
+ /** Accept only a direct JSX file or directory index without a competing entry. */
2360
+ function unambiguousJsxPath(file, original) {
2361
+ if (!/\.[jt]sx$/.test(file))
2362
+ return false;
2363
+ const stem = file.slice(0, -4);
2364
+ const index = stem === path.join(original, 'index');
2365
+ if (stem !== original && !index)
2366
+ return false;
2367
+ const exists = (name) => fs.lstatSync(name, { throwIfNoEntry: false });
2368
+ if (index ? !exists(original)?.isDirectory() : exists(original))
2369
+ return false;
2370
+ return (!hasModuleSibling(file) &&
2371
+ !exists(original + '.json') &&
2372
+ !exists(original + '.tsrx') &&
2373
+ (!index || (!exists(stem) && !exists(stem + '.json') && !exists(stem + '.tsrx'))));
2374
+ }
2375
+ function propsOf(file, importedRender, hostText, types) {
2376
+ if (hasModuleSibling(file))
1784
2377
  return () => false;
1785
2378
  const { sf, checker } = bind(file, fs.readFileSync(file, 'utf8'));
1786
2379
  const module = checker.getSymbolAtLocation(sf);
@@ -2004,8 +2597,7 @@ function catalogName(specifier) {
2004
2597
  return null;
2005
2598
  }
2006
2599
  /**
2007
- * The React package a specifier names when Octane has no binding for it, or
2008
- * null.
2600
+ * The React package a specifier names when the codemod keeps it on React, or null.
2009
2601
  * @param from the importing module
2010
2602
  */
2011
2603
  function unportedName(specifier, from) {
@@ -2146,25 +2738,158 @@ function rendersWithReact(name, from) {
2146
2738
  * Point `<script src>` in HTML entry pages at renamed modules.
2147
2739
  * @param targets the paths being migrated
2148
2740
  */
2149
- function planEntryPages(root, targets, renames, unmatched) {
2741
+ async function planEntryPages(root, targets, renames, unmatched) {
2150
2742
  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) {
2743
+ const pages = renames.size ? findHtml(root, targets) : [];
2744
+ if (!pages.length)
2745
+ return updated;
2746
+ const { parse, html: { NS }, } = await import('parse5');
2747
+ function elements(source, scriptingEnabled) {
2748
+ const nodes = [
2749
+ parse(source, { sourceCodeLocationInfo: !scriptingEnabled, scriptingEnabled }),
2750
+ ];
2751
+ const result = [];
2752
+ for (const node of nodes) {
2753
+ if ('childNodes' in node)
2754
+ for (const child of node.childNodes)
2755
+ nodes.push(child);
2756
+ if (!scriptingEnabled && 'content' in node)
2757
+ nodes.push(node.content);
2758
+ if ('attrs' in node)
2759
+ result.push(node);
2760
+ }
2761
+ return result;
2762
+ }
2763
+ for (const page of pages) {
2764
+ const source = fs.readFileSync(page, 'utf8');
2765
+ let hasBase;
2766
+ const edits = [];
2767
+ // Vite loads scripts in templates and noscript.
2768
+ for (const script of elements(source, false)) {
2769
+ if (script.tagName !== 'script')
2770
+ continue;
2771
+ const src = script.sourceCodeLocation?.attrs?.src;
2772
+ if (!src)
2773
+ continue;
2774
+ const raw = source.slice(src.startOffset, src.endOffset);
2775
+ const quoted = /^src\s*=\s*(["'])([\s\S]*)\1$/i.exec(raw);
2776
+ if (!quoted)
2777
+ continue;
2778
+ const value = quoted[2];
2779
+ const pathname = value.split(/[?#]/, 1)[0];
2780
+ const extension = /\.[jt]sx?$/.exec(pathname);
2781
+ if (!extension)
2782
+ continue;
2783
+ if (pathname !== value) {
2784
+ const parsedPath = script.attrs
2785
+ .find(({ name, prefix }) => !prefix && name === 'src')
2786
+ ?.value.split(/[?#]/, 1)[0];
2787
+ if (!script.attrs.some(({ name, prefix, value }) => !prefix && name === 'type' && value === 'module') ||
2788
+ script.attrs.some(({ name, prefix }) => !prefix && name === 'vite-ignore') ||
2789
+ !/^\.{1,2}\//.test(pathname) ||
2790
+ /[\u0000-\u0020%\\]/.test(pathname) ||
2791
+ parsedPath !== pathname)
2792
+ continue;
2793
+ // Only an active document base changes resolution in the browser.
2794
+ hasBase ??=
2795
+ /<base\b/i.test(source) &&
2796
+ elements(source, true).some((node) => node.namespaceURI === NS.HTML &&
2797
+ node.tagName === 'base' &&
2798
+ node.attrs.some(({ name }) => name === 'href'));
2799
+ if (hasBase)
2800
+ continue;
2801
+ }
2802
+ const file = path.join(path.dirname(page), pathname);
2803
+ if (!renames.has(file)) {
2158
2804
  unmatched(file, page);
2159
- return match;
2805
+ continue;
2160
2806
  }
2161
- return open + quote + src.replace(/\.[jt]sx?$/, '.tsrx') + quote;
2162
- });
2163
- if (next !== html)
2807
+ const end = src.endOffset - 1 - (value.length - pathname.length);
2808
+ edits.push({ start: end - extension[0].length, end });
2809
+ }
2810
+ let next = source;
2811
+ for (const { start, end } of edits.sort((a, b) => b.start - a.start)) {
2812
+ next = next.slice(0, start) + '.tsrx' + next.slice(end);
2813
+ }
2814
+ if (next !== source)
2164
2815
  updated.set(page, next);
2165
2816
  }
2166
2817
  return updated;
2167
2818
  }
2819
+ /** A strict identity test observes the loader's main module without exposing it. */
2820
+ function comparesMainModule(node) {
2821
+ const test = node.parent;
2822
+ if (!ts.isBinaryExpression(test) ||
2823
+ (test.operatorToken.kind !== ts.SyntaxKind.EqualsEqualsEqualsToken &&
2824
+ test.operatorToken.kind !== ts.SyntaxKind.ExclamationEqualsEqualsToken))
2825
+ return false;
2826
+ const [main, module] = ts.isIdentifier(test.left)
2827
+ ? [test.right, test.left]
2828
+ : [test.left, test.right];
2829
+ return (ts.isIdentifier(module) &&
2830
+ module.text === 'module' &&
2831
+ ts.isPropertyAccessExpression(main) &&
2832
+ main.name.text === 'main' &&
2833
+ ts.isIdentifier(main.expression) &&
2834
+ main.expression.text === 'require');
2835
+ }
2836
+ function observesRequire(member) {
2837
+ const use = member.parent;
2838
+ if (member.name.text === 'main')
2839
+ return comparesMainModule(member);
2840
+ if (member.name.text === 'resolve')
2841
+ return ts.isCallExpression(use) && use.expression === member;
2842
+ if (member.name.text !== 'cache')
2843
+ return false;
2844
+ // Cache entries are mutable Module objects. A presence test or deleting the
2845
+ // map entry does not expose an object that can replace the wrapper's loader.
2846
+ const entry = ts.isElementAccessExpression(use) && use.expression === member ? use : member;
2847
+ const parent = entry.parent;
2848
+ return ((ts.isPrefixUnaryExpression(parent) && parent.operator === ts.SyntaxKind.ExclamationToken) ||
2849
+ (ts.isIfStatement(parent) && parent.expression === entry) ||
2850
+ (entry !== member && ts.isDeleteExpression(parent)));
2851
+ }
2852
+ /** Positions of calls to the CommonJS wrapper's own `require`. */
2853
+ function commonJsRequires(file, code) {
2854
+ const calls = new Set();
2855
+ const format = ts.getImpliedNodeFormatForFile(file, undefined, ts.sys, {
2856
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
2857
+ });
2858
+ if (format !== ts.ModuleKind.CommonJS)
2859
+ return calls;
2860
+ const { sf, checker } = bind(file, code);
2861
+ const opaque = contains(sf, (node) => {
2862
+ if (ts.isWithStatement(node))
2863
+ return true;
2864
+ if (!ts.isIdentifier(node))
2865
+ return false;
2866
+ const parent = node.parent;
2867
+ if (ts.isPropertyAccessExpression(parent) && parent.name === node)
2868
+ return false;
2869
+ // Dynamic scope and the wrapper's arguments can change the loader.
2870
+ if (node.text === 'eval' || node.text === 'arguments')
2871
+ return true;
2872
+ // Node's wrapper delegates to module.require. Allow ordinary exports assignments.
2873
+ if (node.text === 'module' &&
2874
+ !comparesMainModule(node) &&
2875
+ !(ts.isPropertyAccessExpression(parent) &&
2876
+ parent.expression === node &&
2877
+ parent.name.text === 'exports'))
2878
+ return true;
2879
+ if (node.text !== 'require' ||
2880
+ checker.resolveName(node.text, node, ts.SymbolFlags.Value, false)?.declarations?.length)
2881
+ return false;
2882
+ if (ts.isPropertyAccessExpression(parent))
2883
+ return !observesRequire(parent);
2884
+ if (!ts.isCallExpression(parent) || parent.expression !== node)
2885
+ return true;
2886
+ calls.add(node.end);
2887
+ return false;
2888
+ });
2889
+ if (opaque)
2890
+ calls.clear();
2891
+ return calls;
2892
+ }
2168
2893
  /**
2169
2894
  * Follow imports outside the migrated paths as well as exact path strings
2170
2895
  * in scripts and configs. Parse TSRX importers with their own grammar so
@@ -2227,9 +2952,30 @@ function rewriteModulePaths(code, file, root, renames, resolveRename, unmatched)
2227
2952
  }
2228
2953
  else {
2229
2954
  const sf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
2955
+ const mayRequire = file.endsWith('.js') && !ts.isExternalModule(sf);
2956
+ let requires;
2230
2957
  const visit = (node) => {
2231
2958
  if (ts.isStringLiteralLike(node)) {
2232
2959
  const p = node.parent;
2960
+ if (mayRequire &&
2961
+ ts.isCallExpression(p) &&
2962
+ p.arguments[0] === node &&
2963
+ p.arguments.length === 1 &&
2964
+ !p.questionDotToken &&
2965
+ ts.isIdentifier(p.expression) &&
2966
+ p.expression.text === 'require' &&
2967
+ /^\.{1,2}\/.*\.js$/.test(node.text)) {
2968
+ const callee = p.expression;
2969
+ let preservesRequire = false;
2970
+ resolveRename(file, node.text, () => {
2971
+ requires ??= commonJsRequires(file, code);
2972
+ preservesRequire = requires.has(callee.end);
2973
+ return preservesRequire;
2974
+ });
2975
+ // A split blocks the rename and keeps this call intact in preview.
2976
+ if (preservesRequire)
2977
+ return;
2978
+ }
2233
2979
  const moduleSource = ((ts.isImportDeclaration(p) || ts.isExportDeclaration(p)) &&
2234
2980
  p.moduleSpecifier === node) ||
2235
2981
  ts.isExternalModuleReference(p) ||