@astryxdesign/cli 0.7.2-canary.fe2c655 → 0.7.3-canary.02f5fe4

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 (694) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/README.md +216 -162
  3. package/api/build/_adapter.d.mts +66 -0
  4. package/api/build/_adapter.mjs +139 -4
  5. package/api/build/blocks/blocks.d.mts +92 -0
  6. package/api/build/blocks/blocks.mjs +528 -0
  7. package/api/build/blocks/blocks.test.mjs +238 -0
  8. package/api/build/blocks/blocks.weights.json +1 -0
  9. package/api/build/build.doc.mjs +4 -0
  10. package/api/build/build.mjs +25 -6
  11. package/api/build/build.type.mjs +1 -1
  12. package/api/build/help/help.mjs +1 -1
  13. package/api/build/kit/answer.d.mts +18 -0
  14. package/api/build/kit/answer.mjs +195 -0
  15. package/api/build/kit/answer.test.mjs +108 -0
  16. package/api/build/kit/kind.d.mts +25 -0
  17. package/api/build/kit/kind.mjs +170 -0
  18. package/api/build/kit/kit.d.mts +2 -4
  19. package/api/build/kit/kit.mjs +8 -406
  20. package/api/build/kit/rank.d.mts +3 -32
  21. package/api/build/kit/rank.mjs +25 -342
  22. package/api/build/kit/rank.test.mjs +2 -1
  23. package/api/build/kit/signals.d.mts +79 -0
  24. package/api/build/kit/signals.mjs +295 -0
  25. package/api/build/kit/start.d.mts +32 -0
  26. package/api/build/kit/start.mjs +163 -0
  27. package/api/build/kit/words.d.mts +72 -0
  28. package/api/build/kit/words.mjs +202 -0
  29. package/api/build/tree.d.mts +20 -0
  30. package/api/build/tree.mjs +53 -0
  31. package/api/build/tree.test.mjs +185 -0
  32. package/api/build/tree.weights.json +1 -0
  33. package/api/component/_adapter.d.mts +72 -1
  34. package/api/component/_adapter.mjs +251 -23
  35. package/api/component/component-replacement.test.mjs +1 -0
  36. package/api/component/component.doc.mjs +6 -1
  37. package/api/component/component.mjs +97 -16
  38. package/api/component/component.test.mjs +95 -0
  39. package/api/component/doc-links.test.mjs +386 -0
  40. package/api/component/integration-export-name.test.mjs +644 -0
  41. package/api/component/list/list.mjs +42 -4
  42. package/api/discover/_adapter.d.mts +131 -12
  43. package/api/discover/_adapter.mjs +520 -34
  44. package/api/discover/_adapter.test.mjs +641 -17
  45. package/api/discover/_catalog-view.d.mts +16 -5
  46. package/api/discover/_catalog-view.mjs +32 -8
  47. package/api/discover/detail/doc/doc.mjs +9 -1
  48. package/api/discover/discover.d.mts +11 -0
  49. package/api/discover/discover.doc.mjs +9 -7
  50. package/api/discover/discover.mjs +120 -19
  51. package/api/discover/discover.type.d.mts +20 -7
  52. package/api/discover/discover.type.mjs +17 -7
  53. package/api/discover/list/list.d.mts +4 -3
  54. package/api/discover/list/list.mjs +17 -10
  55. package/api/docs/_adapter.d.mts +76 -2
  56. package/api/docs/_adapter.mjs +630 -34
  57. package/api/docs/docs-homes.test.mjs +127 -0
  58. package/api/docs/docs.doc.mjs +5 -4
  59. package/api/docs/docs.mjs +2 -1
  60. package/api/docs/docs.test.mjs +39 -20
  61. package/api/docs/integration-tree.test.mjs +42 -20
  62. package/api/docs/integrationDocs.test.mjs +125 -1
  63. package/api/docs/list/list.mjs +12 -2
  64. package/api/docs/namespace-section.test.mjs +6 -6
  65. package/api/docs/reference-blocks.test.mjs +3 -5
  66. package/api/doctor/_adapter.d.mts +128 -0
  67. package/api/doctor/_adapter.mjs +253 -4
  68. package/api/doctor/doctor.d.mts +217 -0
  69. package/api/doctor/doctor.doc.mjs +3 -2
  70. package/api/doctor/doctor.mjs +691 -52
  71. package/api/doctor/doctor.test.mjs +267 -18
  72. package/api/doctor/release-checks.test.mjs +156 -0
  73. package/api/doctor/theme-checks.mjs +17 -4
  74. package/api/doctor/theme-checks.test.mjs +223 -7
  75. package/api/error.d.mts +10 -0
  76. package/api/error.mjs +25 -0
  77. package/api/gap-report/gap-report.d.mts +3 -0
  78. package/api/gap-report/gap-report.doc.mjs +11 -3
  79. package/api/gap-report/gap-report.mjs +219 -52
  80. package/api/gap-report/gap-report.test.mjs +233 -0
  81. package/api/gap-report/gap-report.type.d.mts +41 -0
  82. package/api/gap-report/gap-report.type.mjs +18 -0
  83. package/api/hook/_adapter.mjs +3 -11
  84. package/api/hook/hook.doc.mjs +4 -0
  85. package/api/hook/hook.mjs +1 -1
  86. package/api/hook/list/list.d.mts +1 -1
  87. package/api/index.d.mts +2 -0
  88. package/api/index.mjs +2 -0
  89. package/api/init/_adapter.d.mts +22 -0
  90. package/api/init/_adapter.mjs +59 -0
  91. package/api/init/init.d.mts +7 -5
  92. package/api/init/init.doc.mjs +45 -10
  93. package/api/init/init.mjs +28 -4
  94. package/api/init/init.test.mjs +18 -2
  95. package/api/init/init.type.d.mts +50 -5
  96. package/api/init/init.type.mjs +39 -5
  97. package/api/init/remove/remove.mjs +17 -4
  98. package/api/init/remove/remove.test.mjs +114 -2
  99. package/api/init/run/run.d.mts +1 -1
  100. package/api/init/run/run.mjs +86 -12
  101. package/api/init/user/user.d.mts +14 -0
  102. package/api/init/user/user.mjs +87 -0
  103. package/api/init/user/user.test.mjs +232 -0
  104. package/api/integration/_adapter.d.mts +53 -0
  105. package/api/integration/_adapter.mjs +132 -0
  106. package/api/integration/add-contribution.component-names.test.mjs +66 -0
  107. package/api/integration/add-contribution.mjs +8 -4
  108. package/api/integration/add-contribution.test.mjs +4 -2
  109. package/api/integration/authoring-checks.mjs +192 -14
  110. package/api/integration/authoring-checks.test.mjs +1028 -0
  111. package/api/integration/authoring-checks.type.d.mts +143 -0
  112. package/api/integration/authoring-checks.type.mjs +74 -2
  113. package/api/integration/check/check.d.mts +96 -0
  114. package/api/integration/check/check.mjs +357 -0
  115. package/api/integration/check/check.test.mjs +489 -0
  116. package/api/integration/integration-check.type.d.mts +118 -0
  117. package/api/integration/integration-check.type.mjs +84 -0
  118. package/api/integration/integrationCheck.doc.d.mts +10 -0
  119. package/api/integration/integrationCheck.doc.mjs +73 -0
  120. package/api/integration/integrationComponentConflicts.doc.mjs +45 -6
  121. package/api/integration/integrationDocConflicts.doc.mjs +22 -5
  122. package/api/integration/pack-check.mjs +486 -123
  123. package/api/integration/pack-check.test.mjs +817 -10
  124. package/api/integration/validate-integration-case-disk.test.mjs +111 -0
  125. package/api/integration/validate-integration-fixes.test.mjs +73 -5
  126. package/api/integration/validate-integration-gaps.test.mjs +1975 -0
  127. package/api/integration/validate-integration.d.mts +23 -2
  128. package/api/integration/validate-integration.mjs +358 -45
  129. package/api/integration/validate-integration.test.mjs +88 -8
  130. package/api/integration/validate-integration.type.d.mts +105 -0
  131. package/api/integration/validate-integration.type.mjs +79 -1
  132. package/api/integration/validate-unread-theme-folders.test.mjs +3 -2
  133. package/api/integration/validateIntegration.doc.mjs +19 -3
  134. package/api/search/ORDERING.md +28 -0
  135. package/api/search/_adapter.d.mts +91 -0
  136. package/api/search/_adapter.mjs +172 -0
  137. package/api/search/_adapter.test.mjs +173 -0
  138. package/api/search/_candidate-score.d.mts +40 -0
  139. package/api/search/_candidate-score.mjs +238 -0
  140. package/api/search/_cards.json +6098 -0
  141. package/api/search/_compound.d.mts +50 -0
  142. package/api/search/_compound.mjs +170 -0
  143. package/api/search/_doc-searcher.d.mts +4 -0
  144. package/api/search/_doc-searcher.mjs +23 -0
  145. package/api/search/_doc-searcher.test.mjs +36 -0
  146. package/api/search/_doc-searcher.weights.json +1 -0
  147. package/api/search/_doc-text.d.mts +30 -0
  148. package/api/search/_doc-text.mjs +87 -0
  149. package/api/search/_entries.d.mts +63 -0
  150. package/api/search/_entries.mjs +232 -0
  151. package/api/search/_entries.test.mjs +48 -0
  152. package/api/search/_features.d.mts +35 -0
  153. package/api/search/_features.mjs +155 -0
  154. package/api/search/_gather-components.d.mts +26 -0
  155. package/api/search/_gather-components.mjs +284 -0
  156. package/api/search/_gather-docs.d.mts +20 -0
  157. package/api/search/_gather-docs.mjs +254 -0
  158. package/api/search/_gather-hooks.d.mts +12 -0
  159. package/api/search/_gather-hooks.mjs +52 -0
  160. package/api/search/_gather-templates.d.mts +25 -0
  161. package/api/search/_gather-templates.mjs +107 -0
  162. package/api/search/_lexical.d.mts +135 -0
  163. package/api/search/_lexical.mjs +351 -0
  164. package/api/search/_main-searcher.d.mts +19 -0
  165. package/api/search/_main-searcher.mjs +115 -0
  166. package/api/search/_main-searcher.test.mjs +106 -0
  167. package/api/search/_main-searcher.weights.json +1 -0
  168. package/api/search/_module-doc.d.mts +32 -0
  169. package/api/search/_module-doc.mjs +78 -0
  170. package/api/search/_order.d.mts +32 -0
  171. package/api/search/_order.mjs +162 -0
  172. package/api/search/_order.test.mjs +72 -0
  173. package/api/search/_priority.d.mts +50 -0
  174. package/api/search/_priority.mjs +139 -0
  175. package/api/search/_query-words.d.mts +25 -0
  176. package/api/search/_query-words.mjs +92 -0
  177. package/api/search/_query.d.mts +65 -0
  178. package/api/search/_query.mjs +176 -0
  179. package/api/search/_result.d.mts +97 -0
  180. package/api/search/_result.mjs +150 -0
  181. package/api/search/_score.d.mts +60 -0
  182. package/api/search/_score.mjs +283 -0
  183. package/api/search/_synonyms.d.mts +21 -0
  184. package/api/search/_synonyms.mjs +67 -0
  185. package/api/search/_template-searcher.d.mts +4 -0
  186. package/api/search/_template-searcher.mjs +23 -0
  187. package/api/search/_template-searcher.test.mjs +40 -0
  188. package/api/search/_template-searcher.weights.json +1 -0
  189. package/api/search/_titles.d.mts +33 -0
  190. package/api/search/_titles.mjs +65 -0
  191. package/api/search/_words.d.mts +64 -0
  192. package/api/search/_words.mjs +157 -0
  193. package/api/search/search.d.mts +22 -236
  194. package/api/search/search.doc.mjs +14 -7
  195. package/api/search/search.domain-priority.test.mjs +108 -18
  196. package/api/search/search.integration-check.test.mjs +24 -0
  197. package/api/search/search.mjs +59 -1904
  198. package/api/search/search.test.mjs +193 -15
  199. package/api/search/search.type.d.mts +20 -2
  200. package/api/search/search.type.mjs +12 -2
  201. package/api/search/tree.d.mts +15 -0
  202. package/api/search/tree.mjs +40 -0
  203. package/api/search/tree.test.mjs +66 -0
  204. package/api/search/tree.weights.json +1 -0
  205. package/api/swizzle/_adapter.mjs +2 -2
  206. package/api/swizzle/copy/copy.mjs +29 -15
  207. package/api/template/template-integration.test.mjs +1 -1
  208. package/api/template/template.mjs +5 -1
  209. package/api/template/template.test.mjs +120 -3
  210. package/api/theme/_adapter.d.mts +16 -0
  211. package/api/theme/_adapter.mjs +32 -5
  212. package/api/theme/build/build.d.mts +2 -1
  213. package/api/theme/build/build.family.test.mjs +64 -0
  214. package/api/theme/build/build.mjs +250 -38
  215. package/api/theme/build/build.packed-old-core.test.mjs +21 -3
  216. package/api/theme/build/font-warning.mjs +5 -3
  217. package/api/theme/build/font-warning.test.mjs +2 -1
  218. package/api/theme/remove/remove.test.mjs +2 -2
  219. package/api/theme/targets/targets.mjs +3 -10
  220. package/api/theme/themeBuild.doc.mjs +4 -4
  221. package/api/theme/themeTargets.doc.mjs +4 -0
  222. package/api/theme/use/use.test.mjs +1 -1
  223. package/api/upgrade/_adapter.d.mts +97 -11
  224. package/api/upgrade/_adapter.mjs +315 -32
  225. package/api/upgrade/registry/registry.d.mts +10 -4
  226. package/api/upgrade/registry/registry.mjs +33 -16
  227. package/api/upgrade/registry/registry.test.mjs +85 -0
  228. package/api/upgrade/run/cli-behind-core.test.mjs +438 -0
  229. package/api/upgrade/run/run.d.mts +4 -2
  230. package/api/upgrade/run/run.mjs +48 -4
  231. package/api/upgrade/run/run.test.mjs +417 -3
  232. package/api/upgrade/status/status.d.mts +21 -5
  233. package/api/upgrade/status/status.mjs +45 -8
  234. package/api/upgrade/upgrade.doc.mjs +16 -8
  235. package/api/upgrade/upgrade.mjs +18 -3
  236. package/api/upgrade/upgrade.test.mjs +194 -0
  237. package/api/upgrade/upgrade.type.d.mts +28 -3
  238. package/api/upgrade/upgrade.type.mjs +24 -7
  239. package/assets/codemods/__tests__/registry.test.mjs +1 -0
  240. package/assets/codemods/registry.mjs +1 -0
  241. package/assets/codemods/runner.mjs +7 -1
  242. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +11 -0
  243. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +3 -3
  244. package/assets/codemods/transforms/v0.7.2/__tests__/migrate-list-edge-compensation-to-edge.test.mjs +120 -0
  245. package/assets/codemods/transforms/v0.7.2/index.mjs +20 -0
  246. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +198 -0
  247. package/assets/discover/official-packages.json +367 -0
  248. package/assets/docs/README.md +10 -0
  249. package/assets/docs/author-a-theme.doc.mjs +5 -5
  250. package/assets/docs/browser-support.doc.mjs +1 -1
  251. package/assets/docs/getting-started.doc.mjs +26 -6
  252. package/assets/docs/is-my-code-good.doc.mjs +287 -0
  253. package/assets/docs/styling-overview.doc.mjs +1 -1
  254. package/assets/docs/theme.doc.dense.mjs +1 -1
  255. package/assets/docs/theme.doc.mjs +2 -2
  256. package/assets/docs/theme.doc.zh.mjs +1 -1
  257. package/assets/docs/tree/add-a-component.doc.mjs +22 -2
  258. package/assets/docs/tree/add-a-theme.doc.mjs +14 -4
  259. package/assets/docs/tree/add-a-topic.doc.mjs +54 -9
  260. package/assets/docs/tree/agent-guidance.doc.mjs +19 -5
  261. package/assets/docs/tree/api.doc.mjs +6 -0
  262. package/assets/docs/tree/authoring.doc.mjs +61 -0
  263. package/assets/docs/tree/block-template.doc.mjs +8 -20
  264. package/assets/docs/tree/build-the-template.doc.mjs +1 -1
  265. package/assets/docs/tree/building-blocks.doc.mjs +6 -2
  266. package/assets/docs/tree/check-the-props.doc.mjs +201 -0
  267. package/assets/docs/tree/check-your-docs.doc.mjs +69 -11
  268. package/assets/docs/tree/checks.doc.mjs +32 -24
  269. package/assets/docs/tree/ci-and-containers.doc.mjs +101 -0
  270. package/assets/docs/tree/cli-command.doc.mjs +142 -0
  271. package/assets/docs/tree/cli.doc.mjs +7 -1
  272. package/assets/docs/tree/codemods.doc.mjs +17 -7
  273. package/assets/docs/tree/commands.doc.mjs +7 -1
  274. package/assets/docs/tree/component-family.doc.mjs +8 -6
  275. package/assets/docs/tree/component-imports.doc.mjs +21 -3
  276. package/assets/docs/tree/components.doc.mjs +7 -1
  277. package/assets/docs/tree/computer-agent-guide.doc.mjs +160 -0
  278. package/assets/docs/tree/computer-integrations.doc.mjs +93 -0
  279. package/assets/docs/tree/configuration.doc.mjs +8 -4
  280. package/assets/docs/tree/debug-and-gap-reports.doc.mjs +41 -22
  281. package/assets/docs/tree/define-the-theme.doc.mjs +7 -6
  282. package/assets/docs/tree/describe-the-component.doc.mjs +3 -3
  283. package/assets/docs/tree/docs.doc.mjs +9 -3
  284. package/assets/docs/tree/document-the-template.doc.mjs +1 -1
  285. package/assets/docs/tree/document-the-theme.doc.mjs +4 -4
  286. package/assets/docs/tree/export-template-assets.doc.mjs +1 -1
  287. package/assets/docs/tree/extend-or-replace.doc.mjs +19 -9
  288. package/assets/docs/{authoring.doc.mjs → tree/field-reference.doc.mjs} +4 -3
  289. package/assets/docs/tree/fonts-and-assets.doc.mjs +3 -3
  290. package/assets/docs/tree/generate-a-palette.doc.mjs +8 -6
  291. package/assets/docs/tree/global-integrations.doc.mjs +124 -0
  292. package/assets/docs/tree/global.doc.mjs +131 -0
  293. package/assets/docs/tree/grade-template-with-agent.doc.mjs +5 -5
  294. package/assets/docs/tree/help.doc.mjs +2 -2
  295. package/assets/docs/tree/host-entry.doc.mjs +128 -0
  296. package/assets/docs/tree/install-once.doc.mjs +105 -0
  297. package/assets/docs/tree/layout-spacing.doc.mjs +2 -3
  298. package/assets/docs/tree/layout.doc.mjs +6 -6
  299. package/assets/docs/tree/links.doc.mjs +7 -6
  300. package/assets/docs/tree/migration-setup.doc.mjs +3 -2
  301. package/assets/docs/tree/migration-verification.doc.mjs +0 -1
  302. package/assets/docs/tree/migration.doc.mjs +0 -1
  303. package/assets/docs/tree/monorepos.doc.mjs +84 -0
  304. package/assets/docs/tree/package-and-test.doc.mjs +1 -1
  305. package/assets/docs/tree/page-template.doc.mjs +4 -8
  306. package/assets/docs/tree/problems.doc.mjs +205 -0
  307. package/assets/docs/tree/project-global-or-both.doc.mjs +131 -0
  308. package/assets/docs/tree/publishing.doc.mjs +6 -6
  309. package/assets/docs/tree/quick-start.doc.mjs +54 -28
  310. package/assets/docs/tree/reference.doc.mjs +192 -0
  311. package/assets/docs/tree/replace-a-core-component.doc.mjs +15 -7
  312. package/assets/docs/tree/replace-a-core-template.doc.mjs +10 -12
  313. package/assets/docs/tree/scaffold.doc.mjs +1 -1
  314. package/assets/docs/tree/sections-and-placement.doc.mjs +9 -11
  315. package/assets/docs/tree/see-it-in-an-app.doc.mjs +17 -5
  316. package/assets/docs/tree/ship.doc.mjs +2 -2
  317. package/assets/docs/tree/short-and-findable.doc.mjs +9 -8
  318. package/assets/docs/tree/single-component.doc.mjs +15 -6
  319. package/assets/docs/tree/start-a-template.doc.mjs +18 -8
  320. package/assets/docs/tree/subcomponent.doc.mjs +6 -6
  321. package/assets/docs/tree/template-assets.doc.mjs +2 -2
  322. package/assets/docs/tree/template-doc-overview.doc.mjs +6 -17
  323. package/assets/docs/tree/template-fonts.doc.mjs +1 -1
  324. package/assets/docs/tree/template-grading-rubric.doc.mjs +17 -38
  325. package/assets/docs/tree/template-icons.doc.mjs +1 -1
  326. package/assets/docs/tree/template-images-media.doc.mjs +1 -1
  327. package/assets/docs/tree/template-styles.doc.mjs +2 -2
  328. package/assets/docs/tree/templates.doc.mjs +7 -1
  329. package/assets/docs/tree/test-in-an-app.doc.mjs +7 -7
  330. package/assets/docs/tree/test-template-in-app.doc.mjs +5 -5
  331. package/assets/docs/tree/themes.doc.mjs +5 -1
  332. package/assets/docs/tree/tokens-and-setup.doc.mjs +19 -15
  333. package/assets/docs/tree/tokens-data.doc.mjs +2 -2
  334. package/assets/docs/tree/troubleshooting.doc.mjs +29 -13
  335. package/assets/docs/tree/type-scale.doc.mjs +3 -3
  336. package/assets/docs/tree/uninstall.doc.mjs +109 -0
  337. package/assets/docs/tree/updates.doc.mjs +92 -0
  338. package/assets/docs/tree/upgrading.doc.mjs +6 -6
  339. package/assets/docs/tree/use-a-theme-in-an-app.doc.mjs +15 -3
  340. package/assets/docs/tree/verify-packed-template.doc.mjs +3 -3
  341. package/assets/docs/tree/versioning.doc.mjs +14 -9
  342. package/assets/docs/tree/who-answers.doc.mjs +119 -0
  343. package/assets/docs/tree/write-good-templates.doc.mjs +1 -1
  344. package/assets/docs/tree/write-the-template-file.doc.mjs +7 -6
  345. package/assets/docs/use-a-theme.doc.mjs +2 -2
  346. package/assets/docs/use-integrations.doc.mjs +120 -0
  347. package/assets/docs/working-with-ai.doc.mjs +70 -13
  348. package/assets/templates/themes/butter/butterTheme.ts +4 -2
  349. package/assets/templates/themes/stone/stoneTheme.ts +4 -2
  350. package/assets/templates/themes/y2k/y2kTheme.ts +4 -2
  351. package/assets/theme.template.ts +1 -1
  352. package/authoring/codemod/codemod.doc.mjs +7 -3
  353. package/authoring/config/config.doc.mjs +9 -6
  354. package/authoring/config/type.ts +4 -2
  355. package/authoring/debug/parse.d.mts +5 -5
  356. package/authoring/discover/discover.doc.mjs +7 -1
  357. package/authoring/doctypes/_schema.d.mts +8 -3
  358. package/authoring/doctypes/_schema.mjs +1 -0
  359. package/authoring/doctypes/base/graph-fields.doc.mjs +6 -4
  360. package/authoring/doctypes/command/command.doc.mjs +20 -12
  361. package/authoring/doctypes/command/type.ts +14 -0
  362. package/authoring/doctypes/component/component.doc.mjs +30 -27
  363. package/authoring/doctypes/component/type.ts +21 -8
  364. package/authoring/doctypes/enum/enum.doc.mjs +7 -4
  365. package/authoring/doctypes/function/function.doc.mjs +9 -8
  366. package/authoring/doctypes/hook/hook.doc.mjs +5 -4
  367. package/authoring/doctypes/hook/type.ts +4 -0
  368. package/authoring/doctypes/namespace/namespace.doc.mjs +7 -6
  369. package/authoring/doctypes/reference/reference.doc.mjs +12 -11
  370. package/authoring/doctypes/schema/schema.doc.mjs +10 -10
  371. package/authoring/doctypes/template/integration-template.doc.d.mts +11 -0
  372. package/authoring/doctypes/template/integration-template.doc.mjs +49 -0
  373. package/authoring/doctypes/template/parse.d.mts +6 -2
  374. package/authoring/doctypes/template/parse.mjs +3 -1
  375. package/authoring/doctypes/template/template.doc.mjs +3 -3
  376. package/authoring/doctypes/template/type.ts +22 -0
  377. package/authoring/doctypes/theme/theme.doc.mjs +2 -2
  378. package/authoring/gap-report/gap-report.doc.mjs +2 -2
  379. package/authoring/identity/identity.doc.mjs +3 -3
  380. package/authoring/index.d.ts +2 -0
  381. package/authoring/integration/integration.doc.mjs +30 -6
  382. package/authoring/integration/parse.test.mjs +21 -0
  383. package/authoring/integration/schema.d.mts +16 -3
  384. package/authoring/integration/schema.mjs +34 -2
  385. package/authoring/integration/type.ts +13 -1
  386. package/clients/cli/bin/astryx.mjs +11 -65
  387. package/clients/cli/cli-command.test.mjs +166 -0
  388. package/clients/cli/command-result-coverage.test.mjs +6 -5
  389. package/clients/cli/commands/blog.doc.mjs +1 -0
  390. package/clients/cli/commands/build-theme.batch-report.test.mjs +17 -3
  391. package/clients/cli/commands/build-theme.color-scheme.test.mjs +1 -1
  392. package/clients/cli/commands/build-theme.font-warning.test.mjs +3 -3
  393. package/clients/cli/commands/build-theme.path-safety.test.mjs +224 -6
  394. package/clients/cli/commands/build-theme.registry.test.mjs +5 -2
  395. package/clients/cli/commands/build.doc.mjs +1 -0
  396. package/clients/cli/commands/build.exit-codes-doc.test.mjs +4 -0
  397. package/clients/cli/commands/cli-postinstall.test.mjs +49 -1
  398. package/clients/cli/commands/component.doc.mjs +1 -0
  399. package/clients/cli/commands/{component/index.mjs → component.mjs} +37 -37
  400. package/clients/cli/commands/component.test.mjs +6 -6
  401. package/clients/cli/commands/discover.broken-integration.test.mjs +11 -7
  402. package/clients/cli/commands/discover.doc.mjs +9 -1
  403. package/clients/cli/commands/discover.mjs +144 -93
  404. package/clients/cli/commands/discover.no-source.test.mjs +448 -33
  405. package/clients/cli/commands/discover.sources.test.mjs +20 -1
  406. package/clients/cli/commands/docs.doc.mjs +3 -2
  407. package/clients/cli/commands/docs.mjs +50 -20
  408. package/clients/cli/commands/docs.test.mjs +16 -16
  409. package/clients/cli/commands/doctor-integration-components.doc.mjs +19 -4
  410. package/clients/cli/commands/doctor-integration-docs.doc.mjs +20 -5
  411. package/clients/cli/commands/doctor-integration-templates.doc.mjs +1 -0
  412. package/clients/cli/commands/doctor-integration-validate.doc.mjs +22 -2
  413. package/clients/cli/commands/doctor-integration.test.mjs +936 -3
  414. package/clients/cli/commands/doctor.doc.mjs +12 -2
  415. package/clients/cli/commands/doctor.mjs +332 -7
  416. package/clients/cli/commands/doctor.test.mjs +75 -4
  417. package/clients/cli/commands/gap-report.doc.mjs +15 -2
  418. package/clients/cli/commands/gap-report.mjs +24 -2
  419. package/clients/cli/commands/gap-report.test.mjs +79 -0
  420. package/clients/cli/commands/hook.doc.mjs +1 -0
  421. package/clients/cli/commands/{hook/index.mjs → hook.mjs} +22 -22
  422. package/clients/cli/commands/import-hint-correctness.test.mjs +1 -1
  423. package/clients/cli/commands/init.behavior.test.mjs +235 -1
  424. package/clients/cli/commands/init.doc.mjs +55 -10
  425. package/clients/cli/commands/init.flag-help.test.mjs +1 -0
  426. package/clients/cli/commands/init.mjs +2 -2
  427. package/clients/cli/commands/integration-add.doc.mjs +7 -0
  428. package/clients/cli/commands/integration-authoring.test.mjs +49 -3
  429. package/clients/cli/commands/integration-check.doc.mjs +93 -0
  430. package/clients/cli/commands/integration-check.test.mjs +489 -0
  431. package/clients/cli/commands/integration-pack.doc.mjs +8 -1
  432. package/clients/cli/commands/integration-verify.doc.mjs +8 -1
  433. package/clients/cli/commands/integration.doc.mjs +6 -2
  434. package/clients/cli/commands/integration.mjs +119 -7
  435. package/clients/cli/commands/json-contract.test.mjs +11 -2
  436. package/clients/cli/commands/manifest.doc.mjs +2 -1
  437. package/clients/cli/commands/manifest.mjs +67 -0
  438. package/clients/cli/commands/outside-project.test.mjs +874 -0
  439. package/clients/cli/commands/postinstall.doc.mjs +23 -0
  440. package/clients/cli/commands/postinstall.mjs +31 -0
  441. package/clients/cli/commands/search.doc.mjs +1 -0
  442. package/clients/cli/commands/search.mjs +16 -11
  443. package/clients/cli/commands/search.test.mjs +429 -296
  444. package/clients/cli/commands/setup-nudge.test.mjs +180 -2
  445. package/clients/cli/commands/swizzle.doc.mjs +7 -0
  446. package/clients/cli/commands/swizzle.mjs +5 -3
  447. package/clients/cli/commands/swizzle.routing.test.mjs +19 -2
  448. package/clients/cli/commands/template.doc.mjs +1 -0
  449. package/clients/cli/commands/text-json-parity.test.mjs +5 -0
  450. package/clients/cli/commands/theme-add-lifecycle.test.mjs +3 -3
  451. package/clients/cli/commands/theme-add.doc.mjs +8 -1
  452. package/clients/cli/commands/theme-build.doc.mjs +3 -2
  453. package/clients/cli/commands/theme-eject.doc.mjs +1 -0
  454. package/clients/cli/commands/theme-list.behavior.test.mjs +6 -0
  455. package/clients/cli/commands/theme-list.doc.mjs +1 -0
  456. package/clients/cli/commands/theme-palette-generate.doc.mjs +1 -0
  457. package/clients/cli/commands/theme-remove.doc.mjs +7 -0
  458. package/clients/cli/commands/theme-targets.doc.mjs +1 -0
  459. package/clients/cli/commands/theme-template.doc.mjs +1 -0
  460. package/clients/cli/commands/theme-use.doc.mjs +7 -0
  461. package/clients/cli/commands/{build-theme.mjs → theme.mjs} +27 -14
  462. package/clients/cli/commands/upgrade.config-ordering.test.mjs +2 -1
  463. package/clients/cli/commands/upgrade.doc.mjs +26 -3
  464. package/clients/cli/commands/upgrade.file-protection.test.mjs +3 -2
  465. package/clients/cli/commands/upgrade.hook-output.test.mjs +2 -1
  466. package/clients/cli/commands/upgrade.mjs +9 -2
  467. package/clients/cli/commands/upgrade.older-cli.test.mjs +160 -0
  468. package/clients/cli/commands/upgrade.subfolder-path.test.mjs +97 -0
  469. package/clients/cli/index.mjs +156 -100
  470. package/clients/cli/lib/cli-error.mjs +4 -1
  471. package/clients/cli/lib/component-format.mjs +1 -1
  472. package/clients/cli/lib/component-format.test.mjs +1 -1
  473. package/clients/cli/lib/define-command.mjs +14 -9
  474. package/clients/cli/lib/exit-codes.test.mjs +5 -0
  475. package/clients/cli/lib/json-shim.mjs +3 -1
  476. package/clients/cli/lib/manifest.d.ts +9 -0
  477. package/clients/cli/lib/manifest.mjs +17 -1
  478. package/clients/cli/lib/manifest.test.mjs +37 -0
  479. package/clients/cli/lib/welcome-box.mjs +50 -0
  480. package/clients/cli/run.mjs +108 -0
  481. package/foundation/agent-docs/agent-doc-state.d.mts +67 -13
  482. package/foundation/agent-docs/agent-doc-state.mjs +123 -14
  483. package/foundation/agent-docs/agent-docs.d.mts +104 -15
  484. package/foundation/agent-docs/agent-docs.mjs +1028 -114
  485. package/foundation/agent-docs/agent-docs.path-safety.test.mjs +1239 -17
  486. package/foundation/agent-docs/agent-docs.test.mjs +683 -39
  487. package/foundation/agent-docs/computer-agent-text.d.mts +170 -0
  488. package/foundation/agent-docs/computer-agent-text.mjs +750 -0
  489. package/foundation/agent-docs/computer-agent-text.test.mjs +699 -0
  490. package/foundation/config/project.d.mts +35 -3
  491. package/foundation/config/project.mjs +243 -26
  492. package/foundation/config/project.test.mjs +122 -0
  493. package/foundation/config/theme-state.mjs +5 -4
  494. package/foundation/discovery/authoring-self-docs.d.mts +7 -0
  495. package/foundation/discovery/authoring-self-docs.mjs +17 -4
  496. package/foundation/discovery/authoring-self-docs.test.mjs +15 -3
  497. package/foundation/discovery/authoring-surface.d.mts +1 -1
  498. package/foundation/discovery/authoring-surface.mjs +2 -2
  499. package/foundation/discovery/authoring-surface.test.mjs +1 -1
  500. package/foundation/discovery/cli-self-docs.d.mts +2 -1
  501. package/foundation/discovery/cli-self-docs.mjs +22 -4
  502. package/foundation/discovery/cli-self-docs.test.mjs +3 -2
  503. package/foundation/discovery/component-discovery.d.mts +227 -10
  504. package/foundation/discovery/component-discovery.export-names.test.mjs +760 -0
  505. package/foundation/discovery/component-discovery.mjs +940 -57
  506. package/foundation/discovery/component-discovery.test.mjs +96 -0
  507. package/foundation/discovery/component-loader.d.mts +1 -1
  508. package/foundation/discovery/component-replacement.mjs +20 -1
  509. package/foundation/discovery/component-replacement.test.mjs +40 -0
  510. package/foundation/discovery/copied-passages.d.mts +216 -0
  511. package/foundation/discovery/copied-passages.mjs +720 -0
  512. package/foundation/discovery/copied-passages.test.mjs +124 -0
  513. package/foundation/discovery/doc-consistency.d.mts +34 -0
  514. package/foundation/discovery/doc-consistency.mjs +513 -0
  515. package/foundation/discovery/doc-consistency.test.mjs +347 -0
  516. package/foundation/discovery/doc-fluff.d.mts +112 -0
  517. package/foundation/discovery/doc-fluff.mjs +328 -0
  518. package/foundation/discovery/doc-fluff.test.mjs +142 -0
  519. package/foundation/discovery/doc-types.d.mts +157 -0
  520. package/foundation/discovery/doc-types.mjs +1231 -0
  521. package/foundation/discovery/doc-types.test.mjs +744 -0
  522. package/foundation/discovery/docs-discovery.d.mts +88 -0
  523. package/foundation/discovery/docs-discovery.mjs +97 -3
  524. package/foundation/discovery/integration-doc-files.d.mts +22 -0
  525. package/foundation/discovery/integration-doc-files.mjs +231 -0
  526. package/foundation/discovery/integration-doc-files.test.mjs +246 -0
  527. package/foundation/discovery/module-exports.d.mts +68 -0
  528. package/foundation/discovery/module-exports.mjs +609 -31
  529. package/foundation/discovery/module-exports.test.mjs +172 -0
  530. package/foundation/discovery/package-tsconfig.d.mts +14 -0
  531. package/foundation/discovery/package-tsconfig.mjs +228 -0
  532. package/foundation/discovery/package-tsconfig.test.mjs +210 -0
  533. package/foundation/discovery/project-typescript.d.mts +32 -0
  534. package/foundation/discovery/project-typescript.mjs +89 -0
  535. package/foundation/discovery/prop-drift.d.mts +297 -0
  536. package/foundation/discovery/prop-drift.mjs +2428 -0
  537. package/foundation/discovery/prop-drift.test.mjs +2337 -0
  538. package/foundation/discovery/runner-allowlist.d.mts +38 -0
  539. package/foundation/discovery/runner-allowlist.mjs +51 -0
  540. package/foundation/discovery/runner-commands.d.mts +77 -0
  541. package/foundation/discovery/runner-commands.mjs +294 -0
  542. package/foundation/discovery/runner-commands.test.mjs +128 -0
  543. package/foundation/discovery/stray-pointers.d.mts +52 -0
  544. package/foundation/discovery/stray-pointers.mjs +293 -0
  545. package/foundation/discovery/stray-pointers.test.mjs +86 -0
  546. package/foundation/discovery/template-adapter.mjs +92 -6
  547. package/foundation/discovery/template-needs.mjs +6 -46
  548. package/foundation/discovery/theme-discovery.mjs +147 -3
  549. package/foundation/discovery/theme-imports.mjs +8 -4
  550. package/foundation/discovery/theme-imports.test.mjs +1 -1
  551. package/foundation/discovery/type-match.d.mts +53 -0
  552. package/foundation/discovery/type-match.mjs +660 -0
  553. package/foundation/discovery/type-match.test.mjs +169 -0
  554. package/foundation/discovery/type-text.d.mts +68 -0
  555. package/foundation/discovery/type-text.mjs +658 -0
  556. package/foundation/discovery/type-text.test.mjs +196 -0
  557. package/foundation/discovery/unresolved-references.d.mts +62 -0
  558. package/foundation/discovery/unresolved-references.mjs +790 -0
  559. package/foundation/discovery/unresolved-references.test.mjs +567 -0
  560. package/foundation/doc-compiler/doc-loads.test.mjs +84 -10
  561. package/foundation/doc-compiler/inputs.mjs +27 -1
  562. package/foundation/doc-compiler/inputs.test.mjs +0 -1
  563. package/foundation/doc-compiler/links.d.mts +41 -5
  564. package/foundation/doc-compiler/links.mjs +167 -28
  565. package/foundation/doc-compiler/links.test.mjs +97 -4
  566. package/foundation/doc-compiler/read.d.mts +1 -1
  567. package/foundation/doc-compiler/read.mjs +59 -1
  568. package/foundation/doc-compiler/read.test.mjs +11 -2
  569. package/foundation/doc-compiler/split-topic-keywords.test.mjs +3 -2
  570. package/foundation/doc-compiler/tree.d.mts +32 -6
  571. package/foundation/doc-compiler/tree.mjs +107 -44
  572. package/foundation/doc-compiler/tree.test.mjs +14 -7
  573. package/foundation/env/cli-command.d.mts +83 -0
  574. package/foundation/env/cli-command.mjs +152 -0
  575. package/foundation/env/cli-command.test.mjs +129 -0
  576. package/foundation/env/node-version.test.mjs +15 -3
  577. package/foundation/env/package-manager.d.mts +93 -9
  578. package/foundation/env/package-manager.global.test.mjs +66 -0
  579. package/foundation/env/package-manager.mjs +184 -13
  580. package/foundation/env/package-manager.test.mjs +341 -15
  581. package/foundation/env/project-scope.d.mts +9 -0
  582. package/foundation/env/project-scope.mjs +33 -0
  583. package/foundation/env/search-path.d.mts +42 -0
  584. package/foundation/env/search-path.mjs +205 -0
  585. package/foundation/env/search-path.test.mjs +122 -0
  586. package/foundation/env/user-dirs.d.mts +39 -0
  587. package/foundation/env/user-dirs.mjs +93 -0
  588. package/foundation/env/user-dirs.test.mjs +72 -0
  589. package/foundation/env/user-settings.d.mts +46 -0
  590. package/foundation/env/user-settings.mjs +106 -0
  591. package/foundation/env/user-settings.test.mjs +64 -0
  592. package/foundation/fs/file-protection.mjs +15 -1
  593. package/foundation/fs/module-loader.d.mts +2 -1
  594. package/foundation/fs/module-loader.mjs +60 -4
  595. package/foundation/fs/module-loader.stdout.test.mjs +3 -2
  596. package/foundation/fs/module-loader.test.mjs +194 -0
  597. package/foundation/fs/path-compare.d.mts +33 -0
  598. package/foundation/fs/path-compare.mjs +73 -0
  599. package/foundation/fs/paths.d.mts +122 -4
  600. package/foundation/fs/paths.mjs +675 -29
  601. package/foundation/fs/paths.test.mjs +439 -54
  602. package/foundation/fs/read-record.d.mts +18 -0
  603. package/foundation/fs/read-record.mjs +131 -0
  604. package/foundation/fs/read-record.test.mjs +77 -0
  605. package/foundation/integrations/autolink.d.mts +2 -1
  606. package/foundation/integrations/autolink.mjs +4 -13
  607. package/foundation/integrations/cli-peer-version.d.mts +36 -0
  608. package/foundation/integrations/cli-peer-version.mjs +132 -0
  609. package/foundation/integrations/cli-peer-version.test.mjs +354 -0
  610. package/foundation/integrations/computer-integrations.d.mts +81 -0
  611. package/foundation/integrations/computer-integrations.mjs +345 -0
  612. package/foundation/integrations/computer-integrations.test.mjs +292 -0
  613. package/foundation/integrations/contribution-inventory.d.mts +26 -20
  614. package/foundation/integrations/contribution-inventory.mjs +97 -8
  615. package/foundation/integrations/exports-subpaths.d.mts +57 -0
  616. package/foundation/integrations/exports-subpaths.mjs +113 -0
  617. package/foundation/integrations/integration-warnings.mjs +3 -2
  618. package/foundation/integrations/integration-warnings.test.mjs +8 -9
  619. package/foundation/integrations/integrations.d.mts +51 -1
  620. package/foundation/integrations/integrations.mjs +106 -4
  621. package/foundation/integrations/issue.ts +6 -0
  622. package/foundation/integrations/public-imports.d.mts +118 -0
  623. package/foundation/integrations/public-imports.mjs +1769 -0
  624. package/foundation/integrations/public-imports.test.mjs +1793 -0
  625. package/foundation/integrations/validate-contributions.d.mts +117 -0
  626. package/foundation/integrations/validate-contributions.mjs +1209 -14
  627. package/foundation/release/agent-text-worker.d.mts +4 -0
  628. package/foundation/release/agent-text-worker.mjs +52 -0
  629. package/foundation/release/cache.d.mts +310 -0
  630. package/foundation/release/cache.mjs +1216 -0
  631. package/foundation/release/cache.test.mjs +923 -0
  632. package/foundation/release/choose.d.mts +207 -0
  633. package/foundation/release/choose.mjs +677 -0
  634. package/foundation/release/choose.test.mjs +427 -0
  635. package/foundation/release/core-worker.d.mts +4 -0
  636. package/foundation/release/core-worker.mjs +38 -0
  637. package/foundation/release/global-state.d.mts +263 -0
  638. package/foundation/release/global-state.mjs +474 -0
  639. package/foundation/release/global-state.test.mjs +381 -0
  640. package/foundation/release/handoff.d.mts +79 -0
  641. package/foundation/release/handoff.e2e.test.mjs +278 -0
  642. package/foundation/release/handoff.mjs +524 -0
  643. package/foundation/release/lock-lease.d.mts +23 -0
  644. package/foundation/release/lock-lease.mjs +80 -0
  645. package/foundation/release/notices.d.mts +307 -0
  646. package/foundation/release/notices.mjs +707 -0
  647. package/foundation/release/notices.test.mjs +586 -0
  648. package/foundation/release/npm-guard.d.mts +4 -0
  649. package/foundation/release/npm-guard.mjs +126 -0
  650. package/foundation/release/project.d.mts +141 -0
  651. package/foundation/release/project.mjs +466 -0
  652. package/foundation/release/project.test.mjs +288 -0
  653. package/foundation/release/refresh-worker.d.mts +4 -0
  654. package/foundation/release/refresh-worker.mjs +27 -0
  655. package/foundation/release/run-context.d.mts +47 -0
  656. package/foundation/release/run-context.mjs +163 -0
  657. package/foundation/release/update-notice-env.d.mts +28 -0
  658. package/foundation/release/update-notice-env.mjs +39 -0
  659. package/foundation/response/base.d.ts +26 -3
  660. package/foundation/response/error-codes.d.mts +3 -1
  661. package/foundation/response/error-codes.doc.mjs +12 -0
  662. package/foundation/response/error-codes.mjs +17 -0
  663. package/foundation/response/error-codes.test.mjs +2 -0
  664. package/foundation/response/json-contract.test.mjs +7 -2
  665. package/foundation/response/json.mjs +4 -1
  666. package/foundation/response/response-types.doc.mjs +22 -11
  667. package/foundation/response/response-types.doc.test.mjs +46 -0
  668. package/foundation/response/response.doc.mjs +3 -3
  669. package/foundation/route/route.d.mts +285 -0
  670. package/foundation/route/route.mjs +324 -0
  671. package/foundation/route/route.test.mjs +153 -0
  672. package/foundation/runtime/hosted-runtime.test.mjs +403 -0
  673. package/foundation/runtime/locked-versions.d.mts +32 -0
  674. package/foundation/runtime/locked-versions.mjs +65 -0
  675. package/foundation/runtime/package-root.d.mts +91 -0
  676. package/foundation/runtime/package-root.mjs +174 -0
  677. package/foundation/runtime/package-set.d.mts +62 -0
  678. package/foundation/runtime/package-set.mjs +130 -0
  679. package/foundation/runtime/package-set.test.mjs +432 -0
  680. package/foundation/text/string-utils.d.mts +2 -1
  681. package/foundation/text/string-utils.mjs +16 -5
  682. package/foundation/text/suggest-order.d.mts +72 -0
  683. package/foundation/text/suggest-order.mjs +363 -0
  684. package/foundation/text/suggest-order.test.mjs +259 -0
  685. package/foundation/xle/browser-imports.test.mjs +74 -0
  686. package/foundation/xle/registry.mjs +4 -0
  687. package/foundation/xle/registry.test.mjs +28 -0
  688. package/host/door-conformance.test.mjs +274 -0
  689. package/host/index.d.ts +116 -0
  690. package/host/index.mjs +295 -0
  691. package/host/index.test.mjs +302 -0
  692. package/package.json +16 -11
  693. package/scripts/postinstall.mjs +24 -5
  694. package/assets/docs/tree/integrations.doc.mjs +0 -40
@@ -3,1761 +3,42 @@
3
3
  /**
4
4
  * @file Programmatic API for the unified `search` command.
5
5
  *
6
- * Returns the same typed envelope { type, data } that `xds --json search`
6
+ * Returns the same typed envelope { type, data } that `astryx --json search`
7
7
  * outputs. The CLI command handler is a thin wrapper around this function.
8
8
  *
9
- * `search(query)` is the single "I'm looking for X" entry point across ALL
10
- * content domains — components, hooks, docs topics, templates (page + block),
11
- * and themes. Finding the right thing otherwise takes separate list calls
12
- * (`component --list`, `hook --list`, `docs`, `template --list`, `theme list`)
13
- * plus manual scanning; this collapses them into one ranked, typed result set.
14
- *
15
- * Scoring is keyword + fuzzy ranking (NOT semantic / embeddings — that is a
16
- * deliberate future follow-up). It reuses the same signal weighting as the
17
- * component fuzzy resolver in lib/string-utils.mjs:
18
- *
19
- * 100 exact name match
20
- * 95 name is the term's plural or stem form ("buttons" -> Button)
21
- * 90 exact keyword match
22
- * 88 keyword is the term's plural or stem form
23
- * 80 name Levenshtein distance 1 (one-word lookups, words of 5+ letters)
24
- * 70 keyword word prefix / distance 1 (distance: one-word lookups, 5+ letters)
25
- * 60 name word prefix (>=4 chars, >=50% coverage)
26
- * 60 exact weak-keyword match
27
- * 50 description / prose mentions the term
28
- * 45 usage guidance mentions the term
29
- * 40 name Levenshtein distance 2 (one-word lookups, 8+ letters)
30
- * 40 weak-keyword word prefix
31
- * 30 keyword Levenshtein distance 2 (one-word lookups, 8+ letters)
32
- * 20 name Levenshtein distance 3 (one-word lookups, 11+ letters)
33
- *
34
- * Name + keyword signals always outweigh description/prose, so an exact match
35
- * sorts above an incidental mention.
36
- *
37
- * A term matches inside a name or keyword only at the start of one of its
38
- * words: "dash" finds "dashboard" and "input" finds "TextInput", but "file"
39
- * does not find "profile". Edit distance is typo tolerance, so it applies only
40
- * to a one-word lookup, where a typo is the likely explanation, and only to
41
- * words long enough that one edit rarely makes another real word. In a
42
- * sentence, a near miss is usually a different word: "site" is not "side",
43
- * "cable" is not "table".
44
- *
45
- * A multi-word query has a reserved top tier (see {@link scoreQuery}): the
46
- * whole query as a candidate's name or keyword (190-200), then the whole query
47
- * as a phrase inside a doc's title or one of its headings (170), then a whole
48
- * title of two words or more inside the query (160-169), then a candidate that
49
- * matches every word of the query, at least one of them by name or keyword
50
- * (151-159). Below those sits everything else: a partial match, or every word
51
- * matched only in prose or through the components a page renders. A section titled "Light/Dark Mode" answers `dark
52
- * mode` better than any doc that merely names `mode` in code, however exactly;
53
- * "Dark mode" answers `how do I add dark mode`; and a guide whose title and
54
- * description hold both words of `troubleshoot integration` answers it better
55
- * than a doc named `integration`.
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
- *
64
- * Description and guidance are separate tiers on purpose. A component's own
65
- * one-line description saying "notification" is a claim about what it IS; the
66
- * same word inside another component's best-practice advice is a passing
67
- * mention. Scored equally, `Toast` — "a brief, non-blocking notification" —
68
- * ties with `Card`, `Dialog` and `Item`, which merely mention notifications in
69
- * their guidance, and ties break alphabetically, so Toast falls off the end of
70
- * its own best query.
71
- *
72
- * `keywords` carry AUTHORED intent — a block's `componentsUsed`, a page's
73
- * `category` words. `weakKeywords` are DERIVED: the components a page template
74
- * happens to render, scraped out of its JSX. Derived signal is deliberately
75
- * capped below the confident-match gate on its own, because breadth is not
76
- * relevance. At full keyword strength every rendered component is an
77
- * independent 90-point shot with no penalty for how many a template has, so
78
- * the broadest pages (a theme showcase rendering one of everything) win
79
- * queries they have nothing to do with.
9
+ * `search(query)` is the single "I'm looking for X" entry point across all
10
+ * content domains: components, hooks, docs topics, templates (page and
11
+ * block), and themes. The adapter gathers every candidate (_adapter.mjs),
12
+ * and search's tree (tree.mjs) picks the searcher that answers.
13
+ * `searchCore(query)` is the lexical ranker alone (_lexical.mjs); `build`
14
+ * reads it, so build's output does not move when search's tree does.
80
15
  */
81
16
 
82
17
  import {withListingCache} from '../../foundation/fs/listing-cache.mjs';
83
- import {readDocView} from '../../foundation/doc-compiler/read.mjs';
84
- import {findCoreDir} from '../../foundation/fs/paths.mjs';
85
18
  import {
86
- discoverComponents,
87
- discoverValidIntegrationComponents,
88
- findComponentReadme,
89
- resolveImportPath,
90
- resolveIntegrationImportPath,
91
- CORE_PACKAGE,
92
- } from '../../foundation/discovery/component-discovery.mjs';
93
- import {
94
- discoverHooks,
95
- findHookDoc,
96
- } from '../../foundation/discovery/hook-discovery.mjs';
97
- import {
98
- loadComponentReplacements,
99
- loadIntegrationsSafely,
100
- } from '../component/_adapter.mjs';
101
- import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';
102
- import {discoverTemplates, extractComponents} from '../template/template.mjs';
103
- import {templateLookupIds} from '../../foundation/discovery/template-adapter.mjs';
104
- import {listAvailableThemes} from '../theme/_adapter.mjs';
105
- import {
106
- guideEntry,
107
- loadDocsCatalog,
108
- lowerTopic,
109
- projectTree,
110
- holdsOwnName,
111
- } from '../docs/_adapter.mjs';
112
- import {unlinkText} from '../../foundation/doc-compiler/links.mjs';
113
- import {nodeView} from '../docs/node/node.mjs';
114
- import {
115
- sectionKey,
116
- sectionSummary,
117
- } from '../../foundation/discovery/docs-section-key.mjs';
118
- import {AstryxError} from '../error.mjs';
119
- import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
120
- import {setResultCoverage} from './coverage.mjs';
121
-
122
- /**
123
- * A search candidate gathered from one content domain. Extra underscore-
124
- * prefixed fields carry domain-specific payload used only by {@link toResult}.
125
- * @typedef {object} Candidate
126
- * @property {'component'|'hook'|'doc'|'template'|'theme'} domain
127
- * @property {string} name
128
- * @property {string[]} [aliases] - Other names the candidate answers to, scored
129
- * with the same name signals: a theme's display name.
130
- * @property {string[]} [keywords]
131
- * @property {string[]} [weakKeywords]
132
- * @property {string} [description]
133
- * @property {string[]} [prose]
134
- * @property {string[]} [guidance]
135
- * @property {string[]} [titles] - A doc's title and the headings inside it:
136
- * the lines a reader scans to pick it. The whole query standing in one of
137
- * them, or one of them standing whole in the query, is a top-tier match.
138
- * @property {string} [_import]
139
- * @property {string} [_title]
140
- * @property {string} [_topic] - A doc result's topic or docs-tree route.
141
- * @property {string} [_section] - A doc result's section key, when it is one section.
142
- * @property {string} [_command] - The command that reads exactly this doc part.
143
- * @property {string} [_parent] - The command that opens the level above a doc
144
- * part: its topic's section list, or the docs-tree namespace it sits in.
145
- * @property {string} [_package] - The npm package that owns the candidate:
146
- * Core's package for its components, hooks, and templates, the integration's
147
- * for what it contributed, and for a doc part the package that wrote it.
148
- * @property {string} [_displayName]
149
- * @property {'page'|'block'} [_kind]
150
- * @property {string} [_resultName]
151
- * @property {string} [_commandName]
152
- */
153
-
154
- /**
155
- * Synonym / intent map: product-language terms an agent is likely to type,
156
- * expanded to the catalog's vocabulary so oblique queries still rank. Keys and
157
- * values are matched bidirectionally (typing any value also pulls in the key
158
- * and its siblings). Lowercase, single words or short phrases. Exported for
159
- * `build`, whose page ranker expands a query with the same vocabulary.
160
- */
161
- export const SYNONYMS = {
162
- dashboard: [
163
- 'overview',
164
- 'analytics',
165
- 'kpi',
166
- 'kpis',
167
- 'metrics',
168
- 'stats',
169
- 'reporting',
170
- 'insights',
171
- 'control',
172
- ],
173
- login: ['signin', 'auth', 'authentication', 'sso', 'credentials', 'account'],
174
- signup: ['register', 'registration', 'onboarding'],
175
- payment: ['checkout', 'billing', 'card', 'pay', 'purchase', 'order'],
176
- pricing: ['plans', 'plan', 'tiers', 'tier', 'subscription', 'subscriptions'],
177
- chat: ['messaging', 'message', 'messages', 'conversation', 'inbox', 'dm'],
178
- settings: ['preferences', 'config', 'configuration', 'account'],
179
- calendar: ['schedule', 'scheduling', 'events', 'event', 'month', 'agenda'],
180
- table: ['list', 'rows', 'records', 'grid', 'spreadsheet', 'datatable'],
181
- gallery: ['photos', 'photo', 'images', 'image', 'pictures'],
182
- hero: ['banner', 'splash', 'headline', 'landing'],
183
- form: ['fields', 'input', 'inputs', 'survey'],
184
- profile: ['bio', 'avatar', 'user'],
185
- documentation: ['docs', 'reference', 'guide', 'api'],
186
- navigation: ['nav', 'menu', 'sidebar'],
187
- };
188
-
189
- // Flatten into a token -> Set(expansions) lookup (bidirectional).
190
- const SYNONYM_INDEX = (() => {
191
- /** @type {Map<string, Set<string>>} */
192
- const idx = new Map();
193
- /**
194
- * @param {string} a
195
- * @param {string} b
196
- */
197
- const add = (a, b) => {
198
- let set = idx.get(a);
199
- if (!set) {
200
- set = new Set();
201
- idx.set(a, set);
202
- }
203
- set.add(b);
204
- };
205
- for (const [key, vals] of Object.entries(SYNONYMS)) {
206
- for (const v of vals) {
207
- add(key, v);
208
- add(v, key);
209
- for (const v2 of vals) if (v2 !== v) add(v, v2);
210
- }
211
- }
212
- return idx;
213
- })();
214
-
215
- /**
216
- * Light stemmer: strips common English suffixes so "charts"/"charting" and
217
- * "chart" share a root. Deliberately crude (no Porter) — good enough to bridge
218
- * plural/gerund gaps without a dependency.
219
- * @param {string} w
220
- * @returns {string}
221
- */
222
- export function stem(w) {
223
- let s = w;
224
- for (const suf of ['ing', 'ed', 'ies', 'es', 's']) {
225
- if (s.length > suf.length + 2 && s.endsWith(suf)) {
226
- s = suf === 'ies' ? s.slice(0, -3) + 'y' : s.slice(0, -suf.length);
227
- break;
228
- }
229
- }
230
- return s;
231
- }
232
-
233
- /**
234
- * The forms of a word that count as the same word: itself, its stem, and its
235
- * singular when it ends in a plural suffix — so "tables" is "table",
236
- * "statuses" is "status", and "filtering" is "filter".
237
- * @param {string} w - Lowercase word.
238
- * @returns {Set<string>}
239
- */
240
- function wordForms(w) {
241
- const forms = new Set([w, stem(w)]);
242
- if (w.length > 3 && w.endsWith('s')) forms.add(w.slice(0, -1));
243
- if (w.length > 4 && w.endsWith('es')) forms.add(w.slice(0, -2));
244
- if (w.length > 4 && w.endsWith('ies')) forms.add(w.slice(0, -3) + 'y');
245
- return forms;
246
- }
247
-
248
- /**
249
- * Whether two lowercase words are the same word, up to plural and stem form.
250
- * @param {string} a
251
- * @param {string} b
252
- * @returns {boolean}
253
- */
254
- export function sameWord(a, b) {
255
- if (a === b) return true;
256
- const forms = wordForms(a);
257
- for (const f of wordForms(b)) if (forms.has(f)) return true;
258
- return false;
259
- }
260
-
261
- /**
262
- * The lowercase words of a name or keyword: split at non-alphanumerics and at
263
- * camelCase boundaries, so "TextInput" is ["text", "input"] and
264
- * "Dashboard - Analytics" is ["dashboard", "analytics"].
265
- * @param {string} text
266
- * @returns {string[]}
267
- */
268
- function wordsOf(text) {
269
- return String(text)
270
- .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
271
- .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
272
- .toLowerCase()
273
- .split(/[^a-z0-9]+/)
274
- .filter(Boolean);
275
- }
276
-
277
- /**
278
- * Whether a term is found inside a name or keyword: it is one of its words, or
279
- * the start of one (a truncation), and covers at least half of the whole
280
- * string. Four letters minimum, so a short term never matches by accident.
281
- * @param {string} term - Lowercase term.
282
- * @param {string} text - The name or keyword as authored.
283
- * @returns {boolean}
284
- */
285
- function startsAWordOf(term, text) {
286
- if (term.length < 4) return false;
287
- if (term.length / String(text).length < 0.5) return false;
288
- return wordsOf(text).some(w => w.startsWith(term) || sameWord(term, w));
289
- }
290
-
291
- /**
292
- * The fewest letters both words need before an edit distance counts as a
293
- * typo, by distance. Below them, one edit usually makes a different word.
294
- */
295
- const TYPO_MIN_LENGTH = {1: 5, 2: 8, 3: 11};
296
-
297
- /**
298
- * @param {string} a
299
- * @param {string} b
300
- * @param {number} dist
301
- */
302
- const isTypo = (a, b, dist) =>
303
- dist > 0 &&
304
- dist <= 3 &&
305
- Math.min(a.length, b.length) >=
306
- TYPO_MIN_LENGTH[/** @type {1 | 2 | 3} */ (dist)];
307
-
308
- /** Valid domain filters for `--type`. */
309
- export const SEARCH_DOMAINS = ['component', 'hook', 'doc', 'template', 'theme'];
310
-
311
- /**
312
- * The domains a search reads without @astryxdesign/core. An open search outside
313
- * an app covers these alone.
314
- */
315
- const CORELESS_DOMAINS = ['doc', 'theme'];
316
-
317
- /**
318
- * Filler words stripped from multi-word queries so natural-language phrasing
319
- * ("a page where you can see business stats") ranks on its content words.
320
- * Exported for `build`, whose page ranker strips the same words.
321
- */
322
- export const STOPWORDS = new Set([
323
- 'a',
324
- 'an',
325
- 'the',
326
- 'of',
327
- 'for',
328
- 'to',
329
- 'with',
330
- 'and',
331
- 'or',
332
- 'in',
333
- 'on',
334
- 'at',
335
- 'by',
336
- 'that',
337
- 'this',
338
- 'my',
339
- 'your',
340
- 'our',
341
- 'their',
342
- 'is',
343
- 'are',
344
- 'be',
345
- 'it',
346
- 'its',
347
- 'as',
348
- 'from',
349
- 'page',
350
- 'screen',
351
- 'app',
352
- 'application',
353
- 'view',
354
- 'where',
355
- 'you',
356
- 'can',
357
- 'some',
358
- 'like',
359
- 'just',
360
- 'basically',
361
- 'kinda',
362
- 'want',
363
- 'wants',
364
- 'need',
365
- 'needs',
366
- 'something',
367
- 'thing',
368
- 'things',
369
- 'build',
370
- 'make',
371
- 'create',
372
- 'i',
373
- 'me',
374
- 'we',
375
- 'us',
376
- 'so',
377
- 'up',
378
- 'out',
379
- 'over',
380
- 'side',
381
- 'one',
382
- 'big',
383
- ]);
384
-
385
- /**
386
- * Split a query into meaningful content tokens (lowercased, stopwords + very
387
- * short words removed). Empty for single-word queries (callers fall back to
388
- * whole-phrase scoring).
389
- * @param {string} term - Already-lowercased query.
390
- * @returns {string[]}
391
- */
392
- export function tokenizeQuery(term) {
393
- return (
394
- term
395
- .split(/\s+/)
396
- // Strip only leading/trailing punctuation; keep joined identifiers intact
397
- // (e.g. "foo_bar" stays one token) so gibberish stays gibberish.
398
- .map(t => t.replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, ''))
399
- .filter(t => t.length >= 2 && !STOPWORDS.has(t))
400
- );
401
- }
402
-
403
- /**
404
- * Score a candidate against a query, handling multi-word natural language.
405
- * Tries the whole phrase (so exact/near matches still win) AND a per-token
406
- * pass (so "data table with filters" matches `table-page` via table+filter),
407
- * and returns whichever is stronger.
408
- *
409
- * @param {string} term - Lowercased full query.
410
- * @param {string[]} tokens - Content tokens from tokenizeQuery(term).
411
- * @param {object} candidate
412
- * @returns {{score: number, reason: string} | null}
413
- */
414
- /**
415
- * Minimum per-token score (in the multi-word pass) to count as a real match.
416
- * 50 = a genuine name/keyword/description hit; below that is loose Levenshtein
417
- * fuzz that would otherwise turn gibberish queries into noise.
418
- *
419
- * Guidance (45) is deliberately BELOW this floor, so it never counts as one of
420
- * the matched concepts in a multi-word query. Measured: letting it count moved
421
- * `nested menu` from SideNav to List and `explain why a field is required` from
422
- * Field to TextInput — in both cases a component whose guidance happens to
423
- * mention the other word displaced the one that IS the answer. Breadth is not
424
- * relevance, the same reason `weakKeywords` are capped. Guidance still decides
425
- * single-word queries and still breaks ties, which is where it earns its place.
426
- */
427
- const MIN_TOKEN_SCORE = 50;
428
-
429
- /**
430
- * Best score for a token against a candidate, fanning out through synonyms
431
- * (synonym hits are discounted so a direct hit always wins).
432
- * @param {string} tok
433
- * @param {Candidate} candidate
434
- * @param {{fuzzy?: boolean}} [opts]
435
- * @returns {{score: number, reason: string} | null}
436
- */
437
- function bestForToken(tok, candidate, opts = {}) {
438
- let best = scoreCandidate(tok, candidate, opts);
439
- const syns = SYNONYM_INDEX.get(tok);
440
- if (syns) {
441
- for (const s of syns) {
442
- const h = scoreCandidate(s, candidate, opts);
443
- if (h) {
444
- const score = Math.round(h.score * 0.85);
445
- if (!best || score > best.score)
446
- best = {score, reason: `${h.reason} (~${tok})`};
447
- }
448
- }
449
- }
450
- return best;
451
- }
452
-
453
- /**
454
- * The score of a whole-query phrase inside a doc's title or heading: a keyword
455
- * substring hit (70) promoted by the same 100 as the exact tier. Below an
456
- * exact name or keyword (190-200), above the token-sum path (~151 at most).
457
- */
458
- const TITLE_PHRASE_SCORE = 170;
459
-
460
- /**
461
- * The score of a whole title inside a longer query, before its coverage bonus:
462
- * one step below {@link TITLE_PHRASE_SCORE}. The bonus (one per query term the
463
- * candidate matches, at most 9) orders the sections that share a common title,
464
- * so "best practices for spacing" puts Spacing's Best Practices first.
465
- */
466
- const TITLE_IN_QUERY_SCORE = 160;
467
-
468
- /**
469
- * The score of a candidate that matches every content word of a multi-word
470
- * query, before a bonus of up to 8 for how strong its strongest match is: just
471
- * above anything that matches only some of the words. The token-sum path tops
472
- * out near 150 for a partial match (a 100 on one word, the per-word bonus, and
473
- * the coverage term), so an AND-match with one keyword-strength hit (see
474
- * {@link STRONG_TOKEN_SCORE}) always outranks an OR-match, and stays below the
475
- * title tiers.
476
- */
477
- const FULL_COVERAGE_SCORE = 151;
478
-
479
- /**
480
- * The strongest single-word hit an every-word match needs to take that tier: a
481
- * keyword substring. Two passing mentions in prose, or the components a page
482
- * happens to render, are breadth, not relevance; they stay on the token sum,
483
- * below an exact name or keyword hit on one of the words.
484
- */
485
- const STRONG_TOKEN_SCORE = 70;
486
-
487
- /**
488
- * A match's domain priority: 0 (none), 1, or 2 (a doc the whole query names).
489
- * A component, hook, template, or theme with priority ranks ahead of any doc
490
- * without it, whatever the two scores are. Docs among themselves rank by
491
- * priority, then score; everything else ranks among itself by score.
492
- *
493
- * A component, hook, template, or theme has priority (1) when one of the
494
- * query's words, or the whole query, hits its name or an authored keyword at
495
- * {@link STRONG_TOKEN_SCORE} or above, or when it matches every word.
496
- *
497
- * A doc has priority when the reader asked for that doc:
498
- * - 2: the whole query is the topic's name, its last route segment, or its
499
- * own title, as words and whatever the plural (`font setup` is
500
- * typography/font-setup, `side panel` is "Side panels");
501
- * - 1: a word of the query is the topic's name (`illustration` in a longer
502
- * question is the illustrations guide);
503
- * - 1: the query holds one of the doc's titles whole (`resizable side panels`
504
- * names "Side panels"; `light dark mode button` names "Light/Dark Mode");
505
- * - 1: the doc matches every word of the query and one of them is a word of
506
- * its title (`switch to a dark theme` and "Use a theme").
507
- * A section answers to its topic's name.
508
- *
509
- * A doc that matched only by keyword, by a heading holding the query, or by
510
- * words spread through its text has no priority. Docs are split into many
511
- * small topics, and each declares its own keywords and headings, so a common
512
- * phrase such as `font size` hits a guide's keyword or heading exactly
513
- * (170-190) while the component the reader is after matches one word by
514
- * keyword (`Text`, 98). Ranked on text alone, every split adds another doc
515
- * above the component. Broad reference pages match every word of many queries
516
- * in their text the same way. The score stays the text-match strength the
517
- * result reports, so callers that gate on it (`build`) see the same numbers.
518
- *
519
- * @param {string} term - Lowercased search term.
520
- * @param {string[]} tokens - Content tokens from tokenizeQuery(term).
521
- * @param {Candidate} candidate
522
- * @param {{score: number, matched: number, total: number}} hit - The
523
- * candidate's scoreQuery result.
524
- * @returns {0 | 1 | 2}
525
- */
526
- export function domainPriority(term, tokens, candidate, hit) {
527
- const words = [term, ...tokens];
528
- if (candidate.domain === 'doc') {
529
- const topic = String(candidate._topic ?? candidate.name).toLowerCase();
530
- // The whole query, read as words, is the topic's route, its last
531
- // segment, or its own title, whatever the plural: `side panel` is
532
- // layout/side-panels, and `header and footer` is "Headers and footers".
533
- // A section's title is a heading inside a topic, not the topic's name.
534
- const named = [topic, topic.slice(topic.lastIndexOf('/') + 1)];
535
- if (candidate._section == null && candidate.titles?.[0]) {
536
- named.push(candidate.titles[0]);
537
- }
538
- if (named.some(n => samePhrase(term, n))) {
539
- return 2;
540
- }
541
- if (
542
- words.some(
543
- w =>
544
- (scoreCandidate(w, {name: topic}, {fuzzy: false})?.score ?? 0) >= 95,
545
- )
546
- ) {
547
- return 1;
548
- }
549
- // A whole title inside the query is the only path to 160-169.
550
- if (hit.score >= TITLE_IN_QUERY_SCORE && hit.score < TITLE_PHRASE_SCORE) {
551
- return 1;
552
- }
553
- // Every word matched, and one of them names the doc in its title.
554
- if (
555
- hit.score >= FULL_COVERAGE_SCORE &&
556
- hit.score < TITLE_IN_QUERY_SCORE &&
557
- hit.matched === hit.total
558
- ) {
559
- const titleWords = phraseWords(candidate.titles?.[0] ?? '');
560
- if (
561
- (tokens.length ? tokens : [term]).some(t =>
562
- titleWords.some(w => samePhraseWord(t, w) || sameWord(t, w)),
563
- )
564
- ) {
565
- return 1;
566
- }
567
- }
568
- return 0;
569
- }
570
- if (hit.score >= FULL_COVERAGE_SCORE) return 1;
571
- const fuzzy = tokens.length <= 1;
572
- return words.some(
573
- w =>
574
- (bestForToken(w, candidate, {fuzzy})?.score ?? 0) >= STRONG_TOKEN_SCORE,
575
- )
576
- ? 1
577
- : 0;
578
- }
579
-
580
- /**
581
- * The words of a title or query, lowercased, without punctuation or code ticks.
582
- * @param {string} text
583
- * @returns {string[]}
584
- */
585
- function phraseWords(text) {
586
- return (
587
- unlinkText(text)
588
- .toLowerCase()
589
- .match(/[a-z0-9]+/g) ?? []
590
- );
591
- }
592
-
593
- /**
594
- * Whether two words are the same word, allowing a plural on either side, so
595
- * `data attributes selector` still reads "Data attribute selectors".
596
- * @param {string} a
597
- * @param {string} b
598
- */
599
- function samePhraseWord(a, b) {
600
- return (
601
- a === b ||
602
- `${a}s` === b ||
603
- `${b}s` === a ||
604
- `${a}es` === b ||
605
- `${b}es` === a
606
- );
607
- }
608
-
609
- /**
610
- * Whether two phrases are the same words, in order, ignoring case,
611
- * punctuation, and a plural on any word: `side panel` is "Side panels", and
612
- * `headers and footers` is `header-and-footer`.
613
- * @param {string} a
614
- * @param {string} b
615
- * @returns {boolean}
616
- */
617
- function samePhrase(a, b) {
618
- const x = phraseWords(a);
619
- const y = phraseWords(b);
620
- return (
621
- x.length > 0 &&
622
- x.length === y.length &&
623
- x.every((w, k) => samePhraseWord(w, y[k]) || sameWord(w, y[k]))
624
- );
625
- }
626
-
627
- /**
628
- * Whether `plural` is the plural of `word`: `integrations` of `integration`,
629
- * `boxes` of `box`. `es` only follows s, x, z, ch, or sh, so `notes` is not a
630
- * plural of `not`.
631
- * @param {string} plural
632
- * @param {string} word
633
- */
634
- function pluralOf(plural, word) {
635
- if (word.length < 3) return false;
636
- if (plural === `${word}s`) return true;
637
- return /(?:s|x|z|ch|sh)$/.test(word) && plural === `${word}es`;
638
- }
639
-
640
- /**
641
- * The first title or heading that holds every word of the query, in order and
642
- * side by side, or null.
643
- * @param {string} term - Lowercased full query.
644
- * @param {string[] | undefined} titles
645
- * @returns {string | null}
646
- */
647
- export function headingWithPhrase(term, titles) {
648
- const query = phraseWords(term);
649
- if (query.length < 2 || !titles) return null;
650
- for (const title of titles) {
651
- const words = phraseWords(String(title ?? ''));
652
- for (let i = 0; i + query.length <= words.length; i++) {
653
- if (query.every((word, j) => samePhraseWord(words[i + j], word)))
654
- return title;
655
- }
656
- }
657
- return null;
658
- }
659
-
660
- /**
661
- * The first title or heading of two words or more that the query holds whole,
662
- * in order and side by side, or null. A question such as "how do I add dark
663
- * mode" names the "Dark mode" section outright, around words no title has.
664
- * @param {string} term - Lowercased full query.
665
- * @param {string[] | undefined} titles
666
- * @returns {string | null}
667
- */
668
- export function titleInQuery(term, titles) {
669
- const query = phraseWords(term);
670
- if (!titles) return null;
671
- for (const title of titles) {
672
- const words = phraseWords(String(title ?? ''));
673
- if (words.length < 2 || words.length > query.length) continue;
674
- for (let i = 0; i + words.length <= query.length; i++) {
675
- if (words.every((word, j) => samePhraseWord(query[i + j], word)))
676
- return title;
677
- }
678
- }
679
- return null;
680
- }
681
-
682
- /**
683
- * @param {string} term - Lowercased full query.
684
- * @param {string[]} tokens - Content tokens from tokenizeQuery(term).
685
- * @param {Candidate} candidate
686
- * @returns {{score: number, reason: string, matched: number, total: number} | null}
687
- * `matched`/`total` are the query concepts this candidate answered, out of
688
- * the concepts the query had. Callers that must distinguish "matched one word
689
- * of three" from "matched all three" — `build`, which gates its pages group
690
- * on coverage — cannot recover that from the score, because a single strong
691
- * hit and a broad weak one land on the same number.
692
- */
693
- export function scoreQuery(term, tokens, candidate) {
694
- const total = Math.max(tokens.length, 1);
695
- // A whole-phrase hit answered the whole query by definition.
696
- const asFull = (/** @type {{score: number, reason: string}} */ hit) => ({
697
- ...hit,
698
- matched: total,
699
- total,
700
- });
701
- // Typo tolerance is for one-word lookups. In a multi-word query a near miss
702
- // is usually a different word, not a typo.
703
- const fuzzy = tokens.length <= 1;
704
- const full = scoreCandidate(term, candidate, {fuzzy});
705
- // A query of several words keeps its phrase tiers below even when stopwords
706
- // leave one content word: "make an integration" is still the phrase an
707
- // author declares as a keyword, and "build an integration" still names a
708
- // title outright, though each tokenizes to `integration` alone.
709
- const phrase = phraseWords(term).length >= 2;
710
-
711
- /** 0–1 content tokens: whole-phrase fuzzy matching (typo tolerance for
712
- * single words), but if stopwords left exactly one DIFFERENT token (e.g.
713
- * "pricing page" → "pricing"), score that token too and take the stronger. */
714
- const fewTokens = () => {
715
- const single =
716
- tokens.length === 1 ? bestForToken(tokens[0], candidate, {fuzzy}) : null;
717
- if (full && (!single || full.score >= single.score)) return asFull(full);
718
- return single ? asFull(single) : null;
719
- };
720
- if (tokens.length <= 1 && !phrase) return fewTokens();
721
-
722
- // The full (untokenized) query matching a candidate's name or a declared
723
- // keyword VERBATIM — full.score 90 or 100, the only two scoreCandidate
724
- // outcomes at or above that mark — is a deliberate, explicit label the
725
- // author chose for exactly this multi-word concept. Promote it to a
726
- // reserved top tier, safely above the token-sum path's ceiling below
727
- // (~151: 100 avg + 36 bonus + 15 coverage), so it always outranks a
728
- // candidate that merely happens to contain several of the query's
729
- // individual words. Without this, "table of contents" never surfaces
730
- // Outline (which declares that exact phrase as a keyword) because dozens
731
- // of Table-related templates each match "table" and "contents" separately
732
- // and accumulate a higher raw score (#5239).
733
- if (full && full.score >= 90) {
734
- return asFull({score: full.score + 100, reason: full.reason});
735
- }
736
-
737
- // The whole query standing as a phrase in a doc's title or one of its
738
- // headings is the next tier down, and still above the token-sum path. The
739
- // reader named what the section is about, in order: `dark mode` is the
740
- // "Light/Dark Mode" section. Without this, the title scores a keyword
741
- // substring (70) and loses to a doc that happens to name `mode` exactly in
742
- // a code tick (90 on one token, 98 with coverage), so API enum docs outrank
743
- // the guide section.
744
- const heading = headingWithPhrase(term, candidate.titles);
745
- if (heading != null) {
746
- return asFull({
747
- score: TITLE_PHRASE_SCORE,
748
- reason: `title "${heading}" holds the whole query`,
749
- });
750
- }
751
- if (tokens.length <= 1) return fewTokens();
752
-
753
- // Multi-word natural language: score each content token, counting only
754
- // strong hits, then reward coverage so candidates matching more terms win.
755
- let strongest = 0;
756
- let matched = 0;
757
- let tokenSum = 0;
758
- /** @type {string[]} */
759
- const hitTerms = [];
760
- for (const tok of tokens) {
761
- const h = bestForToken(tok, candidate, {fuzzy});
762
- if (h && h.score >= MIN_TOKEN_SCORE) {
763
- if (h.score > strongest) strongest = h.score;
764
- matched++;
765
- hitTerms.push(tok);
766
- tokenSum += h.score;
767
- }
768
- }
769
- // The reverse of the title tier, a step lower: the query holds a whole title
770
- // of two words or more, so the reader asked a question around the section's
771
- // name ("how do I add dark mode"). Coverage breaks ties between sections
772
- // that share a title such as "Best Practices".
773
- const named = titleInQuery(term, candidate.titles);
774
- if (named != null) {
775
- return {
776
- score: TITLE_IN_QUERY_SCORE + Math.min(matched, 9),
777
- reason: `the query names the title "${named}"`,
778
- matched,
779
- total,
780
- };
781
- }
782
- if (matched === 0) return full ? asFull(full) : null;
783
-
784
- const reason = `matches ${matched}/${tokens.length} terms: ${hitTerms.join(', ')}`;
785
-
786
- // Every word matched is its own tier. Summed per word, a doc that matches
787
- // both words of `troubleshoot integration` in its title and description
788
- // (50 + bonus + coverage = 77) lost to thirty docs that each match
789
- // `integration` alone, by name or in a code tick (98-108). The reader asked for
790
- // both; a candidate that has both comes first, ordered among its peers by
791
- // how strong its matches are. It needs one keyword-strength hit:
792
- // every word mentioned in prose, or rendered by a page, is breadth, and
793
- // stays on the token sum below an exact hit on one word.
794
- //
795
- // The TOTAL quality of matches orders candidates within this tier, not
796
- // just the strongest single hit. A doc matching both words by keyword
797
- // (90 + 90 = 180) outranks one matching keyword + prose (90 + 50 = 140).
798
- // Before this, every all-word match whose strongest hit was a keyword (90)
799
- // scored 157, burying the better match among dozens of ties.
800
- if (matched === tokens.length && strongest >= STRONG_TOKEN_SCORE) {
801
- return {
802
- score:
803
- FULL_COVERAGE_SCORE +
804
- Math.min(
805
- Math.floor((tokenSum - matched * MIN_TOKEN_SCORE) / (matched * 5)),
806
- 8,
807
- ),
808
- reason,
809
- matched,
810
- total,
811
- };
812
- }
813
-
814
- // Base the score on the STRONGEST concept that matched, plus a bonus per
815
- // additional matched concept and a coverage term.
816
- //
817
- // Deliberately not the mean, and deliberately not divided by total query
818
- // length. Dividing by total length penalizes verbose / low-fidelity prompts.
819
- // Dividing by the number of MATCHED tokens (what this used to do) made the
820
- // score non-monotonic: a second, weaker hit could drag the mean down by more
821
- // than the coverage bonus added it back, so matching fewer terms well beat
822
- // matching more terms partially. Concretely, `build "file browser"` scored
823
- // two form wizards matching only "file" at 98, above the actual file browser
824
- // matching both terms at 97 — and 98 clears the PAGE_DIRECT gate, so the
825
- // wrong template was returned as a confident match.
826
- //
827
- // Taking the max keeps both properties: a verbose prompt is still scored on
828
- // the concepts it did hit, and matching a superset of another candidate's
829
- // terms can never score lower, since every term of the expression is
830
- // non-decreasing in the set of matched tokens.
831
- const coverage = matched / tokens.length;
832
- const tokenScore = Math.round(
833
- strongest + Math.min(matched - 1, 3) * 12 + coverage * 15,
834
- );
835
- if (full && full.score >= tokenScore) return asFull(full);
836
- return {score: tokenScore, reason, matched, total};
837
- }
838
-
839
- /**
840
- * Score a single candidate against the search term across name, keywords,
841
- * and prose signals. Returns the best (highest) score plus a human reason,
842
- * or null if nothing matched above the floor.
843
- *
844
- * @param {string} term - Lowercased search term.
845
- * @param {object} candidate
846
- * @param {string} candidate.name - Primary identifier (component/hook name, topic, template name).
847
- * @param {string[]} [candidate.aliases] - Other names, scored like the name (a theme's display name).
848
- * @param {string} [candidate.domain] - A component, hook, or template name
849
- * also matches typed as words: `command palette` is CommandPalette.
850
- * @param {string[]} [candidate.keywords] - Authored intent (componentsUsed, category words).
851
- * @param {string[]} [candidate.weakKeywords] - Derived signal (components a page renders).
852
- * @param {string} [candidate.description]
853
- * @param {string[]} [candidate.prose] - Extra free-text blobs (doc section text, best practices).
854
- * @param {string[]} [candidate.guidance] - Usage guidance (features, best practices) — scored a tier below description.
855
- * @param {{fuzzy?: boolean}} [opts] - `fuzzy`: allow edit-distance (typo) matches. Default true; multi-word queries pass false.
856
- * @returns {{score: number, reason: string} | null}
857
- */
858
- export function scoreCandidate(
859
- term,
860
- {
861
- name,
862
- aliases = [],
863
- domain,
864
- keywords = [],
865
- weakKeywords = [],
866
- description = '',
867
- prose = [],
868
- guidance = [],
869
- },
870
- {fuzzy = true} = {},
871
- ) {
872
- let best = 0;
873
- let reason = '';
874
- /**
875
- * @param {number} score
876
- * @param {string} why
877
- */
878
- const consider = (score, why) => {
879
- if (score > best) {
880
- best = score;
881
- reason = why;
882
- }
883
- };
884
-
885
- // ── Name signals ────────────────────────────────────────────────
886
- // An alias is a name too: a theme answers to its display name as well as
887
- // its slug.
888
- for (const candidateName of [name, ...aliases.filter(Boolean)]) {
889
- const nameLower = candidateName.toLowerCase();
890
- // A placed guide's name is its route, and the route's last segment is its
891
- // name too, as a flat topic's is: `codemods` is cli/integrations/codemods.
892
- const leafLower = nameLower.slice(nameLower.lastIndexOf('/') + 1);
893
-
894
- // A plural of the name is the name: `integration` is the `integrations`
895
- // guides, `tab` the `tabs` doc.
896
- // A component, hook, or template name typed as words is its name:
897
- // `command palette` is CommandPalette. A doc's name is a route or key,
898
- // matched as written.
899
- const spelled =
900
- domain !== 'doc' &&
901
- !/[\s_-]/.test(nameLower) &&
902
- nameLower === term.replace(/\s+/g, '');
903
- if (nameLower === term || leafLower === term || spelled) {
904
- consider(100, 'exact name');
905
- } else if (pluralOf(nameLower, term) || pluralOf(term, nameLower)) {
906
- // One point under the exact spelling, so the doc named `tokens` still
907
- // outranks the Token component for `tokens`.
908
- consider(99, 'plural of the name');
909
- } else {
910
- if (sameWord(term, nameLower)) consider(95, `name "${candidateName}"`);
911
- // The term is a word of the name, or starts one: "input" in TextInput.
912
- else if (startsAWordOf(term, candidateName)) {
913
- consider(60, `name contains "${term}"`);
914
- }
915
- if (fuzzy) {
916
- const dist = levenshteinDistance(term, nameLower);
917
- if (isTypo(term, nameLower, dist)) {
918
- consider(
919
- dist === 1 ? 80 : dist === 2 ? 40 : 20,
920
- `similar name (distance ${dist})`,
921
- );
922
- }
923
- }
924
- }
925
- }
926
-
927
- // ── Keyword signals ─────────────────────────────────────────────
928
- for (const kw of keywords) {
929
- const kwLower = String(kw).toLowerCase();
930
- if (kwLower === term) {
931
- consider(90, `keyword "${kw}"`);
932
- continue;
933
- }
934
- if (sameWord(term, kwLower)) {
935
- consider(88, `keyword "${kw}"`);
936
- continue;
937
- }
938
- if (startsAWordOf(term, kw)) consider(70, `keyword "${kw}"`);
939
- if (fuzzy) {
940
- const dist = levenshteinDistance(term, kwLower);
941
- if (isTypo(term, kwLower, dist) && dist <= 2) {
942
- consider(dist === 1 ? 70 : 30, `keyword "${kw}" (distance ${dist})`);
943
- }
944
- }
945
- }
946
-
947
- // ── Weak keyword signals (derived, not authored) ─────────────────
948
- // Capped at 60 so one incidental component match cannot clear the
949
- // confident-match gate on its own; it still counts toward multi-term
950
- // coverage, which is where "this page renders that" is real evidence.
951
- // No Levenshtein tier — fuzzy matching a derived signal is pure noise.
952
- for (const kw of weakKeywords) {
953
- const kwLower = String(kw).toLowerCase();
954
- if (kwLower === term || sameWord(term, kwLower)) {
955
- consider(60, `renders ${kw}`);
956
- continue;
957
- }
958
- if (startsAWordOf(term, kw)) consider(40, `renders ${kw}`);
959
- }
960
-
961
- // ── Prose / description / guidance signals (stem-tolerant whole word) ──
962
- // Match the term's stem as a whole word, tolerating plural/gerund suffixes
963
- // so "chart" matches "charts" and "filter" matches "filtering".
964
- if (term.length >= 3) {
965
- const root = stem(term);
966
- const escaped = root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
967
- const re = new RegExp(`\\b${escaped}(s|es|ing|ed|ies)?\\b`);
968
- if (description && re.test(description.toLowerCase())) {
969
- consider(50, `description mentions "${term}"`);
970
- } else {
971
- let matchedProse = false;
972
- for (const blob of prose) {
973
- if (blob && re.test(String(blob).toLowerCase())) {
974
- consider(50, `docs mention "${term}"`);
975
- matchedProse = true;
976
- break;
977
- }
978
- }
979
- // A tier below prose: guidance is what a component says about USING it,
980
- // so the term appearing there is weaker evidence than the component's own
981
- // summary. Only consulted when nothing stronger matched.
982
- if (!matchedProse) {
983
- for (const blob of guidance) {
984
- if (blob && re.test(String(blob).toLowerCase())) {
985
- consider(45, `guidance mentions "${term}"`);
986
- break;
987
- }
988
- }
989
- }
990
- }
991
- }
992
-
993
- return best > 0 ? {score: best, reason} : null;
994
- }
995
-
996
- /**
997
- * A component or hook doc, compiled, or null when it cannot be read.
998
- * @param {string} docPath
999
- * @param {string} [exportName]
1000
- * @param {'components' | 'hooks'} [root]
1001
- * @returns {Promise<any>}
1002
- */
1003
- async function loadModuleDoc(
1004
- docPath,
1005
- exportName = 'docs',
1006
- root = 'components',
1007
- ) {
1008
- try {
1009
- // Support both the stamped default export and the legacy named export.
1010
- return (
1011
- (await readDocView(docPath, {
1012
- root,
1013
- loader: 'native',
1014
- exports: ['default', exportName],
1015
- })) ?? null
1016
- );
1017
- } catch {
1018
- return null;
1019
- }
1020
- }
1021
-
1022
- /**
1023
- * Build component candidates from core's own tree: name + keywords +
1024
- * usage/description from the component's .doc.mjs.
1025
- * @param {string} coreDir
1026
- * @returns {Promise<Candidate[]>}
1027
- */
1028
- /**
1029
- * Usage guidance from a component doc: its feature list and its best-practice
1030
- * advice, flattened to plain strings.
1031
- *
1032
- * This is where a reader's vocabulary usually lives. `Banner` calls itself "a
1033
- * persistent message" and only its guidance names "form errors, system
1034
- * updates, maintenance notices" — so a search for the words people actually
1035
- * type finds nothing without it.
1036
- *
1037
- * @param {any} doc
1038
- * @returns {string[]}
1039
- */
1040
- function guidanceFrom(doc) {
1041
- if (!doc) return [];
1042
- const features = Array.isArray(doc.features) ? doc.features : [];
1043
- const practices = Array.isArray(doc.usage?.bestPractices)
1044
- ? doc.usage.bestPractices
1045
- : [];
1046
- return [...features, ...practices]
1047
- .map(entry =>
1048
- typeof entry === 'string'
1049
- ? entry
1050
- : [
1051
- entry?.title,
1052
- entry?.text,
1053
- entry?.description,
1054
- entry?.do,
1055
- entry?.dont,
1056
- ]
1057
- .filter(Boolean)
1058
- .join(' '),
1059
- )
1060
- .filter(Boolean);
1061
- }
1062
-
1063
- /**
1064
- * Build component candidates from core's own tree: name + keywords +
1065
- * usage/description from the component's .doc.mjs.
1066
- * @param {string} coreDir
1067
- * @returns {Promise<Candidate[]>}
1068
- */
1069
- async function gatherCoreComponents(coreDir) {
1070
- const grouped = discoverComponents(coreDir);
1071
- const names = Object.values(grouped).flat();
1072
- /** @type {Candidate[]} */
1073
- const candidates = [];
1074
- for (const comp of names) {
1075
- const readme = findComponentReadme(coreDir, comp);
1076
- /** @type {string[]} */
1077
- let keywords = [];
1078
- let description = '';
1079
- /** @type {string[]} */
1080
- let guidance = [];
1081
- if (readme && readme.endsWith('.doc.mjs')) {
1082
- const doc = await loadModuleDoc(readme);
1083
- if (doc) {
1084
- keywords = Array.isArray(doc.keywords) ? doc.keywords : [];
1085
- description = doc.usage?.description || doc.description || '';
1086
- guidance = guidanceFrom(doc);
1087
- }
1088
- }
1089
- candidates.push({
1090
- domain: 'component',
1091
- name: comp,
1092
- keywords,
1093
- description,
1094
- guidance,
1095
- _package: CORE_PACKAGE,
1096
- _import: resolveImportPath(coreDir, comp),
1097
- });
1098
- }
1099
- return candidates;
1100
- }
1101
-
1102
- /**
1103
- * Build component candidates contributed by the project's configured
1104
- * integrations (astryx.config's `integrations`): name + keywords +
1105
- * usage/description from each component's .doc.mjs, same as core. Without
1106
- * this, an integration component is invisible to `search`/`build` even
1107
- * though `component --list`/`component <Name>` already resolve it — the two
1108
- * discovery paths silently disagreed.
1109
- * @param {import('../../foundation/integrations/integrations.mjs').LoadedIntegration[]} loadedIntegrations
1110
- * @returns {Promise<Candidate[]>}
1111
- */
1112
- async function gatherIntegrationComponents(loadedIntegrations) {
1113
- /** @type {Candidate[]} */
1114
- const candidates = [];
1115
- for (const integration of loadedIntegrations) {
1116
- const {components} = await discoverValidIntegrationComponents(integration);
1117
- for (const rec of components) {
1118
- const doc = await loadModuleDoc(rec.docPath);
1119
- candidates.push({
1120
- domain: 'component',
1121
- name: rec.name,
1122
- keywords: doc && Array.isArray(doc.keywords) ? doc.keywords : [],
1123
- description: doc ? doc.usage?.description || doc.description || '' : '',
1124
- guidance: guidanceFrom(doc),
1125
- _package: rec.package ?? integration.name,
1126
- // Exactly what `component` reports: a doc may state its own specifier
1127
- // (one entry point exporting several components), and only when it
1128
- // does not do we resolve the subpath against the owning package's
1129
- // exports — read off the integration, which the loader already parsed.
1130
- // Reporting the bare package name here handed out a path that does not
1131
- // resolve, and disagreed with what `component <Name>` said about the
1132
- // very same component.
1133
- _import: resolveIntegrationImportPath(
1134
- {
1135
- exportsMap: integration.__packageExports,
1136
- packageDir: integration.__packageDir,
1137
- docPath: rec.docPath,
1138
- packageName: rec.package,
1139
- },
1140
- rec.name,
1141
- doc?.import,
1142
- ),
1143
- });
1144
- }
1145
- }
1146
- return candidates;
1147
- }
1148
-
1149
- /**
1150
- * Build component candidates: core's own tree plus every configured
1151
- * integration's components.
1152
- * @param {string} coreDir
1153
- * @param {string} cwd
1154
- * @returns {Promise<Candidate[]>}
1155
- */
1156
- async function gatherComponents(coreDir, cwd) {
1157
- const loadedIntegrations = await loadIntegrationsSafely(cwd);
1158
- const [core, integrations, replacements] = await Promise.all([
1159
- gatherCoreComponents(coreDir),
1160
- gatherIntegrationComponents(loadedIntegrations),
1161
- loadComponentReplacements(coreDir, loadedIntegrations),
1162
- ]);
1163
- // An active replacement answers to the Core name it replaces, so a search
1164
- // for that name finds the replacement and not the Core original
1165
- // (spec:AST-035 FR11).
1166
- /** @type {Map<string, string>} */
1167
- const targetOf = new Map(
1168
- replacements.active.map(active => [
1169
- `${active.package}\0${active.name}`,
1170
- active.target,
1171
- ]),
1172
- );
1173
- return [
1174
- ...core.filter(candidate => !replacements.forTarget(candidate.name)),
1175
- ...integrations.map(candidate => {
1176
- const target = targetOf.get(`${candidate._package}\0${candidate.name}`);
1177
- if (target != null) {
1178
- return {...candidate, aliases: [...(candidate.aliases ?? []), target]};
1179
- }
1180
- // Another package's component named after a replaced Core component is
1181
- // shadowed for the bare name (FR14): its command names its package.
1182
- const shadowedBy = replacements.forTarget(candidate.name);
1183
- return shadowedBy && shadowedBy.package !== candidate._package
1184
- ? {
1185
- ...candidate,
1186
- _command: `astryx component ${candidate.name} --package ${candidate._package}`,
1187
- }
1188
- : candidate;
1189
- }),
1190
- ];
1191
- }
1192
-
1193
- /**
1194
- * The components each search response was scored against, by response:
1195
- * `build` reads them to tell a part of a page from a page without gathering
1196
- * them again. Module-private, so they never enter search's JSON.
1197
- * @type {WeakMap<object, {name: string, keywords: string[]}[]>}
1198
- */
1199
- const searchedComponentsOf = new WeakMap();
1200
-
1201
- /**
1202
- * The components (name and keywords) a search response was scored against, or
1203
- * null when that search was narrowed away from components.
1204
- * @param {object} response
1205
- * @returns {{name: string, keywords: string[]}[] | null}
1206
- */
1207
- export function searchedComponents(response) {
1208
- return searchedComponentsOf.get(response) ?? null;
1209
- }
1210
-
1211
- /**
1212
- * Every component the project can use, Core's and its integrations', with the
1213
- * keywords its own doc declares: the discovery and doc reads search's own
1214
- * candidates use, without the import paths and prose a result carries. `build`
1215
- * reads it to tell a part of a page from a page when its search was narrowed
1216
- * away from components.
1217
- * @param {string} coreDir
1218
- * @param {string} cwd
1219
- * @returns {Promise<{name: string, keywords: string[]}[]>}
1220
- */
1221
- export async function componentKeywords(coreDir, cwd) {
1222
- /** @param {any} doc */
1223
- const keywordsOf = doc => (Array.isArray(doc?.keywords) ? doc.keywords : []);
1224
- const core = Object.values(discoverComponents(coreDir))
1225
- .flat()
1226
- .map(async name => {
1227
- const readme = findComponentReadme(coreDir, name);
1228
- const doc =
1229
- readme && readme.endsWith('.doc.mjs')
1230
- ? await loadModuleDoc(readme)
1231
- : null;
1232
- return {name, keywords: keywordsOf(doc)};
1233
- });
1234
- const loadedIntegrations = await loadIntegrationsSafely(cwd);
1235
- const replacements = await loadComponentReplacements(
1236
- coreDir,
1237
- loadedIntegrations,
1238
- );
1239
- const integrations = loadedIntegrations.map(async integration => {
1240
- const {components} = await discoverValidIntegrationComponents(integration);
1241
- return Promise.all(
1242
- components.map(async rec => ({
1243
- name: rec.name,
1244
- keywords: keywordsOf(await loadModuleDoc(rec.docPath)),
1245
- })),
1246
- );
1247
- });
1248
- return [
1249
- ...(await Promise.all(core)).filter(
1250
- component => !replacements.forTarget(component.name),
1251
- ),
1252
- ...(await Promise.all(integrations)).flat(),
1253
- ];
1254
- }
1255
-
1256
- /**
1257
- * Build hook candidates: name + keywords + usage/description from the hook's
1258
- * .doc.mjs.
1259
- * @param {string} coreDir
1260
- * @returns {Promise<Candidate[]>}
1261
- */
1262
- async function gatherHooks(coreDir) {
1263
- const grouped = discoverHooks(coreDir);
1264
- const names = Object.values(grouped).flat();
1265
- /** @type {Candidate[]} */
1266
- const candidates = [];
1267
- for (const hookName of names) {
1268
- const docPath = findHookDoc(coreDir, hookName);
1269
- /** @type {string[]} */
1270
- let keywords = [];
1271
- let description = '';
1272
- let importPath = '@astryxdesign/core/hooks';
1273
- if (docPath) {
1274
- const doc = await loadModuleDoc(docPath, 'docs', 'hooks');
1275
- if (doc) {
1276
- keywords = Array.isArray(doc.keywords) ? doc.keywords : [];
1277
- description = doc.usage?.description || doc.description || '';
1278
- importPath = doc.importPath || importPath;
1279
- }
1280
- }
1281
- candidates.push({
1282
- domain: 'hook',
1283
- name: hookName,
1284
- keywords,
1285
- description,
1286
- _package: CORE_PACKAGE,
1287
- _import: importPath,
1288
- });
1289
- }
1290
- return candidates;
1291
- }
1292
-
1293
- /**
1294
- * Build doc candidates at the grain a reader reads them: each section of a
1295
- * topic, whose command reads just that section; each topic as a whole, whose
1296
- * command lists its sections; and each docs-tree node by its route. The tree's
1297
- * guides split into sections like topics, and its typed docs also match by
1298
- * their own name, so `assertResponse` finds `cli/api/functions/assert-response`.
1299
- *
1300
- * Reads the project's catalog rather than the CLI's own docs directory, so a
1301
- * topic an integration contributed (or replaced) is searchable exactly like a
1302
- * built-in one — otherwise the replacement is served by `astryx docs` but
1303
- * invisible to the command whose job is finding it.
1304
- * @param {string} cwd
1305
- * @returns {Promise<Candidate[]>}
1306
- */
1307
- async function gatherDocs(cwd) {
1308
- /** @type {Candidate[]} */
1309
- const candidates = [];
1310
- let catalog;
1311
- try {
1312
- catalog = await loadDocsCatalog(cwd);
1313
- } catch {
1314
- return candidates;
1315
- }
1316
- let tree = null;
1317
- try {
1318
- tree = await projectTree(catalog);
1319
- } catch {
1320
- // `astryx doctor` reports a tree that fails to build; search still
1321
- // indexes the topics.
1322
- }
1323
- for (const entry of catalog.entries()) {
1324
- // A topic whose name opens another doc (spec:AST-046 FR11) is not
1325
- // offered: every hit's command must open the hit.
1326
- if (tree && !holdsOwnName(tree, catalog, entry)) continue;
1327
- let lowered = null;
1328
- try {
1329
- lowered = await lowerTopic(catalog, entry);
1330
- } catch {
1331
- // A topic that cannot be loaded is reported by the commands that own
1332
- // integration issues; search just cannot index it.
1333
- }
1334
- const doc = lowered?.doc ?? null;
1335
- // A flat topic lives in the Unorganized level; its hits say so, and name
1336
- // the package each section came from.
1337
- const home = tree?.get(entry.name);
1338
- const placed = home?.ref?.flatTopic === entry.name ? home : null;
1339
- /** @type {Map<string, string>} */
1340
- const packages = new Map([
1341
- [entry.providerId ?? entry.package, entry.package],
1342
- ...entry.extensions.map(
1343
- ext =>
1344
- /** @type {[string, string]} */ ([
1345
- ext.providerId ?? ext.package,
1346
- ext.package,
1347
- ]),
1348
- ),
1349
- ]);
1350
- candidates.push(
1351
- ...topicCandidates(
1352
- entry.name,
1353
- doc,
1354
- entry.title,
1355
- '',
1356
- placed && tree
1357
- ? [
1358
- ...tree.ancestors(placed).map(a => a.title),
1359
- doc?.title || entry.title || entry.name,
1360
- ].join(' › ')
1361
- : undefined,
1362
- placed ? `astryx docs ${placed.parent}` : undefined,
1363
- entry.package,
1364
- key =>
1365
- packages.get(lowered?.sectionProviders?.[key] ?? '') ?? entry.package,
1366
- ),
1367
- );
1368
- }
1369
- if (tree == null) return candidates;
1370
- for (const node of tree.nodes.values()) {
1371
- // A flat topic is indexed above, as a topic.
1372
- if (node.ref?.flatTopic) continue;
1373
- // A tree hit names where it lives: its ancestors' titles, then its own.
1374
- const path = [...tree.ancestors(node).map(a => a.title), node.title];
1375
- if (node.kind === 'generic') {
1376
- let doc = null;
1377
- try {
1378
- doc = (await lowerTopic(catalog, guideEntry(node))).doc;
1379
- } catch {
1380
- // As above: the owning commands report it.
1381
- }
1382
- candidates.push(
1383
- ...topicCandidates(
1384
- node.route,
1385
- doc,
1386
- node.title,
1387
- node.summary,
1388
- path.join(' › '),
1389
- node.parent == null ? undefined : `astryx docs ${node.parent}`,
1390
- node.provider,
1391
- ),
1392
- );
1393
- continue;
1394
- }
1395
- const selfDoc = /** @type {any} */ (node.ref)?.selfDoc;
1396
- // A typed doc's content is what `astryx docs <route>` prints. The first
1397
- // column of its tables names what the doc defines (an error code, an
1398
- // option, a parameter), so each is a keyword the doc answers to.
1399
- /** @type {any[]} */
1400
- const content = (await nodeView(catalog, tree, node)).content ?? [];
1401
- /** @type {string[]} */
1402
- const defined = [];
1403
- for (const block of content) {
1404
- if (block.type !== 'table' || !Array.isArray(block.rows)) continue;
1405
- for (const row of block.rows)
1406
- if (row[0] != null) defined.push(plain(row[0]));
1407
- }
1408
- candidates.push({
1409
- domain: 'doc',
1410
- name: node.name,
1411
- keywords: [
1412
- node.route.slice(node.route.lastIndexOf('/') + 1),
1413
- ...(Array.isArray(selfDoc?.keywords) ? selfDoc.keywords : []),
1414
- // A namespace doc's own keywords, which it declares for search.
1415
- ...(Array.isArray(node.keywords) ? node.keywords : []),
1416
- ...defined,
1417
- ...codeTerms({content}),
1418
- ],
1419
- description: node.summary || '',
1420
- prose: sectionProse({title: node.title, content}),
1421
- titles: [node.title],
1422
- _topic: node.route,
1423
- _title: path.join(' › '),
1424
- _command: `astryx docs ${node.route}`,
1425
- _parent:
1426
- node.parent == null ? 'astryx docs' : `astryx docs ${node.parent}`,
1427
- _package: node.provider,
1428
- });
1429
- }
1430
- return candidates;
1431
- }
1432
-
1433
- /**
1434
- * The words one section says: its prose, headings, and list items.
1435
- * @param {any} section
1436
- * @returns {string[]}
1437
- */
1438
- function sectionProse(section) {
1439
- /** @type {string[]} */
1440
- const prose = [];
1441
- if (section?.title) prose.push(section.title);
1442
- for (const block of section?.content || []) {
1443
- if ((block.type === 'prose' || block.type === 'heading') && block.text) {
1444
- prose.push(block.text);
1445
- } else if (block.type === 'list' && Array.isArray(block.items)) {
1446
- for (const item of block.items) {
1447
- const text = typeof item === 'string' ? item : item?.text;
1448
- if (typeof text === 'string') prose.push(text);
1449
- }
1450
- } else if (block.type === 'table' && Array.isArray(block.rows)) {
1451
- for (const row of block.rows) prose.push(row.map(plain).join(' '));
1452
- } else if (block.type === 'code' && typeof block.code === 'string') {
1453
- prose.push([block.label, block.code].filter(Boolean).join(' '));
1454
- }
1455
- }
1456
- return prose;
1457
- }
1458
-
1459
- /**
1460
- * The identifiers a doc part names in code ticks (`token-ref`,
1461
- * `ERR_UNKNOWN_SECTION`). Each is a keyword: a reader who types one exactly
1462
- * wants the part that defines or explains it.
1463
- * @param {any} part - a section, or `{content}` of a typed doc
1464
- * @returns {string[]}
1465
- */
1466
- function codeTerms(part) {
1467
- /** @type {Set<string>} */
1468
- const terms = new Set();
1469
- /** @param {unknown} text */
1470
- const scan = text => {
1471
- for (const m of String(text ?? '').matchAll(/`([^`\s]{2,40})`/g)) {
1472
- terms.add(m[1]);
1473
- }
1474
- };
1475
- for (const block of part?.content || []) {
1476
- if (block.type === 'prose') scan(block.text);
1477
- else if (block.type === 'list' && Array.isArray(block.items)) {
1478
- for (const item of block.items) {
1479
- scan(typeof item === 'string' ? item : item?.text);
1480
- }
1481
- } else if (block.type === 'table' && Array.isArray(block.rows)) {
1482
- for (const row of block.rows) for (const cell of row) scan(cell);
1483
- }
1484
- }
1485
- return [...terms];
1486
- }
1487
-
1488
- /**
1489
- * The headings inside a section. Each names a subsection, so a query that
1490
- * names one should find the section as surely as one that names its title.
1491
- * @param {any} section
1492
- * @returns {string[]}
1493
- */
1494
- function headings(section) {
1495
- return (section?.content || [])
1496
- .filter(
1497
- (/** @type {any} */ block) => block.type === 'heading' && block.text,
1498
- )
1499
- .map((/** @type {any} */ block) => String(block.text));
1500
- }
1501
-
1502
- /**
1503
- * A table cell as plain words, without its code ticks.
1504
- * @param {unknown} cell
1505
- * @returns {string}
1506
- */
1507
- function plain(cell) {
1508
- return unlinkText(String(cell ?? '')).replaceAll('`', '');
1509
- }
1510
-
1511
- /**
1512
- * The candidates one topic yields: the topic itself, and one per section when
1513
- * it has more than one. A topic's command lists its sections, and a section's
1514
- * command reads only that section, so a hit never costs a whole-topic read.
1515
- * @param {string} name - the topic name, or a placed guide's route
1516
- * @param {any} doc - the lowered topic, or null when it did not load
1517
- * @param {string} [title]
1518
- * @param {string} [summary]
1519
- * @param {string} [path] - where the topic lives in the docs tree, as titles
1520
- * joined by ` › `; a flat topic is its own title
1521
- * @param {string} [parent] - the command that opens the level above the
1522
- * topic: its namespace, or the Unorganized level for a flat topic
1523
- * @param {string} [pkg] - the npm package that authored the topic
1524
- * @param {(key: string) => string} [sectionPackage] - the npm package a
1525
- * section came from: an extension's section names the extension's package
1526
- * @returns {Candidate[]}
1527
- */
1528
- function topicCandidates(
1529
- name,
1530
- doc,
1531
- title,
1532
- summary = '',
1533
- path,
1534
- parent,
1535
- pkg,
1536
- sectionPackage,
1537
- ) {
1538
- /** @type {any[]} */
1539
- const sections = doc?.sections ?? [];
1540
- const docTitle = path || doc?.title || title || name;
1541
- const split = sections.length > 1;
1542
- // A placed guide also answers to its last route segment's words:
1543
- // `quick start` is cli/integrations/quick-start.
1544
- const leaf = name.slice(name.lastIndexOf('/') + 1);
1545
- /** @type {Candidate[]} */
1546
- const out = [
1547
- {
1548
- domain: 'doc',
1549
- name,
1550
- keywords: [
1551
- ...(leaf !== name ? [leaf.replaceAll('-', ' ')] : []),
1552
- ...(doc?.title || title ? [doc?.title || title] : []),
1553
- ...(Array.isArray(doc?.keywords) ? doc.keywords : []),
1554
- ],
1555
- description: doc?.description || summary,
1556
- prose: split
1557
- ? sections.map(section => section.title).filter(Boolean)
1558
- : sections.flatMap(sectionProse),
1559
- titles: [
1560
- doc?.title || title || name,
1561
- // A topic read whole answers for the headings inside it.
1562
- ...(split ? [] : sections.flatMap(s => [s.title, ...headings(s)])),
1563
- ].filter(Boolean),
1564
- _topic: name,
1565
- _title: docTitle,
1566
- _command: split ? `astryx docs ${name} --index` : `astryx docs ${name}`,
1567
- ...(parent ? {_parent: parent} : {}),
1568
- ...(pkg ? {_package: pkg} : {}),
1569
- },
1570
- ];
1571
- if (!split) return out;
1572
- for (const section of sections) {
1573
- const key = sectionKey(section);
1574
- out.push({
1575
- domain: 'doc',
1576
- name: key,
1577
- keywords: [
1578
- ...(section.title ? [section.title] : []),
1579
- ...headings(section),
1580
- ...codeTerms(section),
1581
- ],
1582
- description: sectionSummary(section),
1583
- prose: sectionProse(section),
1584
- titles: [section.title, ...headings(section)].filter(Boolean),
1585
- _topic: name,
1586
- _section: key,
1587
- _title: `${docTitle} › ${section.title}`,
1588
- _command: `astryx docs ${name} ${key}`,
1589
- _parent: `astryx docs ${name} --index`,
1590
- ...((sectionPackage?.(key) ?? pkg)
1591
- ? {_package: sectionPackage?.(key) ?? pkg}
1592
- : {}),
1593
- });
1594
- }
1595
- return out;
1596
- }
1597
-
1598
- /**
1599
- * Build template candidates (page + block) from the template discovery API.
1600
- * @param {string} cwd
1601
- * @returns {Promise<Candidate[]>}
1602
- */
1603
- async function gatherTemplates(cwd) {
1604
- let templates;
1605
- try {
1606
- templates = await discoverTemplates(cwd);
1607
- } catch {
1608
- return [];
1609
- }
1610
- return templates.map(t => {
1611
- // A replacement's target is its canonical unqualified lookup id. Keep the
1612
- // integration-owned id as a keyword and response label, but score and print
1613
- // commands against the id that `template()` resolves back to this entry.
1614
- // This matters for replacement chains: one replacement's own id can be the
1615
- // target of another, so using that shadowed id as the command would select
1616
- // the other template.
1617
- const commandName = t.replaces ?? t.dirName;
1618
- // Blocks ship an authored componentsUsed; page templates don't, so derive
1619
- // them from the source. Category words (e.g. "Dashboard - Analytics") are
1620
- // strong intent signal for pages, which otherwise only index on name +
1621
- // description.
1622
- //
1623
- // Authored signal and derived signal are kept apart: componentsUsed and
1624
- // category words are a deliberate statement of what the template is for,
1625
- // while scraped JSX tags only say what it happens to render. See the
1626
- // scoring table at the top of this file for why the derived set is capped.
1627
- const keywords = Array.isArray(t.componentsUsed)
1628
- ? [...t.componentsUsed]
1629
- : [];
1630
- keywords.push(...templateLookupIds(t).filter(id => id !== commandName));
1631
- /** @type {string[]} */
1632
- let weakKeywords = [];
1633
- if (t.type === 'page') {
1634
- if (t.filePath) {
1635
- try {
1636
- weakKeywords = extractComponents(t.filePath);
1637
- } catch {
1638
- // Best-effort: skip keyword enrichment if the source can't be read.
1639
- }
1640
- }
1641
- if (t.category)
1642
- keywords.push(...t.category.split(/[^A-Za-z0-9]+/).filter(Boolean));
1643
- }
1644
- return {
1645
- domain: 'template',
1646
- name: commandName,
1647
- keywords,
1648
- weakKeywords,
1649
- description: t.description || '',
1650
- // A template's own keywords name the many ideas it serves, so they score
1651
- // as its prose does, not as a name: one of them matching one word of a
1652
- // short idea is not a direct match.
1653
- prose: t.keywords ?? [],
1654
- _displayName: t.name,
1655
- _package: t.package ?? CORE_PACKAGE,
1656
- _kind: t.type, // 'page' | 'block'
1657
- _resultName: t.dirName,
1658
- _commandName: commandName,
1659
- };
1660
- });
1661
- }
1662
-
1663
- /**
1664
- * Build theme candidates from bundled and integration-provided themes. Without
1665
- * this, an integration's themes are invisible to `search` even though
1666
- * `theme list` and `discover` already resolve them.
1667
- *
1668
- * A theme's slug and display name are its names, and its description is prose
1669
- * (`spec:AST-050/FR14`). A theme declares no keywords, so a word it shares with
1670
- * the query only through its description is a description mention: read as a
1671
- * keyword, every word of the description would outrank the components and docs
1672
- * that declare that word.
1673
- * @param {string} cwd
1674
- * @returns {Promise<Candidate[]>}
1675
- */
1676
- async function gatherThemes(cwd) {
1677
- let themes;
1678
- try {
1679
- themes = await listAvailableThemes(cwd);
1680
- } catch {
1681
- return [];
1682
- }
1683
- return themes.map(t => ({
1684
- domain: 'theme',
1685
- name: t.slug,
1686
- aliases: t.displayName ? [t.displayName] : [],
1687
- description: t.description || '',
1688
- _displayName: t.displayName,
1689
- _package: t.package,
1690
- }));
1691
- }
1692
-
1693
- /**
1694
- * Map a scored candidate to its public, actionable result shape. Each result
1695
- * carries enough to act on it: the domain, name, a one-line description, and
1696
- * the follow-up command (and import path where relevant).
1697
- *
1698
- * @param {Candidate} c - candidate
1699
- * @param {number} score
1700
- * @param {string} reason
1701
- * @param {number} matchedTerms - Query concepts this result answered.
1702
- * @param {number} queryTerms - Query concepts there were to answer.
1703
- */
1704
- function toResult(c, score, reason, matchedTerms, queryTerms) {
1705
- const base = {
1706
- domain: c.domain,
1707
- name: c._resultName ?? c.name,
1708
- package: c._package,
1709
- score,
1710
- reason,
1711
- description: c.description || '',
1712
- };
1713
- let result;
1714
- switch (c.domain) {
1715
- case 'component':
1716
- result = {
1717
- ...base,
1718
- import: c._import,
1719
- command: c._command ?? `astryx component ${c.name}`,
1720
- };
1721
- break;
1722
- case 'hook':
1723
- result = {
1724
- ...base,
1725
- import: c._import,
1726
- command: `astryx hook ${c.name}`,
1727
- };
1728
- break;
1729
- case 'doc':
1730
- // A doc result names its topic or route, plus the section when the
1731
- // hit is one section; its command reads exactly that part.
1732
- result = {
1733
- ...base,
1734
- name: c._topic ?? c.name,
1735
- ...(c._section ? {section: c._section} : {}),
1736
- title: c._title,
1737
- command: c._command ?? `astryx docs ${c.name}`,
1738
- ...(c._parent ? {parent: c._parent} : {}),
1739
- };
1740
- break;
1741
- case 'template':
1742
- result = {
1743
- ...base,
1744
- displayName: c._displayName,
1745
- kind: c._kind,
1746
- command: `astryx template ${c._commandName ?? c.name} --type ${c._kind}`,
1747
- };
1748
- break;
1749
- case 'theme':
1750
- result = {
1751
- ...base,
1752
- displayName: c._displayName,
1753
- command: `astryx theme add ${c.name}`,
1754
- };
1755
- break;
1756
- default:
1757
- result = base;
1758
- }
1759
- return setResultCoverage(result, matchedTerms, queryTerms);
1760
- }
19
+ gatherCandidates,
20
+ gatherCandidatesReused,
21
+ loadSearchData,
22
+ } from './_adapter.mjs';
23
+ import {rankLexical} from './_lexical.mjs';
24
+ import {checkSearchArgs} from './_result.mjs';
25
+ import {runTree} from '../../foundation/route/route.mjs';
26
+ import {SEARCH_TREE} from './tree.mjs';
27
+ import {linkSearchResponse} from '../component/_adapter.mjs';
28
+
29
+ // The domains a search covers (the command handler lists them), and what
30
+ // build reads from search: its word vocabulary, the components a search
31
+ // read, and the keywords of Core's components.
32
+ export {SEARCH_DOMAINS, STOPWORDS, tokenizeQuery} from './_query.mjs';
33
+ export {headingWithPhrase, titleInQuery} from './_titles.mjs';
34
+ export {scoreCandidate} from './_candidate-score.mjs';
35
+ export {scoreQuery} from './_score.mjs';
36
+ export {domainPriority} from './_priority.mjs';
37
+ export {compoundHit} from './_compound.mjs';
38
+ export {SYNONYMS} from './_synonyms.mjs';
39
+ export {sameWord, spellIdentifiers, stem} from './_words.mjs';
40
+ export {searchedComponents} from './_result.mjs';
41
+ export {componentKeywords} from './_adapter.mjs';
1761
42
 
1762
43
  /**
1763
44
  * Unified ranked search across components, hooks, docs, templates, and themes.
@@ -1770,164 +51,38 @@ function toResult(c, score, reason, matchedTerms, queryTerms) {
1770
51
  * @returns {Promise<import('./search.type.mjs').SearchResponse>}
1771
52
  */
1772
53
  export async function search(query, options = {}) {
1773
- // Every candidate resolves its source and docs by walking the same tree;
1774
- // read each directory once for this call.
1775
- return withListingCache(() => searchOnce(query, options));
54
+ checkSearchArgs(query, options);
55
+ return withListingCache(
56
+ async () =>
57
+ /** @type {import('./search.type.mjs').SearchResponse} */ (
58
+ await linkSearchResponse(
59
+ /** @type {import('./search.type.mjs').SearchResponse} */ (
60
+ await runTree(
61
+ SEARCH_TREE,
62
+ {query, options},
63
+ {...(await gatherCandidatesReused(options)), data: loadSearchData()},
64
+ )
65
+ ),
66
+ options.cwd ?? process.cwd(),
67
+ )
68
+ ),
69
+ );
1776
70
  }
1777
71
 
1778
72
  /**
73
+ * The lexical ranker alone: keyword and fuzzy scoring of every candidate.
74
+ * `build` ranks from it.
75
+ *
1779
76
  * @param {string} query
1780
- * @param {NonNullable<Parameters<typeof search>[1]>} options
1781
- * @returns {ReturnType<typeof search>}
77
+ * @param {{cwd?: string, type?: 'component'|'hook'|'doc'|'template'|'theme', limit?: number}} [options]
78
+ * @returns {Promise<import('./search.type.mjs').SearchResponse>}
1782
79
  */
1783
- async function searchOnce(query, options) {
1784
- const {cwd = process.cwd(), type, limit = 20} = options;
1785
-
1786
- if (!query || !String(query).trim()) {
1787
- throw new AstryxError(
1788
- 'A search query is required',
1789
- [{name: 'astryx search button', reason: 'example'}],
1790
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1791
- );
1792
- }
1793
-
1794
- if (type && !SEARCH_DOMAINS.includes(type)) {
1795
- throw new AstryxError(
1796
- `Unknown --type "${type}"`,
1797
- SEARCH_DOMAINS.map(d => ({name: d, reason: 'valid type'})),
1798
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1799
- );
1800
- }
1801
-
1802
- // Validate limit here (not just in the CLI) so direct API callers get the same
1803
- // contract: a non-positive or non-integer limit is an error, never a silent
1804
- // "return everything". (Previously `limit <= 0` fell through to the full set.)
1805
- if (limit != null && (!Number.isInteger(limit) || limit <= 0)) {
1806
- throw new AstryxError(
1807
- `Invalid limit "${limit}". Must be a positive integer.`,
1808
- undefined,
1809
- ERROR_CODES.ERR_INVALID_ARGUMENT,
1810
- );
1811
- }
1812
-
1813
- const term = String(query).trim().toLowerCase();
1814
- const tokens = tokenizeQuery(term);
1815
-
1816
- // `astryx docs` reads docs without @astryxdesign/core, and `astryx theme
1817
- // list` reads themes without it (bundled themes need no project), so a
1818
- // search of either must too. Every other domain reads core: asked for by
1819
- // name, it is an error without core; an open search then covers the docs
1820
- // and themes alone.
1821
- const needsCore = !type || !CORELESS_DOMAINS.includes(type);
1822
- const coreDir = needsCore ? findCoreDir(cwd) : null;
1823
- if (type && needsCore && !coreDir) {
1824
- throw new AstryxError(
1825
- 'Could not find @astryxdesign/core package',
1826
- undefined,
1827
- ERROR_CODES.ERR_CORE_NOT_FOUND,
1828
- );
1829
- }
1830
-
1831
- // Gather candidates from each requested domain in parallel.
1832
- /** @param {string} d */
1833
- const wants = d =>
1834
- (!type && (coreDir != null || CORELESS_DOMAINS.includes(d))) || type === d;
1835
- const [components, hooks, docTopics, templates, themes] = await Promise.all([
1836
- wants('component')
1837
- ? gatherComponents(/** @type {string} */ (coreDir), cwd)
1838
- : [],
1839
- wants('hook') ? gatherHooks(/** @type {string} */ (coreDir)) : [],
1840
- wants('doc') ? gatherDocs(cwd) : [],
1841
- wants('template') ? gatherTemplates(cwd) : [],
1842
- wants('theme') ? gatherThemes(cwd) : [],
1843
- ]);
1844
-
1845
- const all = [...components, ...hooks, ...docTopics, ...templates, ...themes];
1846
-
1847
- // Score every candidate on its own merits. The consumer groups results by
1848
- // role (page / block / component) and takes the top of each, so there's no
1849
- // cross-role competition to engineer — a target page only needs to be the
1850
- // strongest PAGE, not outrank every component.
1851
- /** @type {{result: any, priority: 0 | 1 | 2}[]} */
1852
- const ranked = [];
1853
- for (const candidate of all) {
1854
- const hit = scoreQuery(term, tokens, candidate);
1855
- if (hit)
1856
- ranked.push({
1857
- result: toResult(
1858
- candidate,
1859
- hit.score,
1860
- hit.reason,
1861
- hit.matched,
1862
- hit.total,
1863
- ),
1864
- priority: domainPriority(term, tokens, candidate, hit),
1865
- });
1866
- }
1867
-
1868
- // Docs and everything else are each sorted by score desc, then domain
1869
- // (stable order), then name. The two are merged: at each step the stronger
1870
- // head goes next, except that a head with domain priority goes ahead of a
1871
- // doc head without it (see domainPriority). Each side keeps its own order.
1872
- /** @type {Record<string, number>} */
1873
- const domainOrder = {component: 0, hook: 1, doc: 2, template: 3, theme: 4};
1874
- /**
1875
- * @param {{result: any}} x
1876
- * @param {{result: any}} y
1877
- */
1878
- const byScore = ({result: a}, {result: b}) =>
1879
- b.score - a.score ||
1880
- (domainOrder[a.domain] ?? 9) - (domainOrder[b.domain] ?? 9) ||
1881
- a.name.localeCompare(b.name);
1882
- const others = ranked.filter(r => r.result.domain !== 'doc').sort(byScore);
1883
- // Against other domains, a doc the reader asked for competes ahead of docs
1884
- // they did not, so it is not held behind a broad page that outscores it.
1885
- // Docs alone keep their text-match order, with a doc the whole query names
1886
- // first.
1887
- const docs = ranked
1888
- .filter(r => r.result.domain === 'doc')
1889
- .sort((x, y) =>
1890
- others.length > 0
1891
- ? y.priority - x.priority || byScore(x, y)
1892
- : Number(y.priority === 2) - Number(x.priority === 2) || byScore(x, y),
1893
- );
1894
- const scored = [];
1895
- let i = 0;
1896
- let j = 0;
1897
- while (i < others.length || j < docs.length) {
1898
- const other = others[i];
1899
- const doc = docs[j];
1900
- const otherFirst =
1901
- !doc ||
1902
- (other != null &&
1903
- ((other.priority && !doc.priority) || byScore(other, doc) < 0));
1904
- scored.push(otherFirst ? others[i++].result : docs[j++].result);
1905
- }
1906
-
1907
- // `results` is bounded by `limit` so a caller (and the recorded run that
1908
- // quotes it) never carries an unbounded payload. `matchCount` is the number
1909
- // of matches that bound was applied TO — reporting `results.length` there
1910
- // would report the cap back as if it were the answer, so a query matching
1911
- // 57 things and one matching exactly 20 would be indistinguishable.
1912
- const limited = scored.slice(0, limit);
1913
-
1914
- /** @type {import('./search.type.mjs').SearchResponse} */
1915
- const response = {
1916
- type: 'search',
1917
- data: {
1918
- query: String(query).trim(),
1919
- matchCount: scored.length,
1920
- // toResult gives every domain its command and domain fields.
1921
- results: /** @type {import('./search.type.mjs').SearchResultEntry[]} */ (
1922
- limited
1923
- ),
1924
- },
1925
- };
1926
- if (wants('component')) {
1927
- searchedComponentsOf.set(
1928
- response,
1929
- components.map(c => ({name: c.name, keywords: c.keywords ?? []})),
1930
- );
1931
- }
1932
- return response;
80
+ export async function searchCore(query, options = {}) {
81
+ checkSearchArgs(query, options);
82
+ return withListingCache(async () =>
83
+ linkSearchResponse(
84
+ rankLexical(query, options, await gatherCandidates(options)),
85
+ options.cwd ?? process.cwd(),
86
+ ),
87
+ );
1933
88
  }