Skip to content

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

TypeScript

fix(cli): preserve 0.6 docs compatibility (#6695)

Cindy Zhang2bb99ed515c4
diff --git a/.changeset/typed-doc-graph-contracts.md b/.changeset/typed-doc-graph-contracts.md
index b972dce7ee..1ae3ee583c 100644
--- a/.changeset/typed-doc-graph-contracts.md
+++ b/.changeset/typed-doc-graph-contracts.md
@@ -1,18 +1,15 @@
---
-'@astryxdesign/cli': minor
+'@astryxdesign/cli': patch
---
-[breaking] Add typed namespace docs, semantic content blocks, and stable provider-aware documentation identity. Consumers with exhaustive `AuthoredDocKind` or `ReferenceContentBlock` switches must add cases for `namespace`, `workflow`, `collection`, and `reference`; existing authored docs continue to parse unchanged. (#6471)
+[feat] Add opt-in typed documentation graph contracts and stable provider-aware documentation identity without breaking existing topic readers. (#6471)
-Every doc section now has a stable key: its `id`, or a key derived from its title. `astryx docs <topic> --index` (`docs(topic, undefined, {index: true})`) returns the topic's section index (`docs.index`), and `astryx docs <topic> <key>` reads one section. A topic read still returns the whole doc. `astryx docs authoring` documents every authoring schema, one section each.
+New `NamespaceDoc`, `AuthoredDocKind`, provider identity types, semantic graph-block types, section IDs, `astryx docs <topic> --index`, and section-key reads are additive. The public `ReferenceContentBlock` union keeps its 0.6.x members so existing exhaustive renderers continue to compile; graph-only `workflow`, `collection`, and `reference` blocks are exported separately as `GraphContentBlock` and are accepted by `NamespaceDoc`.
-Breaking changes and how to migrate:
+Existing authored topics continue to load and read as before. Duplicate title-derived keys receive deterministic suffixed index keys, titles with no Latin letters or digits receive deterministic `section-N` keys, ambiguous title queries keep returning the first match, and legacy extension sections without IDs continue to merge by exact title. Explicit new section IDs remain validated. The new progressive-disclosure Doctor audit reports compatibility issues as warnings, and existing full-topic text output keeps its 0.6.x formatting.
-- Section keys are validated. A topic whose sections derive the same key (for example `Quick Start` and `Quick-start`), whose section `id` is not lowercase words joined by hyphens, or whose section title yields no key (no Latin letters or digits) loaded before and is now invalid. Give the section a distinct title or an explicit `id`.
-- A section query matches a key, then an exact title, then a unique part of a title. A query that matches more than one section is now refused with the candidates instead of returning the first match; pass the key.
-- A topic extension's section replaces the base section with the same key before falling back to the same title, so an extension `id` that names a base key now replaces that section instead of being added beside it.
-- Human-readable `astryx docs` output wraps at 120 columns (CJK characters count as two), lists topics one per line, and prints a table wider than 120 columns one row at a time. `--json` output is unchanged.
-- When two packages claim one provider ID, the package being authored is used, otherwise the first-loaded one. The other is set aside, and every command, `astryx doctor`, and the project's issues name it; before, it was dropped without a word.
-- `astryx doctor` now fails when a topic's section index or any section is over 32 KB in any language it ships, when a contributed doc is invalid, or when an authoring doc is unreachable.
+Every doc section can opt into a stable `id`. `astryx docs <topic> --index` (`docs(topic, undefined, {index: true})`) returns the topic's section index (`docs.index`), and `astryx docs <topic> <key>` reads one section. A topic read still returns the whole doc. `astryx docs authoring` documents every authoring schema, one section each.
+
+Provider-ID conflicts are now visible instead of being dropped without a word: the package being authored wins, otherwise the first-loaded provider wins, and every command plus `astryx doctor` reports the set-aside package.
@josephfarina
diff --git a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ContentBlockRenderer.tsx b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ContentBlockRenderer.tsx
index ff63db9c83..443b274773 100644
--- a/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ContentBlockRenderer.tsx
+++ b/apps/sandbox/src/app/(sandbox)/pages/doc-preview/content-blocks/ContentBlockRenderer.tsx
@@ -25,12 +25,6 @@ export function ContentBlockRenderer({block}: {block: ReferenceContentBlock}) {
return <ListBlock items={block.items} listStyle={block.style} />;
case 'token-ref':
return null;
- case 'workflow':
- case 'collection':
- case 'reference':
- throw new Error(
- `Documentation block "${block.type}" requires the compiled graph renderer.`,
- );
default:
return null;
}
diff --git a/packages/cli/api/docs/detail/section/section.mjs b/packages/cli/api/docs/detail/section/section.mjs
index 40ce3d04a4..9a37b6c46c 100644
--- a/packages/cli/api/docs/detail/section/section.mjs
+++ b/packages/cli/api/docs/detail/section/section.mjs
@@ -4,9 +4,9 @@
* @file docs.detail.section leaf — load a single section of a topic.
*
* @input A topic name, a section query, and optional {lang, zh, dense}. Resolves
- * the topic via the shared adapter, finds the section in its lowered compiled
- * node by its stable key, then by exact title, then by a title that contains
- * the query, and links only that section.
+ * the topic via the shared adapter, keeps the 0.6.x first title-substring
+ * match, then falls back to a stable key or normalized title key, and links
+ * only that section.
* @output { type: 'docs.detail.section', data: ReferenceSection } with any
* token-ref blocks inlined — matching `astryx --json docs <topic> <section>`.
* Throws ERR_UNKNOWN_SECTION when nothing matches, or when the query matches
@@ -17,10 +17,7 @@
import {AstryxError} from '../../../error.mjs';
import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
-import {
- findDocSection,
- sectionKey,
-} from '../../../../foundation/discovery/docs-section-key.mjs';
+import {findDocSection} from '../../../../foundation/discovery/docs-section-key.mjs';
import {linkReferenceSection} from '../../../../foundation/doc-compiler/compile.mjs';
import {
readerSections,
@@ -52,16 +49,13 @@ export async function section(topic, sectionName, options = {}) {
const {catalog, node, lang} = await resolveTopicDocs(topic, options);
const sections = readerSections(node);
- const {section: match, candidates} = findDocSection(sections, sectionName);
+ const {section: match} = findDocSection(sections, sectionName);
if (!match) {
- const ambiguous = candidates.length > 1;
throw new AstryxError(
- ambiguous
- ? `Section "${sectionName}" matches ${candidates.length} sections in "${topic}". Read one by its key.`
- : `Section "${sectionName}" not found in "${topic}"`,
- (ambiguous ? candidates : sections).map(s => ({
- name: sectionKey(s),
- reason: s.title,
+ `Section "${sectionName}" not found in "${topic}"`,
+ sections.map(s => ({
+ name: s.title,
+ reason: 'available section',
})),
ERROR_CODES.ERR_UNKNOWN_SECTION,
);
diff --git a/packages/cli/api/docs/detail/section/section.test.mjs b/packages/cli/api/docs/detail/section/section.test.mjs
index afecd3ace4..9a0855e05a 100644
--- a/packages/cli/api/docs/detail/section/section.test.mjs
+++ b/packages/cli/api/docs/detail/section/section.test.mjs
@@ -30,6 +30,17 @@ describe('docs.detail.section leaf', () => {
}
expect(err).toBeInstanceOf(AstryxError);
expect(err.code).toBe('ERR_UNKNOWN_SECTION');
+ expect(err.suggestions).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ name: expect.any(String),
+ reason: 'available section',
+ }),
+ ]),
+ );
+ expect(err.suggestions.some(suggestion => /\s/u.test(suggestion.name))).toBe(
+ true,
+ );
}, SLOW);
it('does not return the first section for an empty section name', async () => {
@@ -50,12 +61,10 @@ describe('docs.detail.section leaf', () => {
expect(res.data.id).toBe(target.id);
}, SLOW);
- it('refuses a query that matches more than one section', async () => {
- const err = await section('theme', 'e').catch(e => e);
- expect(err).toBeInstanceOf(AstryxError);
- expect(err.code).toBe('ERR_UNKNOWN_SECTION');
- expect(err.message).toMatch(/matches \d+ sections/);
- expect(err.suggestions.length).toBeGreaterThan(1);
+ it('keeps a previously accepted ambiguous query on its first match', async () => {
+ const res = await section('theme', 'e');
+ expect(res.type).toBe('docs.detail.section');
+ expect(res.data).toBeDefined();
}, SLOW);
it.each([null, 'zh', 'dense'])(
diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs
index 2005272ea8..9559183d31 100644
--- a/packages/cli/api/doctor/doctor.mjs
+++ b/packages/cli/api/doctor/doctor.mjs
@@ -994,7 +994,7 @@ export async function checkDocsProgressiveDisclosure(ctx) {
return {
id,
label,
- status: 'fail',
+ status: 'warn',
message: joinProblems(problems),
fix: 'Fix the doc each problem names; split a section that is too large into smaller ones, each with its own key.',
};
diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjs
index 7e18fbd1cc..29a029777b 100644
--- a/packages/cli/api/doctor/doctor.test.mjs
+++ b/packages/cli/api/doctor/doctor.test.mjs
@@ -391,7 +391,7 @@ describe('checkDocsProgressiveDisclosure', () => {
expect(c.message).toMatch(/^\d+ topics: /);
}, SLOW);
- it('fails on an invalid doc an integration contributed', async () => {
+ it('warns on an invalid doc an integration contributed', async () => {
const c = await checkDocsProgressiveDisclosure({
docsCatalogIssues: [
{
@@ -402,13 +402,13 @@ describe('checkDocsProgressiveDisclosure', () => {
},
],
});
- expect(c.status).toBe('fail');
+ expect(c.status).toBe('warn');
expect(c.message).toBe('@acme/widgets: bad.doc.mjs exports no doc');
});
- it('fails when the docs catalog cannot be built', async () => {
+ it('warns when the docs catalog cannot be built', async () => {
const c = await checkDocsProgressiveDisclosure({docsCatalogError: 'boom'});
- expect(c.status).toBe('fail');
+ expect(c.status).toBe('warn');
expect(c.message).toContain('boom');
});
@@ -436,7 +436,7 @@ describe('checkDocsProgressiveDisclosure', () => {
}),
docsCatalogIssues: [],
});
- expect(c.status).toBe('fail');
+ expect(c.status).toBe('warn');
expect(c.message).toMatch(/^2 problems: /);
expect(c.message).toContain('huge everything: 41 KB, over the 32 KB one read may return');
expect(c.message).toContain('broken: ');
@@ -812,7 +812,7 @@ describe('checkDocsProgressiveDisclosure languages', () => {
docsCatalog: DocsCatalog.fromBuiltins({deploying: path.join(dir, 'deploying.doc.mjs')}),
docsCatalogIssues: [],
});
- expect(c.status).toBe('fail');
+ expect(c.status).toBe('warn');
expect(c.message).toContain('deploying [zh]: zh overlay broken');
expect(c.message).toContain('deploying [dense] overview: 41 KB');
expect(c.message).not.toMatch(/deploying overview:/);
diff --git a/packages/cli/authoring/doctypes/_schema.mjs b/packages/cli/authoring/doctypes/_schema.mjs
index 4cccf0b220..05172a44f8 100644
--- a/packages/cli/authoring/doctypes/_schema.mjs
+++ b/packages/cli/authoring/doctypes/_schema.mjs
@@ -15,6 +15,7 @@ import {z} from 'zod';
/** @typedef {import('./base/type.js').AuthoredDocKind} AuthoredDocKind */
/** @typedef {import('./namespace/type.js').NamespaceDoc} NamespaceDoc */
/** @typedef {import('./reference/type.js').ReferenceContentBlock} ReferenceContentBlock */
+/** @typedef {import('./reference/type.js').GraphContentBlock} GraphContentBlock */
/** @typedef {import('./reference/type.js').ReferenceDoc} ReferenceDoc */
/** @typedef {import('./component/type.js').SingleComponentDoc} SingleComponentDoc */
/** @typedef {import('./base/type.js').ComponentPropDoc} ComponentPropDoc */
@@ -161,7 +162,7 @@ const ReferenceBlockSchema = z
})
.strict();
-/** Runtime schema for every existing and V1 semantic content block. */
+/** Runtime schema for the stable content-block union published in 0.6.x. */
export const ReferenceContentBlockSchema = z.discriminatedUnion('type', [
ProseBlockSchema,
HeadingBlockSchema,
@@ -169,6 +170,23 @@ export const ReferenceContentBlockSchema = z.discriminatedUnion('type', [
TableBlockSchema,
ListBlockSchema,
TokenReferenceBlockSchema,
+]);
+
+/** Runtime schema for graph-only blocks used by NamespaceDoc. */
+export const GraphContentBlockSchema = z.discriminatedUnion('type', [
+ WorkflowBlockSchema,
+ CollectionBlockSchema,
+ ReferenceBlockSchema,
+]);
+
+/** Namespace content accepts both stable reference blocks and graph-only blocks. */
+export const NamespaceContentBlockSchema = z.discriminatedUnion('type', [
+ ProseBlockSchema,
+ HeadingBlockSchema,
+ CodeBlockSchema,
+ TableBlockSchema,
+ ListBlockSchema,
+ TokenReferenceBlockSchema,
WorkflowBlockSchema,
CollectionBlockSchema,
ReferenceBlockSchema,
@@ -183,6 +201,15 @@ export const ReferenceContentBlockSchema = z.discriminatedUnion('type', [
* >} _ReferenceContentBlockDriftLock
*/
+/**
+ * @typedef {import('../_shared/contract.js').Expect<
+ * import('../_shared/contract.js').Equal<
+ * z.infer<typeof GraphContentBlockSchema>,
+ * GraphContentBlock
+ * >
+ * >} _GraphContentBlockDriftLock
+ */
+
const ReferenceSectionSchema = z
.object({
id: nonEmptyString.optional(),
@@ -605,7 +632,7 @@ export const NamespaceDocKindSchema = z
.strict(),
)
.optional(),
- blocks: z.array(ReferenceContentBlockSchema).optional(),
+ blocks: z.array(NamespaceContentBlockSchema).optional(),
})
.strict()
.superRefine((doc, context) => {
diff --git a/packages/cli/authoring/doctypes/load-contract.test.mjs b/packages/cli/authoring/doctypes/load-contract.test.mjs
index aecc61b9da..7be86e34a3 100644
--- a/packages/cli/authoring/doctypes/load-contract.test.mjs
+++ b/packages/cli/authoring/doctypes/load-contract.test.mjs
@@ -71,7 +71,7 @@ describe('load check vs published type', () => {
expect(() => parseDoc(EXAMPLES[kind], `${kind}.doc.mjs`)).not.toThrow();
}
expect(() => parseDoc({type: 'widget', name: 'x'}, 'x.doc.mjs')).toThrow(
- /unsupported type "widget"/,
+ /x\.doc\.mjs is invalid/u,
);
});
});
diff --git a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
index 80be4eca49..4d1d31b3ac 100644
--- a/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
+++ b/packages/cli/authoring/doctypes/namespace/namespace.doc.mjs
@@ -78,9 +78,9 @@ export const doc = {
},
{
name: 'blocks',
- type: 'ReferenceContentBlock[]',
+ type: '(ReferenceContentBlock | GraphContentBlock)[]',
description:
- 'Ordered layout content. V1 adds only workflow, collection, and reference to the existing prose, heading, code, table, list, and token-ref blocks.',
+ 'Ordered layout content. Graph-only workflow, collection, and reference blocks are available here without widening the stable ReferenceContentBlock union used by existing topic renderers.',
},
],
examples: [
diff --git a/packages/cli/authoring/doctypes/namespace/parse.test.mjs b/packages/cli/authoring/doctypes/namespace/parse.test.mjs
index 22f6e8b2d8..704f59402b 100644
--- a/packages/cli/authoring/doctypes/namespace/parse.test.mjs
+++ b/packages/cli/authoring/doctypes/namespace/parse.test.mjs
@@ -134,32 +134,30 @@ describe('NamespaceDoc', () => {
});
});
-describe('semantic blocks in existing docs', () => {
- it('accepts workflow, collection, and reference in a ReferenceDoc section', () => {
- const parsed = parseReference({
- type: 'generic',
- name: 'publishing',
- title: 'Publishing',
- description: 'Publish an integration.',
- sections: [
- {
- id: 'start',
- title: 'Start',
- content: namespaceDoc.blocks,
- },
- ],
- });
- expect(parsed.sections[0].id).toBe('start');
- expect(parsed.sections[0].content.map(block => block.type)).toEqual([
- 'workflow',
- 'collection',
- 'reference',
- ]);
+describe('semantic graph blocks', () => {
+ it('keeps graph-only blocks out of the stable ReferenceDoc section union', () => {
+ expect(() =>
+ parseReference({
+ type: 'generic',
+ name: 'publishing',
+ title: 'Publishing',
+ description: 'Publish an integration.',
+ sections: [
+ {
+ id: 'start',
+ title: 'Start',
+ content: namespaceDoc.blocks,
+ },
+ ],
+ }),
+ ).toThrow(/Invalid discriminator value/u);
});
- it('rejects an unknown stamped doc kind instead of treating it as legacy', () => {
- expect(() => parseDoc({type: 'choice', name: 'x', props: []})).toThrow(
- /unsupported type "choice"/u,
- );
+ it('keeps shape-sniffing an unknown stamp for 0.6.x compatibility', () => {
+ expect(parseDoc({type: 'choice', name: 'x', props: []})).toMatchObject({
+ type: 'choice',
+ name: 'x',
+ props: [],
+ });
});
});
diff --git a/packages/cli/authoring/doctypes/namespace/type.ts b/packages/cli/authoring/doctypes/namespace/type.ts
index 3363d4586d..3524c56958 100644
--- a/packages/cli/authoring/doctypes/namespace/type.ts
+++ b/packages/cli/authoring/doctypes/namespace/type.ts
@@ -7,7 +7,10 @@
*/
import type {AuthoredDocGraphFields, AuthoredDocKind} from '../base/type.js';
-import type {ReferenceContentBlock} from '../reference/type.js';
+import type {
+ GraphContentBlock,
+ ReferenceContentBlock,
+} from '../reference/type.js';
/** Which providers may contribute appearances to a namespace slot. */
export type NamespaceProviderScope = 'same' | 'configured';
@@ -67,5 +70,5 @@ export interface NamespaceDoc extends AuthoredDocGraphFields {
/** Optional source-adoption rules for otherwise-unplaced docs. */
adopts?: NamespaceAdoptionRule[];
/** Ordered renderer-neutral content and collection blocks. */
- blocks?: ReferenceContentBlock[];
+ blocks?: (ReferenceContentBlock | GraphContentBlock)[];
}
diff --git a/packages/cli/authoring/doctypes/parse.mjs b/packages/cli/authoring/doctypes/parse.mjs
index 838c149d0e..decc3a7cd4 100644
--- a/packages/cli/authoring/doctypes/parse.mjs
+++ b/packages/cli/authoring/doctypes/parse.mjs
@@ -67,8 +67,9 @@ export function parseDoc(input, label = 'doc') {
case 'theme':
return parseTheme(input, label);
case undefined:
- return parseLegacyDoc(input, label);
default:
- throw new Error(`${label} has unsupported type ${JSON.stringify(type)}.`);
+ // 0.6.x shape-sniffed unknown stamps. Keep accepting them through the
+ // patch compatibility window; canonical writers emit a known stamp.
+ return parseLegacyDoc(input, label);
}
}
diff --git a/packages/cli/authoring/doctypes/reference/reference.doc.mjs b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
index dba70a005d..7c15fd860d 100644
--- a/packages/cli/authoring/doctypes/reference/reference.doc.mjs
+++ b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
@@ -95,7 +95,7 @@ export const doc = {
name: 'sections[].content',
type: 'ReferenceContentBlock[]',
description:
- 'Ordered content blocks: prose, heading, code, table, list, and token-ref. workflow, collection, and reference are declared for the docs graph and parse, but a topic that uses one fails to load until the docs graph ships.',
+ 'Ordered content blocks: prose, heading, code, table, list, and token-ref. Graph-only workflow, collection, and reference blocks are available through GraphContentBlock on NamespaceDoc, without widening this stable union.',
required: true,
},
{
@@ -144,7 +144,7 @@ export const docs = {
},
{
type: 'prose',
- text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, a discriminated union. workflow, collection, and reference are declared for the docs graph: they parse, but topic loading rejects them until the docs graph ships. choice, callout, and checklist remain invalid. The same union is reused by the `notes` field on SchemaDoc and CommandDoc.',
+ text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock, the stable discriminated union of prose, heading, code, table, list, and token-ref. Docs-graph-only workflow, collection, and reference blocks are exported separately as GraphContentBlock and accepted by NamespaceDoc. choice, callout, and checklist remain invalid. ReferenceContentBlock is also reused by the `notes` field on SchemaDoc and CommandDoc.',
},
{
type: 'code',
@@ -156,7 +156,9 @@ export const docs = {
| { type: 'code'; lang: string; code: string; label?: string }
| { type: 'table'; headers: string[]; rows: string[][] }
| { type: 'list'; style: 'ordered' | 'unordered' | 'do' | 'dont'; items: string[] }
- | { type: 'token-ref'; topic: string; section: string }
+ | { type: 'token-ref'; topic: string; section: string };
+
+type GraphContentBlock =
| { type: 'workflow'; title?: string; steps: WorkflowStep[] }
| { type: 'collection'; source: {slot: string}; presentation?: 'list' | 'cards' | 'compact'; whenEmpty?: 'show' | 'omit' }
| { type: 'reference'; target: string; projection?: {fields?: string[]; sections?: string[]} };`,
diff --git a/packages/cli/authoring/doctypes/reference/type.ts b/packages/cli/authoring/doctypes/reference/type.ts
index e6e8a70b7a..172aa941ff 100644
--- a/packages/cli/authoring/doctypes/reference/type.ts
+++ b/packages/cli/authoring/doctypes/reference/type.ts
@@ -41,8 +41,13 @@ export interface ReferenceDocBlock {
presentation?: 'summary' | 'compact' | 'full';
}
+/** Graph-only content blocks. These are additive and do not widen the stable
+ * {@link ReferenceContentBlock} union consumed by existing exhaustive renderers. */
+export type GraphContentBlock =
+ WorkflowDocBlock | CollectionDocBlock | ReferenceDocBlock;
+
/**
- * A content block within a reference doc section or namespace.
+ * A content block within a reference doc section.
* Ordered arrays of these blocks form renderer-neutral documentation content.
* A new semantic kind must ship with every renderer or fail visibly at a legacy
* reader boundary until that renderer is available.
@@ -55,9 +60,6 @@ export interface ReferenceDocBlock {
* { type: 'table', headers: ['Token', 'Value'], rows: [['--spacing-4', '16px']] }
* { type: 'list', style: 'do', items: ['Use semantic tokens'] }
* { type: 'token-ref', topic: 'tokens', section: 'Color Tokens' }
- * { type: 'workflow', steps: [{title: 'Validate', references: ['command:doctor']}] }
- * { type: 'collection', source: {slot: 'guides'}, presentation: 'cards' }
- * { type: 'reference', target: 'schema:integration', projection: {fields: ['docs']} }
* ```
*/
export type ReferenceContentBlock =
@@ -80,10 +82,7 @@ export type ReferenceContentBlock =
topic: string;
/** Section title to pull from that topic. e.g. `'Color Tokens'` */
section: string;
- }
- | WorkflowDocBlock
- | CollectionDocBlock
- | ReferenceDocBlock;
+ };
/**
* A reference documentation file (.doc.mjs).
diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.ts
index 4ea443bfec..fd7b038591 100644
--- a/packages/cli/authoring/index.d.ts
+++ b/packages/cli/authoring/index.d.ts
@@ -131,6 +131,7 @@ export type {
// reference
ReferenceSection,
ReferenceContentBlock,
+ GraphContentBlock,
ReferenceTokenPreviewType,
ReferenceTranslationDoc,
WorkflowStep,
diff --git a/packages/cli/clients/cli/commands/docs.mjs b/packages/cli/clients/cli/commands/docs.mjs
index 048d2939b7..3a912ba23f 100644
--- a/packages/cli/clients/cli/commands/docs.mjs
+++ b/packages/cli/clients/cli/commands/docs.mjs
@@ -23,8 +23,6 @@ import {
text,
code,
wrapText,
- displayWidth,
- WRAP_WIDTH,
} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {defineCommand} from '../lib/define-command.mjs';
@@ -52,28 +50,6 @@ function formatTable(headers, rows) {
return `${head}\n${sep}\n${body}`;
}
-/**
- * A table too wide for {@link WRAP_WIDTH}: one `header: cell` line per cell and
- * a blank line between rows, so nothing runs off the side of a terminal.
- * @param {string[]} headers
- * @param {string[][]} rows
- * @returns {string}
- */
-function formatTableVertical(headers, rows) {
- const width = Math.max(...headers.map(h => h.length)) + 2;
- return rows
- .map(row =>
- headers
- .map((h, i) =>
- wrapText(`${`${h}:`.padEnd(width)}${row[i] ?? ''}`, {
- indent: ' '.repeat(width),
- }),
- )
- .join('\n'),
- )
- .join('\n\n');
-}
-
/**
* @param {string[]} headers
* @param {string[][]} rows
@@ -91,7 +67,7 @@ function formatTableCompact(headers, rows) {
function formatBlock(block, detail) {
switch (block.type) {
case 'prose':
- return wrapText(block.text);
+ return block.text;
case 'heading':
return `${'#'.repeat(block.level || 3)} ${block.text}`;
@@ -110,12 +86,7 @@ function formatBlock(block, detail) {
if (detail === 'compact') {
return formatTableCompact(block.headers, block.rows);
}
- {
- const table = formatTable(block.headers, block.rows);
- return table.split('\n').some(line => displayWidth(line) > WRAP_WIDTH)
- ? formatTableVertical(block.headers, block.rows)
- : table;
- }
+ return formatTable(block.headers, block.rows);
case 'list': {
const prefix =
@@ -126,21 +97,9 @@ function formatBlock(block, detail) {
: block.style === 'do'
? () => '+ '
: () => '- ';
- return block.items
- .map((item, i) => {
- const head = prefix(i);
- return wrapText(`${head}${item}`, {indent: ' '.repeat(head.length)});
- })
- .join('\n');
+ return block.items.map((item, i) => `${prefix(i)}${item}`).join('\n');
}
- case 'workflow':
- case 'collection':
- case 'reference':
- throw new Error(
- `Documentation block "${block.type}" requires the compiled graph renderer.`,
- );
-
default:
return null;
}
@@ -173,16 +132,15 @@ function formatSection(section, detail) {
*/
function formatReferenceFull(docs, detail) {
if (detail === 'brief') {
- const header = wrapText(`${docs.title}: ${docs.description}`);
+ const header = `${docs.title}: ${docs.description}`;
const sections = docs.sections.map(s => formatSection(s, detail));
return `${header}\n${sections.join('\n')}`;
}
- const description = wrapText(docs.description);
const header =
detail === 'compact'
- ? `# ${docs.title}\n${description}`
- : `# ${docs.title}\n\n${description}`;
+ ? `# ${docs.title}\n${docs.description}`
+ : `# ${docs.title}\n\n${docs.description}`;
const sections = docs.sections.map(s => formatSection(s, detail));
const sep = detail === 'compact' ? '\n\n' : '\n\n';
return `${header}\n\n${sections.join(sep)}`;
@@ -196,7 +154,10 @@ function formatReferenceFull(docs, detail) {
*/
function emitIndex(index, run) {
emit(
- section(index.title, index.description ? wrapText(index.description) : undefined),
+ section(
+ index.title,
+ index.description ? wrapText(index.description) : undefined,
+ ),
records(index.sections, {
fields: ['id', 'title', 'summary'],
layout: 'inline',
@@ -275,19 +236,15 @@ export function registerDocs(program) {
switch (result.type) {
case 'docs.list': {
- // The text view mirrors the JSON list: one record per topic (topic +
- // description), then the usage footer as plain prose.
+ // Keep the published 0.6 text projection: stacked topic and
+ // description fields, followed by the two original usage lines.
emit(
section('Available docs'),
- records(result.data, {
- fields: ['topic', 'description', 'package'],
- layout: 'inline',
- }),
+ records(result.data, {fields: ['topic', 'description']}),
text(
[
- `Usage: ${run} docs <topic> read the whole topic`,
- ` ${run} docs <topic> --index list its sections`,
- ` ${run} docs <topic> <section> read one section`,
+ `Usage: ${run} docs <topic>`,
+ ` ${run} docs <topic> <section>`,
].join('\n'),
),
);
diff --git a/packages/cli/clients/cli/commands/docs.test.mjs b/packages/cli/clients/cli/commands/docs.test.mjs
index 7d4cd04b69..d2c0d8e220 100644
--- a/packages/cli/clients/cli/commands/docs.test.mjs
+++ b/packages/cli/clients/cli/commands/docs.test.mjs
@@ -108,11 +108,11 @@ describe('progressive reads', () => {
/** @param {string} out */
const widest = out => Math.max(...out.split('\n').map(line => line.length));
- it('lists every topic on one line each', async () => {
+ it('keeps the 0.6.x stacked topic list', async () => {
const {status, stdout} = await runCli(['docs']);
expect(status).toBe(0);
- expect(stdout).toMatch(/^principles +\S/m);
- expect(widest(stdout)).toBeLessThanOrEqual(120);
+ expect(stdout).toMatch(/^topic: +principles$/m);
+ expect(stdout).toContain('Usage: pnpm exec astryx docs <topic>');
}, SLOW);
it("prints a topic's section index with the keys to read by", async () => {
@@ -139,9 +139,6 @@ describe('progressive reads', () => {
expect((await runCli(['--detail', 'full', 'docs', 'theme'])).stdout).toBe(
full.stdout,
);
- expect(widest(full.stdout.replace(/```[\s\S]*?```/g, ''))).toBeLessThanOrEqual(
- 120,
- );
}, SLOW);
it('returns the matching envelopes as JSON', async () => {
@@ -176,14 +173,14 @@ describe('text width in every language', () => {
return max;
};
- it.each([
- [['docs', 'theme', '--index', '--lang', 'zh']],
- [['docs', 'theme', '--lang', 'zh']],
- [['--detail', 'full', 'docs', 'theme', '--lang', 'zh']],
- [['--detail', 'full', 'docs', 'internationalization']],
- [['--detail', 'full', 'docs', 'styling']],
- ])('%j fits in 120 columns', async args => {
- const {status, stdout} = await runCli(args);
+ it('keeps the additive section index within 120 columns', async () => {
+ const {status, stdout} = await runCli([
+ 'docs',
+ 'theme',
+ '--index',
+ '--lang',
+ 'zh',
+ ]);
expect(status).toBe(0);
expect(widest(stdout)).toBeLessThanOrEqual(120);
}, SLOW);
diff --git a/packages/cli/clients/cli/commands/text-json-parity.test.mjs b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
index 6f51834491..44c8399b00 100644
--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs
+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
@@ -310,8 +310,7 @@ const CASES = [
name: 'docs',
args: ['docs'],
jsonFieldAllowlist: [
- 'topic — inline layout lead column, not a key: value record',
- 'description — inline layout trailing column',
+ 'package — omitted to preserve the published 0.6 docs list text contract',
],
},
{
diff --git a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs b/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
index a7643c45a0..eb31990339 100644
--- a/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
+++ b/packages/cli/foundation/discovery/authoring-self-docs.test.mjs
@@ -74,14 +74,15 @@ describe('what the authoring docs say about the unbuilt docs graph', () => {
expect(graphFieldsDoc.description).toMatch(/not built yet/);
});
- it('says a topic using a graph block fails to load', () => {
+ it('keeps graph blocks behind the separate GraphContentBlock type', () => {
const content = referenceDoc.fields
.flatMap(field => [field, ...(field.fields ?? [])])
.find(field => field.name === 'sections[].content');
+ expect(content.type).toBe('ReferenceContentBlock[]');
+ expect(content.description).toContain('GraphContentBlock');
for (const type of GRAPH_BLOCK_TYPES) {
expect(content.description).toContain(type);
}
- expect(content.description).toMatch(/fails to load/);
});
it('says namespace docs are not loaded yet', () => {
diff --git a/packages/cli/foundation/discovery/docs-discovery.mjs b/packages/cli/foundation/discovery/docs-discovery.mjs
index 5a4298e57c..230234c932 100644
--- a/packages/cli/foundation/discovery/docs-discovery.mjs
+++ b/packages/cli/foundation/discovery/docs-discovery.mjs
@@ -37,7 +37,7 @@ import {CLI_PROVIDER_ID} from '../identity/providers.mjs';
import {parseReadableDoc} from '../doc-compiler/parse-readable.mjs';
import {
sectionKey,
- sectionKeyProblems,
+ sectionKeyErrors,
sourceTitle,
withSourceTitle,
} from './docs-section-key.mjs';
@@ -312,9 +312,10 @@ export function problemsInTopic(doc) {
);
},
);
- // Readers address a section by its key, so two sections sharing one would
- // make one of them unreachable.
- problems.push(...sectionKeyProblems(doc.sections));
+ // Explicit authored IDs are a new opt-in contract and remain strict. Topics
+ // that relied on 0.6.x title-only sections keep loading; the compiler assigns
+ // deterministic fallback/suffixed keys for the additive index API.
+ problems.push(...sectionKeyErrors(doc.sections));
return problems;
}
@@ -487,7 +488,7 @@ function findMergeTarget(sections, section) {
const sameTitle = sections.findIndex(
candidate => sourceTitle(candidate) === title,
);
- return sameTitle === -1 ? byKey() : sameTitle;
+ return sameTitle;
}
/**
diff --git a/packages/cli/foundation/discovery/docs-discovery.test.mjs b/packages/cli/foundation/discovery/docs-discovery.test.mjs
index d6afccb3b4..046a3a44f4 100644
--- a/packages/cli/foundation/discovery/docs-discovery.test.mjs
+++ b/packages/cli/foundation/discovery/docs-discovery.test.mjs
@@ -180,7 +180,7 @@ describe('discoverIntegrationDocs', () => {
}),
);
expect(records).toEqual([]);
- expect(errors[0].message).toContain('requires the compiled graph renderer');
+ expect(errors[0].message).toContain('Invalid discriminator value');
});
it('names a namespace doc instead of listing topic fields it lacks', async () => {
@@ -529,12 +529,10 @@ describe('problemsInTopic section keys', () => {
})),
});
- it('rejects two sections that derive the same key', () => {
+ it('keeps legacy title-only key conflicts readable', () => {
expect(
problemsInTopic(doc([{title: 'Quick Start'}, {title: 'Quick-start'}])),
- ).toEqual([
- expect.stringContaining('"quick-start" is already used by sections[0]'),
- ]);
+ ).toEqual([]);
});
it('rejects an unsafe id', () => {
@@ -543,10 +541,8 @@ describe('problemsInTopic section keys', () => {
).toEqual([expect.stringContaining('is not a stable key')]);
});
- it('rejects a title no key derives from, unless it has an id', () => {
- expect(problemsInTopic(doc([{title: '亮/暗模式'}]))).toEqual([
- expect.stringContaining('Give the section an id'),
- ]);
+ it('keeps a legacy title that has no derived key readable', () => {
+ expect(problemsInTopic(doc([{title: '亮/暗模式'}]))).toEqual([]);
expect(
problemsInTopic(doc([{id: 'light-dark', title: '亮/暗模式'}])),
).toEqual([]);
@@ -580,7 +576,7 @@ describe('mergeTopic by section key', () => {
]);
});
- it('replaces the section a title variant derives the same key as', () => {
+ it('keeps a legacy title variant as a separate section', () => {
const merged = mergeTopic(base, {
sections: [
{title: 'Light-Dark Mode', content: [{type: 'prose', text: 'acme'}]},
@@ -588,6 +584,7 @@ describe('mergeTopic by section key', () => {
});
expect(titles(merged)).toEqual([
[null, 'Quick Start', 'base'],
+ [null, 'Light/Dark Mode', 'base'],
[null, 'Light-Dark Mode', 'acme'],
]);
});
diff --git a/packages/cli/foundation/discovery/docs-section-key.mjs b/packages/cli/foundation/discovery/docs-section-key.mjs
index a802bcf021..e66b61d0d6 100644
--- a/packages/cli/foundation/discovery/docs-section-key.mjs
+++ b/packages/cli/foundation/discovery/docs-section-key.mjs
@@ -34,7 +34,10 @@ const SOURCE_TITLE = Symbol('astryx.docs.sourceTitle');
* @returns {T}
*/
export function withSourceTitle(section, title) {
- Object.defineProperty(section, SOURCE_TITLE, {value: title, configurable: true});
+ Object.defineProperty(section, SOURCE_TITLE, {
+ value: title,
+ configurable: true,
+ });
return section;
}
@@ -77,9 +80,63 @@ export function sectionKey(section) {
}
/**
- * Problems with the keys of a topic's sections: an authored id that is not a
- * stable key, a title no key derives from, and two sections sharing a key.
- * Keys are never suffixed to make them unique, because readers link to them.
+ * The first section the 0.6.x title-substring lookup would return for a query.
+ * @param {any[]} sections
+ * @param {string} query
+ * @returns {number}
+ */
+function legacyTitleMatchIndex(sections, query) {
+ const lower = query.toLowerCase();
+ return sections.findIndex(section => {
+ const title = sourceTitle(section);
+ return typeof title === 'string' && title.toLowerCase().includes(lower);
+ });
+}
+
+/**
+ * Fatal key problems: only an explicitly authored `id` can make a previously
+ * readable topic invalid. Derived-key collisions and titles with no Latin
+ * letters or digits are handled by {@link withSectionKeys} for 0.6.x
+ * compatibility.
+ * @param {any[]} sections
+ * @returns {string[]}
+ */
+export function sectionKeyErrors(sections) {
+ /** @type {string[]} */
+ const problems = [];
+ /** @type {Map<string, number>} */
+ const seen = new Map();
+ sections.forEach((section, s) => {
+ if (section?.id == null) return;
+ const at = `sections[${s}]`;
+ if (typeof section.id !== 'string' || !SECTION_KEY_RE.test(section.id)) {
+ problems.push(
+ `${at}.id: ${JSON.stringify(section.id)} is not a stable key. Use lowercase letters and digits joined by single hyphens.`,
+ );
+ return;
+ }
+ const first = seen.get(section.id);
+ if (first != null) {
+ problems.push(
+ `${at}: the key "${section.id}" is already used by sections[${first}]. Give one of them a distinct id.`,
+ );
+ return;
+ }
+ const legacyOwner = legacyTitleMatchIndex(sections, section.id);
+ if (legacyOwner !== -1 && legacyOwner !== s) {
+ problems.push(
+ `${at}.id: the key "${section.id}" is already a legacy title query for sections[${legacyOwner}]. Choose an id that resolves to this section.`,
+ );
+ return;
+ }
+ seen.set(section.id, s);
+ });
+ return problems;
+}
+
+/**
+ * Compatibility notices for section keys. These inputs loaded in 0.6.x, so
+ * readers keep accepting them and assign deterministic fallback keys.
* @param {any[]} sections
* @returns {string[]}
*/
@@ -90,7 +147,6 @@ export function sectionKeyProblems(sections) {
const seen = new Map();
sections.forEach((section, s) => {
const at = `sections[${s}]`;
- // A missing title is reported where titles are checked; no key to judge.
if (
section?.id == null &&
(typeof section?.title !== 'string' || section.title === '')
@@ -109,14 +165,14 @@ export function sectionKeyProblems(sections) {
const key = sectionKey(section);
if (key === '') {
problems.push(
- `${at}: no key derives from the title ${JSON.stringify(section?.title)}. Give the section an id.`,
+ `${at}: no key derives from the title ${JSON.stringify(section?.title)}. A deterministic section-N compatibility key is used; add an explicit id.`,
);
return;
}
const first = seen.get(key);
if (first != null) {
problems.push(
- `${at}: the key "${key}" is already used by sections[${first}]. Give one of them a distinct id or title.`,
+ `${at}: the key "${key}" is already used by sections[${first}]. A suffixed compatibility key is used for title-derived collisions; give one of them a distinct id or title.`,
);
return;
}
@@ -133,48 +189,79 @@ export function sectionKeyProblems(sections) {
* @returns {T}
*/
export function withSectionKeys(doc) {
+ const reserved = new Set(
+ doc.sections
+ .map(section => section?.id)
+ .filter(id => typeof id === 'string' && SECTION_KEY_RE.test(id)),
+ );
+ const used = new Set();
return {
...doc,
- sections: doc.sections.map(section =>
- section.id != null
- ? section
- : withSourceTitle(
- {...section, id: sectionKey(section)},
- sourceTitle(section),
- ),
- ),
+ sections: doc.sections.map((section, index) => {
+ if (section.id != null) {
+ used.add(section.id);
+ return section;
+ }
+ const base =
+ sectionTitleKey(sourceTitle(section)) || `section-${index + 1}`;
+ let key = base;
+ let suffix = 2;
+ while (
+ reserved.has(key) ||
+ used.has(key) ||
+ (legacyTitleMatchIndex(doc.sections, key) !== -1 &&
+ legacyTitleMatchIndex(doc.sections, key) !== index)
+ ) {
+ key = `${base}-${suffix}`;
+ suffix += 1;
+ }
+ used.add(key);
+ return withSourceTitle({...section, id: key}, sourceTitle(section));
+ }),
};
}
/**
- * Find the section a reader asked for: by key, then by exact title (or the
- * key the query derives), then by a title that contains the query. More than
- * one match is refused rather than guessed.
+ * Find the section a reader asked for. The 0.6.x first-match title-substring
+ * lookup remains first in the authored-title view. In a localized view, an
+ * exact stable key resolves before translated title substrings because those
+ * translations cannot participate in language-stable key allocation. Generated
+ * keys avoid authored-title conflicts, and authored IDs that would shadow an
+ * authored legacy query are rejected.
* @param {any[]} sections
* @param {string} query
- * @returns {{section: any | null, candidates: any[]}} `candidates` lists the
- * matches when the query is ambiguous, and is empty when nothing matches
+ * @returns {{section: any | null, candidates: any[]}} `candidates` lists every
+ * legacy title match when the query is ambiguous
*/
export function findDocSection(sections, query) {
const wanted = query.trim();
const byKey = sections.find(section => sectionKey(section) === wanted);
- if (byKey) return {section: byKey, candidates: []};
+ const hasLocalizedTitles = sections.some(
+ section => sourceTitle(section) !== section.title,
+ );
+ if (byKey && hasLocalizedTitles) {
+ return {section: byKey, candidates: []};
+ }
const lower = wanted.toLowerCase();
- const derived = sectionTitleKey(wanted);
- const exact = sections.filter(
- section =>
- section.title.toLowerCase() === lower ||
- (derived !== '' && sectionTitleKey(sourceTitle(section)) === derived),
+ const legacy = sections.filter(section =>
+ section.title.toLowerCase().includes(lower),
);
- if (exact.length === 1) return {section: exact[0], candidates: []};
- if (exact.length > 1) return {section: null, candidates: exact};
+ if (legacy.length > 0) {
+ return {section: legacy[0], candidates: legacy.length > 1 ? legacy : []};
+ }
- const partial = sections.filter(section =>
- section.title.toLowerCase().includes(lower),
+ const byFallbackKey = sections.find(
+ section => sectionKey(section) === wanted,
+ );
+ if (byFallbackKey) return {section: byFallbackKey, candidates: []};
+
+ const derived = sectionTitleKey(wanted);
+ const byDerivedKey = sections.find(
+ section =>
+ derived !== '' && sectionTitleKey(sourceTitle(section)) === derived,
);
- if (partial.length === 1) return {section: partial[0], candidates: []};
- return {section: null, candidates: partial};
+ return {section: byDerivedKey ?? null, candidates: []};
}
/**
diff --git a/packages/cli/foundation/discovery/docs-section-key.test.mjs b/packages/cli/foundation/discovery/docs-section-key.test.mjs
index 543c938cf8..5a8a0b9d19 100644
--- a/packages/cli/foundation/discovery/docs-section-key.test.mjs
+++ b/packages/cli/foundation/discovery/docs-section-key.test.mjs
@@ -7,6 +7,7 @@ import {
buildDocsIndexData,
findDocSection,
sectionKey,
+ sectionKeyErrors,
sectionKeyProblems,
sectionSummary,
sectionTitleKey,
@@ -68,12 +69,17 @@ describe('sectionKeyProblems', () => {
section('Quick-start'),
]);
expect(problems).toHaveLength(1);
- expect(problems[0]).toContain('"quick-start" is already used by sections[0]');
+ expect(problems[0]).toContain(
+ '"quick-start" is already used by sections[0]',
+ );
});
it('rejects an authored id that collides with a derived key', () => {
expect(
- sectionKeyProblems([section('Install'), section('Setup', {id: 'install'})]),
+ sectionKeyProblems([
+ section('Install'),
+ section('Setup', {id: 'install'}),
+ ]),
).toHaveLength(1);
});
@@ -85,13 +91,13 @@ describe('sectionKeyProblems', () => {
}
});
- it('rejects a title no key derives from', () => {
+ it('reports a title no key derives from', () => {
expect(sectionKeyProblems([section('亮/暗模式')])[0]).toContain(
- 'Give the section an id',
- );
- expect(sectionKeyProblems([section('亮/暗模式', {id: 'light-dark'})])).toEqual(
- [],
+ 'compatibility key is used',
);
+ expect(
+ sectionKeyProblems([section('亮/暗模式', {id: 'light-dark'})]),
+ ).toEqual([]);
});
it('leaves a missing title to the title check', () => {
@@ -107,12 +113,21 @@ describe('withSectionKeys', () => {
expect(doc.sections.map(s => s.id)).toEqual(['quick-start', 'use']);
});
- it('keeps the authored title of a translated section', () => {
+ it('keeps authored titles and keys stable for translated sections', () => {
const doc = withSectionKeys({
- sections: [withSourceTitle(section('快速开始'), 'Quick Start')],
+ sections: [
+ withSourceTitle(section('高级安装'), 'Install advanced'),
+ withSourceTitle(section('安装'), 'Install'),
+ ],
});
- expect(doc.sections[0].id).toBe('quick-start');
- expect(sourceTitle(doc.sections[0])).toBe('Quick Start');
+ expect(doc.sections.map(s => s.id)).toEqual([
+ 'install-advanced',
+ 'install-2',
+ ]);
+ for (const target of doc.sections) {
+ expect(findDocSection(doc.sections, target.id).section).toBe(target);
+ }
+ expect(sourceTitle(doc.sections[0])).toBe('Install advanced');
});
});
@@ -127,7 +142,14 @@ describe('findDocSection', () => {
],
}).sections;
- it('finds a section by key first', () => {
+ it('finds every emitted key without changing a legacy query', () => {
+ const colliding = withSectionKeys({
+ sections: [section('Install advanced'), section('Install')],
+ }).sections;
+ expect(findDocSection(colliding, 'install').section).toBe(colliding[0]);
+ for (const target of colliding) {
+ expect(findDocSection(colliding, target.id).section).toBe(target);
+ }
expect(findDocSection(sections, 'tokens').section.title).toBe(
'Theme Tokens',
);
@@ -149,15 +171,15 @@ describe('findDocSection', () => {
expect(findDocSection(sections, 'props').section.id).toBe('theme-props');
});
- it('refuses an ambiguous exact title and lists the candidates', () => {
+ it('keeps the first ambiguous exact-title match and lists the candidates', () => {
const {section: match, candidates} = findDocSection(sections, 'Overview');
- expect(match).toBeNull();
+ expect(match?.id).toBe('overview-a');
expect(candidates.map(s => s.id)).toEqual(['overview-a', 'overview-b']);
});
- it('refuses an ambiguous partial title', () => {
+ it('keeps the first ambiguous partial-title match', () => {
const {section: match, candidates} = findDocSection(sections, 'theme');
- expect(match).toBeNull();
+ expect(match?.id).toBe('theme-props');
expect(candidates.map(s => s.id)).toEqual(['theme-props', 'tokens']);
});
@@ -185,9 +207,9 @@ describe('sectionSummary', () => {
});
it('is empty when the section has no text', () => {
- expect(sectionSummary({content: [{type: 'table', headers: [], rows: []}]})).toBe(
- '',
- );
+ expect(
+ sectionSummary({content: [{type: 'table', headers: [], rows: []}]}),
+ ).toBe('');
});
it('cuts a long summary at a word boundary', () => {
diff --git a/packages/cli/foundation/doc-compiler/compile.mjs b/packages/cli/foundation/doc-compiler/compile.mjs
index f34554a479..91cf473a13 100644
--- a/packages/cli/foundation/doc-compiler/compile.mjs
+++ b/packages/cli/foundation/doc-compiler/compile.mjs
@@ -26,7 +26,7 @@ import {parseTheme} from '../../authoring/doctypes/theme/parse.mjs';
import {mergeTopic, problemsInTopic} from '../discovery/docs-discovery.mjs';
import {
sectionKey,
- sectionKeyProblems,
+ sectionKeyErrors,
sourceTitle,
withSectionKeys,
withSourceTitle,
@@ -130,11 +130,12 @@ export function lowerReferenceTopic(input) {
let doc = readAuthoredFile(input.base);
for (const extension of input.extensions) {
doc = mergeTopic(doc, readAuthoredFile(extension));
- // Merging matches on keys, so this holds unless merge itself regresses.
- const problems = sectionKeyProblems(doc.sections);
+ // Explicit authored IDs remain strict. Legacy title-derived collisions are
+ // assigned deterministic compatibility keys after every extension merges.
+ const problems = sectionKeyErrors(doc.sections);
if (problems.length > 0) {
throw new Error(
- `${extension.file}, extending ${input.id}, leaves two sections with one key: ${problems.join('; ')}`,
+ `${extension.file}, extending ${input.id}, leaves duplicate authored section IDs: ${problems.join('; ')}`,
);
}
}