Skip to content

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

TypeScript

docsite: unify Lab integration plumbing (admission, automaticity, coverage report) (#6800)

Xinzi Zhou2bdba849d0b6
diff --git a/apps/docsite/scripts/generate-data.mjs b/apps/docsite/scripts/generate-data.mjs
index d334af5dc8..6b277911e0 100644
--- a/apps/docsite/scripts/generate-data.mjs
+++ b/apps/docsite/scripts/generate-data.mjs
@@ -30,6 +30,7 @@ import {
template as queryTemplates,
} from '@astryxdesign/cli/api';
import docsiteConfig from '../astryx.config.mjs';
+import {integrationContentEnabled} from '../src/lib/integrationTargets.mjs';
import {expandWorkspaceDirs} from '../../../scripts/lib/workspace-globs.mjs';
import {
buildTypeDefinitionIndex,
@@ -92,7 +93,9 @@ function writeRegistry(filename, content) {
* published package snapshot and never loads workspace integrations.
*/
function discoverConfiguredComponentPackages() {
- if (DOCSITE_TARGET !== 'canary') {
+ // Same gate as generate-scope.mjs (src/lib/integrationTargets.mjs): only the
+ // canary target ever loads workspace integration packages.
+ if (!integrationContentEnabled(DOCSITE_TARGET)) {
return new Set();
}
@@ -1480,7 +1483,7 @@ async function generateBlockRegistry() {
});
}
- if (DOCSITE_TARGET === 'canary') {
+ if (integrationContentEnabled(DOCSITE_TARGET)) {
const templateList = await queryTemplates(undefined, {
list: true,
type: 'block',
diff --git a/apps/docsite/scripts/generate-playground-types.mjs b/apps/docsite/scripts/generate-playground-types.mjs
index d41d480ab1..76d73ed4f1 100644
--- a/apps/docsite/scripts/generate-playground-types.mjs
+++ b/apps/docsite/scripts/generate-playground-types.mjs
@@ -2,8 +2,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * Generates a JSON bundle of @astryxdesign/core, React, StyleX, icon, and
- * Recharts declarations for the playground's Monaco editor.
+ * Generates a JSON bundle of @astryxdesign/core, React, StyleX, icon,
+ * Recharts, and canary integration-package declarations for the playground's
+ * Monaco editor.
* Output: public/playground-types.json
*
* Structure: { "@astryxdesign/core": { "Button/index.d.ts": "...", ... } }
@@ -23,6 +24,9 @@ import {
import {createRequire} from 'node:module';
import {join, dirname, relative} from 'node:path';
import {fileURLToPath} from 'node:url';
+import docsiteConfig from '../astryx.config.mjs';
+import {getTarget} from './resolve-content-root.mjs';
+import {integrationPackagesForTarget} from '../src/lib/integrationTargets.mjs';
// Resolves from this script, so docsite's own dependencies are found wherever
// the installer put them. Throws if one is missing, rather than emitting a
@@ -306,6 +310,20 @@ function buildThemeTypes() {
return files;
}
+// Integration packages the canary preview scope exposes (the same shared gate
+// generate-scope.mjs uses, so production declares none). Declared as shorthand
+// ambient modules: imports resolve, typed as `any`, so the editor shows no
+// unresolved-module error on code that renders. Like the theme packages, their
+// dist is not built in CI's docsite-test job, so real declarations are left
+// for a follow-up.
+function buildIntegrationTypes() {
+ const files = {};
+ for (const pkg of integrationPackagesForTarget(getTarget(), docsiteConfig)) {
+ files[pkg] = {'index.d.ts': `declare module '${pkg}';\n`};
+ }
+ return files;
+}
+
// Runtime-only aliases the scope also serves: `next/image` renders a plain
// <img>, and bare `stylex` is the same object as `@stylexjs/stylex`.
const nextImageTypes = `
@@ -326,12 +344,16 @@ const heroiconTypes = buildHeroiconTypes();
const rechartsTypes = buildRechartsTypes();
const lucideTypes = buildLucideTypes();
const themeTypes = buildThemeTypes();
+const integrationTypes = buildIntegrationTypes();
console.log(
`Generated Lucide types: ${(lucideTypes['index.d.ts'].match(/: LucideIcon;/g) ?? []).length} icon exports`,
);
console.log(
`Generated theme types: ${Object.keys(themeTypes).length} packages`,
);
+console.log(
+ `Generated integration types: ${Object.keys(integrationTypes).length} packages`,
+);
console.log(
`Generated heroicon types: ${Object.keys(heroiconTypes).length} variants`,
);
@@ -349,6 +371,7 @@ const output = {
'lucide-react': lucideTypes,
'next/image': {'index.d.ts': nextImageTypes},
...themeTypes,
+ ...integrationTypes,
};
const json = JSON.stringify(output);
diff --git a/apps/docsite/scripts/generate-scope.mjs b/apps/docsite/scripts/generate-scope.mjs
index 7341d2aa31..64800cdae6 100644
--- a/apps/docsite/scripts/generate-scope.mjs
+++ b/apps/docsite/scripts/generate-scope.mjs
@@ -4,7 +4,10 @@
/**
* Generates apps/docsite/src/generated/playground-scope.ts
*
- * Maps every Astryx module available in the playground preview iframe.
+ * Maps Core exports and configured canary integrations into the preview iframe.
+ * @input Core package exports, docsite integrations, and the content target
+ * @output The runtime module scope used by copyable Playground examples
+ * @position Build-time companion to component and block registry generation
* This runs as part of `pnpm generate` (before dev/build) so new components
* are picked up automatically — no manual maintenance needed.
*
@@ -14,11 +17,20 @@
import {readFileSync, writeFileSync, mkdirSync} from 'node:fs';
import {dirname, resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
+import docsiteConfig from '../astryx.config.mjs';
+import {getTarget} from './resolve-content-root.mjs';
+import {integrationPackagesForTarget} from '../src/lib/integrationTargets.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, '..');
const CORE_PKG = resolve(ROOT, '../../packages/core/package.json');
const OUT = resolve(ROOT, 'src/generated/playground-scope.ts');
+// Shared with generate-data.mjs so the canary-only admission rule for
+// integration packages cannot drift between the two generators.
+const integrationPackages = integrationPackagesForTarget(
+ getTarget(),
+ docsiteConfig,
+);
const HEADER = `// Copyright (c) Meta Platforms, Inc. and affiliates.
@@ -250,6 +262,13 @@ for (const {specifier, identifier} of nestedModules) {
}
lines.push('');
+// Use the same configured package roots as the canary component/block catalog.
+// Otherwise an example's import silently resolves to an empty placeholder.
+for (const [index, pkg] of integrationPackages.entries()) {
+ lines.push(`import * as Integration${index} from '${pkg}';`);
+}
+lines.push('');
+
// ── Theme imports ──────────────────────────────────────────────────────
for (const t of SCOPE_THEMES) {
lines.push(`import {${t.name}} from '${t.pkg}${t.subpath}';`);
@@ -346,6 +365,24 @@ lines.push(' stylex: {default: stylexMock, ...stylexMock},');
// Recharts comes before Astryx so Astryx components win global name collisions.
lines.push(' recharts: Recharts,');
+// Core entries follow these so Core keeps precedence for unqualified globals.
+//
+// Whole-package admission is deliberate (owner-ratified): every export of a
+// configured integration is available so a NEW integration component needs no
+// scope edits. Each package keeps its own namespace entry, so QUALIFIED
+// imports (`import {Chart} from '@astryxdesign/charts'`) always resolve to
+// their own package. For UNQUALIFIED globals the preview runner iterates this
+// map in insertion order with later-wins (see runner.ts buildGlobalScope), so
+// on shared export names a later-configured integration shadows an earlier
+// one — @astryxdesign/lab and @astryxdesign/charts currently share 14 names
+// (Chart, ChartAxis, ChartGrid, ChartTooltip, ChartLegend, useChart,
+// useChartColors, getChartColors, getChartColorsFromResolver, compactNumber,
+// currency, percent, shortDate, monthYear), which charts wins — and the Core
+// entries below shadow every integration. Covered by playground-scope.test.ts.
+for (const [index, pkg] of integrationPackages.entries()) {
+ lines.push(` '${pkg}': Integration${index},`);
+}
+
// themes
for (const t of SCOPE_THEMES) {
lines.push(` '${t.pkg}': {default: ${t.name}, ${t.name}},`);
@@ -398,6 +435,7 @@ writeFileSync(OUT, lines.join('\n'));
console.log(`✓ Generated ${OUT}`);
console.log(` ${components.length} components`);
console.log(` ${nestedModules.length} nested modules`);
+console.log(` ${integrationPackages.length} integration packages`);
console.log(` ${SCOPE_THEMES.length} themes`);
console.log(
` lucide-react icons + ${HEROICON_VARIANTS.length} heroicon variants`,
diff --git a/apps/docsite/src/__tests__/example-automaticity.test.ts b/apps/docsite/src/__tests__/example-automaticity.test.ts
new file mode 100644
index 0000000000..d7eb4a5cf1
--- /dev/null
+++ b/apps/docsite/src/__tests__/example-automaticity.test.ts
@@ -0,0 +1,148 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration-block automaticity proof (discovery seam).
+ *
+ * The contract: once an integration package declares its templates root,
+ * documenting a NEW example needs exactly two authored files — a same-stem
+ * `<Name>.tsx` + `<Name>.doc.mjs` pair in that root — and ZERO edits anywhere
+ * else (no astryx.config change, no generator change, no hand-maintained
+ * catalog). The probe uses @astryxdesign/charts, whose `templates: './blocks'`
+ * root already holds real blocks; Lab declares its root together with its
+ * first block, because `integration pack --check` rejects an empty root.
+ *
+ * SCOPE: this file proves the DISCOVERY seam only — it writes a temporary
+ * fixture pair into packages/charts/blocks and asserts the exact CLI API call
+ * `generate-data.mjs` makes (`template --list/--show`, same cwd) returns it.
+ * It does not re-run generation. Separate, narrower guarantees exist around
+ * it, and nothing proves more than their sum:
+ * 1. this file — generic CLI discovery of a new authored pair;
+ * 2. example-coverage.test.ts — every authored, valid Lab block appears in
+ * the generated blockRegistry (blockRegistry only);
+ * 3. playground-scope.test.ts — imports used by registered integration
+ * blocks resolve in the generated Playground scope.
+ * General loader completeness for a future block's showcase/example
+ * projection is NOT proved by any of these.
+ *
+ * The fixture files exist only while this file runs (created in beforeAll,
+ * removed in afterAll; leftovers from a killed run are cleaned first). The
+ * AUTOMATICITY_FIXTURE_PREFIX is reserved so the example-coverage report,
+ * which walks the same directory in a parallel worker, ignores them.
+ *
+ * @input A temporary authored block pair in packages/charts/blocks and the CLI
+ * template listing API with the docsite's own working directory
+ * @output Proof that block authoring is registration-free for integrations
+ * @position Build-time docsite discovery verification
+ * Run: pnpm -F @astryxdesign/docsite test
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {afterAll, beforeAll, describe, expect, it} from 'vitest';
+import {template as queryTemplates} from '@astryxdesign/cli/api';
+import type {
+ TemplateListEntry,
+ TemplateListResponse,
+ TemplateShowResponse,
+} from '@astryxdesign/cli/api';
+import {AUTOMATICITY_FIXTURE_PREFIX} from '../lib/exampleCoverage.mjs';
+
+/** The api's declared envelope is `{type, data: unknown}`; narrow to the
+ * documented response typedefs for the two invocations this file makes. */
+async function listBlocks(cwd: string): Promise<TemplateListEntry[]> {
+ const response = (await queryTemplates(undefined, {
+ list: true,
+ type: 'block',
+ cwd,
+ })) as TemplateListResponse;
+ return response.data;
+}
+
+const DOCSITE_ROOT = path.resolve(__dirname, '../..');
+const PROBE_PACKAGE = '@astryxdesign/charts';
+const PROBE_BLOCKS_DIR = path.resolve(
+ DOCSITE_ROOT,
+ '../../packages/charts/blocks',
+);
+const FIXTURE_NAME = AUTOMATICITY_FIXTURE_PREFIX;
+const FIXTURE_TSX = path.join(PROBE_BLOCKS_DIR, `${FIXTURE_NAME}.tsx`);
+const FIXTURE_DOC = path.join(PROBE_BLOCKS_DIR, `${FIXTURE_NAME}.doc.mjs`);
+const FIXTURE_MARKER =
+ 'Automaticity probe: zero-registration integration block';
+
+const FIXTURE_TSX_SOURCE = `// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {Text} from '@astryxdesign/core/Text';
+
+export default function ${FIXTURE_NAME}() {
+ return <Text>${FIXTURE_MARKER}</Text>;
+}
+`;
+
+const FIXTURE_DOC_SOURCE = `// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export default {
+ type: 'block',
+ name: '${FIXTURE_NAME}',
+ displayName: '${FIXTURE_NAME}',
+ description:
+ 'Temporary test fixture written by example-automaticity.test.ts; never committed.',
+ isReady: true,
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Text'],
+};
+`;
+
+function removeFixture() {
+ fs.rmSync(FIXTURE_TSX, {force: true});
+ fs.rmSync(FIXTURE_DOC, {force: true});
+}
+
+beforeAll(() => {
+ expect(fs.existsSync(PROBE_BLOCKS_DIR)).toBe(true);
+ removeFixture();
+ fs.writeFileSync(FIXTURE_TSX, FIXTURE_TSX_SOURCE, 'utf-8');
+ fs.writeFileSync(FIXTURE_DOC, FIXTURE_DOC_SOURCE, 'utf-8');
+});
+
+afterAll(() => {
+ removeFixture();
+});
+
+describe('integration block automaticity', () => {
+ it('discovers a newly authored integration block pair with zero registration edits', async () => {
+ // Exactly what generate-data.mjs runs to assemble the canary block
+ // registry — same API, same cwd. Nothing about the fixture exists outside
+ // packages/charts/blocks: astryx.config.mjs, the integration manifest,
+ // and every generator are untouched.
+ const entries = await listBlocks(DOCSITE_ROOT);
+ const entry = entries.find(
+ candidate =>
+ candidate.package === PROBE_PACKAGE && candidate.id === FIXTURE_NAME,
+ );
+ expect(
+ entry,
+ `authored fixture pair was not discovered as a ${PROBE_PACKAGE} block`,
+ ).toBeDefined();
+ expect(entry!.name).toBe(FIXTURE_NAME);
+ expect(entry!.description).toContain('Temporary test fixture');
+
+ const shown = (await queryTemplates(entry!.id, {
+ show: true,
+ type: 'block',
+ package: entry!.package,
+ cwd: DOCSITE_ROOT,
+ })) as TemplateShowResponse;
+ expect(shown.data.source).toContain(FIXTURE_MARKER);
+ }, 60_000);
+
+ it("still lists the package's authored blocks alongside the fixture (no shadowing)", async () => {
+ const entries = await listBlocks(DOCSITE_ROOT);
+ const probeIds = entries
+ .filter(candidate => candidate.package === PROBE_PACKAGE)
+ .map(candidate => candidate.id);
+ expect(probeIds).toContain(FIXTURE_NAME);
+ expect(probeIds.some(id => id !== FIXTURE_NAME)).toBe(true);
+ }, 60_000);
+});
diff --git a/apps/docsite/src/__tests__/example-coverage.test.ts b/apps/docsite/src/__tests__/example-coverage.test.ts
new file mode 100644
index 0000000000..85637e3a08
--- /dev/null
+++ b/apps/docsite/src/__tests__/example-coverage.test.ts
@@ -0,0 +1,130 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Example-coverage report (report-only).
+ *
+ * Prints, for every configured integration package and for Core, how many
+ * authored doc-example labels have a paired runnable block — starting from the
+ * AUTHORED files, so an example that silently renders as a CLI snippet (no
+ * runnable demo) is visible in CI logs. This is a REPORT, not a gate: Core
+ * does not require pairing and integration packages are intentionally no
+ * stricter (owner decision, 2026-09-30); a repo-wide pairing gate remains an
+ * open decision.
+ *
+ * @input Authored component docs and template descriptors across documented
+ * packages, plus the generated block registry
+ * @output CI-visible coverage inventory and regression coverage for
+ * authored-block admission into the registry
+ * @position Build-time docsite documentation-coverage reporting
+ * Run: pnpm -F @astryxdesign/docsite test
+ */
+
+import * as path from 'node:path';
+import {describe, expect, it} from 'vitest';
+import docsiteConfig from '../../astryx.config.mjs';
+import {
+ inventoryPackageExamples,
+ pairExampleCoverage,
+ formatCoverageReport,
+ resolveTemplatesRoot,
+} from '../lib/exampleCoverage.mjs';
+import {blocks as registeredBlocks} from '../generated/blockRegistry';
+import {packages} from '../generated/packageRegistry';
+
+const REPO_ROOT = path.resolve(__dirname, '../../../..');
+
+interface PackageInventory {
+ packageName: string;
+ components: Awaited<
+ ReturnType<typeof inventoryPackageExamples>
+ >['components'];
+ blocks: Awaited<ReturnType<typeof inventoryPackageExamples>>['blocks'];
+ coverage: ReturnType<typeof pairExampleCoverage>;
+}
+
+async function inventoryIntegration(
+ packageName: string,
+): Promise<PackageInventory> {
+ const registryEntry = packages.find(pkg => pkg.name === packageName);
+ expect(
+ registryEntry,
+ `${packageName} missing from packageRegistry`,
+ ).toBeDefined();
+ const packageDir = path.join(REPO_ROOT, registryEntry!.packagePath);
+ const {components, blocks} = await inventoryPackageExamples({
+ repoRoot: REPO_ROOT,
+ srcDir: path.join(packageDir, 'src'),
+ blocksDir: await resolveTemplatesRoot(packageDir),
+ });
+ return {
+ packageName,
+ components,
+ blocks,
+ coverage: pairExampleCoverage(components, blocks),
+ };
+}
+
+describe('example coverage (report-only)', () => {
+ it('reports authored example-label ↔ runnable-block coverage per package', async () => {
+ const inventories: PackageInventory[] = [];
+ for (const packageName of docsiteConfig.integrations) {
+ inventories.push(await inventoryIntegration(packageName));
+ }
+ // Core authors its runnable blocks centrally in the CLI's assets tree.
+ const {components, blocks} = await inventoryPackageExamples({
+ repoRoot: REPO_ROOT,
+ srcDir: path.join(REPO_ROOT, 'packages/core/src'),
+ blocksDir: path.join(REPO_ROOT, 'packages/cli/assets/templates/blocks'),
+ });
+ inventories.push({
+ packageName: '@astryxdesign/core',
+ components,
+ blocks,
+ coverage: pairExampleCoverage(components, blocks),
+ });
+
+ for (const inventory of inventories) {
+ // Write straight to stdout: vitest's console interceptor hides
+ // console.* output for passing tests, and this report's whole job is
+ // to be readable in CI logs.
+ process.stdout.write(
+ formatCoverageReport(
+ inventory.packageName,
+ inventory.coverage,
+ inventory.blocks,
+ ) + '\n',
+ );
+ // Report-only: the inventory must compute, nothing more.
+ expect(Array.isArray(inventory.coverage)).toBe(true);
+ }
+ }, 120_000);
+
+ it('admits every authored Lab block into the generated registry', async () => {
+ // Authored → generated direction: a well-formed descriptor pair sitting in
+ // packages/lab/blocks that never reaches blockRegistry would be a silent
+ // drop in the plumbing (as opposed to an authoring choice, which the
+ // report above covers). Lab currently has no broken descriptors, so every
+ // authored block must appear, attributed to the package. With no Lab
+ // blocks authored yet this loop is vacuous; it becomes the admission
+ // regression as soon as the first block lands.
+ const lab = await inventoryIntegration('@astryxdesign/lab');
+ const registeredLabNames = new Set(
+ registeredBlocks
+ .filter(block => block.sourcePackage === '@astryxdesign/lab')
+ .map(block => block.name),
+ );
+ for (const block of lab.blocks) {
+ if (
+ block.type !== 'block' ||
+ block.loadError != null ||
+ !block.hasSource
+ ) {
+ continue;
+ }
+ expect(
+ registeredLabNames.has(block.name),
+ `${block.file} is authored but missing from the generated blockRegistry`,
+ ).toBe(true);
+ }
+ }, 60_000);
+});
diff --git a/apps/docsite/src/__tests__/integration-targets.test.ts b/apps/docsite/src/__tests__/integration-targets.test.ts
new file mode 100644
index 0000000000..0345ea4d90
--- /dev/null
+++ b/apps/docsite/src/__tests__/integration-targets.test.ts
@@ -0,0 +1,117 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration-content target gating tests.
+ *
+ * The production (`latest`) docsite must contain ZERO integration content:
+ * the configured integration packages (@astryxdesign/lab et al.) are
+ * canary-only (spec:AST-017). generate-data.mjs and generate-scope.mjs share
+ * one admission gate (src/lib/integrationTargets.mjs); this file unit-tests
+ * that gate for every target and pins the canary-side invariants that make
+ * the exclusion provable from the generated artifacts.
+ *
+ * @input The shared integration target gate, docsite config, and the
+ * canary-generated registries
+ * @output Regression coverage for production exclusion of integration content
+ * @position Build-time docsite target verification
+ * Run: pnpm -F @astryxdesign/docsite test
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {describe, expect, it} from 'vitest';
+import docsiteConfig from '../../astryx.config.mjs';
+import {
+ integrationContentEnabled,
+ integrationPackagesForTarget,
+} from '../lib/integrationTargets.mjs';
+import {blocks} from '../generated/blockRegistry';
+import {components} from '../generated/componentRegistry';
+import {packages} from '../generated/packageRegistry';
+
+const REPO_ROOT = path.resolve(__dirname, '../../../..');
+
+describe('integration target gate', () => {
+ it('admits integration content only on canary', () => {
+ expect(integrationContentEnabled('canary')).toBe(true);
+ expect(integrationContentEnabled('latest')).toBe(false);
+ });
+
+ it('returns the configured packages, in order, on canary', () => {
+ expect(integrationPackagesForTarget('canary', docsiteConfig)).toEqual(
+ docsiteConfig.integrations,
+ );
+ });
+
+ it('returns no packages on latest regardless of configuration', () => {
+ expect(integrationPackagesForTarget('latest', docsiteConfig)).toEqual([]);
+ });
+
+ it('tolerates a config without an integrations list', () => {
+ expect(integrationPackagesForTarget('canary', {})).toEqual([]);
+ expect(integrationPackagesForTarget('canary', undefined)).toEqual([]);
+ });
+});
+
+describe('production-exclusion invariants (asserted on canary artifacts)', () => {
+ it('attributes every integration-sourced block to a configured package', () => {
+ // Every block the canary build admits beyond Core's CLI assets must come
+ // from a package named in astryx.config — those are exactly the entries
+ // the latest build drops, so nothing integration-shaped can ride along
+ // unattributed.
+ const configured = new Set<string>(docsiteConfig.integrations);
+ const sourced = blocks.filter(block => block.sourcePackage != null);
+ expect(sourced.length).toBeGreaterThan(0);
+ for (const block of sourced) {
+ expect(configured.has(block.sourcePackage as string)).toBe(true);
+ }
+ });
+
+ it('attributes every non-core component entry to a configured package', () => {
+ const configured = new Set<string>(docsiteConfig.integrations);
+ for (const packageName of Object.keys(components)) {
+ if (packageName === '@astryxdesign/core') {
+ continue;
+ }
+ expect(configured.has(packageName)).toBe(true);
+ }
+ });
+
+ it('marks every configured integration canary-only or private, so the latest content snapshot can never materialize it', () => {
+ // resolve-content-root.mjs materializes the `latest` content root from the
+ // packages published to the stable npm tag, excluding `private` and
+ // `astryx.canaryOnly` manifests (mirroring release.yml). As long as every
+ // configured integration carries one of those flags, the production data
+ // pipeline cannot even see its sources. Revisit this invariant before ever
+ // configuring a stable package as a docsite integration.
+ for (const name of docsiteConfig.integrations) {
+ const registryEntry = packages.find(pkg => pkg.name === name);
+ // Present on canary (documented at all) …
+ expect(
+ registryEntry,
+ `${name} missing from canary packageRegistry`,
+ ).toBeDefined();
+ const manifest = JSON.parse(
+ fs.readFileSync(
+ path.join(REPO_ROOT, registryEntry!.packagePath, 'package.json'),
+ 'utf-8',
+ ),
+ );
+ const excludedFromStable =
+ manifest.private === true || manifest.astryx?.canaryOnly === true;
+ expect(
+ excludedFromStable,
+ `${name} is neither private nor astryx.canaryOnly — it would be eligible for the latest content snapshot`,
+ ).toBe(true);
+ }
+ });
+
+ it('documents @astryxdesign/lab on canary (presence proof for the exclusion tests)', () => {
+ // The latest-target run proves absence; this proves the same pipeline
+ // genuinely admits Lab components on canary, so the absence is exclusion,
+ // not a silently empty catalog. Lab block admission is covered generically
+ // once a Lab block is authored; this setup change does not add one.
+ expect(Object.keys(components)).toContain('@astryxdesign/lab');
+ expect(blocks.some(block => block.sourcePackage != null)).toBe(true);
+ });
+});
diff --git a/apps/docsite/src/__tests__/playground-scope.test.ts b/apps/docsite/src/__tests__/playground-scope.test.ts
index a53fec5099..d4527ab3a9 100644
--- a/apps/docsite/src/__tests__/playground-scope.test.ts
+++ b/apps/docsite/src/__tests__/playground-scope.test.ts
@@ -5,7 +5,8 @@
*
* Validates that the generated playground scope includes every public
* component exported from @astryxdesign/core/package.json, plus the expected
- * non-component scope entries and editor declarations used by page templates.
+ * non-component scope entries and editor declarations used by page templates
+ * and the imports needed by registered integration example blocks.
*
* This test reads the generated file as text (rather than importing it)
* because the scope imports @astryxdesign/core/* which requires a prior build step.
@@ -17,6 +18,8 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {describe, it, expect, beforeAll} from 'vitest';
+import docsiteConfig from '../../astryx.config.mjs';
+import {blocks} from '../generated/blockRegistry';
const GENERATED_SCOPE_PATH = path.resolve(
__dirname,
@@ -322,8 +325,76 @@ describe('playground-scope', () => {
);
});
+ // ── Integration packages (canary whole-package bridge) ─────────────────
+
+ it('maps every configured integration package under its own namespace', () => {
+ // Whole-package admission is the contract: a NEW component exported by a
+ // configured integration is playground-importable with no scope edits.
+ // Each package gets a DISTINCT namespace import, so qualified imports
+ // (`import {Chart} from '@astryxdesign/charts'`) keep package identity
+ // even where packages share export names (@astryxdesign/lab and
+ // @astryxdesign/charts currently share 14, e.g. Chart/ChartAxis/useChart).
+ docsiteConfig.integrations.forEach((pkg: string, index: number) => {
+ expect(scopeContent).toContain(
+ `import * as Integration${index} from '${pkg}';`,
+ );
+ expect(scopeContent).toContain(`'${pkg}': Integration${index},`);
+ });
+ });
+
+ it('orders integration scope entries after recharts, in config order, before Core', () => {
+ // The preview runner builds UNQUALIFIED globals by iterating the scope
+ // map in insertion order with later-wins (runner.ts buildGlobalScope),
+ // so this order IS the collision policy: among integrations the
+ // later-configured package owns a shared unqualified name (charts
+ // shadows lab for their 14 shared exports), and Core's entries shadow
+ // every integration. Qualified imports are unaffected.
+ const mapStart = scopeContent.indexOf('export const scope');
+ expect(mapStart).toBeGreaterThan(-1);
+ const scopeMap = scopeContent.slice(mapStart);
+
+ const integrationPositions = docsiteConfig.integrations.map(
+ (pkg: string, index: number) =>
+ scopeMap.indexOf(`'${pkg}': Integration${index},`),
+ );
+ for (const position of integrationPositions) {
+ expect(position).toBeGreaterThan(-1);
+ }
+ expect([...integrationPositions].sort((a, b) => a - b)).toEqual(
+ integrationPositions,
+ );
+
+ const rechartsPosition = scopeMap.indexOf('recharts: Recharts,');
+ expect(rechartsPosition).toBeGreaterThan(-1);
+ expect(Math.min(...integrationPositions)).toBeGreaterThan(rechartsPosition);
+
+ const firstCorePosition = scopeMap.indexOf("'@astryxdesign/core");
+ expect(firstCorePosition).toBeGreaterThan(-1);
+ expect(firstCorePosition).toBeGreaterThan(
+ Math.max(...integrationPositions),
+ );
+ });
+
// ── What the templates actually import ─────────────────────────────────
+ it('resolves every bare import in registered integration example blocks', () => {
+ const scopedModules = getScopeKeys(scopeContent);
+ const missing = new Set<string>();
+ for (const block of blocks.filter(entry => entry.sourcePackage)) {
+ for (const match of block.source.matchAll(IMPORT_RE)) {
+ const id = match[1];
+ if (
+ !id.startsWith('.') &&
+ !ASSET_RE.test(id) &&
+ !scopedModules.has(id.toLowerCase())
+ ) {
+ missing.add(id);
+ }
+ }
+ }
+ expect([...missing].sort()).toEqual([]);
+ });
+
it('resolves every bare import in the page templates', () => {
// The assertions above are an allowlist, and an allowlist only covers what
// someone remembered to add. Recharts was missing from the scope for as
diff --git a/apps/docsite/src/__tests__/resolve-content-root.test.ts b/apps/docsite/src/__tests__/resolve-content-root.test.ts
new file mode 100644
index 0000000000..343abfb85c
--- /dev/null
+++ b/apps/docsite/src/__tests__/resolve-content-root.test.ts
@@ -0,0 +1,90 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Content-target resolution tests.
+ *
+ * Pins the DOCSITE_TARGET × VERCEL_ENV matrix of getTarget() exactly as it
+ * behaves today — test-only documentation of an intentional contract, not a
+ * behavior change. The explicit DOCSITE_TARGET override always wins: it exists
+ * for CI lanes and local runs. Deployments rely on VERCEL_ENV alone (canary
+ * site = preview, production → latest) and never set the override.
+ *
+ * @input DOCSITE_TARGET / VERCEL_ENV environment combinations
+ * @output Regression coverage for the target-selection contract
+ * @position Build-time docsite target verification
+ * Run: pnpm -F @astryxdesign/docsite test
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {getTarget} from '../../scripts/resolve-content-root.mjs';
+
+const ENV_KEYS = ['DOCSITE_TARGET', 'VERCEL_ENV'] as const;
+const saved: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>> =
+ {};
+
+function setEnv(vercelEnv: string | null, docsiteTarget: string | null) {
+ if (vercelEnv == null) {
+ delete process.env.VERCEL_ENV;
+ } else {
+ process.env.VERCEL_ENV = vercelEnv;
+ }
+ if (docsiteTarget == null) {
+ delete process.env.DOCSITE_TARGET;
+ } else {
+ process.env.DOCSITE_TARGET = docsiteTarget;
+ }
+}
+
+beforeEach(() => {
+ for (const key of ENV_KEYS) {
+ saved[key] = process.env[key];
+ }
+});
+
+afterEach(() => {
+ for (const key of ENV_KEYS) {
+ const value = saved[key];
+ if (value === undefined) {
+ delete process.env[key];
+ } else {
+ process.env[key] = value;
+ }
+ }
+});
+
+describe('getTarget', () => {
+ it('defaults to canary outside production (development, preview, unset)', () => {
+ setEnv(null, null);
+ expect(getTarget()).toBe('canary');
+ setEnv('preview', null);
+ expect(getTarget()).toBe('canary');
+ setEnv('development', null);
+ expect(getTarget()).toBe('canary');
+ });
+
+ it('derives latest from a production deployment', () => {
+ setEnv('production', null);
+ expect(getTarget()).toBe('latest');
+ });
+
+ it('lets an explicit DOCSITE_TARGET override the deployment default', () => {
+ // The override exists for CI lanes and local runs (e.g. generating the
+ // latest catalog on a dev machine, or pinning a preview to published
+ // content). Deployed environments never set it: the canary site deploys
+ // as VERCEL_ENV=preview and production deploys with no override, so
+ // production always resolves to latest in practice.
+ setEnv(null, 'latest');
+ expect(getTarget()).toBe('latest');
+ setEnv('preview', 'latest');
+ expect(getTarget()).toBe('latest');
+ setEnv('production', 'latest');
+ expect(getTarget()).toBe('latest');
+ setEnv('production', 'canary');
+ expect(getTarget()).toBe('canary');
+ });
+
+ it('rejects unknown target values', () => {
+ setEnv(null, 'bogus');
+ expect(() => getTarget()).toThrow(/Invalid DOCSITE_TARGET="bogus"/);
+ });
+});
diff --git a/apps/docsite/src/lib/exampleCoverage.mjs b/apps/docsite/src/lib/exampleCoverage.mjs
new file mode 100644
index 0000000000..65349133f3
--- /dev/null
+++ b/apps/docsite/src/lib/exampleCoverage.mjs
@@ -0,0 +1,296 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file exampleCoverage.mjs
+ *
+ * Read-only inventory pairing AUTHORED component-doc example labels with
+ * AUTHORED runnable block descriptors, per documented package. It reads
+ * authored inputs ONLY — it does not look at the generated registries, so it
+ * cannot detect a block lost between authoring and generation (the Lab
+ * authored→blockRegistry admission check in example-coverage.test.ts covers
+ * that, for blockRegistry only). What it surfaces is authoring-side: a doc
+ * example with no same-named runnable block, a block named after no label,
+ * a descriptor missing its source, a descriptor that fails to load. An
+ * unpaired label is a NAME mismatch, not proof the component has no demos —
+ * blocks attach to a page via exampleFor regardless of name.
+ *
+ * REPORTS, NEVER GATES. Core does not require doc examples to have paired
+ * blocks, and integration packages are intentionally no stricter (owner
+ * decision, 2026-09-30). Whether example↔block pairing should gate CI is an
+ * open repo-wide decision; until then tests print this inventory for CI-log
+ * visibility only.
+ *
+ * @input Authored component docs (src/X/X.doc.mjs) and template descriptors
+ * (the package's declared templates root, e.g. packages/lab/blocks)
+ * @output Per-component pairing of example labels to block names, plus
+ * structural findings (missing same-stem sources, descriptor load failures)
+ * @position Shared by docsite reporting tests; no generator consumes this.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+
+/**
+ * Basename prefix reserved for the automaticity test fixture
+ * (example-automaticity.test.ts writes a temporary block pair into
+ * packages/charts/blocks at runtime). The inventory skips it so the coverage
+ * report and the fixture test cannot interfere when vitest runs both files in
+ * parallel workers.
+ */
+export const AUTOMATICITY_FIXTURE_PREFIX = 'ZzDocsiteAutomaticityProbe';
+
+const SRC_SKIP_DIRS = new Set(['utils', '__tests__', 'node_modules']);
+
+/**
+ * Template descriptor suffixes this inventory can load natively. `.doc.ts` /
+ * `.template.ts` descriptors are valid for the CLI (loaded via jiti) but none
+ * exist in this repo; they are collected as `skipped` rather than imported.
+ */
+const DESCRIPTOR_SUFFIXES = [
+ '.doc.mjs',
+ '.doc.js',
+ '.template.mjs',
+ '.template.js',
+];
+const TS_DESCRIPTOR_SUFFIXES = ['.doc.ts', '.template.ts'];
+
+/**
+ * @param {string} dir
+ * @param {(name: string) => boolean} matches
+ * @param {Set<string>} skipDirs
+ * @returns {string[]}
+ */
+function walk(dir, matches, skipDirs = new Set()) {
+ /** @type {string[]} */
+ const out = [];
+ if (!fs.existsSync(dir)) return out;
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (!skipDirs.has(entry.name)) out.push(...walk(full, matches, skipDirs));
+ } else if (matches(entry.name)) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+/**
+ * Resolve the templates root a package declares in its integration manifest.
+ * Returns null when the package has no manifest or declares no templates root.
+ * (Only `.mjs`/`.js` manifests are readable here; every in-repo integration
+ * uses `.mjs`.)
+ *
+ * @param {string} packageDir absolute package directory
+ * @returns {Promise<string | null>} absolute templates root or null
+ */
+export async function resolveTemplatesRoot(packageDir) {
+ for (const basename of ['astryx.integration.mjs', 'astryx.integration.js']) {
+ const manifestPath = path.join(packageDir, basename);
+ if (!fs.existsSync(manifestPath)) continue;
+ const manifest = (await import(pathToFileURL(manifestPath).href)).default;
+ if (typeof manifest?.templates !== 'string') return null;
+ return path.resolve(packageDir, manifest.templates);
+ }
+ return null;
+}
+
+/**
+ * @typedef {object} AuthoredComponentExamples
+ * @property {string} name component doc name
+ * @property {string} file repo-relative doc path
+ * @property {string[]} labels authored example labels ('' for an unlabeled example)
+ */
+
+/**
+ * @typedef {object} AuthoredBlock
+ * @property {string} file repo-relative descriptor path
+ * @property {string} name descriptor name (pairs with an example label by equality)
+ * @property {'page'|'block'|null} type
+ * @property {string | null} exampleFor
+ * @property {string[]} alsoExampleFor
+ * @property {boolean} isShowcase
+ * @property {boolean} hasSource same-stem .tsx exists
+ * @property {string} [loadError]
+ */
+
+/**
+ * Inventory one package's authored docs and template descriptors.
+ *
+ * @param {object} options
+ * @param {string} options.repoRoot
+ * @param {string} options.srcDir absolute component-doc root (may not exist)
+ * @param {string | null} options.blocksDir absolute templates root (null = none declared)
+ * @returns {Promise<{components: AuthoredComponentExamples[], blocks: AuthoredBlock[], skippedTsDescriptors: string[]}>}
+ */
+export async function inventoryPackageExamples({repoRoot, srcDir, blocksDir}) {
+ /** @type {AuthoredComponentExamples[]} */
+ const components = [];
+ for (const file of walk(
+ srcDir,
+ name => name.endsWith('.doc.mjs'),
+ SRC_SKIP_DIRS,
+ )) {
+ try {
+ const mod = await import(pathToFileURL(file).href);
+ const docs = mod.docs;
+ if (!docs || !Array.isArray(docs.examples) || docs.examples.length === 0)
+ continue;
+ components.push({
+ name: docs.name ?? path.basename(file, '.doc.mjs'),
+ file: path.relative(repoRoot, file),
+ labels: docs.examples.map(example => example.label ?? ''),
+ });
+ } catch {
+ // A component doc that does not load contributes no examples; the
+ // docsite generator already warns on these during generation.
+ }
+ }
+
+ /** @type {AuthoredBlock[]} */
+ const blocks = [];
+ /** @type {string[]} */
+ const skippedTsDescriptors = [];
+ if (blocksDir != null) {
+ const descriptorFiles = walk(blocksDir, name =>
+ [...DESCRIPTOR_SUFFIXES, ...TS_DESCRIPTOR_SUFFIXES].some(suffix =>
+ name.endsWith(suffix),
+ ),
+ );
+ for (const file of descriptorFiles) {
+ const basename = path.basename(file);
+ if (basename.startsWith(AUTOMATICITY_FIXTURE_PREFIX)) continue;
+ const suffix = [...DESCRIPTOR_SUFFIXES, ...TS_DESCRIPTOR_SUFFIXES].find(
+ s => basename.endsWith(s),
+ );
+ if (suffix == null) continue;
+ if (TS_DESCRIPTOR_SUFFIXES.includes(suffix)) {
+ skippedTsDescriptors.push(path.relative(repoRoot, file));
+ continue;
+ }
+ const stem = file.slice(0, -suffix.length);
+ const entry = {
+ file: path.relative(repoRoot, file),
+ name: path.basename(stem),
+ type: /** @type {'page'|'block'|null} */ (null),
+ exampleFor: /** @type {string | null} */ (null),
+ alsoExampleFor: /** @type {string[]} */ ([]),
+ isShowcase: false,
+ hasSource: fs.existsSync(`${stem}.tsx`),
+ };
+ try {
+ const mod = await import(pathToFileURL(file).href);
+ const doc = mod.default ?? mod.doc;
+ entry.type =
+ doc?.type === 'page' || doc?.type === 'block' ? doc.type : null;
+ entry.name = doc?.name ?? entry.name;
+ entry.exampleFor = doc?.exampleFor ?? null;
+ entry.alsoExampleFor = Array.isArray(doc?.alsoExampleFor)
+ ? doc.alsoExampleFor
+ : [];
+ entry.isShowcase = doc?.isShowcase === true;
+ } catch (error) {
+ blocks.push({
+ ...entry,
+ loadError: error instanceof Error ? error.message : String(error),
+ });
+ continue;
+ }
+ blocks.push(entry);
+ }
+ }
+
+ return {components, blocks, skippedTsDescriptors};
+}
+
+/**
+ * @typedef {object} ComponentCoverage
+ * @property {string} component
+ * @property {string[]} labels
+ * @property {string[]} pairedNames block names attributed to the component
+ * @property {string[]} missing labels with no same-named block
+ * @property {string[]} extra attributed block names matching no label
+ * @property {string[]} showcases attributed block names with isShowcase
+ */
+
+/**
+ * Pair authored example labels with authored blocks by the recommended
+ * naming convention: a block belongs to a component via
+ * `exampleFor`/`alsoExampleFor`, and pairs with the example whose label equals
+ * the block's `name`.
+ *
+ * @param {AuthoredComponentExamples[]} components
+ * @param {AuthoredBlock[]} blocks
+ * @returns {ComponentCoverage[]}
+ */
+export function pairExampleCoverage(components, blocks) {
+ return components.map(component => {
+ const attributed = blocks.filter(
+ block =>
+ block.type === 'block' &&
+ block.loadError == null &&
+ (block.exampleFor === component.name ||
+ block.alsoExampleFor.includes(component.name)),
+ );
+ const pairedNames = attributed.map(block => block.name);
+ const nameSet = new Set(pairedNames);
+ return {
+ component: component.name,
+ labels: component.labels,
+ pairedNames,
+ missing: component.labels.filter(label => !nameSet.has(label)),
+ extra: pairedNames.filter(name => !component.labels.includes(name)),
+ showcases: attributed
+ .filter(block => block.isShowcase)
+ .map(block => block.name),
+ };
+ });
+}
+
+/**
+ * Human-readable coverage summary for one package, for CI-log visibility.
+ *
+ * @param {string} packageName
+ * @param {ComponentCoverage[]} coverage
+ * @param {AuthoredBlock[]} blocks
+ * @returns {string}
+ */
+export function formatCoverageReport(packageName, coverage, blocks) {
+ const lines = [`example coverage — ${packageName}`];
+ const unpaired = coverage.filter(
+ entry => entry.missing.length > 0 || entry.extra.length > 0,
+ );
+ const paired = coverage.length - unpaired.length;
+ lines.push(
+ ` ${coverage.length} component doc(s) with examples; ${paired} with every label paired to a same-named block`,
+ );
+ // "Unpaired" is a NAME mismatch, not necessarily a missing demo: a
+ // component's page still renders every block attributed to it via
+ // exampleFor. An unpaired LABEL means that example exists only as a CLI
+ // snippet; an unpaired BLOCK NAME means the demo renders but under a name
+ // no authored example uses.
+ for (const entry of unpaired) {
+ const parts = [];
+ if (entry.missing.length > 0) {
+ parts.push(
+ `${entry.missing.length}/${entry.labels.length} label(s) unpaired — no same-named block${entry.pairedNames.length > 0 ? ` (component has ${entry.pairedNames.length} block(s) under other names)` : ' (example ships as a CLI snippet only)'}: ${entry.missing.map(label => JSON.stringify(label)).join(', ')}`,
+ );
+ }
+ if (entry.extra.length > 0) {
+ parts.push(
+ `block name(s) not matching any label: ${entry.extra.map(name => JSON.stringify(name)).join(', ')}`,
+ );
+ }
+ lines.push(` - ${entry.component}: ${parts.join(' | ')}`);
+ }
+ const broken = blocks.filter(
+ block => block.loadError != null || !block.hasSource,
+ );
+ for (const block of broken) {
+ lines.push(
+ ` ! ${block.file}: ${block.loadError ?? 'missing same-stem .tsx source'}`,
+ );
+ }
+ return lines.join('\n');
+}
diff --git a/apps/docsite/src/lib/integrationTargets.mjs b/apps/docsite/src/lib/integrationTargets.mjs
new file mode 100644
index 0000000000..1d9730e541
--- /dev/null
+++ b/apps/docsite/src/lib/integrationTargets.mjs
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file integrationTargets.mjs
+ *
+ * Single decision point for whether a docsite content target admits workspace
+ * integration packages (their component docs, runnable blocks, and playground
+ * scope modules).
+ *
+ * @input A resolved docsite target ('canary' | 'latest') and the docsite
+ * astryx.config
+ * @output Whether integration content is admitted, and the admitted package
+ * names in configuration order
+ * @position Shared by scripts/generate-data.mjs, scripts/generate-scope.mjs and
+ * scripts/generate-playground-types.mjs so the production-exclusion rule
+ * cannot drift between generators. The
+ * production (`latest`) site must contain zero integration content — the
+ * configured packages are canary-only (e.g. @astryxdesign/lab, spec:AST-017).
+ * Unit-tested directly in src/__tests__/integration-targets.test.ts.
+ */
+
+/**
+ * Integration content (workspace packages beyond @astryxdesign/core) is only
+ * ever admitted on the canary target. `latest` documents the published stable
+ * release, which never includes canary-only packages.
+ *
+ * @param {string} target resolved docsite target ('canary' | 'latest')
+ * @returns {boolean}
+ */
+export function integrationContentEnabled(target) {
+ return target === 'canary';
+}
+
+/**
+ * The integration packages a target admits, in configuration order (the order
+ * is meaningful: the playground runner resolves unqualified globals with
+ * later-wins across scope entries, so a later-configured package owns a
+ * shared export name).
+ *
+ * @param {string} target resolved docsite target ('canary' | 'latest')
+ * @param {{integrations?: unknown}} [config] the docsite astryx.config module
+ * @returns {string[]} admitted package names; empty off-canary
+ */
+export function integrationPackagesForTarget(target, config) {
+ if (!integrationContentEnabled(target)) return [];
+ return Array.isArray(config?.integrations) ? [...config.integrations] : [];
+}
diff --git a/packages/lab/README.md b/packages/lab/README.md
index 1ed01a0321..e566c6b967 100644
--- a/packages/lab/README.md
+++ b/packages/lab/README.md
@@ -50,6 +50,29 @@ import '@astryxdesign/lab/lab.css';
> Canary builds track the latest commit on `main` (`0.x.y-canary.<sha>`). They can break between any two versions — pin an exact version if you need stability.
+## Documenting a Lab component (canary docsite)
+
+Lab appears **only on the canary docsite** — the production site documents the published stable release and never loads this package (see the target gates in `apps/docsite/scripts/` and the exclusion tests in `apps/docsite/src/__tests__/integration-targets.test.ts`).
+
+Authoring is the same two-artifact flow a Core author uses; the only difference is where the runnable demos live (Core keeps its blocks centrally in `packages/cli/assets/templates/blocks/`, Lab owns its own `blocks/` directory here):
+
+1. **Component doc** — `src/<Name>/<Name>.doc.mjs` exporting `docs` (props, usage, playground config, `examples`). Picked up automatically on canary; no registration anywhere.
+2. **Runnable demos** — same-stem pairs in `blocks/`: `<BlockName>.tsx` + `<BlockName>.doc.mjs` (a `TemplateDoc` stamped `type: 'block'`). Discovered automatically once this package declares the directory — nothing per-component. The docsite renders the pair as the component page's showcase/examples and the playground can import anything the package exports.
+
+**First block only:** the pull request that adds Lab's first block also adds `templates: './blocks'` to `astryx.integration.mjs` and `"blocks"` to the `files` list in `package.json`. Declaring the root earlier would fail `astryx integration pack --check`, which rejects a declared root with no contributions. After that one-time step, a new demo is just its block pair.
+
+How a demo reaches a component page: **`exampleFor: '<Component>'` (or `alsoExampleFor`) is what attaches a block** — the page renders every block attributed to it, whatever the block is named. The block's `name` is the demo's display name; component-doc example `labels` are CLI-snippet headings. The two are independent mechanisms.
+
+Use these conventions for new demos:
+
+- Give the block descriptor the same `name` as the component doc's example `label`, so the snippet and its runnable demo read as one documented set (this naming convention is what the `example-coverage` report keys on — it is not how the docsite attaches demos).
+- Exactly one attributed block sets `isShowcase: true` (the hero demo — conventionally the first example).
+- `displayName` and `description` are required by the docsite build; set `componentsUsed` and `aspectRatio` for the gallery.
+
+A doc example with no corresponding block exists only as a CLI/code snippet — the docsite page's demos come solely from blocks. Note the converse does not follow from names alone: an example label with no _same-named_ block does not by itself mean the demo is missing, because the component may render demos under other names (several Core components do). The `example-coverage` docsite test output reports both sides of that pairing; it is a _report_, not a gate — Core has the same non-guarantee, and whether pairing should gate CI is an open repo-wide decision.
+
+> Note: `astryx integration add template` scaffolds a `./templates` root for a package that declares none. Declare `templates: './blocks'` explicitly instead, matching charts and richtext; unifying the two conventions is a pending repo decision.
+
## Why no stable release?
`package.json` keeps `"private": true` plus an `"astryx": { "canaryOnly": true }` marker. The release workflow's stable (`latest`) job skips both private and `canaryOnly` packages, while the canary job strips `private` in its ephemeral CI checkout only (never in git) to publish the `@canary` tag. The committed `private: true` is npm's hard guarantee that no stable publish can ever happen — **do not remove it.**