@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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
  3. package/api/integration/pack-check.mjs +10 -4
  4. package/api/integration/pack-check.test.mjs +5 -1
  5. package/api/upgrade/_adapter.d.mts +2 -0
  6. package/api/upgrade/run/failure-receipt.test.mjs +212 -0
  7. package/api/upgrade/run/run.mjs +251 -10
  8. package/api/upgrade/upgrade.doc.mjs +4 -4
  9. package/api/upgrade/upgrade.mjs +19 -4
  10. package/api/upgrade/upgrade.type.d.mts +12 -1
  11. package/api/upgrade/upgrade.type.mjs +17 -4
  12. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  13. package/assets/codemods/__tests__/runner.unparseable.test.mjs +457 -0
  14. package/assets/codemods/integration-runner.mjs +8 -2
  15. package/assets/codemods/integration-runner.protection.test.mjs +53 -0
  16. package/assets/codemods/parse.mjs +94 -0
  17. package/assets/codemods/run-codemod.mjs +109 -5
  18. package/assets/codemods/runner.mjs +108 -10
  19. package/assets/codemods/transform-prop.mjs +99 -49
  20. package/assets/codemods/transform-prop.test.mjs +36 -1
  21. package/assets/codemods/transforms/v0.1.3/__tests__/migrate-layout-components-to-experimental.test.mjs +216 -2
  22. package/assets/codemods/transforms/v0.1.3/migrate-layout-components-to-experimental.mjs +88 -6
  23. package/assets/codemods/transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs +4 -3
  24. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  25. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +123 -70
  26. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  27. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +244 -42
  28. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +19 -77
  29. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  30. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.doc.mjs +1 -1
  31. package/assets/templates/blocks/components/CodeBlock/CodeBlockBashCommand.tsx +10 -2
  32. package/assets/templates/pages/library/page.tsx +1 -2
  33. package/authoring/codemod/type.ts +10 -0
  34. package/clients/cli/commands/upgrade.doc.mjs +27 -0
  35. package/clients/cli/commands/upgrade.file-protection.test.mjs +175 -0
  36. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  37. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  38. package/clients/cli/commands/upgrade.mjs +9 -2
  39. package/foundation/response/base.d.ts +7 -0
  40. package/foundation/response/error-codes.doc.mjs +3 -2
  41. package/foundation/response/error-codes.mjs +1 -1
  42. package/foundation/response/json.d.mts +10 -3
  43. package/foundation/response/json.mjs +16 -4
  44. package/package.json +10 -9
@@ -0,0 +1,457 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file A protected file a codemod cannot parse is declined for manual review
5
+ * instead of failing the run; every other codemod error still fails it.
6
+ */
7
+
8
+ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
9
+ import * as fs from 'node:fs';
10
+ import * as path from 'node:path';
11
+ import {runCodemods} from '../runner.mjs';
12
+ import {parseCss, processSelector} from '../parse.mjs';
13
+ import validateDataTokenOwnership, {
14
+ meta as validateDataTokenOwnershipMeta,
15
+ } from '../transforms/v0.7.0/validate-data-token-ownership.mjs';
16
+ import migrateThemeSelectors, {
17
+ meta as migrateThemeSelectorsMeta,
18
+ } from '../transforms/v0.6.0/migrate-astryx-theme-selectors-to-data-attrs.mjs';
19
+ import migrateDeprecatedThemeSurface, {
20
+ meta as migrateDeprecatedThemeSurfaceMeta,
21
+ } from '../transforms/v0.7.0/migrate-deprecated-theme-surface.mjs';
22
+
23
+ let tmpDir;
24
+ let originalCwd;
25
+
26
+ beforeEach(() => {
27
+ originalCwd = process.cwd();
28
+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-runner-test-'));
29
+ process.chdir(tmpDir);
30
+ });
31
+
32
+ afterEach(() => {
33
+ process.chdir(originalCwd);
34
+ fs.rmSync(tmpDir, {recursive: true, force: true});
35
+ });
36
+
37
+ describe('runCodemods — protected files that do not parse', () => {
38
+ // A transform that parses every file it is handed, like real codemods do.
39
+ const manifests = [
40
+ {
41
+ version: '0.1.3',
42
+ transforms: [
43
+ {
44
+ name: 'rename-foo',
45
+ meta: {title: 'rename foo'},
46
+ transform: (file, {jscodeshift: j}) => {
47
+ const root = j(file.source);
48
+ root.find(j.Identifier, {name: 'foo'}).forEach(p => {
49
+ p.node.name = 'bar';
50
+ });
51
+ return root.toSource();
52
+ },
53
+ },
54
+ ],
55
+ },
56
+ ];
57
+ const BROKEN = 'export const foo = {;\n';
58
+
59
+ function seedVendored() {
60
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
61
+ fs.mkdirSync(path.join(tmpDir, 'vendor'), {recursive: true});
62
+ fs.writeFileSync(
63
+ path.join(tmpDir, '.gitattributes'),
64
+ 'vendor/** linguist-vendored\n',
65
+ );
66
+ fs.writeFileSync(path.join(tmpDir, 'src', 'owned.ts'), 'const foo = 1;\n');
67
+ fs.writeFileSync(path.join(tmpDir, 'vendor', 'bundle.js'), BROKEN);
68
+ }
69
+
70
+ it('declines a vendored file that does not parse and completes the owned edits', async () => {
71
+ seedVendored();
72
+
73
+ const r = await runCodemods(manifests, {
74
+ apply: true,
75
+ path: '.',
76
+ silent: true,
77
+ });
78
+
79
+ expect(r.errors).toEqual([]);
80
+ expect(r.protectedFiles).toEqual([]);
81
+ expect(r.declinedCandidates).toEqual([
82
+ {
83
+ file: path.join('vendor', 'bundle.js'),
84
+ codemod: 'core:rename-foo',
85
+ location: '1:21',
86
+ reason: expect.stringMatching(
87
+ /^unparseable protected file \(vendored\): /,
88
+ ),
89
+ },
90
+ ]);
91
+ expect(fs.readFileSync(path.join(tmpDir, 'src', 'owned.ts'), 'utf-8')).toBe(
92
+ 'const bar = 1;\n',
93
+ );
94
+ expect(
95
+ fs.readFileSync(path.join(tmpDir, 'vendor', 'bundle.js'), 'utf-8'),
96
+ ).toBe(BROKEN);
97
+ });
98
+
99
+ it('declines the same file in a dry run', async () => {
100
+ seedVendored();
101
+
102
+ const r = await runCodemods(manifests, {
103
+ apply: false,
104
+ path: '.',
105
+ silent: true,
106
+ });
107
+
108
+ expect(r.errors).toEqual([]);
109
+ expect(r.declinedCandidates.map(item => item.file)).toEqual([
110
+ path.join('vendor', 'bundle.js'),
111
+ ]);
112
+ expect(r.changedFiles.map(f => path.basename(f))).toEqual(['owned.ts']);
113
+ });
114
+
115
+ it('declines an unparseable file under an ignore rule or a generated marker', async () => {
116
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
117
+ fs.writeFileSync(path.join(tmpDir, '.gitignore'), 'ignored/\n');
118
+ fs.mkdirSync(path.join(tmpDir, 'ignored'), {recursive: true});
119
+ fs.writeFileSync(path.join(tmpDir, 'ignored', 'a.js'), BROKEN);
120
+ fs.writeFileSync(
121
+ path.join(tmpDir, 'src', 'gen.js'),
122
+ `// @generated\n${BROKEN}`,
123
+ );
124
+
125
+ const r = await runCodemods(manifests, {
126
+ apply: true,
127
+ path: '.',
128
+ silent: true,
129
+ });
130
+
131
+ expect(r.errors).toEqual([]);
132
+ expect(r.declinedCandidates.map(item => item.file).sort()).toEqual([
133
+ path.join('ignored', 'a.js'),
134
+ path.join('src', 'gen.js'),
135
+ ]);
136
+ });
137
+
138
+ it('still analyses a protected file that parses and reports its required change', async () => {
139
+ seedVendored();
140
+ fs.writeFileSync(
141
+ path.join(tmpDir, 'vendor', 'parsed.js'),
142
+ 'export const foo = 1;\n',
143
+ );
144
+
145
+ const r = await runCodemods(manifests, {
146
+ apply: true,
147
+ path: '.',
148
+ silent: true,
149
+ });
150
+
151
+ expect(r.protectedFiles).toEqual([
152
+ expect.objectContaining({
153
+ file: path.join('vendor', 'parsed.js'),
154
+ reason: 'vendored',
155
+ }),
156
+ ]);
157
+ expect(r.declinedCandidates.map(item => item.file)).toEqual([
158
+ path.join('vendor', 'bundle.js'),
159
+ ]);
160
+ });
161
+
162
+ it('still fails on owned source that does not parse', async () => {
163
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
164
+ fs.writeFileSync(path.join(tmpDir, 'src', 'broken.js'), BROKEN);
165
+
166
+ const r = await runCodemods(manifests, {
167
+ apply: true,
168
+ path: '.',
169
+ silent: true,
170
+ });
171
+
172
+ expect(r.declinedCandidates).toEqual([]);
173
+ expect(r.errors).toEqual([
174
+ expect.objectContaining({
175
+ file: path.join('src', 'broken.js'),
176
+ codemod: 'core:rename-foo',
177
+ }),
178
+ ]);
179
+ });
180
+
181
+ it('still fails when a transform throws on a protected file that parses', async () => {
182
+ seedVendored();
183
+ fs.writeFileSync(
184
+ path.join(tmpDir, 'vendor', 'bundle.js'),
185
+ 'const x = 1;\n',
186
+ );
187
+ const throwing = [
188
+ {
189
+ version: '0.1.3',
190
+ transforms: [
191
+ {
192
+ name: 'throws',
193
+ meta: {title: 'throws'},
194
+ transform: file => {
195
+ if (file.path.endsWith('bundle.js')) throw new Error('boom');
196
+ return null;
197
+ },
198
+ },
199
+ ],
200
+ },
201
+ ];
202
+
203
+ const r = await runCodemods(throwing, {
204
+ apply: true,
205
+ path: '.',
206
+ silent: true,
207
+ });
208
+
209
+ expect(r.declinedCandidates).toEqual([]);
210
+ expect(r.errors).toEqual([
211
+ {
212
+ file: path.join('vendor', 'bundle.js'),
213
+ codemod: 'core:throws',
214
+ error: 'boom',
215
+ },
216
+ ]);
217
+ });
218
+
219
+ it('keeps a CSS codemod error on a generated stylesheet that parses', async () => {
220
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
221
+ const theme =
222
+ '/* @generated by `astryx theme build` */\n' +
223
+ ':root {\n --color-data-1: #000;\n}\n';
224
+ fs.writeFileSync(path.join(tmpDir, 'src', 'theme.css'), theme);
225
+
226
+ const r = await runCodemods(
227
+ [
228
+ {
229
+ version: '0.7.0',
230
+ transforms: [
231
+ {
232
+ name: 'validate-data-token-ownership',
233
+ transform: validateDataTokenOwnership,
234
+ meta: validateDataTokenOwnershipMeta,
235
+ },
236
+ ],
237
+ },
238
+ ],
239
+ {apply: true, path: '.', silent: true},
240
+ );
241
+
242
+ expect(r.declinedCandidates).toEqual([]);
243
+ expect(r.errors).toEqual([
244
+ {
245
+ file: path.join('src', 'theme.css'),
246
+ codemod: 'core:validate-data-token-ownership',
247
+ error: expect.stringContaining('astryx theme build'),
248
+ },
249
+ ]);
250
+ expect(
251
+ fs.readFileSync(path.join(tmpDir, 'src', 'theme.css'), 'utf-8'),
252
+ ).toBe(theme);
253
+ });
254
+
255
+ it('declines a protected stylesheet that does not parse as CSS', async () => {
256
+ fs.mkdirSync(path.join(tmpDir, 'vendor'), {recursive: true});
257
+ fs.writeFileSync(
258
+ path.join(tmpDir, '.gitattributes'),
259
+ 'vendor/** linguist-vendored\n',
260
+ );
261
+ fs.writeFileSync(path.join(tmpDir, 'vendor', 'broken.css'), 'a {\n');
262
+
263
+ const r = await runCodemods(
264
+ [
265
+ {
266
+ version: '0.1.3',
267
+ transforms: [
268
+ {
269
+ name: 'css',
270
+ meta: {title: 'css', fileExtensions: ['.css']},
271
+ transform: file => parseCss(file.source).toString(),
272
+ },
273
+ ],
274
+ },
275
+ ],
276
+ {apply: true, path: '.', silent: true},
277
+ );
278
+
279
+ expect(r.errors).toEqual([]);
280
+ expect(r.declinedCandidates).toEqual([
281
+ {
282
+ file: path.join('vendor', 'broken.css'),
283
+ codemod: 'core:css',
284
+ location: '1:1',
285
+ reason: 'unparseable protected file (vendored): Unclosed block',
286
+ },
287
+ ]);
288
+ });
289
+
290
+ it('declines a vendored stylesheet whose selector the real theme codemod cannot parse', async () => {
291
+ fs.mkdirSync(path.join(tmpDir, 'vendor'), {recursive: true});
292
+ fs.writeFileSync(
293
+ path.join(tmpDir, '.gitattributes'),
294
+ 'vendor/** linguist-vendored\n',
295
+ );
296
+ const bundle = 'a:: { color: red; }\n';
297
+ fs.writeFileSync(path.join(tmpDir, 'vendor', 'bundle.css'), bundle);
298
+
299
+ const r = await runCodemods(
300
+ [
301
+ {
302
+ version: '0.7.0',
303
+ transforms: [
304
+ {
305
+ name: 'migrate-deprecated-theme-surface',
306
+ transform: migrateDeprecatedThemeSurface,
307
+ meta: migrateDeprecatedThemeSurfaceMeta,
308
+ },
309
+ ],
310
+ },
311
+ ],
312
+ {apply: true, path: '.', silent: true},
313
+ );
314
+
315
+ expect(r.errors).toEqual([]);
316
+ expect(r.protectedFiles).toEqual([]);
317
+ expect(r.declinedCandidates).toEqual([
318
+ {
319
+ file: path.join('vendor', 'bundle.css'),
320
+ codemod: 'core:migrate-deprecated-theme-surface',
321
+ location: '1:3',
322
+ reason:
323
+ 'unparseable protected file (vendored): Expected a pseudo-class or pseudo-element.',
324
+ },
325
+ ]);
326
+ expect(
327
+ fs.readFileSync(path.join(tmpDir, 'vendor', 'bundle.css'), 'utf-8'),
328
+ ).toBe(bundle);
329
+ });
330
+
331
+ it('keeps an error a transform throws after the file parses', async () => {
332
+ fs.mkdirSync(path.join(tmpDir, 'vendor'), {recursive: true});
333
+ fs.writeFileSync(
334
+ path.join(tmpDir, '.gitattributes'),
335
+ 'vendor/** linguist-vendored\n',
336
+ );
337
+ fs.writeFileSync(
338
+ path.join(tmpDir, 'vendor', 'a.css'),
339
+ 'a { color: red; }\n',
340
+ );
341
+
342
+ const r = await runCodemods(
343
+ [
344
+ {
345
+ version: '0.1.3',
346
+ transforms: [
347
+ {
348
+ name: 'walks',
349
+ meta: {title: 'walks', fileExtensions: ['.css']},
350
+ transform: file => {
351
+ parseCss(file.source).walkRules(rule =>
352
+ processSelector(rule.selector, () => {
353
+ throw new Error('callback failed');
354
+ }),
355
+ );
356
+ return null;
357
+ },
358
+ },
359
+ ],
360
+ },
361
+ ],
362
+ {apply: true, path: '.', silent: true},
363
+ );
364
+
365
+ expect(r.declinedCandidates).toEqual([]);
366
+ expect(r.errors).toEqual([
367
+ {
368
+ file: path.join('vendor', 'a.css'),
369
+ codemod: 'core:walks',
370
+ error: 'callback failed',
371
+ },
372
+ ]);
373
+ });
374
+
375
+ it('lists a file another codemod still needs to change under protectedFiles only', async () => {
376
+ fs.mkdirSync(path.join(tmpDir, 'vendor'), {recursive: true});
377
+ fs.writeFileSync(
378
+ path.join(tmpDir, '.gitattributes'),
379
+ 'vendor/** linguist-vendored\n',
380
+ );
381
+ fs.writeFileSync(
382
+ path.join(tmpDir, 'vendor', 'bundle.css'),
383
+ 'a:: { color: red; }\n',
384
+ );
385
+
386
+ const r = await runCodemods(
387
+ [
388
+ {
389
+ version: '0.6.0',
390
+ transforms: [
391
+ {
392
+ name: 'migrate-astryx-theme-selectors-to-data-attrs',
393
+ transform: migrateThemeSelectors,
394
+ meta: migrateThemeSelectorsMeta,
395
+ },
396
+ ],
397
+ },
398
+ {
399
+ version: '0.7.0',
400
+ transforms: [
401
+ {
402
+ name: 'migrate-deprecated-theme-surface',
403
+ transform: migrateDeprecatedThemeSurface,
404
+ meta: migrateDeprecatedThemeSurfaceMeta,
405
+ },
406
+ ],
407
+ },
408
+ ],
409
+ {apply: true, path: '.', silent: true},
410
+ );
411
+
412
+ expect(r.errors).toEqual([]);
413
+ expect(r.protectedFiles.map(item => item.file)).toEqual([
414
+ 'vendor/bundle.css',
415
+ ]);
416
+ expect(r.declinedCandidates).toEqual([]);
417
+ });
418
+
419
+ it('gives a rejected @scope prelude its position in the stylesheet', async () => {
420
+ fs.mkdirSync(path.join(tmpDir, 'vendor'), {recursive: true});
421
+ fs.writeFileSync(
422
+ path.join(tmpDir, '.gitattributes'),
423
+ 'vendor/** linguist-vendored\n',
424
+ );
425
+ fs.writeFileSync(
426
+ path.join(tmpDir, 'vendor', 'bundle.css'),
427
+ '.x { color: blue; }\n\n@scope (a::) {\n b { color: red; }\n}\n',
428
+ );
429
+
430
+ const r = await runCodemods(
431
+ [
432
+ {
433
+ version: '0.7.0',
434
+ transforms: [
435
+ {
436
+ name: 'migrate-deprecated-theme-surface',
437
+ transform: migrateDeprecatedThemeSurface,
438
+ meta: migrateDeprecatedThemeSurfaceMeta,
439
+ },
440
+ ],
441
+ },
442
+ ],
443
+ {apply: true, path: '.', silent: true},
444
+ );
445
+
446
+ expect(r.errors).toEqual([]);
447
+ expect(r.declinedCandidates).toEqual([
448
+ {
449
+ file: path.join('vendor', 'bundle.css'),
450
+ codemod: 'core:migrate-deprecated-theme-surface',
451
+ location: '3:9',
452
+ reason:
453
+ 'unparseable protected file (vendored): Expected a pseudo-class or pseudo-element.',
454
+ },
455
+ ]);
456
+ });
457
+ });
@@ -24,6 +24,7 @@ import {
24
24
  runCodeCodemod,
25
25
  runConfigCodemod,
26
26
  } from './run-codemod.mjs';
27
+ import {withoutProtected} from './runner.mjs';
27
28
  import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
28
29
 
29
30
  /**
@@ -44,7 +45,7 @@ import {createFileProtectionResolver} from '../../foundation/fs/file-protection.
44
45
  * @param {string} [options.root]
45
46
  * @param {Map<string, string>} [options.contents] staged bytes from earlier dry-run phases
46
47
  * @param {{root: string, classify: (file: string) => import('../../foundation/fs/file-protection.mjs').FileProtection[]}} [options.protection]
47
- * @returns {{totalFilesChanged: number, totalTransformsApplied: 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<import('../../authoring/codemod/type').CodemodEntry>}}
48
+ * @returns {{totalFilesChanged: number, totalTransformsApplied: 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<import('../../authoring/codemod/type').CodemodEntry>}}
48
49
  */
49
50
  export function runIntegrationCodemods(
50
51
  versionGroups,
@@ -74,6 +75,8 @@ export function runIntegrationCodemods(
74
75
  const writtenFiles = [];
75
76
  /** @type {import('../../authoring/codemod/type').CodemodRunResult['protectedFiles']} */
76
77
  const protectedFiles = [];
78
+ /** @type {NonNullable<import('../../authoring/codemod/type').CodemodRunResult['declinedCandidates']>} */
79
+ const declinedCandidates = [];
77
80
  /** @type {Array<{file: string, codemod: string, error: string}>} */
78
81
  const errors = [];
79
82
  /** @type {Array<import('../../authoring/codemod/type').CodemodEntry>} */
@@ -125,7 +128,7 @@ export function runIntegrationCodemods(
125
128
  if (codeEntries.length > 0) {
126
129
  const resolvedPath = path.resolve(srcPath);
127
130
  const files = fs.existsSync(resolvedPath)
128
- ? findSourceFiles(resolvedPath)
131
+ ? findSourceFiles(resolvedPath, path.resolve(root))
129
132
  : [];
130
133
  for (const entry of codeEntries) {
131
134
  if (apply && writtenFiles.length !== protectionWriteCount) {
@@ -147,9 +150,11 @@ export function runIntegrationCodemods(
147
150
  changedFiles.push(...r.changedFiles);
148
151
  writtenFiles.push(...r.writtenFiles);
149
152
  protectedFiles.push(...r.protectedFiles);
153
+ declinedCandidates.push(...(r.declinedCandidates ?? []));
150
154
  errors.push(...r.errors);
151
155
  }
152
156
  }
157
+ const reportedDeclined = withoutProtected(declinedCandidates, protectedFiles);
153
158
 
154
159
  // A file several codemods changed is one file; transforms count each change.
155
160
  const totalFilesChanged = new Set(changedFiles).size;
@@ -161,6 +166,7 @@ export function runIntegrationCodemods(
161
166
  writtenFiles,
162
167
  stagedContents: virtualContents,
163
168
  protectedFiles,
169
+ declinedCandidates: reportedDeclined,
164
170
  errors,
165
171
  skippedOptional,
166
172
  };
@@ -150,4 +150,57 @@ describe('integration codemod file protection', () => {
150
150
  }),
151
151
  ]);
152
152
  });
153
+
154
+ it('declines a protected file that does not parse, as the core runner does', async () => {
155
+ write('.gitattributes', 'src/vendor/** linguist-vendored\n');
156
+ write('src/owned.js', "export const value = 'old';\n");
157
+ write('src/vendor/bundle.js', 'export const value = {;\n');
158
+ write('src/broken.js', 'export const value = {;\n');
159
+
160
+ const groups = [
161
+ {
162
+ version: '1.0.0',
163
+ codemods: [
164
+ {
165
+ id: 'code',
166
+ type: 'code',
167
+ package: '@acme/integration',
168
+ codemod: {
169
+ title: 'code',
170
+ fileExtensions: ['.js'],
171
+ transform: (file, {jscodeshift: j}) => {
172
+ const ast = j(file.source);
173
+ ast.find(j.Identifier, {name: 'value'}).forEach(p => {
174
+ p.node.name = 'renamed';
175
+ });
176
+ return ast.toSource();
177
+ },
178
+ },
179
+ },
180
+ ],
181
+ },
182
+ ];
183
+ const jscodeshift = (await import('jscodeshift')).default;
184
+ const result = runIntegrationCodemods(groups, {
185
+ apply: true,
186
+ path: path.join(root, 'src'),
187
+ root,
188
+ jscodeshift,
189
+ silent: true,
190
+ });
191
+
192
+ expect(fs.readFileSync(path.join(root, 'src/owned.js'), 'utf8')).toContain(
193
+ 'renamed',
194
+ );
195
+ expect(result.declinedCandidates).toEqual([
196
+ expect.objectContaining({
197
+ file: path.join('src', 'vendor', 'bundle.js'),
198
+ codemod: '@acme/integration:code',
199
+ location: '1:23',
200
+ }),
201
+ ]);
202
+ expect(result.errors).toEqual([
203
+ expect.objectContaining({file: path.join('src', 'broken.js')}),
204
+ ]);
205
+ });
153
206
  });
@@ -0,0 +1,94 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Parse entry points that mark their own failures.
5
+ *
6
+ * @input Source text a codemod reads: a file's JavaScript or TypeScript, a
7
+ * stylesheet, or one CSS selector.
8
+ * @output The parsed tree; a parse failure is rethrown with
9
+ * `code: 'ERR_CODEMOD_PARSE'`.
10
+ * @position Shared by the codemod runner and the core CSS codemods. The runner
11
+ * skips a protected file only when its error carries this code, so any other
12
+ * error a codemod throws still fails the run.
13
+ */
14
+
15
+ import postcss from 'postcss';
16
+ import selectorParser from 'postcss-selector-parser';
17
+
18
+ export const CODEMOD_PARSE_ERROR = 'ERR_CODEMOD_PARSE';
19
+
20
+ /**
21
+ * Mark an error as a parse failure and return it.
22
+ * @template T
23
+ * @param {T} err
24
+ * @returns {T}
25
+ */
26
+ export function markParseError(err) {
27
+ if (err && typeof err === 'object') {
28
+ /** @type {any} */ (err).code = CODEMOD_PARSE_ERROR;
29
+ }
30
+ return err;
31
+ }
32
+
33
+ /**
34
+ * @param {unknown} err
35
+ * @returns {boolean}
36
+ */
37
+ export function isCodemodParseError(err) {
38
+ return /** @type {any} */ (err)?.code === CODEMOD_PARSE_ERROR;
39
+ }
40
+
41
+ /**
42
+ * `postcss.parse`, with a failure marked as a parse error.
43
+ * @param {string} source
44
+ * @param {import('postcss').ProcessOptions} [options]
45
+ */
46
+ export function parseCss(source, options) {
47
+ try {
48
+ return postcss.parse(source, options);
49
+ } catch (err) {
50
+ throw markParseError(err);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Parse one selector, hand its tree to `callback`, and return the tree as
56
+ * text, like `selectorParser(callback).processSync(selector, {lossless:
57
+ * true})`. Pass the PostCSS rule rather than its selector text when there is
58
+ * one: a failure then reports its line and column in the stylesheet. Only a
59
+ * failure to parse is marked; an error `callback` throws is passed through
60
+ * unchanged.
61
+ * @param {string | import('postcss').Rule} selector selector text, or the rule that holds it
62
+ * @param {(root: import('postcss-selector-parser').Root) => void} callback
63
+ * @returns {string}
64
+ */
65
+ export function processSelector(selector, callback) {
66
+ let root;
67
+ try {
68
+ root = selectorParser().astSync(selector, {lossless: true});
69
+ } catch (err) {
70
+ throw markParseError(err);
71
+ }
72
+ callback(root);
73
+ return root.toString();
74
+ }
75
+
76
+ /**
77
+ * The jscodeshift a code codemod receives for one file. Parsing that file's
78
+ * own source (`j(file.source)`) marks a failure as a parse error; every other
79
+ * call and property behaves as jscodeshift does.
80
+ * @param {any} j jscodeshift bound to the file's parser
81
+ * @param {string} source the file's source
82
+ * @returns {any}
83
+ */
84
+ export function markingSourceParseErrors(j, source) {
85
+ return new Proxy(j, {
86
+ apply(target, thisArg, args) {
87
+ try {
88
+ return Reflect.apply(target, thisArg, args);
89
+ } catch (err) {
90
+ throw args[0] === source ? markParseError(err) : err;
91
+ }
92
+ },
93
+ });
94
+ }