Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

chore: add codemod next workflow (#4663)

Cindy Zhangef849b1bc8b2
diff --git a/.changeset/codemod-next-workflow.md b/.changeset/codemod-next-workflow.md
new file mode 100644
index 0000000000..57ea7e9008
--- /dev/null
+++ b/.changeset/codemod-next-workflow.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[docs] Document the core codemod staging workflow and add release-time automation that promotes `transforms/next` codemods into the resolved release version folder.
+
+@cixzhang
diff --git a/.github/scripts/codemod-verify.mjs b/.github/scripts/codemod-verify.mjs
index 6ac2dd8732..22006b55a1 100644
--- a/.github/scripts/codemod-verify.mjs
+++ b/.github/scripts/codemod-verify.mjs
@@ -38,23 +38,46 @@ function getChangedFiles() {
};
}
-function getCodemodVersions(changedFiles) {
+function getCodemodTargets(changedFiles) {
const versionPattern =
/^packages\/cli\/assets\/codemods\/transforms\/v([\d.]+)\//;
- const versions = new Set();
+ const targets = new Set();
for (const file of changedFiles) {
const match = file.match(versionPattern);
- if (match) versions.add(match[1]);
+ if (match) {
+ targets.add(match[1]);
+ continue;
+ }
+ if (file.startsWith('packages/cli/assets/codemods/transforms/next/')) {
+ targets.add('next');
+ }
+ }
+ return [...targets].sort((a, b) => {
+ if (a === 'next') return 1;
+ if (b === 'next') return -1;
+ return a.localeCompare(b, undefined, {numeric: true});
+ });
+}
+
+async function getManifestsForTargets(targets, fromVersion, latestVersion) {
+ if (targets.includes('next')) {
+ const manifest =
+ await import('../../packages/cli/assets/codemods/transforms/next/index.mjs');
+ const manifests = [{version: 'next', transforms: manifest.default}];
+ const releasedTargets = targets.filter(target => target !== 'next');
+ if (releasedTargets.length === 0) return manifests;
+ return [
+ ...(await getTransformsBetween(fromVersion, latestVersion)),
+ ...manifests,
+ ];
}
- return [...versions].sort();
+ return getTransformsBetween(fromVersion, latestVersion);
}
function getChangedConsumerFiles(changedFiles) {
- return changedFiles.filter((f) =>
+ return changedFiles.filter(f =>
CONSUMER_DIRS.some(
- (dir) =>
- f.startsWith(dir + '/') &&
- /\.(tsx?|jsx?)$/.test(f),
+ dir => f.startsWith(dir + '/') && /\.(tsx?|jsx?)$/.test(f),
),
);
}
@@ -63,13 +86,15 @@ async function main() {
console.log('πŸ” Codemod Verification\n');
const {base, files: changedFiles} = getChangedFiles();
- const codemodVersions = getCodemodVersions(changedFiles);
+ const codemodTargets = getCodemodTargets(changedFiles);
const consumerFiles = getChangedConsumerFiles(changedFiles);
- console.log(`Codemod versions modified: ${codemodVersions.join(', ') || 'none'}`);
+ console.log(
+ `Codemod targets modified: ${codemodTargets.join(', ') || 'none'}`,
+ );
console.log(`Consumer files changed: ${consumerFiles.length}`);
- if (codemodVersions.length === 0) {
+ if (codemodTargets.length === 0) {
console.log('\nβœ… No codemod changes β€” nothing to verify.');
process.exit(0);
}
@@ -82,7 +107,9 @@ async function main() {
process.exit(0);
}
- console.log(`\nConsumer files to verify:\n${consumerFiles.map((f) => ` ${f}`).join('\n')}\n`);
+ console.log(
+ `\nConsumer files to verify:\n${consumerFiles.map(f => ` ${f}`).join('\n')}\n`,
+ );
// Save the PR version of each consumer file
const prVersions = {};
@@ -101,7 +128,9 @@ async function main() {
console.log(` ⏭ ${file} β€” new in this PR, skipping`);
}
}
- console.log(`Reverted ${revertedFiles.length} files to base (${base.slice(0, 8)})\n`);
+ console.log(
+ `Reverted ${revertedFiles.length} files to base (${base.slice(0, 8)})\n`,
+ );
if (revertedFiles.length === 0) {
console.log('βœ… All consumer files are new β€” nothing to verify.');
@@ -114,13 +143,20 @@ async function main() {
// Determine the version range for codemods
// Only run the new versions added in this PR β€” the base branch already
// has earlier codemod changes applied to consumer files.
- const earliestVersion = codemodVersions[0];
- const latestVersion = codemodVersions[codemodVersions.length - 1];
+ const releasedTargets = codemodTargets.filter(target => target !== 'next');
+ const earliestVersion = releasedTargets[0] ?? 'next';
+ const latestVersion = releasedTargets[releasedTargets.length - 1] ?? 'next';
// Find the version just before the earliest modified one
- const {versions: allVersions} = await import('../../packages/cli/assets/codemods/registry.mjs');
+ const {versions: allVersions, latestVersion: latestRegisteredVersion} =
+ await import('../../packages/cli/assets/codemods/registry.mjs');
const earliestIdx = allVersions.indexOf(earliestVersion);
- const fromVersion = earliestIdx > 0 ? allVersions[earliestIdx - 1] : '0.0.0';
+ const fromVersion =
+ earliestVersion === 'next'
+ ? latestRegisteredVersion
+ : earliestIdx > 0
+ ? allVersions[earliestIdx - 1]
+ : '0.0.0';
// Save the base versions to detect which files the codemod actually modified
const baseVersions = {};
@@ -131,13 +167,21 @@ async function main() {
// Run codemods on each affected consumer directory
const affectedDirs = [
...new Set(
- revertedFiles.map((f) => CONSUMER_DIRS.find((dir) => f.startsWith(dir + '/'))).filter(Boolean),
+ revertedFiles
+ .map(f => CONSUMER_DIRS.find(dir => f.startsWith(dir + '/')))
+ .filter(Boolean),
),
];
for (const dir of affectedDirs) {
- console.log(`Running codemods (${fromVersion} β†’ ${latestVersion}) on ${dir}/...`);
- const manifests = await getTransformsBetween(fromVersion, latestVersion);
+ console.log(
+ `Running codemods (${fromVersion} β†’ ${latestVersion}) on ${dir}/...`,
+ );
+ const manifests = await getManifestsForTargets(
+ codemodTargets,
+ fromVersion,
+ latestVersion,
+ );
if (manifests.length === 0) {
console.log(' No applicable codemods found.');
continue;
@@ -155,17 +199,21 @@ async function main() {
// Filter to only files the codemod actually modified.
// Files unchanged by the codemod have unrelated edits in this PR β€” skip them.
- const codemodModifiedFiles = revertedFiles.filter((file) => {
+ const codemodModifiedFiles = revertedFiles.filter(file => {
try {
return fs.readFileSync(file, 'utf-8') !== baseVersions[file];
} catch {
return false;
}
});
- const skippedFiles = revertedFiles.filter((f) => !codemodModifiedFiles.includes(f));
+ const skippedFiles = revertedFiles.filter(
+ f => !codemodModifiedFiles.includes(f),
+ );
if (codemodModifiedFiles.length === 0) {
- console.log('\nβœ… Codemod made no changes to consumer files β€” nothing to verify.');
+ console.log(
+ '\nβœ… Codemod made no changes to consumer files β€” nothing to verify.',
+ );
for (const file of consumerFiles) {
fs.writeFileSync(file, prVersions[file]);
}
@@ -173,7 +221,9 @@ async function main() {
}
if (skippedFiles.length > 0) {
- console.log(`\nSkipping ${skippedFiles.length} file(s) not modified by codemod:`);
+ console.log(
+ `\nSkipping ${skippedFiles.length} file(s) not modified by codemod:`,
+ );
for (const file of skippedFiles) {
console.log(` ⏭ ${file}`);
}
@@ -183,7 +233,9 @@ async function main() {
// (jscodeshift's toSource() may change quotes, spacing, etc.)
console.log('\nFormatting codemod output with prettier...');
try {
- run(`npx prettier --write ${codemodModifiedFiles.map((f) => `"${f}"`).join(' ')}`);
+ run(
+ `npx prettier --write ${codemodModifiedFiles.map(f => `"${f}"`).join(' ')}`,
+ );
} catch (e) {
console.log(' ⚠️ Prettier formatting failed, comparing raw output');
}
@@ -235,32 +287,46 @@ async function main() {
const prLines = expected.split('\n');
// Find lines removed by codemod (in base but not in codemod output)
- const codemodRemovedFromBase = baseLines.filter((l) => !codemodLines.includes(l));
+ const codemodRemovedFromBase = baseLines.filter(
+ l => !codemodLines.includes(l),
+ );
// Find lines added by codemod (in codemod output but not in base)
- const codemodAddedToBase = codemodLines.filter((l) => !baseLines.includes(l));
+ const codemodAddedToBase = codemodLines.filter(
+ l => !baseLines.includes(l),
+ );
// Check: removed lines should also be absent from PR
const missingRemovals = codemodRemovedFromBase.filter(
- (l) => l.trim() && prLines.includes(l),
+ l => l.trim() && prLines.includes(l),
);
// Check: added lines should be present in PR
const missingAdditions = codemodAddedToBase.filter(
- (l) => l.trim() && !prLines.includes(l),
+ l => l.trim() && !prLines.includes(l),
);
if (missingRemovals.length === 0 && missingAdditions.length === 0) {
matches++;
- console.log(` βœ… ${file} (superset β€” PR includes codemod changes + additional edits)`);
+ console.log(
+ ` βœ… ${file} (superset β€” PR includes codemod changes + additional edits)`,
+ );
} else {
mismatches++;
const issues = [];
if (missingRemovals.length > 0) {
- issues.push(`${missingRemovals.length} line(s) codemod removed still present in PR`);
+ issues.push(
+ `${missingRemovals.length} line(s) codemod removed still present in PR`,
+ );
}
if (missingAdditions.length > 0) {
- issues.push(`${missingAdditions.length} line(s) codemod added missing from PR`);
+ issues.push(
+ `${missingAdditions.length} line(s) codemod added missing from PR`,
+ );
}
- mismatchDetails.push({file, diffLines: missingRemovals.length + missingAdditions.length, issues: issues.join('; ')});
+ mismatchDetails.push({
+ file,
+ diffLines: missingRemovals.length + missingAdditions.length,
+ issues: issues.join('; '),
+ });
console.log(` ❌ ${file} (${issues.join('; ')})`);
}
}
@@ -282,15 +348,21 @@ async function main() {
console.log(` ❌ Mismatches: ${mismatches}`);
if (mismatches > 0) {
- console.log('\nMismatched files (codemod changes not fully reflected in PR):');
+ console.log(
+ '\nMismatched files (codemod changes not fully reflected in PR):',
+ );
for (const {file, diffLines, issues} of mismatchDetails) {
console.log(` ❌ ${file} (${issues || diffLines + ' lines differ'})`);
}
- console.log('\n⚠️ The codemod did not reproduce the committed consumer changes.');
+ console.log(
+ '\n⚠️ The codemod did not reproduce the committed consumer changes.',
+ );
console.log('This means either:');
console.log(' 1. Callsites were hand-edited instead of using the codemod');
console.log(' 2. The codemod is incomplete (add missing transforms)');
- console.log(' 3. Changes are intentionally beyond codemod scope (add allow-manual-edit label)');
+ console.log(
+ ' 3. Changes are intentionally beyond codemod scope (add allow-manual-edit label)',
+ );
process.exit(1);
}
@@ -298,7 +370,7 @@ async function main() {
process.exit(0);
}
-main().catch((err) => {
+main().catch(err => {
console.error('Codemod verification failed:', err);
process.exit(1);
});
diff --git a/docs/release.md b/docs/release.md
index f4d16dad46..65761fc7b9 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -4,10 +4,24 @@ astryx publishes its 12 public `@astryxdesign/*` packages to the public npm regi
### How it fits together
-- **Versioning is local and unchanged.** `pnpm run version-packages` (= `changeset version && format-changelogs`) only edits files and changelogs on disk. It needs no npm auth and is untouched by trusted publishing.
+- **Versioning is local and unchanged.** `pnpm run version-packages` (= `changeset version && promote-codemod-next && sync-internal-deps && format-changelogs`) only edits files, changelogs, and release-staged codemods on disk. It needs no npm auth and is untouched by trusted publishing.
- **Publishing is pnpm-native and tokenless.** CI runs `pnpm publish ... --provenance --access public --no-git-checks` (not `changeset publish`, whose `npm whoami` precheck breaks under tokenless OIDC). pnpm natively fetches the OIDC token and attaches provenance.
- **Trust is per-package.** npm allows exactly **one** trust configuration per package, registered against the **calling** workflow. Each of the 12 packages must be configured individually.
+### Version-package codemod promotion
+
+Core codemods for unreleased breaking changes are staged in
+`packages/cli/assets/codemods/transforms/next/`, not in a guessed future version
+folder. During the Version Packages PR, `pnpm version-packages` runs
+`scripts/promote-codemod-next.mjs` immediately after `changeset version`, when
+`packages/core/package.json` contains the actual version being released.
+
+The promotion step copies every entry from `next` except `README.md` into
+`packages/cli/assets/codemods/transforms/v<released-version>/`, removes the
+promoted files from `next`, and registers the new version folder in
+`packages/cli/assets/codemods/registry.mjs`. Review those generated files in the
+Version Packages PR the same way you review changelog output.
+
### The publish workflow (`.github/workflows/deploy.yml`)
The `publish` job runs on push to `main` after `test` passes. The two requirements for OIDC are already present:
diff --git a/package.json b/package.json
index 2b33074a93..cc5f748d9f 100644
--- a/package.json
+++ b/package.json
@@ -29,7 +29,7 @@
"package:source": "node scripts/package-source.js",
"changeset": "changeset",
"changeset:new": "node scripts/changeset-new.mjs",
- "version-packages": "changeset version && node scripts/sync-internal-deps.mjs && node scripts/format-changelogs.mjs",
+ "version-packages": "changeset version && node scripts/promote-codemod-next.mjs && node scripts/sync-internal-deps.mjs && node scripts/format-changelogs.mjs",
"format-changelogs": "node scripts/format-changelogs.mjs",
"setup-trusted-publishing": "node scripts/npm/setup-trusted-publishing.mjs",
"verify-exports": "node scripts/verify-exports.mjs",
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 2f3d3da55e..b43e47c592 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -482,6 +482,30 @@ The config is validated against a strict schema when the CLI loads it, so an
unknown field is a hard error rather than a silent no-op. `astryx doctor`
reports whether the config loads cleanly.
+## Core codemod authoring
+
+Core codemods live under `packages/cli/assets/codemods/transforms/`. Released
+codemods are grouped by the target package version (`v0.3.0`, `v0.3.1`, ...),
+which is the version that first contains the breaking change.
+
+Do not guess that version in ordinary feature PRs. Add new codemods to
+`packages/cli/assets/codemods/transforms/next/` instead:
+
+- put transform modules and tests in `transforms/next/`;
+- maintain `transforms/next/index.mjs` with the run order for the staged
+ transforms;
+- leave `transforms/next/README.md` in place; it documents the staging area and
+ is never promoted.
+
+During the Version Packages PR, `pnpm version-packages` runs
+`scripts/promote-codemod-next.mjs` after `changeset version`. The script copies
+all staged entries except the README into `transforms/v<new-core-version>/`,
+registers that version in `packages/cli/assets/codemods/registry.mjs`, and clears
+the promoted files from `next`.
+
+This mirrors Changesets: feature PRs stage migration work without knowing the
+future release number; the release PR assigns the exact version.
+
## Integrations
An **integration** is any npm package that contributes its own components,
diff --git a/packages/cli/assets/codemods/transforms/next/README.md b/packages/cli/assets/codemods/transforms/next/README.md
new file mode 100644
index 0000000000..04f7b8d63f
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/next/README.md
@@ -0,0 +1,30 @@
+# Next release codemods
+
+Put new core codemods here while normal feature PRs are in flight.
+
+Why: the folder that ships a codemod is the **target package version** that will
+include the breaking change. Feature PRs usually do not know that version yet;
+the Version Packages PR decides it after `changeset version` resolves all pending
+changesets. This `next` folder works like Changesets: contributors stage work
+here, then the release/versioning step promotes it into the actual versioned
+folder.
+
+## Authoring rules
+
+- Add new transform modules directly under this directory.
+- Add or update this directory's `index.mjs` so it exports the transforms in the
+ order they should run.
+- Keep tests next to the transform, following existing version-folder patterns.
+- Do **not** guess a future `v0.x.y` folder in feature PRs.
+- Do **not** put release-specific content in this README; it stays in `next`.
+
+## Release promotion
+
+`pnpm version-packages` runs `scripts/promote-codemod-next.mjs` after
+`changeset version`. The script copies every entry in this directory except this
+README into `packages/cli/assets/codemods/transforms/v<new-core-version>/` and
+removes the promoted files from `next`.
+
+After promotion, the Version Packages PR should review the generated version
+folder and add it to `packages/cli/assets/codemods/registry.mjs` if it is a new
+version folder.
diff --git a/scripts/promote-codemod-next.mjs b/scripts/promote-codemod-next.mjs
new file mode 100755
index 0000000000..685da04464
--- /dev/null
+++ b/scripts/promote-codemod-next.mjs
@@ -0,0 +1,147 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * Promote staged codemods from transforms/next into the just-bumped release
+ * version folder. Run after `changeset version`, when package.json contains
+ * the actual version this release will publish.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const DEFAULT_ROOT = path.resolve(__dirname, '..');
+const README = 'README.md';
+
+function readJson(file) {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+}
+
+function writeText(file, text) {
+ fs.writeFileSync(file, text.endsWith('\n') ? text : `${text}\n`);
+}
+
+function listPromotableEntries(nextDir) {
+ if (!fs.existsSync(nextDir)) return [];
+ return fs.readdirSync(nextDir, {withFileTypes: true}).filter(entry => {
+ if (entry.name === README) return false;
+ if (entry.name.startsWith('.')) return false;
+ return entry.isFile() || entry.isDirectory();
+ });
+}
+
+function copyRecursive(src, dest) {
+ const stat = fs.statSync(src);
+ if (stat.isDirectory()) {
+ fs.mkdirSync(dest, {recursive: true});
+ for (const entry of fs.readdirSync(src, {withFileTypes: true})) {
+ copyRecursive(path.join(src, entry.name), path.join(dest, entry.name));
+ }
+ return;
+ }
+ fs.mkdirSync(path.dirname(dest), {recursive: true});
+ fs.copyFileSync(src, dest, fs.constants.COPYFILE_EXCL);
+}
+
+function removeRecursive(src) {
+ fs.rmSync(src, {recursive: true, force: true});
+}
+
+function ensureRegistryEntry(registryPath, version) {
+ const text = fs.readFileSync(registryPath, 'utf8');
+ const entry = ` ['${version}', () => import('./transforms/v${version}/index.mjs')],`;
+ if (text.includes(`['${version}',`)) return false;
+
+ const marker = ']);';
+ const markerIndex = text.indexOf(marker);
+ if (markerIndex === -1) {
+ throw new Error('codemod-next: could not locate registry map terminator.');
+ }
+
+ const nextText = `${text.slice(0, markerIndex)}${entry}\n${text.slice(markerIndex)}`;
+ writeText(registryPath, nextText);
+ return true;
+}
+
+export function promoteCodemodNext({root = DEFAULT_ROOT} = {}) {
+ const corePackage = path.join(root, 'packages/core/package.json');
+ const transformsDir = path.join(
+ root,
+ 'packages/cli/assets/codemods/transforms',
+ );
+ const registryPath = path.join(
+ root,
+ 'packages/cli/assets/codemods/registry.mjs',
+ );
+ const nextDir = path.join(transformsDir, 'next');
+
+ const entries = listPromotableEntries(nextDir);
+ if (entries.length === 0) {
+ return {
+ promoted: [],
+ registryUpdated: false,
+ message: 'codemod-next: no staged codemods to promote.',
+ };
+ }
+
+ const version = readJson(corePackage).version;
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
+ throw new Error(
+ `codemod-next: invalid package version ${JSON.stringify(version)}`,
+ );
+ }
+
+ if (!entries.some(entry => entry.name === 'index.mjs')) {
+ throw new Error(
+ 'codemod-next: staged codemods must include next/index.mjs so the promoted version folder is registry-loadable.',
+ );
+ }
+
+ const versionDir = path.join(transformsDir, `v${version}`);
+ if (!fs.existsSync(versionDir)) fs.mkdirSync(versionDir, {recursive: true});
+
+ /** @type {Array<{from: string, to: string}>} */
+ const promoted = [];
+ for (const entry of entries) {
+ const src = path.join(nextDir, entry.name);
+ const dest = path.join(versionDir, entry.name);
+ if (fs.existsSync(dest)) {
+ throw new Error(
+ `codemod-next: refusing to overwrite existing ${path.relative(root, dest)}`,
+ );
+ }
+ copyRecursive(src, dest);
+ removeRecursive(src);
+ promoted.push({
+ from: path.relative(root, src),
+ to: path.relative(root, dest),
+ });
+ }
+
+ const registryUpdated = ensureRegistryEntry(registryPath, version);
+ return {version, promoted, registryUpdated};
+}
+
+function main() {
+ const result = promoteCodemodNext();
+ if (result.message) {
+ console.log(result.message);
+ return;
+ }
+ for (const entry of result.promoted) {
+ console.log(`codemod-next: promoted ${entry.from} -> ${entry.to}`);
+ }
+ if (result.registryUpdated) {
+ console.log(
+ `codemod-next: registered v${result.version} in packages/cli/assets/codemods/registry.mjs`,
+ );
+ }
+ console.log(
+ `codemod-next: promoted ${result.promoted.length} entr${result.promoted.length === 1 ? 'y' : 'ies'} into v${result.version}.`,
+ );
+}
+
+if (import.meta.url === `file://${process.argv[1]}`) {
+ main();
+}
diff --git a/scripts/promote-codemod-next.test.mjs b/scripts/promote-codemod-next.test.mjs
new file mode 100644
index 0000000000..d96fed5116
--- /dev/null
+++ b/scripts/promote-codemod-next.test.mjs
@@ -0,0 +1,113 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for codemod next-folder promotion.
+ */
+
+import {afterEach, describe, expect, it} from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import {promoteCodemodNext} from './promote-codemod-next.mjs';
+
+let tmpDir;
+
+afterEach(() => {
+ if (tmpDir) fs.rmSync(tmpDir, {recursive: true, force: true});
+ tmpDir = undefined;
+});
+
+function scaffold({version = '0.4.0'} = {}) {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-codemod-next-'));
+ fs.mkdirSync(path.join(tmpDir, 'packages/core'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'packages/core/package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version}, null, 2) + '\n',
+ );
+ const transforms = path.join(
+ tmpDir,
+ 'packages/cli/assets/codemods/transforms',
+ );
+ fs.mkdirSync(path.join(transforms, 'next'), {recursive: true});
+ fs.writeFileSync(
+ path.join(tmpDir, 'packages/cli/assets/codemods/registry.mjs'),
+ "const registry = new Map([\n ['0.3.0', () => import('./transforms/v0.3.0/index.mjs')],\n]);\n",
+ );
+ return {root: tmpDir, transforms};
+}
+
+describe('promoteCodemodNext', () => {
+ it('does nothing when only the next README exists', () => {
+ const {root, transforms} = scaffold();
+ fs.writeFileSync(path.join(transforms, 'next', 'README.md'), '# Next\n');
+
+ const result = promoteCodemodNext({root});
+
+ expect(result.promoted).toEqual([]);
+ expect(result.registryUpdated).toBe(false);
+ expect(result.message).toContain('no staged codemods');
+ });
+
+ it('promotes staged files into the current package version and registers it', () => {
+ const {root, transforms} = scaffold({version: '0.4.0'});
+ fs.writeFileSync(path.join(transforms, 'next', 'README.md'), '# Next\n');
+ fs.writeFileSync(
+ path.join(transforms, 'next', 'index.mjs'),
+ 'export default [];\n',
+ );
+ fs.writeFileSync(
+ path.join(transforms, 'next', 'rename-thing.mjs'),
+ 'export default function transform() {}\n',
+ );
+
+ const result = promoteCodemodNext({root});
+
+ expect(result.version).toBe('0.4.0');
+ expect(result.promoted.map(entry => entry.to).sort()).toEqual([
+ 'packages/cli/assets/codemods/transforms/v0.4.0/index.mjs',
+ 'packages/cli/assets/codemods/transforms/v0.4.0/rename-thing.mjs',
+ ]);
+ expect(result.registryUpdated).toBe(true);
+ expect(fs.existsSync(path.join(transforms, 'next', 'README.md'))).toBe(
+ true,
+ );
+ expect(fs.existsSync(path.join(transforms, 'next', 'index.mjs'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(transforms, 'v0.4.0', 'index.mjs'))).toBe(
+ true,
+ );
+ expect(
+ fs.readFileSync(
+ path.join(root, 'packages/cli/assets/codemods/registry.mjs'),
+ 'utf8',
+ ),
+ ).toContain("['0.4.0', () => import('./transforms/v0.4.0/index.mjs')]");
+ });
+
+ it('requires a next index manifest when staged transforms exist', () => {
+ const {root, transforms} = scaffold();
+ fs.writeFileSync(
+ path.join(transforms, 'next', 'rename-thing.mjs'),
+ 'export default function transform() {}\n',
+ );
+
+ expect(() => promoteCodemodNext({root})).toThrow(/next\/index\.mjs/);
+ });
+
+ it('refuses to overwrite an existing version-folder file', () => {
+ const {root, transforms} = scaffold({version: '0.4.0'});
+ fs.writeFileSync(
+ path.join(transforms, 'next', 'index.mjs'),
+ 'export default [];\n',
+ );
+ fs.mkdirSync(path.join(transforms, 'v0.4.0'), {recursive: true});
+ fs.writeFileSync(
+ path.join(transforms, 'v0.4.0', 'index.mjs'),
+ 'export default [];\n',
+ );
+
+ expect(() => promoteCodemodNext({root})).toThrow(/refusing to overwrite/);
+ });
+});