@astryxdesign/cli 0.7.5-canary.bc40b80 → 0.7.5-canary.c26ae3f
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 +1 -1
- package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
- package/api/integration/pack-check.mjs +10 -4
- package/api/integration/pack-check.test.mjs +5 -1
- package/api/upgrade/_adapter.d.mts +2 -0
- package/api/upgrade/run/failure-receipt.test.mjs +212 -0
- package/api/upgrade/run/run.mjs +251 -10
- package/api/upgrade/upgrade.doc.mjs +4 -4
- package/api/upgrade/upgrade.mjs +19 -4
- package/api/upgrade/upgrade.type.d.mts +12 -1
- package/api/upgrade/upgrade.type.mjs +17 -4
- package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
- package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
- package/assets/codemods/integration-runner.mjs +8 -2
- package/assets/codemods/integration-runner.protection.test.mjs +53 -0
- package/assets/codemods/parse.mjs +94 -0
- package/assets/codemods/run-codemod.mjs +109 -5
- package/assets/codemods/runner.mjs +108 -10
- package/assets/codemods/transform-prop.mjs +99 -49
- package/assets/codemods/transform-prop.test.mjs +36 -1
- package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
- package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
- package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
- package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
- package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +123 -70
- package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
- package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
- package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +19 -77
- package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
- package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
- package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
- package/assets/templates/pages/library/page.tsx +1 -2
- package/authoring/codemod/type.ts +10 -0
- package/clients/cli/commands/upgrade.doc.mjs +27 -0
- package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
- package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
- package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
- package/clients/cli/commands/upgrade.mjs +9 -2
- package/foundation/response/base.d.ts +7 -0
- package/foundation/response/error-codes.doc.mjs +3 -2
- package/foundation/response/error-codes.mjs +1 -1
- package/foundation/response/json.d.mts +10 -3
- package/foundation/response/json.mjs +16 -4
- package/package.json +10 -9
|
@@ -35,8 +35,10 @@ import {
|
|
|
35
35
|
fixDirectiveCorruption,
|
|
36
36
|
validateOutput,
|
|
37
37
|
isIgnoredDirectory,
|
|
38
|
+
isIgnoredLinkedDirectory,
|
|
38
39
|
} from './runner.mjs';
|
|
39
40
|
import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
|
|
41
|
+
import {isCodemodParseError, markingSourceParseErrors} from './parse.mjs';
|
|
40
42
|
|
|
41
43
|
export const DEFAULT_CODE_EXTENSIONS = [
|
|
42
44
|
'.tsx',
|
|
@@ -71,6 +73,69 @@ function protectedResult(filePath, name, protection) {
|
|
|
71
73
|
}));
|
|
72
74
|
}
|
|
73
75
|
|
|
76
|
+
/**
|
|
77
|
+
* @typedef {{file: string, codemod: string, location?: string, reason: string}} DeclinedCandidate
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Where a parse error points, as 1-based `line:column`, and its message
|
|
82
|
+
* without the position Babel appends. Babel reports a 0-based column on
|
|
83
|
+
* `loc`; PostCSS reports 1-based `line` and `column`.
|
|
84
|
+
* @param {any} err
|
|
85
|
+
* @returns {{message: string, location?: string}}
|
|
86
|
+
*/
|
|
87
|
+
function describeParseError(err) {
|
|
88
|
+
if (err?.name === 'CssSyntaxError') {
|
|
89
|
+
return {
|
|
90
|
+
message: String(err.reason ?? err.message),
|
|
91
|
+
...(typeof err.line === 'number'
|
|
92
|
+
? {location: `${err.line}:${err.column ?? 1}`}
|
|
93
|
+
: {}),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const loc = err?.loc;
|
|
97
|
+
return {
|
|
98
|
+
message: String(err?.message ?? err).replace(/\s*\(\d+:\d+\)$/, ''),
|
|
99
|
+
...(loc && typeof loc.line === 'number'
|
|
100
|
+
? {location: `${loc.line}:${(loc.column ?? 0) + 1}`}
|
|
101
|
+
: {}),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Decline a protected file a codemod could not parse. A codemod can prove
|
|
107
|
+
* nothing in bytes it cannot parse, and the file is never written anyway, so
|
|
108
|
+
* it is listed for manual review instead of failing the run. Only an error a
|
|
109
|
+
* parse entry point marked (see `parse.mjs`) counts: owned source that does
|
|
110
|
+
* not parse, and every other error a codemod throws, still fail.
|
|
111
|
+
* @param {unknown} err
|
|
112
|
+
* @param {string} filePath
|
|
113
|
+
* @param {string} relativePath
|
|
114
|
+
* @param {string} name
|
|
115
|
+
* @param {{root: string, classify: (file: string) => import('../../foundation/fs/file-protection.mjs').FileProtection[]}} protection
|
|
116
|
+
* @returns {DeclinedCandidate|null}
|
|
117
|
+
*/
|
|
118
|
+
function declineUnparseableProtected(
|
|
119
|
+
err,
|
|
120
|
+
filePath,
|
|
121
|
+
relativePath,
|
|
122
|
+
name,
|
|
123
|
+
protection,
|
|
124
|
+
) {
|
|
125
|
+
if (!isCodemodParseError(err)) return null;
|
|
126
|
+
const protections = protection.classify(filePath);
|
|
127
|
+
if (protections.length === 0) return null;
|
|
128
|
+
const {message, location} = describeParseError(err);
|
|
129
|
+
return {
|
|
130
|
+
file: relativePath,
|
|
131
|
+
codemod: name,
|
|
132
|
+
...(location ? {location} : {}),
|
|
133
|
+
// The category, not the declaration: a declaration names its source
|
|
134
|
+
// file from the project root, and `file` may be rebased elsewhere.
|
|
135
|
+
reason: `unparseable protected file (${[...new Set(protections.map(item => item.reason))].join(', ')}): ${message}`,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
74
139
|
/**
|
|
75
140
|
* Print one blocked candidate without implying that the protected bytes changed.
|
|
76
141
|
* @param {import('../../authoring/codemod/type').CliLog} log
|
|
@@ -86,9 +151,10 @@ function logProtected(log, protections) {
|
|
|
86
151
|
/**
|
|
87
152
|
* Recursively find candidate source files in a directory.
|
|
88
153
|
* @param {string} dir
|
|
154
|
+
* @param {string} [root] the operation's project root (default: `dir`)
|
|
89
155
|
* @returns {string[]}
|
|
90
156
|
*/
|
|
91
|
-
export function findSourceFiles(dir) {
|
|
157
|
+
export function findSourceFiles(dir, root = dir) {
|
|
92
158
|
/** @type {string[]} */
|
|
93
159
|
const results = [];
|
|
94
160
|
/** @param {string} currentDir @param {Set<string>} [ancestors] */
|
|
@@ -111,12 +177,24 @@ export function findSourceFiles(dir) {
|
|
|
111
177
|
for (const entry of entries) {
|
|
112
178
|
const fullPath = path.join(currentDir, entry.name);
|
|
113
179
|
// Symlinked files and descendants remain read-only candidates so a
|
|
114
|
-
// required change can be reported. Real-path ancestors prevent cycles
|
|
180
|
+
// required change can be reported. Real-path ancestors prevent cycles,
|
|
181
|
+
// and a link into a dependency or VCS tree is not descended.
|
|
115
182
|
if (entry.isSymbolicLink()) {
|
|
116
183
|
try {
|
|
117
184
|
const target = fs.statSync(fullPath);
|
|
118
185
|
if (target.isFile()) results.push(fullPath);
|
|
119
|
-
else if (
|
|
186
|
+
else if (
|
|
187
|
+
target.isDirectory() &&
|
|
188
|
+
!isIgnoredLinkedDirectory(
|
|
189
|
+
dir,
|
|
190
|
+
fullPath,
|
|
191
|
+
entry.name,
|
|
192
|
+
fs.realpathSync(fullPath),
|
|
193
|
+
root,
|
|
194
|
+
)
|
|
195
|
+
) {
|
|
196
|
+
walk(fullPath, nextAncestors);
|
|
197
|
+
}
|
|
120
198
|
} catch {
|
|
121
199
|
// Broken links have no source bytes to evaluate.
|
|
122
200
|
}
|
|
@@ -285,6 +363,8 @@ export function runCodeCodemod(
|
|
|
285
363
|
const protectedFiles = [];
|
|
286
364
|
/** @type {Array<{file: string, codemod: string, error: string}>} */
|
|
287
365
|
const errors = [];
|
|
366
|
+
/** @type {DeclinedCandidate[]} */
|
|
367
|
+
const declinedCandidates = [];
|
|
288
368
|
/** @type {Array<{filePath: string, relativePath: string, result: string}>} */
|
|
289
369
|
const candidates = [];
|
|
290
370
|
|
|
@@ -300,7 +380,11 @@ export function runCodeCodemod(
|
|
|
300
380
|
contents?.get(filePath) ?? fs.readFileSync(filePath, 'utf-8');
|
|
301
381
|
const parser = ext === '.tsx' || ext === '.ts' ? 'tsx' : 'babel';
|
|
302
382
|
const j = jscodeshift.withParser(parser);
|
|
303
|
-
const api = {
|
|
383
|
+
const api = {
|
|
384
|
+
jscodeshift: markingSourceParseErrors(j, source),
|
|
385
|
+
stats: () => {},
|
|
386
|
+
report: () => {},
|
|
387
|
+
};
|
|
304
388
|
let result = codemod.transform({source, path: filePath}, api);
|
|
305
389
|
|
|
306
390
|
if (result == null || result === source) continue;
|
|
@@ -320,6 +404,19 @@ export function runCodeCodemod(
|
|
|
320
404
|
}
|
|
321
405
|
candidates.push({filePath, relativePath, result});
|
|
322
406
|
} catch (err) {
|
|
407
|
+
const declined = declineUnparseableProtected(
|
|
408
|
+
err,
|
|
409
|
+
filePath,
|
|
410
|
+
relativePath,
|
|
411
|
+
name,
|
|
412
|
+
resolver,
|
|
413
|
+
);
|
|
414
|
+
if (declined) {
|
|
415
|
+
// Printed by the caller once every codemod has run: a later codemod
|
|
416
|
+
// can still make this file a protected one, listed only as such.
|
|
417
|
+
declinedCandidates.push(declined);
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
323
420
|
const message = /** @type {any} */ (err).message;
|
|
324
421
|
log.error(` ✗ ${relativePath} — ${message}`);
|
|
325
422
|
errors.push({file: relativePath, codemod: name, error: message});
|
|
@@ -372,5 +469,12 @@ export function runCodeCodemod(
|
|
|
372
469
|
}
|
|
373
470
|
}
|
|
374
471
|
|
|
375
|
-
return {
|
|
472
|
+
return {
|
|
473
|
+
filesChanged,
|
|
474
|
+
changedFiles,
|
|
475
|
+
writtenFiles,
|
|
476
|
+
protectedFiles,
|
|
477
|
+
declinedCandidates,
|
|
478
|
+
errors,
|
|
479
|
+
};
|
|
376
480
|
}
|
|
@@ -61,22 +61,85 @@ const IGNORED_DIRS = new Set([
|
|
|
61
61
|
]);
|
|
62
62
|
export {IGNORED_DIRS};
|
|
63
63
|
|
|
64
|
+
/** Yarn's install and cache folders, a hard boundary under `.yarn`. */
|
|
65
|
+
const YARN_STORE_DIRS = new Set(['__virtual__', 'cache', 'sdks', 'unplugged']);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The number of path segments a hard boundary starting at `parts[index]`
|
|
69
|
+
* spans: 1 for a name in {@link IGNORED_DIRS}, 2 for `.yarn` followed by one
|
|
70
|
+
* of its store folders, 0 when none starts there.
|
|
71
|
+
* @param {string[]} parts
|
|
72
|
+
* @param {number} index
|
|
73
|
+
*/
|
|
74
|
+
function boundaryLength(parts, index) {
|
|
75
|
+
if (IGNORED_DIRS.has(parts[index])) return 1;
|
|
76
|
+
if (parts[index] === '.yarn' && YARN_STORE_DIRS.has(parts[index + 1])) {
|
|
77
|
+
return 2;
|
|
78
|
+
}
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
64
82
|
/** @param {string} root @param {string} fullPath @param {string} name */
|
|
65
83
|
export function isIgnoredDirectory(root, fullPath, name) {
|
|
66
84
|
if (IGNORED_DIRS.has(name)) return true;
|
|
67
85
|
const parts = path.relative(root, fullPath).split(path.sep);
|
|
68
|
-
return (
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
86
|
+
return boundaryLength(parts, 0) === 2;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Whether a symbolic link to a directory leads into a tree the scan never
|
|
91
|
+
* descends. The link is checked like a directory by {@link isIgnoredDirectory},
|
|
92
|
+
* and its resolved target's absolute path is searched for the same hard
|
|
93
|
+
* boundaries, wherever the target lives: a symlinked `node_modules`, or a link
|
|
94
|
+
* into a dependency, package-store or version-control tree such as another
|
|
95
|
+
* project's `.yarn/cache`, is not walked. Only a target that stays inside the
|
|
96
|
+
* operation root may sit below a boundary that also contains that root, so a
|
|
97
|
+
* project that itself lives below a `node_modules` folder is still scanned; a
|
|
98
|
+
* link from it to a sibling package under that same folder is not.
|
|
99
|
+
* @param {string} root scan root
|
|
100
|
+
* @param {string} fullPath the link's path
|
|
101
|
+
* @param {string} name the link's name
|
|
102
|
+
* @param {string} realTarget the link's resolved real path
|
|
103
|
+
* @param {string} [operationRoot] the project root of the operation (default: the scan root)
|
|
104
|
+
* @returns {boolean}
|
|
105
|
+
*/
|
|
106
|
+
export function isIgnoredLinkedDirectory(
|
|
107
|
+
root,
|
|
108
|
+
fullPath,
|
|
109
|
+
name,
|
|
110
|
+
realTarget,
|
|
111
|
+
operationRoot = root,
|
|
112
|
+
) {
|
|
113
|
+
if (isIgnoredDirectory(root, fullPath, name)) return true;
|
|
114
|
+
let realRoot = operationRoot;
|
|
115
|
+
try {
|
|
116
|
+
realRoot = fs.realpathSync(operationRoot);
|
|
117
|
+
} catch {
|
|
118
|
+
// An unreadable root has no descendants to compare against.
|
|
119
|
+
}
|
|
120
|
+
const relative = path.relative(realRoot, realTarget);
|
|
121
|
+
const inside =
|
|
122
|
+
relative === '' ||
|
|
123
|
+
(relative !== '..' &&
|
|
124
|
+
!relative.startsWith(`..${path.sep}`) &&
|
|
125
|
+
!path.isAbsolute(relative));
|
|
126
|
+
// Inside the root, only a boundary that ends below the root counts.
|
|
127
|
+
const floor = inside ? realRoot.split(path.sep).length : 0;
|
|
128
|
+
const targetParts = realTarget.split(path.sep);
|
|
129
|
+
for (let index = 0; index < targetParts.length; index++) {
|
|
130
|
+
const length = boundaryLength(targetParts, index);
|
|
131
|
+
if (length > 0 && index + length > floor) return true;
|
|
132
|
+
}
|
|
133
|
+
return false;
|
|
72
134
|
}
|
|
73
135
|
|
|
74
136
|
/**
|
|
75
137
|
* Recursively find all source files in a directory.
|
|
76
138
|
* @param {string} dir
|
|
139
|
+
* @param {string} [root] the operation's project root (default: `dir`)
|
|
77
140
|
* @returns {string[]}
|
|
78
141
|
*/
|
|
79
|
-
function findSourceFiles(dir) {
|
|
142
|
+
function findSourceFiles(dir, root = dir) {
|
|
80
143
|
/** @type {string[]} */
|
|
81
144
|
const results = [];
|
|
82
145
|
const extensions = new Set([
|
|
@@ -112,13 +175,23 @@ function findSourceFiles(dir) {
|
|
|
112
175
|
for (const entry of entries) {
|
|
113
176
|
const fullPath = path.join(currentDir, entry.name);
|
|
114
177
|
// Symlinked files and descendants remain read-only candidates so a
|
|
115
|
-
// required change can be reported. Real-path ancestors prevent cycles
|
|
178
|
+
// required change can be reported. Real-path ancestors prevent cycles,
|
|
179
|
+
// and a link into a dependency or VCS tree is not descended.
|
|
116
180
|
if (entry.isSymbolicLink()) {
|
|
117
181
|
try {
|
|
118
182
|
const target = fs.statSync(fullPath);
|
|
119
183
|
if (target.isFile() && extensions.has(path.extname(entry.name))) {
|
|
120
184
|
results.push(fullPath);
|
|
121
|
-
} else if (
|
|
185
|
+
} else if (
|
|
186
|
+
target.isDirectory() &&
|
|
187
|
+
!isIgnoredLinkedDirectory(
|
|
188
|
+
dir,
|
|
189
|
+
fullPath,
|
|
190
|
+
entry.name,
|
|
191
|
+
fs.realpathSync(fullPath),
|
|
192
|
+
root,
|
|
193
|
+
)
|
|
194
|
+
) {
|
|
122
195
|
walk(fullPath, nextAncestors);
|
|
123
196
|
}
|
|
124
197
|
} catch {
|
|
@@ -142,6 +215,22 @@ function findSourceFiles(dir) {
|
|
|
142
215
|
return results.sort();
|
|
143
216
|
}
|
|
144
217
|
|
|
218
|
+
/**
|
|
219
|
+
* The declined candidates that are not also protected files the run reports.
|
|
220
|
+
* A file another codemod still requires a change to is listed once, under
|
|
221
|
+
* `protectedFiles`, which already makes the run incomplete.
|
|
222
|
+
* @template {{file: string}} T
|
|
223
|
+
* @param {T[]} declined
|
|
224
|
+
* @param {Array<{file: string}>} protectedRows
|
|
225
|
+
* @returns {T[]}
|
|
226
|
+
*/
|
|
227
|
+
export function withoutProtected(declined, protectedRows) {
|
|
228
|
+
/** @param {string} file */
|
|
229
|
+
const key = file => file.split(path.sep).join('/');
|
|
230
|
+
const blocked = new Set(protectedRows.map(item => key(item.file)));
|
|
231
|
+
return declined.filter(item => !blocked.has(key(item.file)));
|
|
232
|
+
}
|
|
233
|
+
|
|
145
234
|
/**
|
|
146
235
|
* Validate transform output before writing to disk.
|
|
147
236
|
*
|
|
@@ -419,7 +508,7 @@ async function runProjectCodemod(
|
|
|
419
508
|
* @param {string} [options.root] - Project root a project codemod reads (default: the process cwd)
|
|
420
509
|
* @param {{root: string, classify: (file: string) => import('../../foundation/fs/file-protection.mjs').FileProtection[]}} [options.protection] - Preloaded protection resolver
|
|
421
510
|
* @param {boolean} [options.coversTarget] - False when these codemods stop before the installed target (the CLI is older than Core), so a run with no changes does not say the code is up to date. Default true.
|
|
422
|
-
* @returns {Promise<{totalFilesChanged: number, totalTransformsApplied: number, totalValidationBlocked: number, changedFiles: string[], writtenFiles: string[], stagedContents: Map<string, string>, protectedFiles: import('../../authoring/codemod/type').CodemodRunResult['protectedFiles'], errors: Array<{file: string, codemod: string, error: string}>, skippedOptional: Array<{name: string, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, version: string}>} | {ok: false, reason: string, resolvedPath: string}>}
|
|
511
|
+
* @returns {Promise<{totalFilesChanged: number, totalTransformsApplied: number, totalValidationBlocked: number, changedFiles: string[], writtenFiles: string[], stagedContents: Map<string, string>, protectedFiles: import('../../authoring/codemod/type').CodemodRunResult['protectedFiles'], declinedCandidates: NonNullable<import('../../authoring/codemod/type').CodemodRunResult['declinedCandidates']>, errors: Array<{file: string, codemod: string, error: string}>, skippedOptional: Array<{name: string, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, version: string}>} | {ok: false, reason: string, resolvedPath: string}>}
|
|
423
512
|
*/
|
|
424
513
|
export async function runCodemods(
|
|
425
514
|
versionManifests,
|
|
@@ -472,7 +561,7 @@ export async function runCodemods(
|
|
|
472
561
|
let files = [];
|
|
473
562
|
if (sourcePathExists) {
|
|
474
563
|
log.step(`Scanning ${resolvedPath} for source files...`);
|
|
475
|
-
files = findSourceFiles(resolvedPath);
|
|
564
|
+
files = findSourceFiles(resolvedPath, path.resolve(root));
|
|
476
565
|
if (files.length === 0) {
|
|
477
566
|
log.warn('No source files found.');
|
|
478
567
|
} else {
|
|
@@ -500,6 +589,8 @@ export async function runCodemods(
|
|
|
500
589
|
const writtenFiles = [];
|
|
501
590
|
/** @type {import('../../authoring/codemod/type').CodemodRunResult['protectedFiles']} */
|
|
502
591
|
const protectedFiles = [];
|
|
592
|
+
/** @type {NonNullable<import('../../authoring/codemod/type').CodemodRunResult['declinedCandidates']>} */
|
|
593
|
+
const declinedCandidates = [];
|
|
503
594
|
/** @type {Array<{name: string, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, version: string}>} */
|
|
504
595
|
const skippedOptional = [];
|
|
505
596
|
for (const {version, transforms} of versionManifests) {
|
|
@@ -589,6 +680,7 @@ export async function runCodemods(
|
|
|
589
680
|
);
|
|
590
681
|
errors.push(...result.errors);
|
|
591
682
|
protectedFiles.push(...result.protectedFiles);
|
|
683
|
+
declinedCandidates.push(...(result.declinedCandidates ?? []));
|
|
592
684
|
changedFiles.push(...result.changedFiles);
|
|
593
685
|
writtenFiles.push(...result.writtenFiles);
|
|
594
686
|
totalTransformsApplied += result.filesChanged;
|
|
@@ -640,10 +732,15 @@ export async function runCodemods(
|
|
|
640
732
|
);
|
|
641
733
|
}
|
|
642
734
|
|
|
735
|
+
// A later codemod can block a file an earlier one declined. The caller
|
|
736
|
+
// prints declined files once it has reconciled every runner's results.
|
|
737
|
+
const reportedDeclined = withoutProtected(declinedCandidates, protectedFiles);
|
|
738
|
+
|
|
643
739
|
if (
|
|
644
740
|
totalFilesChanged === 0 &&
|
|
645
741
|
errors.length === 0 &&
|
|
646
|
-
protectedFiles.length === 0
|
|
742
|
+
protectedFiles.length === 0 &&
|
|
743
|
+
reportedDeclined.length === 0
|
|
647
744
|
) {
|
|
648
745
|
// Codemods that stop before the installed target cannot vouch for the
|
|
649
746
|
// code; the caller says what is missing.
|
|
@@ -693,6 +790,7 @@ export async function runCodemods(
|
|
|
693
790
|
changedFiles,
|
|
694
791
|
writtenFiles,
|
|
695
792
|
protectedFiles,
|
|
793
|
+
declinedCandidates: reportedDeclined,
|
|
696
794
|
stagedContents: virtualContents,
|
|
697
795
|
errors,
|
|
698
796
|
skippedOptional,
|
|
@@ -1,27 +1,47 @@
|
|
|
1
1
|
// Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* Find imported components, resolve their local
|
|
5
|
-
* and yield matching JSX prop paths to a
|
|
4
|
+
* Find imported components, resolve their local names (including aliases and
|
|
5
|
+
* namespace members) at a use site, and yield matching JSX prop paths to a
|
|
6
|
+
* visitor.
|
|
6
7
|
*
|
|
7
|
-
*
|
|
8
|
-
* variables, helper calls, object spreads, wrapper components, or types.
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
* `transformProp` intentionally stops at the JSX boundary. It does not follow
|
|
9
|
+
* variables, helper calls, object spreads, wrapper components, or types. The
|
|
10
|
+
* resolver it is built on (`importedComponents`, `resolveImportedComponent`,
|
|
11
|
+
* `isModuleBinding`) is exported for transforms that prove other use sites.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {{
|
|
13
16
|
* matchesImport: (source: string) => boolean,
|
|
14
17
|
* components: ReadonlyMap<string, ReadonlySet<string>>,
|
|
15
18
|
* normalizeComponentName?: (name: string) => string,
|
|
16
|
-
* }}
|
|
17
|
-
* @param {(propPath: any, context: {component: string, localName: string}) => void} visit
|
|
19
|
+
* }} ImportOptions
|
|
18
20
|
*/
|
|
19
|
-
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {{
|
|
24
|
+
* direct: Map<string, {component: string, props: ReadonlySet<string>}>,
|
|
25
|
+
* namespaces: Set<string>,
|
|
26
|
+
* normalize: (name: string) => string,
|
|
27
|
+
* components: ReadonlyMap<string, ReadonlySet<string>>,
|
|
28
|
+
* }} ImportedComponents
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Local names bound by accepted runtime imports: named, aliased and default
|
|
33
|
+
* component imports, and namespace imports.
|
|
34
|
+
* @param {any} root jscodeshift collection for one source file
|
|
35
|
+
* @param {any} j configured jscodeshift instance
|
|
36
|
+
* @param {ImportOptions} options
|
|
37
|
+
* @returns {ImportedComponents}
|
|
38
|
+
*/
|
|
39
|
+
export function importedComponents(root, j, options) {
|
|
20
40
|
const normalize = options.normalizeComponentName ?? (name => name);
|
|
21
|
-
/** @type {
|
|
22
|
-
const
|
|
41
|
+
/** @type {ImportedComponents['direct']} */
|
|
42
|
+
const direct = new Map();
|
|
23
43
|
/** @type {Set<string>} */
|
|
24
|
-
const
|
|
44
|
+
const namespaces = new Set();
|
|
25
45
|
|
|
26
46
|
root.find(j.ImportDeclaration).forEach((/** @type {any} */ importPath) => {
|
|
27
47
|
const source = importPath.node.source.value;
|
|
@@ -46,53 +66,83 @@ export function transformProp(root, j, options, visit) {
|
|
|
46
66
|
const component = normalize(importedName);
|
|
47
67
|
const props = options.components.get(component);
|
|
48
68
|
if (!props) continue;
|
|
49
|
-
|
|
50
|
-
component,
|
|
51
|
-
props,
|
|
52
|
-
});
|
|
69
|
+
direct.set(specifier.local?.name ?? importedName, {component, props});
|
|
53
70
|
} else if (specifier.type === 'ImportDefaultSpecifier' && subpathProps) {
|
|
54
|
-
|
|
71
|
+
direct.set(specifier.local.name, {
|
|
55
72
|
component: subpathName,
|
|
56
73
|
props: subpathProps,
|
|
57
74
|
});
|
|
58
75
|
} else if (specifier.type === 'ImportNamespaceSpecifier') {
|
|
59
|
-
|
|
76
|
+
namespaces.add(specifier.local.name);
|
|
60
77
|
}
|
|
61
78
|
}
|
|
62
79
|
});
|
|
63
80
|
|
|
64
|
-
|
|
81
|
+
return {direct, namespaces, normalize, components: options.components};
|
|
82
|
+
}
|
|
65
83
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
84
|
+
/**
|
|
85
|
+
* True when `localName` at `path` resolves to a module-scope binding. A
|
|
86
|
+
* parameter or local declaration with the same name shadows the import.
|
|
87
|
+
* @param {any} path any node path inside the file
|
|
88
|
+
* @param {string} localName
|
|
89
|
+
*/
|
|
90
|
+
export function isModuleBinding(path, localName) {
|
|
91
|
+
return path.scope?.lookup(localName)?.path.node.type === 'Program';
|
|
92
|
+
}
|
|
71
93
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
94
|
+
/**
|
|
95
|
+
* Resolve a component reference (`Card`, `Lib.Card`, or their JSX forms) to
|
|
96
|
+
* the imported component it names at `scopePath`, or null.
|
|
97
|
+
* @param {any} nameNode Identifier, JSXIdentifier, MemberExpression, or JSXMemberExpression
|
|
98
|
+
* @param {any} scopePath the path whose scope the reference is evaluated in
|
|
99
|
+
* @param {ImportedComponents} imports
|
|
100
|
+
* @returns {{component: string, props: ReadonlySet<string>, localName: string} | null}
|
|
101
|
+
*/
|
|
102
|
+
export function resolveImportedComponent(nameNode, scopePath, imports) {
|
|
103
|
+
let localName;
|
|
104
|
+
let binding;
|
|
105
|
+
if (nameNode?.type === 'JSXIdentifier' || nameNode?.type === 'Identifier') {
|
|
106
|
+
localName = nameNode.name;
|
|
107
|
+
binding = imports.direct.get(localName);
|
|
108
|
+
} else if (
|
|
109
|
+
(nameNode?.type === 'JSXMemberExpression' ||
|
|
110
|
+
(nameNode?.type === 'MemberExpression' && !nameNode.computed)) &&
|
|
111
|
+
(nameNode.object?.type === 'JSXIdentifier' ||
|
|
112
|
+
nameNode.object?.type === 'Identifier') &&
|
|
113
|
+
(nameNode.property?.type === 'JSXIdentifier' ||
|
|
114
|
+
nameNode.property?.type === 'Identifier') &&
|
|
115
|
+
imports.namespaces.has(nameNode.object.name)
|
|
116
|
+
) {
|
|
117
|
+
localName = nameNode.object.name;
|
|
118
|
+
const component = imports.normalize(nameNode.property.name);
|
|
119
|
+
const props = imports.components.get(component);
|
|
120
|
+
if (props) binding = {component, props};
|
|
121
|
+
}
|
|
122
|
+
if (!binding || !isModuleBinding(scopePath, localName)) return null;
|
|
123
|
+
return {...binding, localName};
|
|
124
|
+
}
|
|
90
125
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
126
|
+
/**
|
|
127
|
+
* @param {any} root jscodeshift collection for one source file
|
|
128
|
+
* @param {any} j configured jscodeshift instance
|
|
129
|
+
* @param {ImportOptions} options
|
|
130
|
+
* @param {(propPath: any, context: {component: string, localName: string}) => void} visit
|
|
131
|
+
*/
|
|
132
|
+
export function transformProp(root, j, options, visit) {
|
|
133
|
+
const imports = importedComponents(root, j, options);
|
|
134
|
+
if (imports.direct.size === 0 && imports.namespaces.size === 0) return;
|
|
135
|
+
|
|
136
|
+
root.find(j.JSXOpeningElement).forEach((/** @type {any} */ jsxPath) => {
|
|
137
|
+
// Only JSX tags whose root binding resolves to Program are usages of the
|
|
138
|
+
// import discovered above.
|
|
139
|
+
const resolved = resolveImportedComponent(
|
|
140
|
+
jsxPath.node.name,
|
|
141
|
+
jsxPath,
|
|
142
|
+
imports,
|
|
143
|
+
);
|
|
144
|
+
if (!resolved) return;
|
|
145
|
+
const {component, props, localName} = resolved;
|
|
96
146
|
|
|
97
147
|
for (let index = 0; index < jsxPath.node.attributes.length; index++) {
|
|
98
148
|
const attribute = jsxPath.node.attributes[index];
|
|
@@ -2,7 +2,11 @@
|
|
|
2
2
|
|
|
3
3
|
import {describe, expect, it} from 'vitest';
|
|
4
4
|
import jscodeshift from 'jscodeshift';
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
importedComponents,
|
|
7
|
+
resolveImportedComponent,
|
|
8
|
+
transformProp,
|
|
9
|
+
} from './transform-prop.mjs';
|
|
6
10
|
|
|
7
11
|
const j = jscodeshift.withParser('tsx');
|
|
8
12
|
const components = new Map([
|
|
@@ -92,4 +96,35 @@ const b = <Group tone="old" size="old" />;`);
|
|
|
92
96
|
expect(output).toContain('<Widget size="old" migratedtone="old"');
|
|
93
97
|
expect(output).toContain('<Group tone="old" migratedsize="old"');
|
|
94
98
|
});
|
|
99
|
+
|
|
100
|
+
it('resolves non-JSX references through the same import and shadow rules', () => {
|
|
101
|
+
const root = j(`import {Widget as Card} from '@example/core';
|
|
102
|
+
import * as Lib from '@example/core';
|
|
103
|
+
const a = Card;
|
|
104
|
+
const b = Lib.Group;
|
|
105
|
+
function shadow(Card, Lib) {
|
|
106
|
+
return [Card, Lib.Group];
|
|
107
|
+
}`);
|
|
108
|
+
const imports = importedComponents(root, j, {
|
|
109
|
+
matchesImport: value => /^@example\/core(?:\/|$)/.test(value),
|
|
110
|
+
components,
|
|
111
|
+
});
|
|
112
|
+
const resolved = root
|
|
113
|
+
.find(j.VariableDeclarator)
|
|
114
|
+
.paths()
|
|
115
|
+
.map(
|
|
116
|
+
path =>
|
|
117
|
+
resolveImportedComponent(path.node.init, path, imports)?.component,
|
|
118
|
+
);
|
|
119
|
+
expect(resolved).toEqual(['Widget', 'Group']);
|
|
120
|
+
const shadowed = root
|
|
121
|
+
.find(j.ArrayExpression)
|
|
122
|
+
.paths()
|
|
123
|
+
.flatMap(path =>
|
|
124
|
+
path.node.elements.map(element =>
|
|
125
|
+
resolveImportedComponent(element, path, imports),
|
|
126
|
+
),
|
|
127
|
+
);
|
|
128
|
+
expect(shadowed).toEqual([null, null]);
|
|
129
|
+
});
|
|
95
130
|
});
|