@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.
Files changed (58) hide show
  1. package/README.md +295 -4
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +162 -0
  4. package/dist/compiler.d.ts +11 -0
  5. package/dist/compiler.js +48 -0
  6. package/dist/effect-receivers.d.ts +11 -0
  7. package/dist/effect-receivers.js +315 -0
  8. package/dist/expression-wrappers.d.ts +6 -0
  9. package/dist/expression-wrappers.js +16 -0
  10. package/dist/forwarded-props.d.ts +27 -0
  11. package/dist/forwarded-props.js +489 -0
  12. package/dist/index.d.ts +6 -0
  13. package/{src → dist}/index.js +1 -0
  14. package/dist/linked-state.d.ts +17 -0
  15. package/dist/linked-state.js +126 -0
  16. package/dist/local-calls.d.ts +20 -0
  17. package/dist/local-calls.js +143 -0
  18. package/dist/local-react-hook.d.ts +15 -0
  19. package/dist/local-react-hook.js +353 -0
  20. package/dist/local-uses.d.ts +13 -0
  21. package/dist/local-uses.js +987 -0
  22. package/dist/mappings.d.ts +57 -0
  23. package/dist/mappings.js +343 -0
  24. package/dist/path-svg.d.ts +60 -0
  25. package/dist/path-svg.js +207 -0
  26. package/dist/project.d.ts +9 -0
  27. package/dist/project.js +1568 -0
  28. package/dist/react-intl.d.ts +4 -0
  29. package/dist/react-intl.js +389 -0
  30. package/dist/react-renderer.d.ts +9 -0
  31. package/dist/react-renderer.js +106 -0
  32. package/dist/scoped-signal.d.ts +4 -0
  33. package/dist/scoped-signal.js +480 -0
  34. package/dist/scoped-store-contract.d.ts +13 -0
  35. package/dist/scoped-store-contract.js +741 -0
  36. package/dist/store-hook-uses.d.ts +18 -0
  37. package/dist/store-hook-uses.js +403 -0
  38. package/dist/store-inputs.d.ts +16 -0
  39. package/dist/store-inputs.js +391 -0
  40. package/dist/strong.d.ts +24 -0
  41. package/dist/strong.js +142 -0
  42. package/dist/transform.d.ts +27 -0
  43. package/dist/transform.js +4890 -0
  44. package/dist/types.d.ts +203 -0
  45. package/dist/types.js +1 -0
  46. package/package.json +18 -6
  47. package/src/path-svg.ts +218 -0
  48. package/templates/octane-path-svg.ts +56 -0
  49. package/templates/octane-store-context.tsrx +49 -0
  50. package/templates/octane-store-hooks.ts +61 -0
  51. package/templates/react-intl.tsrx +116 -0
  52. package/src/bin.js +0 -151
  53. package/src/compiler.js +0 -61
  54. package/src/index.d.ts +0 -95
  55. package/src/mappings.js +0 -429
  56. package/src/project.js +0 -738
  57. package/src/strong.js +0 -149
  58. package/src/transform.js +0 -3455
package/src/project.js DELETED
@@ -1,738 +0,0 @@
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 {{ name: string, range: string }[]} dependencies the bindings
44
- * added to package.json, which the project did not declare yet
45
- * @property {{ name: string, patch: string }[]} patched patches the project
46
- * applies to replaced React packages, which do not reach their bindings
47
- * @property {Missing[]} missing React packages the code imports that have no
48
- * Octane port, and how it uses them
49
- * @property {string[]} html entry pages whose script reference was updated
50
- * @property {string | null} compiler where the verifying compiler came from
51
- *
52
- * @typedef {import('./transform.js').Unported & { modules: number }} Missing
53
- * with how many modules import it
54
- */
55
-
56
- const SOURCE = /\.(?:[cm]?[jt]sx?)$/;
57
- /** React packages and the Octane package that replaces each. */
58
- const CATALOG = { ...DATA.reactPackages, ...PORTED_PACKAGES };
59
- /** A package that, by its name, renders through React. */
60
- const REACT_PACKAGE = /^(?:react-|@[^/]+\/react(?:-|\/|$)|[^/]+\/react$)|-react(?:\/|$)/;
61
-
62
- /**
63
- * Migrate every React module under `paths`.
64
- *
65
- * Two passes: the first decides which modules become `.tsrx`, the second
66
- * rewrites every module with that rename map in hand, so an import of a
67
- * renamed module is updated wherever it is.
68
- *
69
- * @param {string[]} paths
70
- * @param {CodemodOptions} [options]
71
- * @returns {Promise<CodemodResult>}
72
- */
73
- export async function runCodemod(paths, options = {}) {
74
- const target = options.target ?? 'tsrx';
75
- const strong = options.strong === true && target === 'tsrx';
76
- const root = path.resolve(options.root ?? findRoot(paths[0] ?? '.'));
77
- const files = paths.flatMap((entry) => collect(path.resolve(entry)));
78
-
79
- const known = new Set(files);
80
- const config = tsconfigOptions(root);
81
- const program = projectProgram(config, files);
82
- const checker = program?.getTypeChecker();
83
- /** @type {Map<string, string>} */
84
- const renames = new Map();
85
- /** @type {Map<string, import('./transform.js').ModuleExports>} */
86
- const exports = new Map();
87
- for (const file of files) {
88
- const result = transformModule(fs.readFileSync(file, 'utf8'), file, { target });
89
- exports.set(file, result.exports);
90
- if (result.template) renames.set(file, file.replace(/\.(?:jsx?|tsx)$/, '.tsrx'));
91
- }
92
- const contextsOf = contextIndex(exports, known);
93
-
94
- const verify = options.verify !== false;
95
- const compiler = verify || strong ? await loadCompiler(root) : null;
96
- /** @type {Map<string, string>} */
97
- const packages = new Map();
98
- /** @type {Map<string, Missing>} */
99
- const missing = new Map();
100
- // `ReactCompat` hosts a component from a package with no port in a React
101
- // root, from 19.2 within the React 19 series it supports.
102
- const reactCompat = ['react', 'react-dom'].every((name) =>
103
- /^19\.(?:[2-9]|\d{2,})\./.test(readInstalled(root, name)?.version ?? ''),
104
- );
105
- /** @type {FileResult[]} */
106
- const results = [];
107
- for (const file of files) {
108
- const source = fs.readFileSync(file, 'utf8');
109
- /** @type {Note[]} */
110
- const extra = [];
111
- const resolveSpecifier = (/** @type {string} */ specifier) =>
112
- resolveRelative(file, specifier, known, renames) ??
113
- resolveAlias(file, specifier, renames, config) ??
114
- resolveBinding(specifier, packages, extra);
115
- const isContext = (/** @type {string} */ specifier, /** @type {string} */ name) => {
116
- if (!specifier.startsWith('.')) return null;
117
- const target = resolveModule(file, specifier, known);
118
- return target ? contextsOf(target.file).has(name) : null;
119
- };
120
- const sourceFile = program?.getSourceFile(file);
121
- const result = transformModule(source, file, {
122
- target,
123
- strong,
124
- strictNullChecks: program !== null,
125
- types: sourceFile && checker && { sourceFile, checker },
126
- resolveSpecifier,
127
- isContext,
128
- unported: (specifier) => unportedName(specifier, file),
129
- reactCompat,
130
- });
131
- for (const port of result.unported) {
132
- const entry = missing.get(port.name) ?? {
133
- name: port.name,
134
- modules: 0,
135
- islands: 0,
136
- blocked: 0,
137
- };
138
- entry.modules++;
139
- entry.islands += port.islands;
140
- entry.blocked += port.blocked;
141
- missing.set(port.name, entry);
142
- }
143
- const output = renames.get(file) ?? file;
144
- let code = result.code;
145
- /** @type {boolean | null} */
146
- let isStrong = null;
147
- /** @type {string[]} */
148
- let strongFixes = [];
149
- /** @type {FileResult['diagnostics']} */
150
- let diagnostics = [];
151
- if (compiler && result.changed) {
152
- if (strong && result.template) {
153
- const strengthened = strengthen(compiler, code, output, { force: options.forceStrong });
154
- code = strengthened.code;
155
- isStrong = strengthened.strong;
156
- strongFixes = strengthened.fixed;
157
- if (!strengthened.strong) diagnostics.push(...strengthened.blockers);
158
- }
159
- if (verify && isCompiled(output, code))
160
- diagnostics.push(...compile(compiler, code, output, isStrong === true));
161
- }
162
- results.push({
163
- file: path.relative(root, file),
164
- output: path.relative(root, output),
165
- changed: result.changed || output !== file,
166
- rules: result.rules,
167
- notes: [...result.notes, ...extra],
168
- strong: isStrong,
169
- strongFixes,
170
- diagnostics: dedupe(diagnostics),
171
- code,
172
- });
173
- }
174
-
175
- // TSRX written for React (`@tsrx/react`) is a dialect the TypeScript
176
- // parser cannot read, so it is reported rather than skipped silently.
177
- for (const file of paths.flatMap((entry) => collect(path.resolve(entry), isTsrx))) {
178
- const source = fs.readFileSync(file, 'utf8');
179
- const react = /^import\b[^;]*?\bfrom\s+['"]react(?:-dom)?(?:\/[^'"]*)?['"]/m.exec(source);
180
- if (!react || /\bfrom\s+['"]octane(?:\/[^'"]*)?['"]/.test(source)) continue;
181
- results.push({
182
- file: path.relative(root, file),
183
- output: path.relative(root, file),
184
- changed: false,
185
- rules: {},
186
- notes: [
187
- {
188
- rule: 'tsrx-react',
189
- severity: 'error',
190
- line: source.slice(0, react.index).split('\n').length,
191
- message:
192
- '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.',
193
- },
194
- ],
195
- strong: null,
196
- strongFixes: [],
197
- diagnostics: [],
198
- code: source,
199
- });
200
- }
201
-
202
- // Configs and scripts name modules by path too, such as Vite's
203
- // `server.warmup.clientFiles`, including those outside the migrated paths.
204
- const byFile = new Map(results.map((result) => [path.join(root, result.file), result]));
205
- for (const file of collect(root, (name) => SOURCE.test(name))) {
206
- if (renames.has(file)) continue;
207
- const result = byFile.get(file);
208
- const paths = rewriteModulePaths(
209
- result?.code ?? fs.readFileSync(file, 'utf8'),
210
- file,
211
- root,
212
- renames,
213
- );
214
- if (!paths) continue;
215
- const rules = { ...result?.rules, 'module-paths': paths.count };
216
- if (result) Object.assign(result, { code: paths.code, changed: true, rules });
217
- else {
218
- const name = path.relative(root, file);
219
- results.push({
220
- file: name,
221
- output: name,
222
- changed: true,
223
- rules,
224
- notes: [],
225
- strong: null,
226
- strongFixes: [],
227
- diagnostics: [],
228
- code: paths.code,
229
- });
230
- }
231
- }
232
-
233
- const html = rewriteEntryPages(
234
- root,
235
- paths.map((entry) => path.resolve(entry)),
236
- renames,
237
- options.write !== false,
238
- );
239
- const dependencies = addBindings(root, packages, options.write !== false);
240
- if (options.write !== false) {
241
- for (const result of results) {
242
- if (!result.changed) continue;
243
- const output = path.join(root, result.output);
244
- fs.writeFileSync(output, result.code);
245
- if (result.output !== result.file) fs.rmSync(path.join(root, result.file));
246
- }
247
- }
248
- return {
249
- root,
250
- files: results,
251
- packages: [...packages].map(([from, to]) => ({ from, to })),
252
- dependencies,
253
- patched: patchedPackages(root, packages),
254
- missing: [...missing.values()].sort((a, b) => a.name.localeCompare(b.name)),
255
- html,
256
- compiler: compiler?.from ?? null,
257
- };
258
- }
259
-
260
- /**
261
- * Whether Octane compiles this module: `.tsrx`, JSX, or a module that imports
262
- * the runtime. A declaration file is only types.
263
- *
264
- * @param {string} file
265
- * @param {string} code
266
- */
267
- function isCompiled(file, code) {
268
- if (file.endsWith('.d.ts')) return false;
269
- return /\.(?:tsrx|[jt]sx)$/.test(file) || /from\s+['"]octane['"]/.test(code);
270
- }
271
-
272
- /**
273
- * @param {import('./compiler.js').Compiler} compiler
274
- * @param {string} code
275
- * @param {string} file
276
- * @param {boolean} strong
277
- */
278
- function compile(compiler, code, file, strong) {
279
- try {
280
- const result = compiler.collectDiagnostics(code, file, strong ? { strong: true } : {});
281
- const found = result.diagnostics.filter((d) => d.severity !== 'hint').map(finding);
282
- return result.error == null ? found : [...found, thrown(result.error)];
283
- } catch (error) {
284
- return [thrown(error)];
285
- }
286
- }
287
-
288
- /** @param {FileResult['diagnostics']} diagnostics */
289
- function dedupe(diagnostics) {
290
- const seen = new Set();
291
- return diagnostics.filter((d) => {
292
- const key = `${d.code}:${d.line}:${d.message}`;
293
- if (seen.has(key)) return false;
294
- seen.add(key);
295
- return true;
296
- });
297
- }
298
-
299
- /**
300
- * The modules under `entry` that pass `test`: by default, those the codemod
301
- * migrates.
302
- *
303
- * @param {string} entry
304
- * @param {(name: string) => boolean} [test]
305
- */
306
- function collect(entry, test = isSource) {
307
- if (fs.statSync(entry).isFile()) return test(entry) ? [entry] : [];
308
- return scanSourceFiles(entry, { limit: Infinity }).filter(test).sort();
309
- }
310
-
311
- /** @param {string} name */
312
- function isTsrx(name) {
313
- return name.endsWith('.tsrx');
314
- }
315
-
316
- /**
317
- * The compiler options of the tsconfig that governs `root`, or null.
318
- *
319
- * @param {string} root
320
- * @returns {ts.CompilerOptions | null}
321
- */
322
- function tsconfigOptions(root) {
323
- const file = ts.findConfigFile(root, ts.sys.fileExists);
324
- if (!file) return null;
325
- const { config } = ts.readConfigFile(file, ts.sys.readFile);
326
- return ts.parseJsonConfigFileContent(config ?? {}, ts.sys, path.dirname(file)).options;
327
- }
328
-
329
- /**
330
- * A program over the TypeScript modules being migrated, under the project's
331
- * tsconfig, so their types resolve through imports. Null unless that config
332
- * enables `strictNullChecks`: without it a `string` may still hold null, so
333
- * types cannot prove a hole is text.
334
- *
335
- * @param {ts.CompilerOptions | null} options
336
- * @param {string[]} files
337
- */
338
- function projectProgram(options, files) {
339
- if (!options || !(options.strictNullChecks ?? options.strict)) return null;
340
- return ts.createProgram(
341
- files.filter((name) => /\.[cm]?tsx?$/.test(name)),
342
- // As the compiler's typed-text proof requires.
343
- { ...options, noEmit: true, noUncheckedIndexedAccess: true },
344
- );
345
- }
346
-
347
- /**
348
- * Bundler and tool configs belong to `octane init`, not the codemod.
349
- *
350
- * @param {string} name
351
- */
352
- function isSource(name) {
353
- return SOURCE.test(name) && !/\.config\.[cm]?[jt]s$/.test(name);
354
- }
355
-
356
- /**
357
- * The project module a relative specifier names, trying the extensions and
358
- * directory indexes a bundler would.
359
- *
360
- * @param {string} from
361
- * @param {string} specifier
362
- * @param {Set<string>} files
363
- * @returns {{ file: string, index: boolean } | null}
364
- */
365
- function resolveModule(from, specifier, files) {
366
- if (!specifier.startsWith('.')) return null;
367
- const base = path.resolve(path.dirname(from), specifier);
368
- const stem = base.replace(/\.(?:[cm]?[jt]sx?)$/, '');
369
- for (const file of [base, ...['.tsx', '.ts', '.jsx', '.js'].map((ext) => stem + ext)]) {
370
- if (files.has(file)) return { file, index: false };
371
- }
372
- for (const ext of ['.tsx', '.ts', '.jsx', '.js']) {
373
- const file = path.join(base, 'index' + ext);
374
- if (files.has(file)) return { file, index: true };
375
- }
376
- return null;
377
- }
378
-
379
- /**
380
- * The new specifier for a relative import of a renamed module. `.tsrx` modules
381
- * are imported by their full name.
382
- *
383
- * @param {string} from
384
- * @param {string} specifier
385
- * @param {Set<string>} files
386
- * @param {Map<string, string>} renames
387
- */
388
- function resolveRelative(from, specifier, files, renames) {
389
- const target = resolveModule(from, specifier, files);
390
- if (!target || !renames.has(target.file)) return null;
391
- if (target.index) return specifier.replace(/\/?$/, '/index.tsrx');
392
- return specifier.replace(/\.(?:[cm]?[jt]sx?)$/, '') + '.tsrx';
393
- }
394
-
395
- /**
396
- * The new specifier for an import of a renamed module through a tsconfig
397
- * `paths` alias (`~/components/Card`), resolved as TypeScript resolves it.
398
- *
399
- * @param {string} from
400
- * @param {string} specifier
401
- * @param {Map<string, string>} renames
402
- * @param {ts.CompilerOptions | null} options
403
- */
404
- function resolveAlias(from, specifier, renames, options) {
405
- if (!options?.paths || specifier.startsWith('.')) return null;
406
- const file = ts.resolveModuleName(specifier, from, { ...options, preserveSymlinks: true }, ts.sys)
407
- .resolvedModule?.resolvedFileName;
408
- if (!file || !renames.has(file)) return null;
409
- if (SOURCE.test(specifier)) return specifier.replace(SOURCE, '.tsrx');
410
- return path.basename(file).startsWith('index.') && !/(?:^|\/)index$/.test(specifier)
411
- ? `${specifier}/index.tsrx`
412
- : `${specifier}.tsrx`;
413
- }
414
-
415
- /**
416
- * Which names each module exports as a context, following `export … from`.
417
- *
418
- * @param {Map<string, import('./transform.js').ModuleExports>} exports
419
- * @param {Set<string>} files
420
- * @returns {(file: string) => Set<string>}
421
- */
422
- function contextIndex(exports, files) {
423
- /** @type {Map<string, Set<string>>} */
424
- const resolved = new Map();
425
- const contextsOf = (/** @type {string} */ file) => {
426
- let names = resolved.get(file);
427
- if (names) return names;
428
- names = new Set(exports.get(file)?.contexts);
429
- // Set before following re-exports, so a cycle ends.
430
- resolved.set(file, names);
431
- for (const { specifier, names: pairs } of exports.get(file)?.reexports ?? []) {
432
- const target = resolveModule(file, specifier, files);
433
- if (!target) continue;
434
- const theirs = contextsOf(target.file);
435
- if (pairs === null) for (const name of theirs) names.add(name);
436
- else for (const [imported, exported] of pairs) if (theirs.has(imported)) names.add(exported);
437
- }
438
- return names;
439
- };
440
- return contextsOf;
441
- }
442
-
443
- /**
444
- * The binding that replaces a React package import, recorded so the report
445
- * can list the dependency changes.
446
- *
447
- * @param {string} specifier
448
- * @param {Map<string, string>} packages
449
- * @param {Note[]} notes
450
- */
451
- function resolveBinding(specifier, packages, notes) {
452
- const name = catalogName(specifier);
453
- if (name === null) return null;
454
- const binding = CATALOG[name];
455
- packages.set(name, binding);
456
- const entry = DATA.bindings.find((candidate) => candidate.name === binding);
457
- // An aggregate binding (`@octanejs/visx`, for `@visx/visx`) serves each
458
- // package of its scope from a subpath: `@visx/hierarchy` is
459
- // `@octanejs/visx/hierarchy`.
460
- const upstream = entry?.upstream?.package;
461
- const aggregate = upstream?.match(/^@([^/]+)\/\1$/);
462
- if (aggregate && name !== upstream && name.startsWith(`@${aggregate[1]}/`)) {
463
- return `${binding}/${name.slice(aggregate[1].length + 2)}${specifier.slice(name.length)}`;
464
- }
465
- const subpath = specifier.slice(name.length);
466
- if (subpath === '' || entry?.exports.some((key) => serves(key, `.${subpath}`))) {
467
- return binding + subpath;
468
- }
469
- // A binding outside the catalog has exports the codemod cannot see.
470
- notes.push(
471
- entry
472
- ? {
473
- rule: 'bindings',
474
- severity: 'error',
475
- line: 1,
476
- message: `\`${binding}\` has no \`.${subpath}\` export. Import these names from its root if it exports them there.`,
477
- }
478
- : {
479
- rule: 'bindings',
480
- severity: 'warning',
481
- line: 1,
482
- message: `Check that \`${binding}${subpath}\` exists; the binding may export it from its root.`,
483
- },
484
- );
485
- return binding + subpath;
486
- }
487
-
488
- /**
489
- * Whether a package `exports` key serves a subpath, directly or through a
490
- * `*` pattern such as `./locale/*`.
491
- *
492
- * @param {string} key
493
- * @param {string} subpath
494
- */
495
- function serves(key, subpath) {
496
- const [head, tail] = key.split('*');
497
- return tail === undefined ? key === subpath : subpath.startsWith(head) && subpath.endsWith(tail);
498
- }
499
-
500
- /**
501
- * The catalog entry for a package specifier, or null. The catalog keys some
502
- * bindings by subpath (`better-auth/react`), so the longest matching prefix
503
- * wins.
504
- *
505
- * @param {string} specifier
506
- */
507
- function catalogName(specifier) {
508
- if (specifier.startsWith('.') || specifier.startsWith('/')) return null;
509
- const parts = specifier.split('/');
510
- for (let length = parts.length; length > 0; length--) {
511
- const candidate = parts.slice(0, length).join('/');
512
- if (candidate in CATALOG) return candidate;
513
- }
514
- return null;
515
- }
516
-
517
- /**
518
- * The React package a specifier names when Octane has no binding for it, or
519
- * null.
520
- *
521
- * @param {string} specifier
522
- * @param {string} from the importing module
523
- */
524
- function unportedName(specifier, from) {
525
- if (specifier.startsWith('.') || specifier.startsWith('/') || catalogName(specifier) !== null)
526
- return null;
527
- const root = packageName(specifier);
528
- // Any package's `/react` entry renders with React (`@tanstack/markdown/react`).
529
- if (/\/react(?:\/|$)/.test(specifier.slice(root.length))) return specifier;
530
- return rendersWithReact(root, from) ? root : null;
531
- }
532
-
533
- /**
534
- * The package a bare specifier imports from: `@pierre/diffs` for
535
- * `@pierre/diffs/react`.
536
- *
537
- * @param {string} specifier
538
- */
539
- function packageName(specifier) {
540
- return specifier
541
- .split('/')
542
- .slice(0, specifier.startsWith('@') ? 2 : 1)
543
- .join('/');
544
- }
545
-
546
- /**
547
- * Add the bindings the migrated code imports to the project's package.json,
548
- * each at its catalog version and in the field that lists the React package it
549
- * replaces. TanStack publishes its Octane adapters outside the catalog, so
550
- * those take `latest`.
551
- *
552
- * @param {string} root
553
- * @param {Map<string, string>} packages
554
- * @param {boolean} write
555
- * @returns {CodemodResult['dependencies']}
556
- */
557
- function addBindings(root, packages, write) {
558
- const file = path.join(root, 'package.json');
559
- if (!fs.existsSync(file)) return [];
560
- const text = fs.readFileSync(file, 'utf8');
561
- const manifest = JSON.parse(text);
562
- const fields = ['dependencies', 'devDependencies', 'peerDependencies'];
563
- /** @type {CodemodResult['dependencies']} */
564
- const added = [];
565
- for (const [from, to] of packages) {
566
- if (fields.some((field) => manifest[field]?.[to] !== undefined)) continue;
567
- const version = DATA.bindings.find((binding) => binding.name === to)?.version;
568
- const range = version ? `^${version}` : 'latest';
569
- const field = manifest.devDependencies?.[packageName(from)]
570
- ? 'devDependencies'
571
- : 'dependencies';
572
- manifest[field] = Object.fromEntries(
573
- Object.entries({ ...manifest[field], [to]: range }).sort(([a], [b]) => a.localeCompare(b)),
574
- );
575
- added.push({ name: to, range });
576
- }
577
- if (write && added.length > 0) {
578
- const indent = /^[ \t]+/m.exec(text)?.[0] ?? ' ';
579
- fs.writeFileSync(file, JSON.stringify(manifest, null, indent) + '\n');
580
- }
581
- return added;
582
- }
583
-
584
- /**
585
- * The patches a project applies to the React packages the migration replaces,
586
- * which stop applying once the code imports the binding instead: pnpm's and
587
- * Bun's `patchedDependencies`, in package.json or pnpm-workspace.yaml, and
588
- * patch-package's `patches/name+version.patch`. They live where the project
589
- * installs, so each directory up from `root` is read until a lockfile.
590
- *
591
- * @param {string} root
592
- * @param {Map<string, string>} packages
593
- * @returns {CodemodResult['patched']}
594
- */
595
- function patchedPackages(root, packages) {
596
- const replaced = new Set([...packages.keys()].map(packageName));
597
- /** @type {CodemodResult['patched']} */
598
- const patched = [];
599
- for (let dir = root; ; dir = path.dirname(dir)) {
600
- const read = (/** @type {string} */ name) => {
601
- const file = path.join(dir, name);
602
- return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
603
- };
604
- const manifest = JSON.parse(read('package.json') ?? '{}');
605
- /** @type {[string, string][]} `name@version` and its patch */
606
- const declared = Object.entries({
607
- ...manifest.pnpm?.patchedDependencies,
608
- ...manifest.patchedDependencies,
609
- });
610
- const workspace =
611
- /^patchedDependencies:[ \t]*\r?\n((?:[ \t]+.*\r?\n?)*)/m.exec(
612
- read('pnpm-workspace.yaml') ?? '',
613
- )?.[1] ?? '';
614
- for (const [, , key, , patch] of workspace.matchAll(
615
- /^[ \t]+(["']?)(.+?)\1:[ \t]*(["']?)(.+?)\3[ \t]*$/gm,
616
- )) {
617
- declared.push([key, patch]);
618
- }
619
- const patches = path.join(dir, 'patches');
620
- for (const name of fs.existsSync(patches) ? fs.readdirSync(patches) : []) {
621
- const match = /^((?:@[^+]+\+)?[^+]+)\+[^+]+\.patch$/.exec(name);
622
- if (match) declared.push([match[1].replace('+', '/'), `patches/${name}`]);
623
- }
624
- for (const [key, patch] of declared) {
625
- const name = key.replace(/(?!^)@[^@]*$/, '');
626
- if (replaced.has(name))
627
- patched.push({ name, patch: path.relative(root, path.join(dir, patch)) });
628
- }
629
- const installed = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock', 'bun.lockb'];
630
- if (installed.some((name) => fs.existsSync(path.join(dir, name))) || path.dirname(dir) === dir)
631
- return patched;
632
- }
633
- }
634
-
635
- /**
636
- * Whether a package renders through React: it declares `react` as a peer or
637
- * dependency when installed, or its name says so when it is not. A package
638
- * with a `./react` entry (`@pierre/trees/react`) renders through React there,
639
- * which the caller matches by subpath; its other entries need no binding. An
640
- * optional peer alone does not say which entries use React.
641
- *
642
- * @param {string} name
643
- * @param {string} from
644
- */
645
- function rendersWithReact(name, from) {
646
- if (name === 'octane' || name.startsWith('@octanejs/') || name.startsWith('node:')) return false;
647
- const manifest = readInstalled(path.dirname(from), name)?.manifest;
648
- if (!manifest) return REACT_PACKAGE.test(name);
649
- if (manifest.exports?.['./react']) return false;
650
- return ['peerDependencies', 'dependencies'].some((field) => manifest[field]?.react !== undefined);
651
- }
652
-
653
- /**
654
- * Point `<script src>` in HTML entry pages at renamed modules.
655
- *
656
- * @param {string} root
657
- * @param {string[]} targets the paths being migrated
658
- * @param {Map<string, string>} renames
659
- * @param {boolean} write
660
- */
661
- function rewriteEntryPages(root, targets, renames, write) {
662
- /** @type {string[]} */
663
- const updated = [];
664
- for (const page of findHtml(root, targets)) {
665
- const html = fs.readFileSync(page, 'utf8');
666
- const next = html.replace(
667
- /(<script\b[^>]*\bsrc=)(["'])([^"']+)\2/g,
668
- (match, open, quote, src) => {
669
- // Vite serves `/` from the page's own directory, as it does `./`.
670
- const file = path.join(path.dirname(page), src);
671
- const renamed = renames.get(file);
672
- if (!renamed) return match;
673
- return open + quote + src.replace(/\.[jt]sx?$/, '.tsrx') + quote;
674
- },
675
- );
676
- if (next !== html) {
677
- updated.push(path.relative(root, page));
678
- if (write) fs.writeFileSync(page, next);
679
- }
680
- }
681
- return updated;
682
- }
683
-
684
- /**
685
- * Point the exact path strings in a module that keeps its name at the modules
686
- * renamed to `.tsrx`. A path resolves from the module or, as Vite resolves its
687
- * options, from the root; a glob or an extensionless path stays.
688
- *
689
- * @param {string} code
690
- * @param {string} file
691
- * @param {string} root
692
- * @param {Map<string, string>} renames
693
- * @returns {{ code: string, count: number } | null}
694
- */
695
- function rewriteModulePaths(code, file, root, renames) {
696
- const sf = ts.createSourceFile(file, code, ts.ScriptTarget.Latest);
697
- /** @type {ts.StringLiteralLike[]} */
698
- const paths = [];
699
- const visit = (/** @type {ts.Node} */ node) => {
700
- if (
701
- ts.isStringLiteralLike(node) &&
702
- SOURCE.test(node.text) &&
703
- [path.dirname(file), root].some((dir) => renames.has(path.join(dir, node.text)))
704
- ) {
705
- paths.push(node);
706
- }
707
- ts.forEachChild(node, visit);
708
- };
709
- visit(sf);
710
- if (paths.length === 0) return null;
711
- let next = code;
712
- for (const node of paths.reverse()) {
713
- // The extension ends the literal, just before its closing quote.
714
- const end = node.getEnd() - 1;
715
- const start = node.getStart(sf);
716
- next = next.slice(0, start) + next.slice(start, end).replace(SOURCE, '.tsrx') + next.slice(end);
717
- }
718
- return { code: next, count: paths.length };
719
- }
720
-
721
- /**
722
- * The HTML pages a Vite or CRA app keeps beside its sources: those in the
723
- * root, `public/`, `src/`, and each migrated directory.
724
- *
725
- * @param {string} root
726
- * @param {string[]} targets
727
- */
728
- function findHtml(root, targets) {
729
- const dirs = new Set([root, path.join(root, 'public'), path.join(root, 'src'), ...targets]);
730
- return [...dirs]
731
- .filter((dir) => fs.existsSync(dir) && fs.statSync(dir).isDirectory())
732
- .flatMap((dir) =>
733
- fs
734
- .readdirSync(dir)
735
- .filter((name) => name.endsWith('.html'))
736
- .map((name) => path.join(dir, name)),
737
- );
738
- }