@octanejs/codemod 0.2.0 → 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.
Files changed (40) hide show
  1. package/README.md +140 -12
  2. package/dist/bin.js +2 -2
  3. package/dist/effect-receivers.d.ts +14 -2
  4. package/dist/effect-receivers.js +171 -22
  5. package/dist/expression-wrappers.d.ts +2 -0
  6. package/dist/expression-wrappers.js +19 -0
  7. package/dist/forwarded-props.d.ts +4 -1
  8. package/dist/forwarded-props.js +18 -3
  9. package/dist/linked-state.d.ts +1 -1
  10. package/dist/linked-state.js +7 -3
  11. package/dist/local-react-hook.d.ts +13 -6
  12. package/dist/local-react-hook.js +316 -53
  13. package/dist/local-uses.d.ts +10 -1
  14. package/dist/local-uses.js +87 -5
  15. package/dist/mappings.d.ts +7 -1
  16. package/dist/mappings.js +21 -3
  17. package/dist/path-svg.d.ts +68 -4
  18. package/dist/path-svg.js +162 -56
  19. package/dist/project.js +1589 -147
  20. package/dist/react-intl.d.ts +1 -1
  21. package/dist/react-intl.js +43 -6
  22. package/dist/react-island-sources.d.ts +53 -0
  23. package/dist/react-island-sources.js +979 -0
  24. package/dist/react-renderer.d.ts +2 -0
  25. package/dist/react-renderer.js +94 -0
  26. package/dist/scoped-store-contract.d.ts +9 -2
  27. package/dist/scoped-store-contract.js +209 -33
  28. package/dist/store-hook-uses.d.ts +7 -5
  29. package/dist/store-hook-uses.js +218 -62
  30. package/dist/store-inputs.d.ts +9 -2
  31. package/dist/store-inputs.js +213 -16
  32. package/dist/strong.d.ts +2 -2
  33. package/dist/strong.js +72 -18
  34. package/dist/transform.d.ts +14 -0
  35. package/dist/transform.js +2856 -292
  36. package/dist/types.d.ts +40 -10
  37. package/package.json +4 -3
  38. package/src/path-svg.ts +183 -62
  39. package/templates/octane-path-svg.ts +5 -1
  40. package/templates/react-intl.tsrx +64 -11
package/dist/project.js CHANGED
@@ -1,6 +1,6 @@
1
- import { createScopedStorePlanner } from './scoped-store-contract.js';
1
+ import { createScopedStorePlanner, runtimeTargets } from './scoped-store-contract.js';
2
2
  import { parseStaticSvg } from './path-svg.js';
3
- import { storeSources } from './store-inputs.js';
3
+ import { resourceHints, retainedLiteralExports, storeSources } from './store-inputs.js';
4
4
  import { createHash } from 'node:crypto';
5
5
  import fs from 'node:fs';
6
6
  import { createRequire } from 'node:module';
@@ -10,15 +10,27 @@ 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 { PORTED_PACKAGES } from './mappings.js';
13
+ import { skipWrappers } from './expression-wrappers.js';
14
+ import { isReactMotion, PORTED_PACKAGES } from './mappings.js';
14
15
  import { strengthen } from './strong.js';
15
- import { bind, projectTypeAt, textKind, transformModule } from './transform.js';
16
- import { directReactHooks, nativeExternalStore } from './local-react-hook.js';
17
- import { forwardedProps } from './forwarded-props.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';
18
20
  const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
19
- const ADAPTER_OCTANE_VERSION = /^0\.(?:16\.(?:[7-9]|[1-9]\d+)|17\.(?:0|[1-9]\d*))$/;
21
+ const ADAPTER_OCTANE_VERSION = /^0\.(?:16\.(?:[7-9]|[1-9]\d+)|1[789]\.(?:0|[1-9]\d*))$/;
22
+ // React Intl 7.1.14. Both entry points re-export a hook that calls React.useContext.
23
+ const INTL_HOOK_FILES = {
24
+ 'index.js': '8f5854dadcd055f066234e13a344bd0b102aea2d50ddfd2f0cf12e9f48116059',
25
+ 'lib/index.js': '208130dc122cbb84cbc0d4cce54fd7f458954f45d2cd5dc505d7263686ca6093',
26
+ 'src/components/useIntl.js': '7f26c3c5aebaf874aa2ee7f56952358530c246382f7ca9e729a3ee33d196d6c8',
27
+ 'lib/src/components/useIntl.js': '36bb0433939586c08e79a211372987b4173c73552f75d2ae66b6250bdf1f3b8c',
28
+ };
20
29
  /** React packages and the Octane entry point that replaces each. */
21
30
  const CATALOG = { ...DATA.reactPackages, ...PORTED_PACKAGES };
31
+ const MOTION_BINDING = '@octanejs/motion';
32
+ const MOTION_VERSION = DATA.bindings.find(({ name }) => name === MOTION_BINDING).version;
33
+ const MOTION_EXPORTS = new Set(DATA.motionExports);
22
34
  const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies'];
23
35
  /** A package that, by its name, renders through React. */
24
36
  const REACT_PACKAGE = /^(?:react-|@[^/]+\/react(?:-|\/|$)|[^/]+\/react$)|-react(?:\/|$)/;
@@ -38,9 +50,50 @@ export async function runCodemod(paths, options = {}) {
38
50
  findRoot(fs.statSync(first, { throwIfNoEntry: false })?.isFile() ? path.dirname(first) : first));
39
51
  const known = new Set(paths.flatMap((entry) => collect(path.resolve(entry))));
40
52
  const files = [...known];
53
+ let selectedRealpaths;
41
54
  const renames = new Map();
42
55
  const exports = new Map();
43
56
  const owners = new Map();
57
+ const outputDirectories = new Map();
58
+ function entryKey(file) {
59
+ // A symlinked parent can name the same output. Keep the last path component
60
+ // lexical because the write owns that directory entry, not a symlink target.
61
+ const dir = path.dirname(file);
62
+ let physical = outputDirectories.get(dir);
63
+ if (physical === undefined) {
64
+ // On macOS the native lookup also returns the stored Unicode spelling.
65
+ physical = process.platform === 'darwin' ? fs.realpathSync.native(dir) : fs.realpathSync(dir);
66
+ outputDirectories.set(dir, physical);
67
+ }
68
+ return path.join(physical, path.basename(file));
69
+ }
70
+ function outputKey(file) {
71
+ const output = entryKey(file);
72
+ return ts.sys.useCaseSensitiveFileNames ? output : output.toLowerCase();
73
+ }
74
+ const normalizedOwners = process.platform === 'darwin' && files.some((file) => /[^\x00-\x7F]/.test(path.basename(file)))
75
+ ? new Map()
76
+ : undefined;
77
+ function normalizedOwner(key, file) {
78
+ if (!normalizedOwners)
79
+ return;
80
+ const group = path.join(path.dirname(key), path.basename(key).normalize('NFC'));
81
+ let candidates = normalizedOwners.get(group);
82
+ if (!candidates)
83
+ normalizedOwners.set(group, (candidates = []));
84
+ // Use an ordinary existing entry to probe the other stem without following leaf links.
85
+ const regularFile = (name) => fs.lstatSync(name, { throwIfNoEntry: false })?.isFile();
86
+ const sameStem = (source, other) => {
87
+ const alternate = other.slice(0, -path.extname(other).length) + path.extname(source);
88
+ return (regularFile(source) &&
89
+ regularFile(alternate) &&
90
+ fs.realpathSync.native(source) === fs.realpathSync.native(alternate));
91
+ };
92
+ const previous = candidates.filter((candidate) => sameStem(candidate, file) || sameStem(file, candidate));
93
+ if (previous.length === 0 || !previous.some(regularFile))
94
+ candidates.push(file);
95
+ return previous;
96
+ }
44
97
  const conflicts = new Map();
45
98
  const conflictFor = (file, source, output, reason) => unchangedFile(path.relative(root, file), source, {
46
99
  rule: 'rename-conflict',
@@ -57,10 +110,12 @@ export async function runCodemod(paths, options = {}) {
57
110
  const output = file.replace(/\.(?:jsx?|tsx)$/, '.tsrx');
58
111
  if (output === file)
59
112
  continue;
60
- const key = ts.sys.useCaseSensitiveFileNames ? output : output.toLowerCase();
61
- const previous = owners.get(key);
62
- if (!previous)
63
- owners.set(key, file);
113
+ const key = outputKey(output);
114
+ const direct = owners.get(key);
115
+ const normalized = normalizedOwner(key, file);
116
+ const previous = direct ?? normalized?.[0];
117
+ if (!direct)
118
+ owners.set(key, previous ?? file);
64
119
  if (previous || fs.lstatSync(output, { throwIfNoEntry: false })) {
65
120
  const reason = previous
66
121
  ? `is also the target of ${path.relative(root, previous)}`
@@ -69,15 +124,28 @@ export async function runCodemod(paths, options = {}) {
69
124
  if (write)
70
125
  return blockedWrite(root, conflict);
71
126
  conflicts.set(file, conflict);
72
- const previousOutput = previous && renames.get(previous);
73
- if (previous && previousOutput) {
74
- conflicts.set(previous, conflictFor(previous, fs.readFileSync(previous, 'utf8'), previousOutput, `is also the target of ${path.relative(root, file)}`));
75
- renames.delete(previous);
127
+ for (const owner of new Set([previous, ...(normalized ?? [])])) {
128
+ const ownerOutput = owner && renames.get(owner);
129
+ if (owner && ownerOutput) {
130
+ conflicts.set(owner, conflictFor(owner, fs.readFileSync(owner, 'utf8'), ownerOutput, `is also the target of ${path.relative(root, file)}`));
131
+ renames.delete(owner);
132
+ }
76
133
  }
77
134
  continue;
78
135
  }
79
136
  renames.set(file, output);
80
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
+ }
81
149
  // A colliding source remains in place, so its imports and export contracts
82
150
  // must not participate in the preview as if it had been migrated.
83
151
  for (const file of conflicts.keys())
@@ -95,7 +163,54 @@ export async function runCodemod(paths, options = {}) {
95
163
  return { sourceFile, checker: program.getTypeChecker() };
96
164
  }
97
165
  const contextsOf = contextIndex(exports, known);
98
- const renamed = renamedImports(root, config, renames);
166
+ const contextPaths = Object.keys(config?.paths ?? {}).map((pattern) => pattern.split('*'));
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);
175
+ const foldNames = process.platform === 'darwin';
176
+ const leafKey = (file) => {
177
+ const name = path.basename(file);
178
+ return foldNames ? name.normalize('NFC').toLowerCase() : name;
179
+ };
180
+ const sourceNames = new Set([...renames.keys()].map(leafKey));
181
+ const sourceEntries = new Map([...renames.keys()].map((file) => [entryKey(file), file]));
182
+ const foldedSources = new Map();
183
+ if (foldNames) {
184
+ for (const [entry, source] of sourceEntries) {
185
+ const key = path.join(path.dirname(entry), leafKey(entry));
186
+ const group = foldedSources.get(key);
187
+ if (group)
188
+ group.push(source);
189
+ else
190
+ foldedSources.set(key, [source]);
191
+ }
192
+ }
193
+ function linkedRename(file) {
194
+ if (renames.has(path.normalize(file)))
195
+ return;
196
+ const name = leafKey(file);
197
+ if (!sourceNames.has(name) || !fs.existsSync(file))
198
+ return;
199
+ const entry = entryKey(file);
200
+ const selected = sourceEntries.get(entry);
201
+ if (selected)
202
+ return selected;
203
+ const folded = foldNames && foldedSources.get(path.join(path.dirname(entry), name));
204
+ if (!folded)
205
+ return;
206
+ // APFS reports the stored spelling. A leaf symlink or hard link must
207
+ // remain a distinct entry even when it reaches the same file.
208
+ if (!fs.lstatSync(file, { throwIfNoEntry: false })?.isFile())
209
+ return;
210
+ const actual = fs.realpathSync.native(file);
211
+ return folded.find((source) => fs.lstatSync(source, { throwIfNoEntry: false })?.isFile() &&
212
+ fs.realpathSync.native(source) === actual);
213
+ }
99
214
  const resolveRename = (from, specifier) => renamed(from, specifier)?.specifier ?? null;
100
215
  const propChecks = new Map();
101
216
  function forwardedProp(from, specifier, name, prop, destination, ordinaryCaller, depth = 0) {
@@ -119,7 +234,7 @@ export async function runCodemod(paths, options = {}) {
119
234
  }
120
235
  return inspect(destination, name, prop, ordinaryCaller, depth);
121
236
  }
122
- // resolveRename returns only an on-disk source that actually won import resolution.
237
+ // Index the exports of selected source modules by their planned output.
123
238
  const elementExports = new Map();
124
239
  const descriptorExports = new Map();
125
240
  for (const [from, to] of renames) {
@@ -134,22 +249,31 @@ export async function runCodemod(paths, options = {}) {
134
249
  const compiler = verify || strong ? await loadCompiler(root) : null;
135
250
  const packages = new Map();
136
251
  const missing = new Map();
137
- // `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
138
253
  // root, from 19.2 within the React 19 series it supports.
139
254
  const reactCompat = ['react', 'react-dom'].every((name) => /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''));
140
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
+ }
265
+ function automaticReactJsx(file) {
266
+ // A nested project can compile the same file with another JSX factory.
267
+ return (config?.jsx === ts.JsxEmit.ReactJSX &&
268
+ !config.jsxFactory &&
269
+ !config.jsxFragmentFactory &&
270
+ (!config.jsxImportSource || config.jsxImportSource === 'react') &&
271
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject);
272
+ }
141
273
  function reactStoreComponent(file, specifier) {
142
- if (!reactCompat || !unportedName(specifier, file))
274
+ if (!reactCompat || !unportedName(specifier, file) || !automaticReactJsx(file))
143
275
  return false;
144
276
  const dir = path.dirname(file);
145
- // A nested project and the migration root can both include this file but
146
- // compile its JSX with different factories or module resolution.
147
- if (config?.jsx !== ts.JsxEmit.ReactJSX ||
148
- config.jsxFactory ||
149
- config.jsxFragmentFactory ||
150
- (config.jsxImportSource && config.jsxImportSource !== 'react') ||
151
- ts.findConfigFile(dir, ts.sys.fileExists) !== rootProject)
152
- return false;
153
277
  const name = packageName(specifier);
154
278
  const lib = readInstalled(dir, name);
155
279
  if (!lib ||
@@ -174,19 +298,65 @@ export async function runCodemod(paths, options = {}) {
174
298
  const original = ts.resolveModuleName(module, file, { ...bindings, paths: undefined, baseUrl: undefined }, ts.sys).resolvedModule;
175
299
  return target?.resolvedFileName === original?.resolvedFileName ? (target ?? null) : undefined;
176
300
  }
177
- function installedReact(file) {
301
+ function installedReact(file, module = 'react') {
178
302
  const dir = path.dirname(file);
179
303
  if (ts.findConfigFile(dir, ts.sys.fileExists) !== rootProject)
180
304
  return false;
181
- const target = originalModule(file, 'react');
182
- if (!target || !['react', '@types/react'].includes(target.packageId?.name ?? ''))
305
+ const target = originalModule(file, module);
306
+ if (!target || ![module, `@types/${module}`].includes(target.packageId?.name ?? ''))
183
307
  return false;
184
- // TypeScript can resolve @types/react even when the runtime is missing or linked locally.
185
- const runtime = readInstalled(dir, 'react');
186
- return (runtime?.manifest.name === 'react' &&
308
+ // TypeScript can resolve declarations even when the runtime is missing or linked locally.
309
+ const runtime = readInstalled(dir, module);
310
+ return (runtime?.manifest.name === module &&
187
311
  fs.realpathSync(runtime.dir).split(path.sep).includes('node_modules') &&
188
312
  fs.realpathSync(target.resolvedFileName).split(path.sep).includes('node_modules'));
189
313
  }
314
+ let physicalRoot;
315
+ const retainedStoreArguments = new Map();
316
+ const descriptorModules = new Map();
317
+ function retainedStoreArgument(file, source, name) {
318
+ const key = file + '\0' + source;
319
+ let retained = retainedStoreArguments.get(key);
320
+ if (retained === undefined) {
321
+ retained = retainsPackageTarget(file, source);
322
+ retainedStoreArguments.set(key, retained);
323
+ }
324
+ return retained?.has(name) ?? false;
325
+ }
326
+ function retainsPackageTarget(file, source) {
327
+ if (resolveRename(file, source) || catalogName(source) !== null || unportedName(source, file))
328
+ return null;
329
+ const target = originalModule(file, source);
330
+ if (!target?.isExternalLibraryImport || !installedReact(file))
331
+ return null;
332
+ try {
333
+ const runtime = createRequire(file).resolve(source);
334
+ if (!path.isAbsolute(runtime))
335
+ return null;
336
+ const real = fs.realpathSync(runtime);
337
+ if (known.has(real) || known.has(target.resolvedFileName))
338
+ return null;
339
+ const authored = path.relative((physicalRoot ??= fs.realpathSync(root)), real);
340
+ if (!authored.startsWith('..' + path.sep) &&
341
+ !path.isAbsolute(authored) &&
342
+ !authored.split(path.sep).includes('node_modules'))
343
+ return null;
344
+ const [entry] = runtimeTargets(source, real, file, true);
345
+ if (fs.realpathSync(target.resolvedFileName) !== real ||
346
+ !entry ||
347
+ fs.realpathSync(entry) !== real)
348
+ return null;
349
+ let descriptors = descriptorModules.get(real);
350
+ if (descriptors === undefined) {
351
+ descriptors = retainedLiteralExports(real);
352
+ descriptorModules.set(real, descriptors);
353
+ }
354
+ return descriptors;
355
+ }
356
+ catch {
357
+ return null;
358
+ }
359
+ }
190
360
  const inlineCompatDirs = new Map();
191
361
  function supportsInlineReactCompat(file) {
192
362
  const issuer = path.dirname(file);
@@ -234,11 +404,47 @@ export async function runCodemod(paths, options = {}) {
234
404
  });
235
405
  });
236
406
  }
407
+ function bindingOptions(file) {
408
+ const dir = path.dirname(file);
409
+ return ts.findConfigFile(dir, ts.sys.fileExists) === rootProject
410
+ ? config
411
+ : tsconfigOptions(dir);
412
+ }
413
+ const installedMotionExports = new Map();
414
+ const motionExportsByIssuer = new Map();
415
+ function motionExports(file) {
416
+ const dir = path.dirname(file);
417
+ const known = motionExportsByIssuer.get(dir);
418
+ if (known !== undefined)
419
+ return known;
420
+ const installed = readInstalled(dir, MOTION_BINDING);
421
+ const declarations = bindingDeclarations(root, dir, MOTION_BINDING);
422
+ let actual = null;
423
+ if (installed &&
424
+ !declarations.some((spec) => typeof spec === 'string' &&
425
+ /^\d+\.\d+\.\d+(?:-[\da-z.-]+)?(?:\+[\da-z.-]+)?$/i.test(spec) &&
426
+ spec !== installed.version)) {
427
+ const physical = fs.realpathSync(installed.dir);
428
+ const cached = installedMotionExports.get(physical);
429
+ actual = cached === undefined ? readMotionExports(installed.manifest, physical) : cached;
430
+ installedMotionExports.set(physical, actual);
431
+ }
432
+ else if (!installed &&
433
+ declarations.every((spec) => catalogBindingVersion(spec, MOTION_VERSION))) {
434
+ actual = MOTION_EXPORTS;
435
+ }
436
+ motionExportsByIssuer.set(dir, actual);
437
+ return actual;
438
+ }
439
+ function bindingExports(file, from, to) {
440
+ return to === MOTION_BINDING && isReactMotion(from)
441
+ ? (motionExports(file) ?? undefined)
442
+ : undefined;
443
+ }
237
444
  const bindingProject = {
238
445
  root,
239
- original(file, module) {
240
- const dir = path.dirname(file);
241
- const options = ts.findConfigFile(dir, ts.sys.fileExists) === rootProject ? config : tsconfigOptions(dir);
446
+ motionExports,
447
+ original(file, module, options = bindingOptions(file)) {
242
448
  return ((!options?.paths && !options?.baseUrl) ||
243
449
  originalModule(file, module, options) !== undefined);
244
450
  },
@@ -267,6 +473,12 @@ export async function runCodemod(paths, options = {}) {
267
473
  ADAPTER_OCTANE_VERSION.test(octane) &&
268
474
  ['react', 'react-dom'].every((name) => /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(base, name)?.version ?? '')) &&
269
475
  [file, adapter].every((source) => {
476
+ const options = bindingOptions(source);
477
+ if (!bindingProject.original(source, 'react-intl', options))
478
+ return false;
479
+ const conditions = options?.customConditions;
480
+ if (conditions?.length && hasRuntimeExportCondition(lib.manifest.exports, conditions))
481
+ return false;
270
482
  const resolved = ts.resolveModuleName('react-intl', source, bindings, ts.sys).resolvedModule;
271
483
  return (original &&
272
484
  resolved &&
@@ -291,8 +503,7 @@ export async function runCodemod(paths, options = {}) {
291
503
  if (adapterSource === undefined) {
292
504
  adapterSource = fs.readFileSync(new URL('../templates/react-intl.tsrx', import.meta.url), 'utf8');
293
505
  adapterState = inspectAdapter(adapter, adapterSource, PREVIOUS_INTL_HASHES);
294
- if (adapterState.kind === 'conflict' ||
295
- owners.has(ts.sys.useCaseSensitiveFileNames ? adapter : adapter.toLowerCase())) {
506
+ if (adapterState.kind === 'conflict' || owners.has(outputKey(adapter))) {
296
507
  adapterError = `Cannot generate the React Intl adapter because ${adapterName} is already in use.`;
297
508
  }
298
509
  else if (compiler &&
@@ -300,8 +511,7 @@ export async function runCodemod(paths, options = {}) {
300
511
  adapterError = 'The project compiler cannot compile the React Intl adapter.';
301
512
  }
302
513
  }
303
- const specifier = path.relative(dir, adapter).split(path.sep).join('/');
304
- return specifier.startsWith('.') ? specifier : './' + specifier;
514
+ return relativeImport(file, adapter);
305
515
  };
306
516
  const helperDir = path.dirname(adapter);
307
517
  const storeBridge = path.join(helperDir, 'octane-store-context.tsrx');
@@ -312,7 +522,7 @@ export async function runCodemod(paths, options = {}) {
312
522
  ADAPTER_OCTANE_VERSION.test(readInstalled(helperDir, 'octane')?.version ?? '')
313
523
  ? createScopedStorePlanner(helperDir, storeBridge, config ?? undefined)
314
524
  : null;
315
- const { inputFactory, helperFunction, localFile } = storeSources(root, config, (file, source) => {
525
+ function unchangedStoreInput(file, source) {
316
526
  if (renames.has(file) ||
317
527
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
318
528
  rewriteModulePaths(source, file, root, renames, resolveRename))
@@ -330,10 +540,160 @@ export async function runCodemod(paths, options = {}) {
330
540
  },
331
541
  resolveSpecifier: (specifier) => resolveRename(file, specifier) ??
332
542
  resolveBinding(specifier, file, bindingProject, new Map(), []),
543
+ bindingExports: (from, to) => bindingExports(file, from, to),
333
544
  }).changed;
334
- });
335
- const localHooks = new Map();
545
+ }
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
+ }
336
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
+ }
625
+ const localHints = new Map();
626
+ function initializerResourceHint(from, module, name, retainedOnly = false) {
627
+ const file = localFile(from, module);
628
+ if (!file ||
629
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
630
+ !installedReact(from))
631
+ return;
632
+ let calls = localHints.get(file);
633
+ if (!calls) {
634
+ calls = new Map();
635
+ const source = fs.readFileSync(file, 'utf8');
636
+ if ((source.includes('react-dom') || source.includes('\\')) &&
637
+ installedReact(file, 'react-dom')) {
638
+ const { sf, checker } = bind(file, source);
639
+ calls = directRendererCalls(sf, checker, 'react-dom', (api) => resourceHints.has(api));
640
+ }
641
+ localHints.set(file, calls);
642
+ }
643
+ const hint = calls.get(name);
644
+ if (hint && (!retainedOnly || (fs.statSync(file).nlink === 1 && !writesSelectedInput(file))))
645
+ return hint;
646
+ }
647
+ const localHooks = new Map();
648
+ const intlHookPackages = new Map();
649
+ function originalIntlHook(file) {
650
+ const types = originalModule(file, 'react-intl');
651
+ if (types?.packageId?.name !== 'react-intl')
652
+ return false;
653
+ const installed = readInstalled(path.dirname(file), 'react-intl');
654
+ if (installed?.manifest.name !== 'react-intl' ||
655
+ installed.version !== '7.1.14' ||
656
+ installed.manifest.browser ||
657
+ installed.manifest.exports ||
658
+ installed.manifest.main !== 'index.js' ||
659
+ installed.manifest.module !== 'lib/index.js')
660
+ return false;
661
+ try {
662
+ const dir = fs.realpathSync(installed.dir);
663
+ const entry = path.join(dir, 'index.js');
664
+ const issuer = createRequire(file);
665
+ if (!dir.split(path.sep).includes('node_modules') ||
666
+ fs.realpathSync(types.resolvedFileName) !== path.join(dir, 'index.d.ts') ||
667
+ issuer.resolve('react-intl') !== entry ||
668
+ readInstalled(path.dirname(file), 'react')?.manifest.name !== 'react')
669
+ return false;
670
+ const react = issuer.resolve('react');
671
+ if (!['src', 'lib/src'].every((prefix) => createRequire(path.join(dir, prefix, 'components/useIntl.js')).resolve('react') ===
672
+ react))
673
+ return false;
674
+ let verified = intlHookPackages.get(dir);
675
+ if (verified === undefined) {
676
+ // An extra executable can shadow an extensionless import before its verified .js.
677
+ verified =
678
+ ['src', 'lib/src'].every((prefix) => ['', '.mjs', '.mts', '.ts', '.jsx', '.tsx'].every((ext) => !fs.lstatSync(path.join(dir, prefix, 'components/useIntl' + ext), {
679
+ throwIfNoEntry: false,
680
+ }))) &&
681
+ Object.entries(INTL_HOOK_FILES).every(([name, hash]) => {
682
+ const executable = path.join(dir, name);
683
+ const stat = fs.lstatSync(executable, { throwIfNoEntry: false });
684
+ return (stat?.isFile() &&
685
+ stat.size < 16_384 &&
686
+ fs.realpathSync(executable) === executable &&
687
+ createHash('sha256').update(fs.readFileSync(executable)).digest('hex') === hash);
688
+ });
689
+ intlHookPackages.set(dir, verified);
690
+ }
691
+ return verified;
692
+ }
693
+ catch {
694
+ return false;
695
+ }
696
+ }
337
697
  function localReactHook(from, module, name, nativeOnly) {
338
698
  if (catalogName(module) !== null ||
339
699
  resolveRename(from, module) ||
@@ -341,36 +701,59 @@ export async function runCodemod(paths, options = {}) {
341
701
  ts.findConfigFile(path.dirname(from), ts.sys.fileExists) !== rootProject)
342
702
  return;
343
703
  const file = localFile(from, module);
704
+ const jsSpecifier = module.endsWith('.js') && (module.startsWith('./') || module.startsWith('../'));
344
705
  if (!file ||
706
+ (jsSpecifier && path.resolve(path.dirname(from), module.slice(0, -3) + '.ts') !== file) ||
345
707
  known.has(file) ||
346
708
  path.basename(file) === 'index.ts' ||
347
709
  fs.existsSync(file.slice(0, -3) + '.tsrx') ||
348
- (path.extname(module) && !module.endsWith('.ts')) ||
710
+ (path.extname(module) && !module.endsWith('.ts') && !jsSpecifier) ||
349
711
  fs.realpathSync(file) !== path.join(fs.realpathSync(root), path.relative(root, file)) ||
350
712
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
351
713
  return;
352
714
  let hooks = localHooks.get(file);
353
715
  if (!hooks) {
354
716
  const source = fs.readFileSync(file, 'utf8');
355
- hooks = new Map();
356
- if ((/\b(?:useState|useSyncExternalStore)\b/.test(source) || source.includes('\\u')) &&
717
+ hooks = { direct: new Map(), privateContexts: new Set() };
718
+ const escaped = source.includes('\\u');
719
+ const react = (/\b(?:useCallback|useContext|useEffect|useEffectEvent|useState|useSyncExternalStore)\b/.test(source) ||
720
+ (source.includes('\\') && source.includes('createContext')) ||
721
+ escaped) &&
357
722
  originalModule(file, 'react') &&
358
- readInstalled(path.dirname(file), 'react')?.manifest.name === 'react') {
723
+ readInstalled(path.dirname(file), 'react')?.manifest.name === 'react';
724
+ const intl = (source.includes('useIntl') || escaped) && originalIntlHook(file);
725
+ const store = planStoreHook && /\buse[A-Z]|\\u/.test(source);
726
+ if (react || intl || store) {
359
727
  const existing = program?.getSourceFile(file);
360
728
  const bound = existing && program
361
729
  ? { sf: existing, checker: program.getTypeChecker() }
362
730
  : bind(file, source);
363
- hooks = directReactHooks(bound.sf, bound.checker);
731
+ if (planStoreHook && store)
732
+ hooks.retainedStores = directRendererCalls(bound.sf, bound.checker, (specifier, exported) => !!unportedName(specifier, file) &&
733
+ planStoreHook(specifier, exported, file)?.requiresReact() === true);
734
+ if (react)
735
+ hooks.direct = directRendererCalls(bound.sf, bound.checker, 'react', (name) => name === 'useCallback' ||
736
+ name === 'useContext' ||
737
+ name === 'useState' ||
738
+ name === 'useSyncExternalStore', hooks.privateContexts);
739
+ if (intl)
740
+ for (const [name, hook] of directRendererCalls(bound.sf, bound.checker, 'react-intl', (name) => name === 'useIntl'))
741
+ hooks.direct.set(name, hook);
364
742
  }
365
743
  localHooks.set(file, hooks);
366
744
  }
367
- const hook = hooks.get(name);
368
- if (!hook || 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)
369
750
  return;
370
- // Writing an unrenamed selection through a symlink changes its physical target.
371
- selectedInPlace ??= new Set([...known].filter((f) => !renames.has(f) && !conflicts.has(f)).map((f) => fs.realpathSync(f)));
372
- if (selectedInPlace.has(fs.realpathSync(file)))
751
+ if (writesSelectedInput(file))
373
752
  return;
753
+ if (!hook)
754
+ return retainedStore
755
+ ? { retainedStore: true }
756
+ : { privateContext: true };
374
757
  if (nativeOnly &&
375
758
  compiler &&
376
759
  hook === 'useSyncExternalStore' &&
@@ -395,12 +778,11 @@ export async function runCodemod(paths, options = {}) {
395
778
  return;
396
779
  return bind(leaf, fs.readFileSync(leaf, 'utf8'));
397
780
  });
398
- const output = file.slice(0, -3) + '.octane.ts';
399
- if (code &&
400
- !compile(compiler, code, output, true).some((finding) => finding.severity === 'error') &&
401
- !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)) {
402
784
  generatedHelpers.set(output, code);
403
- return { from: relativeTsImport(from, output) };
785
+ return { from: relativeImport(from, output) };
404
786
  }
405
787
  }
406
788
  return hook;
@@ -409,20 +791,26 @@ export async function runCodemod(paths, options = {}) {
409
791
  const generatedHelpers = new Map();
410
792
  const svgHelpers = new Set();
411
793
  const svgHelper = path.join(helperDir, 'octane-path-svg.ts');
794
+ // Null marks unsupported geometry. A parsed asset records whether its root declares xmlns.
412
795
  const svgAssets = new Map();
796
+ const svgNamespaceWarnings = new Set();
413
797
  let svgHelperCode;
414
798
  function nativeSvgModule(asset, errors, color) {
415
799
  if (!asset.startsWith(root + path.sep) ||
416
800
  asset.split(path.sep).includes('node_modules') ||
417
801
  /[!%?#]/.test(path.relative(root, asset)))
418
802
  return null;
419
- if (!svgAssets.has(asset)) {
803
+ let hasXmlns = svgAssets.get(asset);
804
+ if (hasXmlns === undefined) {
420
805
  const stat = fs.lstatSync(asset, { throwIfNoEntry: false });
421
- svgAssets.set(asset, !!stat?.isFile() &&
422
- fs.realpathSync(asset) === path.join(fs.realpathSync(root), path.relative(root, asset)) &&
423
- !!parseStaticSvg(fs.readFileSync(asset, 'utf8')));
806
+ const svg = stat?.isFile() &&
807
+ fs.realpathSync(asset) === path.join(fs.realpathSync(root), path.relative(root, asset))
808
+ ? parseStaticSvg(fs.readFileSync(asset, 'utf8'))
809
+ : null;
810
+ hasXmlns = svg ? Object.hasOwn(svg.root, 'xmlns') : null;
811
+ svgAssets.set(asset, hasXmlns);
424
812
  }
425
- if (!svgAssets.get(asset))
813
+ if (hasXmlns === null)
426
814
  return null;
427
815
  svgHelperCode ??=
428
816
  fs.readFileSync(new URL('../templates/octane-path-svg.ts', import.meta.url), 'utf8') +
@@ -454,6 +842,8 @@ export async function runCodemod(paths, options = {}) {
454
842
  generatedHelpers.set(sidecar, code);
455
843
  svgHelpers.add(svgHelper);
456
844
  svgHelpers.add(sidecar);
845
+ if (hasXmlns)
846
+ svgNamespaceWarnings.add(asset);
457
847
  return sidecar;
458
848
  }
459
849
  function pathSvgAdapter(file, specifier, errors, color) {
@@ -474,7 +864,7 @@ export async function runCodemod(paths, options = {}) {
474
864
  ? cached.error
475
865
  : 'Two generated adapters need different code at ' + path.relative(root, output);
476
866
  const name = path.relative(root, output);
477
- const ownerOf = (file) => owners.has(ts.sys.useCaseSensitiveFileNames ? file : file.toLowerCase());
867
+ const ownerOf = (file) => owners.has(outputKey(file));
478
868
  // Bundlers can prefer a JavaScript or JSX sibling over our extensionless .ts import.
479
869
  const shadowed = output.endsWith('.ts') &&
480
870
  ['', '.js', '.jsx', '.tsx', '.mjs', '.cjs', '.mts', '.cts', '.json', '.tsrx'].some((ext) => {
@@ -505,6 +895,7 @@ export async function runCodemod(paths, options = {}) {
505
895
  return error;
506
896
  }
507
897
  const results = [];
898
+ const storeHookComponents = new Map();
508
899
  if (options.svgPaths && target === 'tsrx') {
509
900
  // Explicit SVG inputs prepare a native component even if a caller's renderer is unknown.
510
901
  // Directory scans still generate components only for verified JSX uses.
@@ -536,11 +927,42 @@ export async function runCodemod(paths, options = {}) {
536
927
  const extra = [];
537
928
  const reactStoreComponents = new Map();
538
929
  let installedClsx;
539
- const isContext = (specifier, name) => {
540
- if (!specifier.startsWith('.'))
541
- return null;
930
+ let reactJsx;
931
+ const isContext = (specifier, name, local) => {
932
+ if (!specifier.startsWith('.')) {
933
+ if (!contextPaths.length ||
934
+ !esmContextProject ||
935
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
936
+ !contextPaths.some(([start, end]) => end === undefined
937
+ ? specifier === start
938
+ : specifier.startsWith(start) && specifier.endsWith(end)))
939
+ return null;
940
+ const source = localFile(file, specifier, true);
941
+ return source &&
942
+ exports.has(source) &&
943
+ ts.findConfigFile(path.dirname(source), ts.sys.fileExists) === rootProject &&
944
+ (exports.get(source)?.contexts.includes(name) ||
945
+ (name === 'default' ? local : name).endsWith('Context'))
946
+ ? 'review-alias'
947
+ : null;
948
+ }
542
949
  const target = resolveModule(file, specifier, known);
543
- return target ? contextsOf(target.file).has(name) : null;
950
+ if (target)
951
+ return contextsOf(target.file).has(name);
952
+ if (!name.endsWith('Context') ||
953
+ !esmContextProject ||
954
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
955
+ return null;
956
+ const source = localFile(file, specifier, true);
957
+ if (!source)
958
+ return null;
959
+ const direct = path.resolve(path.dirname(file), specifier);
960
+ // A bundler can load a sibling file ahead of TypeScript's directory index.
961
+ return (source === direct || source === direct + path.extname(source)) &&
962
+ ts.findConfigFile(path.dirname(source), ts.sys.fileExists) === rootProject &&
963
+ exportsConstObject(source, name)
964
+ ? false
965
+ : null;
544
966
  };
545
967
  const matchesExport = (index, binding) => {
546
968
  const to = resolveRename(file, binding.module);
@@ -559,9 +981,11 @@ export async function runCodemod(paths, options = {}) {
559
981
  : (module, name, safeUses) => {
560
982
  if (!unportedName(module, file))
561
983
  return null;
562
- const plan = planStoreHook(module, name, file);
984
+ const plan = planStoreHook(module, name, file)?.plan;
563
985
  if (!plan ||
564
- !safeUses((source, name) => {
986
+ !safeUses((source, name, selection) => {
987
+ if (selection)
988
+ return changedJsxExport(file, source, name, selection) ? 'opaque' : false;
565
989
  const input = inputFactory(file, source, name, plan.isSharedExport);
566
990
  if (!input)
567
991
  return false;
@@ -573,7 +997,7 @@ export async function runCodemod(paths, options = {}) {
573
997
  (originalReact ??=
574
998
  ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject &&
575
999
  !!originalModule(file, 'react')) &&
576
- helperFunction(file, source, name)))
1000
+ helperFunction(file, source, name), (source, name) => retainedStoreArgument(file, source, name)))
577
1001
  return null;
578
1002
  storeTemplates ??= new Map([
579
1003
  [
@@ -602,6 +1026,7 @@ export async function runCodemod(paths, options = {}) {
602
1026
  .replace(/\.ts$/, '');
603
1027
  return { from: relative.startsWith('.') ? relative : './' + relative, name: plan.name };
604
1028
  };
1029
+ let originalSvgServer;
605
1030
  const svgAdapter = options.svgPaths && renames.has(file)
606
1031
  ? (specifier, color) => pathSvgAdapter(file, specifier, svgErrors, color)
607
1032
  : undefined;
@@ -617,12 +1042,79 @@ export async function runCodemod(paths, options = {}) {
617
1042
  reactIntlAdapter: intl,
618
1043
  forwardedText: (module, name, prop, ordinaryCaller, through) => forwardedProp(file, module, name, prop, through ? 'forwarded-text' : 'text', ordinaryCaller),
619
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,
620
1059
  get originalReact() {
621
1060
  return installedReact(file);
622
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'),
1092
+ initializerResourceHint: renames.has(file)
1093
+ ? (module, name, retainedOnly) => initializerResourceHint(file, module, name, retainedOnly)
1094
+ : undefined,
623
1095
  localReactHook: renames.has(file)
624
1096
  ? (module, name, nativeOnly) => localReactHook(file, module, name, nativeOnly)
625
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,
1107
+ localReactRootComponent: renames.has(file)
1108
+ ? (module, name) => {
1109
+ const hook = localReactHook(file, module, name, false);
1110
+ if (typeof hook === 'string' &&
1111
+ hook !== 'useEffect' &&
1112
+ hook !== 'useEffectEvent' &&
1113
+ installedReact(file, 'react-dom') &&
1114
+ originalModule(file, 'react-dom/client'))
1115
+ return hook;
1116
+ }
1117
+ : undefined,
626
1118
  strong,
627
1119
  strictNullChecks: strictConfig !== null,
628
1120
  get types() {
@@ -630,12 +1122,24 @@ export async function runCodemod(paths, options = {}) {
630
1122
  },
631
1123
  resolveSpecifier: (specifier) => resolveRename(file, specifier) ??
632
1124
  resolveBinding(specifier, file, bindingProject, packages, notes),
1125
+ bindingExports: (from, to) => bindingExports(file, from, to),
1126
+ recordBindingRewrite: (from, to) => packages.set(from, to),
633
1127
  isContext,
634
1128
  elementChild: !elementExports.size
635
1129
  ? undefined
636
- : (binding) => typeof binding === 'number'
637
- ? (exports.get(file)?.elementChildren?.some((x) => x.start === binding) ?? false)
638
- : 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
+ },
639
1143
  descriptorChild: descriptorExports.size
640
1144
  ? (binding) => matchesExport(descriptorExports, binding)
641
1145
  : undefined,
@@ -650,6 +1154,13 @@ export async function runCodemod(paths, options = {}) {
650
1154
  forwardedRender: options.svgPaths && renames.has(file)
651
1155
  ? (module, name, prop, depth) => forwardedProp(file, module, name, prop, 'render', true, depth)
652
1156
  : undefined,
1157
+ get automaticReactJsx() {
1158
+ return (reactJsx ??=
1159
+ !/@jsx(?:ImportSource|Runtime|Frag)?\b/i.test(source) &&
1160
+ automaticReactJsx(file) &&
1161
+ !!originalModule(file, 'react/jsx-runtime') &&
1162
+ installedReact(file));
1163
+ },
653
1164
  get installedClsx() {
654
1165
  if (installedClsx === undefined) {
655
1166
  const target = originalModule(file, 'clsx');
@@ -669,6 +1180,12 @@ export async function runCodemod(paths, options = {}) {
669
1180
  return real.endsWith('.module.css') ? real : undefined;
670
1181
  },
671
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
+ },
672
1189
  fixedColorSvgAdapter: svgAdapter,
673
1190
  reactStoreComponent: (specifier) => {
674
1191
  if (!reactStoreComponents.has(specifier))
@@ -694,6 +1211,20 @@ export async function runCodemod(paths, options = {}) {
694
1211
  }
695
1212
  }
696
1213
  const result = transform();
1214
+ if (result.exports.storeHookComponents)
1215
+ storeHookComponents.set(file, result.exports.storeHookComponents);
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 ||
1219
+ note.rule === MAP_PARAMETER_TDZ ||
1220
+ note.rule === MAP_CALLBACK_SCOPE ||
1221
+ note.rule === CONTEXT_ALIAS ||
1222
+ note.rule === CONTEXT_PROVIDER_GETTER ||
1223
+ note.rule === INTL_PROVIDER_DEFAULTS ||
1224
+ note.rule === ELEMENT_CHILD_ALIAS ||
1225
+ note.rule === REACT_TYPE_PROJECTION);
1226
+ if (write && blockedTransform)
1227
+ return blockedWrite(root, unchangedFile(path.relative(root, file), source, blockedTransform), compiler?.from);
697
1228
  for (const message of [...storeErrors, ...svgErrors]) {
698
1229
  const note = {
699
1230
  rule: svgErrors.has(message) ? 'svg-paths' : 'store-hook',
@@ -776,33 +1307,531 @@ export async function runCodemod(paths, options = {}) {
776
1307
  // Configs and scripts name modules by path too, such as Vite's
777
1308
  // `server.warmup.clientFiles`, including those outside the migrated paths.
778
1309
  const byFile = new Map(results.map((result) => [path.join(root, result.file), result]));
779
- for (const file of renames.size
780
- ? collect(root, (name) => SOURCE.test(name) || isTsrx(name))
1310
+ // React executes imported island components with their original module dependencies.
1311
+ const edited = new Set(results.filter((r) => r.changed).map((r) => path.join(root, r.file)));
1312
+ const inspected = new Set();
1313
+ let physicalEdits;
1314
+ let islandConflict;
1315
+ function originalOctaneBridge(file, specifier) {
1316
+ const installed = readInstalled(path.dirname(file), 'octane');
1317
+ const module = originalModule(file, specifier, bindingOptions(file));
1318
+ return (installed?.manifest.name === 'octane' &&
1319
+ module?.packageId?.name === 'octane' &&
1320
+ fs.realpathSync(module.resolvedFileName).startsWith(fs.realpathSync(installed.dir) + path.sep));
1321
+ }
1322
+ function originalOctaneRuntime(file, specifier, options = config) {
1323
+ const installed = readInstalled(path.dirname(file), 'octane');
1324
+ const module = originalModule(file, specifier, options);
1325
+ const adapterRuntime = readInstalled(helperDir, 'octane');
1326
+ if (installed?.manifest.name !== 'octane' ||
1327
+ module?.packageId?.name !== 'octane' ||
1328
+ !adapterRuntime)
1329
+ return false;
1330
+ try {
1331
+ const source = fs.realpathSync(module.resolvedFileName);
1332
+ const directory = fs.realpathSync(installed.dir) + path.sep;
1333
+ if (fs.realpathSync(adapterRuntime.dir) + path.sep !== directory)
1334
+ return false;
1335
+ const targets = runtimeTargets(specifier, source, file);
1336
+ return (source.startsWith(directory) &&
1337
+ targets.length > 0 &&
1338
+ targets.every((target) => fs.realpathSync(target).startsWith(directory)));
1339
+ }
1340
+ catch {
1341
+ return false;
1342
+ }
1343
+ }
1344
+ function storeRootNote({ name, line }, server) {
1345
+ const component = name === 'default' ? 'default export' : name;
1346
+ return {
1347
+ rule: 'store-hook',
1348
+ severity: 'warning',
1349
+ line,
1350
+ message: server
1351
+ ? `If this server call runs standalone and reaches the migrated ${component}'s store hook, it may need NativeStoreProvider with its original store context and value.`
1352
+ : `If the migrated ${component}'s store hook reads context, this standalone Octane root needs NativeStoreProvider with its original store context and value.`,
1353
+ };
1354
+ }
1355
+ function originalReactEntry(file, name, options = config) {
1356
+ const packageRoot = packageName(name);
1357
+ const types = originalModule(file, name, options)?.packageId?.name;
1358
+ if (types !== packageRoot && types !== `@types/${packageRoot}`)
1359
+ return false;
1360
+ const installed = readInstalled(path.dirname(file), packageRoot);
1361
+ try {
1362
+ return (installed?.manifest.name === packageRoot &&
1363
+ fs
1364
+ .realpathSync(createRequire(file).resolve(name))
1365
+ .startsWith(fs.realpathSync(installed.dir) + path.sep));
1366
+ }
1367
+ catch {
1368
+ return false;
1369
+ }
1370
+ }
1371
+ const reverseIslands = 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();
1513
+ function checkLinkedRename(file, issuer) {
1514
+ const selected = linkedRename(file);
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
+ }
1518
+ }
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;
1526
+ function protectIslandModule(issuer, specifier, owner) {
1527
+ const file = ts.resolveModuleName(specifier, issuer, { moduleResolution: ts.ModuleResolutionKind.Bundler, ...bindingOptions(issuer) }, ts.sys).resolvedModule?.resolvedFileName;
1528
+ if (!file || /\.d\.[cm]?ts$/.test(file) || !SOURCE.test(file))
1529
+ return;
1530
+ const physical = fs.realpathSync(file);
1531
+ if (inspected.has(physical))
1532
+ return;
1533
+ inspected.add(physical);
1534
+ // A workspace import and an explicitly selected path may reach the same file through different links.
1535
+ if (!physicalEdits) {
1536
+ physicalEdits = new Map();
1537
+ for (const selected of edited) {
1538
+ const real = fs.realpathSync(selected);
1539
+ const group = physicalEdits.get(real) ?? [];
1540
+ group.push(byFile.get(selected));
1541
+ physicalEdits.set(real, group);
1542
+ }
1543
+ }
1544
+ for (const result of physicalEdits.get(physical) ?? []) {
1545
+ const note = {
1546
+ rule: 'react-compat',
1547
+ severity: 'error',
1548
+ line: 1,
1549
+ message: `Keep ${result.file} in React: the authored React island in ${path.relative(root, owner)} uses its original implementation. Exclude this module from the migration.`,
1550
+ };
1551
+ result.notes.push(note);
1552
+ if (write && !islandConflict)
1553
+ islandConflict = unchangedFile(result.file, fs.readFileSync(file, 'utf8'), note);
1554
+ }
1555
+ if (physical.split(path.sep).includes('node_modules'))
1556
+ return;
1557
+ for (const module of executableImports(file, fs.readFileSync(file, 'utf8'), !!bindingOptions(file)?.verbatimModuleSyntax))
1558
+ protectIslandModule(file, module, owner);
1559
+ }
1560
+ const routesEntry = routerEntries?.[1];
1561
+ for (const file of edited.size || renames.size
1562
+ ? new Set([...collect(root, (name) => SOURCE.test(name) || isTsrx(name)), ...files])
781
1563
  : []) {
782
- if (renames.has(file) || conflicts.has(file))
1564
+ const source = fs.readFileSync(file, 'utf8');
1565
+ if (edited.size && importsReactBridge(source)) {
1566
+ for (const module of await islandComponents(file, source, (spec) => bindingProject.original(file, spec)))
1567
+ protectIslandModule(file, module, file);
1568
+ }
1569
+ if (islandConflict)
1570
+ return blockedWrite(root, islandConflict, compiler?.from);
1571
+ if (!renames.size || linkedRename(file) || conflicts.has(file))
783
1572
  continue;
784
1573
  const result = byFile.get(file);
785
- const paths = rewriteModulePaths(result?.code ?? fs.readFileSync(file, 'utf8'), file, root, renames, resolveRename);
786
- if (!paths)
1574
+ const selected = renames.has(file);
1575
+ const serverBridge = 'octane/react/server';
1576
+ const originalHost = (bridge) => automaticReactJsx(file) &&
1577
+ originalOctaneBridge(file, bridge) &&
1578
+ originalReactEntry(file, 'react/jsx-runtime');
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;
1588
+ const note = {
1589
+ rule: 'react-compat',
1590
+ severity: 'error',
1591
+ line: edge.line,
1592
+ message: 'Keep the authored OctaneCompat host in React. Exclude this module from the migration.',
1593
+ };
1594
+ if (write)
1595
+ return blockedWrite(root, unchangedFile(result.file, source, note), compiler?.from);
1596
+ result.notes.push(note);
1597
+ break;
1598
+ }
1599
+ }
1600
+ if (selected &&
1601
+ storeHookComponents.size &&
1602
+ result?.rules['server-render'] &&
1603
+ automaticReactJsx(file) &&
1604
+ originalReactEntry(file, 'react-dom/server') &&
1605
+ originalOctaneBridge(file, 'octane/server')) {
1606
+ for (const edge of reactServerComponents(file, source, (module) => originalReactEntry(file, module), true)) {
1607
+ const leaf = renamed(file, edge.module)?.file;
1608
+ if (!leaf ||
1609
+ leaf !== path.resolve(path.dirname(file), edge.module) ||
1610
+ !storeHookComponents.get(leaf)?.includes(edge.name))
1611
+ continue;
1612
+ result.notes.push(storeRootNote(edge, true));
1613
+ }
1614
+ }
1615
+ const paths = rewriteModulePaths(selected ? source : (result?.code ?? source), file, root, renames, scanRename, selected ? undefined : checkLinkedRename);
1616
+ const retainedJsx = (paths || renamedJsx) && !known.has(file) && /\.[jt]sx$/.test(file) && source.includes('<');
1617
+ if (!paths && !retainedJsx)
787
1618
  continue;
788
- const rules = { ...result?.rules, 'module-paths': paths.count };
789
- if (result)
790
- Object.assign(result, { code: paths.code, changed: true, rules });
791
- else {
792
- const name = path.relative(root, file);
793
- results.push({
794
- file: name,
795
- output: name,
796
- changed: true,
797
- rules,
798
- notes: [],
799
- strong: null,
800
- strongFixes: [],
801
- diagnostics: [],
802
- code: paths.code,
803
- });
1619
+ const storeNotes = result?.notes ?? [];
1620
+ if (paths &&
1621
+ storeHookComponents.size &&
1622
+ SOURCE.test(file) &&
1623
+ ((source.includes('octane') &&
1624
+ (source.includes('createRoot') ||
1625
+ source.includes('hydrateRoot') ||
1626
+ (source.includes('octane/server') &&
1627
+ (source.includes('renderToString') || source.includes('renderToStaticMarkup'))))) ||
1628
+ source.includes('\\')) &&
1629
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject) {
1630
+ const originalRuntimes = new Map();
1631
+ for (const edge of octaneRootComponents(file, source)) {
1632
+ const leaf = renamed(file, edge.module)?.file;
1633
+ if (!leaf ||
1634
+ leaf !== path.resolve(path.dirname(file), edge.module) ||
1635
+ !storeHookComponents.get(leaf)?.includes(edge.name))
1636
+ continue;
1637
+ if (!originalRuntimes.has(edge.runtime))
1638
+ originalRuntimes.set(edge.runtime, originalOctaneRuntime(file, edge.runtime));
1639
+ if (originalRuntimes.get(edge.runtime))
1640
+ storeNotes.push(storeRootNote(edge, edge.runtime === 'octane/server'));
1641
+ }
1642
+ }
1643
+ if (selected)
1644
+ continue;
1645
+ const rules = paths ? { ...result?.rules, 'module-paths': paths.count } : {};
1646
+ const name = path.relative(root, file);
1647
+ const host = result ?? {
1648
+ file: name,
1649
+ output: name,
1650
+ changed: !!paths,
1651
+ rules,
1652
+ notes: storeNotes,
1653
+ strong: null,
1654
+ strongFixes: [],
1655
+ diagnostics: [],
1656
+ code: paths?.code ?? source,
1657
+ };
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('\\'));
1687
+ if (!edited.has(file) &&
1688
+ (retainedJsx || retainedServer || retainedElement) &&
1689
+ ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject) {
1690
+ const edges = [];
1691
+ if (retainedJsx && automaticReactJsx(file) && originalReactEntry(file, 'react/jsx-runtime'))
1692
+ for (const edge of retainedReactComponentReturns(file, source))
1693
+ edges.push({ ...edge, renderer: 'JSX' });
1694
+ if (retainedServer && originalReactEntry(file, 'react-dom/server'))
1695
+ for (const edge of reactServerComponents(file, source, (module) => module === 'react'
1696
+ ? installedReact(file)
1697
+ : automaticReactJsx(file) && originalReactEntry(file, module)))
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;
1703
+ for (const edge of edges) {
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')))
1747
+ continue;
1748
+ const leaf = byFile.get(match.file);
1749
+ if (!leaf?.output.endsWith('.tsrx'))
1750
+ continue;
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
+ }
1774
+ }
1775
+ const note = {
1776
+ rule: 'react-compat',
1777
+ severity: 'warning',
1778
+ line: edge.line,
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.`,
1786
+ };
1787
+ host.notes.push(note);
1788
+ leaf.notes.push({ ...note, line: 1 });
1789
+ }
1790
+ }
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)) {
1798
+ const match = edge.module.startsWith('.') && renamed(file, edge.module);
1799
+ if (!match)
1800
+ continue;
1801
+ const leaf = byFile.get(match.file);
1802
+ if (!leaf?.output.endsWith('.tsrx'))
1803
+ continue;
1804
+ let names = reverseIslands.get(match.file);
1805
+ if (!names) {
1806
+ names = await reverseIslandExports(leaf.output, leaf.code, (module) => originalOctaneBridge(match.file, module));
1807
+ reverseIslands.set(match.file, names);
1808
+ }
1809
+ if (!names.has(edge.name))
1810
+ continue;
1811
+ const note = {
1812
+ rule: 'react-compat',
1813
+ severity: 'error',
1814
+ line: edge.line,
1815
+ message: `React SSR cannot render ${leaf.output} inside OctaneCompat because it returns a ReactCompat island.`,
1816
+ };
1817
+ if (write)
1818
+ return blockedWrite(root, unchangedFile(name, source, note), compiler?.from);
1819
+ host.notes.push(note);
1820
+ leaf.notes.push({
1821
+ ...note,
1822
+ line: 1,
1823
+ message: `${note.message} Server host: ${name}:${edge.line}.`,
1824
+ });
1825
+ }
804
1826
  }
805
1827
  }
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);
1831
+ if (write)
1832
+ return blockedWrite(root, conflict, compiler?.from);
1833
+ byFile.get(file)?.notes.push(...conflict.notes);
1834
+ }
806
1835
  const intlConsumer = results.find((file) => file.rules['react-intl']);
807
1836
  const svg = generatedHelpers.has(svgHelper) && checkedHelpers.get(svgHelper);
808
1837
  if (write) {
@@ -879,7 +1908,17 @@ export async function runCodemod(paths, options = {}) {
879
1908
  strongFixes: [],
880
1909
  });
881
1910
  }
882
- const html = rewriteEntryPages(root, paths.map((entry) => path.resolve(entry)), renames, write);
1911
+ for (const asset of svgNamespaceWarnings)
1912
+ results.push(unchangedFile(path.relative(root, asset), '', {
1913
+ rule: 'svg-paths',
1914
+ severity: 'warning',
1915
+ line: 1,
1916
+ message: 'If the React SVG loader forwards the authored xmlns prop, a fresh Octane mount places it in the XMLNS namespace while React uses the null namespace. Review code that reads the attribute namespace.',
1917
+ }));
1918
+ if (write)
1919
+ for (const [page, next] of pages)
1920
+ fs.writeFileSync(page, next);
1921
+ const html = [...pages.keys()].map((page) => path.relative(root, page));
883
1922
  const dependencies = addBindings(root, packages, write);
884
1923
  if (write) {
885
1924
  for (const result of results) {
@@ -906,8 +1945,15 @@ export async function runCodemod(paths, options = {}) {
906
1945
  };
907
1946
  }
908
1947
  // Hash only previously shipped helpers. A locally edited file belongs to the application.
909
- const PREVIOUS_INTL_HASHES = ['07ec8e00847ebc6f0bd5ffeb14bc064aa23df42d1d3db5102344c739f54dca98'];
1948
+ const PREVIOUS_INTL_HASHES = [
1949
+ '07ec8e00847ebc6f0bd5ffeb14bc064aa23df42d1d3db5102344c739f54dca98',
1950
+ '9cd8a44e85984cab413e73e63999156ac8508518c109cf53c26449c54a973043',
1951
+ 'b2c10462518bfabfd9aecc774696c8a594b456b4752b6e753cd6311f889fba0e',
1952
+ '37cdc7e5d0f17d4d0504bf4a948b724559c584650af441e000563f8ebe7e33e6',
1953
+ ];
910
1954
  const PREVIOUS_SVG_HASHES = [
1955
+ '90bc12d849bbed4f1932e9e7ab5b939242237a4b8876d4c0f01e093a7d5b8c80',
1956
+ '9068d68b34a68b8dd4199764d16c174f1cf9cbf79172396b1f8960ddf5217916',
911
1957
  '893474efdb9186489e6c0113d1dedaaf9b7d2a0443f8b5d04048680610696bdf',
912
1958
  '88de6c9053abe0f94934ebb7cd54cd681e4d2544b3facab0dbdf3d4c588649a5',
913
1959
  '62ef936e3ce64cfe809297e08e74538f0c409f0bde6a926ca7b88de93161a38d',
@@ -916,6 +1962,7 @@ const PREVIOUS_SVG_HASHES = [
916
1962
  '3becf859871f17914f6f0631e8db8058aa4932fd4a9817718b98eb247a902b24',
917
1963
  '1dbf34eea75c07c21c8ab3814d54e58115e833aa140fc5f34b5f2cba91d018c3',
918
1964
  'b53641cfbe77205a174179b4d0de60989b34cf4073690fc98536c22a68ee844a',
1965
+ 'febbdb7b04b5240afe5b417d134e52d963aa077780e54f5ef0582bc581f4dc70',
919
1966
  ];
920
1967
  function inspectAdapter(file, source, previous) {
921
1968
  const stat = fs.lstatSync(file, { throwIfNoEntry: false });
@@ -1044,6 +2091,118 @@ function collect(entry, test = isSource) {
1044
2091
  function isTsrx(name) {
1045
2092
  return name.endsWith('.tsrx');
1046
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
+ }
1047
2206
  /** The compiler options of the tsconfig that governs `root`, or null. */
1048
2207
  function tsconfigOptions(root) {
1049
2208
  const file = ts.findConfigFile(root, ts.sys.fileExists);
@@ -1077,8 +2236,11 @@ function resolveModule(from, specifier, files) {
1077
2236
  return null;
1078
2237
  }
1079
2238
  function relativeTsImport(from, to) {
1080
- const specifier = path.relative(path.dirname(from), to).split(path.sep).join('/').slice(0, -3);
1081
- 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;
1082
2244
  }
1083
2245
  /** Only relative assets and unambiguous directory aliases have a local file to inspect. */
1084
2246
  function svgAsset(root, dir, specifier, config) {
@@ -1108,7 +2270,7 @@ function svgAsset(root, dir, specifier, config) {
1108
2270
  * Resolve against the files on disk before any rename, including modules
1109
2271
  * outside the selected paths that could win an extensionless lookup.
1110
2272
  */
1111
- function renamedImports(root, config, renames) {
2273
+ function renamedImports(root, config, renames, issuerOptions, linkedRename) {
1112
2274
  const options = {
1113
2275
  moduleResolution: ts.ModuleResolutionKind.Bundler,
1114
2276
  ...config,
@@ -1123,7 +2285,18 @@ function renamedImports(root, config, renames) {
1123
2285
  : null;
1124
2286
  return { start, end, directory };
1125
2287
  });
1126
- return (from, specifier) => {
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) => {
1127
2300
  const matches = specifier.startsWith('.')
1128
2301
  ? []
1129
2302
  : aliases.filter(({ start, end }) => end === undefined
@@ -1131,32 +2304,76 @@ function renamedImports(root, config, renames) {
1131
2304
  : specifier.startsWith(start) && specifier.endsWith(end));
1132
2305
  if (!renames.size || (!specifier.startsWith('.') && !matches.length))
1133
2306
  return null;
1134
- const resolved = ts.resolveModuleName(specifier, from, options, ts.sys, cache).resolvedModule;
1135
- const target = resolved && renames.get(resolved.resolvedFileName);
1136
- if (!target)
2307
+ const resolved = ts.resolveModuleName(specifier, from, options, ts.sys, cache, undefined, commonJs ? ts.ModuleKind.CommonJS : undefined).resolvedModule;
2308
+ // TypeScript returns slash-delimited names, including on Windows.
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
+ }
2322
+ const target = file && renames.get(file);
2323
+ if (!target) {
2324
+ if (file)
2325
+ unmatched?.(file);
2326
+ return null;
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);
1137
2334
  return null;
2335
+ }
1138
2336
  // Only a single directory alias preserves the specifier's suffix.
1139
2337
  // A fixed alias or fallback list may resolve elsewhere after a rename.
1140
2338
  const alias = matches.length === 1 ? matches[0] : null;
1141
2339
  if (alias?.directory && target.startsWith(alias.directory)) {
1142
2340
  return {
1143
- file: resolved.resolvedFileName,
2341
+ file,
1144
2342
  specifier: alias.start + target.slice(alias.directory.length).split(path.sep).join('/'),
1145
2343
  };
1146
2344
  }
1147
2345
  const relative = path.relative(path.dirname(from), target).split(path.sep).join('/');
1148
2346
  return {
1149
- file: resolved.resolvedFileName,
2347
+ file,
1150
2348
  specifier: relative.startsWith('../') ? relative : './' + relative,
1151
2349
  };
1152
2350
  };
1153
2351
  }
1154
- 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) {
1155
2354
  const stem = file.slice(0, -path.extname(file).length);
1156
2355
  const dir = path.dirname(stem);
1157
2356
  const stems = path.basename(stem) === 'index' ? [stem, dir] : [stem, path.join(stem, 'index')];
1158
- if (stems.some((base) => ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts'].some((ext) => base + ext !== file && fs.existsSync(base + ext))) ||
1159
- 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))
1160
2377
  return () => false;
1161
2378
  const { sf, checker } = bind(file, fs.readFileSync(file, 'utf8'));
1162
2379
  const module = checker.getSymbolAtLocation(sf);
@@ -1222,19 +2439,28 @@ function resolveBinding(specifier, file, project, packages, notes) {
1222
2439
  const entry = DATA.bindings.find((candidate) => candidate.name === binding);
1223
2440
  const subpath = target.slice(binding.length) + specifier.slice(name.length);
1224
2441
  const served = entry && entry.exports.some((key) => serves(key, `.${subpath}`));
1225
- if (target !== binding) {
2442
+ const reactMotion = isReactMotion(specifier);
2443
+ if (target !== binding || reactMotion) {
1226
2444
  const shadowed = [specifier, binding + subpath].find((name) => !project.original(file, name));
1227
- const message = shadowed
1228
- ? `Resolve \`${shadowed}\` to its original package before migrating this import.`
1229
- : !served || !canUseBindingSubpath(file, project.root, binding, subpath, entry.version)
1230
- ? `Install a version of \`${binding}\` that exports \`.${subpath}\` before migrating this import.`
1231
- : null;
2445
+ let message;
2446
+ if (shadowed) {
2447
+ message = `Resolve \`${shadowed}\` to its original package before migrating this import.`;
2448
+ }
2449
+ else if (reactMotion && project.motionExports(file) === null) {
2450
+ message = `Could not check the exports of \`${MOTION_BINDING}\`. Install the intended binding version and rerun the codemod.`;
2451
+ }
2452
+ else if (subpath &&
2453
+ (!served || !canUseBindingSubpath(file, project.root, binding, subpath, entry.version))) {
2454
+ message = `Install a version of \`${binding}\` that exports \`.${subpath}\` before migrating this import.`;
2455
+ }
1232
2456
  if (message) {
1233
2457
  notes.push({ rule: 'bindings', severity: 'error', line: 1, message });
1234
2458
  return null;
1235
2459
  }
1236
2460
  }
1237
- packages.set(name, binding);
2461
+ // Partial bindings are recorded only after their export check accepts a rewrite.
2462
+ if (!reactMotion)
2463
+ packages.set(name, binding);
1238
2464
  // An aggregate binding (`@octanejs/visx`, for `@visx/visx`) serves each
1239
2465
  // package of its scope from a subpath: `@visx/hierarchy` is
1240
2466
  // `@octanejs/visx/hierarchy`.
@@ -1265,6 +2491,43 @@ function resolveBinding(specifier, file, project, packages, notes) {
1265
2491
  });
1266
2492
  return binding + subpath;
1267
2493
  }
2494
+ /** Read the published binding's authored ESM root without loading it. */
2495
+ function readMotionExports(manifest, dir) {
2496
+ const pkg = record(manifest);
2497
+ const target = record(pkg.exports)['.'];
2498
+ if (pkg.name !== MOTION_BINDING ||
2499
+ pkg.type !== 'module' ||
2500
+ typeof target !== 'string' ||
2501
+ !target.startsWith('./') ||
2502
+ !target.endsWith('.ts') ||
2503
+ target.endsWith('.d.ts'))
2504
+ return null;
2505
+ const entry = path.resolve(dir, target);
2506
+ if (!entry.startsWith(dir + path.sep) ||
2507
+ !ts.sys.fileExists(entry) ||
2508
+ !fs.realpathSync(entry).startsWith(dir + path.sep))
2509
+ return null;
2510
+ const program = ts.createProgram([entry], {
2511
+ module: ts.ModuleKind.ESNext,
2512
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
2513
+ target: ts.ScriptTarget.ESNext,
2514
+ skipLibCheck: true,
2515
+ types: [],
2516
+ });
2517
+ const source = program.getSourceFile(entry);
2518
+ if (!source)
2519
+ return null;
2520
+ const checker = program.getTypeChecker();
2521
+ const module = checker.getSymbolAtLocation(source);
2522
+ if (!module)
2523
+ return null;
2524
+ return new Set(checker
2525
+ .getExportsOfModule(module)
2526
+ .filter((symbol) => MOTION_EXPORTS.has(symbol.name) &&
2527
+ (!(symbol.flags & ts.SymbolFlags.Alias) ||
2528
+ checker.getAliasedSymbol(symbol).declarations?.length))
2529
+ .map(({ name }) => name));
2530
+ }
1268
2531
  function canUseBindingSubpath(file, root, binding, subpath, version) {
1269
2532
  const dir = path.dirname(file);
1270
2533
  const installed = readInstalled(dir, binding);
@@ -1285,20 +2548,26 @@ function canUseBindingSubpath(file, root, binding, subpath, version) {
1285
2548
  return (resolved.startsWith(installed.dir + path.sep) &&
1286
2549
  fs.statSync(resolved, { throwIfNoEntry: false })?.isFile());
1287
2550
  }
1288
- // New dependencies use the catalog version. For a different declaration,
1289
- // require an installed export before rewriting its imports.
2551
+ // New dependencies use the catalog version. Other pins need an installed export proof.
2552
+ return bindingDeclarations(root, dir, binding).every((spec) => catalogBindingVersion(spec, version));
2553
+ }
2554
+ function bindingDeclarations(root, dir, binding) {
2555
+ const versions = [];
1290
2556
  for (const project of new Set([root, findRoot(dir)])) {
1291
2557
  const manifestFile = path.join(project, 'package.json');
1292
2558
  if (!fs.existsSync(manifestFile))
1293
2559
  continue;
1294
2560
  const manifest = record(JSON.parse(fs.readFileSync(manifestFile, 'utf8')));
1295
- if (DEPENDENCY_FIELDS.some((field) => {
2561
+ for (const field of DEPENDENCY_FIELDS) {
1296
2562
  const spec = record(manifest[field])[binding];
1297
- return spec !== undefined && spec !== version && spec !== `^${version}`;
1298
- }))
1299
- return false;
2563
+ if (spec !== undefined)
2564
+ versions.push(spec);
2565
+ }
1300
2566
  }
1301
- return true;
2567
+ return versions;
2568
+ }
2569
+ function catalogBindingVersion(spec, version) {
2570
+ return spec === version || spec === `^${version}`;
1302
2571
  }
1303
2572
  /**
1304
2573
  * Whether a package `exports` key serves a subpath, directly or through a
@@ -1319,14 +2588,16 @@ function catalogName(specifier) {
1319
2588
  const parts = specifier.split('/');
1320
2589
  for (let length = parts.length; length > 0; length--) {
1321
2590
  const candidate = parts.slice(0, length).join('/');
1322
- if (candidate in CATALOG)
2591
+ if (candidate === 'motion/react' && candidate !== specifier)
2592
+ continue;
2593
+ // Lottie's exported view still needs explicit renderer ownership at its callers.
2594
+ if (candidate !== 'lottie-react' && candidate in CATALOG)
1323
2595
  return candidate;
1324
2596
  }
1325
2597
  return null;
1326
2598
  }
1327
2599
  /**
1328
- * The React package a specifier names when Octane has no binding for it, or
1329
- * null.
2600
+ * The React package a specifier names when the codemod keeps it on React, or null.
1330
2601
  * @param from the importing module
1331
2602
  */
1332
2603
  function unportedName(specifier, from) {
@@ -1354,6 +2625,21 @@ function isRecord(value) {
1354
2625
  function record(value) {
1355
2626
  return isRecord(value) ? value : {};
1356
2627
  }
2628
+ /** A shared declaration entry can hide an executable branch from TypeScript resolution. */
2629
+ function hasRuntimeExportCondition(exports, conditions) {
2630
+ const map = record(exports);
2631
+ const root = Object.keys(map).some((key) => key.startsWith('.')) ? map['.'] : exports;
2632
+ function walk(value, matched) {
2633
+ if (typeof value === 'string' || value === null)
2634
+ return matched;
2635
+ if (Array.isArray(value))
2636
+ return value.some((entry) => walk(entry, matched));
2637
+ return Object.entries(record(value)).some(([key, entry]) => key !== 'types' &&
2638
+ !key.startsWith('types@') &&
2639
+ walk(entry, matched || conditions.includes(key)));
2640
+ }
2641
+ return walk(root, false);
2642
+ }
1357
2643
  /**
1358
2644
  * Add the bindings the migrated code imports to the project's package.json,
1359
2645
  * each at its catalog version and in the field that lists the React package it
@@ -1452,40 +2738,175 @@ function rendersWithReact(name, from) {
1452
2738
  * Point `<script src>` in HTML entry pages at renamed modules.
1453
2739
  * @param targets the paths being migrated
1454
2740
  */
1455
- function rewriteEntryPages(root, targets, renames, write) {
1456
- const updated = [];
1457
- for (const page of findHtml(root, targets)) {
1458
- const html = fs.readFileSync(page, 'utf8');
1459
- const next = html.replace(/(<script\b[^>]*\bsrc=)(["'])([^"']+)\2/g, (match, open, quote, src) => {
1460
- // Vite serves `/` from the page's own directory, as it does `./`.
1461
- const file = path.join(path.dirname(page), src);
1462
- const renamed = renames.get(file);
1463
- if (!renamed)
1464
- return match;
1465
- return open + quote + src.replace(/\.[jt]sx?$/, '.tsrx') + quote;
1466
- });
1467
- if (next !== html) {
1468
- updated.push(path.relative(root, page));
1469
- if (write)
1470
- fs.writeFileSync(page, next);
2741
+ async function planEntryPages(root, targets, renames, unmatched) {
2742
+ const updated = new Map();
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)) {
2804
+ unmatched(file, page);
2805
+ continue;
2806
+ }
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);
1471
2813
  }
2814
+ if (next !== source)
2815
+ updated.set(page, next);
1472
2816
  }
1473
2817
  return updated;
1474
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
+ }
1475
2893
  /**
1476
2894
  * Follow imports outside the migrated paths as well as exact path strings
1477
2895
  * in scripts and configs. Parse TSRX importers with their own grammar so
1478
2896
  * template text that looks like an import remains text.
1479
2897
  */
1480
- function rewriteModulePaths(code, file, root, renames, resolveRename) {
2898
+ function rewriteModulePaths(code, file, root, renames, resolveRename, unmatched) {
1481
2899
  const edits = [];
1482
2900
  function literal(value, start, end, moduleSource) {
1483
2901
  if (!moduleSource) {
1484
2902
  const ext = SOURCE.exec(value)?.[0];
1485
- if (ext &&
1486
- code.slice(end - 1 - ext.length, end - 1) === ext &&
1487
- [path.dirname(file), root].some((dir) => renames.has(path.join(dir, value)))) {
1488
- edits.push({ start: end - 1 - ext.length, end: end - 1, text: '.tsrx' });
2903
+ if (ext && code.slice(end - 1 - ext.length, end - 1) === ext) {
2904
+ const candidates = [path.dirname(file), root].map((dir) => path.join(dir, value));
2905
+ if (candidates.some((candidate) => renames.has(candidate)))
2906
+ edits.push({ start: end - 1 - ext.length, end: end - 1, text: '.tsrx' });
2907
+ else
2908
+ for (const candidate of candidates)
2909
+ unmatched?.(candidate, file);
1489
2910
  }
1490
2911
  return;
1491
2912
  }
@@ -1531,9 +2952,30 @@ function rewriteModulePaths(code, file, root, renames, resolveRename) {
1531
2952
  }
1532
2953
  else {
1533
2954
  const sf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
2955
+ const mayRequire = file.endsWith('.js') && !ts.isExternalModule(sf);
2956
+ let requires;
1534
2957
  const visit = (node) => {
1535
2958
  if (ts.isStringLiteralLike(node)) {
1536
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
+ }
1537
2979
  const moduleSource = ((ts.isImportDeclaration(p) || ts.isExportDeclaration(p)) &&
1538
2980
  p.moduleSpecifier === node) ||
1539
2981
  ts.isExternalModuleReference(p) ||