@octanejs/codemod 0.1.4 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +295 -4
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +162 -0
- package/dist/compiler.d.ts +11 -0
- package/dist/compiler.js +48 -0
- package/dist/effect-receivers.d.ts +11 -0
- package/dist/effect-receivers.js +315 -0
- package/dist/expression-wrappers.d.ts +6 -0
- package/dist/expression-wrappers.js +16 -0
- package/dist/forwarded-props.d.ts +27 -0
- package/dist/forwarded-props.js +489 -0
- package/dist/index.d.ts +6 -0
- package/{src → dist}/index.js +1 -0
- package/dist/linked-state.d.ts +17 -0
- package/dist/linked-state.js +126 -0
- package/dist/local-calls.d.ts +20 -0
- package/dist/local-calls.js +143 -0
- package/dist/local-react-hook.d.ts +15 -0
- package/dist/local-react-hook.js +353 -0
- package/dist/local-uses.d.ts +13 -0
- package/dist/local-uses.js +987 -0
- package/dist/mappings.d.ts +57 -0
- package/dist/mappings.js +343 -0
- package/dist/path-svg.d.ts +60 -0
- package/dist/path-svg.js +207 -0
- package/dist/project.d.ts +9 -0
- package/dist/project.js +1568 -0
- package/dist/react-intl.d.ts +4 -0
- package/dist/react-intl.js +389 -0
- package/dist/react-renderer.d.ts +9 -0
- package/dist/react-renderer.js +106 -0
- package/dist/scoped-signal.d.ts +4 -0
- package/dist/scoped-signal.js +480 -0
- package/dist/scoped-store-contract.d.ts +13 -0
- package/dist/scoped-store-contract.js +741 -0
- package/dist/store-hook-uses.d.ts +18 -0
- package/dist/store-hook-uses.js +403 -0
- package/dist/store-inputs.d.ts +16 -0
- package/dist/store-inputs.js +391 -0
- package/dist/strong.d.ts +24 -0
- package/dist/strong.js +142 -0
- package/dist/transform.d.ts +27 -0
- package/dist/transform.js +4890 -0
- package/dist/types.d.ts +203 -0
- package/dist/types.js +1 -0
- package/package.json +18 -6
- package/src/path-svg.ts +218 -0
- package/templates/octane-path-svg.ts +56 -0
- package/templates/octane-store-context.tsrx +49 -0
- package/templates/octane-store-hooks.ts +61 -0
- package/templates/react-intl.tsrx +116 -0
- package/src/bin.js +0 -151
- package/src/compiler.js +0 -61
- package/src/index.d.ts +0 -95
- package/src/mappings.js +0 -429
- package/src/project.js +0 -738
- package/src/strong.js +0 -149
- package/src/transform.js +0 -3455
package/dist/project.js
ADDED
|
@@ -0,0 +1,1568 @@
|
|
|
1
|
+
import { createScopedStorePlanner } from './scoped-store-contract.js';
|
|
2
|
+
import { parseStaticSvg } from './path-svg.js';
|
|
3
|
+
import { storeSources } from './store-inputs.js';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import { createRequire } from 'node:module';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { findRoot, readInstalled, scanSourceFiles } from '@octanejs/cli';
|
|
9
|
+
import { DATA } from '@octanejs/cli/data';
|
|
10
|
+
import { parseSync } from '@tsrx/oxc/parser';
|
|
11
|
+
import ts from 'typescript';
|
|
12
|
+
import { finding, loadCompiler, thrown } from './compiler.js';
|
|
13
|
+
import { PORTED_PACKAGES } from './mappings.js';
|
|
14
|
+
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';
|
|
18
|
+
const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
|
|
19
|
+
const ADAPTER_OCTANE_VERSION = /^0\.(?:16\.(?:[7-9]|[1-9]\d+)|17\.(?:0|[1-9]\d*))$/;
|
|
20
|
+
/** React packages and the Octane entry point that replaces each. */
|
|
21
|
+
const CATALOG = { ...DATA.reactPackages, ...PORTED_PACKAGES };
|
|
22
|
+
const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'peerDependencies'];
|
|
23
|
+
/** A package that, by its name, renders through React. */
|
|
24
|
+
const REACT_PACKAGE = /^(?:react-|@[^/]+\/react(?:-|\/|$)|[^/]+\/react$)|-react(?:\/|$)/;
|
|
25
|
+
/**
|
|
26
|
+
* Migrate every React module under `paths`.
|
|
27
|
+
*
|
|
28
|
+
* Two passes: the first decides which modules become `.tsrx`, the second
|
|
29
|
+
* rewrites every module with that rename map in hand, so an import of a
|
|
30
|
+
* renamed module is updated wherever it is.
|
|
31
|
+
*/
|
|
32
|
+
export async function runCodemod(paths, options = {}) {
|
|
33
|
+
const write = options.write !== false;
|
|
34
|
+
const target = options.target ?? 'tsrx';
|
|
35
|
+
const strong = options.strong === true && target === 'tsrx';
|
|
36
|
+
const first = path.resolve(paths[0] ?? '.');
|
|
37
|
+
const root = path.resolve(options.root ??
|
|
38
|
+
findRoot(fs.statSync(first, { throwIfNoEntry: false })?.isFile() ? path.dirname(first) : first));
|
|
39
|
+
const known = new Set(paths.flatMap((entry) => collect(path.resolve(entry))));
|
|
40
|
+
const files = [...known];
|
|
41
|
+
const renames = new Map();
|
|
42
|
+
const exports = new Map();
|
|
43
|
+
const owners = new Map();
|
|
44
|
+
const conflicts = new Map();
|
|
45
|
+
const conflictFor = (file, source, output, reason) => unchangedFile(path.relative(root, file), source, {
|
|
46
|
+
rule: 'rename-conflict',
|
|
47
|
+
severity: 'error',
|
|
48
|
+
line: 1,
|
|
49
|
+
message: `Cannot migrate to ${path.relative(root, output)} because it ${reason}.`,
|
|
50
|
+
});
|
|
51
|
+
for (const file of files) {
|
|
52
|
+
const source = fs.readFileSync(file, 'utf8');
|
|
53
|
+
const result = transformModule(source, file, { target });
|
|
54
|
+
exports.set(file, result.exports);
|
|
55
|
+
if (!result.template)
|
|
56
|
+
continue;
|
|
57
|
+
const output = file.replace(/\.(?:jsx?|tsx)$/, '.tsrx');
|
|
58
|
+
if (output === file)
|
|
59
|
+
continue;
|
|
60
|
+
const key = ts.sys.useCaseSensitiveFileNames ? output : output.toLowerCase();
|
|
61
|
+
const previous = owners.get(key);
|
|
62
|
+
if (!previous)
|
|
63
|
+
owners.set(key, file);
|
|
64
|
+
if (previous || fs.lstatSync(output, { throwIfNoEntry: false })) {
|
|
65
|
+
const reason = previous
|
|
66
|
+
? `is also the target of ${path.relative(root, previous)}`
|
|
67
|
+
: 'already exists';
|
|
68
|
+
const conflict = conflictFor(file, source, output, reason);
|
|
69
|
+
if (write)
|
|
70
|
+
return blockedWrite(root, conflict);
|
|
71
|
+
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);
|
|
76
|
+
}
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
renames.set(file, output);
|
|
80
|
+
}
|
|
81
|
+
// A colliding source remains in place, so its imports and export contracts
|
|
82
|
+
// must not participate in the preview as if it had been migrated.
|
|
83
|
+
for (const file of conflicts.keys())
|
|
84
|
+
exports.delete(file);
|
|
85
|
+
const config = tsconfigOptions(root);
|
|
86
|
+
const strictConfig = (config?.strictNullChecks ?? config?.strict) ? config : null;
|
|
87
|
+
let program;
|
|
88
|
+
function typesOf(file) {
|
|
89
|
+
if (!strictConfig || options.projectTypes === false)
|
|
90
|
+
return;
|
|
91
|
+
// Even one input can import a large graph. Bind it only for a rewrite that needs its types.
|
|
92
|
+
program ??= ts.createProgram(files.filter((name) => /\.[cm]?tsx?$/.test(name)), { ...strictConfig, noEmit: true, noUncheckedIndexedAccess: true });
|
|
93
|
+
const sourceFile = program.getSourceFile(file);
|
|
94
|
+
if (sourceFile)
|
|
95
|
+
return { sourceFile, checker: program.getTypeChecker() };
|
|
96
|
+
}
|
|
97
|
+
const contextsOf = contextIndex(exports, known);
|
|
98
|
+
const renamed = renamedImports(root, config, renames);
|
|
99
|
+
const resolveRename = (from, specifier) => renamed(from, specifier)?.specifier ?? null;
|
|
100
|
+
const propChecks = new Map();
|
|
101
|
+
function forwardedProp(from, specifier, name, prop, destination, ordinaryCaller, depth = 0) {
|
|
102
|
+
if (destination === 'forwarded-text' &&
|
|
103
|
+
ts.findConfigFile(path.dirname(from), ts.sys.fileExists) !== rootProject)
|
|
104
|
+
return false;
|
|
105
|
+
const match = renamed(from, specifier);
|
|
106
|
+
if (!match || (!specifier.startsWith('.') && match.specifier.startsWith('.')))
|
|
107
|
+
return false;
|
|
108
|
+
if (destination !== 'text' &&
|
|
109
|
+
(!match.file.startsWith(root + path.sep) ||
|
|
110
|
+
match.file.split(path.sep).includes('node_modules') ||
|
|
111
|
+
fs.realpathSync(match.file) !==
|
|
112
|
+
path.join(fs.realpathSync(root), path.relative(root, match.file)) ||
|
|
113
|
+
ts.findConfigFile(path.dirname(match.file), ts.sys.fileExists) !== rootProject))
|
|
114
|
+
return false;
|
|
115
|
+
let inspect = propChecks.get(match.file);
|
|
116
|
+
if (!inspect) {
|
|
117
|
+
inspect = propsOf(match.file, (module, name, slot, depth) => forwardedProp(match.file, module, name, slot, 'render', true, depth), (module, name, prop) => forwardedProp(match.file, module, name, prop, 'host-text', true), () => typesOf(match.file));
|
|
118
|
+
propChecks.set(match.file, inspect);
|
|
119
|
+
}
|
|
120
|
+
return inspect(destination, name, prop, ordinaryCaller, depth);
|
|
121
|
+
}
|
|
122
|
+
// resolveRename returns only an on-disk source that actually won import resolution.
|
|
123
|
+
const elementExports = new Map();
|
|
124
|
+
const descriptorExports = new Map();
|
|
125
|
+
for (const [from, to] of renames) {
|
|
126
|
+
const record = exports.get(from);
|
|
127
|
+
if (record?.elementChildren) {
|
|
128
|
+
elementExports.set(to, new Set(record.elementChildren.flatMap((d) => (d.exported ? [d.exported] : []))));
|
|
129
|
+
}
|
|
130
|
+
if (record?.descriptorChildren)
|
|
131
|
+
descriptorExports.set(to, new Set(record.descriptorChildren));
|
|
132
|
+
}
|
|
133
|
+
const verify = options.verify !== false;
|
|
134
|
+
const compiler = verify || strong ? await loadCompiler(root) : null;
|
|
135
|
+
const packages = new Map();
|
|
136
|
+
const missing = new Map();
|
|
137
|
+
// `ReactCompat` hosts a component from a package with no port in a React
|
|
138
|
+
// root, from 19.2 within the React 19 series it supports.
|
|
139
|
+
const reactCompat = ['react', 'react-dom'].every((name) => /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''));
|
|
140
|
+
const rootProject = ts.findConfigFile(root, ts.sys.fileExists);
|
|
141
|
+
function reactStoreComponent(file, specifier) {
|
|
142
|
+
if (!reactCompat || !unportedName(specifier, file))
|
|
143
|
+
return false;
|
|
144
|
+
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
|
+
const name = packageName(specifier);
|
|
154
|
+
const lib = readInstalled(dir, name);
|
|
155
|
+
if (!lib ||
|
|
156
|
+
lib.manifest.name !== name ||
|
|
157
|
+
!['peerDependencies', 'dependencies'].some((field) => record(lib.manifest[field]).react !== undefined))
|
|
158
|
+
return false;
|
|
159
|
+
// A linked workspace package can itself migrate. A paths alias can also shadow
|
|
160
|
+
// the installed component or the JSX runtime, even when their packages exist.
|
|
161
|
+
const pkg = fs.realpathSync(lib.dir);
|
|
162
|
+
if (!pkg.split(path.sep).includes('node_modules'))
|
|
163
|
+
return false;
|
|
164
|
+
return [specifier, 'react/jsx-runtime'].every((module) => {
|
|
165
|
+
const target = originalModule(file, module);
|
|
166
|
+
return (!!target &&
|
|
167
|
+
(module !== specifier ||
|
|
168
|
+
fs.realpathSync(target.resolvedFileName).startsWith(pkg + path.sep)));
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
function originalModule(file, module, options = config) {
|
|
172
|
+
const bindings = { moduleResolution: ts.ModuleResolutionKind.Bundler, ...options };
|
|
173
|
+
const target = ts.resolveModuleName(module, file, bindings, ts.sys).resolvedModule;
|
|
174
|
+
const original = ts.resolveModuleName(module, file, { ...bindings, paths: undefined, baseUrl: undefined }, ts.sys).resolvedModule;
|
|
175
|
+
return target?.resolvedFileName === original?.resolvedFileName ? (target ?? null) : undefined;
|
|
176
|
+
}
|
|
177
|
+
function installedReact(file) {
|
|
178
|
+
const dir = path.dirname(file);
|
|
179
|
+
if (ts.findConfigFile(dir, ts.sys.fileExists) !== rootProject)
|
|
180
|
+
return false;
|
|
181
|
+
const target = originalModule(file, 'react');
|
|
182
|
+
if (!target || !['react', '@types/react'].includes(target.packageId?.name ?? ''))
|
|
183
|
+
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' &&
|
|
187
|
+
fs.realpathSync(runtime.dir).split(path.sep).includes('node_modules') &&
|
|
188
|
+
fs.realpathSync(target.resolvedFileName).split(path.sep).includes('node_modules'));
|
|
189
|
+
}
|
|
190
|
+
const inlineCompatDirs = new Map();
|
|
191
|
+
function supportsInlineReactCompat(file) {
|
|
192
|
+
const issuer = path.dirname(file);
|
|
193
|
+
if (ts.findConfigFile(issuer, ts.sys.fileExists) !== rootProject)
|
|
194
|
+
return false;
|
|
195
|
+
const installed = readInstalled(issuer, 'octane');
|
|
196
|
+
if (installed?.manifest.name !== 'octane')
|
|
197
|
+
return false;
|
|
198
|
+
const dir = fs.realpathSync(installed.dir);
|
|
199
|
+
if (compiler) {
|
|
200
|
+
try {
|
|
201
|
+
if (createRequire(file).resolve('octane/compiler') !== compiler.from)
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const exports = record(installed.manifest.exports);
|
|
209
|
+
return ['react', 'react/server'].every((name) => {
|
|
210
|
+
const entry = exports['./' + name];
|
|
211
|
+
const conditions = record(entry);
|
|
212
|
+
const types = typeof entry === 'string' ? entry : conditions.types;
|
|
213
|
+
const target = originalModule(file, 'octane/' + name)?.resolvedFileName;
|
|
214
|
+
if (typeof types !== 'string' ||
|
|
215
|
+
!target ||
|
|
216
|
+
fs.realpathSync(target) !== path.resolve(dir, types))
|
|
217
|
+
return false;
|
|
218
|
+
if (typeof entry !== 'string' && typeof conditions.default !== 'string')
|
|
219
|
+
return false;
|
|
220
|
+
// Published packages resolve types separately from the Node and bundler code.
|
|
221
|
+
const entries = typeof entry === 'string' ? [entry] : Object.values(conditions);
|
|
222
|
+
return entries.every((value) => {
|
|
223
|
+
if (typeof value !== 'string' || !value.startsWith('./'))
|
|
224
|
+
return false;
|
|
225
|
+
const file = path.resolve(dir, value);
|
|
226
|
+
if (!ts.sys.fileExists(file) || !fs.realpathSync(file).startsWith(dir + path.sep))
|
|
227
|
+
return false;
|
|
228
|
+
const source = ts.createSourceFile(file, fs.readFileSync(file, 'utf8'), ts.ScriptTarget.Latest);
|
|
229
|
+
return source.statements.some((statement) => ts.isExportDeclaration(statement) &&
|
|
230
|
+
!statement.isTypeOnly &&
|
|
231
|
+
statement.exportClause &&
|
|
232
|
+
ts.isNamedExports(statement.exportClause) &&
|
|
233
|
+
statement.exportClause.elements.some((item) => !item.isTypeOnly && item.name.text === 'ReactCompatInline'));
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
const bindingProject = {
|
|
238
|
+
root,
|
|
239
|
+
original(file, module) {
|
|
240
|
+
const dir = path.dirname(file);
|
|
241
|
+
const options = ts.findConfigFile(dir, ts.sys.fileExists) === rootProject ? config : tsconfigOptions(dir);
|
|
242
|
+
return ((!options?.paths && !options?.baseUrl) ||
|
|
243
|
+
originalModule(file, module, options) !== undefined);
|
|
244
|
+
},
|
|
245
|
+
};
|
|
246
|
+
// One shared context per project, including separate file-by-file migrations.
|
|
247
|
+
const sourceDir = path.join(root, 'src');
|
|
248
|
+
const adapter = path.join(fs.lstatSync(sourceDir, { throwIfNoEntry: false })?.isDirectory() ? sourceDir : root, 'octane-react-intl.tsrx');
|
|
249
|
+
const adapterName = path.relative(root, adapter);
|
|
250
|
+
const intlDirs = new Map();
|
|
251
|
+
let adapterSource;
|
|
252
|
+
let adapterError;
|
|
253
|
+
let adapterState;
|
|
254
|
+
const intlPath = (file) => {
|
|
255
|
+
const dir = path.dirname(file);
|
|
256
|
+
let supported = intlDirs.get(dir);
|
|
257
|
+
if (supported === undefined) {
|
|
258
|
+
const base = path.dirname(adapter);
|
|
259
|
+
const lib = readInstalled(base, 'react-intl');
|
|
260
|
+
const octane = readInstalled(base, 'octane')?.version ?? '';
|
|
261
|
+
const bindings = config ?? { moduleResolution: ts.ModuleResolutionKind.Bundler };
|
|
262
|
+
const original = ts.resolveModuleName('react-intl', adapter, { ...bindings, paths: undefined, baseUrl: undefined }, ts.sys).resolvedModule;
|
|
263
|
+
supported =
|
|
264
|
+
!!lib &&
|
|
265
|
+
lib.manifest.name === 'react-intl' &&
|
|
266
|
+
/^7\./.test(lib.version) &&
|
|
267
|
+
ADAPTER_OCTANE_VERSION.test(octane) &&
|
|
268
|
+
['react', 'react-dom'].every((name) => /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(base, name)?.version ?? '')) &&
|
|
269
|
+
[file, adapter].every((source) => {
|
|
270
|
+
const resolved = ts.resolveModuleName('react-intl', source, bindings, ts.sys).resolvedModule;
|
|
271
|
+
return (original &&
|
|
272
|
+
resolved &&
|
|
273
|
+
fs.realpathSync(resolved.resolvedFileName) ===
|
|
274
|
+
fs.realpathSync(original.resolvedFileName) &&
|
|
275
|
+
fs
|
|
276
|
+
.realpathSync(original.resolvedFileName)
|
|
277
|
+
.startsWith(fs.realpathSync(lib.dir) + path.sep));
|
|
278
|
+
}) &&
|
|
279
|
+
['react-intl', 'react', 'react-dom', 'octane', 'octane/react'].every((name) => {
|
|
280
|
+
try {
|
|
281
|
+
return createRequire(file).resolve(name) === createRequire(adapter).resolve(name);
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
intlDirs.set(dir, supported);
|
|
288
|
+
}
|
|
289
|
+
if (!supported)
|
|
290
|
+
return undefined;
|
|
291
|
+
if (adapterSource === undefined) {
|
|
292
|
+
adapterSource = fs.readFileSync(new URL('../templates/react-intl.tsrx', import.meta.url), 'utf8');
|
|
293
|
+
adapterState = inspectAdapter(adapter, adapterSource, PREVIOUS_INTL_HASHES);
|
|
294
|
+
if (adapterState.kind === 'conflict' ||
|
|
295
|
+
owners.has(ts.sys.useCaseSensitiveFileNames ? adapter : adapter.toLowerCase())) {
|
|
296
|
+
adapterError = `Cannot generate the React Intl adapter because ${adapterName} is already in use.`;
|
|
297
|
+
}
|
|
298
|
+
else if (compiler &&
|
|
299
|
+
compile(compiler, adapterSource, adapter, true).some((d) => d.severity === 'error')) {
|
|
300
|
+
adapterError = 'The project compiler cannot compile the React Intl adapter.';
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const specifier = path.relative(dir, adapter).split(path.sep).join('/');
|
|
304
|
+
return specifier.startsWith('.') ? specifier : './' + specifier;
|
|
305
|
+
};
|
|
306
|
+
const helperDir = path.dirname(adapter);
|
|
307
|
+
const storeBridge = path.join(helperDir, 'octane-store-context.tsrx');
|
|
308
|
+
const storeSlots = path.join(helperDir, 'octane-store-hooks.ts');
|
|
309
|
+
const planStoreHook = target === 'tsrx' &&
|
|
310
|
+
compiler &&
|
|
311
|
+
reactCompat &&
|
|
312
|
+
ADAPTER_OCTANE_VERSION.test(readInstalled(helperDir, 'octane')?.version ?? '')
|
|
313
|
+
? createScopedStorePlanner(helperDir, storeBridge, config ?? undefined)
|
|
314
|
+
: null;
|
|
315
|
+
const { inputFactory, helperFunction, localFile } = storeSources(root, config, (file, source) => {
|
|
316
|
+
if (renames.has(file) ||
|
|
317
|
+
ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject ||
|
|
318
|
+
rewriteModulePaths(source, file, root, renames, resolveRename))
|
|
319
|
+
return false;
|
|
320
|
+
if (!known.has(file) || conflicts.has(file))
|
|
321
|
+
return true;
|
|
322
|
+
// A plain helper selected in a directory run can still have its imports ported.
|
|
323
|
+
return !transformModule(source, file, {
|
|
324
|
+
target,
|
|
325
|
+
strong,
|
|
326
|
+
reactIntlAdapter: reactCompat && source.includes('react-intl') ? intlPath(file) : undefined,
|
|
327
|
+
strictNullChecks: strictConfig !== null,
|
|
328
|
+
get types() {
|
|
329
|
+
return typesOf(file);
|
|
330
|
+
},
|
|
331
|
+
resolveSpecifier: (specifier) => resolveRename(file, specifier) ??
|
|
332
|
+
resolveBinding(specifier, file, bindingProject, new Map(), []),
|
|
333
|
+
}).changed;
|
|
334
|
+
});
|
|
335
|
+
const localHooks = new Map();
|
|
336
|
+
let selectedInPlace;
|
|
337
|
+
function localReactHook(from, module, name, nativeOnly) {
|
|
338
|
+
if (catalogName(module) !== null ||
|
|
339
|
+
resolveRename(from, module) ||
|
|
340
|
+
/[!%?#\\]/.test(module) ||
|
|
341
|
+
ts.findConfigFile(path.dirname(from), ts.sys.fileExists) !== rootProject)
|
|
342
|
+
return;
|
|
343
|
+
const file = localFile(from, module);
|
|
344
|
+
if (!file ||
|
|
345
|
+
known.has(file) ||
|
|
346
|
+
path.basename(file) === 'index.ts' ||
|
|
347
|
+
fs.existsSync(file.slice(0, -3) + '.tsrx') ||
|
|
348
|
+
(path.extname(module) && !module.endsWith('.ts')) ||
|
|
349
|
+
fs.realpathSync(file) !== path.join(fs.realpathSync(root), path.relative(root, file)) ||
|
|
350
|
+
ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
|
|
351
|
+
return;
|
|
352
|
+
let hooks = localHooks.get(file);
|
|
353
|
+
if (!hooks) {
|
|
354
|
+
const source = fs.readFileSync(file, 'utf8');
|
|
355
|
+
hooks = new Map();
|
|
356
|
+
if ((/\b(?:useState|useSyncExternalStore)\b/.test(source) || source.includes('\\u')) &&
|
|
357
|
+
originalModule(file, 'react') &&
|
|
358
|
+
readInstalled(path.dirname(file), 'react')?.manifest.name === 'react') {
|
|
359
|
+
const existing = program?.getSourceFile(file);
|
|
360
|
+
const bound = existing && program
|
|
361
|
+
? { sf: existing, checker: program.getTypeChecker() }
|
|
362
|
+
: bind(file, source);
|
|
363
|
+
hooks = directReactHooks(bound.sf, bound.checker);
|
|
364
|
+
}
|
|
365
|
+
localHooks.set(file, hooks);
|
|
366
|
+
}
|
|
367
|
+
const hook = hooks.get(name);
|
|
368
|
+
if (!hook || fs.statSync(file).nlink > 1)
|
|
369
|
+
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)))
|
|
373
|
+
return;
|
|
374
|
+
if (nativeOnly &&
|
|
375
|
+
compiler &&
|
|
376
|
+
hook === 'useSyncExternalStore' &&
|
|
377
|
+
originalModule(file, 'octane')) {
|
|
378
|
+
try {
|
|
379
|
+
const issuer = createRequire(from);
|
|
380
|
+
const owner = createRequire(file);
|
|
381
|
+
if (issuer.resolve('octane/compiler') !== compiler.from ||
|
|
382
|
+
issuer.resolve('octane') !== owner.resolve('octane') ||
|
|
383
|
+
!originalModule(from, 'octane'))
|
|
384
|
+
return hook;
|
|
385
|
+
}
|
|
386
|
+
catch {
|
|
387
|
+
return hook;
|
|
388
|
+
}
|
|
389
|
+
const code = nativeExternalStore(file, fs.readFileSync(file, 'utf8'), name, (specifier) => {
|
|
390
|
+
const leaf = localFile(file, specifier);
|
|
391
|
+
if (!leaf ||
|
|
392
|
+
known.has(leaf) ||
|
|
393
|
+
selectedInPlace.has(fs.realpathSync(leaf)) ||
|
|
394
|
+
ts.findConfigFile(path.dirname(leaf), ts.sys.fileExists) !== rootProject)
|
|
395
|
+
return;
|
|
396
|
+
return bind(leaf, fs.readFileSync(leaf, 'utf8'));
|
|
397
|
+
});
|
|
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)) {
|
|
402
|
+
generatedHelpers.set(output, code);
|
|
403
|
+
return { from: relativeTsImport(from, output) };
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return hook;
|
|
407
|
+
}
|
|
408
|
+
const checkedHelpers = new Map();
|
|
409
|
+
const generatedHelpers = new Map();
|
|
410
|
+
const svgHelpers = new Set();
|
|
411
|
+
const svgHelper = path.join(helperDir, 'octane-path-svg.ts');
|
|
412
|
+
const svgAssets = new Map();
|
|
413
|
+
let svgHelperCode;
|
|
414
|
+
function nativeSvgModule(asset, errors, color) {
|
|
415
|
+
if (!asset.startsWith(root + path.sep) ||
|
|
416
|
+
asset.split(path.sep).includes('node_modules') ||
|
|
417
|
+
/[!%?#]/.test(path.relative(root, asset)))
|
|
418
|
+
return null;
|
|
419
|
+
if (!svgAssets.has(asset)) {
|
|
420
|
+
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')));
|
|
424
|
+
}
|
|
425
|
+
if (!svgAssets.get(asset))
|
|
426
|
+
return null;
|
|
427
|
+
svgHelperCode ??=
|
|
428
|
+
fs.readFileSync(new URL('../templates/octane-path-svg.ts', import.meta.url), 'utf8') +
|
|
429
|
+
'\n' +
|
|
430
|
+
fs.readFileSync(new URL('../src/path-svg.ts', import.meta.url), 'utf8');
|
|
431
|
+
const sidecar = asset + (color ? '.octane-color-' + color.slice(2) : '.octane') + '.ts';
|
|
432
|
+
const code = 'import source from ' +
|
|
433
|
+
JSON.stringify('./' + path.basename(asset) + '?raw') +
|
|
434
|
+
';\n' +
|
|
435
|
+
'import { pathSvg } from ' +
|
|
436
|
+
JSON.stringify(relativeTsImport(sidecar, svgHelper)) +
|
|
437
|
+
';\n\nexport default pathSvg(source' +
|
|
438
|
+
(color ? ', ' + JSON.stringify('color:var(' + color + ')') : '') +
|
|
439
|
+
');\n';
|
|
440
|
+
let conflict;
|
|
441
|
+
try {
|
|
442
|
+
conflict = checkHelper(svgHelper, svgHelperCode, 'SVG') || checkHelper(sidecar, code, 'SVG');
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
if (!color || error.code !== 'ENAMETOOLONG')
|
|
446
|
+
throw error;
|
|
447
|
+
conflict = 'The SVG adapter path is too long: ' + path.relative(root, sidecar);
|
|
448
|
+
}
|
|
449
|
+
if (conflict) {
|
|
450
|
+
errors.add(conflict);
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
generatedHelpers.set(svgHelper, svgHelperCode);
|
|
454
|
+
generatedHelpers.set(sidecar, code);
|
|
455
|
+
svgHelpers.add(svgHelper);
|
|
456
|
+
svgHelpers.add(sidecar);
|
|
457
|
+
return sidecar;
|
|
458
|
+
}
|
|
459
|
+
function pathSvgAdapter(file, specifier, errors, color) {
|
|
460
|
+
if ((config?.jsxImportSource && config.jsxImportSource !== 'react') ||
|
|
461
|
+
config?.jsxFactory ||
|
|
462
|
+
config?.jsxFragmentFactory ||
|
|
463
|
+
ts.findConfigFile(path.dirname(file), ts.sys.fileExists) !== rootProject)
|
|
464
|
+
return null;
|
|
465
|
+
const asset = svgAsset(root, path.dirname(file), specifier, config);
|
|
466
|
+
const sidecar = asset && nativeSvgModule(asset, errors, color);
|
|
467
|
+
return sidecar ? relativeTsImport(file, sidecar) : null;
|
|
468
|
+
}
|
|
469
|
+
let storeTemplates;
|
|
470
|
+
function checkHelper(output, code, kind = 'workspace hook') {
|
|
471
|
+
const cached = checkedHelpers.get(output);
|
|
472
|
+
if (cached)
|
|
473
|
+
return cached.code === code
|
|
474
|
+
? cached.error
|
|
475
|
+
: 'Two generated adapters need different code at ' + path.relative(root, output);
|
|
476
|
+
const name = path.relative(root, output);
|
|
477
|
+
const ownerOf = (file) => owners.has(ts.sys.useCaseSensitiveFileNames ? file : file.toLowerCase());
|
|
478
|
+
// Bundlers can prefer a JavaScript or JSX sibling over our extensionless .ts import.
|
|
479
|
+
const shadowed = output.endsWith('.ts') &&
|
|
480
|
+
['', '.js', '.jsx', '.tsx', '.mjs', '.cjs', '.mts', '.cts', '.json', '.tsrx'].some((ext) => {
|
|
481
|
+
const sibling = output.slice(0, -3) + ext;
|
|
482
|
+
return ownerOf(sibling) || fs.lstatSync(sibling, { throwIfNoEntry: false });
|
|
483
|
+
});
|
|
484
|
+
const state = shadowed || ownerOf(output)
|
|
485
|
+
? { kind: 'conflict' }
|
|
486
|
+
: inspectAdapter(output, code, output === svgHelper ? PREVIOUS_SVG_HASHES : undefined);
|
|
487
|
+
let error;
|
|
488
|
+
if (state.kind === 'conflict') {
|
|
489
|
+
error = 'The ' + kind + ' adapter path is occupied: ' + name;
|
|
490
|
+
}
|
|
491
|
+
else {
|
|
492
|
+
const rejected = output.endsWith('.tsrx')
|
|
493
|
+
? compile(compiler, code, output, true).some((d) => d.severity === 'error')
|
|
494
|
+
: ts
|
|
495
|
+
.transpileModule(code, {
|
|
496
|
+
fileName: output,
|
|
497
|
+
reportDiagnostics: true,
|
|
498
|
+
compilerOptions: { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.ESNext },
|
|
499
|
+
})
|
|
500
|
+
.diagnostics?.some((d) => d.category === ts.DiagnosticCategory.Error);
|
|
501
|
+
if (rejected)
|
|
502
|
+
error = 'The target compiler rejected the ' + kind + ' adapter: ' + name;
|
|
503
|
+
}
|
|
504
|
+
checkedHelpers.set(output, { code, state, error });
|
|
505
|
+
return error;
|
|
506
|
+
}
|
|
507
|
+
const results = [];
|
|
508
|
+
if (options.svgPaths && target === 'tsrx') {
|
|
509
|
+
// Explicit SVG inputs prepare a native component even if a caller's renderer is unknown.
|
|
510
|
+
// Directory scans still generate components only for verified JSX uses.
|
|
511
|
+
for (const entry of new Set(paths.filter((name) => /\.svg$/i.test(name)).map((name) => path.resolve(name)))) {
|
|
512
|
+
if (fs.lstatSync(entry).isDirectory())
|
|
513
|
+
continue;
|
|
514
|
+
const errors = new Set();
|
|
515
|
+
if (nativeSvgModule(entry, errors))
|
|
516
|
+
continue;
|
|
517
|
+
const file = unchangedFile(path.relative(root, entry), '', {
|
|
518
|
+
rule: 'svg-paths',
|
|
519
|
+
severity: 'error',
|
|
520
|
+
line: 1,
|
|
521
|
+
message: [...errors].join('; ') ||
|
|
522
|
+
'Cannot generate a native SVG component for this asset. Expected supported static SVG geometry inside the project.',
|
|
523
|
+
});
|
|
524
|
+
if (write)
|
|
525
|
+
return blockedWrite(root, file, compiler?.from);
|
|
526
|
+
results.push(file);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
for (const file of files) {
|
|
530
|
+
const conflict = conflicts.get(file);
|
|
531
|
+
if (conflict) {
|
|
532
|
+
results.push(conflict);
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
const source = fs.readFileSync(file, 'utf8');
|
|
536
|
+
const extra = [];
|
|
537
|
+
const reactStoreComponents = new Map();
|
|
538
|
+
let installedClsx;
|
|
539
|
+
const isContext = (specifier, name) => {
|
|
540
|
+
if (!specifier.startsWith('.'))
|
|
541
|
+
return null;
|
|
542
|
+
const target = resolveModule(file, specifier, known);
|
|
543
|
+
return target ? contextsOf(target.file).has(name) : null;
|
|
544
|
+
};
|
|
545
|
+
const matchesExport = (index, binding) => {
|
|
546
|
+
const to = resolveRename(file, binding.module);
|
|
547
|
+
return Boolean(to?.startsWith('.') &&
|
|
548
|
+
index.get(path.resolve(path.dirname(file), to))?.has(binding.imported));
|
|
549
|
+
};
|
|
550
|
+
let types;
|
|
551
|
+
let intl = target === 'tsrx' && reactCompat && source.includes('react-intl')
|
|
552
|
+
? intlPath(file)
|
|
553
|
+
: undefined;
|
|
554
|
+
const storeErrors = new Set();
|
|
555
|
+
const svgErrors = new Set();
|
|
556
|
+
let originalReact;
|
|
557
|
+
const resolveStoreHook = !planStoreHook || !renames.has(file)
|
|
558
|
+
? undefined
|
|
559
|
+
: (module, name, safeUses) => {
|
|
560
|
+
if (!unportedName(module, file))
|
|
561
|
+
return null;
|
|
562
|
+
const plan = planStoreHook(module, name, file);
|
|
563
|
+
if (!plan ||
|
|
564
|
+
!safeUses((source, name) => {
|
|
565
|
+
const input = inputFactory(file, source, name, plan.isSharedExport);
|
|
566
|
+
if (!input)
|
|
567
|
+
return false;
|
|
568
|
+
if ('opaque' in input)
|
|
569
|
+
return 'opaque';
|
|
570
|
+
return plan.isSharedExport(input.module, input.name, input.from);
|
|
571
|
+
}, (source, name) => !resolveRename(file, source) &&
|
|
572
|
+
catalogName(source) === null &&
|
|
573
|
+
(originalReact ??=
|
|
574
|
+
ts.findConfigFile(path.dirname(file), ts.sys.fileExists) === rootProject &&
|
|
575
|
+
!!originalModule(file, 'react')) &&
|
|
576
|
+
helperFunction(file, source, name)))
|
|
577
|
+
return null;
|
|
578
|
+
storeTemplates ??= new Map([
|
|
579
|
+
[
|
|
580
|
+
storeBridge,
|
|
581
|
+
fs.readFileSync(new URL('../templates/octane-store-context.tsrx', import.meta.url), 'utf8'),
|
|
582
|
+
],
|
|
583
|
+
[
|
|
584
|
+
storeSlots,
|
|
585
|
+
fs.readFileSync(new URL('../templates/octane-store-hooks.ts', import.meta.url), 'utf8'),
|
|
586
|
+
],
|
|
587
|
+
]);
|
|
588
|
+
const helpers = new Map([...plan.files, ...storeTemplates]);
|
|
589
|
+
for (const [output, code] of helpers) {
|
|
590
|
+
const error = checkHelper(output, code);
|
|
591
|
+
if (error) {
|
|
592
|
+
storeErrors.add(error);
|
|
593
|
+
return null;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
for (const [output, code] of helpers)
|
|
597
|
+
generatedHelpers.set(output, code);
|
|
598
|
+
const relative = path
|
|
599
|
+
.relative(path.dirname(file), plan.entry)
|
|
600
|
+
.split(path.sep)
|
|
601
|
+
.join('/')
|
|
602
|
+
.replace(/\.ts$/, '');
|
|
603
|
+
return { from: relative.startsWith('.') ? relative : './' + relative, name: plan.name };
|
|
604
|
+
};
|
|
605
|
+
const svgAdapter = options.svgPaths && renames.has(file)
|
|
606
|
+
? (specifier, color) => pathSvgAdapter(file, specifier, svgErrors, color)
|
|
607
|
+
: undefined;
|
|
608
|
+
const transform = (notes = extra, retry) => transformModule(source, file, {
|
|
609
|
+
captureEffectReceivers: retry === 'effectReceivers' ||
|
|
610
|
+
retry === 'effectProperties' ||
|
|
611
|
+
retry === 'effectSnapshots',
|
|
612
|
+
snapshotEffectProperties: retry === 'effectProperties',
|
|
613
|
+
captureEffectHelpers: retry === 'effectProperties' && installedReact(file),
|
|
614
|
+
captureEffectSnapshots: retry === 'effectSnapshots',
|
|
615
|
+
linkRenderState: retry === 'linkedState' && installedReact(file),
|
|
616
|
+
target,
|
|
617
|
+
reactIntlAdapter: intl,
|
|
618
|
+
forwardedText: (module, name, prop, ordinaryCaller, through) => forwardedProp(file, module, name, prop, through ? 'forwarded-text' : 'text', ordinaryCaller),
|
|
619
|
+
resolveStoreHook,
|
|
620
|
+
get originalReact() {
|
|
621
|
+
return installedReact(file);
|
|
622
|
+
},
|
|
623
|
+
localReactHook: renames.has(file)
|
|
624
|
+
? (module, name, nativeOnly) => localReactHook(file, module, name, nativeOnly)
|
|
625
|
+
: undefined,
|
|
626
|
+
strong,
|
|
627
|
+
strictNullChecks: strictConfig !== null,
|
|
628
|
+
get types() {
|
|
629
|
+
return (types ??= typesOf(file));
|
|
630
|
+
},
|
|
631
|
+
resolveSpecifier: (specifier) => resolveRename(file, specifier) ??
|
|
632
|
+
resolveBinding(specifier, file, bindingProject, packages, notes),
|
|
633
|
+
isContext,
|
|
634
|
+
elementChild: !elementExports.size
|
|
635
|
+
? undefined
|
|
636
|
+
: (binding) => typeof binding === 'number'
|
|
637
|
+
? (exports.get(file)?.elementChildren?.some((x) => x.start === binding) ?? false)
|
|
638
|
+
: matchesExport(elementExports, binding),
|
|
639
|
+
descriptorChild: descriptorExports.size
|
|
640
|
+
? (binding) => matchesExport(descriptorExports, binding)
|
|
641
|
+
: undefined,
|
|
642
|
+
unported: (specifier) => unportedName(specifier, file),
|
|
643
|
+
reactCompat,
|
|
644
|
+
get reactCompatInline() {
|
|
645
|
+
const dir = path.dirname(file);
|
|
646
|
+
if (!inlineCompatDirs.has(dir))
|
|
647
|
+
inlineCompatDirs.set(dir, supportsInlineReactCompat(file));
|
|
648
|
+
return inlineCompatDirs.get(dir);
|
|
649
|
+
},
|
|
650
|
+
forwardedRender: options.svgPaths && renames.has(file)
|
|
651
|
+
? (module, name, prop, depth) => forwardedProp(file, module, name, prop, 'render', true, depth)
|
|
652
|
+
: undefined,
|
|
653
|
+
get installedClsx() {
|
|
654
|
+
if (installedClsx === undefined) {
|
|
655
|
+
const target = originalModule(file, 'clsx');
|
|
656
|
+
installedClsx =
|
|
657
|
+
target?.packageId?.name === 'clsx' &&
|
|
658
|
+
fs.realpathSync(target.resolvedFileName).split(path.sep).includes('node_modules');
|
|
659
|
+
}
|
|
660
|
+
return installedClsx;
|
|
661
|
+
},
|
|
662
|
+
cssModuleFile: (specifier) => {
|
|
663
|
+
if (!/^\.\.?\/[^!%?#\\]+\.module\.css$/.test(specifier))
|
|
664
|
+
return;
|
|
665
|
+
const sheet = path.resolve(path.dirname(file), specifier);
|
|
666
|
+
if (!ts.sys.fileExists(sheet))
|
|
667
|
+
return;
|
|
668
|
+
const real = fs.realpathSync(sheet);
|
|
669
|
+
return real.endsWith('.module.css') ? real : undefined;
|
|
670
|
+
},
|
|
671
|
+
pathSvgAdapter: svgAdapter,
|
|
672
|
+
fixedColorSvgAdapter: svgAdapter,
|
|
673
|
+
reactStoreComponent: (specifier) => {
|
|
674
|
+
if (!reactStoreComponents.has(specifier))
|
|
675
|
+
reactStoreComponents.set(specifier, reactStoreComponent(file, specifier));
|
|
676
|
+
return reactStoreComponents.get(specifier);
|
|
677
|
+
},
|
|
678
|
+
});
|
|
679
|
+
if (intl && adapterError) {
|
|
680
|
+
// Public utilities such as defineMessages can stay on React Intl without a helper.
|
|
681
|
+
const needsAdapter = transform([]).rules['react-intl'];
|
|
682
|
+
intl = undefined;
|
|
683
|
+
if (needsAdapter) {
|
|
684
|
+
const note = {
|
|
685
|
+
rule: 'react-intl',
|
|
686
|
+
line: 1,
|
|
687
|
+
severity: 'error',
|
|
688
|
+
message: write ? adapterError + ' No changes were written.' : adapterError,
|
|
689
|
+
};
|
|
690
|
+
if (write) {
|
|
691
|
+
return blockedWrite(root, unchangedFile(path.relative(root, file), source, note), compiler?.from);
|
|
692
|
+
}
|
|
693
|
+
extra.push(note);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
const result = transform();
|
|
697
|
+
for (const message of [...storeErrors, ...svgErrors]) {
|
|
698
|
+
const note = {
|
|
699
|
+
rule: svgErrors.has(message) ? 'svg-paths' : 'store-hook',
|
|
700
|
+
line: 1,
|
|
701
|
+
severity: 'error',
|
|
702
|
+
message: write ? message + '. No changes were written.' : message,
|
|
703
|
+
};
|
|
704
|
+
if (write)
|
|
705
|
+
return blockedWrite(root, unchangedFile(path.relative(root, file), source, note), compiler?.from);
|
|
706
|
+
extra.push(note);
|
|
707
|
+
}
|
|
708
|
+
if (result.rules['store-hook'])
|
|
709
|
+
extra.push({
|
|
710
|
+
rule: 'store-hook',
|
|
711
|
+
line: 1,
|
|
712
|
+
severity: 'info',
|
|
713
|
+
message: 'React-hosted consumers inherit their store context. At a standalone Octane root, supply the active context and value with NativeStoreProvider.',
|
|
714
|
+
});
|
|
715
|
+
for (const port of result.unported) {
|
|
716
|
+
const entry = missing.get(port.name) ?? {
|
|
717
|
+
name: port.name,
|
|
718
|
+
modules: 0,
|
|
719
|
+
islands: 0,
|
|
720
|
+
blocked: 0,
|
|
721
|
+
};
|
|
722
|
+
entry.modules++;
|
|
723
|
+
entry.islands += port.islands;
|
|
724
|
+
entry.blocked += port.blocked;
|
|
725
|
+
missing.set(port.name, entry);
|
|
726
|
+
}
|
|
727
|
+
const output = renames.get(file) ?? file;
|
|
728
|
+
let code = result.code;
|
|
729
|
+
let isStrong = null;
|
|
730
|
+
let strongFixes = [];
|
|
731
|
+
let diagnostics = [];
|
|
732
|
+
if (compiler && result.changed) {
|
|
733
|
+
if (strong && result.template) {
|
|
734
|
+
const strengthened = strengthen(compiler, code, output, {
|
|
735
|
+
force: options.forceStrong,
|
|
736
|
+
withEffectReceivers: () => transform([], 'effectReceivers').code,
|
|
737
|
+
withEffectProperties: () => transform([], 'effectProperties').code,
|
|
738
|
+
withEffectSnapshots: () => transform([], 'effectSnapshots').code,
|
|
739
|
+
withLinkedState: () => transform([], 'linkedState').code,
|
|
740
|
+
});
|
|
741
|
+
code = strengthened.code;
|
|
742
|
+
isStrong = strengthened.strong;
|
|
743
|
+
strongFixes = strengthened.fixed;
|
|
744
|
+
if (!strengthened.strong)
|
|
745
|
+
diagnostics.push(...strengthened.blockers);
|
|
746
|
+
}
|
|
747
|
+
if (verify && isCompiled(output, code))
|
|
748
|
+
diagnostics.push(...compile(compiler, code, output, isStrong === true));
|
|
749
|
+
}
|
|
750
|
+
results.push({
|
|
751
|
+
file: path.relative(root, file),
|
|
752
|
+
output: path.relative(root, output),
|
|
753
|
+
changed: result.changed || output !== file,
|
|
754
|
+
rules: result.rules,
|
|
755
|
+
notes: [...result.notes, ...extra],
|
|
756
|
+
strong: isStrong,
|
|
757
|
+
strongFixes,
|
|
758
|
+
diagnostics: dedupe(diagnostics),
|
|
759
|
+
code,
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
// TSRX written for React (`@tsrx/react`) is a dialect the TypeScript
|
|
763
|
+
// parser cannot read, so it is reported rather than skipped silently.
|
|
764
|
+
for (const file of paths.flatMap((entry) => collect(path.resolve(entry), isTsrx))) {
|
|
765
|
+
const source = fs.readFileSync(file, 'utf8');
|
|
766
|
+
const react = /^import\b[^;]*?\bfrom\s+['"]react(?:-dom)?(?:\/[^'"]*)?['"]/m.exec(source);
|
|
767
|
+
if (!react || /\bfrom\s+['"]octane(?:\/[^'"]*)?['"]/.test(source))
|
|
768
|
+
continue;
|
|
769
|
+
results.push(unchangedFile(path.relative(root, file), source, {
|
|
770
|
+
rule: 'tsrx-react',
|
|
771
|
+
severity: 'error',
|
|
772
|
+
line: source.slice(0, react.index).split('\n').length,
|
|
773
|
+
message: 'This is TSRX written for React (`@tsrx/react`), which the codemod cannot read. Port it by hand: its templates are already TSRX, but its React imports and APIs need the changes the codemod makes to TSX.',
|
|
774
|
+
}));
|
|
775
|
+
}
|
|
776
|
+
// Configs and scripts name modules by path too, such as Vite's
|
|
777
|
+
// `server.warmup.clientFiles`, including those outside the migrated paths.
|
|
778
|
+
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))
|
|
781
|
+
: []) {
|
|
782
|
+
if (renames.has(file) || conflicts.has(file))
|
|
783
|
+
continue;
|
|
784
|
+
const result = byFile.get(file);
|
|
785
|
+
const paths = rewriteModulePaths(result?.code ?? fs.readFileSync(file, 'utf8'), file, root, renames, resolveRename);
|
|
786
|
+
if (!paths)
|
|
787
|
+
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
|
+
});
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
const intlConsumer = results.find((file) => file.rules['react-intl']);
|
|
807
|
+
const svg = generatedHelpers.has(svgHelper) && checkedHelpers.get(svgHelper);
|
|
808
|
+
if (write) {
|
|
809
|
+
const updates = [];
|
|
810
|
+
if (adapterState && adapterSource && intlConsumer)
|
|
811
|
+
updates.push({
|
|
812
|
+
file: adapter,
|
|
813
|
+
source: adapterSource,
|
|
814
|
+
state: adapterState,
|
|
815
|
+
previous: PREVIOUS_INTL_HASHES,
|
|
816
|
+
rule: 'react-intl',
|
|
817
|
+
});
|
|
818
|
+
if (svg)
|
|
819
|
+
updates.push({
|
|
820
|
+
file: svgHelper,
|
|
821
|
+
source: svg.code,
|
|
822
|
+
state: svg.state,
|
|
823
|
+
previous: PREVIOUS_SVG_HASHES,
|
|
824
|
+
rule: 'svg-paths',
|
|
825
|
+
});
|
|
826
|
+
// Check both shared helpers before writing either. Recheck again at publication.
|
|
827
|
+
const conflict = updates.find(({ file, source, state, previous }) => !canPublishAdapter(inspectAdapter(file, source, previous), state)) ??
|
|
828
|
+
updates.find(({ file, source, state, previous }) => !publishAdapter(file, source, state, previous));
|
|
829
|
+
if (conflict) {
|
|
830
|
+
const name = path.relative(root, conflict.file);
|
|
831
|
+
return blockedWrite(root, unchangedFile(name, '', {
|
|
832
|
+
rule: conflict.rule,
|
|
833
|
+
severity: 'error',
|
|
834
|
+
line: 1,
|
|
835
|
+
message: `Cannot update ${name} because it changed during migration. No caller files were written.`,
|
|
836
|
+
}), compiler?.from);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
if (adapterState && adapterSource && intlConsumer) {
|
|
840
|
+
if (adapterState.kind === 'missing' || adapterState.kind === 'previous') {
|
|
841
|
+
results.push({
|
|
842
|
+
file: adapterName,
|
|
843
|
+
output: adapterName,
|
|
844
|
+
changed: true,
|
|
845
|
+
code: adapterSource,
|
|
846
|
+
rules: { 'react-intl-adapter': 1 },
|
|
847
|
+
notes: adapterState.kind === 'previous'
|
|
848
|
+
? [
|
|
849
|
+
{
|
|
850
|
+
rule: 'react-intl-adapter',
|
|
851
|
+
severity: 'info',
|
|
852
|
+
line: 1,
|
|
853
|
+
message: 'Update the previously generated React Intl adapter at its existing path.',
|
|
854
|
+
},
|
|
855
|
+
]
|
|
856
|
+
: [],
|
|
857
|
+
diagnostics: [],
|
|
858
|
+
strong: compiler ? true : null,
|
|
859
|
+
strongFixes: [],
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
for (const [output, code] of generatedHelpers) {
|
|
864
|
+
const { state } = checkedHelpers.get(output);
|
|
865
|
+
if (state.kind !== 'missing' && state.kind !== 'previous')
|
|
866
|
+
continue;
|
|
867
|
+
const name = path.relative(root, output);
|
|
868
|
+
if (write && output !== svgHelper)
|
|
869
|
+
fs.writeFileSync(output, code, { flag: 'wx' });
|
|
870
|
+
results.push({
|
|
871
|
+
file: name,
|
|
872
|
+
output: name,
|
|
873
|
+
changed: true,
|
|
874
|
+
code,
|
|
875
|
+
rules: { [svgHelpers.has(output) ? 'svg-paths-adapter' : 'store-hook-adapter']: 1 },
|
|
876
|
+
notes: [],
|
|
877
|
+
diagnostics: [],
|
|
878
|
+
strong: code.startsWith("'use strong'") ? true : null,
|
|
879
|
+
strongFixes: [],
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
const html = rewriteEntryPages(root, paths.map((entry) => path.resolve(entry)), renames, write);
|
|
883
|
+
const dependencies = addBindings(root, packages, write);
|
|
884
|
+
if (write) {
|
|
885
|
+
for (const result of results) {
|
|
886
|
+
if (!result.changed ||
|
|
887
|
+
result.rules['react-intl-adapter'] ||
|
|
888
|
+
result.rules['store-hook-adapter'] ||
|
|
889
|
+
result.rules['svg-paths-adapter'])
|
|
890
|
+
continue;
|
|
891
|
+
const output = path.join(root, result.output);
|
|
892
|
+
fs.writeFileSync(output, result.code, { flag: result.output === result.file ? 'w' : 'wx' });
|
|
893
|
+
if (result.output !== result.file)
|
|
894
|
+
fs.rmSync(path.join(root, result.file));
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
return {
|
|
898
|
+
root,
|
|
899
|
+
files: results,
|
|
900
|
+
packages: [...packages].map(([from, to]) => ({ from, to })),
|
|
901
|
+
dependencies,
|
|
902
|
+
patched: patchedPackages(root, packages),
|
|
903
|
+
missing: [...missing.values()].sort((a, b) => a.name.localeCompare(b.name)),
|
|
904
|
+
html,
|
|
905
|
+
compiler: compiler?.from ?? null,
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
// Hash only previously shipped helpers. A locally edited file belongs to the application.
|
|
909
|
+
const PREVIOUS_INTL_HASHES = ['07ec8e00847ebc6f0bd5ffeb14bc064aa23df42d1d3db5102344c739f54dca98'];
|
|
910
|
+
const PREVIOUS_SVG_HASHES = [
|
|
911
|
+
'893474efdb9186489e6c0113d1dedaaf9b7d2a0443f8b5d04048680610696bdf',
|
|
912
|
+
'88de6c9053abe0f94934ebb7cd54cd681e4d2544b3facab0dbdf3d4c588649a5',
|
|
913
|
+
'62ef936e3ce64cfe809297e08e74538f0c409f0bde6a926ca7b88de93161a38d',
|
|
914
|
+
'a3d611226ba955f4f5601caa4c6987f0a5a943fab97362843d16f02c686c6944',
|
|
915
|
+
'058f232bcee5d0caf24d72ec8f9864152b7eb6a9e882614bff3209ff0d145d00',
|
|
916
|
+
'3becf859871f17914f6f0631e8db8058aa4932fd4a9817718b98eb247a902b24',
|
|
917
|
+
'1dbf34eea75c07c21c8ab3814d54e58115e833aa140fc5f34b5f2cba91d018c3',
|
|
918
|
+
'b53641cfbe77205a174179b4d0de60989b34cf4073690fc98536c22a68ee844a',
|
|
919
|
+
];
|
|
920
|
+
function inspectAdapter(file, source, previous) {
|
|
921
|
+
const stat = fs.lstatSync(file, { throwIfNoEntry: false });
|
|
922
|
+
if (!stat)
|
|
923
|
+
return { kind: 'missing' };
|
|
924
|
+
if (!stat.isFile())
|
|
925
|
+
return { kind: 'conflict' };
|
|
926
|
+
const bytes = fs.readFileSync(file);
|
|
927
|
+
if (bytes.equals(Buffer.from(source)))
|
|
928
|
+
return { kind: 'current' };
|
|
929
|
+
if (previous) {
|
|
930
|
+
const hash = createHash('sha256').update(bytes).digest('hex');
|
|
931
|
+
if (previous.includes(hash))
|
|
932
|
+
return { kind: 'previous', mode: stat.mode & 0o777, hash };
|
|
933
|
+
}
|
|
934
|
+
return { kind: 'conflict' };
|
|
935
|
+
}
|
|
936
|
+
function canPublishAdapter(current, planned) {
|
|
937
|
+
return (current.kind === 'current' ||
|
|
938
|
+
(current.kind === 'missing' && planned.kind === 'missing') ||
|
|
939
|
+
(current.kind === 'previous' &&
|
|
940
|
+
planned.kind === 'previous' &&
|
|
941
|
+
current.mode === planned.mode &&
|
|
942
|
+
current.hash === planned.hash));
|
|
943
|
+
}
|
|
944
|
+
function publishAdapter(file, source, planned, previous) {
|
|
945
|
+
const current = inspectAdapter(file, source, previous);
|
|
946
|
+
if (current.kind === 'current')
|
|
947
|
+
return true;
|
|
948
|
+
if (!canPublishAdapter(current, planned))
|
|
949
|
+
return false;
|
|
950
|
+
if (current.kind === 'missing') {
|
|
951
|
+
try {
|
|
952
|
+
fs.writeFileSync(file, source, { flag: 'wx' });
|
|
953
|
+
return true;
|
|
954
|
+
}
|
|
955
|
+
catch (error) {
|
|
956
|
+
if (error.code !== 'EEXIST')
|
|
957
|
+
throw error;
|
|
958
|
+
return inspectAdapter(file, source, previous).kind === 'current';
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
if (current.kind !== 'previous')
|
|
962
|
+
return false;
|
|
963
|
+
const stage = fs.mkdtempSync(path.join(path.dirname(file), '.octane-adapter-'));
|
|
964
|
+
try {
|
|
965
|
+
const next = path.join(stage, 'next');
|
|
966
|
+
fs.writeFileSync(next, source, { mode: 0o600 });
|
|
967
|
+
fs.chmodSync(next, current.mode);
|
|
968
|
+
const latest = inspectAdapter(file, source, previous);
|
|
969
|
+
if (latest.kind !== 'previous')
|
|
970
|
+
return latest.kind === 'current';
|
|
971
|
+
if (!canPublishAdapter(latest, current))
|
|
972
|
+
return false;
|
|
973
|
+
fs.renameSync(next, file);
|
|
974
|
+
return true;
|
|
975
|
+
}
|
|
976
|
+
finally {
|
|
977
|
+
fs.rmSync(stage, { recursive: true, force: true });
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
/** A write conflict stops the batch before any file, entry page or dependency is updated. */
|
|
981
|
+
function blockedWrite(root, conflict, compiler = null) {
|
|
982
|
+
return {
|
|
983
|
+
root,
|
|
984
|
+
files: [conflict],
|
|
985
|
+
packages: [],
|
|
986
|
+
dependencies: [],
|
|
987
|
+
patched: [],
|
|
988
|
+
missing: [],
|
|
989
|
+
html: [],
|
|
990
|
+
compiler,
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
function unchangedFile(file, code, note) {
|
|
994
|
+
return {
|
|
995
|
+
file,
|
|
996
|
+
output: file,
|
|
997
|
+
code,
|
|
998
|
+
changed: false,
|
|
999
|
+
rules: {},
|
|
1000
|
+
notes: [note],
|
|
1001
|
+
strong: null,
|
|
1002
|
+
strongFixes: [],
|
|
1003
|
+
diagnostics: [],
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Whether Octane compiles this module: `.tsrx`, JSX, or a module that imports
|
|
1008
|
+
* the runtime. A declaration file is only types.
|
|
1009
|
+
*/
|
|
1010
|
+
function isCompiled(file, code) {
|
|
1011
|
+
if (file.endsWith('.d.ts'))
|
|
1012
|
+
return false;
|
|
1013
|
+
return /\.(?:tsrx|[jt]sx)$/.test(file) || /from\s+['"]octane['"]/.test(code);
|
|
1014
|
+
}
|
|
1015
|
+
function compile(compiler, code, file, strong) {
|
|
1016
|
+
try {
|
|
1017
|
+
const result = compiler.collectDiagnostics(code, file, strong ? { strong: true } : {});
|
|
1018
|
+
const found = result.diagnostics.filter((d) => d.severity !== 'hint').map(finding);
|
|
1019
|
+
return result.error == null ? found : [...found, thrown(result.error)];
|
|
1020
|
+
}
|
|
1021
|
+
catch (error) {
|
|
1022
|
+
return [thrown(error)];
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
function dedupe(diagnostics) {
|
|
1026
|
+
const seen = new Set();
|
|
1027
|
+
return diagnostics.filter((d) => {
|
|
1028
|
+
const key = `${d.code}:${d.line}:${d.message}`;
|
|
1029
|
+
if (seen.has(key))
|
|
1030
|
+
return false;
|
|
1031
|
+
seen.add(key);
|
|
1032
|
+
return true;
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* The modules under `entry` that pass `test`: by default, those the codemod
|
|
1037
|
+
* migrates.
|
|
1038
|
+
*/
|
|
1039
|
+
function collect(entry, test = isSource) {
|
|
1040
|
+
if (fs.statSync(entry).isFile())
|
|
1041
|
+
return test(entry) ? [entry] : [];
|
|
1042
|
+
return scanSourceFiles(entry, { limit: Infinity }).filter(test).sort();
|
|
1043
|
+
}
|
|
1044
|
+
function isTsrx(name) {
|
|
1045
|
+
return name.endsWith('.tsrx');
|
|
1046
|
+
}
|
|
1047
|
+
/** The compiler options of the tsconfig that governs `root`, or null. */
|
|
1048
|
+
function tsconfigOptions(root) {
|
|
1049
|
+
const file = ts.findConfigFile(root, ts.sys.fileExists);
|
|
1050
|
+
if (!file)
|
|
1051
|
+
return null;
|
|
1052
|
+
const { config } = ts.readConfigFile(file, ts.sys.readFile);
|
|
1053
|
+
return ts.parseJsonConfigFileContent(config ?? {}, ts.sys, path.dirname(file)).options;
|
|
1054
|
+
}
|
|
1055
|
+
/** Bundler and tool configs belong to `octane init`, not the codemod. */
|
|
1056
|
+
function isSource(name) {
|
|
1057
|
+
return SOURCE.test(name) && !/\.config\.[cm]?[jt]s$/.test(name);
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* The project module a relative specifier names, trying the extensions and
|
|
1061
|
+
* directory indexes a bundler would.
|
|
1062
|
+
*/
|
|
1063
|
+
function resolveModule(from, specifier, files) {
|
|
1064
|
+
if (!specifier.startsWith('.'))
|
|
1065
|
+
return null;
|
|
1066
|
+
const base = path.resolve(path.dirname(from), specifier);
|
|
1067
|
+
const stem = base.replace(/\.(?:[cm]?[jt]sx?)$/, '');
|
|
1068
|
+
for (const file of [base, ...['.tsx', '.ts', '.jsx', '.js'].map((ext) => stem + ext)]) {
|
|
1069
|
+
if (files.has(file))
|
|
1070
|
+
return { file, index: false };
|
|
1071
|
+
}
|
|
1072
|
+
for (const ext of ['.tsx', '.ts', '.jsx', '.js']) {
|
|
1073
|
+
const file = path.join(base, 'index' + ext);
|
|
1074
|
+
if (files.has(file))
|
|
1075
|
+
return { file, index: true };
|
|
1076
|
+
}
|
|
1077
|
+
return null;
|
|
1078
|
+
}
|
|
1079
|
+
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;
|
|
1082
|
+
}
|
|
1083
|
+
/** Only relative assets and unambiguous directory aliases have a local file to inspect. */
|
|
1084
|
+
function svgAsset(root, dir, specifier, config) {
|
|
1085
|
+
if (!/\.svg$/i.test(specifier) || /[!%?#\\]/.test(specifier))
|
|
1086
|
+
return null;
|
|
1087
|
+
if (specifier.startsWith('./') || specifier.startsWith('../'))
|
|
1088
|
+
return path.resolve(dir, specifier);
|
|
1089
|
+
const matches = Object.entries(config?.paths ?? {}).filter(([key]) => {
|
|
1090
|
+
const star = key.indexOf('*');
|
|
1091
|
+
return star < 0
|
|
1092
|
+
? key === specifier
|
|
1093
|
+
: specifier.startsWith(key.slice(0, star)) && specifier.endsWith(key.slice(star + 1));
|
|
1094
|
+
});
|
|
1095
|
+
if (matches.length !== 1)
|
|
1096
|
+
return null;
|
|
1097
|
+
const [key, targets] = matches[0];
|
|
1098
|
+
if (key.indexOf('*') !== key.length - 1 ||
|
|
1099
|
+
!key.endsWith('/*') ||
|
|
1100
|
+
targets.length !== 1 ||
|
|
1101
|
+
targets[0].indexOf('*') !== targets[0].length - 1 ||
|
|
1102
|
+
!targets[0].endsWith('/*'))
|
|
1103
|
+
return null;
|
|
1104
|
+
const base = config?.baseUrl ?? (typeof config?.pathsBasePath === 'string' ? config.pathsBasePath : root);
|
|
1105
|
+
return path.resolve(base, targets[0].slice(0, -1), specifier.slice(key.length - 1));
|
|
1106
|
+
}
|
|
1107
|
+
/**
|
|
1108
|
+
* Resolve against the files on disk before any rename, including modules
|
|
1109
|
+
* outside the selected paths that could win an extensionless lookup.
|
|
1110
|
+
*/
|
|
1111
|
+
function renamedImports(root, config, renames) {
|
|
1112
|
+
const options = {
|
|
1113
|
+
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
|
1114
|
+
...config,
|
|
1115
|
+
preserveSymlinks: true,
|
|
1116
|
+
};
|
|
1117
|
+
const cache = ts.createModuleResolutionCache(root, (file) => file, options);
|
|
1118
|
+
const pathsBase = options.baseUrl ?? (typeof config?.pathsBasePath === 'string' ? config.pathsBasePath : root);
|
|
1119
|
+
const aliases = Object.entries(options.paths ?? {}).map(([key, targets]) => {
|
|
1120
|
+
const [start, end] = key.split('*');
|
|
1121
|
+
const directory = key.endsWith('/*') && targets.length === 1 && targets[0].endsWith('/*')
|
|
1122
|
+
? path.resolve(pathsBase, targets[0].slice(0, -1)) + path.sep
|
|
1123
|
+
: null;
|
|
1124
|
+
return { start, end, directory };
|
|
1125
|
+
});
|
|
1126
|
+
return (from, specifier) => {
|
|
1127
|
+
const matches = specifier.startsWith('.')
|
|
1128
|
+
? []
|
|
1129
|
+
: aliases.filter(({ start, end }) => end === undefined
|
|
1130
|
+
? specifier === start
|
|
1131
|
+
: specifier.startsWith(start) && specifier.endsWith(end));
|
|
1132
|
+
if (!renames.size || (!specifier.startsWith('.') && !matches.length))
|
|
1133
|
+
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)
|
|
1137
|
+
return null;
|
|
1138
|
+
// Only a single directory alias preserves the specifier's suffix.
|
|
1139
|
+
// A fixed alias or fallback list may resolve elsewhere after a rename.
|
|
1140
|
+
const alias = matches.length === 1 ? matches[0] : null;
|
|
1141
|
+
if (alias?.directory && target.startsWith(alias.directory)) {
|
|
1142
|
+
return {
|
|
1143
|
+
file: resolved.resolvedFileName,
|
|
1144
|
+
specifier: alias.start + target.slice(alias.directory.length).split(path.sep).join('/'),
|
|
1145
|
+
};
|
|
1146
|
+
}
|
|
1147
|
+
const relative = path.relative(path.dirname(from), target).split(path.sep).join('/');
|
|
1148
|
+
return {
|
|
1149
|
+
file: resolved.resolvedFileName,
|
|
1150
|
+
specifier: relative.startsWith('../') ? relative : './' + relative,
|
|
1151
|
+
};
|
|
1152
|
+
};
|
|
1153
|
+
}
|
|
1154
|
+
function propsOf(file, importedRender, hostText, types) {
|
|
1155
|
+
const stem = file.slice(0, -path.extname(file).length);
|
|
1156
|
+
const dir = path.dirname(stem);
|
|
1157
|
+
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')))
|
|
1160
|
+
return () => false;
|
|
1161
|
+
const { sf, checker } = bind(file, fs.readFileSync(file, 'utf8'));
|
|
1162
|
+
const module = checker.getSymbolAtLocation(sf);
|
|
1163
|
+
const names = module && new Map(checker.getExportsOfModule(module).map((s) => [s.name, s]));
|
|
1164
|
+
const checks = new Map();
|
|
1165
|
+
const typeOf = (node) => projectTypeAt(node, types())?.type ?? checker.getTypeAtLocation(node);
|
|
1166
|
+
const renderTypes = { typeOf, text: (ref) => textKind(typeOf(ref)) !== 0 };
|
|
1167
|
+
return (destination, name, prop, ordinaryCaller, depth) => {
|
|
1168
|
+
let accepts = checks.get(destination);
|
|
1169
|
+
if (!accepts)
|
|
1170
|
+
checks.set(destination, (accepts = forwardedProps(sf, checker, destination === 'render' ? { imported: importedRender, ...renderTypes } : 'text', undefined, undefined, destination === 'forwarded-text' || destination === 'host-text'
|
|
1171
|
+
? { ...renderTypes, next: destination === 'forwarded-text' ? hostText : undefined }
|
|
1172
|
+
: undefined)));
|
|
1173
|
+
return accepts(names?.get(name), prop, ordinaryCaller, depth);
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
/** Which names each module exports as a context, following `export … from`. */
|
|
1177
|
+
function contextIndex(exports, files) {
|
|
1178
|
+
const resolved = new Map();
|
|
1179
|
+
const contextsOf = (file) => {
|
|
1180
|
+
let names = resolved.get(file);
|
|
1181
|
+
if (names)
|
|
1182
|
+
return names;
|
|
1183
|
+
names = new Set(exports.get(file)?.contexts);
|
|
1184
|
+
// Set before following re-exports, so a cycle ends.
|
|
1185
|
+
resolved.set(file, names);
|
|
1186
|
+
for (const { specifier, names: pairs } of exports.get(file)?.reexports ?? []) {
|
|
1187
|
+
const target = resolveModule(file, specifier, files);
|
|
1188
|
+
if (!target)
|
|
1189
|
+
continue;
|
|
1190
|
+
const theirs = contextsOf(target.file);
|
|
1191
|
+
if (pairs === null)
|
|
1192
|
+
for (const name of theirs)
|
|
1193
|
+
names.add(name);
|
|
1194
|
+
else
|
|
1195
|
+
for (const [imported, exported] of pairs)
|
|
1196
|
+
if (theirs.has(imported))
|
|
1197
|
+
names.add(exported);
|
|
1198
|
+
}
|
|
1199
|
+
return names;
|
|
1200
|
+
};
|
|
1201
|
+
return contextsOf;
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* The binding that replaces a React package import, recorded so the report
|
|
1205
|
+
* can list the dependency changes.
|
|
1206
|
+
*/
|
|
1207
|
+
function resolveBinding(specifier, file, project, packages, notes) {
|
|
1208
|
+
if (specifier === 'radix-ui' && !project.original(file, specifier)) {
|
|
1209
|
+
notes.push({
|
|
1210
|
+
rule: 'bindings',
|
|
1211
|
+
severity: 'error',
|
|
1212
|
+
line: 1,
|
|
1213
|
+
message: '`radix-ui` resolves to a different module through a TypeScript alias. Review the local component before migrating this import.',
|
|
1214
|
+
});
|
|
1215
|
+
return null;
|
|
1216
|
+
}
|
|
1217
|
+
const name = catalogName(specifier);
|
|
1218
|
+
if (name === null)
|
|
1219
|
+
return null;
|
|
1220
|
+
const target = CATALOG[name];
|
|
1221
|
+
const binding = packageName(target);
|
|
1222
|
+
const entry = DATA.bindings.find((candidate) => candidate.name === binding);
|
|
1223
|
+
const subpath = target.slice(binding.length) + specifier.slice(name.length);
|
|
1224
|
+
const served = entry && entry.exports.some((key) => serves(key, `.${subpath}`));
|
|
1225
|
+
if (target !== binding) {
|
|
1226
|
+
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;
|
|
1232
|
+
if (message) {
|
|
1233
|
+
notes.push({ rule: 'bindings', severity: 'error', line: 1, message });
|
|
1234
|
+
return null;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
packages.set(name, binding);
|
|
1238
|
+
// An aggregate binding (`@octanejs/visx`, for `@visx/visx`) serves each
|
|
1239
|
+
// package of its scope from a subpath: `@visx/hierarchy` is
|
|
1240
|
+
// `@octanejs/visx/hierarchy`.
|
|
1241
|
+
const upstream = entry?.upstream?.package;
|
|
1242
|
+
const aggregate = upstream?.match(/^@([^/]+)\/\1$/);
|
|
1243
|
+
if (target === binding &&
|
|
1244
|
+
aggregate &&
|
|
1245
|
+
name !== upstream &&
|
|
1246
|
+
name.startsWith(`@${aggregate[1]}/`)) {
|
|
1247
|
+
return `${binding}/${name.slice(aggregate[1].length + 2)}${specifier.slice(name.length)}`;
|
|
1248
|
+
}
|
|
1249
|
+
if (subpath === '' || served) {
|
|
1250
|
+
return binding + subpath;
|
|
1251
|
+
}
|
|
1252
|
+
// A binding outside the catalog has exports the codemod cannot see.
|
|
1253
|
+
notes.push(entry
|
|
1254
|
+
? {
|
|
1255
|
+
rule: 'bindings',
|
|
1256
|
+
severity: 'error',
|
|
1257
|
+
line: 1,
|
|
1258
|
+
message: `\`${binding}\` has no \`.${subpath}\` export. Import these names from its root if it exports them there.`,
|
|
1259
|
+
}
|
|
1260
|
+
: {
|
|
1261
|
+
rule: 'bindings',
|
|
1262
|
+
severity: 'warning',
|
|
1263
|
+
line: 1,
|
|
1264
|
+
message: `Check that \`${binding}${subpath}\` exists; the binding may export it from its root.`,
|
|
1265
|
+
});
|
|
1266
|
+
return binding + subpath;
|
|
1267
|
+
}
|
|
1268
|
+
function canUseBindingSubpath(file, root, binding, subpath, version) {
|
|
1269
|
+
const dir = path.dirname(file);
|
|
1270
|
+
const installed = readInstalled(dir, binding);
|
|
1271
|
+
if (installed) {
|
|
1272
|
+
if (installed.manifest.name !== binding)
|
|
1273
|
+
return false;
|
|
1274
|
+
const entry = record(installed.manifest.exports)[`.${subpath}`];
|
|
1275
|
+
let target = entry;
|
|
1276
|
+
if (isRecord(entry)) {
|
|
1277
|
+
const conditions = Object.entries(entry);
|
|
1278
|
+
if (conditions.some(([key]) => !['types', 'import', 'require', 'default'].includes(key)))
|
|
1279
|
+
return false;
|
|
1280
|
+
target = conditions.find(([key]) => key === 'import' || key === 'default')?.[1];
|
|
1281
|
+
}
|
|
1282
|
+
if (typeof target !== 'string' || !target.startsWith('./'))
|
|
1283
|
+
return false;
|
|
1284
|
+
const resolved = path.resolve(installed.dir, target);
|
|
1285
|
+
return (resolved.startsWith(installed.dir + path.sep) &&
|
|
1286
|
+
fs.statSync(resolved, { throwIfNoEntry: false })?.isFile());
|
|
1287
|
+
}
|
|
1288
|
+
// New dependencies use the catalog version. For a different declaration,
|
|
1289
|
+
// require an installed export before rewriting its imports.
|
|
1290
|
+
for (const project of new Set([root, findRoot(dir)])) {
|
|
1291
|
+
const manifestFile = path.join(project, 'package.json');
|
|
1292
|
+
if (!fs.existsSync(manifestFile))
|
|
1293
|
+
continue;
|
|
1294
|
+
const manifest = record(JSON.parse(fs.readFileSync(manifestFile, 'utf8')));
|
|
1295
|
+
if (DEPENDENCY_FIELDS.some((field) => {
|
|
1296
|
+
const spec = record(manifest[field])[binding];
|
|
1297
|
+
return spec !== undefined && spec !== version && spec !== `^${version}`;
|
|
1298
|
+
}))
|
|
1299
|
+
return false;
|
|
1300
|
+
}
|
|
1301
|
+
return true;
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* Whether a package `exports` key serves a subpath, directly or through a
|
|
1305
|
+
* `*` pattern such as `./locale/*`.
|
|
1306
|
+
*/
|
|
1307
|
+
function serves(key, subpath) {
|
|
1308
|
+
const [head, tail] = key.split('*');
|
|
1309
|
+
return tail === undefined ? key === subpath : subpath.startsWith(head) && subpath.endsWith(tail);
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* The catalog entry for a package specifier, or null. The catalog keys some
|
|
1313
|
+
* bindings by subpath (`better-auth/react`), so the longest matching prefix
|
|
1314
|
+
* wins.
|
|
1315
|
+
*/
|
|
1316
|
+
function catalogName(specifier) {
|
|
1317
|
+
if (specifier.startsWith('.') || specifier.startsWith('/'))
|
|
1318
|
+
return null;
|
|
1319
|
+
const parts = specifier.split('/');
|
|
1320
|
+
for (let length = parts.length; length > 0; length--) {
|
|
1321
|
+
const candidate = parts.slice(0, length).join('/');
|
|
1322
|
+
if (candidate in CATALOG)
|
|
1323
|
+
return candidate;
|
|
1324
|
+
}
|
|
1325
|
+
return null;
|
|
1326
|
+
}
|
|
1327
|
+
/**
|
|
1328
|
+
* The React package a specifier names when Octane has no binding for it, or
|
|
1329
|
+
* null.
|
|
1330
|
+
* @param from the importing module
|
|
1331
|
+
*/
|
|
1332
|
+
function unportedName(specifier, from) {
|
|
1333
|
+
if (specifier.startsWith('.') || specifier.startsWith('/') || catalogName(specifier) !== null)
|
|
1334
|
+
return null;
|
|
1335
|
+
const root = packageName(specifier);
|
|
1336
|
+
// Any package's `/react` entry renders with React (`@tanstack/markdown/react`).
|
|
1337
|
+
if (/\/react(?:\/|$)/.test(specifier.slice(root.length)))
|
|
1338
|
+
return specifier;
|
|
1339
|
+
return rendersWithReact(root, from) ? root : null;
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* The package a bare specifier imports from: `@pierre/diffs` for
|
|
1343
|
+
* `@pierre/diffs/react`.
|
|
1344
|
+
*/
|
|
1345
|
+
function packageName(specifier) {
|
|
1346
|
+
return specifier
|
|
1347
|
+
.split('/')
|
|
1348
|
+
.slice(0, specifier.startsWith('@') ? 2 : 1)
|
|
1349
|
+
.join('/');
|
|
1350
|
+
}
|
|
1351
|
+
function isRecord(value) {
|
|
1352
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
1353
|
+
}
|
|
1354
|
+
function record(value) {
|
|
1355
|
+
return isRecord(value) ? value : {};
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Add the bindings the migrated code imports to the project's package.json,
|
|
1359
|
+
* each at its catalog version and in the field that lists the React package it
|
|
1360
|
+
* replaces. TanStack publishes its Octane adapters outside the catalog, so
|
|
1361
|
+
* those take `latest`.
|
|
1362
|
+
*/
|
|
1363
|
+
function addBindings(root, packages, write) {
|
|
1364
|
+
const file = path.join(root, 'package.json');
|
|
1365
|
+
if (!fs.existsSync(file))
|
|
1366
|
+
return [];
|
|
1367
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
1368
|
+
const manifest = JSON.parse(text);
|
|
1369
|
+
if (packages.size === 0)
|
|
1370
|
+
return [];
|
|
1371
|
+
if (!isRecord(manifest) ||
|
|
1372
|
+
DEPENDENCY_FIELDS.some((field) => manifest[field] !== undefined && !isRecord(manifest[field]))) {
|
|
1373
|
+
throw new Error('Cannot add bindings to malformed package.json dependency fields.');
|
|
1374
|
+
}
|
|
1375
|
+
const added = [];
|
|
1376
|
+
for (const [from, to] of packages) {
|
|
1377
|
+
if (DEPENDENCY_FIELDS.some((field) => record(manifest[field])[to] !== undefined))
|
|
1378
|
+
continue;
|
|
1379
|
+
const version = DATA.bindings.find((binding) => binding.name === to)?.version;
|
|
1380
|
+
const range = version ? `^${version}` : 'latest';
|
|
1381
|
+
const field = record(manifest.devDependencies)[packageName(from)]
|
|
1382
|
+
? 'devDependencies'
|
|
1383
|
+
: 'dependencies';
|
|
1384
|
+
manifest[field] = Object.fromEntries(Object.entries({ ...record(manifest[field]), [to]: range }).sort(([a], [b]) => a.localeCompare(b)));
|
|
1385
|
+
added.push({ name: to, range });
|
|
1386
|
+
}
|
|
1387
|
+
if (write && added.length > 0) {
|
|
1388
|
+
const indent = /^[ \t]+/m.exec(text)?.[0] ?? ' ';
|
|
1389
|
+
fs.writeFileSync(file, JSON.stringify(manifest, null, indent) + '\n');
|
|
1390
|
+
}
|
|
1391
|
+
return added;
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* The patches a project applies to the React packages the migration replaces,
|
|
1395
|
+
* which stop applying once the code imports the binding instead: pnpm's and
|
|
1396
|
+
* Bun's `patchedDependencies`, in package.json or pnpm-workspace.yaml, and
|
|
1397
|
+
* patch-package's `patches/name+version.patch`. They live where the project
|
|
1398
|
+
* installs, so each directory up from `root` is read until a lockfile.
|
|
1399
|
+
*/
|
|
1400
|
+
function patchedPackages(root, packages) {
|
|
1401
|
+
const replaced = new Set([...packages.keys()].map(packageName));
|
|
1402
|
+
const patched = [];
|
|
1403
|
+
for (let dir = root;; dir = path.dirname(dir)) {
|
|
1404
|
+
const read = (name) => {
|
|
1405
|
+
const file = path.join(dir, name);
|
|
1406
|
+
return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
|
|
1407
|
+
};
|
|
1408
|
+
const manifest = record(JSON.parse(read('package.json') ?? '{}'));
|
|
1409
|
+
/** `name@version` and its patch */
|
|
1410
|
+
const declared = Object.entries({
|
|
1411
|
+
...record(record(manifest.pnpm).patchedDependencies),
|
|
1412
|
+
...record(manifest.patchedDependencies),
|
|
1413
|
+
}).filter((entry) => typeof entry[1] === 'string');
|
|
1414
|
+
const workspace = /^patchedDependencies:[ \t]*\r?\n((?:[ \t]+.*\r?\n?)*)/m.exec(read('pnpm-workspace.yaml') ?? '')?.[1] ?? '';
|
|
1415
|
+
for (const [, , key, , patch] of workspace.matchAll(/^[ \t]+(["']?)(.+?)\1:[ \t]*(["']?)(.+?)\3[ \t]*$/gm)) {
|
|
1416
|
+
declared.push([key, patch]);
|
|
1417
|
+
}
|
|
1418
|
+
const patches = path.join(dir, 'patches');
|
|
1419
|
+
for (const name of fs.existsSync(patches) ? fs.readdirSync(patches) : []) {
|
|
1420
|
+
const match = /^((?:@[^+]+\+)?[^+]+)\+[^+]+\.patch$/.exec(name);
|
|
1421
|
+
if (match)
|
|
1422
|
+
declared.push([match[1].replace('+', '/'), `patches/${name}`]);
|
|
1423
|
+
}
|
|
1424
|
+
for (const [key, patch] of declared) {
|
|
1425
|
+
const name = key.replace(/(?!^)@[^@]*$/, '');
|
|
1426
|
+
if (replaced.has(name))
|
|
1427
|
+
patched.push({ name, patch: path.relative(root, path.join(dir, patch)) });
|
|
1428
|
+
}
|
|
1429
|
+
const installed = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb'];
|
|
1430
|
+
if (installed.some((name) => fs.existsSync(path.join(dir, name))) || path.dirname(dir) === dir)
|
|
1431
|
+
return patched;
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
/**
|
|
1435
|
+
* Whether a package renders through React: it declares `react` as a peer or
|
|
1436
|
+
* dependency when installed, or its name says so when it is not. A package
|
|
1437
|
+
* with a `./react` entry (`@pierre/trees/react`) renders through React there,
|
|
1438
|
+
* which the caller matches by subpath; its other entries need no binding. An
|
|
1439
|
+
* optional peer alone does not say which entries use React.
|
|
1440
|
+
*/
|
|
1441
|
+
function rendersWithReact(name, from) {
|
|
1442
|
+
if (name === 'octane' || name.startsWith('@octanejs/') || name.startsWith('node:'))
|
|
1443
|
+
return false;
|
|
1444
|
+
const manifest = readInstalled(path.dirname(from), name)?.manifest;
|
|
1445
|
+
if (!isRecord(manifest))
|
|
1446
|
+
return REACT_PACKAGE.test(name);
|
|
1447
|
+
if (record(manifest.exports)['./react'])
|
|
1448
|
+
return false;
|
|
1449
|
+
return ['peerDependencies', 'dependencies'].some((field) => record(manifest[field]).react !== undefined);
|
|
1450
|
+
}
|
|
1451
|
+
/**
|
|
1452
|
+
* Point `<script src>` in HTML entry pages at renamed modules.
|
|
1453
|
+
* @param targets the paths being migrated
|
|
1454
|
+
*/
|
|
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);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
return updated;
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* Follow imports outside the migrated paths as well as exact path strings
|
|
1477
|
+
* in scripts and configs. Parse TSRX importers with their own grammar so
|
|
1478
|
+
* template text that looks like an import remains text.
|
|
1479
|
+
*/
|
|
1480
|
+
function rewriteModulePaths(code, file, root, renames, resolveRename) {
|
|
1481
|
+
const edits = [];
|
|
1482
|
+
function literal(value, start, end, moduleSource) {
|
|
1483
|
+
if (!moduleSource) {
|
|
1484
|
+
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' });
|
|
1489
|
+
}
|
|
1490
|
+
return;
|
|
1491
|
+
}
|
|
1492
|
+
const next = resolveRename(file, value);
|
|
1493
|
+
if (next) {
|
|
1494
|
+
const quoted = JSON.stringify(next);
|
|
1495
|
+
const text = code[start] === "'" ? "'" + quoted.slice(1, -1).replaceAll("'", "\\'") + "'" : quoted;
|
|
1496
|
+
edits.push({ start, end, text });
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
if (isTsrx(file)) {
|
|
1500
|
+
const { program } = parseSync(file, code);
|
|
1501
|
+
// TSRX has dialect nodes beyond TypeScript's visitor. Inspect only the fields
|
|
1502
|
+
// shared by parsed module sources and recurse through the parser's AST.
|
|
1503
|
+
const visit = (node) => {
|
|
1504
|
+
if (Array.isArray(node)) {
|
|
1505
|
+
for (const item of node)
|
|
1506
|
+
visit(item);
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
if (!isRecord(node) || typeof node.type !== 'string')
|
|
1510
|
+
return;
|
|
1511
|
+
const source = node.source ?? (node.type === 'TSExternalModuleReference' ? node.expression : null);
|
|
1512
|
+
if (isRecord(source) && typeof source.start === 'number' && typeof source.end === 'number') {
|
|
1513
|
+
if (source.type === 'Literal' && typeof source.value === 'string') {
|
|
1514
|
+
literal(source.value, source.start, source.end, true);
|
|
1515
|
+
}
|
|
1516
|
+
else if (source.type === 'TemplateLiteral' &&
|
|
1517
|
+
Array.isArray(source.expressions) &&
|
|
1518
|
+
!source.expressions.length &&
|
|
1519
|
+
Array.isArray(source.quasis)) {
|
|
1520
|
+
const quasi = source.quasis[0];
|
|
1521
|
+
if (isRecord(quasi) && isRecord(quasi.value) && typeof quasi.value.cooked === 'string') {
|
|
1522
|
+
literal(quasi.value.cooked, source.start, source.end, true);
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
for (const child of Object.values(node))
|
|
1527
|
+
visit(child);
|
|
1528
|
+
};
|
|
1529
|
+
if (program)
|
|
1530
|
+
visit(program);
|
|
1531
|
+
}
|
|
1532
|
+
else {
|
|
1533
|
+
const sf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest, true);
|
|
1534
|
+
const visit = (node) => {
|
|
1535
|
+
if (ts.isStringLiteralLike(node)) {
|
|
1536
|
+
const p = node.parent;
|
|
1537
|
+
const moduleSource = ((ts.isImportDeclaration(p) || ts.isExportDeclaration(p)) &&
|
|
1538
|
+
p.moduleSpecifier === node) ||
|
|
1539
|
+
ts.isExternalModuleReference(p) ||
|
|
1540
|
+
(ts.isLiteralTypeNode(p) && ts.isImportTypeNode(p.parent) && p.parent.argument === p) ||
|
|
1541
|
+
(ts.isCallExpression(p) &&
|
|
1542
|
+
p.expression.kind === ts.SyntaxKind.ImportKeyword &&
|
|
1543
|
+
p.arguments[0] === node);
|
|
1544
|
+
literal(node.text, node.getStart(sf), node.end, moduleSource);
|
|
1545
|
+
}
|
|
1546
|
+
ts.forEachChild(node, visit);
|
|
1547
|
+
};
|
|
1548
|
+
visit(sf);
|
|
1549
|
+
}
|
|
1550
|
+
if (!edits.length)
|
|
1551
|
+
return null;
|
|
1552
|
+
for (const { start, end, text } of edits.sort((a, b) => b.start - a.start))
|
|
1553
|
+
code = code.slice(0, start) + text + code.slice(end);
|
|
1554
|
+
return { code, count: edits.length };
|
|
1555
|
+
}
|
|
1556
|
+
/**
|
|
1557
|
+
* The HTML pages a Vite or CRA app keeps beside its sources: those in the
|
|
1558
|
+
* root, `public/`, `src/`, and each migrated directory.
|
|
1559
|
+
*/
|
|
1560
|
+
function findHtml(root, targets) {
|
|
1561
|
+
const dirs = new Set([root, path.join(root, 'public'), path.join(root, 'src'), ...targets]);
|
|
1562
|
+
return [...dirs]
|
|
1563
|
+
.filter((dir) => fs.existsSync(dir) && fs.statSync(dir).isDirectory())
|
|
1564
|
+
.flatMap((dir) => fs
|
|
1565
|
+
.readdirSync(dir)
|
|
1566
|
+
.filter((name) => name.endsWith('.html'))
|
|
1567
|
+
.map((name) => path.join(dir, name)));
|
|
1568
|
+
}
|