Skip to content

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

TypeScript

feat(cli): make ShadCN compositions upgrade-safe (#6228)

Joeyabe37c508b49
diff --git a/.changeset/shadcn-composition-upgrades.md b/.changeset/shadcn-composition-upgrades.md
new file mode 100644
index 0000000000..5949b58484
--- /dev/null
+++ b/.changeset/shadcn-composition-upgrades.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Add upgrade receipts and safe three-way reconciliation for ShadCN-copied compositions.
+
+@josephfarina
diff --git a/apps/docsite/scripts/generate-shadcn-registry.mjs b/apps/docsite/scripts/generate-shadcn-registry.mjs
index dd008b9533..87200b1f3f 100644
--- a/apps/docsite/scripts/generate-shadcn-registry.mjs
+++ b/apps/docsite/scripts/generate-shadcn-registry.mjs
@@ -9,7 +9,8 @@
*
* The registry keeps Astryx packages as real dependencies. Component and hook
* items create public re-exports; blocks and pages copy app-level composition
- * source that already imports published package paths.
+ * source that already imports published package paths and add adjacent receipts
+ * so Astryx can reconcile later releases without taking ownership of user edits.
*/
import * as fs from 'node:fs';
@@ -18,6 +19,11 @@ import babel from '@babel/core';
import stylexPlugin from '@stylexjs/babel-plugin';
import ts from 'typescript';
import {registryItemSchema, registrySchema} from 'shadcn/schema';
+import {
+ createRegistryReceipt,
+ registryReceiptTarget,
+ serializeRegistryReceipt,
+} from '../../../packages/cli/authoring/shadcn/receipt.mjs';
import {
blockRegistryIdentity,
componentRegistryIdentity,
@@ -213,7 +219,50 @@ function componentItem(packageName, component, packageDependencies) {
};
}
-function blockItem(block, packageDependencies, cliRoot) {
+function withCompositionReceipt(item, identity, sourceVersion) {
+ const sourceFile = item.files[0];
+ const receiptTarget = registryReceiptTarget(sourceFile.target, item.name);
+ const receipt = createRegistryReceipt({
+ item: {
+ name: item.name,
+ path: identity.path,
+ aliases: identity.aliases,
+ kind: identity.kind,
+ },
+ sourceVersion,
+ receiptTarget,
+ files: [
+ {
+ id: 'primary',
+ target: sourceFile.target,
+ registryPath: sourceFile.path,
+ content: sourceFile.content,
+ },
+ ],
+ });
+
+ return {
+ ...item,
+ files: [
+ sourceFile,
+ {
+ path: `registry/${item.name}/astryx-receipt.json`,
+ type: 'registry:file',
+ target: receiptTarget,
+ content: serializeRegistryReceipt(receipt),
+ },
+ ],
+ astryx: {
+ ...item.astryx,
+ receipt: {
+ schemaVersion: receipt.schemaVersion,
+ target: receiptTarget,
+ },
+ },
+ };
+}
+
+function blockItem(block, packageDependencies, cliRoot, sourceVersion) {
const identity = blockRegistryIdentity(
block.name,
block.exampleFor,
@@ -231,39 +280,43 @@ function blockItem(block, packageDependencies, cliRoot) {
`${block.dirName}.tsx`,
);
const compiled = precompileStylexSource(block.source, fileName);
- return {
- $schema: REGISTRY_ITEM_SCHEMA,
- name: itemName,
- type: 'registry:block',
- title: block.displayName || block.name,
- description: block.description || `Astryx ${kind}: ${block.name}.`,
- author: 'Astryx',
- dependencies: withCoreDependency(
- dependenciesForSource(compiled.source, fileName, packageDependencies),
- packageDependencies,
- ),
- css: ASTRYX_CSS,
- files: [
- {
- path: `registry/${itemName}/${block.dirName}.${compiled.extension}`,
- type: 'registry:block',
- target: `components/astryx/${kind === 'block' ? 'blocks' : `${kind}s`}/${block.dirName}.${compiled.extension}`,
- content: compiled.source,
+ return withCompositionReceipt(
+ {
+ $schema: REGISTRY_ITEM_SCHEMA,
+ name: itemName,
+ type: 'registry:block',
+ title: block.displayName || block.name,
+ description: block.description || `Astryx ${kind}: ${block.name}.`,
+ author: 'Astryx',
+ dependencies: withCoreDependency(
+ dependenciesForSource(compiled.source, fileName, packageDependencies),
+ packageDependencies,
+ ),
+ css: ASTRYX_CSS,
+ files: [
+ {
+ path: `registry/${itemName}/${block.dirName}.${compiled.extension}`,
+ type: 'registry:block',
+ target: `components/astryx/${kind === 'block' ? 'blocks' : `${kind}s`}/${block.dirName}.${compiled.extension}`,
+ content: compiled.source,
+ },
+ ],
+ astryx: {
+ kind,
+ path: identity.path,
+ aliases: identity.aliases,
+ exampleFor: block.exampleFor || null,
+ category: block.category,
+ componentsUsed: block.componentsUsed,
+ precompiledStylex: compiled.precompiledStylex,
},
- ],
- astryx: {
- kind,
- path: identity.path,
- aliases: identity.aliases,
- exampleFor: block.exampleFor || null,
- category: block.category,
- componentsUsed: block.componentsUsed,
- precompiledStylex: compiled.precompiledStylex,
},
- };
+ identity,
+ sourceVersion,
+ );
}
-function pageItem(template, packageDependencies, cliRoot) {
+function pageItem(template, packageDependencies, cliRoot, sourceVersion) {
const identity = pageRegistryIdentity(template.slug, template.registry);
const itemName = identity.name;
const fileName = path.join(
@@ -275,38 +328,42 @@ function pageItem(template, packageDependencies, cliRoot) {
'page.tsx',
);
const compiled = precompileStylexSource(template.source, fileName);
- return {
- $schema: REGISTRY_ITEM_SCHEMA,
- name: itemName,
- type: 'registry:page',
- title: template.name,
- description: template.description || `Astryx page: ${template.name}.`,
- author: 'Astryx',
- dependencies: withCoreDependency(
- dependenciesForSource(compiled.source, fileName, packageDependencies),
- packageDependencies,
- ),
- css: ASTRYX_CSS,
- files: [
- {
- path: `registry/${itemName}/page.${compiled.extension}`,
- // shadcn 4.19.0 silently skips files typed registry:page. The item
- // remains registry:page while its source file uses the working type.
- type: 'registry:block',
- target: `app/astryx/${template.slug}/page.${compiled.extension}`,
- content: compiled.source,
+ return withCompositionReceipt(
+ {
+ $schema: REGISTRY_ITEM_SCHEMA,
+ name: itemName,
+ type: 'registry:page',
+ title: template.name,
+ description: template.description || `Astryx page: ${template.name}.`,
+ author: 'Astryx',
+ dependencies: withCoreDependency(
+ dependenciesForSource(compiled.source, fileName, packageDependencies),
+ packageDependencies,
+ ),
+ css: ASTRYX_CSS,
+ files: [
+ {
+ path: `registry/${itemName}/page.${compiled.extension}`,
+ // shadcn 4.19.0 silently skips files typed registry:page. The item
+ // remains registry:page while its source file uses the working type.
+ type: 'registry:block',
+ target: `app/astryx/${template.slug}/page.${compiled.extension}`,
+ content: compiled.source,
+ },
+ ],
+ astryx: {
+ kind: 'page',
+ path: identity.path,
+ aliases: identity.aliases,
+ category: template.category,
+ isReady: template.isReady,
+ isHiddenFromOverview: template.isHiddenFromOverview,
+ precompiledStylex: compiled.precompiledStylex,
},
- ],
- astryx: {
- kind: 'page',
- path: identity.path,
- aliases: identity.aliases,
- category: template.category,
- isReady: template.isReady,
- isHiddenFromOverview: template.isHiddenFromOverview,
- precompiledStylex: compiled.precompiledStylex,
},
- };
+ identity,
+ sourceVersion,
+ );
}
function assertUniqueItemNames(items) {
@@ -352,6 +409,14 @@ export function buildShadcnRegistry({
dependencyTag = null,
externalDependencySpecs = {},
}) {
+ const cliPackage = packages.find(pkg => pkg.name === '@astryxdesign/cli');
+ const sourceVersion = dependencyTag ?? cliPackage?.version;
+ if (!sourceVersion && (blocks.length > 0 || templates.length > 0)) {
+ throw new Error(
+ 'Cannot generate copied composition receipts without an @astryxdesign/cli version',
+ );
+ }
+
const packageDependencies = new Map([
...packages.map(pkg => [
pkg.name,
@@ -377,7 +442,9 @@ export function buildShadcnRegistry({
let skippedUnpublishedBlocks = 0;
for (const block of blocks) {
try {
- blockItems.push(blockItem(block, packageDependencies, cliRoot));
+ blockItems.push(
+ blockItem(block, packageDependencies, cliRoot, sourceVersion),
+ );
} catch (error) {
if (error instanceof UnpublishedAstryxDependencyError) {
skippedUnpublishedBlocks++;
@@ -392,7 +459,9 @@ export function buildShadcnRegistry({
let skippedUnpublishedPages = 0;
for (const template of templates) {
try {
- pageItems.push(pageItem(template, packageDependencies, cliRoot));
+ pageItems.push(
+ pageItem(template, packageDependencies, cliRoot, sourceVersion),
+ );
} catch (error) {
if (error instanceof UnpublishedAstryxDependencyError) {
skippedUnpublishedPages++;
diff --git a/apps/docsite/src/content/blog/posts/meet-astryx-from-shadcn.md b/apps/docsite/src/content/blog/posts/meet-astryx-from-shadcn.md
index e523a95ce9..59a9ed1fb1 100644
--- a/apps/docsite/src/content/blog/posts/meet-astryx-from-shadcn.md
+++ b/apps/docsite/src/content/blog/posts/meet-astryx-from-shadcn.md
@@ -1,6 +1,6 @@
---
title: 'Meet people where they already build'
-description: 'An experiment that lets shadcn users install Astryx components, examples, blocks, and pages without giving up the Astryx package or CLI.'
+description: 'A compatibility path for shadcn users to install Astryx components, examples, blocks, and pages without giving up the Astryx package or CLI.'
date: '2026-09-02'
type: 'engineering'
draft: true
@@ -46,6 +46,8 @@ This splits the catalog into two useful kinds of install:
That distinction matters. Copying a complete Button implementation into every app makes upgrades harder and lets every copy drift. Copying a dashboard that uses the published Button is normal application development. The design system stays a dependency. The page stays yours.
+Copied compositions include a small adjacent Astryx receipt. After you update the Astryx packages, `astryx upgrade --registry` previews changes against the installed base and the matching registry release. Add `--apply` to update unchanged files and merge non-overlapping edits. Conflicts leave your file untouched with a separate review file.
+
Deep customization still exists, but it remains explicit through `astryx swizzle`. A normal registry install does not cross that line for you.
## We tried the whole catalog
@@ -71,11 +73,12 @@ npx shadcn@latest add <registry-origin>/examples/button/variants.json
# I need help finding and maintaining the right pieces
astryx build "analytics dashboard with filters"
astryx doctor
-astryx upgrade --apply
+astryx upgrade --registry
+astryx upgrade --registry --apply
```
## Why bother?
Incremental adoption is the point. A team can try one Astryx block inside its current app. It can add a full page when that is useful. It does not need to declare a migration project or learn a new tool before seeing value.
-If the experiment holds up, Astryx gets a wider front door without giving up the package boundary or the richer CLI experience. We meet people where they already build, and give them a reason to come further in.
+Astryx gets a wider front door without giving up the package boundary or the richer CLI experience. We meet people where they already build, and give them a reason to come further in.
diff --git a/docs/specs/AST-026/spec.md b/docs/specs/AST-026/spec.md
index 34aa7b62ee..30c6fafd54 100644
--- a/docs/specs/AST-026/spec.md
+++ b/docs/specs/AST-026/spec.md
@@ -30,8 +30,8 @@ Astryx CLI remains the primary, richer interface for discovery, composition,
integrations, themes, validation, and upgrades.
This record governs the approved compatibility foundation. The implementation
-may merge behind the canary docsite while copied-composition upgrades and public
-support ownership remain launch gates for the production endpoint and announcement.
+may merge behind the canary docsite while copied-composition upgrades remain the
+launch gate for the production endpoint and announcement.
## Non-goals
@@ -45,7 +45,7 @@ support ownership remain launch gates for the production endpoint and announceme
## Requirements
-- **FR1 — Standard protocol.** Every experimental item MUST validate against the
+- **FR1 — Standard protocol.** Every registry item MUST validate against the
standard shadcn Registry schema and use a standard registry item type. A
standard shadcn client MUST NOT need Astryx-specific code to read or install
the item.
@@ -78,7 +78,14 @@ support ownership remain launch gates for the production endpoint and announceme
- **FR8 — Staged launch.** Preview builds MUST serve the full registry from their
own `/shadcn` origin with `@canary` package dependencies. Production MUST use
exact released package versions and remain disabled until copied-composition
- upgrades and public support ownership are ready.
+ upgrades are ready.
+- **FR9 — Upgrade-safe copied compositions.** Every copied showcase, example,
+ block, and page MUST install an adjacent machine-readable receipt containing
+ the stable item route, the copied target, the exact installed bytes, and their
+ hash. `astryx upgrade` MUST only apply a canonical item that matches the
+ installed Astryx release, auto-update an unchanged file, three-way merge
+ edits, leave the original untouched when edits conflict, and never recreate a
+ deleted or moved file.
- **IR1 — Generated from current sources.** Registry output MUST come from the
existing docsite and CLI catalogs, never a parallel handwritten item list.
- **IR2 — Build-time static output.** The docsite build MUST generate static JSON
@@ -108,16 +115,19 @@ support ownership remain launch gates for the production endpoint and announceme
## Current-state impact
-The CLI already ships components, 161 blocks, and 47 ready page templates. The
-docsite generator already discovers components, individual showcases and
-examples, blocks, pages, package versions, and source. The experiment adds a
-serializer over that existing catalog rather than a second discovery system.
-
-Prior evidence installed all 921 generated entries through shadcn 4.19.0 into
-a clean Vite application, wrote every component, hook, block, and page file with
-zero install failures, and compiled all 6,620 imported modules in one build.
-Fourteen compositions that author local StyleX are precompiled to compiler-free
-JSX during generation; all other composition source stays typed TSX. Component
+The CLI already ships components, hundreds of examples and showcases, and page
+templates. The docsite generator already discovers components, individual
+showcases and examples, blocks, pages, package versions, and source. The
+compatibility layer adds a serializer over that existing catalog rather than a
+second discovery system.
+
+The current catalog generates 970 items. Its 702 copied compositions each carry
+a validated adjacent receipt. Prior evidence, before receipts were added,
+installed all 921 then-generated entries through shadcn 4.19.0 into a clean Vite
+application, wrote every component, hook, block, and page file with zero install
+failures, and compiled all 6,620 imported modules in one build. Fourteen
+compositions that author local StyleX are precompiled to compiler-free JSX during
+generation; all other composition source stays typed TSX. Component
implementation copying failed because private imports and uncompiled StyleX
crossed the package boundary; FR2 avoids that path by installing the package and
creating a public re-export only.
@@ -132,7 +142,8 @@ creating a public re-export only.
| FR4, IR3 | dependency extraction and relative-import audit | heroicons, recharts, StyleX import, page source | Escaping import or undeclared package fails |
| FR6 | raw JSON and shadcn parse tests | optional `astryx` metadata present | shadcn install changes or Astryx metadata becomes required |
| FR7 | docsite tests and copy-button interaction | component, block, page, compatibility guide | Command is absent, stale, or misstates copy behavior |
-| FR8 | canary preview plus production-target assertion | preview and released package dependencies | Production enables before both launch gates pass |
+| FR8 | canary preview plus production-target assertion | preview and released package dependencies | Production enables before the upgrade gate passes |
+| FR9 | receipt mutation tests plus stock ShadCN install | pristine, edited, conflicting, missing, aliased | User source is overwritten or an old route stops resolving |
| IR4 | clean shadcn-style fixture install, build, and Chrome screenshot | one of each item kind; light and dark | Install, build, or render fails |
## Decision log
@@ -168,7 +179,7 @@ upgrades and crosses private-import and uncompiled-StyleX boundaries.
Merge the compatibility foundation after end-to-end verification, but keep the
production registry and broad announcement disabled until copied-composition
-upgrades and public support ownership are ready.
+upgrades are ready.
### DEC-4 — Derive stable IDs from docs and organize URLs by item kind
@@ -196,11 +207,26 @@ reserve `/r` for a future Astryx-native protocol. Production items pin exact
released Astryx package versions; preview items use the matching preview origin
and `@canary` dependencies.
+### DEC-6 — Install adjacent receipts and reconcile from the canonical registry
+
+**Reference:** `spec:AST-026/DEC-6`
+**Decider:** `josephfarina`, `2026-09-10`
+
+Each copied composition carries a unique JSON receipt beside its source. The
+receipt stores the installed base bytes and hash; the stable item route resolves
+the release's compiled source. `astryx upgrade --registry` refuses a registry
+item that does not match the installed Astryx release, then updates pristine
+files or performs a real three-way merge without treating editable application
+code as package-owned implementation. Conflicts are written to a separate
+artifact and never replace the user's file. Deleted or moved files stay deleted
+or moved.
+
+Rejected: hash-only receipts. They cannot reconstruct the merge base after a
+user edits the file. Also rejected: rebuilding the latest composition from raw
+CLI template assets at upgrade time. StyleX-precompiled registry items require
+the registry's compiled bytes.
+
## Open questions
-- **OQ1 — Support operations.** (`human-api`) Which maintainer and public channel
- own registry support, and what response promise is documented?
-- **OQ2 — Copied-composition upgrades.** (`engineering`) What provenance and
- upgrade flow keeps copied showcases, examples, blocks, and pages maintainable?
-- **OQ3 — Catalog visibility.** (`human-design`) Should hidden or not-ready
+- **OQ1 — Catalog visibility.** (`human-design`) Should hidden or not-ready
catalog entries stay addressable by URL, or be omitted entirely?
diff --git a/internal/shadcn-registry/generate-shadcn-registry.test.mjs b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
index c5169aad60..84767d3fdb 100644
--- a/internal/shadcn-registry/generate-shadcn-registry.test.mjs
+++ b/internal/shadcn-registry/generate-shadcn-registry.test.mjs
@@ -13,6 +13,7 @@ import {
existsSync,
mkdirSync,
mkdtempSync,
+ readFileSync,
rmSync,
writeFileSync,
} from 'node:fs';
@@ -20,6 +21,11 @@ import {tmpdir} from 'node:os';
import path from 'node:path';
import {promisify} from 'node:util';
import {describe, expect, it} from 'vitest';
+import {reconcileRegistryCompositions} from '../../packages/cli/api/upgrade/registry/registry.mjs';
+import {
+ parseRegistryReceipt,
+ registryContentHash,
+} from '../../packages/cli/authoring/shadcn/receipt.mjs';
import {
buildShadcnRegistry,
generateShadcnRegistry,
@@ -33,7 +39,10 @@ import {
const execFileAsync = promisify(execFile);
-const packages = [{name: '@astryxdesign/core', version: '0.5.2'}];
+const packages = [
+ {name: '@astryxdesign/cli', version: '0.6.0'},
+ {name: '@astryxdesign/core', version: '0.5.2'},
+];
function fixture(overrides = {}) {
return {
@@ -310,6 +319,175 @@ describe('buildShadcnRegistry', () => {
);
});
+ it('adds an adjacent provenance receipt only to copied compositions', () => {
+ const {items} = buildShadcnRegistry(fixture());
+ const component = items.find(item => item.name === 'component-button');
+ const block = items.find(item => item.name === 'showcase-button-variants');
+ const page = items.find(item => item.name === 'template-dashboard');
+
+ expect(component.files).toHaveLength(1);
+ for (const item of [block, page]) {
+ expect(item.files).toHaveLength(2);
+ const sourceFile = item.files[0];
+ const receiptFile = item.files[1];
+ expect(receiptFile).toMatchObject({
+ type: 'registry:file',
+ target: expect.stringContaining('/.astryx/'),
+ });
+ const receipt = parseRegistryReceipt(JSON.parse(receiptFile.content));
+ expect(receipt).toMatchObject({
+ schemaVersion: 1,
+ item: {
+ name: item.name,
+ path: item.astryx.path,
+ aliases: item.astryx.aliases,
+ kind: item.astryx.kind,
+ },
+ source: {package: '@astryxdesign/cli', version: '0.6.0'},
+ });
+ expect(receipt.files[0]).toMatchObject({
+ id: 'primary',
+ registryTarget: sourceFile.target,
+ registryPath: sourceFile.path,
+ sha256: registryContentHash(sourceFile.content),
+ content: sourceFile.content,
+ });
+ }
+ });
+
+ it('writes a provenance receipt beside copied source through ShadCN', async () => {
+ const project = mkdtempSync(path.join(tmpdir(), 'astryx-shadcn-receipt-'));
+ try {
+ writeConsumerProject(project);
+ const {items} = buildShadcnRegistry(fixture());
+ const block = items.find(
+ item => item.name === 'showcase-button-variants',
+ );
+ const itemPath = path.join(project, 'block.json');
+ writeFileSync(itemPath, JSON.stringify(block));
+
+ await execFileAsync(
+ path.resolve('node_modules/.bin/shadcn'),
+ ['add', itemPath, '--yes'],
+ {cwd: project, timeout: 30_000},
+ );
+
+ expect(
+ existsSync(
+ path.join(
+ project,
+ 'src',
+ 'components',
+ 'astryx',
+ 'showcases',
+ 'ButtonShowcase.tsx',
+ ),
+ ),
+ ).toBe(true);
+ expect(
+ existsSync(
+ path.join(
+ project,
+ 'src',
+ 'components',
+ 'astryx',
+ 'showcases',
+ '.astryx',
+ 'showcase-button-variants.json',
+ ),
+ ),
+ ).toBe(true);
+ } finally {
+ rmSync(project, {recursive: true, force: true});
+ }
+ });
+
+ it('upgrades a stock-ShadCN install from its adjacent receipt', async () => {
+ const project = mkdtempSync(path.join(tmpdir(), 'astryx-shadcn-upgrade-'));
+ const oldInput = fixture();
+ const oldItem = buildShadcnRegistry(oldInput).items.find(
+ item => item.name === 'showcase-button-variants',
+ );
+ const latestSource =
+ "import {Button} from '@astryxdesign/core/Button';\n" +
+ 'export default function ButtonShowcase() { return <Button label="Updated" />; }\n';
+ const latestInput = fixture({
+ packages: [
+ {name: '@astryxdesign/cli', version: '0.7.0'},
+ {name: '@astryxdesign/core', version: '0.5.2'},
+ ],
+ blocks: [{...oldInput.blocks[0], source: latestSource}],
+ });
+ const latestItem = buildShadcnRegistry(latestInput).items.find(
+ item => item.name === 'showcase-button-variants',
+ );
+ const server = createServer((request, response) => {
+ if (request.url !== '/showcases/button/variants.json') {
+ response.writeHead(404);
+ response.end('not found');
+ return;
+ }
+ response.writeHead(200, {'content-type': 'application/json'});
+ response.end(JSON.stringify(latestItem));
+ });
+
+ try {
+ writeConsumerProject(project);
+ const itemPath = path.join(project, 'block.json');
+ writeFileSync(itemPath, JSON.stringify(oldItem));
+ await execFileAsync(
+ path.resolve('node_modules/.bin/shadcn'),
+ ['add', itemPath, '--yes'],
+ {cwd: project, timeout: 30_000},
+ );
+ await new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', resolve);
+ });
+ const address = server.address();
+ expect(address).not.toBeNull();
+ expect(typeof address).not.toBe('string');
+ const result = await reconcileRegistryCompositions(
+ {apply: true, path: 'src'},
+ {
+ cwd: project,
+ registryOrigin: `http://127.0.0.1:${address.port}`,
+ expectedVersion: '0.7.0',
+ },
+ );
+ const sourcePath = path.join(
+ project,
+ 'src',
+ 'components',
+ 'astryx',
+ 'showcases',
+ 'ButtonShowcase.tsx',
+ );
+ const receiptPath = path.join(
+ project,
+ 'src',
+ 'components',
+ 'astryx',
+ 'showcases',
+ '.astryx',
+ 'showcase-button-variants.json',
+ );
+
+ expect(result.summary).toMatchObject({updated: 1, conflicts: 0});
+ expect(readFileSync(sourcePath, 'utf8')).toBe(latestSource);
+ expect(JSON.parse(readFileSync(receiptPath, 'utf8')).source.version).toBe(
+ '0.7.0',
+ );
+ } finally {
+ if (server.listening) {
+ await new Promise((resolve, reject) => {
+ server.close(error => (error ? reject(error) : resolve()));
+ });
+ }
+ rmSync(project, {recursive: true, force: true});
+ }
+ });
+
it('keeps component implementation inside the package', () => {
const {items} = buildShadcnRegistry(fixture());
const component = items.find(item => item.name === 'component-button');
@@ -492,10 +670,14 @@ describe('buildShadcnRegistry', () => {
dependencyTag: 'canary',
});
const component = items.find(item => item.name === 'component-button');
+ const showcase = items.find(item => item.name === 'showcase-button-variants');
expect(component.dependencies).toEqual([
'@astryxdesign/core@canary',
'@stylexjs/[email protected]',
]);
+ expect(
+ parseRegistryReceipt(JSON.parse(showcase.files[1].content)).source.version,
+ ).toBe('canary');
});
it('precompiles local StyleX with runtime CSS injection', () => {
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 2b48e07062..203b010ac1 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -73,7 +73,7 @@ Options:
| `swizzle` | Copy component source for customization |
| `template` | Inject a page or block template |
| `theme` | Theme tools: build, export, and manage themes |
-| `upgrade` | Run codemods to migrate between versions |
+| `upgrade` | Migrate versions and update ShadCN-copied compositions |
<!-- END GENERATED: commands -->
<!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->
diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjs
index e4f4dbd7ea..33497ae96f 100644
--- a/packages/cli/api/upgrade/_adapter.mjs
+++ b/packages/cli/api/upgrade/_adapter.mjs
@@ -63,6 +63,7 @@ const execFileAsync = promisify(execFile);
* @property {string[]} [integration]
* @property {string} [path]
* @property {boolean} [installDeps]
+ * @property {boolean} [registry]
*/
/**
diff --git a/packages/cli/api/upgrade/registry/registry.mjs b/packages/cli/api/upgrade/registry/registry.mjs
new file mode 100644
index 0000000000..8eb124ca5f
--- /dev/null
+++ b/packages/cli/api/upgrade/registry/registry.mjs
@@ -0,0 +1,917 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Safe reconciliation for source copied from the Astryx ShadCN registry.
+ * @input Adjacent install receipts, current project files, and current registry JSON.
+ * @output Dry-run/apply summaries, clean merges, and separate conflict artifacts.
+ * @position ShadCN composition lane inside the `upgrade` API.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {randomUUID} from 'node:crypto';
+import {mergeDiff3} from 'node-diff3';
+import {
+ PUBLIC_SHADCN_REGISTRY_ORIGIN,
+ parseRegistryReceipt,
+ parseRegistryUpgradeItem,
+ registryContentHash,
+ registryReceiptTarget,
+ serializeRegistryReceipt,
+} from '../../../authoring/shadcn/receipt.mjs';
+import {
+ assertWithin,
+ PathSafetyError,
+} from '../../../foundation/fs/path-safety.mjs';
+import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
+import {AstryxError} from '../../error.mjs';
+import {logger} from '../../logger.mjs';
+import {detectInstalledTargetVersion} from '../_adapter.mjs';
+
+const SKIP_DIRS = new Set([
+ '.cache',
+ '.git',
+ '.next',
+ '.pnpm',
+ '.turbo',
+ 'build',
+ 'coverage',
+ 'dist',
+ 'node_modules',
+ 'out',
+]);
+const MAX_ITEM_BYTES = 16 * 1024 * 1024;
+const FETCH_CONCURRENCY = 8;
+
+/** @param {string} filePath @param {string} root */
+function relativePath(filePath, root) {
+ return path.relative(root, filePath).split(path.sep).join('/');
+}
+
+/** @param {string} root */
+export function discoverRegistryReceipts(root) {
+ /** @type {string[]} */
+ const receipts = [];
+ if (!fs.existsSync(root)) return receipts;
+
+ /** @param {string} dir */
+ function walk(dir) {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ if (SKIP_DIRS.has(entry.name)) continue;
+ const fullPath = path.join(dir, entry.name);
+ if (!entry.isDirectory()) continue;
+ if (entry.name === '.astryx') {
+ for (const receipt of fs.readdirSync(fullPath, {withFileTypes: true})) {
+ if (receipt.isFile() && receipt.name.endsWith('.json')) {
+ receipts.push(path.join(fullPath, receipt.name));
+ }
+ }
+ continue;
+ }
+ walk(fullPath);
+ }
+ }
+
+ walk(root);
+ return receipts.sort();
+}
+
+/** @param {string} filePath @param {string} content */
+function atomicWrite(filePath, content) {
+ const temporary = `${filePath}.astryx-tmp-${randomUUID()}`;
+ const existing = fs.existsSync(filePath) ? fs.lstatSync(filePath) : null;
+ const mode = existing && !existing.isSymbolicLink() ? existing.mode : null;
+ try {
+ fs.writeFileSync(temporary, content, 'utf8');
+ if (mode != null) fs.chmodSync(temporary, mode);
+ fs.renameSync(temporary, filePath);
+ } finally {
+ fs.rmSync(temporary, {force: true});
+ }
+}
+
+/** @param {string} source */
+function lines(source) {
+ return source.split('\n');
+}
+
+/** @param {string} source */
+function normalizeLineEndings(source) {
+ return source.replace(/\r\n/g, '\n');
+}
+
+/** @param {string} source */
+function preferredLineEnding(source) {
+ return source.includes('\r\n') ? '\r\n' : '\n';
+}
+
+/** @param {string} source @param {string} lineEnding */
+function applyLineEnding(source, lineEnding) {
+ const normalized = normalizeLineEndings(source);
+ return lineEnding === '\n'
+ ? normalized
+ : normalized.replace(/\n/g, lineEnding);
+}
+
+/**
+ * @template T, U
+ * @param {T[]} values
+ * @param {number} limit
+ * @param {(value: T, index: number) => Promise<U>} mapper
+ * @returns {Promise<U[]>}
+ */
+async function mapWithConcurrency(values, limit, mapper) {
+ /** @type {U[]} */
+ const results = new Array(values.length);
+ let nextIndex = 0;
+ async function worker() {
+ while (nextIndex < values.length) {
+ const index = nextIndex++;
+ results[index] = await mapper(values[index], index);
+ }
+ }
+ await Promise.all(
+ Array.from({length: Math.min(limit, values.length)}, () => worker()),
+ );
+ return results;
+}
+
+/** @param {Response} response @param {string} url */
+async function readRegistryItemBody(response, url) {
+ const declaredLength = Number(response.headers.get('content-length'));
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_ITEM_BYTES) {
+ throw new Error(`Registry item ${url} exceeds ${MAX_ITEM_BYTES} bytes`);
+ }
+ if (!response.body) {
+ const text = await response.text();
+ if (Buffer.byteLength(text, 'utf8') > MAX_ITEM_BYTES) {
+ throw new Error(`Registry item ${url} exceeds ${MAX_ITEM_BYTES} bytes`);
+ }
+ return text;
+ }
+
+ const reader = response.body.getReader();
+ const chunks = [];
+ let total = 0;
+ while (true) {
+ const {done, value} = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > MAX_ITEM_BYTES) {
+ await reader.cancel();
+ throw new Error(`Registry item ${url} exceeds ${MAX_ITEM_BYTES} bytes`);
+ }
+ chunks.push(Buffer.from(value));
+ }
+ return Buffer.concat(chunks, total).toString('utf8');
+}
+
+/**
+ * @param {string} current
+ * @param {string} installed
+ * @param {string} latest
+ * @param {{current: string, installed: string, latest: string}} labels
+ */
+function threeWayMerge(current, installed, latest, labels) {
+ const result = mergeDiff3(lines(current), lines(installed), lines(latest), {
+ excludeFalseConflicts: true,
+ label: {
+ a: labels.current,
+ o: labels.installed,
+ b: labels.latest,
+ },
+ });
+ return {conflict: result.conflict, content: result.result.join('\n')};
+}
+
+/** @param {string} itemPath @param {string} registryOrigin */
+function registryItemUrl(itemPath, registryOrigin) {
+ return new URL(
+ `${itemPath}.json`,
+ `${registryOrigin.replace(/\/$/, '')}/`,
+ ).toString();
+}
+
+/** @param {string} sourceVersion @param {string} expectedVersion */
+function sourceVersionMatches(sourceVersion, expectedVersion) {
+ if (sourceVersion === expectedVersion) return true;
+ return (
+ sourceVersion === 'canary' &&
+ /(^|[.-])canary([.-]|$)/i.test(expectedVersion)
+ );
+}
+
+/**
+ * @param {string} itemPath
+ * @param {{fetchImpl: typeof fetch, registryOrigin: string, expectedVersion?: string}} options
+ */
+async function fetchLatestReceipt(
+ itemPath,
+ {fetchImpl, registryOrigin, expectedVersion},
+) {
+ const url = registryItemUrl(itemPath, registryOrigin);
+ let response;
+ try {
+ response = await fetchImpl(url, {
+ headers: {accept: 'application/json'},
+ redirect: 'error',
+ signal: globalThis.AbortSignal.timeout(15_000),
+ });
+ } catch (error) {
+ throw new Error(
+ `Could not fetch ${url}: ${error instanceof Error ? error.message : String(error)}`,
+ {cause: error},
+ );
+ }
+ if (!response.ok) {
+ throw new Error(`Could not fetch ${url}: HTTP ${response.status}`);
+ }
+ const text = await readRegistryItemBody(response, url);
+
+ let parsed;
+ try {
+ parsed = parseRegistryUpgradeItem(JSON.parse(text));
+ } catch (error) {
+ throw new Error(
+ `Registry item ${url} is invalid: ${error instanceof Error ? error.message : String(error)}`,
+ {cause: error},
+ );
+ }
+
+ const receiptCandidates = [];
+ for (const file of parsed.files) {
+ if (file.type !== 'registry:file' || !file.path.endsWith('.json')) continue;
+ try {
+ receiptCandidates.push({
+ receipt: parseRegistryReceipt(JSON.parse(file.content)),
+ carrier: file,
+ });
+ } catch {
+ // Other JSON files are allowed; only a valid Astryx receipt counts.
+ }
+ }
+ if (receiptCandidates.length !== 1) {
+ throw new Error(
+ `Registry item ${url} must contain exactly one Astryx receipt; found ${receiptCandidates.length}`,
+ );
+ }
+ const {receipt, carrier} = receiptCandidates[0];
+ if (
+ expectedVersion &&
+ !sourceVersionMatches(receipt.source.version, expectedVersion)
+ ) {
+ throw new Error(
+ `Registry item ${url} targets Astryx ${receipt.source.version}, but the project has ${expectedVersion}. Update Astryx packages first or retry after the registry catches up.`,
+ );
+ }
+ const expectedItemType =
+ receipt.item.kind === 'page' ? 'registry:page' : 'registry:block';
+ if (parsed.name !== receipt.item.name || parsed.type !== expectedItemType) {
+ throw new Error(`Registry item ${url} identity does not match its receipt`);
+ }
+ const expectedReceiptTarget = registryReceiptTarget(
+ receipt.files[0].registryTarget,
+ receipt.item.name,
+ );
+ if (
+ carrier.path !== `registry/${receipt.item.name}/astryx-receipt.json` ||
+ carrier.target !== expectedReceiptTarget
+ ) {
+ throw new Error(`Registry item ${url} has a misplaced Astryx receipt`);
+ }
+ if (
+ receipt.item.path !== itemPath &&
+ !receipt.item.aliases.includes(itemPath)
+ ) {
+ throw new Error(
+ `Registry item ${url} no longer recognizes installed path ${itemPath}`,
+ );
+ }
+
+ for (const file of receipt.files) {
+ const source = parsed.files.find(
+ candidate => candidate.path === file.registryPath,
+ );
+ if (
+ !source ||
+ source.target !== file.registryTarget ||
+ source.content !== file.content
+ ) {
+ throw new Error(
+ `Registry item ${url} receipt does not match ${file.registryPath}`,
+ );
+ }
+ if (registryContentHash(file.content) !== file.sha256) {
+ throw new Error(
+ `Registry item ${url} receipt has a corrupt hash for ${file.registryPath}`,
+ );
+ }
+ }
+ return receipt;
+}
+
+/**
+ * @param {string} receiptPath
+ * @param {string} root
+ */
+function loadInstalledReceipt(receiptPath, root) {
+ let receipt;
+ let receiptText;
+ try {
+ const receiptStat = fs.lstatSync(receiptPath);
+ if (receiptStat.isSymbolicLink()) {
+ throw new Error('receipt is a symbolic link');
+ }
+ if (receiptStat.size > MAX_ITEM_BYTES) {
+ throw new Error(`receipt exceeds ${MAX_ITEM_BYTES} bytes`);
+ }
+ receiptText = fs.readFileSync(receiptPath, 'utf8');
+ receipt = parseRegistryReceipt(JSON.parse(receiptText));
+ if (
+ path.basename(path.dirname(receiptPath)) !== '.astryx' ||
+ path.basename(receiptPath) !== `${receipt.item.name}.json`
+ ) {
+ throw new Error('receipt filename does not match its item identity');
+ }
+ } catch (error) {
+ throw new Error(
+ `Invalid receipt ${relativePath(receiptPath, root)}: ${error instanceof Error ? error.message : String(error)}`,
+ {cause: error},
+ );
+ }
+
+ const files = receipt.files.map(file => {
+ if (registryContentHash(file.content) !== file.sha256) {
+ throw new Error(
+ `Invalid receipt ${relativePath(receiptPath, root)}: stored hash does not match ${file.registryPath}`,
+ );
+ }
+ let sourcePath;
+ try {
+ sourcePath = assertWithin(
+ path.resolve(path.dirname(receiptPath), file.target),
+ root,
+ {allowAbsolute: true, label: 'registry composition source'},
+ );
+ } catch (error) {
+ if (error instanceof PathSafetyError) {
+ throw new Error(
+ `Invalid receipt ${relativePath(receiptPath, root)}: ${error.message}`,
+ {cause: error},
+ );
+ }
+ throw error;
+ }
+ return {...file, sourcePath};
+ });
+
+ return {receipt, files, receiptText};
+}
+
+/**
+ * @param {string} receiptPath
+ * @param {string} root
+ * @param {{fetchImpl: typeof fetch, registryOrigin: string, expectedVersion?: string}} options
+ */
+async function planReceipt(receiptPath, root, options) {
+ let installed;
+ try {
+ installed = loadInstalledReceipt(receiptPath, root);
+ } catch (error) {
+ return {
+ receiptPath,
+ item: path.basename(receiptPath, '.json'),
+ action: 'invalid',
+ message: error instanceof Error ? error.message : String(error),
+ files: [],
+ };
+ }
+
+ const {
+ receipt: oldReceipt,
+ files: oldFiles,
+ receiptText: oldReceiptText,
+ } = installed;
+ let newReceipt;
+ try {
+ newReceipt = await fetchLatestReceipt(oldReceipt.item.path, options);
+ } catch (error) {
+ return {
+ receiptPath,
+ item: oldReceipt.item.name,
+ itemPath: oldReceipt.item.path,
+ action: 'fetch-error',
+ message: error instanceof Error ? error.message : String(error),
+ files: [],
+ };
+ }
+
+ if (
+ newReceipt.item.name !== oldReceipt.item.name ||
+ newReceipt.item.kind !== oldReceipt.item.kind
+ ) {
+ return {
+ receiptPath,
+ item: oldReceipt.item.name,
+ itemPath: oldReceipt.item.path,
+ action: 'conflict',
+ message: 'Latest item changed its stable name or kind',
+ files: [],
+ oldReceiptText,
+ };
+ }
+ const oldIds = oldReceipt.files.map(file => file.id).sort();
+ const newIds = newReceipt.files.map(file => file.id).sort();
+ if (JSON.stringify(oldIds) !== JSON.stringify(newIds)) {
+ return {
+ receiptPath,
+ item: oldReceipt.item.name,
+ itemPath: oldReceipt.item.path,
+ action: 'conflict',
+ message:
+ 'Latest item changed its copied source set; no files were written',
+ files: [],
+ oldReceiptText,
+ };
+ }
+
+ const plannedFiles = [];
+ for (const oldFile of oldFiles) {
+ const newFile = newReceipt.files.find(file => file.id === oldFile.id);
+ const displayPath = relativePath(oldFile.sourcePath, root);
+ if (!newFile) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ action: 'target-changed',
+ message: `Latest item removed source id ${oldFile.id}`,
+ });
+ continue;
+ }
+ if (
+ newFile.target !== oldFile.target ||
+ newFile.registryTarget !== oldFile.registryTarget ||
+ newFile.registryPath !== oldFile.registryPath
+ ) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ action: 'target-changed',
+ message: 'Latest item changed the copied source target',
+ });
+ continue;
+ }
+ if (!fs.existsSync(oldFile.sourcePath)) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ action: 'missing',
+ message: 'Copied source was deleted or moved; it will not be recreated',
+ });
+ continue;
+ }
+
+ let current;
+ try {
+ if (fs.lstatSync(oldFile.sourcePath).isSymbolicLink()) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ action: 'invalid',
+ message: 'Copied source is a symbolic link; it will not be replaced',
+ });
+ continue;
+ }
+ current = fs.readFileSync(oldFile.sourcePath, 'utf8');
+ } catch (error) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ action: 'invalid',
+ message: error instanceof Error ? error.message : String(error),
+ });
+ continue;
+ }
+
+ const lineEnding = preferredLineEnding(current);
+ const conflictPath = `${oldFile.sourcePath}.astryx-conflict`;
+ const currentCanonical = normalizeLineEndings(current);
+ const oldCanonical = normalizeLineEndings(oldFile.content);
+ const newCanonical = normalizeLineEndings(newFile.content);
+ const currentHash = registryContentHash(currentCanonical);
+ const oldHash = registryContentHash(oldCanonical);
+ const newHash = registryContentHash(newCanonical);
+ if (oldHash === newHash) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ sourcePath: oldFile.sourcePath,
+ currentContent: current,
+ conflictPath,
+ action: currentHash === oldHash ? 'current' : 'user-modified',
+ });
+ continue;
+ }
+ if (currentHash === oldHash) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ sourcePath: oldFile.sourcePath,
+ currentContent: current,
+ conflictPath,
+ action: 'update',
+ content: applyLineEnding(newCanonical, lineEnding),
+ });
+ continue;
+ }
+ if (currentHash === newHash) {
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ sourcePath: oldFile.sourcePath,
+ currentContent: current,
+ conflictPath,
+ action: 'receipt-only',
+ });
+ continue;
+ }
+
+ const merged = threeWayMerge(currentCanonical, oldCanonical, newCanonical, {
+ current: 'current project',
+ installed: `installed ${oldReceipt.source.version}`,
+ latest: `latest ${newReceipt.source.version}`,
+ });
+ plannedFiles.push({
+ id: oldFile.id,
+ path: displayPath,
+ sourcePath: oldFile.sourcePath,
+ currentContent: current,
+ action: merged.conflict ? 'conflict' : 'merge',
+ content: applyLineEnding(merged.content, lineEnding),
+ conflictPath,
+ });
+ }
+
+ let action = 'current';
+ if (
+ plannedFiles.some(file =>
+ ['conflict', 'missing', 'invalid', 'target-changed'].includes(
+ file.action,
+ ),
+ )
+ ) {
+ action = 'conflict';
+ } else if (plannedFiles.some(file => file.action === 'merge')) {
+ action = 'merge';
+ } else if (plannedFiles.some(file => file.action === 'update')) {
+ action = 'update';
+ } else if (
+ plannedFiles.some(file => file.action === 'receipt-only') ||
+ serializeRegistryReceipt(oldReceipt) !==
+ serializeRegistryReceipt(newReceipt)
+ ) {
+ action = 'receipt-only';
+ }
+
+ return {
+ receiptPath,
+ item: oldReceipt.item.name,
+ itemPath: oldReceipt.item.path,
+ action,
+ files: plannedFiles,
+ oldReceipt,
+ newReceipt,
+ oldReceiptText,
+ };
+}
+
+/**
+ * @param {ReturnType<typeof emptySummary>} summary
+ * @param {any} item
+ * @param {string} plannedAction
+ * @param {boolean} apply
+ */
+function recordItem(summary, item, plannedAction, apply) {
+ summary.items.push(item);
+ if (['current', 'user-modified'].includes(plannedAction)) summary.current++;
+ else if (plannedAction === 'update') {
+ if (apply) summary.updated++;
+ else summary.wouldUpdate++;
+ } else if (plannedAction === 'merge') {
+ if (apply) summary.merged++;
+ else summary.wouldMerge++;
+ } else if (plannedAction === 'receipt-only') {
+ if (apply) summary.receiptsRefreshed++;
+ else summary.wouldRefreshReceipt++;
+ } else if (plannedAction === 'conflict') summary.conflicts++;
+ else if (plannedAction === 'invalid') summary.invalid++;
+ else if (plannedAction === 'fetch-error') summary.failed++;
+}
+
+/**
+ * @param {boolean} apply
+ * @returns {import('../upgrade.type.mjs').RegistryCompositionSummary}
+ */
+function emptySummary(apply) {
+ return {
+ applied: apply,
+ ok: true,
+ found: 0,
+ current: 0,
+ wouldUpdate: 0,
+ updated: 0,
+ wouldMerge: 0,
+ merged: 0,
+ wouldRefreshReceipt: 0,
+ receiptsRefreshed: 0,
+ conflicts: 0,
+ missing: 0,
+ invalid: 0,
+ failed: 0,
+ items: [],
+ };
+}
+
+/** @param {string} action @param {boolean} apply */
+function publicAction(action, apply) {
+ if (action === 'update') return apply ? 'updated' : 'would-update';
+ if (action === 'merge') return apply ? 'merged' : 'would-merge';
+ if (action === 'receipt-only') {
+ return apply ? 'receipt-refreshed' : 'would-refresh-receipt';
+ }
+ return action;
+}
+
+/** @param {any} item @param {string} root @param {boolean} apply */
+function publicItem(item, root, apply) {
+ return {
+ item: item.item,
+ path: item.itemPath,
+ action: publicAction(item.action, apply),
+ ...(item.message ? {message: item.message} : {}),
+ files: item.files.map(
+ /** @param {any} file */
+ file => ({
+ path: file.path,
+ action: publicAction(file.action, apply),
+ ...(file.message ? {message: file.message} : {}),
+ ...(file.action === 'conflict' && file.conflictPath
+ ? {conflictFile: relativePath(file.conflictPath, root)}
+ : {}),
+ }),
+ ),
+ };
+}
+
+/** @param {any} plan */
+function applyPlan(plan) {
+ if (!['conflict', 'update', 'merge', 'receipt-only'].includes(plan.action)) {
+ return;
+ }
+ if (
+ plan.oldReceiptText != null &&
+ fs.readFileSync(plan.receiptPath, 'utf8') !== plan.oldReceiptText
+ ) {
+ throw new Error('Receipt changed while the upgrade was running');
+ }
+ for (const file of plan.files) {
+ if (
+ file.sourcePath &&
+ file.currentContent != null &&
+ fs.readFileSync(file.sourcePath, 'utf8') !== file.currentContent
+ ) {
+ throw new Error(`${file.path} changed while the upgrade was running`);
+ }
+ }
+
+ if (plan.action === 'conflict') {
+ for (const file of plan.files) {
+ if (
+ file.action === 'conflict' &&
+ file.conflictPath &&
+ file.content != null
+ ) {
+ atomicWrite(file.conflictPath, file.content);
+ }
+ }
+ return;
+ }
+
+ const writable = plan.files.filter(
+ /** @param {any} file */
+ file => ['update', 'merge'].includes(file.action),
+ );
+ const originals = writable.map(
+ /** @param {any} file */
+ file => ({
+ path: file.sourcePath,
+ content: fs.readFileSync(file.sourcePath, 'utf8'),
+ }),
+ );
+ const oldReceiptText = fs.readFileSync(plan.receiptPath, 'utf8');
+ try {
+ for (const file of writable) atomicWrite(file.sourcePath, file.content);
+ atomicWrite(plan.receiptPath, serializeRegistryReceipt(plan.newReceipt));
+ } catch (error) {
+ for (const original of originals) {
+ try {
+ atomicWrite(original.path, original.content);
+ } catch {
+ // Preserve the first failure; the caller reports the item as failed.
+ }
+ }
+ try {
+ atomicWrite(plan.receiptPath, oldReceiptText);
+ } catch {
+ // Preserve the first failure.
+ }
+ throw error;
+ }
+
+ for (const file of plan.files) {
+ if (file.conflictPath) fs.rmSync(file.conflictPath, {force: true});
+ }
+}
+
+/**
+ * @param {{apply?: boolean, path?: string}} options
+ * @param {{cwd?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]
+ */
+export async function reconcileRegistryCompositions(
+ options = {},
+ {
+ cwd = process.cwd(),
+ fetchImpl = globalThis.fetch,
+ registryOrigin = PUBLIC_SHADCN_REGISTRY_ORIGIN,
+ expectedVersion,
+ requireExpectedVersion = false,
+ } = {},
+) {
+ let root;
+ try {
+ root = assertWithin(options.path ?? './src', cwd, {
+ allowAbsolute: true,
+ label: 'source directory',
+ });
+ } catch (error) {
+ if (error instanceof PathSafetyError) {
+ throw new AstryxError(
+ error.message,
+ undefined,
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
+ );
+ }
+ throw error;
+ }
+
+ const apply = options.apply ?? false;
+ const receipts = discoverRegistryReceipts(root);
+ const summary = emptySummary(apply);
+ summary.found = receipts.length;
+ if (receipts.length === 0) return {summary, writtenFiles: []};
+ if (requireExpectedVersion && !expectedVersion) {
+ throw new AstryxError(
+ 'Could not find installed @astryxdesign/core. Install project dependencies before upgrading copied compositions.',
+ undefined,
+ ERROR_CODES.ERR_VERSION_DETECT,
+ );
+ }
+
+ const plans = await mapWithConcurrency(
+ receipts,
+ FETCH_CONCURRENCY,
+ receiptPath =>
+ planReceipt(receiptPath, root, {
+ fetchImpl,
+ registryOrigin,
+ expectedVersion,
+ }),
+ );
+
+ /** @type {string[]} */
+ const writtenFiles = [];
+ for (const plan of plans) {
+ for (const file of plan.files) {
+ if (file.action === 'missing') summary.missing++;
+ if (file.action === 'invalid' || file.action === 'target-changed') {
+ summary.invalid++;
+ }
+ }
+ recordItem(summary, publicItem(plan, root, apply), plan.action, apply);
+ if (!apply) continue;
+
+ try {
+ applyPlan(plan);
+ if (['update', 'merge'].includes(plan.action)) {
+ for (const file of plan.files) {
+ if (file.sourcePath && ['update', 'merge'].includes(file.action)) {
+ writtenFiles.push(file.sourcePath);
+ }
+ }
+ }
+ } catch (error) {
+ if (plan.action === 'update') summary.updated--;
+ else if (plan.action === 'merge') summary.merged--;
+ else if (plan.action === 'receipt-only') summary.receiptsRefreshed--;
+ summary.failed++;
+ const item = summary.items.at(-1);
+ if (item) {
+ item.action = 'write-error';
+ item.message = error instanceof Error ? error.message : String(error);
+ }
+ }
+ }
+
+ summary.ok =
+ summary.conflicts === 0 &&
+ summary.missing === 0 &&
+ summary.invalid === 0 &&
+ summary.failed === 0;
+ return {summary, writtenFiles};
+}
+
+/** @param {import('../upgrade.type.mjs').RegistryCompositionSummary} summary */
+export function logRegistryCompositionSummary(summary) {
+ if (summary.found === 0) return;
+ logger.log(
+ `${summary.found} ShadCN composition receipt${summary.found === 1 ? '' : 's'} checked.`,
+ );
+ const pending =
+ summary.wouldUpdate + summary.wouldMerge + summary.wouldRefreshReceipt;
+ if (!summary.applied && pending > 0) {
+ logger.log(
+ `${pending} update${pending === 1 ? '' : 's'} available (dry run).`,
+ );
+ }
+ const changed = summary.updated + summary.merged;
+ if (changed + summary.receiptsRefreshed > 0) {
+ logger.log(
+ `${changed} composition${changed === 1 ? '' : 's'} updated` +
+ (summary.receiptsRefreshed > 0
+ ? `; ${summary.receiptsRefreshed} receipt${summary.receiptsRefreshed === 1 ? '' : 's'} refreshed.`
+ : '.'),
+ );
+ }
+ if (
+ summary.conflicts + summary.missing + summary.invalid + summary.failed >
+ 0
+ ) {
+ logger.warn(
+ `${summary.conflicts} conflict(s), ${summary.missing} missing file(s), ` +
+ `${summary.invalid} invalid receipt(s), ${summary.failed} failed item(s).`,
+ );
+ for (const item of summary.items) {
+ if (item.message) logger.warn(` ${item.item}: ${item.message}`);
+ for (const file of item.files) {
+ if (
+ !['conflict', 'missing', 'invalid', 'target-changed'].includes(
+ file.action,
+ )
+ ) {
+ continue;
+ }
+ const detail = file.conflictFile
+ ? ` Review ${file.conflictFile}.`
+ : file.message
+ ? ` ${file.message}.`
+ : '';
+ logger.warn(` ${file.path}: ${file.action}.${detail}`);
+ }
+ }
+ }
+}
+
+/**
+ * Standalone `astryx upgrade --registry` leaf.
+ * @param {{apply?: boolean, path?: string}} options
+ * @param {{cwd?: string, fetchImpl?: typeof fetch, registryOrigin?: string, expectedVersion?: string, requireExpectedVersion?: boolean}} [ctx]
+ * @returns {Promise<import('../upgrade.type.mjs').UpgradeRegistryResponse>}
+ */
+export async function registryUpgrade(options = {}, ctx = {}) {
+ const cwd = ctx.cwd ?? process.cwd();
+ const installed = detectInstalledTargetVersion(cwd);
+ const expectedVersion =
+ ctx.expectedVersion ??
+ (installed?.packageName === '@astryxdesign/core'
+ ? installed.version
+ : undefined);
+ const {summary} = await reconcileRegistryCompositions(options, {
+ ...ctx,
+ cwd,
+ expectedVersion,
+ requireExpectedVersion: true,
+ });
+ if (summary.found === 0) {
+ logger.log('No ShadCN composition receipts found.');
+ } else {
+ logRegistryCompositionSummary(summary);
+ }
+ logger.log(
+ summary.ok
+ ? (summary.applied
+ ? 'Registry upgrade complete'
+ : 'Registry dry run complete') + '\n'
+ : 'Registry upgrade finished with unresolved items\n',
+ );
+ return {type: 'upgrade.registry', data: summary};
+}
diff --git a/packages/cli/api/upgrade/registry/registry.test.mjs b/packages/cli/api/upgrade/registry/registry.test.mjs
new file mode 100644
index 0000000000..6a2ed07f12
--- /dev/null
+++ b/packages/cli/api/upgrade/registry/registry.test.mjs
@@ -0,0 +1,523 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {
+ createRegistryReceipt,
+ registryReceiptTarget,
+ serializeRegistryReceipt,
+} from '../../../authoring/shadcn/receipt.mjs';
+import {
+ discoverRegistryReceipts,
+ reconcileRegistryCompositions,
+} from './registry.mjs';
+
+const ITEM = {
+ name: 'example-button-basic',
+ path: 'examples/button/basic',
+ aliases: [],
+ kind: 'example',
+};
+const SOURCE_TARGET = 'components/astryx/examples/ButtonBasic.tsx';
+const REGISTRY_PATH = 'registry/example-button-basic/ButtonBasic.tsx';
+const RECEIPT_TARGET = registryReceiptTarget(SOURCE_TARGET, ITEM.name);
+
+let project;
+let root;
+
+function receipt(content, overrides = {}) {
+ return createRegistryReceipt({
+ item: overrides.item ?? ITEM,
+ sourceVersion: overrides.version ?? '0.5.0',
+ receiptTarget: RECEIPT_TARGET,
+ files: [
+ {
+ id: 'primary',
+ target: SOURCE_TARGET,
+ registryPath: REGISTRY_PATH,
+ content,
+ },
+ ],
+ });
+}
+
+function seed({base, current = base, receiptValue = receipt(base)}) {
+ const sourcePath = path.join(root, SOURCE_TARGET);
+ const receiptPath = path.join(root, RECEIPT_TARGET);
+ fs.mkdirSync(path.dirname(sourcePath), {recursive: true});
+ fs.mkdirSync(path.dirname(receiptPath), {recursive: true});
+ if (current !== null) fs.writeFileSync(sourcePath, current, 'utf8');
+ fs.writeFileSync(
+ receiptPath,
+ typeof receiptValue === 'string'
+ ? receiptValue
+ : serializeRegistryReceipt(receiptValue),
+ 'utf8',
+ );
+ return {sourcePath, receiptPath};
+}
+
+function remote(latest, overrides = {}) {
+ const receiptFiles = [
+ {
+ id: 'primary',
+ target: SOURCE_TARGET,
+ registryPath: REGISTRY_PATH,
+ content: latest,
+ },
+ ...(overrides.extraFiles ?? []),
+ ];
+ const nextReceipt = createRegistryReceipt({
+ item: overrides.item ?? ITEM,
+ sourceVersion: overrides.version ?? '0.6.0',
+ receiptTarget: RECEIPT_TARGET,
+ files: receiptFiles,
+ });
+ const item = {
+ name: nextReceipt.item.name,
+ type: nextReceipt.item.kind === 'page' ? 'registry:page' : 'registry:block',
+ files: [
+ ...receiptFiles.map(file => ({
+ path: file.registryPath,
+ type: 'registry:block',
+ target: file.target,
+ content:
+ file.id === 'primary'
+ ? (overrides.sourceContent ?? file.content)
+ : file.content,
+ })),
+ {
+ path: 'registry/example-button-basic/astryx-receipt.json',
+ type: 'registry:file',
+ target: overrides.receiptTarget ?? RECEIPT_TARGET,
+ content: serializeRegistryReceipt(nextReceipt),
+ },
+ ],
+ };
+ return vi.fn(
+ async () => new globalThis.Response(JSON.stringify(item), {status: 200}),
+ );
+}
+
+async function reconcile(options = {}, context = {}) {
+ return reconcileRegistryCompositions(
+ {path: 'src', ...options},
+ {cwd: project, registryOrigin: 'https://registry.example.test', ...context},
+ );
+}
+
+beforeEach(() => {
+ project = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-composition-upgrade-'),
+ );
+ root = path.join(project, 'src');
+ fs.mkdirSync(root, {recursive: true});
+});
+
+afterEach(() => {
+ fs.rmSync(project, {recursive: true, force: true});
+});
+
+describe('registry composition upgrades', () => {
+ it('discovers only JSON receipts inside .astryx directories', () => {
+ const {receiptPath} = seed({base: 'base\n'});
+ fs.writeFileSync(
+ path.join(path.dirname(receiptPath), 'notes.txt'),
+ 'ignore',
+ );
+ fs.mkdirSync(path.join(root, 'node_modules', 'x', '.astryx'), {
+ recursive: true,
+ });
+ fs.writeFileSync(
+ path.join(root, 'node_modules', 'x', '.astryx', 'ignored.json'),
+ '{}',
+ );
+
+ expect(discoverRegistryReceipts(root)).toEqual([receiptPath]);
+ });
+
+ it('bounds concurrent registry fetches', async () => {
+ const remoteItems = new Map();
+ for (let index = 0; index < 12; index++) {
+ const item = {
+ name: `example-test-${index}`,
+ path: `examples/test/item-${index}`,
+ aliases: [],
+ kind: 'example',
+ };
+ const sourceTarget = `components/astryx/examples/Test${index}.tsx`;
+ const registryPath = `registry/${item.name}/Test${index}.tsx`;
+ const receiptTarget = registryReceiptTarget(sourceTarget, item.name);
+ const installed = createRegistryReceipt({
+ item,
+ sourceVersion: '0.5.0',
+ receiptTarget,
+ files: [
+ {
+ id: 'primary',
+ target: sourceTarget,
+ registryPath,
+ content: 'old\n',
+ },
+ ],
+ });
+ const latest = createRegistryReceipt({
+ item,
+ sourceVersion: '0.6.0',
+ receiptTarget,
+ files: [
+ {
+ id: 'primary',
+ target: sourceTarget,
+ registryPath,
+ content: 'new\n',
+ },
+ ],
+ });
+ const sourcePath = path.join(root, sourceTarget);
+ const receiptPath = path.join(root, receiptTarget);
+ fs.mkdirSync(path.dirname(sourcePath), {recursive: true});
+ fs.mkdirSync(path.dirname(receiptPath), {recursive: true});
+ fs.writeFileSync(sourcePath, 'old\n');
+ fs.writeFileSync(receiptPath, serializeRegistryReceipt(installed));
+ remoteItems.set(
+ `/${item.path}.json`,
+ JSON.stringify({
+ name: item.name,
+ type: 'registry:block',
+ files: [
+ {
+ path: registryPath,
+ type: 'registry:block',
+ target: sourceTarget,
+ content: 'new\n',
+ },
+ {
+ path: `registry/${item.name}/astryx-receipt.json`,
+ type: 'registry:file',
+ target: receiptTarget,
+ content: serializeRegistryReceipt(latest),
+ },
+ ],
+ }),
+ );
+ }
+
+ let active = 0;
+ let maximum = 0;
+ const fetchImpl = vi.fn(async url => {
+ active++;
+ maximum = Math.max(maximum, active);
+ await new Promise(resolve => setTimeout(resolve, 5));
+ active--;
+ const body = remoteItems.get(new URL(url).pathname);
+ return new globalThis.Response(body ?? 'not found', {
+ status: body ? 200 : 404,
+ });
+ });
+ const result = await reconcile({}, {fetchImpl});
+
+ expect(result.summary).toMatchObject({found: 12, wouldUpdate: 12});
+ expect(maximum).toBe(8);
+ });
+
+ it('reports a current pristine source without writing', async () => {
+ const {sourcePath, receiptPath} = seed({base: 'same\n'});
+ const before = fs.readFileSync(receiptPath, 'utf8');
+ const result = await reconcile(
+ {},
+ {fetchImpl: remote('same\n', {version: '0.5.0'})},
+ );
+
+ expect(result.summary).toMatchObject({
+ applied: false,
+ found: 1,
+ current: 1,
+ conflicts: 0,
+ failed: 0,
+ });
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('same\n');
+ expect(fs.readFileSync(receiptPath, 'utf8')).toBe(before);
+ });
+
+ it('refuses source from a different Astryx release', async () => {
+ const {sourcePath} = seed({base: 'old\n'});
+ const result = await reconcile(
+ {apply: true},
+ {fetchImpl: remote('new\n'), expectedVersion: '0.5.0'},
+ );
+
+ expect(result.summary).toMatchObject({ok: false, failed: 1, updated: 0});
+ expect(result.summary.items[0].message).toMatch(/project has 0\.5\.0/);
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');
+ });
+
+ it('accepts canary source for an installed canary release', async () => {
+ const {sourcePath} = seed({base: 'old\n'});
+ const result = await reconcile(
+ {apply: true},
+ {
+ fetchImpl: remote('new\n', {version: 'canary'}),
+ expectedVersion: '0.6.0-canary.42',
+ },
+ );
+
+ expect(result.summary).toMatchObject({ok: true, updated: 1});
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('new\n');
+ });
+
+ it('previews a pristine update without writing', async () => {
+ const {sourcePath, receiptPath} = seed({base: 'old\n'});
+ const before = fs.readFileSync(receiptPath, 'utf8');
+ const result = await reconcile({}, {fetchImpl: remote('new\n')});
+
+ expect(result.summary).toMatchObject({
+ found: 1,
+ wouldUpdate: 1,
+ updated: 0,
+ });
+ expect(result.summary.items[0].action).toBe('would-update');
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');
+ expect(fs.readFileSync(receiptPath, 'utf8')).toBe(before);
+ });
+
+ it('updates a pristine source and advances its receipt', async () => {
+ const {sourcePath, receiptPath} = seed({base: 'old\n'});
+ fs.writeFileSync(`${sourcePath}.astryx-conflict`, 'stale\n');
+ const result = await reconcile({apply: true}, {fetchImpl: remote('new\n')});
+
+ expect(result.summary).toMatchObject({
+ applied: true,
+ found: 1,
+ wouldUpdate: 0,
+ updated: 1,
+ conflicts: 0,
+ items: [{action: 'updated'}],
+ });
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('new\n');
+ expect(fs.existsSync(`${sourcePath}.astryx-conflict`)).toBe(false);
+ expect(
+ JSON.parse(fs.readFileSync(receiptPath, 'utf8')).source.version,
+ ).toBe('0.6.0');
+ });
+
+ it('rolls back source when the receipt write fails', async () => {
+ if (process.platform === 'win32') return;
+ const {sourcePath, receiptPath} = seed({base: 'old\n'});
+ const receiptDir = path.dirname(receiptPath);
+ fs.chmodSync(receiptDir, 0o500);
+ try {
+ const result = await reconcile(
+ {apply: true},
+ {fetchImpl: remote('new\n')},
+ );
+
+ expect(result.summary).toMatchObject({
+ ok: false,
+ updated: 0,
+ failed: 1,
+ items: [{action: 'write-error'}],
+ });
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');
+ expect(
+ JSON.parse(fs.readFileSync(receiptPath, 'utf8')).source.version,
+ ).toBe('0.5.0');
+ } finally {
+ fs.chmodSync(receiptDir, 0o700);
+ }
+ });
+
+ it('preserves CRLF when updating a pristine source', async () => {
+ const {sourcePath} = seed({
+ base: 'first\nsecond\n',
+ current: 'first\r\nsecond\r\n',
+ });
+ const result = await reconcile(
+ {apply: true},
+ {fetchImpl: remote('first\nupdated\n')},
+ );
+
+ expect(result.summary).toMatchObject({updated: 1, conflicts: 0});
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('first\r\nupdated\r\n');
+ });
+
+ it('three-way merges non-overlapping user and upstream edits', async () => {
+ const base = 'title\nbody\nfooter\n';
+ const current = 'custom title\nbody\nfooter\n';
+ const latest = 'title\nbody\nnew footer\n';
+ const {sourcePath} = seed({base, current});
+ const result = await reconcile({apply: true}, {fetchImpl: remote(latest)});
+
+ expect(result.summary).toMatchObject({
+ merged: 1,
+ conflicts: 0,
+ items: [{action: 'merged'}],
+ });
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe(
+ 'custom title\nbody\nnew footer\n',
+ );
+ });
+
+ it('preserves CRLF when three-way merging', async () => {
+ const base = 'title\nbody\nfooter\n';
+ const current = 'custom title\r\nbody\r\nfooter\r\n';
+ const latest = 'title\nbody\nnew footer\n';
+ const {sourcePath} = seed({base, current});
+ const result = await reconcile({apply: true}, {fetchImpl: remote(latest)});
+
+ expect(result.summary).toMatchObject({merged: 1, conflicts: 0});
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe(
+ 'custom title\r\nbody\r\nnew footer\r\n',
+ );
+ });
+
+ it('leaves edited source and receipt untouched on conflict', async () => {
+ const base = 'value = 1\n';
+ const current = 'value = local\n';
+ const latest = 'value = upstream\n';
+ const {sourcePath, receiptPath} = seed({base, current});
+ const beforeReceipt = fs.readFileSync(receiptPath, 'utf8');
+ const result = await reconcile({apply: true}, {fetchImpl: remote(latest)});
+ const conflictPath = `${sourcePath}.astryx-conflict`;
+
+ expect(result.summary).toMatchObject({conflicts: 1, updated: 0, merged: 0});
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe(current);
+ expect(fs.readFileSync(receiptPath, 'utf8')).toBe(beforeReceipt);
+ expect(fs.readFileSync(conflictPath, 'utf8')).toContain(
+ '<<<<<<< current project',
+ );
+ expect(fs.readFileSync(conflictPath, 'utf8')).toContain(
+ '>>>>>>> latest 0.6.0',
+ );
+ });
+
+ it('does not recreate a deleted or moved source', async () => {
+ const {sourcePath} = seed({base: 'old\n', current: null});
+ const result = await reconcile({apply: true}, {fetchImpl: remote('new\n')});
+
+ expect(result.summary).toMatchObject({missing: 1, conflicts: 1});
+ expect(fs.existsSync(sourcePath)).toBe(false);
+ });
+
+ it('does not replace a symbolic-link source', async () => {
+ if (process.platform === 'win32') return;
+ const {sourcePath} = seed({base: 'old\n'});
+ const linkedPath = path.join(root, 'linked.tsx');
+ fs.writeFileSync(linkedPath, 'linked\n', 'utf8');
+ fs.rmSync(sourcePath);
+ fs.symlinkSync(linkedPath, sourcePath);
+
+ const result = await reconcile({apply: true}, {fetchImpl: remote('new\n')});
+
+ expect(result.summary).toMatchObject({invalid: 1, conflicts: 1});
+ expect(fs.lstatSync(sourcePath).isSymbolicLink()).toBe(true);
+ expect(fs.readFileSync(linkedPath, 'utf8')).toBe('linked\n');
+ });
+
+ it('accepts an installed route that became an alias', async () => {
+ seed({base: 'old\n'});
+ const fetchImpl = remote('new\n', {
+ item: {
+ ...ITEM,
+ path: 'examples/button/new-basic',
+ aliases: [ITEM.path],
+ },
+ });
+ const result = await reconcile({apply: true}, {fetchImpl});
+
+ expect(result.summary.updated).toBe(1);
+ expect(fetchImpl.mock.calls[0][0]).toBe(
+ 'https://registry.example.test/examples/button/basic.json',
+ );
+ });
+
+ it('refuses an upstream source-set change', async () => {
+ const {sourcePath} = seed({base: 'old\n'});
+ const result = await reconcile(
+ {apply: true},
+ {
+ fetchImpl: remote('new\n', {
+ extraFiles: [
+ {
+ id: 'secondary',
+ target: 'components/astryx/examples/Helper.ts',
+ registryPath: 'registry/example-button-basic/Helper.ts',
+ content: 'export const helper = true;\n',
+ },
+ ],
+ }),
+ },
+ );
+
+ expect(result.summary).toMatchObject({conflicts: 1, updated: 0});
+ expect(result.summary.items[0].message).toMatch(/source set/);
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');
+ });
+
+ it('rejects a corrupt installed base before fetching or writing', async () => {
+ const value = receipt('base\n');
+ value.files[0].sha256 = '0'.repeat(64);
+ const {sourcePath} = seed({base: 'base\n', receiptValue: value});
+ const fetchImpl = remote('new\n');
+ const result = await reconcile({apply: true}, {fetchImpl});
+
+ expect(result.summary).toMatchObject({invalid: 1, failed: 0});
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('base\n');
+ });
+
+ it('rejects a receipt target that escapes the source root', async () => {
+ const value = receipt('base\n');
+ value.files[0].target = '../../../outside.tsx';
+ const outside = path.join(project, 'outside.tsx');
+ seed({base: 'base\n', receiptValue: value});
+ const result = await reconcile({apply: true}, {fetchImpl: remote('new\n')});
+
+ expect(result.summary.invalid).toBe(1);
+ expect(fs.existsSync(outside)).toBe(false);
+ });
+
+ it('rejects an oversized registry item before reading its body', async () => {
+ seed({base: 'old\n'});
+ const fetchImpl = vi.fn(
+ async () =>
+ new globalThis.Response('{}', {
+ status: 200,
+ headers: {'content-length': String(16 * 1024 * 1024 + 1)},
+ }),
+ );
+ const result = await reconcile({apply: true}, {fetchImpl});
+
+ expect(result.summary.failed).toBe(1);
+ expect(result.summary.items[0].message).toMatch(/exceeds/);
+ });
+
+ it('rejects a remote receipt installed under the wrong target', async () => {
+ const {sourcePath} = seed({base: 'old\n'});
+ const result = await reconcile(
+ {apply: true},
+ {
+ fetchImpl: remote('new\n', {
+ receiptTarget: 'components/astryx/.astryx/wrong.json',
+ }),
+ },
+ );
+
+ expect(result.summary.failed).toBe(1);
+ expect(result.summary.items[0].message).toMatch(/misplaced/);
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');
+ });
+
+ it('rejects a remote receipt that disagrees with shipped source', async () => {
+ const {sourcePath} = seed({base: 'old\n'});
+ const result = await reconcile(
+ {apply: true},
+ {fetchImpl: remote('new\n', {sourceContent: 'tampered\n'})},
+ );
+
+ expect(result.summary.failed).toBe(1);
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');
+ });
+});
diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjs
index 2ec0b6bc73..d7a04c3af4 100644
--- a/packages/cli/api/upgrade/run/run.mjs
+++ b/packages/cli/api/upgrade/run/run.mjs
@@ -11,10 +11,10 @@
*
* Pipeline (--apply): detect installed core → run CORE codemods (before
* Project.load, so a core CONFIG codemod can repair an otherwise-invalid
- * config) → load config → discover + run INTEGRATION codemods → post-codemod
- * hooks → render + refresh agent docs from final post-upgrade state.
- * Integration DISCOVERY errors skip that integration; execution errors abort
- * before the agent-doc write.
+ * config) → load config → discover + run INTEGRATION codemods → reconcile
+ * ShadCN-copied compositions → post-codemod hooks → render + refresh agent docs
+ * from final post-upgrade state. Integration DISCOVERY errors skip that
+ * integration; execution errors abort before the agent-doc write.
*/
import * as path from 'node:path';
@@ -33,6 +33,10 @@ import {
selectIntegrationCodemodsFor,
runIntegrationCodemodsStep,
} from '../_adapter.mjs';
+import {
+ logRegistryCompositionSummary,
+ reconcileRegistryCompositions,
+} from '../registry/registry.mjs';
import {
statusUpToDate,
statusNoCodemods,
@@ -87,11 +91,32 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
}
const targetVersion = installed.version;
+ const reconcileCompositions = async () => {
+ if (options.codemod) return null;
+ const result = await reconcileRegistryCompositions(
+ {apply, path: path_},
+ {
+ cwd,
+ expectedVersion:
+ installed.packageName === '@astryxdesign/core'
+ ? targetVersion
+ : undefined,
+ requireExpectedVersion: true,
+ },
+ );
+ if (result.summary.found > 0) {
+ logRegistryCompositionSummary(result.summary);
+ return result;
+ }
+ return null;
+ };
+
logger.log(`From version: ${currentVersion}`);
logger.log(`Installed target: ${targetVersion} (${installed.packageName})`);
// Up-to-date check — no codemods will run, safe to render agent docs now.
if (!options.force && semverGte(currentVersion, targetVersion)) {
+ const registryResult = await reconcileCompositions();
const agentDocsPlan = await prepareAgentDocsRefresh({
cwd,
installedVersion: targetVersion,
@@ -104,6 +129,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
from: currentVersion,
to: targetVersion,
agentDocs,
+ ...(registryResult ? {registryCompositions: registryResult.summary} : {}),
});
}
@@ -214,6 +240,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
}
if (versionManifests.length === 0 && !hasIntegrationCodemods) {
+ const registryResult = await reconcileCompositions();
// No codemods in range — safe to render agent docs from current state.
const agentDocsPlan = await prepareAgentDocsRefresh({
cwd,
@@ -227,6 +254,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
from: currentVersion,
to: targetVersion,
agentDocs,
+ ...(registryResult ? {registryCompositions: registryResult.summary} : {}),
});
}
@@ -244,7 +272,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
}
/**
- * @type {{from: string, to: string, codemods: number, integrations: string[], agentDocsRefreshed: boolean, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, filesChanged?: number, transformsApplied?: number, errors?: Array<{file: string, codemod: string, error: string}>}}
+ * @type {{from: string, to: string, codemods: number, integrations: string[], agentDocsRefreshed: boolean, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary, filesChanged?: number, transformsApplied?: number, errors?: Array<{file: string, codemod: string, error: string}>}}
*/
const receipt = {
from: currentVersion,
@@ -269,12 +297,19 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
});
}
+ const registryResult = await reconcileCompositions();
+
const mergedFilesChanged = (coreResult?.totalFilesChanged ?? 0) + (integrationResult?.totalFilesChanged ?? 0);
const mergedTransformsApplied = (coreResult?.totalTransformsApplied ?? 0) + (integrationResult?.totalTransformsApplied ?? 0);
- const mergedWrittenFiles = [...(coreResult?.writtenFiles ?? []), ...(integrationResult?.writtenFiles ?? [])];
+ const mergedWrittenFiles = [
+ ...(coreResult?.writtenFiles ?? []),
+ ...(integrationResult?.writtenFiles ?? []),
+ ...(registryResult?.writtenFiles ?? []),
+ ];
const mergedErrors = [...(coreResult?.errors ?? []), ...(integrationResult?.errors ?? [])];
+ const registryFilesChanged = registryResult?.writtenFiles.length ?? 0;
- if (postCodemodHooks.length > 0 && mergedFilesChanged > 0) {
+ if (postCodemodHooks.length > 0 && (mergedFilesChanged > 0 || registryFilesChanged > 0)) {
const files = uniqueFiles(mergedWrittenFiles).map(file => path.relative(cwd, file));
try {
await runPostCodemodHooks(postCodemodHooks, {packageDir: cwd, files, apply: apply || false});
@@ -290,6 +325,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
receipt.filesChanged = mergedFilesChanged;
receipt.transformsApplied = mergedTransformsApplied;
receipt.errors = mergedErrors;
+ if (registryResult) receipt.registryCompositions = registryResult.summary;
if (receipt.errors?.length > 0) {
const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;
@@ -310,7 +346,12 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {
receipt.agentDocs = completedAgentDocs;
receipt.agentDocsRefreshed = completedAgentDocs.refreshed;
- logger.log((apply ? 'Upgrade complete' : 'Dry run complete') + '\n');
+ const registryOk = receipt.registryCompositions?.ok ?? true;
+ logger.log(
+ registryOk
+ ? (apply ? 'Upgrade complete' : 'Dry run complete') + '\n'
+ : 'Upgrade finished with unresolved registry items\n',
+ );
return {
type: 'upgrade.run',
data: /** @type {import('../upgrade.type.mjs').UpgradeRunResponse['data']} */ (/** @type {unknown} */ (receipt)),
diff --git a/packages/cli/api/upgrade/status/status.mjs b/packages/cli/api/upgrade/status/status.mjs
index 0049c2c88b..ab32b021ce 100644
--- a/packages/cli/api/upgrade/status/status.mjs
+++ b/packages/cli/api/upgrade/status/status.mjs
@@ -20,25 +20,43 @@ import {logger} from '../../logger.mjs';
/**
* `--from` is at/after the installed target (and no `--force`): nothing to run.
- * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary}} data
+ * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary}} data
* @returns {import('../upgrade.type.mjs').UpgradeStatusResponse}
*/
-export function statusUpToDate({from, to, agentDocs}) {
+export function statusUpToDate({from, to, agentDocs, registryCompositions}) {
logger.log('✓ Already up to date — no codemods to run.');
logger.log('Use --force to run codemods anyway.');
- logger.log('Done\n');
- return {type: 'upgrade.status', data: {status: 'up_to_date', from, to, agentDocs}};
+ logger.log(registryCompositions?.ok === false ? 'Finished with unresolved registry items\n' : 'Done\n');
+ return {
+ type: 'upgrade.status',
+ data: {
+ status: 'up_to_date',
+ from,
+ to,
+ agentDocs,
+ ...(registryCompositions ? {registryCompositions} : {}),
+ },
+ };
}
/**
* No core or integration codemods apply to the requested version range.
- * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary}} data
+ * @param {{from: string, to: string, agentDocs: import('../upgrade.type.mjs').AgentDocsSummary, registryCompositions?: import('../upgrade.type.mjs').RegistryCompositionSummary}} data
* @returns {import('../upgrade.type.mjs').UpgradeStatusResponse}
*/
-export function statusNoCodemods({from, to, agentDocs}) {
+export function statusNoCodemods({from, to, agentDocs, registryCompositions}) {
logger.log('✓ No codemods available for this version range.');
- logger.log('Done\n');
- return {type: 'upgrade.status', data: {status: 'no_codemods', from, to, agentDocs}};
+ logger.log(registryCompositions?.ok === false ? 'Finished with unresolved registry items\n' : 'Done\n');
+ return {
+ type: 'upgrade.status',
+ data: {
+ status: 'no_codemods',
+ from,
+ to,
+ agentDocs,
+ ...(registryCompositions ? {registryCompositions} : {}),
+ },
+ };
}
/**
diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjs
index 740eaf9eb3..defef00da5 100644
--- a/packages/cli/api/upgrade/upgrade.doc.mjs
+++ b/packages/cli/api/upgrade/upgrade.doc.mjs
@@ -12,8 +12,7 @@ export const doc = {
kind: 'api',
name: 'upgrade',
displayName: 'upgrade()',
- summary:
- 'Run version-migration codemods and refresh the managed agent-docs block.',
+ summary: 'Run version migrations and reconcile ShadCN-copied compositions.',
description:
'Migrates project source from a previous Astryx version to the currently ' +
'installed one by running the registered codemods, and compares the fully ' +
@@ -22,17 +21,27 @@ export const doc = {
'writes the prepared block only after selected codemods and hooks succeed. ' +
'Core codemods run before ' +
'the config is loaded so a config codemod can repair an otherwise-invalid ' +
- 'astryx.config.',
+ 'astryx.config. ShadCN-copied compositions carry adjacent receipts; upgrade ' +
+ 'compares those installed bases with the matching registry release, updates pristine ' +
+ 'files, merges non-overlapping edits, and leaves conflicting originals untouched.',
importPath: '@astryxdesign/cli/api',
signature:
- 'upgrade(options?: UpgradeOptions, ctx?: {cwd?: string}): Promise<UpgradeListResponse | UpgradeStatusResponse | UpgradeRunResponse>',
- keywords: ['upgrade', 'migrate', 'codemod', 'migration', 'version'],
+ 'upgrade(options?: UpgradeOptions, ctx?: {cwd?: string}): Promise<UpgradeListResponse | UpgradeRegistryResponse | UpgradeStatusResponse | UpgradeRunResponse>',
+ keywords: [
+ 'upgrade',
+ 'migrate',
+ 'codemod',
+ 'migration',
+ 'version',
+ 'shadcn',
+ 'registry',
+ ],
params: [
{
name: 'options.from',
type: 'string',
description:
- 'Version before the dependency bump. Required unless `list` is set.',
+ 'Version before the dependency bump. Required unless `list` or `registry` is set.',
},
{
name: 'options.apply',
@@ -73,6 +82,13 @@ export const doc = {
type: 'boolean',
description: 'Auto-install jscodeshift without prompting.',
},
+ {
+ name: 'options.registry',
+ type: 'boolean',
+ description:
+ 'Reconcile ShadCN-copied compositions from their install receipts without requiring `from`.',
+ default: 'false',
+ },
{
name: 'options.list',
type: 'boolean',
@@ -90,21 +106,26 @@ export const doc = {
description:
'Every available codemod, oldest→newest, as {name, title, version, optional}, returned when `list` is set; nothing is run.',
},
+ {
+ type: 'upgrade.registry',
+ description:
+ 'A dry-run or apply receipt for ShadCN-copied compositions, including safe updates, clean merges, conflicts, missing files, and invalid receipts.',
+ },
{
type: 'upgrade.status',
description:
- 'A short-circuit outcome (no codemods executed): `up_to_date` (`from` is at/after the installed target and no `force`), `no_codemods` (none apply to the range), or `config_fixable` (dry-run preview that a pending config codemod would repair an invalid astryx.config). Each carries the agent-docs summary.',
+ 'A short-circuit outcome (no codemods executed): `up_to_date` (`from` is at/after the installed target and no `force`), `no_codemods` (none apply to the range), or `config_fixable` (dry-run preview that a pending config codemod would repair an invalid astryx.config). Each carries the agent-docs summary and, when found, the copied-composition registry summary.',
},
{
type: 'upgrade.run',
description:
- 'The terminal run receipt: from/to versions, the codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and any per-codemod errors.',
+ 'The terminal run receipt: from/to versions, the codemod count, integrations processed, the agent-docs summary, an optional copied-composition registry summary, and (apply mode) filesChanged, transformsApplied, and any per-codemod errors.',
},
],
throws: [
{
code: 'ERR_INVALID_ARGUMENT',
- when: '`from` is missing (and `list` is not set), or the project config fails strict validation and no pending config codemod can repair it',
+ when: '`from` is missing (and neither `list` nor `registry` is set), or the project config fails strict validation and no pending config codemod can repair it',
},
{code: 'ERR_INVALID_VERSION', when: '`from` is not a valid semver string'},
{code: 'ERR_PATH_TRAVERSAL', when: '`path` resolves outside cwd'},
@@ -131,6 +152,10 @@ export const doc = {
code: 'const r = await upgrade({list: true});',
},
{label: 'Preview (dry-run)', code: "await upgrade({from: '0.0.5'});"},
+ {
+ label: 'Update ShadCN-copied compositions',
+ code: 'await upgrade({registry: true, apply: true});',
+ },
{
label: 'Apply changes',
code: "await upgrade({from: '0.0.5', apply: true});",
diff --git a/packages/cli/api/upgrade/upgrade.mjs b/packages/cli/api/upgrade/upgrade.mjs
index b28ccec33a..97b92e75ad 100644
--- a/packages/cli/api/upgrade/upgrade.mjs
+++ b/packages/cli/api/upgrade/upgrade.mjs
@@ -4,11 +4,13 @@
* @file upgrade API — dispatcher + barrel over the upgrade leaves.
*
* `upgrade(options)` runs codemods that migrate source from a previous Astryx
- * version to the currently installed one, and refreshes the managed agent-docs
- * block. It is the single entry the CLI calls; it validates the invocation and
- * routes to one leaf, each of which returns its `{type, data}` envelope:
- * - `list` (api/upgrade/list) → upgrade.list — available codemods, no run
- * - `run` (api/upgrade/run) → upgrade.run — the terminal run receipt,
+ * version to the currently installed one, refreshes the managed agent-docs
+ * block, and reconciles ShadCN-copied compositions. It is the single entry the
+ * CLI calls; it validates the invocation and routes to one leaf, each of which
+ * returns its `{type, data}` envelope:
+ * - `list` (api/upgrade/list) → upgrade.list — codemods, no run
+ * - `registry` (api/upgrade/registry) → upgrade.registry — copied source only
+ * - `run` (api/upgrade/run) → upgrade.run — the terminal run receipt,
* plus the up_to_date / no_codemods / config_fixable short-circuits it
* delegates to the `status` leaf → upgrade.status
*
@@ -20,6 +22,7 @@
*/
import {list} from './list/list.mjs';
+import {registryUpgrade} from './registry/registry.mjs';
import {run} from './run/run.mjs';
import {isValidSemver} from '../../foundation/env/semver.mjs';
import {getCliInvocation} from '../../foundation/env/package-manager.mjs';
@@ -27,7 +30,6 @@ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {AstryxError} from '../error.mjs';
import {logger} from '../logger.mjs';
-
/**
* @typedef {import('./upgrade.type.mjs').UpgradeOptions} UpgradeOptions
*/
@@ -39,11 +41,36 @@ import {logger} from '../logger.mjs';
*
* @param {UpgradeOptions} [options]
* @param {{cwd?: string}} [ctx]
- * @returns {Promise<import('./upgrade.type.mjs').UpgradeListResponse | import('./upgrade.type.mjs').UpgradeStatusResponse | import('./upgrade.type.mjs').UpgradeRunResponse>}
+ * @returns {Promise<import('./upgrade.type.mjs').UpgradeListResponse | import('./upgrade.type.mjs').UpgradeRegistryResponse | import('./upgrade.type.mjs').UpgradeStatusResponse | import('./upgrade.type.mjs').UpgradeRunResponse>}
*/
export async function upgrade(options = {}, {cwd = process.cwd()} = {}) {
logger.log('\nUpgrade');
+ if (options.list && options.registry) {
+ const msg = '`--list` and `--registry` cannot be used together.';
+ logger.error(msg);
+ logger.log('Aborted\n');
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);
+ }
+
+ if (options.registry) {
+ const incompatible = [
+ options.from ? '--from' : null,
+ options.force ? '--force' : null,
+ options.codemod ? '--codemod' : null,
+ options.skipCodemod?.length ? '--skip-codemod' : null,
+ options.integration?.length ? '--integration' : null,
+ options.installDeps ? '--install-deps' : null,
+ ].filter(Boolean);
+ if (incompatible.length > 0) {
+ const msg = `\`--registry\` cannot be combined with ${incompatible.join(', ')}.`;
+ logger.error(msg);
+ logger.log('Aborted\n');
+ throw new AstryxError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);
+ }
+ return registryUpgrade(options, {cwd});
+ }
+
if (!options.list && !options.from) {
const msg = `Missing required --from. Install the target version first, then run \`${getCliInvocation()} upgrade --from <old-version>\`.`;
logger.error(msg);
diff --git a/packages/cli/api/upgrade/upgrade.test.mjs b/packages/cli/api/upgrade/upgrade.test.mjs
index c9621ab4f3..a1a1a43861 100644
--- a/packages/cli/api/upgrade/upgrade.test.mjs
+++ b/packages/cli/api/upgrade/upgrade.test.mjs
@@ -19,6 +19,11 @@ import {logger} from '../logger.mjs';
import {AstryxError} from '../error.mjs';
import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
import {generateCompressedIndex} from '../../foundation/agent-docs/agent-docs.mjs';
+import {
+ createRegistryReceipt,
+ registryReceiptTarget,
+ serializeRegistryReceipt,
+} from '../../authoring/shadcn/receipt.mjs';
vi.setConfig({testTimeout: 30000});
@@ -34,6 +39,7 @@ afterEach(() => {
process.chdir(originalCwd);
fs.rmSync(tmpDir, {recursive: true, force: true});
vi.restoreAllMocks();
+ vi.unstubAllGlobals();
logger.setSilent(true);
});
@@ -54,7 +60,87 @@ function writeInstalledCore(dir, version) {
}
function writeAgentBlock(dir, rel, version) {
- fs.writeFileSync(path.join(dir, rel), `# Doc\n\n${generateCompressedIndex(version)}\n`);
+ fs.writeFileSync(
+ path.join(dir, rel),
+ `# Doc\n\n${generateCompressedIndex(version)}\n`,
+ );
+}
+
+function writeRegistryFixture(
+ dir,
+ {base = 'old\n', latest = 'new\n', version = '0.6.0'} = {},
+) {
+ const sourceTarget = 'components/astryx/examples/Example.tsx';
+ const registryPath = 'registry/example-button-basic/Example.tsx';
+ const receiptTarget = registryReceiptTarget(
+ sourceTarget,
+ 'example-button-basic',
+ );
+ const installedReceipt = createRegistryReceipt({
+ item: {
+ name: 'example-button-basic',
+ path: 'examples/button/basic',
+ aliases: [],
+ kind: 'example',
+ },
+ sourceVersion: '0.5.0',
+ receiptTarget,
+ files: [
+ {
+ id: 'primary',
+ target: sourceTarget,
+ registryPath,
+ content: base,
+ },
+ ],
+ });
+ const latestReceipt = createRegistryReceipt({
+ item: installedReceipt.item,
+ sourceVersion: version,
+ receiptTarget,
+ files: [
+ {
+ id: 'primary',
+ target: sourceTarget,
+ registryPath,
+ content: latest,
+ },
+ ],
+ });
+ const sourcePath = path.join(dir, 'src', sourceTarget);
+ const receiptPath = path.join(dir, 'src', receiptTarget);
+ fs.mkdirSync(path.dirname(sourcePath), {recursive: true});
+ fs.mkdirSync(path.dirname(receiptPath), {recursive: true});
+ fs.writeFileSync(sourcePath, base);
+ fs.writeFileSync(receiptPath, serializeRegistryReceipt(installedReceipt));
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(
+ async () =>
+ new globalThis.Response(
+ JSON.stringify({
+ name: latestReceipt.item.name,
+ type: 'registry:block',
+ files: [
+ {
+ path: registryPath,
+ type: 'registry:block',
+ target: sourceTarget,
+ content: latest,
+ },
+ {
+ path: 'registry/example-button-basic/astryx-receipt.json',
+ type: 'registry:file',
+ target: receiptTarget,
+ content: serializeRegistryReceipt(latestReceipt),
+ },
+ ],
+ }),
+ {status: 200},
+ ),
+ ),
+ );
+ return {sourcePath};
}
describe('upgrade() — receipts', () => {
@@ -72,6 +158,71 @@ describe('upgrade() — receipts', () => {
}
});
+ it('runs registry-only mode without --from', async () => {
+ fs.mkdirSync(path.join(tmpDir, 'src'), {recursive: true});
+
+ const res = await upgrade({registry: true, apply: false}, {cwd: tmpDir});
+
+ expect(res).toMatchObject({
+ type: 'upgrade.registry',
+ data: {applied: false, found: 0, conflicts: 0, failed: 0},
+ });
+ });
+
+ it('requires installed Astryx packages when receipts exist', async () => {
+ writeRegistryFixture(tmpDir);
+
+ await expect(
+ upgrade({registry: true, apply: true}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: ERROR_CODES.ERR_VERSION_DETECT});
+ });
+
+ it('rejects combining --list with registry-only mode', async () => {
+ await expect(
+ upgrade({list: true, registry: true}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: ERROR_CODES.ERR_INVALID_ARGUMENT});
+ });
+
+ it('checks receipts on the up-to-date short circuit', async () => {
+ writePkg(tmpDir);
+ writeInstalledCore(tmpDir, '0.6.0');
+ const {sourcePath} = writeRegistryFixture(tmpDir);
+
+ const res = await upgrade({from: '0.6.0', apply: true}, {cwd: tmpDir});
+
+ expect(res).toMatchObject({
+ type: 'upgrade.status',
+ data: {
+ status: 'up_to_date',
+ registryCompositions: {found: 1, updated: 1, conflicts: 0},
+ },
+ });
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('new\n');
+ });
+
+ it('checks receipts on the no-codemods short circuit', async () => {
+ writePkg(tmpDir);
+ writeInstalledCore(tmpDir, '99.0.0');
+ const {sourcePath} = writeRegistryFixture(tmpDir, {version: '99.0.0'});
+
+ const res = await upgrade({from: '98.0.0', apply: false}, {cwd: tmpDir});
+
+ expect(res).toMatchObject({
+ type: 'upgrade.status',
+ data: {
+ status: 'no_codemods',
+ registryCompositions: {found: 1, wouldUpdate: 1},
+ },
+ });
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe('old\n');
+ });
+
+ it('rejects migration flags in registry-only mode', async () => {
+ await expect(
+ upgrade({registry: true, from: '0.5.0', apply: true}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: ERROR_CODES.ERR_INVALID_ARGUMENT});
+ });
+
it('honors cwd: refreshes a stale agent-docs block on the up-to-date path (--apply)', async () => {
// from == installed → up_to_date short-circuit (returns before the codemod
// runner), so this exercises detection + agent-docs purely via the cwd
@@ -106,7 +257,9 @@ describe('upgrade() — receipts', () => {
expect(res.data.status).toBe('up_to_date');
expect(res.data.agentDocs.action).toBe('would-refresh');
expect(res.data.agentDocs.refreshed).toBe(false);
- expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(before);
+ expect(fs.readFileSync(path.join(tmpDir, 'AGENTS.md'), 'utf-8')).toBe(
+ before,
+ );
});
it('returns upgrade.run for an applicable range', async () => {
@@ -117,7 +270,10 @@ describe('upgrade() — receipts', () => {
fs.writeFileSync(path.join(tmpDir, 'src', 'index.ts'), 'const x = 1;\n');
process.chdir(tmpDir);
- const res = await upgrade({from: '0.0.1', apply: false, path: 'src'}, {cwd: tmpDir});
+ const res = await upgrade(
+ {from: '0.0.1', apply: false, path: 'src'},
+ {cwd: tmpDir},
+ );
expect(res.type).toBe('upgrade.run');
expect(res.data.from).toBe('0.0.1');
@@ -125,6 +281,29 @@ describe('upgrade() — receipts', () => {
expect(typeof res.data.codemods).toBe('number');
expect(res.data.agentDocs).toBeDefined();
});
+
+ it('checks receipts on a normal codemod run', async () => {
+ writePkg(tmpDir);
+ writeInstalledCore(tmpDir, '0.0.15');
+ const {sourcePath} = writeRegistryFixture(tmpDir, {
+ base: "export const value = 'old';\n",
+ latest: "export const value = 'new';\n",
+ version: '0.0.15',
+ });
+
+ const res = await upgrade(
+ {from: '0.0.1', apply: false, path: 'src'},
+ {cwd: tmpDir},
+ );
+
+ expect(res).toMatchObject({
+ type: 'upgrade.run',
+ data: {registryCompositions: {found: 1, wouldUpdate: 1}},
+ });
+ expect(fs.readFileSync(sourcePath, 'utf8')).toBe(
+ "export const value = 'old';\n",
+ );
+ });
});
describe('upgrade() — honors cwd for codemod scanning (no chdir)', () => {
@@ -140,14 +319,19 @@ describe('upgrade() — honors cwd for codemod scanning (no chdir)', () => {
// Capture stdout: the runner logs the directory it scans. Enabling the
// shared logger keeps the runner non-silent so its scan line is emitted.
const out = [];
- vi.spyOn(console, 'log').mockImplementation((...a) => out.push(a.join(' ')));
+ vi.spyOn(console, 'log').mockImplementation((...a) =>
+ out.push(a.join(' ')),
+ );
vi.spyOn(process.stdout, 'write').mockImplementation(c => {
out.push(typeof c === 'string' ? c : c.toString());
return true;
});
logger.setSilent(false);
- const res = await upgrade({from: '0.0.1', apply: false, path: 'src'}, {cwd: tmpDir});
+ const res = await upgrade(
+ {from: '0.0.1', apply: false, path: 'src'},
+ {cwd: tmpDir},
+ );
const joined = out.join('\n');
expect(res.type).toBe('upgrade.run');
@@ -167,13 +351,17 @@ describe('upgrade() — errors throw AstryxError', () => {
name: 'AstryxError',
code: ERROR_CODES.ERR_INVALID_ARGUMENT,
});
- await expect(upgrade({}, {cwd: tmpDir})).rejects.toThrow(/Missing required --from/);
+ await expect(upgrade({}, {cwd: tmpDir})).rejects.toThrow(
+ /Missing required --from/,
+ );
});
it('invalid --from → ERR_INVALID_VERSION', async () => {
writePkg(tmpDir);
writeInstalledCore(tmpDir, '0.0.15');
- await expect(upgrade({from: 'not-a-version'}, {cwd: tmpDir})).rejects.toMatchObject({
+ await expect(
+ upgrade({from: 'not-a-version'}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({
code: ERROR_CODES.ERR_INVALID_VERSION,
});
});
@@ -196,7 +384,9 @@ describe('upgrade() — silent by default (noopLogger)', () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
- const outSpy = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ const outSpy = vi
+ .spyOn(process.stdout, 'write')
+ .mockImplementation(() => true);
const res = await upgrade({from: '0.0.15', apply: true}, {cwd: tmpDir});
diff --git a/packages/cli/api/upgrade/upgrade.type.mjs b/packages/cli/api/upgrade/upgrade.type.mjs
index 7c0a05524d..0c659c7718 100644
--- a/packages/cli/api/upgrade/upgrade.type.mjs
+++ b/packages/cli/api/upgrade/upgrade.type.mjs
@@ -8,6 +8,7 @@
* ------------------------------------------------------------------
* xds --json upgrade --list -> upgrade.list
* xds --json upgrade [--apply] -> upgrade.run
+ * xds --json upgrade --registry [--apply] -> upgrade.registry
* xds --json upgrade (status short-circuit) -> upgrade.status
* (version detection failure) -> CLIError
*/
@@ -47,6 +48,52 @@
* @property {'refreshed' | 'would-refresh' | 'nudge-init' | 'error' | 'none'} action
*/
+/**
+ * One copied file tracked by a ShadCN composition receipt.
+ * @typedef {object} RegistryCompositionFileSummary
+ * @property {string} path
+ * @property {'current'|'user-modified'|'would-update'|'updated'|'would-merge'|'merged'|'would-refresh-receipt'|'receipt-refreshed'|'conflict'|'missing'|'invalid'|'target-changed'} action
+ * @property {string} [message]
+ * @property {string} [conflictFile]
+ */
+
+/**
+ * One ShadCN registry item checked during upgrade.
+ * @typedef {object} RegistryCompositionItemSummary
+ * @property {string} item
+ * @property {string} [path]
+ * @property {'current'|'user-modified'|'would-update'|'updated'|'would-merge'|'merged'|'would-refresh-receipt'|'receipt-refreshed'|'conflict'|'invalid'|'fetch-error'|'write-error'} action
+ * @property {string} [message]
+ * @property {RegistryCompositionFileSummary[]} files
+ */
+
+/**
+ * Aggregate receipt for ShadCN-copied composition reconciliation.
+ * @typedef {object} RegistryCompositionSummary
+ * @property {boolean} applied
+ * @property {boolean} ok False when conflicts, missing files, invalid receipts, or failures remain.
+ * @property {number} found
+ * @property {number} current Item count with no upstream source change.
+ * @property {number} wouldUpdate Item count with pristine updates in dry-run.
+ * @property {number} updated Item count with pristine updates applied.
+ * @property {number} wouldMerge Item count with clean merges in dry-run.
+ * @property {number} merged Item count with clean merges applied.
+ * @property {number} wouldRefreshReceipt Item count with metadata-only refreshes in dry-run.
+ * @property {number} receiptsRefreshed Item count with metadata-only refreshes applied.
+ * @property {number} conflicts Item count with at least one unresolved source conflict.
+ * @property {number} missing Per-file count of deleted or moved source files.
+ * @property {number} invalid Count of invalid receipts, unreadable sources, or changed targets.
+ * @property {number} failed Item count with fetch or write failures.
+ * @property {RegistryCompositionItemSummary[]} items
+ */
+
+/**
+ * xds --json upgrade --registry [--apply]
+ * @typedef {object} UpgradeRegistryResponse
+ * @property {'upgrade.registry'} type
+ * @property {RegistryCompositionSummary} data
+ */
+
/**
* xds --json upgrade [--apply]
* @typedef {object} UpgradeRunResponse
@@ -58,6 +105,7 @@
* @property {string[]} data.integrations Integration packages processed in this upgrade (by name/spec).
* @property {boolean} data.agentDocsRefreshed
* @property {AgentDocsSummary} data.agentDocs
+ * @property {RegistryCompositionSummary} [data.registryCompositions]
* @property {number} [data.filesChanged] Total files changed across core + integration codemods (apply mode).
* @property {number} [data.transformsApplied] Total transforms that reported a change.
* @property {Array<{file: string, codemod: string, error: string}>} [data.errors] Per-codemod errors, when any codemod failed.
@@ -76,13 +124,13 @@
*
* @typedef {object} UpgradeStatusResponse
* @property {'upgrade.status'} type
- * @property {{status: 'up_to_date', from: string, to: string, agentDocs: AgentDocsSummary} | {status: 'no_codemods', from: string, to: string, agentDocs: AgentDocsSummary} | {status: 'config_fixable', from: string, to: string, configError: string, configCodemods: string[], suggestedCommand: string, message: string, note: string, agentDocs: AgentDocsSummary}} data
+ * @property {{status: 'up_to_date', from: string, to: string, agentDocs: AgentDocsSummary, registryCompositions?: RegistryCompositionSummary} | {status: 'no_codemods', from: string, to: string, agentDocs: AgentDocsSummary, registryCompositions?: RegistryCompositionSummary} | {status: 'config_fixable', from: string, to: string, configError: string, configCodemods: string[], suggestedCommand: string, message: string, note: string, agentDocs: AgentDocsSummary}} data
*/
/**
* Options for `upgrade()`.
* @typedef {object} UpgradeOptions
- * @property {string} [from] Version before the dependency bump (required unless `list`).
+ * @property {string} [from] Version before the dependency bump (required unless `list` or `registry`).
* @property {boolean} [apply] Write changes to disk (default: dry-run).
* @property {boolean} [force] Run codemods even if `from` >= installed.
* @property {string} [codemod] Run a single named transform.
@@ -90,6 +138,7 @@
* @property {string[]} [integration] Explicit integration package names / file paths.
* @property {string} [path] Source directory to scan (default `./src`).
* @property {boolean} [installDeps] Auto-install jscodeshift without prompting.
+ * @property {boolean} [registry] Reconcile only ShadCN-copied compositions; `from` is not required.
* @property {boolean} [list] Return the available codemods instead of running.
*/
diff --git a/packages/cli/assets/docs/shadcn-compatibility.doc.mjs b/packages/cli/assets/docs/shadcn-compatibility.doc.mjs
index c81ff72f5e..e8289b252f 100644
--- a/packages/cli/assets/docs/shadcn-compatibility.doc.mjs
+++ b/packages/cli/assets/docs/shadcn-compatibility.doc.mjs
@@ -15,7 +15,7 @@ export const docs = {
content: [
{
type: 'prose',
- text: 'Astryx supports the shadcn Registry as a compatibility and distribution protocol. This does not make Astryx a shadcn-based library. The Astryx packages remain the implementation and the Astryx CLI remains the primary interface for discovery, composition, theming, validation, and upgrades.',
+ text: 'This guide is for existing shadcn users who want to add Astryx without replacing their current toolchain. Astryx supports the shadcn Registry as a compatibility and distribution protocol. The Astryx packages remain the implementation and the Astryx CLI remains the richer interface for discovery, composition, theming, validation, and upgrades.',
},
{
type: 'prose',
@@ -23,7 +23,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'This compatibility path is experimental. Use it to test incremental adoption in an existing shadcn-style application. Do not treat the registry URL or generated catalog as a stable support promise until Astryx announces it as supported.',
+ text: 'The registry is published as-is for existing shadcn users. Issues are welcome in the Astryx repository, with no response-time promise.',
},
],
},
@@ -66,17 +66,17 @@ export const docs = {
[
'Showcase or example',
'Editable application-level composition source that imports Astryx packages',
- 'Your app owns the composition; Astryx owns the imported components',
+ 'Your app owns its edits; the adjacent Astryx receipt enables safe upgrades',
],
[
'Block',
'A larger editable composition plus its package dependencies',
- 'Your app owns the composition; Astryx owns the imported components',
+ 'Your app owns its edits; the adjacent Astryx receipt enables safe upgrades',
],
[
'Page',
'A complete editable page plus its package dependencies',
- 'Your app owns the page; Astryx owns the imported components',
+ 'Your app owns its edits; the adjacent Astryx receipt enables safe upgrades',
],
],
},
@@ -128,7 +128,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'For an example, block, or page, the command writes editable TSX into your app. That TSX imports public Astryx package paths. It does not reach into package internals and it does not require a StyleX compiler in your app.',
+ text: 'For an example, block, or page, the command writes editable TSX plus a small adjacent `.astryx` receipt. The TSX imports public Astryx package paths. The receipt stores the exact installed base so a later upgrade can preserve your edits; it is not application code and should stay committed with the copied file.',
},
],
},
@@ -147,7 +147,8 @@ export const docs = {
astryx component Button
astryx template dashboard
astryx doctor
-astryx upgrade --apply`,
+astryx upgrade --registry
+astryx upgrade --registry --apply`,
},
],
},
@@ -159,8 +160,12 @@ astryx upgrade --apply`,
style: 'unordered',
items: [
'Package upgrades update Astryx components, hooks, behavior, accessibility, and compiled styles.',
- 'Copied examples, blocks, and pages are application code. They do not update automatically when the catalog changes.',
- 'The experimental catalog excludes unpublished packages because an external package manager cannot install them.',
+ 'A normal `astryx upgrade` also checks copied-composition receipts. Use `astryx upgrade --registry` to preview only those files; add `--apply` to write safe updates.',
+ 'Registry source must match the installed Astryx release. The command refuses to copy source from a newer or older release.',
+ 'An unchanged copied file updates automatically. Non-overlapping edits are three-way merged against the installed base.',
+ 'A conflicting edit leaves your file untouched and writes a separate `.astryx-conflict` file for review.',
+ 'A deleted or moved copied file is reported but never recreated or overwritten.',
+ 'The registry excludes unpublished packages because an external package manager cannot install them.',
'Your project needs a valid components.json and TypeScript configuration for the shadcn CLI to resolve target paths.',
'The compatibility layer is additive. It does not require replacing existing shadcn components or migrating the whole application.',
],
diff --git a/packages/cli/authoring/shadcn/receipt.mjs b/packages/cli/authoring/shadcn/receipt.mjs
new file mode 100644
index 0000000000..808947ad4e
--- /dev/null
+++ b/packages/cli/authoring/shadcn/receipt.mjs
@@ -0,0 +1,182 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Shared provenance receipt contract for ShadCN-copied Astryx source.
+ * @input A stable registry identity and the exact copied source bytes.
+ * @output Validated, deterministic receipts used by registry generation and upgrade.
+ * @position Protocol boundary between the public ShadCN registry and `astryx upgrade`.
+ */
+
+import {createHash} from 'node:crypto';
+import * as path from 'node:path';
+import {z} from 'zod';
+
+export const REGISTRY_RECEIPT_SCHEMA_VERSION = 1;
+export const PUBLIC_SHADCN_REGISTRY_ORIGIN = 'https://astryx.atmeta.com/shadcn';
+
+const receiptTargetSchema = z
+ .string()
+ .regex(/^\.\.\/[^/\\]+$/, 'must point to one adjacent source file');
+
+const registryFilePathSchema = z
+ .string()
+ .min(1)
+ .refine(value => !path.posix.isAbsolute(value), 'must be relative')
+ .refine(value => !value.includes('\\'), 'must use forward slashes')
+ .refine(
+ value =>
+ value
+ .split('/')
+ .every(
+ segment => segment !== '' && segment !== '.' && segment !== '..',
+ ),
+ 'must be a normalized registry path',
+ );
+
+const registryPathSchema = z
+ .string()
+ .regex(
+ /^[a-z0-9]+(?:-[a-z0-9]+)*(?:\/[a-z0-9]+(?:-[a-z0-9]+)*)*$/,
+ 'must be a lowercase registry path',
+ );
+
+const sourceVersionSchema = z
+ .string()
+ .regex(
+ /^(?:canary|\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/,
+ 'must be canary or an exact semantic version',
+ );
+
+export const registryReceiptSchema = z
+ .object({
+ schemaVersion: z.literal(REGISTRY_RECEIPT_SCHEMA_VERSION),
+ item: z
+ .object({
+ name: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
+ path: registryPathSchema,
+ aliases: z.array(registryPathSchema),
+ kind: z.enum(['showcase', 'example', 'block', 'page']),
+ })
+ .strict(),
+ source: z
+ .object({
+ package: z.literal('@astryxdesign/cli'),
+ version: sourceVersionSchema,
+ })
+ .strict(),
+ files: z
+ .array(
+ z
+ .object({
+ id: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
+ target: receiptTargetSchema,
+ registryTarget: registryFilePathSchema,
+ registryPath: registryFilePathSchema,
+ sha256: z.string().regex(/^[a-f0-9]{64}$/),
+ content: z.string(),
+ })
+ .strict(),
+ )
+ .min(1),
+ })
+ .strict()
+ .superRefine((receipt, context) => {
+ const identities = [
+ {label: 'id', values: receipt.files.map(file => file.id)},
+ {label: 'target', values: receipt.files.map(file => file.target)},
+ {
+ label: 'registryTarget',
+ values: receipt.files.map(file => file.registryTarget),
+ },
+ {
+ label: 'registryPath',
+ values: receipt.files.map(file => file.registryPath),
+ },
+ ];
+ for (const {label, values} of identities) {
+ if (new Set(values).size !== values.length) {
+ context.addIssue({
+ code: 'custom',
+ path: ['files'],
+ message: `receipt file ${label} values must be unique`,
+ });
+ }
+ }
+ });
+
+const registryUpgradeFileSchema = z
+ .object({
+ path: registryFilePathSchema,
+ type: z.string().min(1),
+ target: registryFilePathSchema.optional(),
+ content: z.string(),
+ })
+ .passthrough();
+
+const registryUpgradeItemSchema = z
+ .object({
+ name: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
+ type: z.enum(['registry:block', 'registry:page']),
+ files: z.array(registryUpgradeFileSchema).min(1),
+ })
+ .passthrough();
+
+/** @param {unknown} input */
+export function parseRegistryUpgradeItem(input) {
+ return registryUpgradeItemSchema.parse(input);
+}
+
+/** @param {string} content */
+export function registryContentHash(content) {
+ return createHash('sha256').update(content, 'utf8').digest('hex');
+}
+
+/**
+ * Place a receipt beside its copied source so custom ShadCN aliases resolve
+ * both files through the same root.
+ * @param {string} sourceTarget
+ * @param {string} itemName
+ */
+export function registryReceiptTarget(sourceTarget, itemName) {
+ const sourceDir = path.posix.dirname(sourceTarget);
+ return path.posix.join(sourceDir, '.astryx', `${itemName}.json`);
+}
+
+/**
+ * @param {{
+ * item: {name: string, path: string, aliases: string[], kind: 'showcase'|'example'|'block'|'page'},
+ * sourceVersion: string,
+ * receiptTarget: string,
+ * files: Array<{id: string, target: string, registryPath: string, content: string}>,
+ * }} input
+ */
+export function createRegistryReceipt(input) {
+ const receiptDir = path.posix.dirname(input.receiptTarget);
+ const receipt = {
+ schemaVersion: REGISTRY_RECEIPT_SCHEMA_VERSION,
+ item: input.item,
+ source: {
+ package: '@astryxdesign/cli',
+ version: input.sourceVersion,
+ },
+ files: input.files.map(file => ({
+ id: file.id,
+ target: path.posix.relative(receiptDir, file.target),
+ registryTarget: file.target,
+ registryPath: file.registryPath,
+ sha256: registryContentHash(file.content),
+ content: file.content,
+ })),
+ };
+ return registryReceiptSchema.parse(receipt);
+}
+
+/** @param {unknown} input */
+export function parseRegistryReceipt(input) {
+ return registryReceiptSchema.parse(input);
+}
+
+/** @param {ReturnType<typeof createRegistryReceipt>} receipt */
+export function serializeRegistryReceipt(receipt) {
+ return `${JSON.stringify(receipt, null, 2)}\n`;
+}
diff --git a/packages/cli/authoring/shadcn/receipt.test.mjs b/packages/cli/authoring/shadcn/receipt.test.mjs
new file mode 100644
index 0000000000..e605001c94
--- /dev/null
+++ b/packages/cli/authoring/shadcn/receipt.test.mjs
@@ -0,0 +1,90 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {
+ createRegistryReceipt,
+ parseRegistryReceipt,
+ registryContentHash,
+ registryReceiptTarget,
+ serializeRegistryReceipt,
+} from './receipt.mjs';
+
+function receipt() {
+ const target = 'components/astryx/examples/ButtonExample.tsx';
+ const receiptTarget = registryReceiptTarget(target, 'example-button-basic');
+ return createRegistryReceipt({
+ item: {
+ name: 'example-button-basic',
+ path: 'examples/button/basic',
+ aliases: ['examples/button/old-basic'],
+ kind: 'example',
+ },
+ sourceVersion: '0.6.0',
+ receiptTarget,
+ files: [
+ {
+ id: 'primary',
+ target,
+ registryPath: 'registry/example-button-basic/ButtonExample.tsx',
+ content: 'export default function Example() { return null; }\n',
+ },
+ ],
+ });
+}
+
+describe('ShadCN registry receipts', () => {
+ it('places a unique receipt beside the copied source', () => {
+ expect(
+ registryReceiptTarget(
+ 'components/astryx/examples/ButtonExample.tsx',
+ 'example-button-basic',
+ ),
+ ).toBe('components/astryx/examples/.astryx/example-button-basic.json');
+ });
+
+ it('records the installed base bytes and a relative target', () => {
+ const value = receipt();
+ expect(value.files[0]).toMatchObject({
+ id: 'primary',
+ target: '../ButtonExample.tsx',
+ registryTarget: 'components/astryx/examples/ButtonExample.tsx',
+ registryPath: 'registry/example-button-basic/ButtonExample.tsx',
+ sha256: registryContentHash(value.files[0].content),
+ });
+ expect(
+ parseRegistryReceipt(JSON.parse(serializeRegistryReceipt(value))),
+ ).toEqual(value);
+ });
+
+ it('rejects duplicate file identities', () => {
+ const value = receipt();
+ expect(() =>
+ parseRegistryReceipt({
+ ...value,
+ files: [value.files[0], {...value.files[0]}],
+ }),
+ ).toThrow(/must be unique/);
+ });
+
+ it('rejects traversal and corrupt hashes', () => {
+ const value = receipt();
+ expect(() =>
+ parseRegistryReceipt({
+ ...value,
+ files: [{...value.files[0], target: '../../outside.tsx'}],
+ }),
+ ).toThrow(/adjacent source file/);
+ expect(() =>
+ parseRegistryReceipt({
+ ...value,
+ source: {...value.source, version: '0.6.0\n<<<<<<< injected'},
+ }),
+ ).toThrow(/semantic version/);
+ expect(() =>
+ parseRegistryReceipt({
+ ...value,
+ files: [{...value.files[0], sha256: 'not-a-hash'}],
+ }),
+ ).toThrow();
+ });
+});
diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjs
index 81f7d2c64f..df19e3c141 100644
--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs
@@ -13,18 +13,20 @@ export const doc = {
name: 'upgrade',
displayName: 'astryx upgrade',
namespace: 'cli',
- summary: 'Run codemods to migrate between versions',
+ summary: 'Migrate versions and update ShadCN-copied compositions',
description:
'Migrates project source from a previous Astryx version to the installed one by ' +
'running the registered codemods, and refreshes the fully rendered managed ' +
'agent-docs block when Core or configured integration guidance changes. ' +
- 'Dry-run by default; --apply writes the block after selected codemods and hooks succeed.',
+ 'Dry-run by default. --apply writes codemod and receipt changes, runs hooks, then refreshes agent docs. ' +
+ 'ShadCN-copied compositions are checked automatically during a normal upgrade, or alone with --registry.',
fn: 'upgrade',
options: [
{
flag: '--from <version>',
param: 'options.from',
- description: 'Previous version before the dependency upgrade',
+ description:
+ 'Previous version before the dependency upgrade; required unless --list or --registry is set',
},
{
flag: '--apply',
@@ -69,6 +71,13 @@ export const doc = {
description: 'Auto-install jscodeshift without prompting',
default: false,
},
+ {
+ flag: '--registry',
+ param: 'options.registry',
+ description:
+ 'Only reconcile ShadCN-copied compositions; --from is not required',
+ default: false,
+ },
{
flag: '--list',
param: 'options.list',
@@ -78,13 +87,17 @@ export const doc = {
],
examples: [
{label: 'List available codemods', cli: 'astryx upgrade --list --json'},
+ {
+ label: 'Update ShadCN-copied compositions',
+ cli: 'astryx upgrade --registry --apply',
+ },
{label: 'Apply a migration', cli: 'astryx upgrade --from 0.1.0 --apply'},
],
exitCodes: [
{code: 0, when: 'success (including dry-run previews)'},
{
code: 1,
- when: 'missing or invalid --from, a --path escape, an unknown codemod, or a codemod failure',
+ when: 'missing or invalid --from, a --path escape, an unknown codemod, a codemod failure, or unresolved registry items',
},
],
related: ['init', 'doctor'],
diff --git a/packages/cli/clients/cli/commands/upgrade.mjs b/packages/cli/clients/cli/commands/upgrade.mjs
index 782af1b224..accdcd0cdb 100644
--- a/packages/cli/clients/cli/commands/upgrade.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.mjs
@@ -35,7 +35,7 @@ export function registerUpgrade(program) {
const json = program.opts().json || false;
logger.setSilent(json);
- /** @type {import('../../../api/upgrade/upgrade.type.mjs').UpgradeListResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeStatusResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeRunResponse} */
+ /** @type {import('../../../api/upgrade/upgrade.type.mjs').UpgradeListResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeRegistryResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeStatusResponse | import('../../../api/upgrade/upgrade.type.mjs').UpgradeRunResponse} */
let result;
try {
result = await upgradeApi(options, {cwd: process.cwd()});
@@ -55,6 +55,17 @@ export function registerUpgrade(program) {
if (json) jsonOut(result);
+ const registrySummary =
+ result.type === 'upgrade.registry'
+ ? result.data
+ : result.type === 'upgrade.run'
+ ? result.data.registryCompositions
+ : result.type === 'upgrade.status' &&
+ 'registryCompositions' in result.data
+ ? result.data.registryCompositions
+ : undefined;
+ if (registrySummary && !registrySummary.ok) process.exitCode = 1;
+
// `--list` is the one lookup here: which migrations exist for the
// range. Everything else migrates the project — an effect, reported by
// the receipt rather than counted.
diff --git a/packages/cli/clients/cli/commands/upgrade.test.mjs b/packages/cli/clients/cli/commands/upgrade.test.mjs
index 3ddfd80e2c..95f59ee5d3 100644
--- a/packages/cli/clients/cli/commands/upgrade.test.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.test.mjs
@@ -16,6 +16,7 @@ let originalCwd;
let logCalls;
let stdoutCalls;
let exitCode;
+let previousProcessExitCode;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-upgrade-test-'));
@@ -24,6 +25,8 @@ beforeEach(() => {
logCalls = [];
stdoutCalls = [];
exitCode = undefined;
+ previousProcessExitCode = process.exitCode;
+ process.exitCode = undefined;
vi.spyOn(console, 'log').mockImplementation((...args) => {
logCalls.push(args.join(' '));
});
@@ -43,6 +46,7 @@ beforeEach(() => {
afterEach(() => {
process.chdir(originalCwd);
fs.rmSync(tmpDir, {recursive: true, force: true});
+ process.exitCode = previousProcessExitCode;
vi.restoreAllMocks();
});
@@ -133,6 +137,43 @@ describe('upgrade argument validation', () => {
expect(exitCode).toBe(1);
});
+ it('allows receipt-only upgrades without --from', async () => {
+ writeSourceFile();
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--registry',
+ '--path',
+ 'src',
+ ]);
+
+ expect(result).toMatchObject({
+ type: 'upgrade.registry',
+ data: {found: 0, applied: false},
+ });
+ expect(exitCode).toBeUndefined();
+ });
+
+ it('exits 1 while preserving the receipt for unresolved registry items', async () => {
+ writeInstalledCore('0.6.0');
+ fs.mkdirSync(path.join(tmpDir, 'src', '.astryx'), {recursive: true});
+ fs.writeFileSync(path.join(tmpDir, 'src', '.astryx', 'broken.json'), '{}');
+
+ const result = await runJson([
+ '--json',
+ 'upgrade',
+ '--registry',
+ '--path',
+ 'src',
+ ]);
+
+ expect(result).toMatchObject({
+ type: 'upgrade.registry',
+ data: {ok: false, invalid: 1},
+ });
+ expect(process.exitCode).toBe(1);
+ });
+
it('rejects bogus --from values', async () => {
writePkg();
writeInstalledCore('0.0.15');
diff --git a/packages/cli/package.json b/packages/cli/package.json
index f478c2d62f..7f0089703d 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -102,6 +102,7 @@
"commander": "^12.1.0",
"jiti": "^2.7.0",
"jscodeshift": "^17.3.0",
+ "node-diff3": "3.2.1",
"postcss": "^8.5.23",
"postcss-selector-parser": "^7.1.5",
"zod": "^4.4.3"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3069088623..78c8a441de 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -665,6 +665,9 @@ importers:
jscodeshift:
specifier: ^17.3.0
version: 17.3.0
+ node-diff3:
+ specifier: 3.2.1
+ version: 3.2.1
postcss:
specifier: ^8.5.23
version: 8.5.25
@@ -5496,6 +5499,10 @@ packages:
sass:
optional: true
+ resolution: {integrity: sha512-eKZcJ8RtMQ3cIaA15EgmtwG927fYnRlhtdA4Q9HAcCpAZPQhhU2XptnTH9GeAkMiX2bAXxlJSAFa9shFbztPgw==}
+ engines: {bun: '>=1.3.10'}
+
resolution: {integrity: sha512-J6l92tKHX6w8Jy5nO1Vuc01NoIiRGi/d6qBKVxh+IQ8Cr3b6HbVNfKiF8ZpFKufTwpwxMmce2W3iQZ861ZRyTg==}
engines: {node: '>=18'}
@@ -11238,6 +11245,8 @@ snapshots:
- '@types/node'
- babel-plugin-macros
+