Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/update-rewritten-member-manifests.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modelcontextprotocol/codemod': patch
---

Apply package.json dependency swaps to workspace members whose source files were rewritten during a v1-to-v2 codemod migration.
16 changes: 15 additions & 1 deletion packages/codemod/src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,21 @@ export function run(migration: Migration, options: RunnerOptions): RunnerResult
files.push(fileResult.filePath);
}

const changes = updatePackageJson(manifests, usedByManifest, (options.dryRun ?? false) || targetIsFile, zodInjectedByManifest);
const rewrittenManifestPaths = new Set<string>();
for (const fileResult of fileResults) {
if (fileResult.changes > 0) {
const owner = ownerManifest(fileResult.filePath, manifests);
if (owner) rewrittenManifestPaths.add(owner.path);
}
}

const changes = updatePackageJson(
manifests,
usedByManifest,
(options.dryRun ?? false) || targetIsFile,
zodInjectedByManifest,
rewrittenManifestPaths
);
packageJsonChanges = changes.length > 0 ? changes : undefined;
}

Expand Down
24 changes: 14 additions & 10 deletions packages/codemod/src/utils/packageJsonUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,10 @@ function parseManifest(manifestPath: string): ParsedManifest | undefined {

/**
* Swap the v1 SDK dependency for the v2 packages in the **nearest** manifest (the
* first entry of `manifests`), and report — without modifying — the same edit for
* every other manifest that declares the v1 SDK, so workspace members never receive
* writes the user did not point the codemod at.
* first entry of `manifests`) and any manifest whose files were rewritten in this run,
* and report — without modifying — the same edit for every other manifest that declares
* the v1 SDK, so un-migrated workspace members never receive writes the user did not point
* the codemod at.
*
* The v2 additions come from the **post-transform** import state of the files each
* manifest owns (`usedByManifest`), not from what was rewritten in this run — so a
Expand All @@ -263,7 +264,8 @@ export function updatePackageJson(
manifests: readonly ManifestInfo[],
usedByManifest: ReadonlyMap<string, ReadonlySet<string>>,
dryRun: boolean,
zodInjectedByManifest: ReadonlyMap<string, readonly string[]> = new Map()
zodInjectedByManifest: ReadonlyMap<string, readonly string[]> = new Map(),
writableManifestPaths?: ReadonlySet<string>
): PackageJsonChange[] {
const changes: PackageJsonChange[] = [];
const nearestPath = manifests[0]?.path;
Expand Down Expand Up @@ -339,6 +341,7 @@ export function updatePackageJson(
const declaresAnyV2 = Object.keys({ ...deps, ...devDeps }).some(dep => dep in V2_PACKAGE_VERSIONS);
const usesV2 = (effectiveUsed.get(manifest.path)?.size ?? 0) > 0;
const isNearest = manifest.path === nearestPath;
const isWritable = isNearest || (writableManifestPaths !== undefined && writableManifestPaths.has(manifest.path));

// The file-level `import { z } from 'zod'` injection promises a manifest edit;
// it must land even when this manifest never declared the v1 SDK (a member
Expand All @@ -364,10 +367,10 @@ export function updatePackageJson(
if (!inDeps && !inDevDeps) {
if (needsInjectedZod) {
addInjectedZod('dependencies');
if (isNearest && !dryRun) {
if (isWritable && !dryRun) {
writeManifest(manifest.path, raw, pkgJson);
}
changes.push({ added: ['zod'], removed: [], packageJsonPath: manifest.path, applied: isNearest });
changes.push({ added: ['zod'], removed: [], packageJsonPath: manifest.path, applied: isWritable });
continue;
}
// The zod note only matters for manifests that take part in the migration:
Expand Down Expand Up @@ -410,9 +413,10 @@ export function updatePackageJson(
if (inDeps) delete deps![V1_PACKAGE];
if (inDevDeps) delete devDeps![V1_PACKAGE];

// Only the nearest manifest is written; the others are reported so the user
// applies (or deliberately skips) each workspace-member edit themselves.
if (isNearest && !dryRun) {
// Only the nearest manifest or manifests whose source files were rewritten
// in this run are written; others are reported so the user applies
// (or deliberately skips) each un-migrated workspace-member edit themselves.
if (isWritable && !dryRun) {
writeManifest(manifest.path, raw, pkgJson);
}

Expand All @@ -421,7 +425,7 @@ export function updatePackageJson(
added: added.toSorted(),
removed: [V1_PACKAGE],
packageJsonPath: manifest.path,
applied: isNearest,
applied: isWritable,
...(notes !== undefined && { notes }),
...(warning !== undefined && (added.length > 0 || declaresAnyV2 || usesV2) && { warnings: [warning] })
});
Expand Down
51 changes: 51 additions & 0 deletions packages/codemod/test/v1-to-v2/packageJsonUpdater.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,30 @@ describe('updatePackageJson', () => {
expect(deps['@modelcontextprotocol/server']).toBeUndefined();
});

it('writes a member manifest when included in writableManifestPaths', () => {
writeJson('package.json', { name: 'mono', workspaces: ['packages/*'] });
const member = writeJson('packages/a/package.json', {
name: 'a',
dependencies: { '@modelcontextprotocol/sdk': '^1.29.0' }
});
const manifests = discoverManifests(dir);
const changes = updatePackageJson(
manifests,
new Map([[member, new Set(['@modelcontextprotocol/server'])]]),
false,
new Map(),
new Set([member])
);
expect(changes).toHaveLength(1);
expect(changes[0]!.packageJsonPath).toBe(member);
expect(changes[0]!.applied).toBe(true);
expect(changes[0]!.removed).toEqual(['@modelcontextprotocol/sdk']);
expect(changes[0]!.added).toEqual(['@modelcontextprotocol/server']);
const deps = readJson(member).dependencies as Record<string, string>;
expect(deps['@modelcontextprotocol/sdk']).toBeUndefined();
expect(deps['@modelcontextprotocol/server']).toBeDefined();
});

it('writes the nearest manifest and reports a member that also declares v1', () => {
const root = writeJson('package.json', {
name: 'mono',
Expand Down Expand Up @@ -224,6 +248,33 @@ describe('run() manifest integration', () => {
expect(deps['@modelcontextprotocol/client']).toBeUndefined();
});

it('applies manifest changes to workspace members whose source files were rewritten by the run', () => {
writeJson('package.json', { name: 'mono', workspaces: ['packages/*'] });
const member = writeJson('packages/a/package.json', {
name: 'a',
dependencies: { '@modelcontextprotocol/sdk': '^1.29.0' }
});
mkdirSync(path.join(dir, 'packages/a/src'), { recursive: true });
// Source uses v1 SDK import — will be rewritten by the run
writeFileSync(
path.join(dir, 'packages/a/src/index.ts'),
"import { Client } from '@modelcontextprotocol/sdk/client/index.js';\\nexport const c = new Client({ name: 'x', version: '1' });\\n"
);

const result = run(v1ToV2Migration, { targetDir: dir, dryRun: false });

const change = result.packageJsonChanges?.find(c => c.packageJsonPath === member);
expect(change).toBeDefined();
expect(change!.applied).toBe(true);
expect(change!.removed).toEqual(['@modelcontextprotocol/sdk']);
expect(change!.added).toContain('@modelcontextprotocol/client');

// The member manifest was rewritten because its source files were migrated in this run.
const deps = readJson(member).dependencies as Record<string, string>;
expect(deps['@modelcontextprotocol/sdk']).toBeUndefined();
expect(deps['@modelcontextprotocol/client']).toBeDefined();
});

it('survives a directory symlink cycle without following it', () => {
writeJson('package.json', { name: 'app', dependencies: { '@modelcontextprotocol/sdk': '^1.29.0' } });
mkdirSync(path.join(dir, 'src'), { recursive: true });
Expand Down
Loading