@astryxdesign/cli 0.6.6-canary.f9a0f47 → 0.6.6-canary.fb78fa1

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.
Files changed (35) hide show
  1. package/api/search/search.d.mts +43 -0
  2. package/api/search/search.domain-priority.test.mjs +247 -0
  3. package/api/search/search.mjs +170 -29
  4. package/api/theme/build/build.d.mts +70 -0
  5. package/api/theme/build/build.mjs +205 -43
  6. package/api/theme/build/font-warning.d.mts +11 -0
  7. package/api/theme/build/font-warning.mjs +28 -3
  8. package/assets/docs/author-a-theme.doc.mjs +12 -7
  9. package/assets/docs/theme.doc.zh.mjs +1 -1
  10. package/assets/docs/tree/layout.doc.mjs +20 -0
  11. package/assets/docs/use-a-theme.doc.mjs +6 -3
  12. package/assets/templates/pages/incident-console/page.tsx +1 -1
  13. package/clients/cli/commands/blog.mjs +3 -3
  14. package/clients/cli/commands/build-theme.adaptations.test.mjs +1 -1
  15. package/clients/cli/commands/build-theme.ascii-output.test.mjs +11 -1
  16. package/clients/cli/commands/build-theme.batch-report.test.mjs +335 -0
  17. package/clients/cli/commands/build-theme.font-warning.test.mjs +36 -7
  18. package/clients/cli/commands/build-theme.import-path.test.mjs +3 -3
  19. package/clients/cli/commands/build-theme.mjs +64 -16
  20. package/clients/cli/commands/build-theme.watch.test.mjs +33 -0
  21. package/clients/cli/commands/docs.test.mjs +2 -1
  22. package/clients/cli/commands/doctor.test.mjs +17 -1
  23. package/clients/cli/commands/import-hint-correctness.test.mjs +23 -0
  24. package/clients/cli/commands/search.test.mjs +6 -2
  25. package/clients/cli/commands/swizzle.routing.test.mjs +2 -1
  26. package/clients/cli/commands/template.mjs +2 -2
  27. package/clients/cli/commands/theme-add-lifecycle.test.mjs +9 -6
  28. package/clients/cli/commands/theme-build.doc.mjs +3 -1
  29. package/clients/cli/commands/upgrade.config-ordering.test.mjs +2 -1
  30. package/clients/cli/index.mjs +1 -1
  31. package/clients/cli/lib/component-format.test.mjs +1 -1
  32. package/foundation/env/package-manager.d.mts +28 -8
  33. package/foundation/env/package-manager.mjs +49 -10
  34. package/foundation/env/package-manager.test.mjs +93 -1
  35. package/package.json +9 -9
@@ -24,6 +24,49 @@ export function sameWord(a: string, b: string): boolean;
24
24
  * @returns {string[]}
25
25
  */
26
26
  export function tokenizeQuery(term: string): string[];
27
+ /**
28
+ * A match's domain priority: 0 (none), 1, or 2 (a doc the whole query names).
29
+ * A component, hook, template, or theme with priority ranks ahead of any doc
30
+ * without it, whatever the two scores are. Docs among themselves rank by
31
+ * priority, then score; everything else ranks among itself by score.
32
+ *
33
+ * A component, hook, template, or theme has priority (1) when one of the
34
+ * query's words, or the whole query, hits its name or an authored keyword at
35
+ * {@link STRONG_TOKEN_SCORE} or above, or when it matches every word.
36
+ *
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);
40
+ * - 1: a word of the query is the topic's name (`illustration` in a longer
41
+ * question is the illustrations guide);
42
+ * - 1: the query holds one of the doc's titles whole (`resizable side panels`
43
+ * names "Side panels"; `light dark mode button` names "Light/Dark Mode");
44
+ * - 1: the doc matches every word of the query and one of them is a word of
45
+ * its title (`switch to a dark theme` and "Use a theme").
46
+ * A section answers to its topic's name.
47
+ *
48
+ * A doc that matched only by keyword, by a heading holding the query, or by
49
+ * words spread through its text has no priority. Docs are split into many
50
+ * small topics, and each declares its own keywords and headings, so a common
51
+ * phrase such as `font size` hits a guide's keyword or heading exactly
52
+ * (170-190) while the component the reader is after matches one word by
53
+ * keyword (`Text`, 98). Ranked on text alone, every split adds another doc
54
+ * above the component. Broad reference pages match every word of many queries
55
+ * in their text the same way. The score stays the text-match strength the
56
+ * result reports, so callers that gate on it (`build`) see the same numbers.
57
+ *
58
+ * @param {string} term - Lowercased search term.
59
+ * @param {string[]} tokens - Content tokens from tokenizeQuery(term).
60
+ * @param {Candidate} candidate
61
+ * @param {{score: number, matched: number, total: number}} hit - The
62
+ * candidate's scoreQuery result.
63
+ * @returns {0 | 1 | 2}
64
+ */
65
+ export function domainPriority(term: string, tokens: string[], candidate: Candidate, hit: {
66
+ score: number;
67
+ matched: number;
68
+ total: number;
69
+ }): 0 | 1 | 2;
27
70
  /**
28
71
  * The first title or heading that holds every word of the query, in order and
29
72
  * side by side, or null.
@@ -0,0 +1,247 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Domain priority in `search` ranking (api/search/search.mjs), run
5
+ * against the real docs tree and @astryxdesign/core registry.
6
+ *
7
+ * Splitting a large doc into smaller topics gives each topic its own keywords
8
+ * and headings, and a doc keyword or heading that holds the whole query scores
9
+ * 170-190, above a component that matches one word by keyword (98). Every
10
+ * split then puts another doc above the component a reader asked for. Domain
11
+ * priority ranks a component, hook, template, or theme that a query word hits
12
+ * by name or keyword ahead of docs the reader did not ask for, and keeps a doc
13
+ * the query names, or whose title the query holds, where it was.
14
+ *
15
+ * Both directions are asserted together, so neither can be traded for the
16
+ * other: component queries find the component first, and the obvious question
17
+ * for each guide still finds that guide first.
18
+ */
19
+
20
+ import {describe, it, expect} from 'vitest';
21
+ import * as path from 'node:path';
22
+ import {fileURLToPath} from 'node:url';
23
+ import {docs} from '../docs/docs.mjs';
24
+ import {domainPriority, search, scoreQuery, tokenizeQuery} from './search.mjs';
25
+
26
+ const REPO = path.resolve(
27
+ path.dirname(fileURLToPath(import.meta.url)),
28
+ '../../../..',
29
+ );
30
+ const cwd = REPO;
31
+ const SLOW = 30_000;
32
+
33
+ /**
34
+ * @param {string} q
35
+ * @param {object} candidate
36
+ * @returns {0 | 1 | 2}
37
+ */
38
+ const priority = (q, candidate) => {
39
+ const tokens = tokenizeQuery(q);
40
+ const hit = scoreQuery(q, tokens, candidate) ?? {
41
+ score: 0,
42
+ matched: 0,
43
+ total: 1,
44
+ };
45
+ return domainPriority(q, tokens, /** @type {any} */ (candidate), hit);
46
+ };
47
+
48
+ /**
49
+ * Every placed guide under a namespace, walked through `docs`.
50
+ * @param {string} route
51
+ * @param {Set<string>} [seen]
52
+ * @returns {Promise<string[]>}
53
+ */
54
+ async function placedGuides(route, seen = new Set()) {
55
+ /** @type {any} */
56
+ let node;
57
+ try {
58
+ node = (await docs(route)).data;
59
+ } catch {
60
+ return [];
61
+ }
62
+ /** @type {string[]} */
63
+ const out = [];
64
+ for (const child of (node.slots ?? []).flatMap(
65
+ (/** @type {any} */ slot) => slot.children,
66
+ )) {
67
+ if (!child.route || seen.has(child.route)) continue;
68
+ seen.add(child.route);
69
+ if (child.kind === 'generic' && child.route.includes('/')) {
70
+ out.push(child.route);
71
+ }
72
+ out.push(...(await placedGuides(child.route, seen)));
73
+ }
74
+ return out;
75
+ }
76
+
77
+ describe('search domain priority — the rule', () => {
78
+ it('gives a doc no priority for a keyword or heading match', () => {
79
+ const topic = {
80
+ domain: 'doc',
81
+ name: 'typography/font-setup',
82
+ keywords: ['font size'],
83
+ titles: ['Font Setup', 'Font Sizes'],
84
+ };
85
+ expect(priority('font size', topic)).toBe(0);
86
+ });
87
+
88
+ it('gives a doc priority when the query names it', () => {
89
+ const topic = {domain: 'doc', name: 'typography/font-setup'};
90
+ // The whole query spells its last route segment.
91
+ expect(priority('font setup', topic)).toBe(2);
92
+ expect(priority('typography/font-setup', topic)).toBe(2);
93
+ // A word of a longer query is a flat topic's name, or its plural.
94
+ expect(
95
+ priority('product illustration', {domain: 'doc', name: 'illustrations'}),
96
+ ).toBe(1);
97
+ });
98
+
99
+ it('names a section by its topic', () => {
100
+ // A section candidate's own name is its section key; the reader names the
101
+ // topic it belongs to.
102
+ const section = {
103
+ domain: 'doc',
104
+ name: 'drop-shadows',
105
+ _topic: 'elevation',
106
+ titles: ['Drop shadows'],
107
+ keywords: ['Drop shadows'],
108
+ };
109
+ expect(priority('elevation', section)).toBe(2);
110
+ expect(priority('elevation for a raised tile', section)).toBe(1);
111
+ });
112
+
113
+ it('gives a doc priority when the query holds one of its titles whole', () => {
114
+ const guide = {
115
+ domain: 'doc',
116
+ name: 'layout/side-panels',
117
+ titles: ['Side panels'],
118
+ };
119
+ expect(priority('resizable side panels with a toolbar', guide)).toBe(1);
120
+ });
121
+
122
+ it('gives a doc that matches every word priority only when its title names one', () => {
123
+ const titled = {
124
+ domain: 'doc',
125
+ name: 'use-a-theme',
126
+ titles: ['Use a theme'],
127
+ keywords: ['switcher', 'night'],
128
+ description: 'Apply a theme to your app.',
129
+ };
130
+ expect(priority('night theme switcher', titled)).toBe(1);
131
+ // A reference page that holds every word, but whose title names none.
132
+ const reference = {
133
+ domain: 'doc',
134
+ name: 'api/reference',
135
+ titles: ['Response shapes'],
136
+ keywords: ['switcher', 'night', 'theme'],
137
+ };
138
+ expect(priority('night theme switcher', reference)).toBe(0);
139
+ });
140
+
141
+ it('gives a component priority for a name or keyword hit, not for prose', () => {
142
+ expect(
143
+ priority('font size', {
144
+ domain: 'component',
145
+ name: 'Text',
146
+ keywords: ['font'],
147
+ }),
148
+ ).toBe(1);
149
+ expect(
150
+ priority('date picker', {domain: 'component', name: 'DatePicker'}),
151
+ ).toBe(1);
152
+ expect(
153
+ priority('font size', {
154
+ domain: 'component',
155
+ name: 'Card',
156
+ description: 'A surface whose font size follows its parent.',
157
+ }),
158
+ ).toBe(0);
159
+ });
160
+ });
161
+
162
+ describe('search domain priority — real docs and components', () => {
163
+ it(
164
+ 'finds the Text component before the typography guides for `font size`',
165
+ async () => {
166
+ for (const q of ['font size', 'font weight']) {
167
+ const results = (await search(q, {cwd})).data.results;
168
+ expect(results[0], q).toMatchObject({
169
+ domain: 'component',
170
+ name: 'Text',
171
+ });
172
+ const guide = results.findIndex(
173
+ r => r.domain === 'doc' && /^typography(?:\/|$)/.test(r.name),
174
+ );
175
+ // The guide still matches, below the component.
176
+ expect(guide, q).toBeGreaterThan(0);
177
+ }
178
+ },
179
+ SLOW,
180
+ );
181
+
182
+ it(
183
+ 'reports the text-match score unchanged',
184
+ async () => {
185
+ const results = (await search('font size', {cwd})).data.results;
186
+ const guide = results.find(
187
+ r => r.domain === 'doc' && /^typography(?:\/|$)/.test(r.name),
188
+ );
189
+ expect(guide?.score).toBeGreaterThan(results[0].score);
190
+ },
191
+ SLOW,
192
+ );
193
+
194
+ it(
195
+ 'still finds a flat guide first by its name',
196
+ async () => {
197
+ for (const [q, name] of [
198
+ ['motion', 'motion'],
199
+ ['icons', 'icons'],
200
+ ['tokens', 'tokens'],
201
+ ['illustration', 'illustrations'],
202
+ ['use a theme', 'use-a-theme'],
203
+ ['author a theme', 'author-a-theme'],
204
+ ]) {
205
+ const results = (await search(q, {cwd})).data.results;
206
+ expect(results[0], q).toMatchObject({domain: 'doc', name});
207
+ }
208
+ },
209
+ SLOW,
210
+ );
211
+
212
+ it(
213
+ 'still finds a split topic first by its own name, in every namespace',
214
+ 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.
220
+ 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
+ /** @type {string[]} */
235
+ const misses = [];
236
+ for (const route of sample) {
237
+ const q = route.slice(route.lastIndexOf('/') + 1).replace(/-/g, ' ');
238
+ const top = (await search(q, {cwd})).data.results[0];
239
+ if (top?.domain !== 'doc' || top.name !== route) {
240
+ misses.push(`${q} -> ${top?.domain}:${top?.name}`);
241
+ }
242
+ }
243
+ expect(misses).toEqual([]);
244
+ },
245
+ SLOW * 2,
246
+ );
247
+ });
@@ -54,6 +54,13 @@
54
54
  * description hold both words of `troubleshoot integration` answers it better
55
55
  * than a doc named `integration`.
56
56
  *
57
+ * Between domains, ranking adds one rule ahead of the score: domain priority
58
+ * (see {@link domainPriority}). A component, hook, template, or theme whose
59
+ * name or keyword a query word hits ranks ahead of every doc the reader did not
60
+ * ask for by name or title, so `font size` finds `Text` before a typography
61
+ * topic that declares the phrase. A doc the query names, or whose title the
62
+ * query holds, keeps its place.
63
+ *
57
64
  * Description and guidance are separate tiers on purpose. A component's own
58
65
  * one-line description saying "notification" is a claim about what it IS; the
59
66
  * same word inside another component's best-practice advice is a passing
@@ -476,13 +483,107 @@ const FULL_COVERAGE_SCORE = 151;
476
483
  */
477
484
  const STRONG_TOKEN_SCORE = 70;
478
485
 
486
+ /**
487
+ * A match's domain priority: 0 (none), 1, or 2 (a doc the whole query names).
488
+ * A component, hook, template, or theme with priority ranks ahead of any doc
489
+ * without it, whatever the two scores are. Docs among themselves rank by
490
+ * priority, then score; everything else ranks among itself by score.
491
+ *
492
+ * A component, hook, template, or theme has priority (1) when one of the
493
+ * query's words, or the whole query, hits its name or an authored keyword at
494
+ * {@link STRONG_TOKEN_SCORE} or above, or when it matches every word.
495
+ *
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);
499
+ * - 1: a word of the query is the topic's name (`illustration` in a longer
500
+ * question is the illustrations guide);
501
+ * - 1: the query holds one of the doc's titles whole (`resizable side panels`
502
+ * names "Side panels"; `light dark mode button` names "Light/Dark Mode");
503
+ * - 1: the doc matches every word of the query and one of them is a word of
504
+ * its title (`switch to a dark theme` and "Use a theme").
505
+ * A section answers to its topic's name.
506
+ *
507
+ * A doc that matched only by keyword, by a heading holding the query, or by
508
+ * words spread through its text has no priority. Docs are split into many
509
+ * small topics, and each declares its own keywords and headings, so a common
510
+ * phrase such as `font size` hits a guide's keyword or heading exactly
511
+ * (170-190) while the component the reader is after matches one word by
512
+ * keyword (`Text`, 98). Ranked on text alone, every split adds another doc
513
+ * above the component. Broad reference pages match every word of many queries
514
+ * in their text the same way. The score stays the text-match strength the
515
+ * result reports, so callers that gate on it (`build`) see the same numbers.
516
+ *
517
+ * @param {string} term - Lowercased search term.
518
+ * @param {string[]} tokens - Content tokens from tokenizeQuery(term).
519
+ * @param {Candidate} candidate
520
+ * @param {{score: number, matched: number, total: number}} hit - The
521
+ * candidate's scoreQuery result.
522
+ * @returns {0 | 1 | 2}
523
+ */
524
+ export function domainPriority(term, tokens, candidate, hit) {
525
+ const words = [term, ...tokens];
526
+ if (candidate.domain === 'doc') {
527
+ 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
+ ) {
535
+ return 2;
536
+ }
537
+ if (
538
+ words.some(
539
+ w =>
540
+ (scoreCandidate(w, {name: topic}, {fuzzy: false})?.score ?? 0) >= 95,
541
+ )
542
+ ) {
543
+ return 1;
544
+ }
545
+ // A whole title inside the query is the only path to 160-169.
546
+ if (hit.score >= TITLE_IN_QUERY_SCORE && hit.score < TITLE_PHRASE_SCORE) {
547
+ return 1;
548
+ }
549
+ // Every word matched, and one of them names the doc in its title.
550
+ if (
551
+ hit.score >= FULL_COVERAGE_SCORE &&
552
+ hit.score < TITLE_IN_QUERY_SCORE &&
553
+ hit.matched === hit.total
554
+ ) {
555
+ const titleWords = phraseWords(candidate.titles?.[0] ?? '');
556
+ if (
557
+ (tokens.length ? tokens : [term]).some(t =>
558
+ titleWords.some(w => samePhraseWord(t, w) || sameWord(t, w)),
559
+ )
560
+ ) {
561
+ return 1;
562
+ }
563
+ }
564
+ return 0;
565
+ }
566
+ if (hit.score >= FULL_COVERAGE_SCORE) return 1;
567
+ const fuzzy = tokens.length <= 1;
568
+ return words.some(
569
+ w =>
570
+ (bestForToken(w, candidate, {fuzzy})?.score ?? 0) >= STRONG_TOKEN_SCORE,
571
+ )
572
+ ? 1
573
+ : 0;
574
+ }
575
+
479
576
  /**
480
577
  * The words of a title or query, lowercased, without punctuation or code ticks.
481
578
  * @param {string} text
482
579
  * @returns {string[]}
483
580
  */
484
581
  function phraseWords(text) {
485
- return unlinkText(text).toLowerCase().match(/[a-z0-9]+/g) ?? [];
582
+ return (
583
+ unlinkText(text)
584
+ .toLowerCase()
585
+ .match(/[a-z0-9]+/g) ?? []
586
+ );
486
587
  }
487
588
 
488
589
  /**
@@ -679,9 +780,7 @@ export function scoreQuery(term, tokens, candidate) {
679
780
  score:
680
781
  FULL_COVERAGE_SCORE +
681
782
  Math.min(
682
- Math.floor(
683
- (tokenSum - matched * MIN_TOKEN_SCORE) / (matched * 5),
684
- ),
783
+ Math.floor((tokenSum - matched * MIN_TOKEN_SCORE) / (matched * 5)),
685
784
  8,
686
785
  ),
687
786
  reason,
@@ -1115,17 +1214,15 @@ export async function componentKeywords(coreDir, cwd) {
1115
1214
  coreDir,
1116
1215
  loadedIntegrations,
1117
1216
  );
1118
- const integrations = loadedIntegrations.map(
1119
- async integration => {
1120
- const {components} = await discoverValidIntegrationComponents(integration);
1121
- return Promise.all(
1122
- components.map(async rec => ({
1123
- name: rec.name,
1124
- keywords: keywordsOf(await loadModuleDoc(rec.docPath)),
1125
- })),
1126
- );
1127
- },
1128
- );
1217
+ const integrations = loadedIntegrations.map(async integration => {
1218
+ const {components} = await discoverValidIntegrationComponents(integration);
1219
+ return Promise.all(
1220
+ components.map(async rec => ({
1221
+ name: rec.name,
1222
+ keywords: keywordsOf(await loadModuleDoc(rec.docPath)),
1223
+ })),
1224
+ );
1225
+ });
1129
1226
  return [
1130
1227
  ...(await Promise.all(core)).filter(
1131
1228
  component => !replacements.forTarget(component.name),
@@ -1221,7 +1318,11 @@ async function gatherDocs(cwd) {
1221
1318
  const packages = new Map([
1222
1319
  [entry.providerId ?? entry.package, entry.package],
1223
1320
  ...entry.extensions.map(
1224
- ext => /** @type {[string, string]} */ ([ext.providerId ?? ext.package, ext.package]),
1321
+ ext =>
1322
+ /** @type {[string, string]} */ ([
1323
+ ext.providerId ?? ext.package,
1324
+ ext.package,
1325
+ ]),
1225
1326
  ),
1226
1327
  ]);
1227
1328
  candidates.push(
@@ -1299,7 +1400,8 @@ async function gatherDocs(cwd) {
1299
1400
  _topic: node.route,
1300
1401
  _title: path.join(' › '),
1301
1402
  _command: `astryx docs ${node.route}`,
1302
- _parent: node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,
1403
+ _parent:
1404
+ node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,
1303
1405
  _package: node.provider,
1304
1406
  });
1305
1407
  }
@@ -1463,7 +1565,9 @@ function topicCandidates(
1463
1565
  _title: `${docTitle} › ${section.title}`,
1464
1566
  _command: `astryx docs ${name} ${key}`,
1465
1567
  _parent: `astryx docs ${name} --index`,
1466
- ...((sectionPackage?.(key) ?? pkg) ? {_package: sectionPackage?.(key) ?? pkg} : {}),
1568
+ ...((sectionPackage?.(key) ?? pkg)
1569
+ ? {_package: sectionPackage?.(key) ?? pkg}
1570
+ : {}),
1467
1571
  });
1468
1572
  }
1469
1573
  return out;
@@ -1711,24 +1815,61 @@ export async function search(query, options = {}) {
1711
1815
  // role (page / block / component) and takes the top of each, so there's no
1712
1816
  // cross-role competition to engineer — a target page only needs to be the
1713
1817
  // strongest PAGE, not outrank every component.
1714
- const scored = [];
1818
+ /** @type {{result: any, priority: 0 | 1 | 2}[]} */
1819
+ const ranked = [];
1715
1820
  for (const candidate of all) {
1716
1821
  const hit = scoreQuery(term, tokens, candidate);
1717
1822
  if (hit)
1718
- scored.push(
1719
- toResult(candidate, hit.score, hit.reason, hit.matched, hit.total),
1720
- );
1823
+ ranked.push({
1824
+ result: toResult(
1825
+ candidate,
1826
+ hit.score,
1827
+ hit.reason,
1828
+ hit.matched,
1829
+ hit.total,
1830
+ ),
1831
+ priority: domainPriority(term, tokens, candidate, hit),
1832
+ });
1721
1833
  }
1722
1834
 
1723
- // Sort by score desc, then domain (stable order), then name.
1835
+ // Docs and everything else are each sorted by score desc, then domain
1836
+ // (stable order), then name. The two are merged: at each step the stronger
1837
+ // head goes next, except that a head with domain priority goes ahead of a
1838
+ // doc head without it (see domainPriority). Each side keeps its own order.
1724
1839
  /** @type {Record<string, number>} */
1725
1840
  const domainOrder = {component: 0, hook: 1, doc: 2, template: 3, theme: 4};
1726
- scored.sort(
1727
- (a, b) =>
1728
- b.score - a.score ||
1729
- (domainOrder[a.domain] ?? 9) - (domainOrder[b.domain] ?? 9) ||
1730
- a.name.localeCompare(b.name),
1731
- );
1841
+ /**
1842
+ * @param {{result: any}} x
1843
+ * @param {{result: any}} y
1844
+ */
1845
+ const byScore = ({result: a}, {result: b}) =>
1846
+ b.score - a.score ||
1847
+ (domainOrder[a.domain] ?? 9) - (domainOrder[b.domain] ?? 9) ||
1848
+ a.name.localeCompare(b.name);
1849
+ const others = ranked.filter(r => r.result.domain !== 'doc').sort(byScore);
1850
+ // Against other domains, a doc the reader asked for competes ahead of docs
1851
+ // they did not, so it is not held behind a broad page that outscores it.
1852
+ // Docs alone keep their text-match order, with a doc the whole query names
1853
+ // first.
1854
+ const docs = ranked
1855
+ .filter(r => r.result.domain === 'doc')
1856
+ .sort((x, y) =>
1857
+ others.length > 0
1858
+ ? y.priority - x.priority || byScore(x, y)
1859
+ : Number(y.priority === 2) - Number(x.priority === 2) || byScore(x, y),
1860
+ );
1861
+ const scored = [];
1862
+ let i = 0;
1863
+ let j = 0;
1864
+ while (i < others.length || j < docs.length) {
1865
+ const other = others[i];
1866
+ const doc = docs[j];
1867
+ const otherFirst =
1868
+ !doc ||
1869
+ (other != null &&
1870
+ ((other.priority && !doc.priority) || byScore(other, doc) < 0));
1871
+ scored.push(otherFirst ? others[i++].result : docs[j++].result);
1872
+ }
1732
1873
 
1733
1874
  // `results` is bounded by `limit` so a caller (and the recorded run that
1734
1875
  // quotes it) never carries an unbounded payload. `matchCount` is the number
@@ -71,6 +71,46 @@ export function validateComponentOverridesAgainstRegistry(themeDef: {
71
71
  propsByKey: Record<string, string[]>;
72
72
  deprecatedByKey: Record<string, string>;
73
73
  }): string[];
74
+ /**
75
+ * Print the install snippet and font guidance once for a batch: the first
76
+ * theme as the full example, one import line per built theme, and one font
77
+ * recipe naming every family the themes do not load.
78
+ * @param {ThemeBuildTrailer[]} trailers
79
+ */
80
+ export function printBatchTrailer(trailers: ThemeBuildTrailer[]): void;
81
+ /**
82
+ * Print what a short report keeps after its one line per theme: one line
83
+ * naming the fonts the themes do not load, and, when the caller chose no
84
+ * detail level, where the install example and font recipe are.
85
+ * @param {ThemeBuildTrailer[]} trailers
86
+ * @param {{hint?: boolean}} [options]
87
+ */
88
+ export function printCompactTrailer(trailers: ThemeBuildTrailer[], { hint }?: {
89
+ hint?: boolean;
90
+ }): void;
91
+ /**
92
+ * Build one theme for a batch or compact CLI report. Same build, outputs, and
93
+ * receipt as {@link themeBuild}; the install snippet and font guidance come
94
+ * back as `trailer` instead of being printed, and `compact` leaves out the
95
+ * per-file progress lines. CLI-internal: not exported from the API entry.
96
+ * @param {string} file
97
+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options]
98
+ * @param {{cwd?: string}} [ctx]
99
+ * @param {{compact?: boolean}} [report]
100
+ * @returns {Promise<{receipt: import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null, trailer: ThemeBuildTrailer | null}>}
101
+ */
102
+ export function themeBuildForReport(file: string, options?: {
103
+ out?: string;
104
+ check?: boolean;
105
+ iconsSpecifier?: string;
106
+ }, ctx?: {
107
+ cwd?: string;
108
+ }, { compact }?: {
109
+ compact?: boolean;
110
+ }): Promise<{
111
+ receipt: import("../theme.type.mjs").ThemeBuildResponse | import("../theme.type.mjs").ThemeBuildCheckResponse | null;
112
+ trailer: ThemeBuildTrailer | null;
113
+ }>;
74
114
  /** @param {string} file @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] @param {{cwd?: string}} [ctx] @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>} */
75
115
  export function themeBuild(file: string, options?: {
76
116
  out?: string;
@@ -140,6 +180,36 @@ export function themeBuildFamily(files: string[], options: {
140
180
  * validateAdaptationEnrollment)
141
181
  */
142
182
  export type ComponentValueClass = "builtin" | "enrollment" | "unresolved";
183
+ /**
184
+ * What a standalone build prints after its [ok] lines, kept as data so a
185
+ * batch can print it once for every theme.
186
+ */
187
+ export type ThemeBuildTrailer = {
188
+ /**
189
+ * The theme's name.
190
+ */
191
+ themeName: string;
192
+ /**
193
+ * The built module's theme export.
194
+ */
195
+ exportName: string;
196
+ /**
197
+ * Import specifier of the built JS module.
198
+ */
199
+ jsImport: string;
200
+ /**
201
+ * Import specifier of the built CSS.
202
+ */
203
+ cssImport: string;
204
+ /**
205
+ * Font families the theme names but does not load.
206
+ */
207
+ unloadedFonts: string[];
208
+ /**
209
+ * One notice per unloaded font family.
210
+ */
211
+ fontNotices: string[];
212
+ };
143
213
  /**
144
214
  * The bindings one Core provides: the namespaces interception spreads, the
145
215
  * functions the build calls, and why the import failed, if it did.