@wise/wds-codemods 1.0.0-experimental-be47db3 → 1.0.0-experimental-3bdf602
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/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
const require_constants = require('./constants-CcE2TmzN.js');
|
|
3
|
-
const require_transformer = require('./transformer-
|
|
3
|
+
const require_transformer = require('./transformer-emwItDkN.js');
|
|
4
4
|
const require_helpers = require('./helpers-IFtIGywc.js');
|
|
5
5
|
let node_child_process = require("node:child_process");
|
|
6
6
|
let node_fs_promises = require("node:fs/promises");
|
|
@@ -26,6 +26,7 @@ function logStaticMessage(spinnies$1, message) {
|
|
|
26
26
|
|
|
27
27
|
//#endregion
|
|
28
28
|
//#region src/transforms/list-item/constants.ts
|
|
29
|
+
const CONCURRENCY_LIMIT = 10;
|
|
29
30
|
const DEPRECATED_COMPONENT_NAMES = [
|
|
30
31
|
"ActionOption",
|
|
31
32
|
"NavigationOption",
|
|
@@ -35,6 +36,7 @@ const DEPRECATED_COMPONENT_NAMES = [
|
|
|
35
36
|
"CheckboxOption",
|
|
36
37
|
"RadioOption"
|
|
37
38
|
];
|
|
39
|
+
const GREP_PATTERN = new RegExp(`import\\s*\\{[\\s\\S]*?(${DEPRECATED_COMPONENT_NAMES.join("|")})[\\s\\S]*?\\}\\s*from\\s*['"]@transferwise/components['"]`, "u");
|
|
38
40
|
const MIGRATION_RULES = `Migration rules:
|
|
39
41
|
# Legacy Component → ListItem Migration Guide
|
|
40
42
|
|
|
@@ -303,10 +305,13 @@ async function checkVPN(spinnies$1, baseUrl) {
|
|
|
303
305
|
spinnies$1.succeed("vpnCheck", { text: "Connected to VPN" });
|
|
304
306
|
break;
|
|
305
307
|
}
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
308
|
+
for (let countdown = 5; countdown > 0; countdown -= 1) {
|
|
309
|
+
spinnies$1.update("vpnCheck", { text: `Please connect to VPN... retrying in \x1b[32m${countdown}\x1b[0ms` });
|
|
310
|
+
await new Promise((response) => {
|
|
311
|
+
setTimeout(response, 1e3);
|
|
312
|
+
});
|
|
313
|
+
if (countdown === 1) countdown = 6;
|
|
314
|
+
}
|
|
310
315
|
}
|
|
311
316
|
}
|
|
312
317
|
return true;
|
|
@@ -366,7 +371,7 @@ async function initiateClaudeSessionOptions(spinnies$1) {
|
|
|
366
371
|
}
|
|
367
372
|
return options;
|
|
368
373
|
}
|
|
369
|
-
async function queryClaude(directory, filePath, options,
|
|
374
|
+
async function queryClaude(directory, filePath, options, spinnies$1, isDebug = false) {
|
|
370
375
|
const startTime = Date.now();
|
|
371
376
|
const debugSpinnies = new spinnies.default();
|
|
372
377
|
const result = (0, __anthropic_ai_claude_agent_sdk.query)({
|
|
@@ -377,10 +382,8 @@ async function queryClaude(directory, filePath, options, codemodOptions, spinnie
|
|
|
377
382
|
case "assistant":
|
|
378
383
|
for (const msg of message.message.content) switch (msg.type) {
|
|
379
384
|
case "tool_use":
|
|
380
|
-
if (msg.name === "Read") {
|
|
381
|
-
|
|
382
|
-
spinnies$1.update(`file-${filePath}`, { text: `${formatPathOutput(directory, filePath, true)} - Reading...` });
|
|
383
|
-
} else if (msg.name === "Edit") spinnies$1.update(`file-${filePath}`, { text: `${formatPathOutput(directory, filePath, true)} - Migrating...` });
|
|
385
|
+
if (msg.name === "Read") spinnies$1.update(`file-${filePath}`, { text: `\x1b[2m${formatPathOutput(directory, filePath)} - Reading...\x1b[0m` });
|
|
386
|
+
else if (msg.name === "Edit") spinnies$1.update(`file-${filePath}`, { text: `\x1b[2m${formatPathOutput(directory, filePath)} - Migrating...\x1b[0m` });
|
|
384
387
|
break;
|
|
385
388
|
case "text":
|
|
386
389
|
if (isDebug) logStaticMessage(debugSpinnies, `${require_constants.CONSOLE_ICONS.claude} ${formatClaudeResponseContent(msg.text)}`);
|
|
@@ -389,10 +392,10 @@ async function queryClaude(directory, filePath, options, codemodOptions, spinnie
|
|
|
389
392
|
}
|
|
390
393
|
break;
|
|
391
394
|
case "result":
|
|
392
|
-
if (message.subtype === "success") spinnies$1.succeed(`file-${filePath}`, { text:
|
|
395
|
+
if (message.subtype === "success") spinnies$1.succeed(`file-${filePath}`, { text: `\x1b[0m${formatPathOutput(directory, filePath, true)}\x1b[0m\x1b[2m - Migrated in ${generateElapsedTime(startTime)}\x1b[0m` });
|
|
393
396
|
else {
|
|
394
397
|
logStaticMessage(debugSpinnies, `${require_constants.CONSOLE_ICONS.error} Claude encountered an error:`);
|
|
395
|
-
|
|
398
|
+
logStaticMessage(debugSpinnies, JSON.stringify(message));
|
|
396
399
|
spinnies$1.stopAll("fail");
|
|
397
400
|
debugSpinnies.stopAll("fail");
|
|
398
401
|
}
|
|
@@ -409,47 +412,67 @@ const transformer = async (targetPaths, codemodOptions, isDebug = false) => {
|
|
|
409
412
|
const queryOptions = await initiateClaudeSessionOptions(spinnies$1);
|
|
410
413
|
spinnies$1.remove("placeholder");
|
|
411
414
|
spinnies$1.add("analysing", { text: "Analysing targetted paths - this may take a while..." });
|
|
412
|
-
|
|
415
|
+
const globalExecutingFiles = [];
|
|
416
|
+
const processFile = async (directory, filePath) => {
|
|
417
|
+
spinnies$1.remove("placeholder");
|
|
418
|
+
spinnies$1.add(`file-${filePath}`, {
|
|
419
|
+
indent: 4,
|
|
420
|
+
text: `\x1b[2m${formatPathOutput(directory, filePath)} - Parsing...\x1b[0m`
|
|
421
|
+
});
|
|
422
|
+
const originalFileContent = (0, node_fs.readFileSync)(filePath, "utf-8");
|
|
423
|
+
spinnies$1.update(`file-${filePath}`, {
|
|
424
|
+
indent: 4,
|
|
425
|
+
text: `\x1b[2m${formatPathOutput(directory, filePath)} - Processing...\x1b[0m`
|
|
426
|
+
});
|
|
427
|
+
await queryClaude(directory, filePath, queryOptions, spinnies$1, isDebug);
|
|
428
|
+
if (codemodOptions.isPrint) {
|
|
429
|
+
const newFileContent = (0, node_fs.readFileSync)(filePath, "utf-8");
|
|
430
|
+
logStaticMessage(spinnies$1, `Diff for ${formatPathOutput(directory, filePath, true)}:`);
|
|
431
|
+
logStaticMessage(spinnies$1, generateDiff(originalFileContent, newFileContent));
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
const processDirectory = async (directory) => {
|
|
413
435
|
spinnies$1.add(`directory-${directory}`, {
|
|
414
436
|
indent: 2,
|
|
415
|
-
text: `${formatPathOutput(directory)} - Processing
|
|
437
|
+
text: `${formatPathOutput(directory)} - Processing...`
|
|
416
438
|
});
|
|
417
439
|
const allTsxFiles = (0, node_child_process.execSync)(`find "${directory}" -name "*.tsx" -type f`, { encoding: "utf-8" }).trim().split("\n").filter(Boolean);
|
|
418
|
-
const
|
|
440
|
+
const filesQueued = [];
|
|
419
441
|
const matchingFilePaths = allTsxFiles.filter((filePath) => {
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
return grepPattern.test(content);
|
|
423
|
-
} catch {
|
|
424
|
-
return false;
|
|
425
|
-
}
|
|
442
|
+
const content = (0, node_fs.readFileSync)(filePath, "utf-8");
|
|
443
|
+
return GREP_PATTERN.test(content);
|
|
426
444
|
});
|
|
427
445
|
spinnies$1.update(`directory-${directory}`, { text: `${formatPathOutput(directory)} - Found \x1b[32m${matchingFilePaths.length}\x1b[0m \x1b[2m*.tsx\x1b[0m file(s) needing migration` });
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
446
|
+
const completedFilesInDirectory = { count: 0 };
|
|
447
|
+
for (let i = 0; i < matchingFilePaths.length; i += 1) {
|
|
448
|
+
const promise = processFile(directory, matchingFilePaths[i]).then(() => {
|
|
449
|
+
globalExecutingFiles.splice(globalExecutingFiles.indexOf(promise), 1);
|
|
450
|
+
completedFilesInDirectory.count += 1;
|
|
451
|
+
spinnies$1.update(`directory-${directory}`, { text: `${formatPathOutput(directory)} - Migrated \x1b[32m${completedFilesInDirectory.count}\x1b[0m/\x1b[32m${matchingFilePaths.length}\x1b[0m \x1b[2m*.tsx\x1b[0m files` });
|
|
432
452
|
});
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
}
|
|
444
|
-
spinnies$1.remove("placeholder");
|
|
453
|
+
globalExecutingFiles.push(promise);
|
|
454
|
+
filesQueued.push(promise);
|
|
455
|
+
const moreFilesToProcess = i < matchingFilePaths.length - 1;
|
|
456
|
+
if (globalExecutingFiles.length >= CONCURRENCY_LIMIT) if (moreFilesToProcess) {
|
|
457
|
+
spinnies$1.add("placeholder", {
|
|
458
|
+
text: "\x1B[2mThere are still additional files to be queued, waiting for other files to finish first...\x1B[0m",
|
|
459
|
+
indent: 4
|
|
460
|
+
});
|
|
461
|
+
await Promise.race(globalExecutingFiles);
|
|
462
|
+
} else break;
|
|
445
463
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
464
|
+
Promise.all(filesQueued).then(() => {
|
|
465
|
+
if (matchingFilePaths.length === 0) spinnies$1.succeed(`directory-${directory}`, { text: `${formatPathOutput(directory)}\x1b[2m - No files need migration\x1b[0m` });
|
|
466
|
+
else spinnies$1.succeed(`directory-${directory}`, {
|
|
467
|
+
indent: 2,
|
|
468
|
+
text: `${formatPathOutput(directory)} - Migrated \x1b[32m${matchingFilePaths.length}\x1b[0m file(s) successfully!`
|
|
469
|
+
});
|
|
450
470
|
});
|
|
451
|
-
|
|
452
|
-
|
|
471
|
+
return { filesQueued };
|
|
472
|
+
};
|
|
473
|
+
for (const directory of targetPaths) await processDirectory(directory);
|
|
474
|
+
await Promise.all(globalExecutingFiles);
|
|
475
|
+
spinnies$1.update("analysing", { text: "Successfully analysed all targetted paths" });
|
|
453
476
|
spinnies$1.stopAll("succeed");
|
|
454
477
|
spinnies$1.add("done", {
|
|
455
478
|
text: `Finished migrating - elapsed time: \x1b[1m${generateElapsedTime(startTime)}\x1b[0m`,
|
|
@@ -465,4 +488,4 @@ Object.defineProperty(exports, 'transformer_default', {
|
|
|
465
488
|
return transformer_default;
|
|
466
489
|
}
|
|
467
490
|
});
|
|
468
|
-
//# sourceMappingURL=transformer-
|
|
491
|
+
//# sourceMappingURL=transformer-emwItDkN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transformer-emwItDkN.js","names":["https","spinnies","Spinnies","CONSOLE_ICONS","spinnies","Spinnies","globalExecutingFiles: Promise<void>[]","filesQueued: Promise<void>[]"],"sources":["../src/helpers/spinnerLogs.ts","../src/transforms/list-item/constants.ts","../src/transforms/list-item/helpers.ts","../src/transforms/list-item/claude.ts","../src/transforms/list-item/transformer.ts"],"sourcesContent":["import type Spinnies from 'spinnies';\n\ninterface LogConsoleSpinnerSettings {\n spinnies: Spinnies;\n spinnerId: string;\n options: Partial<Spinnies.SpinnerOptions>;\n}\n\nexport function logToConsole({ spinnies, spinnerId, options }: LogConsoleSpinnerSettings): void {\n spinnies.add(spinnerId, options);\n}\n\nexport function logStaticMessage(spinnies: Spinnies, message: string): void {\n // Create a unique spinner ID for the static message using timestamp, first part of the message and a random number\n const uuid = `static-message-${Date.now()}-${message.slice(0, 10).replace(/\\s+/gu, '-')}-${Math.floor(Math.random() * 10000)}`;\n logToConsole({ spinnies, spinnerId: uuid, options: { text: message, status: 'non-spinnable' } });\n}\n","export const CONCURRENCY_LIMIT = 10; // Set to 10 to avoid process memory issues\nconst DEPRECATED_COMPONENT_NAMES = [\n 'ActionOption',\n 'NavigationOption',\n 'NavigationOptionsList',\n 'Summary',\n 'SwitchOption',\n 'CheckboxOption',\n 'RadioOption',\n];\nexport const GREP_PATTERN = new RegExp(\n `import\\\\s*\\\\{[\\\\s\\\\S]*?(${DEPRECATED_COMPONENT_NAMES.join('|')})[\\\\s\\\\S]*?\\\\}\\\\s*from\\\\s*['\"]@transferwise/components['\"]`,\n 'u',\n);\n\nconst MIGRATION_RULES = `Migration rules:\n# Legacy Component → ListItem Migration Guide\n\n## Universal Rules\n\n1. \\`title\\` → \\`title\\` (direct)\n2. \\`content\\` or \\`description\\` → \\`subtitle\\`\n3. \\`disabled\\` stays on \\`ListItem\\` (not controls)\n4. Keep HTML attributes (\\`id\\`, \\`name\\`, \\`aria-label\\`), remove: \\`as\\`, \\`complex\\`, \\`showMediaAtAllSizes\\`, \\`showMediaCircle\\`, \\`isContainerAligned\\`\n5. In strings, don't convert \\`\\`to\\`'\\`or\\`\"\\`. Preserve what is there.\n\n---\n\n## ActionOption → ListItem.Button\n\n- \\`action\\` → Button children\n- \\`onClick\\` → Button \\`onClick\\`\n- Priority: default/\\`\"primary\"\\` → \\`\"primary\"\\`, \\`\"secondary\"\\` → \\`\"secondary-neutral\"\\`, \\`\"secondary-send\"\\` → \\`\"secondary\"\\`, \\`\"tertiary\"\\` → \\`\"tertiary\"\\`\n\n\\`\\`\\`tsx\n<ActionOption title=\"Title\" content=\"Text\" action=\"Click\" priority=\"secondary\" onClick={fn} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Button priority=\"secondary-neutral\" onClick={fn}>Click</ListItem.Button>} />\n\\`\\`\\`\n\n---\n\n## CheckboxOption → ListItem.Checkbox\n\n- \\`onChange\\`: \\`(checked: boolean)\\` → \\`(event: ChangeEvent)\\` use \\`event.target.checked\\`\n- \\`name\\` move to Checkbox\n- Don't move \\`id\\` to Checkbox\n\n\\`\\`\\`tsx\n<CheckboxOption id=\"x\" name=\"y\" title=\"Title\" content=\"Text\" checked={v} onChange={(c) => set(c)} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Checkbox name=\"y\" checked={v} onChange={(e) => set(e.target.checked)} />} />\n\\`\\`\\`\n\n---\n\n## RadioOption → ListItem.Radio\n\n- \\`name\\`, \\`value\\`, \\`checked\\`, \\`onChange\\` move to Radio\n- Don't move \\`id\\` to Radio\n\n\\`\\`\\`tsx\n<RadioOption id=\"x\" name=\"y\" value=\"v\" title=\"Title\" content=\"Text\" checked={v==='v'} onChange={set} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Radio name=\"y\" value=\"v\" checked={v==='v'} onChange={set} />} />\n\\`\\`\\`\n\n---\n\n## SwitchOption → ListItem.Switch\n\n- \\`onChange\\` → \\`onClick\\`, toggle manually\n- \\`aria-label\\` moves to Switch\n\n\\`\\`\\`tsx\n<SwitchOption title=\"Title\" content=\"Text\" checked={v} aria-label=\"Toggle\" onChange={set} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Switch checked={v} aria-label=\"Toggle\" onClick={() => set(!v)} />} />\n\\`\\`\\`\n\n---\n\n## NavigationOption → ListItem.Navigation\n\n- \\`onClick\\` or \\`href\\` move to Navigation\n\n\\`\\`\\`tsx\n<NavigationOption title=\"Title\" content=\"Text\" onClick={fn} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Navigation onClick={fn} />} />\n\\`\\`\\`\n\n---\n\n## Option → ListItem\n\n- Wrap \\`media\\` in \\`ListItem.AvatarView\\`\n\n\\`\\`\\`tsx\n<Option media={<Icon />} title=\"Title\" />\n→\n<ListItem title=\"Title\" media={<ListItem.AvatarView><Icon /></ListItem.AvatarView>} />\n\\`\\`\\`\n\n---\n\n## Summary → ListItem\n\n**Basic:**\n\n- \\`icon\\` → wrap in \\`ListItem.AvatarView\\` with \\`size={32}\\` as \\`media\\`\n- Remove \\`size\\` from child \\`<Icon />\\`\n\n**Status:**\n\n- \\`Status.DONE\\` → \\`badge={{ status: 'positive' }}\\`\n- \\`Status.PENDING\\` → \\`badge={{ status: 'pending' }}\\`\n- \\`Status.NOT_DONE\\` → no badge\n\n**Action:**\n\n- \\`action.text\\` → \\`action.label\\` in \\`ListItem.AdditionalInfo\\` as \\`additionalInfo\\`\n\n**Info (requires state):**\n\n- \\`MODAL\\` → \\`ListItem.IconButton partiallyInteractive\\` + \\`<Modal>\\` in \\`control\\`\n- \\`POPOVER\\` → \\`<Popover>\\` wrapping \\`ListItem.IconButton partiallyInteractive\\` in \\`control\\`\n- Use \\`QuestionMarkCircle\\` icon (import from \\`@transferwise/icons\\`)\n\n\\`\\`\\`tsx\n// Basic\n<Summary title=\"T\" description=\"D\" icon={<Icon />} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} />\n\n// Status\n<Summary title=\"T\" description=\"D\" icon={<Icon />} status={Status.DONE} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32} badge={{status:'positive'}}><Icon /></ListItem.AvatarView>} />\n\n// Action\n<Summary title=\"T\" description=\"D\" icon={<Icon />} action={{text:'Go', href:'/go'}} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} additionalInfo={<ListItem.AdditionalInfo action={{label:'Go', href:'/go'}} />} />\n\n// Modal (add: const [open, setOpen] = useState(false))\n<Summary title=\"T\" description=\"D\" icon={<Icon />} info={{title:'Help', content:'Text', presentation:'MODAL', 'aria-label':'Info'}} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} control={<ListItem.IconButton partiallyInteractive aria-label=\"Info\" onClick={()=>setOpen(!open)}><QuestionMarkCircle /><Modal open={open} title=\"Help\" body=\"Text\" onClose={()=>setOpen(false)} /></ListItem.IconButton>} />\n\n// Popover\n<Summary title=\"T\" description=\"D\" icon={<Icon />} info={{title:'Help', content:'Text', presentation:'POPOVER', 'aria-label':'Info'}} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} control={<Popover title=\"Help\" content=\"Text\" onClose={()=>setOpen(false)}><ListItem.IconButton partiallyInteractive aria-label=\"Info\"><QuestionMarkCircle /></ListItem.IconButton></Popover>} />\n\\`\\`\\`\n\n---\n\n## DefinitionList → Multiple ListItem\n\n- Array → individual \\`ListItem\\`s\n- \\`value\\` → \\`subtitle\\`\n- \\`key\\` → React \\`key\\` prop\n- Action type: \"Edit\"/\"Update\"/\"View\" → \\`ListItem.Button priority=\"secondary-neutral\"\\`, \"Change\"/\"Password\" → \\`ListItem.Navigation\\`, \"Copy\" → \\`ListItem.IconButton\\`\n\n\\`\\`\\`tsx\n<DefinitionList definitions={[\n {title:'T1', value:'V1', key:'k1'},\n {title:'T2', value:'V2', key:'k2', action:{label:'Edit', onClick:fn}}\n]} />\n→\n\n <ListItem key=\"k1\" title=\"T1\" subtitle=\"V1\" />\n <ListItem key=\"k2\" title=\"T2\" subtitle=\"V2\" control={<ListItem.Button priority=\"secondary-neutral\" onClick={fn}>Edit</ListItem.Button>} />\n\n\\`\\`\\`\n`;\n\nexport const SYSTEM_PROMPT = `You are a code migration assistant that helps migrate TypeScript/JSX code from deprecated Wise Design System (WDS) components to the new ListItem component and ListItem subcomponents from '@transferwise/components'.\n\nRules:\n1. Only ever modify files via the Edit tool - do not use the Write tool\n2. When identifying what code to migrate within a file, explain how you identified it first.\n2. Migrate components per provided migration rules\n3. Maintain TypeScript type safety and update types to match new API\n4. Map props: handle renamed, deprecated, new required, and changed types\n5. Update imports to new WDS components and types\n6. Preserve code style, formatting, and calculated logic\n7. Handle conditional rendering, spread props, and complex expressions\n8. Note: New components may lack feature parity with legacy versions\n9. Only modify code requiring changes per migration rules, and any impacted surrounding code for context.\n10. Final result response should just be whether the migration was successful overall, or if any errors were encountered\n - Do not summarise or explain the changes made\n11. Explain your reasoning and justification before making changes, as you edit each file.\n - Keep it concise and succinct, as only bullet points\n12. After modifying the file, do not summarise the changes made.\n13. If you do not have permission to edit a file, still attempt to edit it and then move onto the next file.\n\nYou'll receive:\n- File paths to migrate in individual queries\n- Deprecated component names at the end of this prompt\n- Migration context and rules for each deprecated component\n\nDeprecated components: ${DEPRECATED_COMPONENT_NAMES.join(', ')}.\n\n${MIGRATION_RULES}`;\n","import { createPatch } from 'diff';\n\n/** Split the path to get the relative path after the directory, and wrap with ANSI color codes */\nexport function formatPathOutput(directory: string, path?: string, asDim?: boolean): string {\n const relativePath = path ? (path.split(directory.replace('.', ''))[1] ?? path) : directory;\n return asDim ? `\\x1b[2m${relativePath}\\x1b[0m` : `\\x1b[32m${relativePath}\\x1b[0m`;\n}\n\n/** Generates a formatted string representing the total elapsed time since the given start time */\nexport function generateElapsedTime(startTime: number): string {\n const endTime = Date.now();\n const elapsedTime = Math.floor((endTime - startTime) / 1000);\n const hours = Math.floor(elapsedTime / 3600);\n const minutes = Math.floor((elapsedTime % 3600) / 60);\n const seconds = elapsedTime % 60;\n\n return `${hours ? `${hours}h ` : ''}${minutes ? `${minutes}m ` : ''}${seconds ? `${seconds}s` : ''}`;\n}\n\n// Formats Claude response with ANSI codes (bold for **, green for `), indenting all lines except the first. Also wraps entire content in dim color\nexport function formatClaudeResponseContent(content: string): string {\n const formatted = content\n .replace(/\\*\\*(.+?)\\*\\*/gu, '\\x1b[1m$1\\x1b[0m\\x1b[2m')\n .replace(/`(.+?)`/gu, '\\x1b[32m$1\\x1b[0m\\x1b[2m')\n .split('\\n')\n .map((line, index) => (index === 0 ? line : ` ${line}`))\n .join('\\n');\n\n return `\\x1b[2m${formatted}\\x1b[0m`;\n}\n\n// Generates a unified diff between the original and modified strings, with ANSI color codes for additions and deletions and line numbers\nexport function generateDiff(original: string, modified: string): string {\n const diffResult = createPatch('', original, modified, '', '').trim();\n\n // Parse and colorize the diff output\n const lines = diffResult\n .split('\\n')\n .slice(4) // Skip the header lines\n .filter((line) => !line.startsWith('\\\')); // Remove \"No newline\" messages\n\n // Track current line numbers from hunk headers\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n const colouredDiff = lines\n .map((line: string) => {\n const trimmedLine = line.trimEnd();\n\n // Parse hunk header to get starting line numbers - format: @@ -oldStart,oldCount +newStart,newCount @@\n if (trimmedLine.startsWith('@@')) {\n const match = /@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/u.exec(trimmedLine);\n if (match) {\n oldLineNumber = Number.parseInt(match[1], 10);\n newLineNumber = Number.parseInt(match[2], 10);\n }\n return `\\x1b[36m${trimmedLine}\\x1b[0m`; // Cyan for hunk headers\n }\n\n let linePrefix = '';\n // Green styling for additions\n if (trimmedLine.startsWith('+')) {\n linePrefix = `${newLineNumber.toString().padStart(4, ' ')} `;\n newLineNumber += 1;\n return `\\x1b[32m${linePrefix}${trimmedLine}\\x1b[0m`;\n }\n\n // Red styling for deletions\n if (trimmedLine.startsWith('-')) {\n linePrefix = `${oldLineNumber.toString().padStart(4, ' ')} `;\n oldLineNumber += 1;\n return `\\x1b[31m${linePrefix}${trimmedLine}\\x1b[0m`;\n }\n\n // Handle unchanged lines\n linePrefix = `${oldLineNumber.toString().padStart(4, ' ')} `;\n oldLineNumber += 1;\n newLineNumber += 1;\n return `${linePrefix}${trimmedLine}`;\n })\n .join('\\n');\n\n return colouredDiff;\n}\n","import https from 'node:https';\n\nimport { type Options, query } from '@anthropic-ai/claude-agent-sdk';\nimport { execSync } from 'child_process';\nimport { readFileSync } from 'fs';\nimport { resolve } from 'path';\nimport Spinnies from 'spinnies';\n\nimport { CONSOLE_ICONS } from '../../constants';\nimport { logStaticMessage } from '../../helpers/spinnerLogs';\nimport { SYSTEM_PROMPT } from './constants';\nimport { formatClaudeResponseContent, formatPathOutput, generateElapsedTime } from './helpers';\nimport type { ClaudeSettings } from './types';\n\nconst CLAUDE_SETTINGS_FILE = '.claude/settings.json';\n\nasync function checkVPN(spinnies: Spinnies, baseUrl?: string): Promise<boolean> {\n if (baseUrl) {\n spinnies.add('vpnCheck', { text: 'Checking VPN connection...' });\n const checkOnce = async (): Promise<boolean> =>\n new Promise<boolean>((resolveCheck) => {\n const url = new URL('/health', baseUrl);\n const req = https.get(url, { timeout: 2000, rejectUnauthorized: false }, (res) => {\n const ok = !!(res.statusCode && res.statusCode >= 200 && res.statusCode < 400);\n res.resume();\n resolveCheck(ok);\n });\n req.on('timeout', () => {\n req.destroy(new Error('timeout'));\n });\n req.on('error', () => resolveCheck(false));\n });\n\n while (true) {\n const ok = await checkOnce();\n if (ok) {\n spinnies.succeed('vpnCheck', { text: 'Connected to VPN' });\n break;\n }\n\n // Countdown from 3s, continuously resetting\n for (let countdown = 5; countdown > 0; countdown -= 1) {\n spinnies.update('vpnCheck', {\n text: `Please connect to VPN... retrying in \\x1b[32m${countdown}\\x1b[0ms`,\n });\n await new Promise<void>((response) => {\n setTimeout(response, 1000);\n });\n // Reset countdown after reaching 0\n if (countdown === 1) {\n countdown = 5 + 1; // +1 because loop will decrement\n }\n }\n }\n }\n return true;\n}\n\nexport function getQueryOptions(sessionId?: string): Options {\n // Read settings from ~/.claude/settings.json to get headers and apiKeyHelper\n const claudeSettingsPath = resolve(process.env.HOME || '', CLAUDE_SETTINGS_FILE);\n const settings = JSON.parse(readFileSync(claudeSettingsPath, 'utf-8')) as ClaudeSettings;\n\n // Get API key by executing the apiKeyHelper script, for authenticating with Okta via LLM Gateway\n let apiKey;\n try {\n apiKey = execSync(`bash ${settings.apiKeyHelper}`, {\n encoding: 'utf-8',\n }).trim();\n } catch {}\n\n if (!apiKey) {\n throw new Error(\n 'Failed to retrieve Anthropic API key. Please check your Claude Code x LLM Gateway configuration - https://transferwise.atlassian.net/wiki/x/_YUe3Q',\n );\n }\n\n const { ANTHROPIC_CUSTOM_HEADERS, ...restEnvVars } = settings?.env ?? {};\n\n const envVars = {\n ANTHROPIC_AUTH_TOKEN: apiKey,\n ANTHROPIC_CUSTOM_HEADERS,\n ...restEnvVars,\n PATH: process.env.PATH, // Specifying PATH, as Claude Agent SDK seems to struggle consuming the actual environment PATH\n };\n\n return {\n resume: sessionId,\n env: envVars,\n permissionMode: 'acceptEdits',\n systemPrompt: {\n type: 'preset',\n preset: 'claude_code',\n append: SYSTEM_PROMPT,\n },\n allowedTools: ['Grep', 'Read'],\n settingSources: ['local', 'project', 'user'],\n };\n}\n\n/** Initiate a new Claude session/conversation and return reusable options */\nexport async function initiateClaudeSessionOptions(spinnies: Spinnies): Promise<Options> {\n const options = getQueryOptions(undefined);\n await checkVPN(spinnies, options.env?.ANTHROPIC_BASE_URL);\n\n spinnies.add('claudeSession', {\n text: 'Starting and verifying Claude instance - your browser may open for Okta authentication if required.',\n });\n\n const result = query({\n options,\n prompt: `You'll be given file paths in additional individual queries to search in for files using deprecated Wise Design System (WDS) components. Migrate the code per the provided migration rules.`,\n });\n\n for await (const message of result) {\n switch (message.type) {\n case 'system':\n if (message.subtype === 'init' && !options.resume) {\n spinnies.succeed('claudeSession', { text: 'Successfully initialised Claude instance' });\n spinnies.add('placeholder', { text: ' ' });\n\n // Set the session ID to resume the conversation in future queries\n options.resume = message.session_id;\n }\n break;\n default:\n if (message.type === 'result' && message.subtype !== 'success') {\n spinnies.fail('claudeSession', {\n text: `Claude encountered an error when initialising: ${message.errors.join('\\n')}`,\n });\n spinnies.stopAll('fail');\n }\n }\n }\n\n return options;\n}\n\n// Queries Claude with the given path and handles logging of tool uses and results\nexport async function queryClaude(\n directory: string,\n filePath: string,\n options: Options,\n spinnies: Spinnies,\n isDebug = false,\n) {\n const startTime = Date.now();\n const debugSpinnies = new Spinnies();\n const result = query({\n options,\n prompt: filePath,\n });\n\n for await (const message of result) {\n switch (message.type) {\n case 'assistant':\n for (const msg of message.message.content) {\n switch (msg.type) {\n // Handles logging of tool uses to determine key stages of the migration\n case 'tool_use':\n if (msg.name === 'Read') {\n spinnies.update(`file-${filePath}`, {\n text: `\\x1b[2m${formatPathOutput(directory, filePath)} - Reading...\\x1b[0m`,\n });\n } else if (msg.name === 'Edit') {\n spinnies.update(`file-${filePath}`, {\n text: `\\x1b[2m${formatPathOutput(directory, filePath)} - Migrating...\\x1b[0m`,\n });\n }\n break;\n case 'text':\n // Log Claude's text responses in debug mode\n if (isDebug) {\n logStaticMessage(\n debugSpinnies,\n `${CONSOLE_ICONS.claude} ${formatClaudeResponseContent(msg.text)}`,\n );\n }\n break;\n default:\n }\n }\n break;\n case 'result':\n if (message.subtype === 'success') {\n spinnies.succeed(`file-${filePath}`, {\n text: `\\x1b[0m${formatPathOutput(directory, filePath, true)}\\x1b[0m\\x1b[2m - Migrated in ${generateElapsedTime(startTime)}\\x1b[0m`,\n });\n } else {\n // Silence non-error errors (false positives)\n logStaticMessage(debugSpinnies, `${CONSOLE_ICONS.error} Claude encountered an error:`);\n logStaticMessage(debugSpinnies, JSON.stringify(message));\n spinnies.stopAll('fail');\n debugSpinnies.stopAll('fail');\n }\n break;\n default:\n }\n }\n}\n","import { execSync } from 'child_process';\nimport { readFileSync } from 'fs';\nimport Spinnies from 'spinnies';\n\nimport type { CodemodOptions } from '../../controller/types';\nimport { logStaticMessage } from '../../helpers/spinnerLogs';\nimport { initiateClaudeSessionOptions, queryClaude } from './claude';\nimport { CONCURRENCY_LIMIT, GREP_PATTERN } from './constants';\nimport { formatPathOutput, generateDiff, generateElapsedTime } from './helpers';\n\nconst transformer = async (\n targetPaths: string[],\n codemodOptions: CodemodOptions,\n isDebug = false,\n) => {\n const startTime = Date.now();\n const spinnies = new Spinnies();\n const queryOptions = await initiateClaudeSessionOptions(spinnies);\n\n spinnies.remove('placeholder');\n spinnies.add('analysing', {\n text: 'Analysing targetted paths - this may take a while...',\n });\n\n // Shared array to track all executing files across all directories\n const globalExecutingFiles: Promise<void>[] = [];\n\n // Helper to process a single file with shared concurrency limit\n const processFile = async (directory: string, filePath: string) => {\n spinnies.remove('placeholder');\n spinnies.add(`file-${filePath}`, {\n indent: 4,\n text: `\\x1b[2m${formatPathOutput(directory, filePath)} - Parsing...\\x1b[0m`,\n });\n\n // Store original file content for diffing later\n const originalFileContent = readFileSync(filePath, 'utf-8');\n spinnies.update(`file-${filePath}`, {\n indent: 4,\n text: `\\x1b[2m${formatPathOutput(directory, filePath)} - Processing...\\x1b[0m`,\n });\n\n await queryClaude(directory, filePath, queryOptions, spinnies, isDebug);\n\n // Create diff from originalFileContent to newFileContent\n if (codemodOptions.isPrint) {\n // Grab new file content after modification so we can create diff\n const newFileContent = readFileSync(filePath, 'utf-8');\n\n logStaticMessage(spinnies, `Diff for ${formatPathOutput(directory, filePath, true)}:`);\n logStaticMessage(spinnies, generateDiff(originalFileContent, newFileContent));\n }\n };\n\n // Process directory function that returns when all files are queued\n const processDirectory = async (directory: string): Promise<{ filesQueued: Promise<void>[] }> => {\n spinnies.add(`directory-${directory}`, {\n indent: 2,\n text: `${formatPathOutput(directory)} - Processing...`,\n });\n\n // First, find all .tsx files in the directory\n const allTsxFiles = execSync(`find \"${directory}\" -name \"*.tsx\" -type f`, {\n encoding: 'utf-8',\n })\n .trim()\n .split('\\n')\n .filter(Boolean);\n\n // Array to track promises for files queued in this directory\n const filesQueued: Promise<void>[] = [];\n\n // Filter files that match the pattern by reading and testing each file\n const matchingFilePaths = allTsxFiles.filter((filePath) => {\n const content = readFileSync(filePath, 'utf-8');\n return GREP_PATTERN.test(content);\n });\n\n spinnies.update(`directory-${directory}`, {\n text: `${formatPathOutput(directory)} - Found \\x1b[32m${matchingFilePaths.length}\\x1b[0m \\x1b[2m*.tsx\\x1b[0m file(s) needing migration`,\n });\n\n // Using object to avoid closure issues in loop, as they're passed by reference\n const completedFilesInDirectory = { count: 0 };\n\n // Process files with a shared concurrency limit between directories\n for (let i = 0; i < matchingFilePaths.length; i += 1) {\n const promise = processFile(directory, matchingFilePaths[i]).then(() => {\n // Remove from global executing files when done\n void globalExecutingFiles.splice(globalExecutingFiles.indexOf(promise), 1);\n completedFilesInDirectory.count += 1;\n spinnies.update(`directory-${directory}`, {\n text: `${formatPathOutput(directory)} - Migrated \\x1b[32m${completedFilesInDirectory.count}\\x1b[0m/\\x1b[32m${matchingFilePaths.length}\\x1b[0m \\x1b[2m*.tsx\\x1b[0m files`,\n });\n });\n\n globalExecutingFiles.push(promise);\n filesQueued.push(promise);\n\n const moreFilesToProcess = i < matchingFilePaths.length - 1;\n\n // If we're at concurrency limit...\n if (globalExecutingFiles.length >= CONCURRENCY_LIMIT) {\n // With more files to process, wait for any to finish\n if (moreFilesToProcess) {\n spinnies.add('placeholder', {\n // Wrap in italics\n text: '\\x1b[2mThere are still additional files to be queued, waiting for other files to finish first...\\x1b[0m',\n indent: 4,\n });\n await Promise.race(globalExecutingFiles);\n } else {\n // With no more files to add, break and start next directory\n break;\n }\n }\n }\n\n // Promise handler for this directory\n void Promise.all(filesQueued).then(() => {\n if (matchingFilePaths.length === 0) {\n spinnies.succeed(`directory-${directory}`, {\n text: `${formatPathOutput(directory)}\\x1b[2m - No files need migration\\x1b[0m`,\n });\n } else {\n spinnies.succeed(`directory-${directory}`, {\n indent: 2,\n text: `${formatPathOutput(directory)} - Migrated \\x1b[32m${matchingFilePaths.length}\\x1b[0m file(s) successfully!`,\n });\n }\n });\n\n return { filesQueued };\n };\n\n // Process directories, starting the next one when the current has fewer than 10 files left\n for (const directory of targetPaths) {\n await processDirectory(directory);\n }\n\n // Wait for all files across all directories to complete migration\n await Promise.all(globalExecutingFiles);\n\n spinnies.update('analysing', {\n text: 'Successfully analysed all targetted paths',\n });\n spinnies.stopAll('succeed'); // Just in case any spinnies are left running\n spinnies.add('done', {\n text: `Finished migrating - elapsed time: \\x1b[1m${generateElapsedTime(startTime)}\\x1b[0m`,\n status: 'succeed',\n });\n};\n\nexport default transformer;\n"],"mappings":";;;;;;;;;;;;AAQA,SAAgB,aAAa,EAAE,sBAAU,WAAW,WAA4C;AAC9F,YAAS,IAAI,WAAW,QAAQ;;AAGlC,SAAgB,iBAAiB,YAAoB,SAAuB;AAG1E,cAAa;EAAE;EAAU,WADZ,kBAAkB,KAAK,KAAK,CAAC,GAAG,QAAQ,MAAM,GAAG,GAAG,CAAC,QAAQ,SAAS,IAAI,CAAC,GAAG,KAAK,MAAM,KAAK,QAAQ,GAAG,IAAM;EAClF,SAAS;GAAE,MAAM;GAAS,QAAQ;GAAiB;EAAE,CAAC;;;;;ACflG,MAAa,oBAAoB;AACjC,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACD;A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OAAM,QAAQ,IAAI,qBAAqB;AAEvC,YAAS,OAAO,aAAa,EAC3B,MAAM,6CACP,CAAC;AACF,YAAS,QAAQ,UAAU;AAC3B,YAAS,IAAI,QAAQ;EACnB,MAAM,6CAA6C,oBAAoB,UAAU,CAAC;EAClF,QAAQ;EACT,CAAC;;AAGJ,0BAAe"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"transformer-DoAMzZmy.js","names":["https","spinnies","Spinnies","CONSOLE_ICONS","spinnies","Spinnies"],"sources":["../src/helpers/spinnerLogs.ts","../src/transforms/list-item/constants.ts","../src/transforms/list-item/helpers.ts","../src/transforms/list-item/claude.ts","../src/transforms/list-item/transformer.ts"],"sourcesContent":["import type Spinnies from 'spinnies';\n\ninterface LogConsoleSpinnerSettings {\n spinnies: Spinnies;\n spinnerId: string;\n options: Partial<Spinnies.SpinnerOptions>;\n}\n\nexport function logToConsole({ spinnies, spinnerId, options }: LogConsoleSpinnerSettings): void {\n spinnies.add(spinnerId, options);\n}\n\nexport function logStaticMessage(spinnies: Spinnies, message: string): void {\n // Create a unique spinner ID for the static message using timestamp, first part of the message and a random number\n const uuid = `static-message-${Date.now()}-${message.slice(0, 10).replace(/\\s+/gu, '-')}-${Math.floor(Math.random() * 10000)}`;\n logToConsole({ spinnies, spinnerId: uuid, options: { text: message, status: 'non-spinnable' } });\n}\n","export const DEPRECATED_COMPONENT_NAMES = [\n 'ActionOption',\n 'NavigationOption',\n 'NavigationOptionsList',\n 'Summary',\n 'SwitchOption',\n 'CheckboxOption',\n 'RadioOption',\n];\n\nconst MIGRATION_RULES = `Migration rules:\n# Legacy Component → ListItem Migration Guide\n\n## Universal Rules\n\n1. \\`title\\` → \\`title\\` (direct)\n2. \\`content\\` or \\`description\\` → \\`subtitle\\`\n3. \\`disabled\\` stays on \\`ListItem\\` (not controls)\n4. Keep HTML attributes (\\`id\\`, \\`name\\`, \\`aria-label\\`), remove: \\`as\\`, \\`complex\\`, \\`showMediaAtAllSizes\\`, \\`showMediaCircle\\`, \\`isContainerAligned\\`\n5. In strings, don't convert \\`\\`to\\`'\\`or\\`\"\\`. Preserve what is there.\n\n---\n\n## ActionOption → ListItem.Button\n\n- \\`action\\` → Button children\n- \\`onClick\\` → Button \\`onClick\\`\n- Priority: default/\\`\"primary\"\\` → \\`\"primary\"\\`, \\`\"secondary\"\\` → \\`\"secondary-neutral\"\\`, \\`\"secondary-send\"\\` → \\`\"secondary\"\\`, \\`\"tertiary\"\\` → \\`\"tertiary\"\\`\n\n\\`\\`\\`tsx\n<ActionOption title=\"Title\" content=\"Text\" action=\"Click\" priority=\"secondary\" onClick={fn} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Button priority=\"secondary-neutral\" onClick={fn}>Click</ListItem.Button>} />\n\\`\\`\\`\n\n---\n\n## CheckboxOption → ListItem.Checkbox\n\n- \\`onChange\\`: \\`(checked: boolean)\\` → \\`(event: ChangeEvent)\\` use \\`event.target.checked\\`\n- \\`name\\` move to Checkbox\n- Don't move \\`id\\` to Checkbox\n\n\\`\\`\\`tsx\n<CheckboxOption id=\"x\" name=\"y\" title=\"Title\" content=\"Text\" checked={v} onChange={(c) => set(c)} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Checkbox name=\"y\" checked={v} onChange={(e) => set(e.target.checked)} />} />\n\\`\\`\\`\n\n---\n\n## RadioOption → ListItem.Radio\n\n- \\`name\\`, \\`value\\`, \\`checked\\`, \\`onChange\\` move to Radio\n- Don't move \\`id\\` to Radio\n\n\\`\\`\\`tsx\n<RadioOption id=\"x\" name=\"y\" value=\"v\" title=\"Title\" content=\"Text\" checked={v==='v'} onChange={set} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Radio name=\"y\" value=\"v\" checked={v==='v'} onChange={set} />} />\n\\`\\`\\`\n\n---\n\n## SwitchOption → ListItem.Switch\n\n- \\`onChange\\` → \\`onClick\\`, toggle manually\n- \\`aria-label\\` moves to Switch\n\n\\`\\`\\`tsx\n<SwitchOption title=\"Title\" content=\"Text\" checked={v} aria-label=\"Toggle\" onChange={set} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Switch checked={v} aria-label=\"Toggle\" onClick={() => set(!v)} />} />\n\\`\\`\\`\n\n---\n\n## NavigationOption → ListItem.Navigation\n\n- \\`onClick\\` or \\`href\\` move to Navigation\n\n\\`\\`\\`tsx\n<NavigationOption title=\"Title\" content=\"Text\" onClick={fn} />\n→\n<ListItem title=\"Title\" subtitle=\"Text\" control={<ListItem.Navigation onClick={fn} />} />\n\\`\\`\\`\n\n---\n\n## Option → ListItem\n\n- Wrap \\`media\\` in \\`ListItem.AvatarView\\`\n\n\\`\\`\\`tsx\n<Option media={<Icon />} title=\"Title\" />\n→\n<ListItem title=\"Title\" media={<ListItem.AvatarView><Icon /></ListItem.AvatarView>} />\n\\`\\`\\`\n\n---\n\n## Summary → ListItem\n\n**Basic:**\n\n- \\`icon\\` → wrap in \\`ListItem.AvatarView\\` with \\`size={32}\\` as \\`media\\`\n- Remove \\`size\\` from child \\`<Icon />\\`\n\n**Status:**\n\n- \\`Status.DONE\\` → \\`badge={{ status: 'positive' }}\\`\n- \\`Status.PENDING\\` → \\`badge={{ status: 'pending' }}\\`\n- \\`Status.NOT_DONE\\` → no badge\n\n**Action:**\n\n- \\`action.text\\` → \\`action.label\\` in \\`ListItem.AdditionalInfo\\` as \\`additionalInfo\\`\n\n**Info (requires state):**\n\n- \\`MODAL\\` → \\`ListItem.IconButton partiallyInteractive\\` + \\`<Modal>\\` in \\`control\\`\n- \\`POPOVER\\` → \\`<Popover>\\` wrapping \\`ListItem.IconButton partiallyInteractive\\` in \\`control\\`\n- Use \\`QuestionMarkCircle\\` icon (import from \\`@transferwise/icons\\`)\n\n\\`\\`\\`tsx\n// Basic\n<Summary title=\"T\" description=\"D\" icon={<Icon />} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} />\n\n// Status\n<Summary title=\"T\" description=\"D\" icon={<Icon />} status={Status.DONE} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32} badge={{status:'positive'}}><Icon /></ListItem.AvatarView>} />\n\n// Action\n<Summary title=\"T\" description=\"D\" icon={<Icon />} action={{text:'Go', href:'/go'}} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} additionalInfo={<ListItem.AdditionalInfo action={{label:'Go', href:'/go'}} />} />\n\n// Modal (add: const [open, setOpen] = useState(false))\n<Summary title=\"T\" description=\"D\" icon={<Icon />} info={{title:'Help', content:'Text', presentation:'MODAL', 'aria-label':'Info'}} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} control={<ListItem.IconButton partiallyInteractive aria-label=\"Info\" onClick={()=>setOpen(!open)}><QuestionMarkCircle /><Modal open={open} title=\"Help\" body=\"Text\" onClose={()=>setOpen(false)} /></ListItem.IconButton>} />\n\n// Popover\n<Summary title=\"T\" description=\"D\" icon={<Icon />} info={{title:'Help', content:'Text', presentation:'POPOVER', 'aria-label':'Info'}} />\n→\n<ListItem title=\"T\" subtitle=\"D\" media={<ListItem.AvatarView size={32}><Icon /></ListItem.AvatarView>} control={<Popover title=\"Help\" content=\"Text\" onClose={()=>setOpen(false)}><ListItem.IconButton partiallyInteractive aria-label=\"Info\"><QuestionMarkCircle /></ListItem.IconButton></Popover>} />\n\\`\\`\\`\n\n---\n\n## DefinitionList → Multiple ListItem\n\n- Array → individual \\`ListItem\\`s\n- \\`value\\` → \\`subtitle\\`\n- \\`key\\` → React \\`key\\` prop\n- Action type: \"Edit\"/\"Update\"/\"View\" → \\`ListItem.Button priority=\"secondary-neutral\"\\`, \"Change\"/\"Password\" → \\`ListItem.Navigation\\`, \"Copy\" → \\`ListItem.IconButton\\`\n\n\\`\\`\\`tsx\n<DefinitionList definitions={[\n {title:'T1', value:'V1', key:'k1'},\n {title:'T2', value:'V2', key:'k2', action:{label:'Edit', onClick:fn}}\n]} />\n→\n\n <ListItem key=\"k1\" title=\"T1\" subtitle=\"V1\" />\n <ListItem key=\"k2\" title=\"T2\" subtitle=\"V2\" control={<ListItem.Button priority=\"secondary-neutral\" onClick={fn}>Edit</ListItem.Button>} />\n\n\\`\\`\\`\n`;\n\nexport const SYSTEM_PROMPT = `You are a code migration assistant that helps migrate TypeScript/JSX code from deprecated Wise Design System (WDS) components to the new ListItem component and ListItem subcomponents from '@transferwise/components'.\n\nRules:\n1. Only ever modify files via the Edit tool - do not use the Write tool\n2. When identifying what code to migrate within a file, explain how you identified it first.\n2. Migrate components per provided migration rules\n3. Maintain TypeScript type safety and update types to match new API\n4. Map props: handle renamed, deprecated, new required, and changed types\n5. Update imports to new WDS components and types\n6. Preserve code style, formatting, and calculated logic\n7. Handle conditional rendering, spread props, and complex expressions\n8. Note: New components may lack feature parity with legacy versions\n9. Only modify code requiring changes per migration rules, and any impacted surrounding code for context.\n10. Final result response should just be whether the migration was successful overall, or if any errors were encountered\n - Do not summarise or explain the changes made\n11. Explain your reasoning and justification before making changes, as you edit each file.\n - Keep it concise and succinct, as only bullet points\n12. After modifying the file, do not summarise the changes made.\n13. If you do not have permission to edit a file, still attempt to edit it and then move onto the next file.\n\nYou'll receive:\n- File paths to migrate in individual queries\n- Deprecated component names at the end of this prompt\n- Migration context and rules for each deprecated component\n\nDeprecated components: ${DEPRECATED_COMPONENT_NAMES.join(', ')}.\n\n${MIGRATION_RULES}`;\n","import { createPatch } from 'diff';\n\n/** Split the path to get the relative path after the directory, and wrap with ANSI color codes */\nexport function formatPathOutput(directory: string, path?: string, asDim?: boolean): string {\n const relativePath = path ? (path.split(directory.replace('.', ''))[1] ?? path) : directory;\n return asDim ? `\\x1b[2m${relativePath}\\x1b[0m` : `\\x1b[32m${relativePath}\\x1b[0m`;\n}\n\n/** Generates a formatted string representing the total elapsed time since the given start time */\nexport function generateElapsedTime(startTime: number): string {\n const endTime = Date.now();\n const elapsedTime = Math.floor((endTime - startTime) / 1000);\n const hours = Math.floor(elapsedTime / 3600);\n const minutes = Math.floor((elapsedTime % 3600) / 60);\n const seconds = elapsedTime % 60;\n\n return `${hours ? `${hours}h ` : ''}${minutes ? `${minutes}m ` : ''}${seconds ? `${seconds}s` : ''}`;\n}\n\n// Formats Claude response with ANSI codes (bold for **, green for `), indenting all lines except the first. Also wraps entire content in dim color\nexport function formatClaudeResponseContent(content: string): string {\n const formatted = content\n .replace(/\\*\\*(.+?)\\*\\*/gu, '\\x1b[1m$1\\x1b[0m\\x1b[2m')\n .replace(/`(.+?)`/gu, '\\x1b[32m$1\\x1b[0m\\x1b[2m')\n .split('\\n')\n .map((line, index) => (index === 0 ? line : ` ${line}`))\n .join('\\n');\n\n return `\\x1b[2m${formatted}\\x1b[0m`;\n}\n\n// Generates a unified diff between the original and modified strings, with ANSI color codes for additions and deletions and line numbers\nexport function generateDiff(original: string, modified: string): string {\n const diffResult = createPatch('', original, modified, '', '').trim();\n\n // Parse and colorize the diff output\n const lines = diffResult\n .split('\\n')\n .slice(4) // Skip the header lines\n .filter((line) => !line.startsWith('\\\')); // Remove \"No newline\" messages\n\n // Track current line numbers from hunk headers\n let oldLineNumber = 0;\n let newLineNumber = 0;\n\n const colouredDiff = lines\n .map((line: string) => {\n const trimmedLine = line.trimEnd();\n\n // Parse hunk header to get starting line numbers - format: @@ -oldStart,oldCount +newStart,newCount @@\n if (trimmedLine.startsWith('@@')) {\n const match = /@@ -(\\d+)(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@/u.exec(trimmedLine);\n if (match) {\n oldLineNumber = Number.parseInt(match[1], 10);\n newLineNumber = Number.parseInt(match[2], 10);\n }\n return `\\x1b[36m${trimmedLine}\\x1b[0m`; // Cyan for hunk headers\n }\n\n let linePrefix = '';\n // Green styling for additions\n if (trimmedLine.startsWith('+')) {\n linePrefix = `${newLineNumber.toString().padStart(4, ' ')} `;\n newLineNumber += 1;\n return `\\x1b[32m${linePrefix}${trimmedLine}\\x1b[0m`;\n }\n\n // Red styling for deletions\n if (trimmedLine.startsWith('-')) {\n linePrefix = `${oldLineNumber.toString().padStart(4, ' ')} `;\n oldLineNumber += 1;\n return `\\x1b[31m${linePrefix}${trimmedLine}\\x1b[0m`;\n }\n\n // Handle unchanged lines\n linePrefix = `${oldLineNumber.toString().padStart(4, ' ')} `;\n oldLineNumber += 1;\n newLineNumber += 1;\n return `${linePrefix}${trimmedLine}`;\n })\n .join('\\n');\n\n return colouredDiff;\n}\n","import https from 'node:https';\n\nimport { type Options, query } from '@anthropic-ai/claude-agent-sdk';\nimport { execSync } from 'child_process';\nimport { readFileSync } from 'fs';\nimport { resolve } from 'path';\nimport Spinnies from 'spinnies';\n\nimport { CONSOLE_ICONS } from '../../constants';\nimport type { CodemodOptions } from '../../controller/types';\nimport { logStaticMessage } from '../../helpers/spinnerLogs';\nimport { SYSTEM_PROMPT } from './constants';\nimport { formatClaudeResponseContent, formatPathOutput, generateElapsedTime } from './helpers';\nimport type { ClaudeSettings } from './types';\n\nconst CLAUDE_SETTINGS_FILE = '.claude/settings.json';\n\nasync function checkVPN(spinnies: Spinnies, baseUrl?: string): Promise<boolean> {\n if (baseUrl) {\n spinnies.add('vpnCheck', { text: 'Checking VPN connection...' });\n const checkOnce = async (): Promise<boolean> =>\n new Promise<boolean>((resolveCheck) => {\n const url = new URL('/health', baseUrl);\n const req = https.get(url, { timeout: 2000, rejectUnauthorized: false }, (res) => {\n const ok = !!(res.statusCode && res.statusCode >= 200 && res.statusCode < 400);\n res.resume();\n resolveCheck(ok);\n });\n req.on('timeout', () => {\n req.destroy(new Error('timeout'));\n });\n req.on('error', () => resolveCheck(false));\n });\n\n while (true) {\n const ok = await checkOnce();\n if (ok) {\n spinnies.succeed('vpnCheck', { text: 'Connected to VPN' });\n break;\n }\n\n // TODO: Could update this to count down from 3s and fail after a certain number of attempts\n spinnies.update('vpnCheck', { text: 'Please connect to VPN... retrying in 3s' });\n await new Promise<void>((response) => {\n setTimeout(response, 3000);\n });\n }\n }\n return true;\n}\n\nexport function getQueryOptions(sessionId?: string): Options {\n // Read settings from ~/.claude/settings.json to get headers and apiKeyHelper\n const claudeSettingsPath = resolve(process.env.HOME || '', CLAUDE_SETTINGS_FILE);\n const settings = JSON.parse(readFileSync(claudeSettingsPath, 'utf-8')) as ClaudeSettings;\n\n // Get API key by executing the apiKeyHelper script, for authenticating with Okta via LLM Gateway\n let apiKey;\n try {\n apiKey = execSync(`bash ${settings.apiKeyHelper}`, {\n encoding: 'utf-8',\n }).trim();\n } catch {}\n\n if (!apiKey) {\n throw new Error(\n 'Failed to retrieve Anthropic API key. Please check your Claude Code x LLM Gateway configuration - https://transferwise.atlassian.net/wiki/x/_YUe3Q',\n );\n }\n\n const { ANTHROPIC_CUSTOM_HEADERS, ...restEnvVars } = settings?.env ?? {};\n\n const envVars = {\n ANTHROPIC_AUTH_TOKEN: apiKey,\n ANTHROPIC_CUSTOM_HEADERS,\n ...restEnvVars,\n PATH: process.env.PATH, // Specifying PATH, as Claude Agent SDK seems to struggle consuming the actual environment PATH\n };\n\n return {\n resume: sessionId,\n env: envVars,\n permissionMode: 'acceptEdits',\n systemPrompt: {\n type: 'preset',\n preset: 'claude_code',\n append: SYSTEM_PROMPT,\n },\n allowedTools: ['Grep', 'Read'],\n settingSources: ['local', 'project', 'user'],\n };\n}\n\n/** Initiate a new Claude session/conversation and return reusable options */\nexport async function initiateClaudeSessionOptions(spinnies: Spinnies): Promise<Options> {\n const options = getQueryOptions(undefined);\n await checkVPN(spinnies, options.env?.ANTHROPIC_BASE_URL);\n\n spinnies.add('claudeSession', {\n text: 'Starting and verifying Claude instance - your browser may open for Okta authentication if required.',\n });\n\n const result = query({\n options,\n prompt: `You'll be given file paths in additional individual queries to search in for files using deprecated Wise Design System (WDS) components. Migrate the code per the provided migration rules.`,\n });\n\n for await (const message of result) {\n switch (message.type) {\n case 'system':\n if (message.subtype === 'init' && !options.resume) {\n spinnies.succeed('claudeSession', { text: 'Successfully initialised Claude instance' });\n spinnies.add('placeholder', { text: ' ' });\n\n // Set the session ID to resume the conversation in future queries\n options.resume = message.session_id;\n }\n break;\n default:\n if (message.type === 'result' && message.subtype !== 'success') {\n spinnies.fail('claudeSession', {\n text: `Claude encountered an error when initialising: ${message.errors.join('\\n')}`,\n });\n spinnies.stopAll('fail');\n }\n }\n }\n\n return options;\n}\n\n// Queries Claude with the given path and handles logging of tool uses and results\nexport async function queryClaude(\n directory: string,\n filePath: string,\n options: Options,\n codemodOptions: CodemodOptions,\n spinnies: Spinnies,\n isDebug = false,\n) {\n const startTime = Date.now();\n const debugSpinnies = new Spinnies();\n const result = query({\n options,\n prompt: filePath,\n });\n\n for await (const message of result) {\n switch (message.type) {\n case 'assistant':\n for (const msg of message.message.content) {\n switch (msg.type) {\n // Handles logging of tool uses to determine key stages of the migration\n case 'tool_use':\n if (msg.name === 'Read') {\n spinnies.remove('placeholder');\n spinnies.update(`file-${filePath}`, {\n text: `${formatPathOutput(directory, filePath, true)} - Reading...`,\n });\n } else if (msg.name === 'Edit') {\n spinnies.update(`file-${filePath}`, {\n text: `${formatPathOutput(directory, filePath, true)} - Migrating...`,\n });\n }\n\n break;\n case 'text':\n if (isDebug) {\n logStaticMessage(\n debugSpinnies,\n `${CONSOLE_ICONS.claude} ${formatClaudeResponseContent(msg.text)}`,\n );\n }\n break;\n default:\n }\n }\n break;\n case 'result':\n if (message.subtype === 'success') {\n spinnies.succeed(`file-${filePath}`, {\n text: `${formatPathOutput(directory, filePath, true)} - Migrated in: ${generateElapsedTime(startTime)}`,\n });\n } else {\n // Silence non-error errors (false positives)\n logStaticMessage(debugSpinnies, `${CONSOLE_ICONS.error} Claude encountered an error:`);\n console.log(message);\n spinnies.stopAll('fail');\n debugSpinnies.stopAll('fail');\n }\n break;\n default:\n }\n }\n}\n","import { execSync } from 'child_process';\nimport { readFileSync } from 'fs';\nimport Spinnies from 'spinnies';\n\nimport type { CodemodOptions } from '../../controller/types';\nimport { logStaticMessage } from '../../helpers/spinnerLogs';\nimport { initiateClaudeSessionOptions, queryClaude } from './claude';\nimport { DEPRECATED_COMPONENT_NAMES } from './constants';\nimport { formatPathOutput, generateDiff, generateElapsedTime } from './helpers';\n\nconst transformer = async (\n targetPaths: string[],\n codemodOptions: CodemodOptions,\n isDebug = false,\n) => {\n const startTime = Date.now();\n const spinnies = new Spinnies();\n const queryOptions = await initiateClaudeSessionOptions(spinnies);\n\n spinnies.remove('placeholder');\n spinnies.add('analysing', {\n text: 'Analysing targetted paths - this may take a while...',\n });\n\n for (const directory of targetPaths) {\n spinnies.add(`directory-${directory}`, {\n indent: 2,\n text: `${formatPathOutput(directory)} - Processing directory`,\n });\n\n // First, find all .tsx files in the directory\n const allTsxFiles = execSync(`find \"${directory}\" -name \"*.tsx\" -type f`, {\n encoding: 'utf-8',\n })\n .trim()\n .split('\\n')\n .filter(Boolean);\n\n const grepPattern = new RegExp(\n `import\\\\s*\\\\{[\\\\s\\\\S]*?(${DEPRECATED_COMPONENT_NAMES.join('|')})[\\\\s\\\\S]*?\\\\}\\\\s*from\\\\s*['\"]@transferwise/components['\"]`,\n );\n\n // Filter files that match the pattern by reading and testing each file\n const matchingFilePaths = allTsxFiles.filter((filePath) => {\n try {\n const content = readFileSync(filePath, 'utf-8');\n return grepPattern.test(content);\n } catch {\n return false;\n }\n });\n\n spinnies.update(`directory-${directory}`, {\n text: `${formatPathOutput(directory)} - Found \\x1b[32m${matchingFilePaths.length}\\x1b[0m \\x1b[2m*.tsx\\x1b[0m file(s) needing migration`,\n });\n\n // Get file path and file content for each matching file, and query Claude for migration\n for (const filePath of matchingFilePaths) {\n spinnies.add(`file-${filePath}`, {\n indent: 4,\n text: `${formatPathOutput(directory, filePath, true)} - Parsing...`,\n });\n\n const originalFileContent = readFileSync(filePath, 'utf-8');\n\n spinnies.update(`file-${filePath}`, {\n indent: 4,\n text: `${formatPathOutput(directory, filePath, true)} - Processing...`,\n });\n\n await queryClaude(directory, filePath, queryOptions, codemodOptions, spinnies, isDebug);\n\n const newFileContent = readFileSync(filePath, 'utf-8');\n\n // Create diff from originalFileContent to newFileContent\n if (codemodOptions.isPrint) {\n logStaticMessage(spinnies, `Diff for ${formatPathOutput(directory, filePath, true)}:`);\n logStaticMessage(spinnies, generateDiff(originalFileContent, newFileContent));\n }\n\n spinnies.remove('placeholder');\n }\n\n if (matchingFilePaths.length === 0) {\n spinnies.succeed(`directory-${directory}`, {\n text: `${formatPathOutput(directory)} - No files need migration`,\n });\n } else {\n spinnies.succeed(`directory-${directory}`, {\n indent: 2,\n text: `${formatPathOutput(directory)} - Migrated \\x1b[32m${matchingFilePaths.length}\\x1b[0m file(s) successfully`,\n });\n }\n }\n\n spinnies.succeed('analysing', {\n text: 'Successfully analysed all targetted paths',\n });\n spinnies.stopAll('succeed');\n spinnies.add('done', {\n text: `Finished migrating - elapsed time: \\x1b[1m${generateElapsedTime(startTime)}\\x1b[0m`,\n status: 'succeed',\n });\n};\n\nexport default transformer;\n"],"mappings":";;;;;;;;;;;;AAQA,SAAgB,aAAa,EAAE,sBAAU,WAAW,WAA4C;AAC9F,YAAS,IAAI,WAAW,QAAQ;;AAGlC,SAAgB,iBAAiB,YAAoB,SAAuB;AAG1E,cAAa;EAAE;EAAU,WADZ,kBAAkB,KAAK,KAAK,CAAC,GAAG,QAAQ,MAAM,GAAG,GAAG,CAAC,QAAQ,SAAS,IAAI,CAAC,GAAG,KAAK,MAAM,KAAK,QAAQ,GAAG,IAAM;EAClF,SAAS;GAAE,MAAM;GAAS,QAAQ;GAAiB;EAAE,CAAC;;;;;ACflG,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAED,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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