@astryxdesign/cli 0.6.6-canary.4470b92 → 0.6.6-canary.4ec0d0e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17,3 +17,47 @@ export function section(topic: string, sectionName: string, options?: {
17
17
  dense?: boolean | undefined;
18
18
  cwd?: string | undefined;
19
19
  }): Promise<import("../../docs.type.mjs").DocsDetailSectionResponse>;
20
+ /**
21
+ * @typedef {object} GuideMatch
22
+ * @property {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode} guide
23
+ * @property {Awaited<ReturnType<typeof resolveTopicDocs>>} resolved
24
+ * @property {any[]} sections the guide's reader sections
25
+ * @property {any} match the section it has
26
+ */
27
+ /**
28
+ * One section of a namespace (spec:AST-046 FR6): the section read of the one
29
+ * guide below the namespace, at any depth, that has it. Each guide answers
30
+ * with the section its own section read returns for the query; when that
31
+ * section's key (its `id`, else the key its title derives) is the query in
32
+ * some guides, those guides answer first. No guide, or several, fail with ERR_UNKNOWN_SECTION, naming
33
+ * the guides to read instead.
34
+ * @param {import('../../../../foundation/doc-compiler/tree.mjs').DocsTree} tree
35
+ * @param {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode} namespace
36
+ * @param {string} sectionName
37
+ * @param {object} [options] as {@link section}
38
+ * @returns {Promise<import('../../docs.type.mjs').DocsDetailSectionResponse>}
39
+ */
40
+ export function namespaceSection(tree: import("../../../../foundation/doc-compiler/tree.mjs").DocsTree, namespace: import("../../../../foundation/doc-compiler/tree.mjs").TreeNode, sectionName: string, options?: object): Promise<import("../../docs.type.mjs").DocsDetailSectionResponse>;
41
+ /**
42
+ * The guide a namespace section read answers from, or null to ask. When the
43
+ * query matches sections in several guides, the read asks the reader which
44
+ * guide they mean (spec:AST-046 FR6), where a flat topic's section read
45
+ * returned its first title match. To return the first match in tree order
46
+ * instead, return `matches[0]` here.
47
+ * @param {GuideMatch[]} matches in tree order
48
+ * @returns {GuideMatch | null}
49
+ */
50
+ export function oneGuide(matches: GuideMatch[]): GuideMatch | null;
51
+ export type GuideMatch = {
52
+ guide: import("../../../../foundation/doc-compiler/tree.mjs").TreeNode;
53
+ resolved: Awaited<ReturnType<typeof resolveTopicDocs>>;
54
+ /**
55
+ * the guide's reader sections
56
+ */
57
+ sections: any[];
58
+ /**
59
+ * the section it has
60
+ */
61
+ match: any;
62
+ };
63
+ import { resolveTopicDocs } from '../../_adapter.mjs';
@@ -11,6 +11,9 @@
11
11
  * token-ref blocks inlined — matching `astryx --json docs <topic> <section>`.
12
12
  * Throws ERR_UNKNOWN_SECTION when nothing matches, or when the query matches
13
13
  * more than one section (the candidates come back as suggestions).
14
+ * A namespace's section read (spec:AST-046 FR6) finds the one guide below the
15
+ * namespace that has the section and answers exactly as that guide's section
16
+ * read does.
14
17
  * @position Leaf nested under api/docs/detail. Shares topic resolution with the
15
18
  * detail leaf via _adapter.mjs and reads through the compiler's lenses.
16
19
  */
@@ -20,6 +23,8 @@ import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
20
23
  import {
21
24
  findDocSection,
22
25
  sectionKey,
26
+ sectionTitleKey,
27
+ sourceTitle,
23
28
  } from '../../../../foundation/discovery/docs-section-key.mjs';
24
29
  import {linkReferenceSection} from '../../../../foundation/doc-compiler/compile.mjs';
25
30
  import {
@@ -43,19 +48,9 @@ import {
43
48
  * @returns {Promise<import('../../docs.type.mjs').DocsDetailSectionResponse>}
44
49
  */
45
50
  export async function section(topic, sectionName, options = {}) {
46
- // An empty section name must error, not resolve to the first section. The
47
- // docs() dispatcher routes a falsy section to the topic, but the leaf must be
48
- // safe on its own; a non-string would otherwise throw a raw TypeError.
49
- if (typeof sectionName !== 'string' || !sectionName.trim()) {
50
- throw new AstryxError(
51
- 'A section name is required',
52
- undefined,
53
- ERROR_CODES.ERR_UNKNOWN_SECTION,
54
- );
55
- }
56
-
57
- const {catalog, node, lang, entry} = await resolveTopicDocs(topic, options);
58
- const sections = readerSections(node);
51
+ requireSectionName(sectionName);
52
+ const resolved = await resolveTopicDocs(topic, options);
53
+ const sections = readerSections(resolved.node);
59
54
  const {section: match} = findDocSection(sections, sectionName);
60
55
  if (!match) {
61
56
  throw new AstryxError(
@@ -68,6 +63,33 @@ export async function section(topic, sectionName, options = {}) {
68
63
  );
69
64
  }
70
65
 
66
+ return sectionResponse(resolved, sections, match);
67
+ }
68
+
69
+ /**
70
+ * An empty section name must error, not resolve to the first section. The
71
+ * docs() dispatcher routes a falsy section to the topic, but a leaf must be
72
+ * safe on its own; a non-string would otherwise throw a raw TypeError.
73
+ * @param {unknown} sectionName
74
+ */
75
+ function requireSectionName(sectionName) {
76
+ if (typeof sectionName !== 'string' || !sectionName.trim()) {
77
+ throw new AstryxError(
78
+ 'A section name is required',
79
+ undefined,
80
+ ERROR_CODES.ERR_UNKNOWN_SECTION,
81
+ );
82
+ }
83
+ }
84
+
85
+ /**
86
+ * The docs.detail.section response for one section of a resolved topic.
87
+ * @param {Awaited<ReturnType<typeof resolveTopicDocs>>} resolved
88
+ * @param {any[]} sections the topic's reader sections
89
+ * @param {any} match one of them
90
+ * @returns {Promise<import('../../docs.type.mjs').DocsDetailSectionResponse>}
91
+ */
92
+ async function sectionResponse({catalog, node, lang, entry}, sections, match) {
71
93
  // A section read on its own inlines its token refs, as the whole topic does;
72
94
  // otherwise a section that is only a token-ref prints blank. Only this
73
95
  // section is linked, so a broken reference elsewhere cannot fail the read.
@@ -93,3 +115,132 @@ export async function section(topic, sectionName, options = {}) {
93
115
  data: {...sectionView(node, linked), links},
94
116
  };
95
117
  }
118
+
119
+ /**
120
+ * @typedef {object} GuideMatch
121
+ * @property {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode} guide
122
+ * @property {Awaited<ReturnType<typeof resolveTopicDocs>>} resolved
123
+ * @property {any[]} sections the guide's reader sections
124
+ * @property {any} match the section it has
125
+ */
126
+
127
+ /**
128
+ * One section of a namespace (spec:AST-046 FR6): the section read of the one
129
+ * guide below the namespace, at any depth, that has it. Each guide answers
130
+ * with the section its own section read returns for the query; when that
131
+ * section's key (its `id`, else the key its title derives) is the query in
132
+ * some guides, those guides answer first. No guide, or several, fail with ERR_UNKNOWN_SECTION, naming
133
+ * the guides to read instead.
134
+ * @param {import('../../../../foundation/doc-compiler/tree.mjs').DocsTree} tree
135
+ * @param {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode} namespace
136
+ * @param {string} sectionName
137
+ * @param {object} [options] as {@link section}
138
+ * @returns {Promise<import('../../docs.type.mjs').DocsDetailSectionResponse>}
139
+ */
140
+ export async function namespaceSection(
141
+ tree,
142
+ namespace,
143
+ sectionName,
144
+ options = {},
145
+ ) {
146
+ requireSectionName(sectionName);
147
+ const guides = guidesBelow(tree, namespace);
148
+ /** @type {Omit<GuideMatch, 'match'>[]} */
149
+ const reads = [];
150
+ for (const guide of guides) {
151
+ const resolved = await resolveTopicDocs(guide.route, options);
152
+ reads.push({guide, resolved, sections: readerSections(resolved.node)});
153
+ }
154
+
155
+ const wanted = sectionName.trim();
156
+ const derived = sectionTitleKey(wanted);
157
+ /** @type {GuideMatch[]} */
158
+ const byKey = [];
159
+ /** @type {GuideMatch[]} */
160
+ const found = [];
161
+ for (const read of reads) {
162
+ // The section the guide's own section read returns for this query, so the
163
+ // namespace read answers exactly what `astryx docs <guide> <section>` does.
164
+ const {section: match} = findDocSection(read.sections, wanted);
165
+ if (!match) continue;
166
+ found.push({...read, match});
167
+ if (
168
+ sectionKey(match) === wanted ||
169
+ (derived !== '' && sectionTitleKey(sourceTitle(match)) === derived)
170
+ ) {
171
+ byKey.push({...read, match});
172
+ }
173
+ }
174
+ const matches = byKey.length > 0 ? byKey : found;
175
+ const chosen = oneGuide(matches);
176
+ if (chosen)
177
+ return sectionResponse(chosen.resolved, chosen.sections, chosen.match);
178
+
179
+ if (guides.length === 0) {
180
+ // A namespace with no guide below it (a reference level such as cli/api)
181
+ // has no sections to read: name its children, as before.
182
+ throw new AstryxError(
183
+ `"${namespace.route}" has no sections. Open one of its children instead.`,
184
+ namespace.slots.flatMap(slot =>
185
+ slot.children.map(route => ({
186
+ name: route,
187
+ reason: tree.get(route)?.summary ?? '',
188
+ })),
189
+ ),
190
+ ERROR_CODES.ERR_UNKNOWN_SECTION,
191
+ );
192
+ }
193
+ if (matches.length === 0) {
194
+ throw new AstryxError(
195
+ `Section "${sectionName}" is not in any guide under "${namespace.route}". Open one of its guides instead.`,
196
+ guides.map(guide => ({name: guide.route, reason: guide.summary})),
197
+ ERROR_CODES.ERR_UNKNOWN_SECTION,
198
+ );
199
+ }
200
+ throw new AstryxError(
201
+ `Section "${sectionName}" matches sections in more than one guide under "${namespace.route}". Read it from one of them.`,
202
+ matches.map(({guide, match}) => ({
203
+ name: guide.route,
204
+ reason: `has "${match.title}"`,
205
+ })),
206
+ ERROR_CODES.ERR_UNKNOWN_SECTION,
207
+ );
208
+ }
209
+
210
+ /**
211
+ * The guide a namespace section read answers from, or null to ask. When the
212
+ * query matches sections in several guides, the read asks the reader which
213
+ * guide they mean (spec:AST-046 FR6), where a flat topic's section read
214
+ * returned its first title match. To return the first match in tree order
215
+ * instead, return `matches[0]` here.
216
+ * @param {GuideMatch[]} matches in tree order
217
+ * @returns {GuideMatch | null}
218
+ */
219
+ export function oneGuide(matches) {
220
+ return matches.length === 1 ? matches[0] : null;
221
+ }
222
+
223
+ /**
224
+ * Every guide below a namespace, at any depth, in tree order.
225
+ * @param {import('../../../../foundation/doc-compiler/tree.mjs').DocsTree} tree
226
+ * @param {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode} namespace
227
+ * @returns {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode[]}
228
+ */
229
+ function guidesBelow(tree, namespace) {
230
+ /** @type {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode[]} */
231
+ const guides = [];
232
+ /** @param {import('../../../../foundation/doc-compiler/tree.mjs').TreeNode} parent */
233
+ const walk = parent => {
234
+ for (const slot of parent.slots) {
235
+ for (const route of slot.children) {
236
+ const child = tree.get(route);
237
+ if (!child || child.parent !== parent.route) continue;
238
+ if (child.kind === 'namespace') walk(child);
239
+ else if (child.kind === 'generic' && child.ref?.topicFile)
240
+ guides.push(child);
241
+ }
242
+ }
243
+ };
244
+ walk(namespace);
245
+ return guides;
246
+ }
@@ -121,7 +121,7 @@ export const doc = {
121
121
  {
122
122
  type: 'docs.detail.section',
123
123
  description:
124
- 'One ReferenceSection of the topic, found by key or title, with token-ref and reference blocks inlined.',
124
+ 'One ReferenceSection of the topic, found by key or title, with token-ref and reference blocks inlined. Asked of a docs-tree namespace, it is the section read of the one guide below the namespace that has the section.',
125
125
  },
126
126
  {
127
127
  type: 'docs.node',
@@ -144,7 +144,7 @@ export const doc = {
144
144
  },
145
145
  {
146
146
  code: 'ERR_UNKNOWN_SECTION',
147
- when: 'a section is requested but is empty, matches no section, matches more than one, or is asked of a docs-tree namespace or typed doc, which have no sections',
147
+ when: 'a section is requested but is empty, matches no section, or matches more than one; asked of a docs-tree namespace, when no guide below it or more than one has the section (suggestions name those guides); or asked of a typed doc, which has no sections',
148
148
  },
149
149
  ],
150
150
  examples: [
package/api/docs/docs.mjs CHANGED
@@ -26,7 +26,10 @@
26
26
  import {list} from './list/list.mjs';
27
27
  import {index} from './index/index.mjs';
28
28
  import {detail} from './detail/detail.mjs';
29
- import {section as sectionLeaf} from './detail/section/section.mjs';
29
+ import {
30
+ namespaceSection,
31
+ section as sectionLeaf,
32
+ } from './detail/section/section.mjs';
30
33
  import {node as nodeLeaf, nodeView} from './node/node.mjs';
31
34
  import {resolveDocsArgument} from './_adapter.mjs';
32
35
  import {AstryxError} from '../error.mjs';
@@ -98,23 +101,15 @@ export async function docs(topic, section, options = {}) {
98
101
  if (!topic) return list(options);
99
102
  const found = await resolveDocsArgument(topic, options);
100
103
  if (found.kind === 'node') {
101
- // A namespace or a typed doc has no sections: it is one read. `--index`
102
- // asks for what the node read already is.
103
104
  if (section) {
105
+ // A namespace answers a section read from the one guide below it that
106
+ // has the section (spec:AST-046 FR6). A typed doc is one read.
107
+ if (found.node.kind === 'namespace') {
108
+ return namespaceSection(found.tree, found.node, section, options);
109
+ }
104
110
  throw new AstryxError(
105
- `"${found.node.route}" has no sections. ${
106
- found.node.kind === 'namespace'
107
- ? 'Open one of its children instead.'
108
- : `Read it whole: astryx docs ${found.node.route}.`
109
- }`,
110
- found.node.kind === 'namespace'
111
- ? found.node.slots.flatMap(slot =>
112
- slot.children.map(route => ({
113
- name: route,
114
- reason: found.tree.get(route)?.summary ?? '',
115
- })),
116
- )
117
- : [{name: found.node.route, reason: found.node.summary}],
111
+ `"${found.node.route}" has no sections. Read it whole: astryx docs ${found.node.route}.`,
112
+ [{name: found.node.route, reason: found.node.summary}],
118
113
  ERROR_CODES.ERR_UNKNOWN_SECTION,
119
114
  );
120
115
  }
@@ -240,16 +240,15 @@ describe('docs() dispatcher routing', () => {
240
240
  );
241
241
  }, SLOW);
242
242
 
243
- it('a section of a namespace -> ERR_UNKNOWN_SECTION, naming its children', async () => {
244
- const err = await docs('cli', 'commands').catch(e => e);
243
+ it('a section no guide of a namespace has -> ERR_UNKNOWN_SECTION, naming its guides', async () => {
244
+ const err = await docs('cli', 'zzzz-nope').catch(e => e);
245
245
  expect(err).toBeInstanceOf(AstryxError);
246
246
  expect(err.code).toBe('ERR_UNKNOWN_SECTION');
247
- // It names the namespace's children, in the order its slots list them.
248
- const cli = (await docs('cli')).data;
249
- expect(err.suggestions.map(s => s.name)).toEqual(
250
- cli.slots.flatMap(slot => slot.children.map(child => child.route)),
251
- );
252
- expect(err.suggestions.map(s => s.name)).toContain('cli/commands');
247
+ // It names every guide below the namespace, at any depth.
248
+ const names = err.suggestions.map(s => s.name);
249
+ expect(names).toContain('cli/component-lookups');
250
+ expect(names).toContain('cli/integrations/quick-start');
251
+ expect(names.every(name => name.startsWith('cli/'))).toBe(true);
253
252
  }, SLOW);
254
253
 
255
254
  it('an unknown route suggests the children of the deepest namespace it reaches', async () => {
@@ -0,0 +1,260 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file A section read on a namespace (spec:AST-046 FR6): `astryx docs
5
+ * <namespace> <section>` answers from the one guide below the namespace that
6
+ * has the section, exactly as that guide's own section read does, so a section
7
+ * read that worked before a topic became a namespace still works.
8
+ */
9
+
10
+ import * as fs from 'node:fs';
11
+ import * as path from 'node:path';
12
+ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
13
+ import {docs} from './docs.mjs';
14
+ import {oneGuide} from './detail/section/section.mjs';
15
+
16
+ const SLOW = 60_000;
17
+
18
+ /** @type {string} */
19
+ let tmpDir;
20
+
21
+ /** @param {Record<string, object>} files the integration's doc files */
22
+ function scaffold(files) {
23
+ fs.writeFileSync(
24
+ path.join(tmpDir, 'package.json'),
25
+ JSON.stringify({name: 'consumer'}),
26
+ );
27
+ fs.writeFileSync(
28
+ path.join(tmpDir, 'astryx.config.mjs'),
29
+ "export default {integrations: ['@acme/kit']};\n",
30
+ );
31
+ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'kit');
32
+ fs.mkdirSync(path.join(pkgDir, 'docs'), {recursive: true});
33
+ fs.writeFileSync(
34
+ path.join(pkgDir, 'package.json'),
35
+ JSON.stringify({name: '@acme/kit', version: '1.0.0'}),
36
+ );
37
+ fs.writeFileSync(
38
+ path.join(pkgDir, 'astryx.integration.mjs'),
39
+ "export default {docs: './docs'};\n",
40
+ );
41
+ for (const [file, doc] of Object.entries(files)) {
42
+ fs.writeFileSync(
43
+ path.join(pkgDir, 'docs', file),
44
+ `export const docs = ${JSON.stringify(doc, null, 2)};\n`,
45
+ );
46
+ }
47
+ }
48
+
49
+ /**
50
+ * @param {string} name
51
+ * @param {number} order
52
+ * @param {Array<{title: string, id?: string}>} sections
53
+ */
54
+ function guide(name, order, sections) {
55
+ return {
56
+ type: 'generic',
57
+ name,
58
+ title: `Acme ${name}`,
59
+ description: `The ${name} guide.`,
60
+ placement: {parent: 'namespace:acme', slot: 'guides', order},
61
+ sections: sections.map(section => ({
62
+ ...section,
63
+ content: [{type: 'prose', text: `${section.title} text.`}],
64
+ })),
65
+ };
66
+ }
67
+
68
+ /** A namespace of two guides that both have a section titled "...setup". */
69
+ function kit() {
70
+ return {
71
+ 'acme.doc.mjs': {
72
+ type: 'namespace',
73
+ name: 'acme',
74
+ title: 'Acme',
75
+ summary: 'Everything about the Acme kit.',
76
+ slots: {guides: {title: 'Guides', accepts: {kinds: ['generic']}}},
77
+ },
78
+ 'install.doc.mjs': guide('install', 1, [
79
+ {title: 'Package setup', id: 'package-setup'},
80
+ {title: 'Verify'},
81
+ ]),
82
+ 'theme.doc.mjs': guide('theme', 2, [
83
+ {title: 'Theme setup'},
84
+ {title: 'Dark mode'},
85
+ ]),
86
+ };
87
+ }
88
+
89
+ beforeEach(() => {
90
+ tmpDir = fs.mkdtempSync(
91
+ path.join(process.cwd(), '.astryx-namespace-section-test-'),
92
+ );
93
+ });
94
+
95
+ afterEach(() => {
96
+ fs.rmSync(tmpDir, {recursive: true, force: true});
97
+ });
98
+
99
+ describe('a section read on a namespace', () => {
100
+ it(
101
+ 'returns the one guide section, by key and by title, as the guide read does',
102
+ async () => {
103
+ for (const query of ['side-panels', 'Side panels', 'side panels']) {
104
+ const read = await docs('layout', query);
105
+ expect(read).toEqual(await docs('layout/side-panels', 'side-panels'));
106
+ expect(read).toMatchObject({
107
+ type: 'docs.detail.section',
108
+ package: '@astryxdesign/cli',
109
+ data: {id: 'side-panels', title: 'Side panels'},
110
+ });
111
+ }
112
+ // A section in a guide of its own, and a section past a guide's first.
113
+ expect((await docs('layout', 'shell')).data.id).toBe('shell');
114
+ expect((await docs('layout', 'responsive-contract')).data.id).toBe(
115
+ 'responsive-contract',
116
+ );
117
+ },
118
+ SLOW,
119
+ );
120
+
121
+ it(
122
+ 'reads dense and Chinese the way the guide read does',
123
+ async () => {
124
+ for (const options of [{dense: true}, {zh: true}, {lang: 'dense'}]) {
125
+ expect(await docs('layout', 'side-panels', options)).toEqual(
126
+ await docs('layout/side-panels', 'side-panels', options),
127
+ );
128
+ }
129
+ },
130
+ SLOW,
131
+ );
132
+
133
+ it(
134
+ "prefers the guide whose section key is the query over another guide's title match",
135
+ async () => {
136
+ scaffold(kit());
137
+ const read = await docs('acme', 'package-setup', {cwd: tmpDir});
138
+ expect(read.data).toMatchObject({
139
+ id: 'package-setup',
140
+ title: 'Package setup',
141
+ });
142
+ expect(read.data.links.up).toBe('astryx docs acme/install --index');
143
+ expect((await docs('acme', 'dark mode', {cwd: tmpDir})).data.title).toBe(
144
+ 'Dark mode',
145
+ );
146
+ },
147
+ SLOW,
148
+ );
149
+
150
+ it(
151
+ 'fails on a miss, naming every guide below the namespace',
152
+ async () => {
153
+ const err = await docs('layout', 'zzzz-nope').catch(e => e);
154
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
155
+ const names = err.suggestions.map(s => s.name);
156
+ expect(names).toContain('layout/scaffold');
157
+ expect(names).toContain('layout/side-panels');
158
+ expect(names.every(name => name.startsWith('layout/'))).toBe(true);
159
+ // At any depth: guides under nested namespaces are named, namespaces are not.
160
+ const cli = await docs('cli', 'zzzz-nope').catch(e => e);
161
+ expect(cli.code).toBe('ERR_UNKNOWN_SECTION');
162
+ expect(cli.suggestions.map(s => s.name)).toContain(
163
+ 'cli/integrations/quick-start',
164
+ );
165
+ expect(cli.suggestions.map(s => s.name)).not.toContain(
166
+ 'cli/integrations',
167
+ );
168
+ },
169
+ SLOW,
170
+ );
171
+
172
+ it(
173
+ 'still fails a section on a typed doc, naming the doc',
174
+ async () => {
175
+ const err = await docs('cli/commands/docs', 'anything').catch(e => e);
176
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
177
+ expect(err.suggestions.map(s => s.name)).toEqual(['cli/commands/docs']);
178
+ },
179
+ SLOW,
180
+ );
181
+ });
182
+
183
+ describe('a namespace read answers what the guide read answers', () => {
184
+ /** A guide with a title match before a key match, and a second guide. */
185
+ function competing() {
186
+ return {
187
+ ...kit(),
188
+ 'install.doc.mjs': guide('install', 1, [
189
+ {title: 'Shell contract'},
190
+ {title: 'Shell'},
191
+ ]),
192
+ 'theme.doc.mjs': guide('theme', 2, [{title: 'Setup', id: 'setup'}]),
193
+ 'extra.doc.mjs': guide('extra', 3, [{title: 'Theme setup'}]),
194
+ };
195
+ }
196
+
197
+ it(
198
+ 'returns the section the guide read returns, even when a later section has the key',
199
+ async () => {
200
+ scaffold(competing());
201
+ const own = await docs('acme/install', 'shell', {cwd: tmpDir});
202
+ const read = await docs('acme', 'shell', {cwd: tmpDir});
203
+ expect(read).toEqual(own);
204
+ expect(read.data.title).toBe('Shell contract');
205
+ },
206
+ SLOW,
207
+ );
208
+
209
+ it(
210
+ "prefers the guide whose own match is the query's key over another guide's title match",
211
+ async () => {
212
+ scaffold(competing());
213
+ const read = await docs('acme', 'setup', {cwd: tmpDir});
214
+ expect(read).toEqual(await docs('acme/theme', 'setup', {cwd: tmpDir}));
215
+ expect(read.data).toMatchObject({id: 'setup', title: 'Setup'});
216
+ },
217
+ SLOW,
218
+ );
219
+
220
+ it(
221
+ 'names the children of a namespace with no guide below it',
222
+ async () => {
223
+ const err = await docs('cli/api', 'anything').catch(e => e);
224
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
225
+ const api = (await docs('cli/api')).data;
226
+ expect(err.suggestions.map(s => s.name)).toEqual(
227
+ api.slots.flatMap(slot => slot.children.map(child => child.route)),
228
+ );
229
+ expect(err.suggestions.length).toBeGreaterThan(0);
230
+ expect(err.message).toContain('Open one of its children');
231
+ },
232
+ SLOW,
233
+ );
234
+ });
235
+
236
+ describe('a section query that matches sections in several guides', () => {
237
+ // It used to guess; now it asks. A flat topic's section read returns its
238
+ // first title match; across guides, the read names each guide instead.
239
+ it(
240
+ 'asks which guide, naming each guide that matches',
241
+ async () => {
242
+ scaffold(kit());
243
+ const err = await docs('acme', 'setup', {cwd: tmpDir}).catch(e => e);
244
+ expect(err.code).toBe('ERR_UNKNOWN_SECTION');
245
+ expect(err.suggestions).toEqual([
246
+ {name: 'acme/install', reason: 'has "Package setup"'},
247
+ {name: 'acme/theme', reason: 'has "Theme setup"'},
248
+ ]);
249
+ },
250
+ SLOW,
251
+ );
252
+
253
+ it('decides in one place: oneGuide answers only a single match', () => {
254
+ const a = /** @type {any} */ ({guide: {route: 'acme/install'}});
255
+ const b = /** @type {any} */ ({guide: {route: 'acme/theme'}});
256
+ expect(oneGuide([a])).toBe(a);
257
+ expect(oneGuide([a, b])).toBeNull();
258
+ expect(oneGuide([])).toBeNull();
259
+ });
260
+ });
@@ -35,8 +35,9 @@ export function tokenizeQuery(term: string): string[];
35
35
  * {@link STRONG_TOKEN_SCORE} or above, or when it matches every word.
36
36
  *
37
37
  * A doc has priority when the reader asked for that doc:
38
- * - 2: the whole query spells the topic's name or its last route segment
39
- * (`font setup` is typography/font-setup, `motion` is the motion guide);
38
+ * - 2: the whole query is the topic's name, its last route segment, or its
39
+ * own title, as words and whatever the plural (`font setup` is
40
+ * typography/font-setup, `side panel` is "Side panels");
40
41
  * - 1: a word of the query is the topic's name (`illustration` in a longer
41
42
  * question is the illustrations guide);
42
43
  * - 1: the query holds one of the doc's titles whole (`resizable side panels`
@@ -96,6 +96,35 @@ describe('search domain priority — the rule', () => {
96
96
  ).toBe(1);
97
97
  });
98
98
 
99
+ it('names a doc by its route or title whatever the plural', () => {
100
+ const guide = {
101
+ domain: 'doc',
102
+ name: 'layout/side-panels',
103
+ titles: ['Side panels'],
104
+ };
105
+ expect(priority('side panel', guide)).toBe(2);
106
+ expect(priority('side panels', guide)).toBe(2);
107
+ expect(priority('side panels', {...guide, name: 'layout/side-panel'})).toBe(
108
+ 2,
109
+ );
110
+ // The topic's own title names it even where the route words differ.
111
+ const titled = {
112
+ domain: 'doc',
113
+ name: 'guides/lookups',
114
+ titles: ['Looking up components'],
115
+ };
116
+ expect(priority('looking up component', titled)).toBe(2);
117
+ // A section's title is a heading inside its topic, not the topic's name.
118
+ const section = {
119
+ domain: 'doc',
120
+ name: 'font-sizes',
121
+ _topic: 'typography',
122
+ _section: 'font-sizes',
123
+ titles: ['Font Sizes'],
124
+ };
125
+ expect(priority('font size', section)).toBe(0);
126
+ });
127
+
99
128
  it('names a section by its topic', () => {
100
129
  // A section candidate's own name is its section key; the reader names the
101
130
  // topic it belongs to.
@@ -210,30 +239,15 @@ describe('search domain priority — real docs and components', () => {
210
239
  );
211
240
 
212
241
  it(
213
- 'still finds a split topic first by its own name, in every namespace',
242
+ 'still finds each layout guide first by its own name',
214
243
  async () => {
215
- const guides = [];
216
- for (const ns of ['layout', 'typography', 'tokens', 'styling', 'cli']) {
217
- guides.push(...(await placedGuides(ns)));
218
- }
219
- // The layout split is in the tree; the walk covers whatever else is.
244
+ // Each search reads the whole index, so this checks one split namespace
245
+ // (layout, six guides) rather than every guide in the tree.
246
+ const guides = await placedGuides('layout');
220
247
  expect(guides).toContain('layout/layout-spacing');
221
- // Each search reads the whole index, so check one guide per namespace
222
- // (its first, in route order): every split is covered without a search
223
- // per guide.
224
- /** @type {Map<string, string>} */
225
- const firstPerNamespace = new Map();
226
- for (const route of [...new Set(guides)].sort()) {
227
- const ns = route.slice(0, route.lastIndexOf('/'));
228
- if (!firstPerNamespace.has(ns)) firstPerNamespace.set(ns, route);
229
- }
230
- const sample = new Set([
231
- 'layout/layout-spacing',
232
- ...firstPerNamespace.values(),
233
- ]);
234
248
  /** @type {string[]} */
235
249
  const misses = [];
236
- for (const route of sample) {
250
+ for (const route of guides) {
237
251
  const q = route.slice(route.lastIndexOf('/') + 1).replace(/-/g, ' ');
238
252
  const top = (await search(q, {cwd})).data.results[0];
239
253
  if (top?.domain !== 'doc' || top.name !== route) {
@@ -242,6 +256,6 @@ describe('search domain priority — real docs and components', () => {
242
256
  }
243
257
  expect(misses).toEqual([]);
244
258
  },
245
- SLOW * 2,
259
+ SLOW,
246
260
  );
247
261
  });
@@ -494,8 +494,9 @@ const STRONG_TOKEN_SCORE = 70;
494
494
  * {@link STRONG_TOKEN_SCORE} or above, or when it matches every word.
495
495
  *
496
496
  * A doc has priority when the reader asked for that doc:
497
- * - 2: the whole query spells the topic's name or its last route segment
498
- * (`font setup` is typography/font-setup, `motion` is the motion guide);
497
+ * - 2: the whole query is the topic's name, its last route segment, or its
498
+ * own title, as words and whatever the plural (`font setup` is
499
+ * typography/font-setup, `side panel` is "Side panels");
499
500
  * - 1: a word of the query is the topic's name (`illustration` in a longer
500
501
  * question is the illustrations guide);
501
502
  * - 1: the query holds one of the doc's titles whole (`resizable side panels`
@@ -525,13 +526,15 @@ export function domainPriority(term, tokens, candidate, hit) {
525
526
  const words = [term, ...tokens];
526
527
  if (candidate.domain === 'doc') {
527
528
  const topic = String(candidate._topic ?? candidate.name).toLowerCase();
528
- const asWords = (/** @type {string} */ n) =>
529
- n.replace(/[-_\s]+/g, ' ').trim();
530
- const spelled = asWords(term);
531
- if (
532
- asWords(topic) === spelled ||
533
- asWords(topic.slice(topic.lastIndexOf('/') + 1)) === spelled
534
- ) {
529
+ // The whole query, read as words, is the topic's route, its last
530
+ // segment, or its own title, whatever the plural: `side panel` is
531
+ // layout/side-panels, and `header and footer` is "Headers and footers".
532
+ // A section's title is a heading inside a topic, not the topic's name.
533
+ const named = [topic, topic.slice(topic.lastIndexOf('/') + 1)];
534
+ if (candidate._section == null && candidate.titles?.[0]) {
535
+ named.push(candidate.titles[0]);
536
+ }
537
+ if (named.some(n => samePhrase(term, n))) {
535
538
  return 2;
536
539
  }
537
540
  if (
@@ -602,6 +605,24 @@ function samePhraseWord(a, b) {
602
605
  );
603
606
  }
604
607
 
608
+ /**
609
+ * Whether two phrases are the same words, in order, ignoring case,
610
+ * punctuation, and a plural on any word: `side panel` is "Side panels", and
611
+ * `headers and footers` is `header-and-footer`.
612
+ * @param {string} a
613
+ * @param {string} b
614
+ * @returns {boolean}
615
+ */
616
+ function samePhrase(a, b) {
617
+ const x = phraseWords(a);
618
+ const y = phraseWords(b);
619
+ return (
620
+ x.length > 0 &&
621
+ x.length === y.length &&
622
+ x.every((w, k) => samePhraseWord(w, y[k]) || sameWord(w, y[k]))
623
+ );
624
+ }
625
+
605
626
  /**
606
627
  * Whether `plural` is the plural of `word`: `integrations` of `integration`,
607
628
  * `boxes` of `box`. `es` only follows s, x, z, ch, or sh, so `notes` is not a
@@ -22,7 +22,8 @@ export const doc = {
22
22
  'does, and `--index` its section index. A route ' +
23
23
  'opens a node of the docs tree: `cli` lists its guides and reference, ' +
24
24
  '`cli/api/functions` lists every API function, and `cli/api/functions/search` prints ' +
25
- 'one. `--depth` reads as far down the tree as you ask, from the doc alone (0) to ' +
25
+ 'one. A namespace plus a section prints that section from the one guide below it ' +
26
+ 'that has it (`astryx docs layout side-panels`). `--depth` reads as far down the tree as you ask, from the doc alone (0) to ' +
26
27
  'everything below it (all), and with it `--detail` sets how much of each doc below ' +
27
28
  'shows: one line (brief, the default), its sections (compact), or all of it (full).',
28
29
  fn: 'docs',
@@ -330,22 +330,25 @@ describe('the docs tree, one level at a time', () => {
330
330
  expect(old.stderr).toContain('Unknown topic "cli-integrations"');
331
331
  }, SLOW);
332
332
 
333
- it('returns docs.node as JSON, and fails a section of a namespace', async () => {
333
+ it('returns docs.node as JSON, and reads a section of a namespace from its guide', async () => {
334
334
  const node = JSON.parse((await runCli(['docs', 'cli', '--json'])).stdout);
335
335
  expect(node).toMatchObject({
336
336
  type: 'docs.node',
337
337
  data: {route: 'cli', kind: 'namespace', breadcrumb: []},
338
338
  });
339
339
  expect(node.data.slots.map(slot => slot.name)).toEqual(['guides', 'reference']);
340
- const section = await runCli(['docs', 'cli', 'commands', '--json']);
341
- expect(section.status).toBe(1);
342
- const error = JSON.parse(section.stdout);
343
- expect(error).toMatchObject({code: 'ERR_UNKNOWN_SECTION'});
344
- // It names the namespace's children, in the order its slots list them.
345
- expect(error.suggestions.map(s => s.name)).toEqual(
346
- node.data.slots.flatMap(slot => slot.children.map(child => child.route)),
340
+ const section = JSON.parse(
341
+ (await runCli(['docs', 'layout', 'side-panels', '--json'])).stdout,
347
342
  );
348
- expect(error.suggestions.map(s => s.name)).toContain('cli/commands');
343
+ expect(section).toMatchObject({
344
+ type: 'docs.detail.section',
345
+ data: {id: 'side-panels', title: 'Side panels'},
346
+ });
347
+ const missing = await runCli(['docs', 'cli', 'zzzz-nope', '--json']);
348
+ expect(missing.status).toBe(1);
349
+ const error = JSON.parse(missing.stdout);
350
+ expect(error).toMatchObject({code: 'ERR_UNKNOWN_SECTION'});
351
+ expect(error.suggestions.map(s => s.name)).toContain('cli/integrations/quick-start');
349
352
  }, SLOW);
350
353
  });
351
354
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/cli",
3
- "version": "0.6.6-canary.4470b92",
3
+ "version": "0.6.6-canary.4ec0d0e",
4
4
  "displayName": "CLI",
5
5
  "description": "Scaffold projects, browse templates, generate themes, and get agent-ready docs from the command line.",
6
6
  "author": "Meta Open Source",
@@ -101,10 +101,10 @@
101
101
  "zod": "^4.4.3"
102
102
  },
103
103
  "peerDependencies": {
104
- "@astryxdesign/charts": "0.6.6-canary.4470b92",
105
- "@astryxdesign/core": "0.6.6-canary.4470b92",
106
- "@astryxdesign/lab": "0.6.6-canary.4470b92",
107
- "@astryxdesign/theme-neutral": "0.6.6-canary.4470b92"
104
+ "@astryxdesign/charts": "0.6.6-canary.4ec0d0e",
105
+ "@astryxdesign/core": "0.6.6-canary.4ec0d0e",
106
+ "@astryxdesign/lab": "0.6.6-canary.4ec0d0e",
107
+ "@astryxdesign/theme-neutral": "0.6.6-canary.4ec0d0e"
108
108
  },
109
109
  "peerDependenciesMeta": {
110
110
  "@astryxdesign/charts": {
@@ -121,10 +121,10 @@
121
121
  }
122
122
  },
123
123
  "devDependencies": {
124
- "@astryxdesign/charts": "0.6.6-canary.4470b92",
125
- "@astryxdesign/core": "0.6.6-canary.4470b92",
126
- "@astryxdesign/lab": "0.6.6-canary.4470b92",
127
- "@astryxdesign/theme-neutral": "0.6.6-canary.4470b92",
124
+ "@astryxdesign/charts": "0.6.6-canary.4ec0d0e",
125
+ "@astryxdesign/core": "0.6.6-canary.4ec0d0e",
126
+ "@astryxdesign/lab": "0.6.6-canary.4ec0d0e",
127
+ "@astryxdesign/theme-neutral": "0.6.6-canary.4ec0d0e",
128
128
  "@heroicons/react": "^2.2.0",
129
129
  "@stylexjs/stylex": "^0.19.0",
130
130
  "@types/babel__core": "^7.20.5",