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