@octanejs/codemod 0.0.0-stage → 0.1.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/src/project.js ADDED
@@ -0,0 +1,538 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { findRoot, readInstalled, scanSourceFiles } from '@octanejs/cli';
4
+ import { DATA } from '@octanejs/cli/data';
5
+ import ts from 'typescript';
6
+ import { finding, loadCompiler, thrown } from './compiler.js';
7
+ import { PORTED_PACKAGES } from './mappings.js';
8
+ import { strengthen } from './strong.js';
9
+ import { transformModule } from './transform.js';
10
+
11
+ /**
12
+ * @typedef {import('./transform.js').Note} Note
13
+ *
14
+ * @typedef {Object} CodemodOptions
15
+ * @property {'tsrx' | 'tsx'} [target]
16
+ * @property {boolean} [strong] migrate to Strong mode where the compiler
17
+ * accepts it, falling back to compatibility mode per module
18
+ * @property {boolean} [forceStrong] keep `"use strong"` even on modules with
19
+ * Strong errors left
20
+ * @property {boolean} [verify] compile every migrated module (default true)
21
+ * @property {boolean} [write] write the result to disk (default true)
22
+ * @property {string} [root] the project root, for resolving its compiler
23
+ *
24
+ * @typedef {Object} FileResult
25
+ * @property {string} file the module's path, relative to the root
26
+ * @property {string} output where it is written, relative to the root
27
+ * @property {boolean} changed
28
+ * @property {Record<string, number>} rules
29
+ * @property {Note[]} notes the codemod's own findings, at the original file's
30
+ * lines
31
+ * @property {boolean | null} strong whether it is Strong, or null when Strong
32
+ * was not requested or does not apply
33
+ * @property {string[]} strongFixes
34
+ * @property {{ code: string, severity: string, message: string, line: number }[]} diagnostics
35
+ * what the compiler reported for the migrated module
36
+ * @property {string} code
37
+ *
38
+ * @typedef {Object} CodemodResult
39
+ * @property {string} root
40
+ * @property {FileResult[]} files
41
+ * @property {{ from: string, to: string }[]} packages React packages the
42
+ * migrated code now imports as Octane bindings
43
+ * @property {Missing[]} missing React packages the code imports that have no
44
+ * Octane port, and how it uses them
45
+ * @property {string[]} html entry pages whose script reference was updated
46
+ * @property {string | null} compiler where the verifying compiler came from
47
+ *
48
+ * @typedef {import('./transform.js').Unported & { modules: number }} Missing
49
+ * with how many modules import it
50
+ */
51
+
52
+ const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
53
+ /** React packages and the Octane package that replaces each. */
54
+ const CATALOG = { ...DATA.reactPackages, ...PORTED_PACKAGES };
55
+ /** A package that, by its name, renders through React. */
56
+ const REACT_PACKAGE = /^(?:react-|@[^/]+\/react(?:-|\/|$)|[^/]+\/react$)|-react(?:\/|$)/;
57
+
58
+ /**
59
+ * Migrate every React module under `paths`.
60
+ *
61
+ * Two passes: the first decides which modules become `.tsrx`, the second
62
+ * rewrites every module with that rename map in hand, so an import of a
63
+ * renamed module is updated wherever it is.
64
+ *
65
+ * @param {string[]} paths
66
+ * @param {CodemodOptions} [options]
67
+ * @returns {Promise<CodemodResult>}
68
+ */
69
+ export async function runCodemod(paths, options = {}) {
70
+ const target = options.target ?? 'tsrx';
71
+ const strong = options.strong === true && target === 'tsrx';
72
+ const root = path.resolve(options.root ?? findRoot(paths[0] ?? '.'));
73
+ const files = paths.flatMap((entry) => collect(path.resolve(entry)));
74
+
75
+ const known = new Set(files);
76
+ const config = tsconfigOptions(root);
77
+ const program = projectProgram(config, files);
78
+ const checker = program?.getTypeChecker();
79
+ /** @type {Map<string, string>} */
80
+ const renames = new Map();
81
+ /** @type {Map<string, import('./transform.js').ModuleExports>} */
82
+ const exports = new Map();
83
+ for (const file of files) {
84
+ const result = transformModule(fs.readFileSync(file, 'utf8'), file, { target });
85
+ exports.set(file, result.exports);
86
+ if (result.template) renames.set(file, file.replace(/\.(?:jsx?|tsx)$/, '.tsrx'));
87
+ }
88
+ const contextsOf = contextIndex(exports, known);
89
+
90
+ const verify = options.verify !== false;
91
+ const compiler = verify || strong ? await loadCompiler(root) : null;
92
+ /** @type {Map<string, string>} */
93
+ const packages = new Map();
94
+ /** @type {Map<string, Missing>} */
95
+ const missing = new Map();
96
+ // `ReactCompat` hosts a component from a package with no port in a React
97
+ // root, from 19.2 within the React 19 series it supports.
98
+ const reactCompat = ['react', 'react-dom'].every((name) =>
99
+ /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''),
100
+ );
101
+ /** @type {FileResult[]} */
102
+ const results = [];
103
+ for (const file of files) {
104
+ const source = fs.readFileSync(file, 'utf8');
105
+ /** @type {Note[]} */
106
+ const extra = [];
107
+ const resolveSpecifier = (/** @type {string} */ specifier) =>
108
+ resolveRelative(file, specifier, known, renames) ??
109
+ resolveAlias(file, specifier, renames, config) ??
110
+ resolveBinding(specifier, packages, extra);
111
+ const isContext = (/** @type {string} */ specifier, /** @type {string} */ name) => {
112
+ if (!specifier.startsWith('.')) return null;
113
+ const target = resolveModule(file, specifier, known);
114
+ return target ? contextsOf(target.file).has(name) : null;
115
+ };
116
+ const sourceFile = program?.getSourceFile(file);
117
+ const result = transformModule(source, file, {
118
+ target,
119
+ strong,
120
+ strictNullChecks: program !== null,
121
+ types: sourceFile && checker && { sourceFile, checker },
122
+ resolveSpecifier,
123
+ isContext,
124
+ unported: (specifier) => unportedName(specifier, file),
125
+ reactCompat,
126
+ });
127
+ for (const port of result.unported) {
128
+ const entry = missing.get(port.name) ?? {
129
+ name: port.name,
130
+ modules: 0,
131
+ islands: 0,
132
+ blocked: 0,
133
+ };
134
+ entry.modules++;
135
+ entry.islands += port.islands;
136
+ entry.blocked += port.blocked;
137
+ missing.set(port.name, entry);
138
+ }
139
+ const output = renames.get(file) ?? file;
140
+ let code = result.code;
141
+ /** @type {boolean | null} */
142
+ let isStrong = null;
143
+ /** @type {string[]} */
144
+ let strongFixes = [];
145
+ /** @type {FileResult['diagnostics']} */
146
+ let diagnostics = [];
147
+ if (compiler && result.changed) {
148
+ if (strong && result.template) {
149
+ const strengthened = strengthen(compiler, code, output, { force: options.forceStrong });
150
+ code = strengthened.code;
151
+ isStrong = strengthened.strong;
152
+ strongFixes = strengthened.fixed;
153
+ if (!strengthened.strong) diagnostics.push(...strengthened.blockers);
154
+ }
155
+ if (verify && isCompiled(output, code))
156
+ diagnostics.push(...compile(compiler, code, output, isStrong === true));
157
+ }
158
+ results.push({
159
+ file: path.relative(root, file),
160
+ output: path.relative(root, output),
161
+ changed: result.changed || output !== file,
162
+ rules: result.rules,
163
+ notes: [...result.notes, ...extra],
164
+ strong: isStrong,
165
+ strongFixes,
166
+ diagnostics: dedupe(diagnostics),
167
+ code,
168
+ });
169
+ }
170
+
171
+ // TSRX written for React (`@tsrx/react`) is a dialect the TypeScript
172
+ // parser cannot read, so it is reported rather than skipped silently.
173
+ for (const file of paths.flatMap((entry) => collect(path.resolve(entry), isTsrx))) {
174
+ const source = fs.readFileSync(file, 'utf8');
175
+ const react = /^import\b[^;]*?\bfrom\s+['"]react(?:-dom)?(?:\/[^'"]*)?['"]/m.exec(source);
176
+ if (!react || /\bfrom\s+['"]octane(?:\/[^'"]*)?['"]/.test(source)) continue;
177
+ results.push({
178
+ file: path.relative(root, file),
179
+ output: path.relative(root, file),
180
+ changed: false,
181
+ rules: {},
182
+ notes: [
183
+ {
184
+ rule: 'tsrx-react',
185
+ severity: 'error',
186
+ line: source.slice(0, react.index).split('\n').length,
187
+ message:
188
+ '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.',
189
+ },
190
+ ],
191
+ strong: null,
192
+ strongFixes: [],
193
+ diagnostics: [],
194
+ code: source,
195
+ });
196
+ }
197
+
198
+ const html = rewriteEntryPages(
199
+ root,
200
+ paths.map((entry) => path.resolve(entry)),
201
+ renames,
202
+ options.write !== false,
203
+ );
204
+ if (options.write !== false) {
205
+ for (const result of results) {
206
+ if (!result.changed) continue;
207
+ const output = path.join(root, result.output);
208
+ fs.writeFileSync(output, result.code);
209
+ if (result.output !== result.file) fs.rmSync(path.join(root, result.file));
210
+ }
211
+ }
212
+ return {
213
+ root,
214
+ files: results,
215
+ packages: [...packages].map(([from, to]) => ({ from, to })),
216
+ missing: [...missing.values()].sort((a, b) => a.name.localeCompare(b.name)),
217
+ html,
218
+ compiler: compiler?.from ?? null,
219
+ };
220
+ }
221
+
222
+ /**
223
+ * Whether Octane compiles this module: `.tsrx`, JSX, or a module that imports
224
+ * the runtime. A declaration file is only types.
225
+ *
226
+ * @param {string} file
227
+ * @param {string} code
228
+ */
229
+ function isCompiled(file, code) {
230
+ if (file.endsWith('.d.ts')) return false;
231
+ return /\.(?:tsrx|[jt]sx)$/.test(file) || /from\s+['"]octane['"]/.test(code);
232
+ }
233
+
234
+ /**
235
+ * @param {import('./compiler.js').Compiler} compiler
236
+ * @param {string} code
237
+ * @param {string} file
238
+ * @param {boolean} strong
239
+ */
240
+ function compile(compiler, code, file, strong) {
241
+ try {
242
+ const result = compiler.collectDiagnostics(code, file, strong ? { strong: true } : {});
243
+ const found = result.diagnostics.filter((d) => d.severity !== 'hint').map(finding);
244
+ return result.error == null ? found : [...found, thrown(result.error)];
245
+ } catch (error) {
246
+ return [thrown(error)];
247
+ }
248
+ }
249
+
250
+ /** @param {FileResult['diagnostics']} diagnostics */
251
+ function dedupe(diagnostics) {
252
+ const seen = new Set();
253
+ return diagnostics.filter((d) => {
254
+ const key = `${d.code}:${d.line}:${d.message}`;
255
+ if (seen.has(key)) return false;
256
+ seen.add(key);
257
+ return true;
258
+ });
259
+ }
260
+
261
+ /**
262
+ * The modules under `entry` that pass `test`: by default, those the codemod
263
+ * migrates.
264
+ *
265
+ * @param {string} entry
266
+ * @param {(name: string) => boolean} [test]
267
+ */
268
+ function collect(entry, test = isSource) {
269
+ if (fs.statSync(entry).isFile()) return test(entry) ? [entry] : [];
270
+ return scanSourceFiles(entry, { limit: Infinity }).filter(test).sort();
271
+ }
272
+
273
+ /** @param {string} name */
274
+ function isTsrx(name) {
275
+ return name.endsWith('.tsrx');
276
+ }
277
+
278
+ /**
279
+ * The compiler options of the tsconfig that governs `root`, or null.
280
+ *
281
+ * @param {string} root
282
+ * @returns {ts.CompilerOptions | null}
283
+ */
284
+ function tsconfigOptions(root) {
285
+ const file = ts.findConfigFile(root, ts.sys.fileExists);
286
+ if (!file) return null;
287
+ const { config } = ts.readConfigFile(file, ts.sys.readFile);
288
+ return ts.parseJsonConfigFileContent(config ?? {}, ts.sys, path.dirname(file)).options;
289
+ }
290
+
291
+ /**
292
+ * A program over the TypeScript modules being migrated, under the project's
293
+ * tsconfig, so their types resolve through imports. Null unless that config
294
+ * enables `strictNullChecks`: without it a `string` may still hold null, so
295
+ * types cannot prove a hole is text.
296
+ *
297
+ * @param {ts.CompilerOptions | null} options
298
+ * @param {string[]} files
299
+ */
300
+ function projectProgram(options, files) {
301
+ if (!options || !(options.strictNullChecks ?? options.strict)) return null;
302
+ return ts.createProgram(
303
+ files.filter((name) => /\.[cm]?tsx?$/.test(name)),
304
+ // As the compiler's typed-text proof requires.
305
+ { ...options, noEmit: true, noUncheckedIndexedAccess: true },
306
+ );
307
+ }
308
+
309
+ /**
310
+ * Bundler and tool configs belong to `octane init`, not the codemod.
311
+ *
312
+ * @param {string} name
313
+ */
314
+ function isSource(name) {
315
+ return SOURCE.test(name) && !/\.config\.[cm]?[jt]s$/.test(name);
316
+ }
317
+
318
+ /**
319
+ * The project module a relative specifier names, trying the extensions and
320
+ * directory indexes a bundler would.
321
+ *
322
+ * @param {string} from
323
+ * @param {string} specifier
324
+ * @param {Set<string>} files
325
+ * @returns {{ file: string, index: boolean } | null}
326
+ */
327
+ function resolveModule(from, specifier, files) {
328
+ if (!specifier.startsWith('.')) return null;
329
+ const base = path.resolve(path.dirname(from), specifier);
330
+ const stem = base.replace(/\.(?:[cm]?[jt]sx?)$/, '');
331
+ for (const file of [base, ...['.tsx', '.ts', '.jsx', '.js'].map((ext) => stem + ext)]) {
332
+ if (files.has(file)) return { file, index: false };
333
+ }
334
+ for (const ext of ['.tsx', '.ts', '.jsx', '.js']) {
335
+ const file = path.join(base, 'index' + ext);
336
+ if (files.has(file)) return { file, index: true };
337
+ }
338
+ return null;
339
+ }
340
+
341
+ /**
342
+ * The new specifier for a relative import of a renamed module. `.tsrx` modules
343
+ * are imported by their full name.
344
+ *
345
+ * @param {string} from
346
+ * @param {string} specifier
347
+ * @param {Set<string>} files
348
+ * @param {Map<string, string>} renames
349
+ */
350
+ function resolveRelative(from, specifier, files, renames) {
351
+ const target = resolveModule(from, specifier, files);
352
+ if (!target || !renames.has(target.file)) return null;
353
+ if (target.index) return specifier.replace(/\/?$/, '/index.tsrx');
354
+ return specifier.replace(/\.(?:[cm]?[jt]sx?)$/, '') + '.tsrx';
355
+ }
356
+
357
+ /**
358
+ * The new specifier for an import of a renamed module through a tsconfig
359
+ * `paths` alias (`~/components/Card`), resolved as TypeScript resolves it.
360
+ *
361
+ * @param {string} from
362
+ * @param {string} specifier
363
+ * @param {Map<string, string>} renames
364
+ * @param {ts.CompilerOptions | null} options
365
+ */
366
+ function resolveAlias(from, specifier, renames, options) {
367
+ if (!options?.paths || specifier.startsWith('.')) return null;
368
+ const file = ts.resolveModuleName(specifier, from, { ...options, preserveSymlinks: true }, ts.sys)
369
+ .resolvedModule?.resolvedFileName;
370
+ if (!file || !renames.has(file)) return null;
371
+ if (SOURCE.test(specifier)) return specifier.replace(SOURCE, '.tsrx');
372
+ return path.basename(file).startsWith('index.') && !/(?:^|\/)index$/.test(specifier)
373
+ ? `${specifier}/index.tsrx`
374
+ : `${specifier}.tsrx`;
375
+ }
376
+
377
+ /**
378
+ * Which names each module exports as a context, following `export … from`.
379
+ *
380
+ * @param {Map<string, import('./transform.js').ModuleExports>} exports
381
+ * @param {Set<string>} files
382
+ * @returns {(file: string) => Set<string>}
383
+ */
384
+ function contextIndex(exports, files) {
385
+ /** @type {Map<string, Set<string>>} */
386
+ const resolved = new Map();
387
+ const contextsOf = (/** @type {string} */ file) => {
388
+ let names = resolved.get(file);
389
+ if (names) return names;
390
+ names = new Set(exports.get(file)?.contexts);
391
+ // Set before following re-exports, so a cycle ends.
392
+ resolved.set(file, names);
393
+ for (const { specifier, names: pairs } of exports.get(file)?.reexports ?? []) {
394
+ const target = resolveModule(file, specifier, files);
395
+ if (!target) continue;
396
+ const theirs = contextsOf(target.file);
397
+ if (pairs === null) for (const name of theirs) names.add(name);
398
+ else for (const [imported, exported] of pairs) if (theirs.has(imported)) names.add(exported);
399
+ }
400
+ return names;
401
+ };
402
+ return contextsOf;
403
+ }
404
+
405
+ /**
406
+ * The binding that replaces a React package import, recorded so the report
407
+ * can list the dependency changes.
408
+ *
409
+ * @param {string} specifier
410
+ * @param {Map<string, string>} packages
411
+ * @param {Note[]} notes
412
+ */
413
+ function resolveBinding(specifier, packages, notes) {
414
+ const name = catalogName(specifier);
415
+ if (name === null) return null;
416
+ const binding = CATALOG[name];
417
+ packages.set(name, binding);
418
+ // An aggregate binding (`@octanejs/visx`, for `@visx/visx`) serves each
419
+ // package of its scope from a subpath: `@visx/hierarchy` is
420
+ // `@octanejs/visx/hierarchy`.
421
+ const upstream = DATA.bindings.find((entry) => entry.name === binding)?.upstream?.package;
422
+ const aggregate = upstream?.match(/^@([^/]+)\/\1$/);
423
+ if (aggregate && name !== upstream && name.startsWith(`@${aggregate[1]}/`)) {
424
+ return `${binding}/${name.slice(aggregate[1].length + 2)}${specifier.slice(name.length)}`;
425
+ }
426
+ const subpath = specifier.slice(name.length);
427
+ if (subpath !== '') {
428
+ notes.push({
429
+ rule: 'bindings',
430
+ severity: 'warning',
431
+ line: 1,
432
+ message: `Check that \`${binding}${subpath}\` exists; the binding may export it from its root.`,
433
+ });
434
+ }
435
+ return binding + subpath;
436
+ }
437
+
438
+ /**
439
+ * The catalog entry for a package specifier, or null. The catalog keys some
440
+ * bindings by subpath (`better-auth/react`), so the longest matching prefix
441
+ * wins.
442
+ *
443
+ * @param {string} specifier
444
+ */
445
+ function catalogName(specifier) {
446
+ if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
447
+ const parts = specifier.split('/');
448
+ for (let length = parts.length; length > 0; length--) {
449
+ const candidate = parts.slice(0, length).join('/');
450
+ if (candidate in CATALOG) return candidate;
451
+ }
452
+ return null;
453
+ }
454
+
455
+ /**
456
+ * The React package a specifier names when Octane has no binding for it, or
457
+ * null.
458
+ *
459
+ * @param {string} specifier
460
+ * @param {string} from the importing module
461
+ */
462
+ function unportedName(specifier, from) {
463
+ if (specifier.startsWith('.') || specifier.startsWith('/') || catalogName(specifier) !== null)
464
+ return null;
465
+ const parts = specifier.split('/');
466
+ const root = specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
467
+ // Any package's `/react` entry renders with React (`@tanstack/markdown/react`).
468
+ if (/\/react(?:\/|$)/.test(specifier.slice(root.length))) return specifier;
469
+ return rendersWithReact(root, from) ? root : null;
470
+ }
471
+
472
+ /**
473
+ * Whether a package renders through React: it declares `react` as a peer or
474
+ * dependency when installed, or its name says so when it is not. A package
475
+ * with a `./react` entry (`@pierre/trees/react`) renders through React there,
476
+ * which the caller matches by subpath; its other entries need no binding. An
477
+ * optional peer alone does not say which entries use React.
478
+ *
479
+ * @param {string} name
480
+ * @param {string} from
481
+ */
482
+ function rendersWithReact(name, from) {
483
+ if (name === 'octane' || name.startsWith('@octanejs/') || name.startsWith('node:')) return false;
484
+ const manifest = readInstalled(path.dirname(from), name)?.manifest;
485
+ if (!manifest) return REACT_PACKAGE.test(name);
486
+ if (manifest.exports?.['./react']) return false;
487
+ return ['peerDependencies', 'dependencies'].some((field) => manifest[field]?.react !== undefined);
488
+ }
489
+
490
+ /**
491
+ * Point `<script src>` in HTML entry pages at renamed modules.
492
+ *
493
+ * @param {string} root
494
+ * @param {string[]} targets the paths being migrated
495
+ * @param {Map<string, string>} renames
496
+ * @param {boolean} write
497
+ */
498
+ function rewriteEntryPages(root, targets, renames, write) {
499
+ /** @type {string[]} */
500
+ const updated = [];
501
+ for (const page of findHtml(root, targets)) {
502
+ const html = fs.readFileSync(page, 'utf8');
503
+ const next = html.replace(
504
+ /(<script\b[^>]*\bsrc=)(["'])([^"']+)\2/g,
505
+ (match, open, quote, src) => {
506
+ // Vite serves `/` from the page's own directory, as it does `./`.
507
+ const file = path.join(path.dirname(page), src);
508
+ const renamed = renames.get(file);
509
+ if (!renamed) return match;
510
+ return open + quote + src.replace(/\.[jt]sx?$/, '.tsrx') + quote;
511
+ },
512
+ );
513
+ if (next !== html) {
514
+ updated.push(path.relative(root, page));
515
+ if (write) fs.writeFileSync(page, next);
516
+ }
517
+ }
518
+ return updated;
519
+ }
520
+
521
+ /**
522
+ * The HTML pages a Vite or CRA app keeps beside its sources: those in the
523
+ * root, `public/`, `src/`, and each migrated directory.
524
+ *
525
+ * @param {string} root
526
+ * @param {string[]} targets
527
+ */
528
+ function findHtml(root, targets) {
529
+ const dirs = new Set([root, path.join(root, 'public'), path.join(root, 'src'), ...targets]);
530
+ return [...dirs]
531
+ .filter((dir) => fs.existsSync(dir) && fs.statSync(dir).isDirectory())
532
+ .flatMap((dir) =>
533
+ fs
534
+ .readdirSync(dir)
535
+ .filter((name) => name.endsWith('.html'))
536
+ .map((name) => path.join(dir, name)),
537
+ );
538
+ }
package/src/strong.js ADDED
@@ -0,0 +1,149 @@
1
+ import { applyFixes, pruneImports } from '@octanejs/cli/fix';
2
+ import { finding, thrown } from './compiler.js';
3
+
4
+ /**
5
+ * @typedef {import('./compiler.js').Compiler} Compiler
6
+ * @typedef {import('./compiler.js').Finding} Finding
7
+ *
8
+ * @typedef {Object} StrongResult
9
+ * @property {string} code the module after every fix the compiler allowed
10
+ * @property {boolean} strong whether it kept `"use strong"`
11
+ * @property {string[]} fixed the diagnostic codes a fix resolved
12
+ * @property {Finding[]} blockers the Strong errors left, when it did not
13
+ */
14
+
15
+ /**
16
+ * The source without the directive the codemod added: its own line after any
17
+ * leading comments and `"use client"`, or, at the very top, that line and the
18
+ * blank line after it. `line` is where it stood and `lines` how many went.
19
+ *
20
+ * @param {string} code
21
+ */
22
+ function withoutDirective(code) {
23
+ const top = '"use strong";\n\n';
24
+ if (code.startsWith(top)) return { code: code.slice(top.length), line: 1, lines: 2 };
25
+ const match = /^"use strong";\n/m.exec(code);
26
+ if (!match) return { code, line: 0, lines: 0 };
27
+ return {
28
+ code: code.slice(0, match.index) + code.slice(match.index + match[0].length),
29
+ line: code.slice(0, match.index).split('\n').length,
30
+ lines: 1,
31
+ };
32
+ }
33
+ const MAX_ROUNDS = 6;
34
+
35
+ /**
36
+ * Compile a module the codemod emitted in Strong mode and repair what the
37
+ * compiler reports, until it compiles clean or nothing more can be fixed.
38
+ *
39
+ * The repairs are the compiler's own suggested edits, as `octane analyze --fix`
40
+ * applies them, plus the rewrites that keep React's behavior exactly:
41
+ *
42
+ * - an explicit dependency list the compiler reports as equivalent to the one
43
+ * it infers is dropped;
44
+ * - state initialized from a prop is captured lazily, `useState(() => prop)`,
45
+ * which is what `useState(prop)` meant in React.
46
+ *
47
+ * Strong errors that remain mean the module needs a person. With `force`
48
+ * unset the module falls back to compatibility mode so the migrated app still
49
+ * builds, and the errors are reported as the work left to make it Strong.
50
+ *
51
+ * @param {Compiler} compiler
52
+ * @param {string} code
53
+ * @param {string} filename
54
+ * @param {{ force?: boolean }} [options]
55
+ * @returns {StrongResult}
56
+ */
57
+ export function strengthen(compiler, code, filename, { force = false } = {}) {
58
+ /** @type {string[]} */
59
+ const fixed = [];
60
+ let diagnostics = [];
61
+ for (let round = 0; round < MAX_ROUNDS; round++) {
62
+ const result = compiler.collectDiagnostics(code, filename, { strong: true });
63
+ if (result.error != null) {
64
+ // A module that compatibility mode cannot compile either has no
65
+ // Strong blocker to report; the compile failure is its own error.
66
+ const compat = compiler.collectDiagnostics(withoutDirective(code).code, filename, {});
67
+ return fallback(code, compat.error == null ? [thrown(result.error)] : [], fixed, force);
68
+ }
69
+ diagnostics = result.diagnostics;
70
+ const fixes = diagnostics.flatMap((diagnostic) => fixesFor(code, diagnostic));
71
+ if (fixes.length === 0) break;
72
+ const { text, applied } = applyFixes(code, fixes);
73
+ if (applied.length === 0) break;
74
+ code = pruneImports(text);
75
+ for (const fix of applied) fixed.push(fix.code);
76
+ }
77
+ const blockers = diagnostics.filter((diagnostic) => diagnostic.severity === 'error').map(finding);
78
+ if (blockers.length === 0) return { code, strong: true, fixed, blockers };
79
+ return fallback(code, blockers, fixed, force);
80
+ }
81
+
82
+ /**
83
+ * @param {string} code
84
+ * @param {Finding[]} blockers
85
+ * @param {string[]} fixed
86
+ * @param {boolean} force
87
+ * @returns {StrongResult}
88
+ */
89
+ function fallback(code, blockers, fixed, force) {
90
+ if (force) return { code, strong: true, fixed, blockers };
91
+ // The module builds in compatibility mode; what kept it there is work
92
+ // left, not a failure. Its lines are the written file's, without the
93
+ // directive.
94
+ const compat = withoutDirective(code);
95
+ const kept = blockers.map((blocker) => ({
96
+ ...blocker,
97
+ severity: 'warning',
98
+ line: blocker.line > compat.line ? blocker.line - compat.lines : blocker.line,
99
+ }));
100
+ return { code: compat.code, strong: false, fixed, blockers: kept };
101
+ }
102
+
103
+ /**
104
+ * The edits that resolve one diagnostic, as `applyFixes` takes them.
105
+ *
106
+ * @param {string} code
107
+ * @param {any} diagnostic
108
+ * @returns {{ code: string, edits: { start: number, end: number, text: string }[] }[]}
109
+ */
110
+ function fixesFor(code, diagnostic) {
111
+ /** @type {{ code: string, edits: { start: number, end: number, text: string }[] }[]} */
112
+ const fixes = [];
113
+ for (const suggestion of diagnostic.suggestions ?? []) {
114
+ if (Array.isArray(suggestion?.edits) && suggestion.edits.length > 0) {
115
+ fixes.push({ code: diagnostic.code, edits: suggestion.edits });
116
+ break;
117
+ }
118
+ }
119
+ if (fixes.length > 0) return fixes;
120
+ const start = diagnostic.start?.offset;
121
+ const end = diagnostic.end?.offset;
122
+ if (typeof start !== 'number' || typeof end !== 'number') return fixes;
123
+
124
+ if (diagnostic.code === 'OCTANE_STRONG_EXPLICIT_DEPENDENCIES' && diagnostic.severity === 'hint') {
125
+ // `useEffect(fn, [a])` -> `useEffect(fn)`: the compiler infers `[a]`.
126
+ const comma = /,\s*$/.exec(code.slice(0, start));
127
+ if (comma && code[start] === '[') {
128
+ fixes.push({ code: diagnostic.code, edits: [{ start: comma.index, end, text: '' }] });
129
+ }
130
+ }
131
+ if (diagnostic.code === 'OCTANE_STRONG_UNLINKED_PROP_STATE') {
132
+ const before = /\S\s*$/.exec(code.slice(0, start))?.[0][0];
133
+ const value = code.slice(start, end);
134
+ if (before === '(') {
135
+ // useState(prop): React captured the value once, as a lazy
136
+ // initializer does.
137
+ const body = /^[\w$.]+$/.test(value) ? value : `(${value})`;
138
+ fixes.push({ code: diagnostic.code, edits: [{ start, end, text: `() => ${body}` }] });
139
+ } else if (before === ',') {
140
+ // useReducer(reducer, prop): an explicit initializer is the
141
+ // deliberate capture.
142
+ fixes.push({
143
+ code: diagnostic.code,
144
+ edits: [{ start: end, end, text: ', (initial) => initial' }],
145
+ });
146
+ }
147
+ }
148
+ return fixes;
149
+ }