@astryxdesign/cli 0.7.16 → 0.7.17-canary.g16fe6a8

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 (380) hide show
  1. package/README.md +76 -86
  2. package/api/build/_adapter.d.mts +12 -0
  3. package/api/build/_adapter.mjs +51 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +4 -3
  7. package/api/build/build.type.d.mts +2 -2
  8. package/api/build/build.type.mjs +3 -3
  9. package/api/build/kit/kind.d.mts +2 -1
  10. package/api/build/kit/kind.mjs +199 -10
  11. package/api/build/kit/kit.mjs +6 -4
  12. package/api/build/kit/rank.d.mts +4 -2
  13. package/api/build/kit/rank.mjs +125 -24
  14. package/api/build/kit/start.d.mts +5 -4
  15. package/api/build/kit/start.mjs +12 -8
  16. package/api/build/kit/weights.d.mts +39 -3
  17. package/api/build/kit/weights.json +1 -1
  18. package/api/build/kit/weights.mjs +340 -43
  19. package/api/build/kit/word-model.d.mts +23 -0
  20. package/api/build/kit/word-model.mjs +46 -0
  21. package/api/build/kit/words.d.mts +48 -0
  22. package/api/build/kit/words.mjs +90 -1
  23. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  24. package/api/component/list/list.d.mts +1 -1
  25. package/api/component/list/list.mjs +48 -6
  26. package/api/discover/_adapter.d.mts +1 -1
  27. package/api/discover/search/search.mjs +3 -2
  28. package/api/docs/_adapter.d.mts +28 -2
  29. package/api/docs/_adapter.mjs +249 -10
  30. package/api/docs/docs.d.mts +3 -0
  31. package/api/docs/docs.doc.mjs +7 -1
  32. package/api/docs/docs.mjs +12 -0
  33. package/api/docs/docs.type.d.mts +5 -0
  34. package/api/docs/docs.type.mjs +2 -0
  35. package/api/docs/node/node.mjs +1 -1
  36. package/api/doctor/_adapter.d.mts +27 -5
  37. package/api/doctor/_adapter.mjs +83 -10
  38. package/api/doctor/built-checks.mjs +40 -14
  39. package/api/doctor/doctor.d.mts +4 -3
  40. package/api/doctor/doctor.mjs +14 -7
  41. package/api/doctor/theme-checks.mjs +121 -17
  42. package/api/icon/_records.mjs +2 -1
  43. package/api/index.d.mts +2 -0
  44. package/api/index.mjs +2 -0
  45. package/api/integration/_adapter.d.mts +44 -0
  46. package/api/integration/_adapter.mjs +77 -1
  47. package/api/integration/authoring-checks.mjs +6 -6
  48. package/api/integration/example-scope.d.mts +14 -0
  49. package/api/integration/example-scope.mjs +44 -0
  50. package/api/integration/example-scope.type.d.mts +29 -0
  51. package/api/integration/example-scope.type.mjs +25 -0
  52. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  53. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  54. package/api/integration/validate-integration.mjs +19 -1
  55. package/api/integration/validate-integration.type.d.mts +9 -0
  56. package/api/integration/validate-integration.type.mjs +1 -1
  57. package/api/integration/validateIntegration.doc.mjs +1 -1
  58. package/api/render/_adapter.mjs +591 -195
  59. package/api/render/render.doc.mjs +11 -3
  60. package/api/render/render.type.d.mts +52 -0
  61. package/api/render/render.type.mjs +31 -1
  62. package/api/search/ORDERING.md +1 -1
  63. package/api/search/_adapter.d.mts +9 -0
  64. package/api/search/_adapter.mjs +85 -0
  65. package/api/search/_candidate-score.mjs +51 -32
  66. package/api/search/_fit-order.mjs +3 -3
  67. package/api/search/_gather-components.d.mts +3 -2
  68. package/api/search/_gather-components.mjs +12 -3
  69. package/api/search/_lexical.d.mts +5 -0
  70. package/api/search/_lexical.mjs +8 -2
  71. package/api/search/_result.d.mts +11 -9
  72. package/api/search/_result.mjs +4 -4
  73. package/api/search/_score.d.mts +6 -1
  74. package/api/search/_score.mjs +15 -3
  75. package/api/search/search-index.mjs +7 -1
  76. package/api/search/search.d.mts +1 -1
  77. package/api/theme/_adapter.mjs +12 -1
  78. package/api/theme/build/build.d.mts +132 -1
  79. package/api/theme/build/build.mjs +482 -157
  80. package/api/theme/build/core-interception.d.mts +10 -0
  81. package/api/theme/build/core-interception.mjs +10 -0
  82. package/api/theme/build/font-warning.d.mts +44 -5
  83. package/api/theme/build/font-warning.mjs +118 -10
  84. package/api/theme/build/icon-imports.mjs +51 -9
  85. package/api/theme/theme.type.d.mts +10 -0
  86. package/api/theme/theme.type.mjs +7 -1
  87. package/api/theme-edit/_adapter.d.mts +115 -4
  88. package/api/theme-edit/_adapter.mjs +997 -83
  89. package/api/theme-edit/_catalog.d.mts +20 -2
  90. package/api/theme-edit/_catalog.mjs +50 -10
  91. package/api/theme-edit/_check.d.mts +75 -24
  92. package/api/theme-edit/_check.mjs +2672 -422
  93. package/api/theme-edit/_color.d.mts +10 -0
  94. package/api/theme-edit/_color.mjs +54 -1
  95. package/api/theme-edit/_compiler.d.mts +1 -0
  96. package/api/theme-edit/_compiler.mjs +133 -15
  97. package/api/theme-edit/_context.d.mts +14 -3
  98. package/api/theme-edit/_context.mjs +225 -65
  99. package/api/theme-edit/_css.d.mts +14 -0
  100. package/api/theme-edit/_css.mjs +46 -1
  101. package/api/theme-edit/_edit.d.mts +54 -4
  102. package/api/theme-edit/_edit.mjs +2966 -286
  103. package/api/theme-edit/_how-commands.d.mts +72 -1
  104. package/api/theme-edit/_how-commands.mjs +770 -9
  105. package/api/theme-edit/_how-question.d.mts +82 -5
  106. package/api/theme-edit/_how-question.mjs +6983 -701
  107. package/api/theme-edit/_how.d.mts +2 -1
  108. package/api/theme-edit/_how.mjs +237 -41
  109. package/api/theme-edit/_importers.d.mts +38 -0
  110. package/api/theme-edit/_importers.mjs +188 -0
  111. package/api/theme-edit/_marks.d.mts +31 -5
  112. package/api/theme-edit/_marks.mjs +57 -5
  113. package/api/theme-edit/_name-rule.d.mts +11 -0
  114. package/api/theme-edit/_name-rule.mjs +12 -0
  115. package/api/theme-edit/_normal.d.mts +303 -0
  116. package/api/theme-edit/_normal.mjs +1517 -0
  117. package/api/theme-edit/_palette.d.mts +12 -0
  118. package/api/theme-edit/_palette.mjs +37 -4
  119. package/api/theme-edit/_part-words.d.mts +31 -0
  120. package/api/theme-edit/_part-words.mjs +126 -0
  121. package/api/theme-edit/_parts.d.mts +28 -2
  122. package/api/theme-edit/_parts.mjs +267 -31
  123. package/api/theme-edit/_preview-app.d.mts +7 -13
  124. package/api/theme-edit/_preview-app.mjs +814 -406
  125. package/api/theme-edit/_preview.d.mts +116 -16
  126. package/api/theme-edit/_preview.mjs +649 -152
  127. package/api/theme-edit/_project.d.mts +22 -1
  128. package/api/theme-edit/_project.mjs +83 -3
  129. package/api/theme-edit/_settings.d.mts +467 -42
  130. package/api/theme-edit/_settings.mjs +3527 -468
  131. package/api/theme-edit/_tables.d.mts +21 -0
  132. package/api/theme-edit/_tables.mjs +97 -3
  133. package/api/theme-edit/_vet.d.mts +31 -0
  134. package/api/theme-edit/_vet.mjs +114 -8
  135. package/api/theme-edit/theme-edit.type.d.mts +16 -2
  136. package/api/theme-edit/theme-edit.type.mjs +6 -3
  137. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  138. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  139. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  140. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  141. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  142. package/api/upgrade/run/run.mjs +4 -3
  143. package/assets/codemods/integration-discovery.mjs +2 -1
  144. package/assets/codemods/run-codemod.mjs +87 -7
  145. package/assets/codemods/transforms/next/index.mjs +11 -1
  146. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  147. package/assets/component-list.generated.json +1 -0
  148. package/assets/docs/author-a-theme.doc.mjs +1 -0
  149. package/assets/docs/theme.doc.dense.mjs +2 -2
  150. package/assets/docs/theme.doc.mjs +1 -1
  151. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  152. package/assets/docs/tree/checks.doc.mjs +1 -1
  153. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  154. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  155. package/assets/docs/tree/share-a-page.doc.mjs +157 -0
  156. package/assets/docs/tree/single-component.doc.mjs +4 -0
  157. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  158. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  159. package/assets/docs/use-a-theme.doc.mjs +1 -1
  160. package/assets/docs.generated.json +2 -2
  161. package/assets/search-catalog.generated.json +2 -0
  162. package/assets/self-audit.generated.json +1 -1
  163. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  164. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  165. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  166. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  167. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  168. package/assets/templates/components.generated.json +1 -1
  169. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  170. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  171. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  172. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  173. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  174. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  175. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  176. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  177. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  178. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  179. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  180. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  181. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  182. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  183. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  184. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  185. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  186. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  187. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  188. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  189. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  190. package/assets/templates/pages/ide/page.tsx +24 -2
  191. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  192. package/assets/templates/pages/library/template.doc.mjs +4 -1
  193. package/assets/templates/pages/login/template.doc.mjs +2 -1
  194. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  195. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  196. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  197. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  198. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  199. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  200. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  201. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  202. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  203. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  204. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  205. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  206. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  207. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  208. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  209. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  210. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  211. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  212. package/assets/theme.template.ts +6 -0
  213. package/authoring/debug/parse.d.mts +3 -3
  214. package/authoring/doctypes/_schema.d.mts +3 -3
  215. package/authoring/doctypes/command/command.doc.mjs +1 -1
  216. package/authoring/doctypes/component/categories.d.mts +37 -0
  217. package/authoring/doctypes/component/categories.mjs +54 -0
  218. package/authoring/doctypes/template/template.doc.mjs +1 -1
  219. package/authoring/doctypes/template/type.ts +9 -0
  220. package/authoring/example/example.doc.d.mts +12 -0
  221. package/authoring/example/example.doc.mjs +69 -0
  222. package/authoring/example/preview.d.mts +92 -0
  223. package/authoring/example/preview.mjs +994 -0
  224. package/authoring/example/type.ts +102 -0
  225. package/authoring/index.d.mts +1 -0
  226. package/authoring/index.d.ts +12 -0
  227. package/authoring/index.mjs +3 -1
  228. package/clients/cli/bin/astryx.mjs +6 -9
  229. package/clients/cli/build-id.generated.json +1 -1
  230. package/clients/cli/commands/component.doc.mjs +1 -1
  231. package/clients/cli/commands/component.mjs +22 -3
  232. package/clients/cli/commands/docs.doc.mjs +7 -1
  233. package/clients/cli/commands/docs.mjs +3 -1
  234. package/clients/cli/commands/doctor.mjs +32 -14
  235. package/clients/cli/commands/experimental/render.mjs +42 -1
  236. package/clients/cli/commands/experimental/theme.mjs +573 -119
  237. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  238. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  239. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  240. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  241. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  242. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  243. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  244. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  245. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  246. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  247. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  248. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  249. package/clients/cli/commands/search.doc.mjs +2 -1
  250. package/clients/cli/commands/search.mjs +6 -1
  251. package/clients/cli/commands/template.mjs +4 -2
  252. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  253. package/clients/cli/commands/theme.doc.mjs +1 -1
  254. package/clients/cli/commands/theme.mjs +718 -438
  255. package/clients/cli/commands/upgrade.mjs +42 -7
  256. package/clients/cli/index.mjs +1 -1
  257. package/clients/cli/lib/cli-error.mjs +2 -1
  258. package/clients/cli/lib/component-format.mjs +205 -98
  259. package/clients/cli/lib/hook-format.mjs +9 -19
  260. package/clients/cli/lib/json-shim.mjs +132 -24
  261. package/clients/cli/lib/manifest.mjs +3 -2
  262. package/clients/cli/manifest.generated.json +1 -1
  263. package/foundation/agent-docs/agent-docs.mjs +1 -1
  264. package/foundation/config/theme-state.d.mts +13 -1
  265. package/foundation/config/theme-state.mjs +47 -7
  266. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  267. package/foundation/discovery/component-discovery.d.mts +11 -0
  268. package/foundation/discovery/component-discovery.mjs +56 -8
  269. package/foundation/discovery/component-replacement.mjs +130 -1
  270. package/foundation/discovery/copied-passages.mjs +2 -1
  271. package/foundation/discovery/core-component-docs.d.mts +29 -0
  272. package/foundation/discovery/core-component-docs.mjs +83 -0
  273. package/foundation/discovery/doc-types.mjs +4 -3
  274. package/foundation/discovery/entry-name-files.d.mts +43 -0
  275. package/foundation/discovery/entry-name-files.mjs +264 -0
  276. package/foundation/discovery/hook-discovery.d.mts +8 -2
  277. package/foundation/discovery/hook-discovery.mjs +22 -8
  278. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  279. package/foundation/discovery/icon-set-checks.mjs +2 -1
  280. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  281. package/foundation/discovery/integration-doc-files.mjs +2 -1
  282. package/foundation/discovery/package-exports.d.mts +10 -0
  283. package/foundation/discovery/package-exports.mjs +56 -3
  284. package/foundation/discovery/prop-drift.mjs +9 -9
  285. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  286. package/foundation/discovery/runner-allowlist.mjs +2 -0
  287. package/foundation/discovery/stored-component-list.d.mts +43 -0
  288. package/foundation/discovery/stored-component-list.mjs +90 -0
  289. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  290. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  291. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  292. package/foundation/discovery/stored-self-audit.mjs +38 -18
  293. package/foundation/discovery/template-adapter.d.mts +53 -1
  294. package/foundation/discovery/template-adapter.mjs +176 -12
  295. package/foundation/discovery/template-icons.mjs +2 -1
  296. package/foundation/discovery/theme-discovery.mjs +31 -4
  297. package/foundation/discovery/theme-imports.d.mts +14 -0
  298. package/foundation/discovery/theme-imports.mjs +43 -1
  299. package/foundation/discovery/theming-targets.d.mts +6 -5
  300. package/foundation/discovery/theming-targets.mjs +31 -47
  301. package/foundation/doc-compiler/import.mjs +7 -1
  302. package/foundation/doc-compiler/inputs.mjs +3 -2
  303. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  304. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  305. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  306. package/foundation/env/semver.mjs +3 -1
  307. package/foundation/fonts/font-stylesheet.d.mts +38 -0
  308. package/foundation/fonts/font-stylesheet.mjs +141 -0
  309. package/foundation/fs/cache-eviction.d.mts +21 -0
  310. package/foundation/fs/cache-eviction.mjs +73 -0
  311. package/foundation/fs/exact-codec.d.mts +12 -2
  312. package/foundation/fs/exact-codec.mjs +23 -6
  313. package/foundation/fs/file-protection.mjs +4 -3
  314. package/foundation/fs/gather-cache.d.mts +62 -4
  315. package/foundation/fs/gather-cache.mjs +517 -91
  316. package/foundation/fs/jiti-cache.d.mts +19 -1
  317. package/foundation/fs/jiti-cache.mjs +130 -6
  318. package/foundation/fs/kept-tree.d.mts +60 -0
  319. package/foundation/fs/kept-tree.mjs +154 -0
  320. package/foundation/fs/listing-cache.d.mts +7 -0
  321. package/foundation/fs/listing-cache.mjs +10 -0
  322. package/foundation/fs/module-loader.d.mts +24 -2
  323. package/foundation/fs/module-loader.mjs +94 -21
  324. package/foundation/fs/paths.d.mts +18 -0
  325. package/foundation/fs/paths.mjs +15 -2
  326. package/foundation/fs/read-record.d.mts +9 -0
  327. package/foundation/fs/read-record.mjs +19 -11
  328. package/foundation/fs/stop-cleanup.d.mts +12 -0
  329. package/foundation/fs/stop-cleanup.mjs +66 -0
  330. package/foundation/identity/provider-identity.d.mts +6 -0
  331. package/foundation/identity/provider-identity.mjs +10 -1
  332. package/foundation/integrations/contribution-inventory.mjs +4 -3
  333. package/foundation/integrations/example-code.d.mts +63 -0
  334. package/foundation/integrations/example-code.mjs +416 -0
  335. package/foundation/integrations/public-imports.d.mts +9 -0
  336. package/foundation/integrations/public-imports.mjs +3 -2
  337. package/foundation/integrations/validate-contributions.mjs +17 -45
  338. package/foundation/render/embedded-files.d.mts +6 -0
  339. package/foundation/render/embedded-files.mjs +25 -5
  340. package/foundation/render/embedded-imports.d.mts +39 -7
  341. package/foundation/render/embedded-imports.mjs +66 -27
  342. package/foundation/render/file-header.d.mts +66 -0
  343. package/foundation/render/file-header.mjs +118 -0
  344. package/foundation/render/host-answer.d.mts +18 -0
  345. package/foundation/render/host-answer.mjs +46 -0
  346. package/foundation/render/host-exit.d.mts +1 -0
  347. package/foundation/render/host-exit.mjs +6 -1
  348. package/foundation/render/html-reader.d.mts +55 -2
  349. package/foundation/render/html-reader.mjs +145 -26
  350. package/foundation/render/markup-edits.d.mts +57 -0
  351. package/foundation/render/markup-edits.mjs +182 -0
  352. package/foundation/render/page-host.mjs +29 -12
  353. package/foundation/render/page-worker.mjs +121 -13
  354. package/foundation/render/picture-chrome.d.mts +4 -0
  355. package/foundation/render/picture-chrome.mjs +185 -0
  356. package/foundation/render/picture-playwright.d.mts +4 -0
  357. package/foundation/render/picture-playwright.mjs +34 -0
  358. package/foundation/render/rebuild.mjs +2 -1
  359. package/foundation/render/render-page.d.mts +35 -3
  360. package/foundation/render/render-page.mjs +641 -96
  361. package/foundation/render/source-block.d.mts +85 -6
  362. package/foundation/render/source-block.mjs +211 -20
  363. package/foundation/render/ts-paths.d.mts +69 -6
  364. package/foundation/render/ts-paths.mjs +326 -40
  365. package/foundation/response/error-codes.d.mts +3 -1
  366. package/foundation/response/error-codes.d.ts +1 -0
  367. package/foundation/response/error-codes.doc.mjs +12 -1
  368. package/foundation/response/error-codes.mjs +11 -1
  369. package/foundation/response/response-types.doc.mjs +2 -2
  370. package/foundation/text/compare-text.d.mts +14 -0
  371. package/foundation/text/compare-text.mjs +68 -0
  372. package/foundation/text/css-escape.d.mts +18 -0
  373. package/foundation/text/css-escape.mjs +35 -0
  374. package/foundation/text/string-utils.d.mts +3 -2
  375. package/foundation/text/string-utils.mjs +18 -4
  376. package/foundation/text/suggest-order.d.mts +9 -0
  377. package/foundation/text/suggest-order.mjs +15 -1
  378. package/foundation/xle/expand.mjs +2 -1
  379. package/host/index.mjs +8 -6
  380. package/package.json +7 -6
@@ -10,6 +10,8 @@
10
10
  * @position api/theme-edit — imported only by _adapter.mjs
11
11
  */
12
12
 
13
+ import {typoNear, wholeNumberOf} from './_normal.mjs';
14
+ import {IMPORTER_SCAN_MAX, pageImporters} from './_importers.mjs';
13
15
  import {parse as parseModule} from '@babel/parser';
14
16
  import * as fs from 'node:fs';
15
17
  import * as path from 'node:path';
@@ -63,9 +65,10 @@ import {template} from '../template/template.mjs';
63
65
  import {
64
66
  analyzeTemplateNeeds,
65
67
  extractImportedPackages,
68
+ parsedSpecifiers,
66
69
  } from '../../foundation/discovery/template-needs.mjs';
67
70
  import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
68
- import {requireProject, context} from './_context.mjs';
71
+ import {coreApp, requireProject, context} from './_context.mjs';
69
72
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
70
73
  import {
71
74
  formatCliCommand,
@@ -73,6 +76,7 @@ import {
73
76
  } from '../../foundation/env/package-manager.mjs';
74
77
  import {sha256} from '../../foundation/render/source-block.mjs';
75
78
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
79
+ import {compareText} from '../../foundation/text/compare-text.mjs';
76
80
 
77
81
  const E = ERROR_CODES;
78
82
 
@@ -179,11 +183,9 @@ function layoutImportsSheet(cwd, app, sheet, dir = app) {
179
183
  } catch {
180
184
  return false;
181
185
  }
182
- if (sheet.test(text)) return true;
183
- for (const m of text.matchAll(
184
- /(?:import|@import)\s*(?:[^'"]*from\s*)?(?:url\()?['"]([^'"]+)['"]/g,
185
- )) {
186
- const spec = m[1];
186
+ const specs = importSpecifiers(file, text);
187
+ if (specs.some(spec => sheet.test(spec))) return true;
188
+ for (const spec of specs) {
187
189
  // An alias the tsconfig sets; else `@/` is the src folder or the
188
190
  // project root.
189
191
  const alias = aliases.find(a => spec.startsWith(a.prefix));
@@ -209,6 +211,25 @@ function layoutImportsSheet(cwd, app, sheet, dir = app) {
209
211
  return starts.some(start => reads(start, 0));
210
212
  }
211
213
 
214
+ /**
215
+ * The modules a file imports, from its import statements: a script's
216
+ * through the shared reader of import statements (its syntax tree, so a
217
+ * comment or a string says nothing), or the `@import` rules of a stylesheet
218
+ * (comments left out).
219
+ * @param {string} file
220
+ * @param {string} text
221
+ * @returns {string[]}
222
+ */
223
+ function importSpecifiers(file, text) {
224
+ if (/\.(css|scss)$/.test(file))
225
+ return [
226
+ ...text
227
+ .replace(/\/\*[\s\S]*?\*\//g, '')
228
+ .matchAll(/@import\s+(?:url\()?\s*['"]([^'"]+)['"]/g),
229
+ ].map(m => m[1]);
230
+ return parsedSpecifiers(text);
231
+ }
232
+
212
233
  /**
213
234
  * The import aliases the app's tsconfig `paths` set (`~/*`, `#app/*`), each
214
235
  * with the folders it stands for.
@@ -238,55 +259,19 @@ function tsconfigAliases(cwd) {
238
259
  }
239
260
 
240
261
  /**
241
- * A note when the app never imports Core's stylesheet, or null: without
242
- * it, components render unstyled, and some show nothing. Read from the
243
- * files of the routes folder and src/ (best effort).
262
+ * A note when the preview's layouts never import Core's stylesheet, or
263
+ * null: without it, components render unstyled, and some show nothing.
264
+ * Judged by the real import statements of the layouts over the preview and
265
+ * the files they import, never by text in a comment or in a file the route
266
+ * does not reach.
244
267
  * @param {string} cwd
245
268
  * @param {{dir: string, app: string | null}} at
246
269
  * @returns {string | null}
247
270
  */
248
271
  function coreStylesheetMissing(cwd, at) {
249
272
  if (!at.app) return null;
250
- const SHEET = /@astryxdesign\/core\/astryx\.css/;
251
- let seen = 0;
252
- /** @param {string} folder @returns {boolean} */
253
- const imports = folder => {
254
- /** @type {fs.Dirent[]} */
255
- let entries;
256
- try {
257
- entries = fs.readdirSync(folder, {withFileTypes: true});
258
- } catch {
259
- return false;
260
- }
261
- for (const e of entries) {
262
- const full = path.join(folder, e.name);
263
- if (e.isDirectory()) {
264
- if (
265
- e.name === 'node_modules' ||
266
- e.name.startsWith('.') ||
267
- full === at.dir
268
- )
269
- continue;
270
- if (imports(full)) return true;
271
- } else if (
272
- /\.(tsx|ts|jsx|js|mjs|css|scss)$/.test(e.name) &&
273
- ++seen < 2000
274
- )
275
- try {
276
- if (SHEET.test(fs.readFileSync(full, 'utf8'))) return true;
277
- } catch {
278
- // Unreadable: skip it.
279
- }
280
- }
281
- return false;
282
- };
283
- const src = path.join(cwd, 'src');
284
- if (
285
- imports(at.app) ||
286
- (at.app.startsWith(src + path.sep) ? false : imports(src)) ||
287
- layoutImportsSheet(cwd, at.app, SHEET, at.dir)
288
- )
289
- return null;
273
+ const SHEET = /^@astryxdesign\/core\/astryx\.css$/;
274
+ if (layoutImportsSheet(cwd, at.app, SHEET, at.dir)) return null;
290
275
  const layout = ['tsx', 'ts', 'jsx', 'js']
291
276
  .map(x => path.join(at.app ?? '', `layout.${x}`))
292
277
  .find(f => fs.existsSync(f));
@@ -562,6 +547,56 @@ function nextConfigNotes(cwd) {
562
547
  * @param {string} dir
563
548
  */
564
549
  function reservedFolder(cwd, dir) {
550
+ // The rules of every app the folder is in: the project's, and a Next app
551
+ // below it that holds the folder (a workspace app, from the root).
552
+ for (const owner of appsOver(cwd, dir)) {
553
+ const why = reservedIn(owner, dir);
554
+ if (why) return why;
555
+ }
556
+ return null;
557
+ }
558
+
559
+ /**
560
+ * The app folders that hold `dir`, nearest first: each Next app between it
561
+ * and the project root (a workspace app, a starter app an earlier
562
+ * `preview app` made), then the project root itself.
563
+ * @param {string} cwd
564
+ * @param {string} dir
565
+ * @returns {string[]}
566
+ */
567
+ function appsOver(cwd, dir) {
568
+ /** @type {string[]} */
569
+ const out = [];
570
+ for (
571
+ let at = path.dirname(path.resolve(dir));
572
+ at.startsWith(path.resolve(cwd) + path.sep);
573
+ at = path.dirname(at)
574
+ )
575
+ if (nextAppAt(at)) out.push(at);
576
+ return [...out, cwd];
577
+ }
578
+
579
+ /**
580
+ * Whether a folder is a Next app: its package.json depends on `next`.
581
+ * @param {string} dir
582
+ */
583
+ function nextAppAt(dir) {
584
+ try {
585
+ const pkg = JSON.parse(
586
+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),
587
+ );
588
+ return ['dependencies', 'devDependencies'].some(k => pkg?.[k]?.next);
589
+ } catch {
590
+ return false;
591
+ }
592
+ }
593
+
594
+ /**
595
+ * {@link reservedFolder} for one app folder.
596
+ * @param {string} cwd the app folder
597
+ * @param {string} dir
598
+ */
599
+ function reservedIn(cwd, dir) {
565
600
  const segs = shown(cwd, dir).split('/').filter(Boolean);
566
601
  if (segs[0] === 'themes')
567
602
  return 'themes/ holds the themes, and everything in a theme folder is copied with the theme';
@@ -588,6 +623,21 @@ function reservedFolder(cwd, dir) {
588
623
  return null;
589
624
  }
590
625
 
626
+ /**
627
+ * The compile of an editor theme as it runs from the folder the command ran
628
+ * in: an editor theme compiles from the app root, so from a subfolder the
629
+ * line goes there first.
630
+ * @param {string} cwd the app root
631
+ * @param {string} slug
632
+ */
633
+ function compileFromHere(cwd, slug) {
634
+ const line = `${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)}`;
635
+ const up = path.relative(process.cwd(), cwd);
636
+ return up && path.resolve(process.cwd()) !== path.resolve(cwd)
637
+ ? `cd ${quoteCommandArgument(up.split(path.sep).join('/'))} && ${line}`
638
+ : line;
639
+ }
640
+
591
641
  /**
592
642
  * The app's tsconfig.json compiler options (comments and trailing commas
593
643
  * allowed), or null when there is none.
@@ -645,9 +695,7 @@ function typeScriptNotes(cwd, dir, added) {
645
695
  `the app has no TypeScript, and the preview's files are .tsx, so the next build sets it up; to do it now: ${installLine(cwd, ['typescript', '@types/react', '@types/node']).replace(/ (add|install) /, ' $1 -D ')}`,
646
696
  ];
647
697
  }
648
- const templates = added.filter(
649
- id => !['overview', 'components', COLORS_PAGE.id].includes(id),
650
- );
698
+ const templates = added.filter(id => !DEFAULT_PAGE_IDS.includes(id));
651
699
  if (options.noUncheckedIndexedAccess !== true || !templates.length) return [];
652
700
  const files = templates.map(id =>
653
701
  shown(cwd, path.join(dir, PAGES_DIR, `${id}.tsx`)),
@@ -857,6 +905,14 @@ function nestedRootLayouts(app) {
857
905
  * @param {Retry} retry
858
906
  */
859
907
  function checkPlacement(cwd, dir, where, retry) {
908
+ // A folder in a Next app below the project (a workspace app, from the
909
+ // root) gets that app's own checks: its routes folder, its next.config,
910
+ // its root layouts. Retries keep the folder as given from here.
911
+ const owner = appsOver(cwd, dir)[0];
912
+ if (owner !== cwd)
913
+ return checkPlacement(owner, dir, where, p =>
914
+ retry(p == null ? null : shown(cwd, path.resolve(owner, p))),
915
+ );
860
916
  const served = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(
861
917
  r => fs.existsSync(r) && fs.statSync(r).isDirectory(),
862
918
  );
@@ -935,7 +991,9 @@ function checkPlacement(cwd, dir, where, retry) {
935
991
  const odd = segs.filter(
936
992
  seg => seg && !/^\(.+\)$|^\[.+\]$/.test(seg) && !PLAIN.test(seg),
937
993
  );
938
- if (app && odd.length) {
994
+ // A preview already there is updated where it is (its pages are served at
995
+ // the encoded URL `see` gives); only a new preview gets a plain name.
996
+ if (app && odd.length && !fs.existsSync(path.join(dir, PREVIEW_DATA))) {
939
997
  const slug = (/** @type {string} */ seg) =>
940
998
  seg
941
999
  .normalize('NFD')
@@ -999,7 +1057,12 @@ function checkPlacement(cwd, dir, where, retry) {
999
1057
  if (served && app !== served)
1000
1058
  refuse(
1001
1059
  E.ERR_INVALID_ARGUMENT,
1002
- `${where} is in ${shown(cwd, app)}/, and Next serves ${shown(cwd, served)}/ instead when both are there.`,
1060
+ // Next serves the root app/ when both are there: a preview in src/app/
1061
+ // under a root app/ is not served, and a new root app/ beside the
1062
+ // app's src/app/ would hide the whole app.
1063
+ path.resolve(app) === path.join(path.resolve(cwd), 'app')
1064
+ ? `${where} would make ${shown(cwd, app)}/ beside ${shown(cwd, served)}/, and Next serves the root app/ when both are there, so the whole app in ${shown(cwd, served)}/ would stop being served.`
1065
+ : `${where} is in ${shown(cwd, app)}/, and Next serves ${shown(cwd, served)}/ instead when both are there.`,
1003
1066
  {
1004
1067
  run: fs.existsSync(path.join(dir, PREVIEW_DATA))
1005
1068
  ? [
@@ -1010,9 +1073,7 @@ function checkPlacement(cwd, dir, where, retry) {
1010
1073
  );
1011
1074
  const exts = readNextConfig(cwd).pageExtensions;
1012
1075
  if (exts && !exts.includes('tsx')) {
1013
- let free = 'theme-app';
1014
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1015
- free = `theme-app-${n}`;
1076
+ const free = freeAppFolder(cwd);
1016
1077
  refuse(
1017
1078
  E.ERR_INVALID_ARGUMENT,
1018
1079
  `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx, the route file the preview writes.`,
@@ -1020,7 +1081,7 @@ function checkPlacement(cwd, dir, where, retry) {
1020
1081
  fix: 'add "tsx" to pageExtensions to use the preview in this app',
1021
1082
  run: [
1022
1083
  `${retry(shown(cwd, dir))} # once "tsx" is in pageExtensions`,
1023
- `${PREVIEW} app ${free} # or a new app of its own, with the preview`,
1084
+ `${appCommand(free)} # or a new app of its own, with the preview`,
1024
1085
  ],
1025
1086
  },
1026
1087
  );
@@ -1031,16 +1092,14 @@ function checkPlacement(cwd, dir, where, retry) {
1031
1092
  !rootLayouts.length &&
1032
1093
  !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)))
1033
1094
  ) {
1034
- let free = 'theme-app';
1035
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1036
- free = `theme-app-${n}`;
1095
+ const free = freeAppFolder(cwd);
1037
1096
  refuse(
1038
1097
  E.ERR_INVALID_ARGUMENT,
1039
1098
  `${shown(cwd, served ?? app)}/ has no root layout (no layout.tsx in it or in a route group)${served ? '' : ' and is not there yet'}, so Next cannot build a page in ${where}.`,
1040
1099
  {
1041
1100
  fix: `add a root layout to ${shown(cwd, served ?? app)}/ to use the preview in this app`,
1042
1101
  run: [
1043
- `${PREVIEW} app ${free} # a new app with its own root layout and the preview`,
1102
+ `${appCommand(free)} # a new app with its own root layout and the preview`,
1044
1103
  ],
1045
1104
  },
1046
1105
  );
@@ -1078,7 +1137,9 @@ function checkPlacement(cwd, dir, where, retry) {
1078
1137
  * serves (`app/`, else `src/app/`).
1079
1138
  * @param {string} cwd
1080
1139
  * @param {string | undefined} where
1081
- * @param {{optional?: boolean, write?: boolean, retry?: Retry}} [opts]
1140
+ * @param {{optional?: boolean, write?: boolean, retry?: Retry, theme?: string | null}} [opts]
1141
+ * `theme`: the theme the command was given, kept by a pointer to a new
1142
+ * starter app
1082
1143
  * `optional`: null instead of a refusal when there is no routes folder;
1083
1144
  * `write`: the folder is checked as a place to write; `retry`: the
1084
1145
  * command again with another --path, for refusals
@@ -1092,17 +1153,44 @@ function previewDir(cwd, where, opts = {}) {
1092
1153
  const routes = ['app', path.join('src', 'app')]
1093
1154
  .map(r => path.join(cwd, r))
1094
1155
  .filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
1095
- const appOf = (/** @type {string} */ dir) =>
1096
- routes.find(r => dir.startsWith(r + path.sep)) ?? null;
1156
+ // The routes folder of the app that holds the folder (a workspace app's,
1157
+ // from the root).
1158
+ const appOf = (/** @type {string} */ dir) => {
1159
+ const owner = appsOver(cwd, dir)[0];
1160
+ return (
1161
+ [path.join(owner, 'app'), path.join(owner, 'src', 'app')].find(r =>
1162
+ dir.startsWith(r + path.sep),
1163
+ ) ?? null
1164
+ );
1165
+ };
1097
1166
  if (where != null) {
1098
1167
  checkFolderName(where, '--path', retry);
1099
1168
  /** @type {string} */
1100
1169
  let dir;
1170
+ // A --path read from the folder the command ran in; one that names a
1171
+ // preview from the project root (as every printed folder is) is read
1172
+ // from there, so a printed tip works from a subfolder too.
1173
+ const fromRoot = (() => {
1174
+ // The --path as given from the subfolder the command ran in, rebased
1175
+ // onto the project root by the caller: when that names no folder and
1176
+ // the path without the subfolder names a preview, that one.
1177
+ const sub = path.relative(cwd, process.cwd());
1178
+ if (!sub || sub.startsWith('..') || path.isAbsolute(where)) return null;
1179
+ const given = path.normalize(where);
1180
+ if (!given.startsWith(sub + path.sep)) return null;
1181
+ const there = path.resolve(cwd, given.slice(sub.length + 1));
1182
+ return !fs.existsSync(path.resolve(cwd, where)) &&
1183
+ fs.existsSync(path.join(there, PREVIEW_DATA))
1184
+ ? there
1185
+ : null;
1186
+ })();
1101
1187
  try {
1102
- dir = assertWithin(path.resolve(cwd, where), cwd, {
1103
- allowAbsolute: true,
1104
- label: '--path',
1105
- });
1188
+ dir =
1189
+ fromRoot ??
1190
+ assertWithin(path.resolve(cwd, where), cwd, {
1191
+ allowAbsolute: true,
1192
+ label: '--path',
1193
+ });
1106
1194
  } catch (e) {
1107
1195
  if (e instanceof PathSafetyError)
1108
1196
  refuse(
@@ -1164,11 +1252,11 @@ function previewDir(cwd, where, opts = {}) {
1164
1252
  const candidates = routes.map(r => path.join(r, 'theme-preview'));
1165
1253
  const known = candidates.find(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
1166
1254
  if (!known && opts.retry) {
1167
- // A preview added with --path is recorded with its theme, so a later
1168
- // command finds it without the flag instead of starting a second one.
1169
- const recorded = [
1170
- ...new Set(editedThemes(cwd).flatMap(t => recordedPreviews(cwd, t))),
1171
- ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
1255
+ // A preview added with --path is recorded with its theme, and one
1256
+ // renamed by hand is found in the routes folders (as list, remove and
1257
+ // see find it), so a later command uses it instead of starting a second
1258
+ // one.
1259
+ const recorded = allPreviews(cwd);
1172
1260
  if (recorded.length === 1) {
1173
1261
  inProjectOrRefuse(cwd, recorded[0], retry);
1174
1262
  if (opts.write)
@@ -1198,23 +1286,46 @@ function previewDir(cwd, where, opts = {}) {
1198
1286
  const dir = known ?? (served && path.join(nested ?? served, 'theme-preview'));
1199
1287
  if (!dir && opts.optional) return /** @type {any} */ (null);
1200
1288
  if (!dir) {
1201
- // A workspace root: the Next apps below it, each with a --path into
1202
- // its routes folder.
1289
+ // A workspace root: the Next apps below it.
1203
1290
  const apps = nextAppsUnder(cwd);
1291
+ const rootIsProject = coreApp(cwd) === path.resolve(cwd);
1292
+ const themesHere = editedThemes(cwd);
1293
+ // The starter carries a theme this folder holds; a theme a workspace
1294
+ // app holds is reached from that app, as `preview app` itself says.
1295
+ const starterTheme =
1296
+ opts.theme != null
1297
+ ? themesHere.includes(opts.theme)
1298
+ ? opts.theme
1299
+ : null
1300
+ : themesHere.length === 1
1301
+ ? themesHere[0]
1302
+ : null;
1303
+ const themeOwner =
1304
+ opts.theme != null && !starterTheme
1305
+ ? apps.find(a =>
1306
+ fs.existsSync(themeFiles(a.root, opts.theme ?? '').settings),
1307
+ )
1308
+ : undefined;
1204
1309
  refuse(
1205
1310
  E.ERR_NOT_FOUND,
1206
1311
  apps.length
1207
1312
  ? `No app routes folder here (app/ or src/app/); the Next ${apps.length > 1 ? 'apps' : 'app'} below ${apps.length > 1 ? 'are' : 'is'} ${apps.map(a => `${shown(cwd, a.root)}/`).join(', ')}.`
1208
1313
  : 'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
1209
1314
  {
1315
+ // The same command for each app below, with every argument kept: a
1316
+ // root that is a project (its themes are here) reaches the app with
1317
+ // --path; any other root runs it from the app's own folder.
1210
1318
  run: [
1211
1319
  ...apps
1212
1320
  .slice(0, 3)
1213
- .map(
1214
- a =>
1215
- `${PREVIEW} add --path ${quoteCommandArgument(shown(cwd, path.join(a.routes, 'theme-preview')))}`,
1321
+ .map(a =>
1322
+ rootIsProject
1323
+ ? retry(shown(cwd, path.join(a.routes, 'theme-preview')))
1324
+ : `${cdTo(shown(cwd, a.root))} && ${retry(null)}`,
1216
1325
  ),
1217
- `${PREVIEW} app theme-app # a new starter app with the preview in it`,
1326
+ themeOwner
1327
+ ? `${cdTo(shown(cwd, themeOwner.root))} && ${appCommand(freeAppFolder(themeOwner.root), opts.theme)} # a new starter app with the preview in it`
1328
+ : `${appCommand(freeAppFolder(cwd), starterTheme)} # a new starter app with the preview in it`,
1218
1329
  ],
1219
1330
  },
1220
1331
  );
@@ -1224,6 +1335,80 @@ function previewDir(cwd, where, opts = {}) {
1224
1335
  return {dir, app: appOf(dir)};
1225
1336
  }
1226
1337
 
1338
+ /**
1339
+ * Whether `preview add` takes this folder (null: its usual one): the checks
1340
+ * add itself runs before it writes, run here with nothing written. A
1341
+ * pointer to `preview add` is offered only when this says so.
1342
+ * @param {string} cwd
1343
+ * @param {string | null} where
1344
+ */
1345
+ function addTakes(cwd, where) {
1346
+ try {
1347
+ previewDir(cwd, where ?? undefined, {write: true, retry: () => ''});
1348
+ return true;
1349
+ } catch {
1350
+ return false;
1351
+ }
1352
+ }
1353
+
1354
+ /**
1355
+ * `preview app` for a folder, as a shell runs it: flags first, and a name
1356
+ * that starts with `-` after `--`, which the command would read as an
1357
+ * option. The one way every pointer to `preview app` is written; the
1358
+ * adapter rebases its folder onto the folder the command ran in.
1359
+ * @param {string} folder
1360
+ * @param {string | null} [theme]
1361
+ */
1362
+ function appCommand(folder, theme = null) {
1363
+ const flags = theme == null ? '' : ` --theme ${quoteCommandArgument(theme)}`;
1364
+ return folder.startsWith('-')
1365
+ ? `${PREVIEW} app${flags} -- ${quoteCommandArgument(folder)}`
1366
+ : `${PREVIEW} app ${quoteCommandArgument(folder)}${flags}`;
1367
+ }
1368
+
1369
+ /**
1370
+ * A `cd` to a folder as a shell runs it: quoted, and a name that starts with
1371
+ * `-` given as `./-name`, which `cd` would read as an option.
1372
+ * @param {string} folder
1373
+ */
1374
+ function cdTo(folder) {
1375
+ return `cd ${quoteCommandArgument(folder.startsWith('-') ? `./${folder}` : folder)}`;
1376
+ }
1377
+
1378
+ /**
1379
+ * A folder name for a new starter app that is free in `cwd`: theme-app, else
1380
+ * theme-app-2, theme-app-3 and so on.
1381
+ * @param {string} cwd
1382
+ */
1383
+ function freeAppFolder(cwd) {
1384
+ return shown(cwd, freeFolder(cwd, cwd, 'theme-app'));
1385
+ }
1386
+
1387
+ /**
1388
+ * A folder in `parent` that `preview app` takes: `base`, else `base-2`,
1389
+ * `base-3` and so on, passing over a name that is there in any form (a
1390
+ * file, a folder, a dangling link), one that differs from a name there only
1391
+ * in case, and a folder no app goes in.
1392
+ * @param {string} cwd the project
1393
+ * @param {string} parent
1394
+ * @param {string} base
1395
+ * @returns {string} the folder, absolute
1396
+ */
1397
+ function freeFolder(cwd, parent, base) {
1398
+ /** @param {string} f */
1399
+ const taken = f => {
1400
+ try {
1401
+ fs.lstatSync(f);
1402
+ return true;
1403
+ } catch {
1404
+ return Boolean(sameCaseSibling(f) || reservedFolder(cwd, f));
1405
+ }
1406
+ };
1407
+ let free = path.join(parent, base);
1408
+ for (let n = 2; taken(free); n++) free = path.join(parent, `${base}-${n}`);
1409
+ return free;
1410
+ }
1411
+
1227
1412
  /**
1228
1413
  * The Next apps in folders below `cwd` (a few levels, node_modules left
1229
1414
  * out): each folder with a package.json that depends on `next` and a routes
@@ -1258,7 +1443,7 @@ function nextAppsUnder(cwd) {
1258
1443
  }
1259
1444
  };
1260
1445
  walk(cwd, 1);
1261
- return out.sort((a, b) => a.root.localeCompare(b.root));
1446
+ return out.sort((a, b) => compareText(a.root, b.root));
1262
1447
  }
1263
1448
 
1264
1449
  /**
@@ -1281,7 +1466,7 @@ export function addWiring(cwd, slug, mode = 'system') {
1281
1466
  : [
1282
1467
  `${slug} is ${mode}-only: give the <Theme> that theme add's wiring puts in the app root mode="${mode}" (<Theme theme={…} mode="${mode}">); the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
1283
1468
  ]),
1284
- `every set and undo builds the theme and its app copy again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)} builds both again`,
1469
+ `every set and undo builds the theme and its app copy again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${compileFromHere(cwd, slug)} builds both again`,
1285
1470
  ];
1286
1471
  }
1287
1472
 
@@ -1324,7 +1509,7 @@ export function appWiring(ctx, slug, data) {
1324
1509
  return [
1325
1510
  ...(blocker
1326
1511
  ? [
1327
- `${blocker} is not the editor's, so the editor does not write the theme's app copy in src/themes/${slug}/ (and theme add does not take it); the steps by hand:`,
1512
+ `the app copy in src/themes/${slug}/ was not updated: ${blocker}; the steps by hand:`,
1328
1513
  ]
1329
1514
  : []),
1330
1515
  `in ${where}, import the theme and its stylesheets: import {Theme} from '@astryxdesign/core/theme'; import {${name}} from '${ti.module.replace(/\.js$/, '')}'; ${ti.css.map(c => `import '${c}';`).join(' ')}`,
@@ -1334,7 +1519,7 @@ export function appWiring(ctx, slug, data) {
1334
1519
  `${appModule} (written by theme add and use) stays as it is: to keep its themes too, merge them in your own file ({...themes, ${JSON.stringify(slug)}: ${name}}), never in ${appModule}, which add, use and remove write again`,
1335
1520
  ]
1336
1521
  : []),
1337
- `every set and undo builds ${shown(cwd, themeFiles(cwd, slug).js)} and ${shown(cwd, themeFiles(cwd, slug).css)} again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)} builds it again`,
1522
+ `every set and undo builds ${shown(cwd, themeFiles(cwd, slug).js)} and ${shown(cwd, themeFiles(cwd, slug).css)} again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${compileFromHere(cwd, slug)} builds it again`,
1338
1523
  ];
1339
1524
  }
1340
1525
 
@@ -1391,7 +1576,7 @@ function inProjectOrRefuse(cwd, dir, retry) {
1391
1576
  run: [
1392
1577
  within(path.dirname(dir))
1393
1578
  ? retry(shown(cwd, free))
1394
- : `${PREVIEW} app theme-app # a new app of its own, inside this folder`,
1579
+ : `${appCommand(freeAppFolder(cwd))} # a new app of its own, inside this folder`,
1395
1580
  ],
1396
1581
  },
1397
1582
  );
@@ -1488,8 +1673,16 @@ export default function Home() {
1488
1673
  */
1489
1674
  function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1490
1675
  const again = (/** @type {string | null} */ p) =>
1491
- `${PREVIEW} app ${quoteCommandArgument(p ?? 'theme-app')}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`;
1492
- checkFolderName(where, 'The app folder', again);
1676
+ appCommand(p ?? freeAppFolder(cwd), slug);
1677
+ // A repaired name (trimmed, with "/" for "\\") is offered only free: the
1678
+ // first free folder from it, as every other suggested folder is.
1679
+ checkFolderName(where, 'The app folder', p => {
1680
+ if (p == null) return again(null);
1681
+ const at = path.resolve(cwd, p);
1682
+ return again(
1683
+ shown(cwd, freeFolder(cwd, path.dirname(at), path.basename(at))),
1684
+ );
1685
+ });
1493
1686
  /** @type {string} */
1494
1687
  let root;
1495
1688
  try {
@@ -1501,44 +1694,48 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1501
1694
  if (e instanceof PathSafetyError)
1502
1695
  refuse(
1503
1696
  E.ERR_PATH_TRAVERSAL,
1504
- `${where} is outside the current folder; make the app inside the folder you run the command from.`,
1697
+ `${where} is outside the project; make the app inside the project folder.`,
1505
1698
  {run: [again(null)]},
1506
1699
  );
1507
1700
  throw e;
1508
1701
  }
1509
1702
  /** A free folder name inside the current folder, near `dir`. @param {string} dir */
1510
- const freeNear = dir => {
1511
- const parent = dir === cwd ? cwd : path.dirname(dir);
1512
- const base = dir === cwd ? 'theme-app' : `${path.basename(dir)}-preview`;
1513
- let free = base;
1514
- for (let n = 2; fs.existsSync(path.join(parent, free)); n++)
1515
- free = `${base}-${n}`;
1516
- return shown(cwd, path.join(parent, free));
1517
- };
1703
+ const freeNear = dir =>
1704
+ dir === cwd
1705
+ ? freeAppFolder(cwd)
1706
+ : shown(
1707
+ cwd,
1708
+ freeFolder(cwd, path.dirname(dir), `${path.basename(dir)}-preview`),
1709
+ );
1518
1710
  const name = shownDir(cwd, root);
1519
- const routes = ['app', path.join('src', 'app')]
1520
- .map(r => path.join(cwd, r))
1711
+ // The routes folders of every app the folder is in (the project's, and a
1712
+ // workspace app's from the root).
1713
+ const routes = appsOver(cwd, root)
1714
+ .flatMap(a => ['app', path.join('src', 'app')].map(r => path.join(a, r)))
1521
1715
  .filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
1716
+ const inRoutes = routes.find(
1717
+ r => root === r || root.startsWith(r + path.sep),
1718
+ );
1522
1719
  const why =
1523
1720
  reservedFolder(cwd, root) ??
1524
- (routes.some(r => root === r || root.startsWith(r + path.sep))
1525
- ? "it is inside this app's routes folder, where Next would serve the new app's files as pages of this one"
1721
+ (inRoutes
1722
+ ? `it is inside the routes folder ${shownDir(cwd, inRoutes)}/, where Next would serve the new app's files as pages of that app`
1526
1723
  : null) ??
1527
1724
  (t =>
1528
1725
  t
1529
1726
  ? `${shownDir(cwd, t)}/ differs from it only in case, and on macOS and Windows they are one folder`
1530
1727
  : null)(sameCaseSibling(root));
1531
1728
  if (why) {
1532
- let free = 'theme-app';
1533
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1534
- free = `theme-app-${n}`;
1729
+ const free = freeAppFolder(cwd);
1535
1730
  refuse(
1536
1731
  E.ERR_INVALID_ARGUMENT,
1537
1732
  `${name} is no place for a new app: ${why}.`,
1538
1733
  {
1539
1734
  run: [
1540
1735
  again(free),
1541
- `${PREVIEW} add # the preview inside this app instead`,
1736
+ ...(addTakes(cwd, null)
1737
+ ? [`${PREVIEW} add # the preview inside this app instead`]
1738
+ : []),
1542
1739
  ],
1543
1740
  },
1544
1741
  );
@@ -1590,7 +1787,7 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1590
1787
  file,
1591
1788
  text:
1592
1789
  key === 'package.json'
1593
- ? starterPackageJson(text, dependencies)
1790
+ ? starterPackageJson(text, dependencies, starterName(cwd, root))
1594
1791
  : key === 'src/app/page.tsx'
1595
1792
  ? STARTER_HOME
1596
1793
  : key === 'src/app/layout.tsx'
@@ -1623,18 +1820,45 @@ function starterLayout(text) {
1623
1820
  }
1624
1821
 
1625
1822
  /**
1626
- * The starter's package.json with the Astryx packages pinned to this CLI's
1627
- * release, and `dependencies` added.
1823
+ * The new app's package name, from its folder's path in the project: two
1824
+ * starter apps in one workspace never share a name, which would break the
1825
+ * whole workspace's install.
1826
+ * @param {string} cwd the project root
1827
+ * @param {string} root the new app's folder
1828
+ */
1829
+ function starterName(cwd, root) {
1830
+ // One spelling per path, no two paths alike: lowercase letters, digits
1831
+ // and `-` stay; a folder break is `.`; every other character (a capital,
1832
+ // a dot, an accent) is `_<its code point in hex>_`.
1833
+ const rel = (path.relative(cwd, root) || path.basename(root))
1834
+ .split(path.sep)
1835
+ .map(seg =>
1836
+ [...seg]
1837
+ .map(c =>
1838
+ /[a-z0-9-]/.test(c)
1839
+ ? c
1840
+ : `_${/** @type {number} */ (c.codePointAt(0)).toString(16)}_`,
1841
+ )
1842
+ .join(''),
1843
+ )
1844
+ .join('.');
1845
+ return `astryx-theme-preview-${rel}`;
1846
+ }
1847
+
1848
+ /**
1849
+ * The starter's package.json with its name, the Astryx packages pinned to
1850
+ * this CLI's release, and `dependencies` added.
1628
1851
  * @param {string} text
1629
1852
  * @param {Record<string, string>} dependencies
1853
+ * @param {string} name the package name
1630
1854
  */
1631
- function starterPackageJson(text, dependencies) {
1855
+ function starterPackageJson(text, dependencies, name) {
1632
1856
  const pinned = text.replaceAll('{{astryxVersion}}', cliVersion());
1633
- if (!Object.keys(dependencies).length) return pinned;
1634
1857
  const pkg = JSON.parse(pinned);
1858
+ pkg.name = name;
1635
1859
  pkg.dependencies = Object.fromEntries(
1636
1860
  Object.entries({...pkg.dependencies, ...dependencies}).sort(([a], [b]) =>
1637
- a.localeCompare(b),
1861
+ compareText(a, b),
1638
1862
  ),
1639
1863
  );
1640
1864
  return `${JSON.stringify(pkg, null, 2)}\n`;
@@ -1696,7 +1920,16 @@ function writeStarterApp(cwd, plan, again) {
1696
1920
  refuse(
1697
1921
  E.ERR_FILE_EXISTS,
1698
1922
  `${shownDir(cwd, root)} was filled by something else while the app was written, so the app was not put there.`,
1699
- {run: [again(`${shownDir(cwd, root)}-2`)]},
1923
+ {
1924
+ run: [
1925
+ again(
1926
+ shown(
1927
+ cwd,
1928
+ freeFolder(cwd, path.dirname(root), path.basename(root)),
1929
+ ),
1930
+ ),
1931
+ ],
1932
+ },
1700
1933
  );
1701
1934
  refuse(
1702
1935
  E.ERR_WRITE_FAILED,
@@ -2339,12 +2572,10 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2339
2572
  2,
2340
2573
  )}\n`,
2341
2574
  );
2342
- commitStep('pending');
2343
2575
  for (const w of writes) {
2344
2576
  current = path.join(dir, w.rel);
2345
2577
  touched.push({file: current, before: before(current)});
2346
2578
  fs.renameSync(tmp(current), current);
2347
- commitStep('rename');
2348
2579
  }
2349
2580
  staged.length = 0;
2350
2581
  step = 'removed';
@@ -2354,7 +2585,6 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2354
2585
  if (was == null) continue;
2355
2586
  touched.push({file: current, before: was});
2356
2587
  fs.rmSync(current);
2357
- commitStep('delete');
2358
2588
  }
2359
2589
  step = 'written';
2360
2590
  current = path.join(dir, PREVIEW_DATA);
@@ -2363,8 +2593,6 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2363
2593
  fs.renameSync(tmp(current), current);
2364
2594
  fs.rmSync(pendingFile, {force: true});
2365
2595
  } catch (e) {
2366
- // A stop injected by a test stands for a kill: nothing is put back.
2367
- if (e === STOPPED) throw e;
2368
2596
  fs.rmSync(pendingFile, {force: true});
2369
2597
  for (const t of staged) fs.rmSync(t, {force: true});
2370
2598
  for (const t of touched.reverse())
@@ -2392,21 +2620,6 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2392
2620
  /** The step record a preview change leaves while it runs. */
2393
2621
  const PENDING = '.theme-preview.pending.json';
2394
2622
 
2395
- /** What a test throws to stop a change part way, as a kill would. */
2396
- const STOPPED = Symbol('stopped');
2397
-
2398
- /** @type {((step: string) => boolean) | null} */
2399
- let stopAt = null;
2400
-
2401
- /**
2402
- * For tests: stop the next preview changes at the step where `when`
2403
- * returns true, as a kill would, with nothing put back. Null clears it.
2404
- * @param {((step: string) => boolean) | null} when
2405
- */
2406
- export function stopPreviewCommitAt(when) {
2407
- stopAt = when;
2408
- }
2409
-
2410
2623
  /** Whether a process is running here. @param {number} pid */
2411
2624
  function alive(pid) {
2412
2625
  if (pid === process.pid) return true;
@@ -2418,191 +2631,6 @@ function alive(pid) {
2418
2631
  }
2419
2632
  }
2420
2633
 
2421
- /** @param {string} step */
2422
- function commitStep(step) {
2423
- if (stopAt?.(step)) throw STOPPED;
2424
- }
2425
-
2426
- /** Folders the importer search never enters: installs and build output. */
2427
- const NOT_SOURCE = new Set([
2428
- 'node_modules',
2429
- 'out',
2430
- 'dist',
2431
- 'build',
2432
- 'coverage',
2433
- ]);
2434
-
2435
- /** At most this many source files are read; past it, nothing is deleted. */
2436
- let IMPORTER_SCAN_MAX = 50000;
2437
-
2438
- /**
2439
- * For tests: read at most `n` source files when checking for importers
2440
- * (null: the default).
2441
- * @param {number | null} n
2442
- */
2443
- export function setImporterScanMax(n) {
2444
- IMPORTER_SCAN_MAX = n ?? 50000;
2445
- }
2446
-
2447
- /**
2448
- * Files of the project's own that import any of `targets` (preview files
2449
- * about to be deleted), so deleting them would break the app's build. The
2450
- * whole project root is read: every .ts/.tsx/.js/.jsx/.mjs/.cjs/.mdx file
2451
- * outside node_modules, build output and dot folders, the preview's own
2452
- * files left out. Each file's import and export-from declarations,
2453
- * import() and require() calls (a string or a template with no
2454
- * substitution) are read from its syntax tree and resolved: relative,
2455
- * `@/`, or a tsconfig `paths` alias. `tooBig` when the project holds more
2456
- * source files than are read, so the caller refuses instead of guessing.
2457
- * @param {string} cwd
2458
- * @param {PreviewData} data
2459
- * @param {string} dir the preview folder
2460
- * @param {string[]} targets absolute paths, without extension
2461
- * @returns {{importers: string[], tooBig: boolean}}
2462
- */
2463
- function pageImporters(cwd, data, dir, targets) {
2464
- const wanted = new Set(targets);
2465
- if (!wanted.size) return {importers: [], tooBig: false};
2466
- const names = [...new Set(targets.map(t => path.basename(t)))];
2467
- const own = new Set(data.files.map(f => path.join(dir, f)));
2468
- const aliases = tsconfigAliases(cwd);
2469
- /** @type {Set<string>} */
2470
- const out = new Set();
2471
- let files = 0;
2472
- let tooBig = false;
2473
- /** @param {string} file @param {string} spec */
2474
- const resolves = (file, spec) => {
2475
- const alias = aliases.find(x => spec.startsWith(x.prefix));
2476
- const bases = alias
2477
- ? alias.to.map(t => path.join(t, spec.slice(alias.prefix.length)))
2478
- : spec.startsWith('@/')
2479
- ? [path.join(cwd, 'src', spec.slice(2)), path.join(cwd, spec.slice(2))]
2480
- : spec.startsWith('.')
2481
- ? [path.resolve(path.dirname(file), spec)]
2482
- : [];
2483
- return bases.some(
2484
- b =>
2485
- wanted.has(b.replace(/\.(tsx|ts|jsx|js|mjs|cjs)$/, '')) ||
2486
- wanted.has(path.join(b, 'index')),
2487
- );
2488
- };
2489
- /** @param {any} node @param {(spec: string) => void} found */
2490
- const specifiers = (node, found) => {
2491
- if (!node || typeof node !== 'object') return;
2492
- if (Array.isArray(node)) {
2493
- for (const x of node) specifiers(x, found);
2494
- return;
2495
- }
2496
- const text = (/** @type {any} */ n) =>
2497
- n?.type === 'StringLiteral'
2498
- ? n.value
2499
- : n?.type === 'TemplateLiteral' && n.expressions.length === 0
2500
- ? n.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
2501
- : null;
2502
- if (
2503
- (node.type === 'ImportDeclaration' ||
2504
- node.type === 'ExportNamedDeclaration' ||
2505
- node.type === 'ExportAllDeclaration') &&
2506
- node.source
2507
- ) {
2508
- const t = text(node.source);
2509
- if (t != null) found(t);
2510
- } else if (node.type === 'ImportExpression') {
2511
- const t = text(node.source);
2512
- if (t != null) found(t);
2513
- } else if (
2514
- node.type === 'CallExpression' &&
2515
- (node.callee?.type === 'Import' ||
2516
- (node.callee?.type === 'Identifier' && node.callee.name === 'require'))
2517
- ) {
2518
- const t = text(node.arguments?.[0]);
2519
- if (t != null) found(t);
2520
- } else if (
2521
- node.type === 'TSImportType' ||
2522
- node.type === 'TSExternalModuleReference'
2523
- ) {
2524
- const t = text(node.argument ?? node.expression);
2525
- if (t != null) found(t);
2526
- }
2527
- for (const [k, v] of Object.entries(node))
2528
- if (
2529
- k !== 'loc' &&
2530
- k !== 'start' &&
2531
- k !== 'end' &&
2532
- v &&
2533
- typeof v === 'object'
2534
- )
2535
- specifiers(v, found);
2536
- };
2537
- /** @param {string} at */
2538
- const walk = at => {
2539
- if (tooBig) return;
2540
- /** @type {fs.Dirent[]} */
2541
- let entries;
2542
- try {
2543
- entries = fs.readdirSync(at, {withFileTypes: true});
2544
- } catch {
2545
- return;
2546
- }
2547
- for (const e of entries) {
2548
- const full = path.join(at, e.name);
2549
- if (e.isDirectory()) {
2550
- if (!NOT_SOURCE.has(e.name) && !e.name.startsWith('.')) walk(full);
2551
- if (tooBig) return;
2552
- continue;
2553
- }
2554
- if (!/\.(tsx|ts|jsx|js|mjs|cjs|mdx)$/.test(e.name) || own.has(full))
2555
- continue;
2556
- if (e.name.endsWith('.d.ts')) continue;
2557
- if (++files > IMPORTER_SCAN_MAX) {
2558
- tooBig = true;
2559
- return;
2560
- }
2561
- /** @type {string} */
2562
- let source;
2563
- try {
2564
- source = fs.readFileSync(full, 'utf8');
2565
- } catch {
2566
- continue;
2567
- }
2568
- // Only a file that names a target's file name can import it.
2569
- if (!names.some(n => source.includes(n))) continue;
2570
- /** @type {string[]} */
2571
- const specs = [];
2572
- try {
2573
- const ast = parseModule(
2574
- e.name.endsWith('.mdx')
2575
- ? source
2576
- .split('\n')
2577
- .filter(l => /^\s*(import|export)\b/.test(l))
2578
- .join('\n')
2579
- : source,
2580
- {
2581
- sourceType: 'unambiguous',
2582
- errorRecovery: true,
2583
- plugins: [
2584
- 'jsx',
2585
- ...(/\.(ts|tsx|mts|cts)$/.test(e.name)
2586
- ? [/** @type {const} */ ('typescript')]
2587
- : []),
2588
- ],
2589
- },
2590
- );
2591
- specifiers(ast.program, spec => specs.push(spec));
2592
- } catch {
2593
- // Not parsed: read its import strings as text.
2594
- for (const m of source.matchAll(
2595
- /(?:from\s*|import\s*\(\s*|require\s*\(\s*|import\s+)['"`]([^'"`$]+)['"`]/g,
2596
- ))
2597
- specs.push(m[1]);
2598
- }
2599
- if (specs.some(sp => resolves(full, sp))) out.add(shown(cwd, full));
2600
- }
2601
- };
2602
- walk(cwd);
2603
- return {importers: [...out].sort(), tooBig};
2604
- }
2605
-
2606
2634
  /**
2607
2635
  * Page files in the preview folder that theme-preview.json does not list:
2608
2636
  * a stopped change can leave one behind when its step record is damaged.
@@ -2999,11 +3027,13 @@ async function buildWorn(cwd, theme, options, notes) {
2999
3027
  const slug = theme.name;
3000
3028
  /** @type {string | null} */
3001
3029
  let why = null;
3030
+ /** What the build reports (the pictures it removed). @type {string[]} */
3031
+ let built = [];
3002
3032
  const build = async () => {
3003
3033
  const t = loadTheme(cwd, slug);
3004
3034
  why = staleBuild(cwd, slug, t);
3005
3035
  if (!why) return;
3006
- await buildTheme(await context(cwd), slug, t);
3036
+ built = (await buildTheme(await context(cwd), slug, t)).notes;
3007
3037
  };
3008
3038
  await (typeof options?.lockTheme === 'function'
3009
3039
  ? options.lockTheme(slug, build)
@@ -3011,6 +3041,7 @@ async function buildWorn(cwd, theme, options, notes) {
3011
3041
  if (why)
3012
3042
  notes.push(
3013
3043
  `built ${shown(cwd, themeFiles(cwd, slug).dir)}/ first: its build was not current (${why})`,
3044
+ ...built,
3014
3045
  );
3015
3046
  }
3016
3047
 
@@ -3021,6 +3052,13 @@ const COLORS_PAGE = wordTable({
3021
3052
  file: `${PAGES_DIR}/colors`,
3022
3053
  });
3023
3054
 
3055
+ /** The default pages a preview starts with, which `--template` adds back. */
3056
+ const DEFAULT_PAGE_IDS = Object.freeze([
3057
+ 'overview',
3058
+ 'components',
3059
+ COLORS_PAGE.id,
3060
+ ]);
3061
+
3024
3062
  /**
3025
3063
  * The Colors page source of a theme, and whether the theme has generated
3026
3064
  * colors. The page imports the generated color module, so it follows every
@@ -3205,8 +3243,11 @@ function dirFlag(cwd, dir) {
3205
3243
  */
3206
3244
  export async function refreshPreviewRoute(cwd, slug) {
3207
3245
  const at = previewDir(cwd, undefined, {optional: true});
3246
+ // The same previews `see` names: the usual folder, the recorded ones,
3247
+ // and any in the routes folders that wear the theme (a folder renamed by
3248
+ // hand, or one whose record was lost).
3208
3249
  const dirs = [
3209
- ...new Set([...(at ? [at.dir] : []), ...recordedPreviews(cwd, slug)]),
3250
+ ...new Set([...(at ? [at.dir] : []), ...themePreviews(cwd, slug)]),
3210
3251
  ];
3211
3252
  let changed = false;
3212
3253
  /** @type {string[]} */
@@ -3244,7 +3285,7 @@ export async function refreshPreviewRoute(cwd, slug) {
3244
3285
  stale.push(
3245
3286
  standIn
3246
3287
  ? `${shown(cwd, file)} (changed by hand, so it is kept; the theme has no generated colors now, so ${standIn}, which the page imports, holds an empty stand-in that keeps the app building. Give the page another name if you want to keep your changes, then run ${PREVIEW} add)`
3247
- : shown(cwd, file),
3288
+ : `${shown(cwd, file)} (changed by hand, so it does not follow this change: move it out of ${shownDir(cwd, dir)}/, keeping your copy elsewhere in the app and importing nothing from the preview folder, then run ${PREVIEW} add${dirFlag(cwd, dir)} to write it again)`,
3248
3289
  );
3249
3290
  return false;
3250
3291
  }
@@ -3260,7 +3301,20 @@ export async function refreshPreviewRoute(cwd, slug) {
3260
3301
  `${shownDir(cwd, dir)}/ (${slug} has generated colors now; ${PREVIEW} add${dirFlag(cwd, dir)} adds its Colors page)`,
3261
3302
  );
3262
3303
  if (!writes.length) continue;
3263
- commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3304
+ // A route that cannot be written (its permissions, a folder in its
3305
+ // place) does not follow this change: said, never a quiet ok.
3306
+ try {
3307
+ commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3308
+ } catch (e) {
3309
+ const code =
3310
+ /\b(E[A-Z]{2,})\b/.exec(
3311
+ `${/** @type {any} */ (e)?.code ?? ''} ${e instanceof Error ? e.message : ''}`,
3312
+ )?.[1] ?? 'it could not be written';
3313
+ stale.push(
3314
+ `${shownDir(cwd, dir)}/ (could not be written: ${code}, so the in-app preview does not follow this change; fix its permissions, then ${PREVIEW} add${dirFlag(cwd, dir)} writes it again)`,
3315
+ );
3316
+ continue;
3317
+ }
3264
3318
  changed = true;
3265
3319
  }
3266
3320
  return {changed, stale};
@@ -3339,11 +3393,53 @@ function routesOf(cwd, at) {
3339
3393
  function previewPath(cwd, at) {
3340
3394
  const app = routesOf(cwd, at);
3341
3395
  if (!app) return null;
3396
+ // A folder Next does not serve (_private, @slot, an intercepting route):
3397
+ // no URL, as add refuses it.
3398
+ if (unservedWhy(cwd, at.dir)) return null;
3342
3399
  const segs = urlSegments(app, at.dir);
3343
3400
  if (segs.some(seg => /^\[.+\]$/.test(seg))) return null;
3344
3401
  const base = nextBasePath(cwd);
3345
3402
  if (base == null) return null;
3346
- return `${base}/${segs.map(seg => encodeURIComponent(seg)).join('/')}`;
3403
+ // A folder named %5F… is served at the decoded name (`_x`), encoded as a
3404
+ // URL segment needs it.
3405
+ const decoded = (/** @type {string} */ seg) => {
3406
+ try {
3407
+ return decodeURIComponent(seg);
3408
+ } catch {
3409
+ return seg;
3410
+ }
3411
+ };
3412
+ return `${base}/${segs.map(seg => encodeURIComponent(decoded(seg))).join('/')}`;
3413
+ }
3414
+
3415
+ /**
3416
+ * Why a preview folder found in the routes folder is not served, or null.
3417
+ * @param {string} cwd
3418
+ * @param {string} dir
3419
+ * @returns {string | null}
3420
+ */
3421
+ function unservedWhy(cwd, dir) {
3422
+ const app = routesOf(cwd, {dir, app: null});
3423
+ if (!app) return null;
3424
+ // The same rules add keeps: src/app/ while app/ is what Next serves, and
3425
+ // a next.config whose page extensions leave out page.tsx.
3426
+ const served = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(
3427
+ r => fs.existsSync(r) && fs.statSync(r).isDirectory(),
3428
+ );
3429
+ if (served && path.resolve(app) !== path.resolve(served))
3430
+ return `Next serves ${shown(cwd, served)}/ instead of ${shown(cwd, app)}/ when both are there`;
3431
+ try {
3432
+ const exts = readNextConfig(cwd).pageExtensions;
3433
+ if (exts && !exts.includes('tsx'))
3434
+ return `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx`;
3435
+ } catch {
3436
+ // A config this cannot read is not a reason to hide the URL.
3437
+ }
3438
+ // A [param] folder is served, with a value for it; only _private, @slot
3439
+ // and intercepting folders are not.
3440
+ const segs = path.relative(app, dir).split(path.sep);
3441
+ if (!segs.some(x => /^[_@]/.test(x) || INTERCEPT.test(x))) return null;
3442
+ return unroutedSegment(app, dir);
3347
3443
  }
3348
3444
 
3349
3445
  /**
@@ -3374,27 +3470,59 @@ function pageUrls(cwd, at, ids) {
3374
3470
  * @param {'colors' | 'components' | 'overview'} focus
3375
3471
  * @param {{code: string, cause: string} | null} [notChecked] why the change
3376
3472
  * could not be rendered
3473
+ * @param {{pictureProblem?: string | null, stale?: string[]}} [extra] this
3474
+ * result's picture problem (what kept --png from taking pictures) and its
3475
+ * previewStale entries (an in-app preview changed by hand)
3377
3476
  * @returns {string}
3378
3477
  */
3379
- export function seeLine(cwd, slug, focus, notChecked = null) {
3478
+ export function seeLine(cwd, slug, focus, notChecked = null, extra = {}) {
3380
3479
  /** @type {string[]} */
3381
3480
  const urls = [];
3382
3481
  /** Previews whose URL depends on the app's routing. @type {string[]} */
3383
3482
  const unplain = [];
3384
- // The previews recorded for the theme, and any found in the routes
3385
- // folders that wear it (a folder renamed by hand), as remove finds them.
3386
- const dirs = [
3387
- ...new Set([...recordedPreviews(cwd, slug), ...previewsIn(cwd)]),
3388
- ];
3483
+ /** Previews in a folder Next does not serve. @type {string[]} */
3484
+ const unserved = [];
3485
+ /** Their folders, as --path takes them. @type {string[]} */
3486
+ const unservedDirs = [];
3487
+ /** @type {string[]} */
3488
+ const stale = extra.stale ?? [];
3489
+ /** Previews whose route was changed by hand. @type {string[]} */
3490
+ const handEdited = [];
3491
+ /** Previews whose record is damaged. @type {string[]} */
3492
+ const damaged = [];
3493
+ const dirs = themePreviews(cwd, slug);
3389
3494
  for (const dir of dirs) {
3390
3495
  /** @type {any} */
3391
3496
  let data;
3392
3497
  try {
3393
3498
  data = JSON.parse(fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'));
3394
- } catch {
3499
+ } catch (e) {
3500
+ // A record that is there but damaged: the preview commands refuse
3501
+ // it until it is fixed, so no add tip, the repair instead.
3502
+ if (
3503
+ fs.existsSync(path.join(dir, PREVIEW_DATA)) &&
3504
+ !(/** @type {any} */ (e)?.code)
3505
+ )
3506
+ damaged.push(shownDir(cwd, dir));
3395
3507
  continue;
3396
3508
  }
3397
3509
  if (data?.theme !== slug) continue;
3510
+ const why = unservedWhy(cwd, dir);
3511
+ if (why) {
3512
+ unserved.push(`${shownDir(cwd, dir)}/ (${why})`);
3513
+ unservedDirs.push(shownDir(cwd, dir));
3514
+ continue;
3515
+ }
3516
+ if (
3517
+ stale.some(
3518
+ f =>
3519
+ f.startsWith(`${shownDir(cwd, dir)}/`) &&
3520
+ /changed by hand|could not be written/.test(f),
3521
+ )
3522
+ ) {
3523
+ handEdited.push(shownDir(cwd, dir));
3524
+ continue;
3525
+ }
3398
3526
  const ids = Array.isArray(data?.pages)
3399
3527
  ? data.pages.map((/** @type {any} */ x) => String(x?.id))
3400
3528
  : [];
@@ -3408,16 +3536,59 @@ export function seeLine(cwd, slug, focus, notChecked = null) {
3408
3536
  );
3409
3537
  }
3410
3538
  const f = themeFiles(cwd, slug);
3539
+ // What keeps --png from taking pictures, when this result's own picture
3540
+ // run failed (a file of yours named like a picture).
3541
+ // A command that only takes pictures, whatever this one was (an undo run
3542
+ // again undoes another change; new refuses a theme that exists).
3543
+ const pngNote = extra.pictureProblem
3544
+ ? `--png took no pictures: ${extra.pictureProblem}`
3545
+ : `${EDITOR} show ${slug} --png takes pictures in ${shownDir(cwd, f.dir)}/ with no dev server (it needs a Playwright or a Chrome)`;
3411
3546
  const own = notChecked
3412
3547
  ? /could not be written/.test(notChecked.cause)
3413
3548
  ? `the change is saved, but ${notChecked.cause}; --png takes no pictures until that is fixed`
3414
3549
  : `the change is saved, but the components could not be rendered here (${notChecked.cause}), so ${shown(cwd, f.preview)} still shows the theme as it was and --png takes no pictures until that is fixed`
3415
- : `look without changing your app: open or screenshot ${shown(cwd, f.preview)} (one self-contained page, current after this change; ${EDITOR} show ${slug} also writes ${shown(cwd, f.sheet)}, every component), or run it with --png for pictures in ${shownDir(cwd, f.dir)}/ with no dev server (it needs a Playwright or a Chrome)`;
3550
+ : `look without changing your app: open or screenshot ${shown(cwd, f.preview)} (one self-contained page, current after this change; ${EDITOR} show ${slug} also writes ${shown(cwd, f.sheet)}, every component), or ${pngNote}`;
3551
+ const edited = handEdited.length
3552
+ ? `; the in-app preview in ${handEdited.slice(0, 2).join(', ')}/ ${stale.some(f => /could not be written/.test(f)) && !stale.some(f => /changed by hand/.test(f)) ? 'could not be written' : 'was changed by hand'}, so it does not follow this change (previewStale says what to move out, then ${PREVIEW} add writes it again)`
3553
+ : '';
3416
3554
  if (urls.length)
3417
- return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}`;
3555
+ return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}${edited}`;
3418
3556
  if (unplain.length)
3419
- return `${own}; the in-app preview is in ${unplain.slice(0, 2).join(', ')}, at a URL that depends on the app's routing`;
3420
- return `${own}; to see it inside your app, ${PREVIEW} add puts the preview pages there, each at its own URL`;
3557
+ return `${own}; the in-app preview is in ${unplain.slice(0, 2).join(', ')}, at a URL that depends on the app's routing${edited}`;
3558
+ if (unserved.length) {
3559
+ // What fixes it, by why it is not served: add's own answer for each.
3560
+ const why = unserved.join(' ');
3561
+ const fix = /Next serves .* when both are there/.test(why)
3562
+ ? `${PREVIEW} remove --path ${quoteCommandArgument(unservedDirs[0])}, then ${PREVIEW} add --theme ${slug} puts it in the folder Next serves`
3563
+ : /pageExtensions/.test(why)
3564
+ ? `add "tsx" to pageExtensions in next.config so Next serves the preview's page.tsx`
3565
+ : `move it back into a folder Next routes, or make one there with ${PREVIEW} add --theme ${slug} --path <a routed folder>`;
3566
+ return `${own}; the in-app preview is in ${unserved.slice(0, 2).join(', ')}, which the app does not serve: ${fix}${edited}`;
3567
+ }
3568
+ if (edited) return `${own}${edited}`;
3569
+ if (damaged.length)
3570
+ return `${own}; the in-app preview in ${damaged.slice(0, 2).join(', ')}/ has a damaged ${PREVIEW_DATA}, so it does not follow this change: fix it by hand, or give the folder a new name that starts with _ and run ${PREVIEW} add${editorThemeCount(cwd) > 1 ? ` --theme ${slug}` : ''}`;
3571
+ // With more than one editor theme, a bare add may wear another one.
3572
+ const many = editorThemeCount(cwd) > 1;
3573
+ // An add this app takes; else a new app of its own, with the preview.
3574
+ return addTakes(cwd, null)
3575
+ ? `${own}; to see it inside your app, ${PREVIEW} add${many ? ` --theme ${slug}` : ''} puts the preview pages there, each at its own URL`
3576
+ : `${own}; this app has no routes folder for the preview pages, so ${appCommand(freeAppFolder(cwd), slug)} makes a new app with them`;
3577
+ }
3578
+
3579
+ /**
3580
+ * How many editor themes the project has.
3581
+ * @param {string} cwd
3582
+ */
3583
+ function editorThemeCount(cwd) {
3584
+ const root = themeFiles(cwd, 'x').root;
3585
+ try {
3586
+ return fs
3587
+ .readdirSync(root)
3588
+ .filter(d => fs.existsSync(themeFiles(cwd, d).settings)).length;
3589
+ } catch {
3590
+ return 0;
3591
+ }
3421
3592
  }
3422
3593
 
3423
3594
  /**
@@ -3473,6 +3644,52 @@ function skipReason(s) {
3473
3644
  ].join(' and ');
3474
3645
  }
3475
3646
 
3647
+ /**
3648
+ * Up to `n` of these page templates that this app can show: each one's
3649
+ * packages installed and no StyleX compiler needed, as add itself checks.
3650
+ * The only pages a suggestion names.
3651
+ * @param {string} cwd
3652
+ * @param {string} appRoot the app whose packages a page needs
3653
+ * @param {string[]} ids in order of preference
3654
+ * @param {number} n
3655
+ * @returns {Promise<string[]>}
3656
+ */
3657
+ async function showablePages(cwd, appRoot, ids, n) {
3658
+ /** @type {string[]} */
3659
+ const out = [];
3660
+ for (const id of ids) {
3661
+ if (out.length >= n) break;
3662
+ try {
3663
+ const shownTemplate = /** @type {any} */ (
3664
+ await template(id, {cwd, type: 'page'})
3665
+ );
3666
+ const needs = pageNeeds(appRoot, shownTemplate.data.source);
3667
+ if (
3668
+ !needs.missingPackages.length &&
3669
+ !needs.notInstalled.length &&
3670
+ !needs.stylexCompiler
3671
+ )
3672
+ out.push(id);
3673
+ } catch {
3674
+ // A template that does not load is not suggested.
3675
+ }
3676
+ }
3677
+ return out;
3678
+ }
3679
+
3680
+ /**
3681
+ * The page a refusal's example adds: the first page template this app can
3682
+ * show (app frames left out), or null when there is none.
3683
+ * @param {string} cwd
3684
+ * @returns {Promise<string | null>}
3685
+ */
3686
+ async function examplePage(cwd) {
3687
+ const pages = (await pageTemplates(cwd))
3688
+ .filter(t => !/^Shell\b/.test(t.category ?? ''))
3689
+ .map(t => t.id);
3690
+ return (await showablePages(cwd, appRootOf(cwd, cwd), pages, 1))[0] ?? null;
3691
+ }
3692
+
3476
3693
  /**
3477
3694
  * The page templates for a description, best first, each with why: the
3478
3695
  * build ranking's picks, then the template search's, so a page the app
@@ -3485,9 +3702,10 @@ function skipReason(s) {
3485
3702
  * @param {string} cwd
3486
3703
  * @param {string[]} notes notes for the result
3487
3704
  * @param {string} flags the caller's other flags, for the suggestions
3705
+ * @param {string | null} [appRoot] the app whose packages a page needs
3488
3706
  * @returns {Promise<Array<{name: string, displayName: string, why: string}>>}
3489
3707
  */
3490
- async function rankedPages(words, cwd, notes, flags) {
3708
+ async function rankedPages(words, cwd, notes, flags, appRoot = null) {
3491
3709
  const kit =
3492
3710
  /** @type {import('../build/build.type.mjs').BuildKitResponse} */ (
3493
3711
  await build(words, {cwd})
@@ -3571,15 +3789,8 @@ async function rankedPages(words, cwd, notes, flags) {
3571
3789
  const label = name => listed.find(t => t.id === name)?.name ?? name;
3572
3790
  const suggest = (/** @type {string[]} */ list) =>
3573
3791
  list.slice(0, 3).map(n => `${PREVIEW} add --template ${n}${flags}`);
3574
- // With no page close, a few pages that need nothing more, and the list.
3575
- const fallback = [
3576
- ...suggest(
3577
- ['dashboard', 'settings', 'login'].filter(id =>
3578
- listed.some(t => t.id === id),
3579
- ),
3580
- ),
3581
- formatCliCommand('template --list --type page', cwd),
3582
- ];
3792
+ /** @param {string[]} ids */
3793
+ const showableOf = ids => showablePages(cwd, appRoot ?? cwd, ids, 3);
3583
3794
  // No page relates when the ranking fell back to a frame with no direct
3584
3795
  // match, and no page the search found matches three words of the request
3585
3796
  // or two fifths of them.
@@ -3604,19 +3815,32 @@ async function rankedPages(words, cwd, notes, flags) {
3604
3815
  !found.some(
3605
3816
  (/** @type {any} */ r) => !frames.has(r.name) && termsMatched(r) >= 2,
3606
3817
  )));
3607
- if (unrelated)
3818
+ if (unrelated) {
3819
+ // With no page close, a few pages this app can show, and the list.
3820
+ const offered = await showableOf(
3821
+ pages.length
3822
+ ? pages
3823
+ : [
3824
+ ...['dashboard', 'settings', 'login'],
3825
+ ...listed.map(t => t.id),
3826
+ ].filter(
3827
+ (id, i, all) =>
3828
+ all.indexOf(id) === i &&
3829
+ listed.some(t => t.id === id) &&
3830
+ !frames.has(id),
3831
+ ),
3832
+ );
3608
3833
  refuse(
3609
3834
  E.ERR_NOT_FOUND,
3610
3835
  `No page template relates to "${words}". Name a page to add it anyway.`,
3611
3836
  {
3612
- run: pages.length
3613
- ? [
3614
- ...suggest(pages),
3615
- formatCliCommand('template --list --type page', cwd),
3616
- ]
3617
- : fallback,
3837
+ run: [
3838
+ ...suggest(offered),
3839
+ formatCliCommand('template --list --type page', cwd),
3840
+ ],
3618
3841
  },
3619
3842
  );
3843
+ }
3620
3844
  if (skippedFrames.length)
3621
3845
  notes.push(
3622
3846
  `left out ${skippedFrames.join(', ')}: app frames, not pages (add one with --template <id>)`,
@@ -3866,6 +4090,17 @@ function wornTheme(cwd, slug, again, without) {
3866
4090
  },
3867
4091
  );
3868
4092
  }
4093
+ // A theme of a workspace app below (from the workspace root): the same
4094
+ // command, run from that app.
4095
+ const owners = nextAppsUnder(cwd).filter(a =>
4096
+ fs.existsSync(themeFiles(a.root, name).settings),
4097
+ );
4098
+ if (!themes.includes(name) && owners.length)
4099
+ refuse(
4100
+ E.ERR_UNKNOWN_THEME,
4101
+ `There is no theme "${slug}" under themes/ here; ${owners.map(a => `${shown(cwd, a.root)}/themes/${name}/`).join(', ')} ${owners.length > 1 ? 'hold' : 'holds'} it, in the app that uses it.`,
4102
+ {run: owners.map(a => `${cdTo(shown(cwd, a.root))} && ${again(name)}`)},
4103
+ );
3869
4104
  const near = themes.includes(name) ? [name] : nearest(name, themes);
3870
4105
  if (near.length)
3871
4106
  refuse(
@@ -3933,10 +4168,10 @@ async function namedTemplate(cwd, id, flags) {
3933
4168
  /** @type {any} */ (await template(undefined, {list: true, cwd})).data
3934
4169
  );
3935
4170
  const other = all.find(t => t.id === id);
3936
- const near = nearest(
3937
- id.toLowerCase(),
3938
- pages.map(t => t.id),
3939
- 5,
4171
+ // Every page --template adds is a candidate: the default pages too, which
4172
+ // the template list never shows.
4173
+ const near = [...DEFAULT_PAGE_IDS, ...pages.map(t => t.id)].filter(n =>
4174
+ typoNear(id, n),
3940
4175
  );
3941
4176
  refuse(
3942
4177
  E.ERR_UNKNOWN_TEMPLATE,
@@ -4062,9 +4297,8 @@ async function addPreview(description, options, box) {
4062
4297
  : '';
4063
4298
  // A default page's id (overview, components, colors), as `remove` takes
4064
4299
  // it, adds exactly that page back (or is refused, saying why).
4065
- const DEFAULT_IDS = ['overview', 'components', COLORS_PAGE.id];
4066
4300
  const isDefault = (/** @type {unknown} */ v) =>
4067
- typeof v === 'string' && DEFAULT_IDS.includes(v.trim().toLowerCase());
4301
+ typeof v === 'string' && DEFAULT_PAGE_IDS.includes(v.trim().toLowerCase());
4068
4302
  // Beside another page asked for, it is refused below (drop one).
4069
4303
  const blank = (/** @type {unknown} */ v) => v == null || !String(v).trim();
4070
4304
  const askedId = [description, options.template]
@@ -4082,10 +4316,15 @@ async function addPreview(description, options, box) {
4082
4316
  const said = (description ?? '').trim();
4083
4317
  const named =
4084
4318
  options.template == null ? null : String(options.template).trim();
4319
+ // A refusal's example is a page this app can show.
4320
+ const example = async () => {
4321
+ const id = await examplePage(cwd);
4322
+ return id ? [`${PREVIEW} add --template ${id}${tf}${pf}`] : [];
4323
+ };
4085
4324
  if (named === '')
4086
4325
  refuse(E.ERR_INVALID_ARGUMENT, '--template needs a page template id.', {
4087
4326
  run: [
4088
- `${PREVIEW} add --template dashboard${tf}${pf}`,
4327
+ ...(await example()),
4089
4328
  formatCliCommand('template --list --type page', cwd),
4090
4329
  ],
4091
4330
  });
@@ -4101,16 +4340,24 @@ async function addPreview(description, options, box) {
4101
4340
  },
4102
4341
  );
4103
4342
  const top = options.top == null ? 1 : Number(String(options.top));
4104
- if (options.top != null && !/^[1-3]$/.test(String(options.top)))
4343
+ if (options.top != null && !/^[1-3]$/.test(String(options.top))) {
4344
+ // The way on is read from what was typed: its exact reading (3 for
4345
+ // "3.0", " 3" or "three"), the nearest bound for an amount out of
4346
+ // range, else the default.
4347
+ const typed = wholeNumberOf(options.top);
4348
+ const offer = typed == null ? 1 : Math.min(3, Math.max(1, typed));
4105
4349
  refuse(
4106
4350
  E.ERR_INVALID_ARGUMENT,
4107
4351
  `--top takes 1, 2 or 3, not "${String(options.top)}".`,
4108
4352
  {
4109
- run: [
4110
- `${PREVIEW} add ${quoteCommandArgument(said || 'a sales dashboard')} --top 2${tf}${pf}`,
4111
- ],
4353
+ run: said
4354
+ ? [
4355
+ `${PREVIEW} add ${quoteCommandArgument(said)}${offer === 1 ? '' : ` --top ${offer}`}${tf}${pf}`,
4356
+ ]
4357
+ : await example(),
4112
4358
  },
4113
4359
  );
4360
+ }
4114
4361
  if (options.top != null && !said)
4115
4362
  refuse(
4116
4363
  E.ERR_INVALID_ARGUMENT,
@@ -4118,11 +4365,12 @@ async function addPreview(description, options, box) {
4118
4365
  ? '--top says how many ranked pages to add; --template names one page, so drop --top.'
4119
4366
  : '--top says how many pages to add for a description, and there is none.',
4120
4367
  {
4121
- run: [
4368
+ run:
4122
4369
  named != null
4123
- ? `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`
4124
- : `${PREVIEW} add 'a sales dashboard' --top ${String(options.top)}${tf}${pf}`,
4125
- ],
4370
+ ? [
4371
+ `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`,
4372
+ ]
4373
+ : await example(),
4126
4374
  },
4127
4375
  );
4128
4376
  /** @type {string[]} */
@@ -4145,8 +4393,12 @@ async function addPreview(description, options, box) {
4145
4393
  );
4146
4394
  }
4147
4395
  const retry = (/** @type {string | null} */ p) =>
4148
- `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4149
- const at = previewDir(cwd, options.path, {write: true, retry});
4396
+ `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${options.top != null ? ` --top ${quoteCommandArgument(String(options.top))}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4397
+ const at = previewDir(cwd, options.path, {
4398
+ write: true,
4399
+ retry,
4400
+ theme: options.theme ?? null,
4401
+ });
4150
4402
  const recovered = recoverPreview(cwd, at.dir);
4151
4403
  if (recovered) notes.push(recovered);
4152
4404
  const unstyled = coreStylesheetMissing(cwd, at);
@@ -4185,6 +4437,8 @@ async function addPreview(description, options, box) {
4185
4437
  wornTheme(cwd, options.theme, againWith, without);
4186
4438
  data.theme = options.theme;
4187
4439
  } else if (data.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir)) {
4440
+ // Not gone when the route imports it from outside this project folder.
4441
+ refuseThemeAway(cwd, at.dir, data.theme, retry);
4188
4442
  const themes = editedThemes(cwd);
4189
4443
  data.theme = themes.length === 1 ? themes[0] : null;
4190
4444
  notes.push(
@@ -4287,7 +4541,7 @@ async function addPreview(description, options, box) {
4287
4541
  const flags = `${tf}${pf}`;
4288
4542
  const picks = explicit
4289
4543
  ? [await namedTemplate(cwd, /** @type {string} */ (named), flags)]
4290
- : await rankedPages(words, cwd, notes, flags);
4544
+ : await rankedPages(words, cwd, notes, flags, appRootOf(cwd, at.dir));
4291
4545
  for (const [i, pick] of picks.entries()) {
4292
4546
  if (add.length >= (explicit ? 1 : top)) break;
4293
4547
  const shownTemplate =
@@ -4491,10 +4745,17 @@ async function addPreview(description, options, box) {
4491
4745
  } catch {
4492
4746
  // A theme that does not load is reported where it is used.
4493
4747
  }
4494
- if (again)
4495
- notes.push(
4496
- `a default page's id brings back the default pages that are missing, as ${PREVIEW} add does`,
4748
+ // What happened: only the page asked for; the others come with a bare
4749
+ // add.
4750
+ if (again) {
4751
+ const stillMissing = DEFAULT_PAGE_IDS.filter(
4752
+ id => !data.pages.some(p => p.id === id),
4497
4753
  );
4754
+ if (stillMissing.length)
4755
+ notes.push(
4756
+ `only ${askedId} was added; ${PREVIEW} add with no page brings back the other default pages that are missing (${stillMissing.join(', ')})`,
4757
+ );
4758
+ }
4498
4759
  notes.push(...typeScriptNotes(cwd, at.dir, added));
4499
4760
  if (
4500
4761
  askedId === COLORS_PAGE.id &&
@@ -4546,7 +4807,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4546
4807
  refuse(
4547
4808
  E.ERR_INVALID_ARGUMENT,
4548
4809
  'Name the folder for the new app: a new or empty folder inside the current one.',
4549
- {run: [`${PREVIEW} app theme-app`]},
4810
+ {run: [appCommand(freeAppFolder(cwd))]},
4550
4811
  );
4551
4812
  options = {...options, theme: themeArg(options.theme)};
4552
4813
  const slug = options.theme ?? null;
@@ -4556,8 +4817,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4556
4817
  : wornTheme(
4557
4818
  cwd,
4558
4819
  slug,
4559
- t =>
4560
- `${PREVIEW} app ${quoteCommandArgument(dir)}${t == null ? '' : ` --theme ${t}`}`,
4820
+ t => appCommand(dir, t),
4561
4821
  'leave out --theme and the app wears the neutral theme',
4562
4822
  );
4563
4823
  // A new app has no Core installed yet: its pages come from this CLI's own
@@ -4592,9 +4852,10 @@ export async function themeEditPreviewApp(dir, options = {}) {
4592
4852
  {run: [`${P} show ${slug}`]},
4593
4853
  );
4594
4854
  } else if (why) {
4595
- await buildTheme(ctx, slug, theme);
4855
+ const built = await buildTheme(ctx, slug, theme);
4596
4856
  notes.push(
4597
4857
  `built ${shown(cwd, from.dir)}/ first: its build was not current (${why}), and the app gets a current copy`,
4858
+ ...built.notes,
4598
4859
  );
4599
4860
  }
4600
4861
  const to = themeFiles('', slug);
@@ -4608,6 +4869,8 @@ export async function themeEditPreviewApp(dir, options = {}) {
4608
4869
  from.sheet,
4609
4870
  from.previewPng,
4610
4871
  from.sheetPng,
4872
+ // The record of pictures, none of which come along.
4873
+ from.pictures,
4611
4874
  ].map(f => path.basename(f)),
4612
4875
  );
4613
4876
  // The whole folder, tokens/ included, as bytes: a font or a picture
@@ -4622,6 +4885,12 @@ export async function themeEditPreviewApp(dir, options = {}) {
4622
4885
  else if (
4623
4886
  entry.isFile() &&
4624
4887
  !(rel === '' && skip.has(entry.name)) &&
4888
+ // No picture or preview page of any kind (dark pictures, section
4889
+ // sheets): the new app builds its own.
4890
+ !(
4891
+ rel === '' &&
4892
+ /^(preview|sheet)(-[a-z0-9-]+)?\.(html|png)$/.test(entry.name)
4893
+ ) &&
4625
4894
  // A temp file a stopped command left is no part of the theme.
4626
4895
  !isEditorTemp(entry.name)
4627
4896
  )
@@ -4632,6 +4901,30 @@ export async function themeEditPreviewApp(dir, options = {}) {
4632
4901
  }
4633
4902
  };
4634
4903
  copyDir('');
4904
+ // A source file of the theme that imports a file outside its folder
4905
+ // would not build in the new app, where that file is not: refused,
4906
+ // naming the import, before anything is written.
4907
+ const outside = themeCopy.flatMap(c => {
4908
+ const rel = path.relative(to.dir, c.rel);
4909
+ if (!/\.(mjs|cjs|js|mts|cts|ts|tsx|jsx)$/.test(rel)) return [];
4910
+ const file = path.join(from.dir, rel);
4911
+ return importSpecifiers(file, String(c.text))
4912
+ .filter(spec => spec.startsWith('.'))
4913
+ .filter(spec => {
4914
+ const at = path.resolve(path.dirname(file), spec);
4915
+ return at !== from.dir && !at.startsWith(from.dir + path.sep);
4916
+ })
4917
+ .map(spec => `${shown(cwd, file)} imports '${spec}'`);
4918
+ });
4919
+ if (outside.length)
4920
+ refuse(
4921
+ E.ERR_INVALID_ARGUMENT,
4922
+ `${slug} cannot be copied into a new app: ${outside.slice(0, 3).join('; ')}, a file outside ${shown(cwd, from.dir)}/, which the new app does not have, so its theme would not build there.`,
4923
+ {
4924
+ fix: `move what it imports into ${shown(cwd, from.dir)}/ (and import it from there), then run the command again`,
4925
+ run: [appCommand(dir, slug)],
4926
+ },
4927
+ );
4635
4928
  if (theme.like && theme.like !== 'neutral')
4636
4929
  dependencies[`@astryxdesign/theme-${theme.like}`] = cliVersion();
4637
4930
  // The copied build was made on this project's Core and base theme: the
@@ -4662,7 +4955,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4662
4955
  };
4663
4956
  // The new app installs its own packages, so every open font the theme
4664
4957
  // names is added, at the version this project has, else a known one.
4665
- const fonts = fontPackages(ctx, theme);
4958
+ const fonts = fontPackages(ctx, theme, {forNewApp: true});
4666
4959
  for (const font of fonts)
4667
4960
  dependencies[font.pkg] =
4668
4961
  readVersion(project, font.pkg) ?? OPEN_FONT_RANGE;
@@ -4738,12 +5031,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4738
5031
  dependencies,
4739
5032
  slug,
4740
5033
  );
4741
- const files = writeStarterApp(
4742
- cwd,
4743
- plan,
4744
- d =>
4745
- `${PREVIEW} app ${quoteCommandArgument(d)}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`,
4746
- );
5034
+ const files = writeStarterApp(cwd, plan, d => appCommand(d, slug));
4747
5035
  const folder = shownDir(cwd, plan.root);
4748
5036
  if (
4749
5037
  plan.root !== cwd &&
@@ -4765,7 +5053,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4765
5053
  files,
4766
5054
  notes,
4767
5055
  // A folder named like a flag (`-`, `-k`) is a path to cd only with ./.
4768
- open: `cd ${quoteCommandArgument(folder.startsWith('-') ? `./${folder}` : folder)} && npm install && npm run dev, then open /theme-preview`,
5056
+ open: `${cdTo(folder)} && npm install && npm run dev, then open /theme-preview`,
4769
5057
  },
4770
5058
  };
4771
5059
  }
@@ -4854,7 +5142,9 @@ export async function themeEditPreviewList(options = {}) {
4854
5142
  /** @type {string[]} */
4855
5143
  const notes = [];
4856
5144
  const themeMissing = Boolean(
4857
- data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
5145
+ data?.theme &&
5146
+ !fs.existsSync(themeFiles(cwd, data.theme).dir) &&
5147
+ !(at && themeElsewhere(cwd, at.dir, data.theme)),
4858
5148
  );
4859
5149
  if (at && fs.existsSync(path.join(at.dir, PENDING)))
4860
5150
  notes.push(
@@ -4943,7 +5233,116 @@ export async function themeEditPreviewList(options = {}) {
4943
5233
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewRemoveResponse>}
4944
5234
  */
4945
5235
  export async function themeEditPreviewRemove(page, options = {}) {
4946
- return reportingRecovery(box => removePreview(page, options, box));
5236
+ try {
5237
+ return await reportingRecovery(box => removePreview(page, options, box));
5238
+ } catch (e) {
5239
+ // Removing a page needs the theme the route wears; removing the whole
5240
+ // preview needs none. Every refusal over a theme that does not load
5241
+ // names it, wherever the theme was read.
5242
+ const err = /** @type {any} */ (e);
5243
+ const pf =
5244
+ options.path != null
5245
+ ? ` --path ${quoteCommandArgument(options.path)}`
5246
+ : '';
5247
+ const whole = `${PREVIEW} remove${pf}`;
5248
+ if (
5249
+ page != null &&
5250
+ [E.ERR_THEME_INVALID, E.ERR_UNKNOWN_THEME, E.ERR_THEME_LOAD].includes(
5251
+ err?.code,
5252
+ ) &&
5253
+ !(err.suggestions ?? []).some((/** @type {any} */ x) => x?.name === whole)
5254
+ )
5255
+ err.suggestions = [
5256
+ {
5257
+ name: whole,
5258
+ reason:
5259
+ 'do this instead: removes the whole preview, which needs no theme',
5260
+ },
5261
+ ...(err.suggestions ?? []),
5262
+ ];
5263
+ throw e;
5264
+ }
5265
+ }
5266
+
5267
+ /**
5268
+ * Refuse a preview command run in a project folder below the one that holds
5269
+ * the theme the preview wears (a workspace app run from its own folder): the
5270
+ * theme is not gone, and no command rewrites it away. The refusal names
5271
+ * the same command, run from the folder that holds the theme.
5272
+ * @param {string} cwd
5273
+ * @param {string} dir the preview folder
5274
+ * @param {string} slug the theme the preview wears
5275
+ * @param {Retry} again the same command, with every argument it was given,
5276
+ * for a --path
5277
+ */
5278
+ function refuseThemeAway(cwd, dir, slug, again) {
5279
+ const away = themeElsewhere(cwd, dir, slug);
5280
+ if (!away) return;
5281
+ const root = path.dirname(path.dirname(away));
5282
+ refuse(
5283
+ E.ERR_INVALID_ARGUMENT,
5284
+ `The preview wears ${slug}, whose theme folder is ${away}/, outside this project folder (${cwd}). Run the command from the folder that holds themes/${slug}/.`,
5285
+ {
5286
+ run: [`${cdTo(root)} && ${again(path.relative(root, dir))}`],
5287
+ },
5288
+ );
5289
+ }
5290
+
5291
+ /**
5292
+ * The theme folder a preview's route imports when it is outside this
5293
+ * project's themes/ (a workspace app run from its own folder, its themes at
5294
+ * the workspace root), or null.
5295
+ * @param {string} cwd
5296
+ * @param {string} dir the preview folder
5297
+ * @param {string} slug
5298
+ * @returns {string | null}
5299
+ */
5300
+ function themeElsewhere(cwd, dir, slug) {
5301
+ if (fs.existsSync(themeFiles(cwd, slug).dir)) return null;
5302
+ /** @type {string} */
5303
+ let route;
5304
+ try {
5305
+ route = fs.readFileSync(path.join(dir, 'page.tsx'), 'utf8');
5306
+ } catch {
5307
+ return null;
5308
+ }
5309
+ const esc = slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5310
+ const m = new RegExp(`['"]([^'"]*themes/${esc})/${esc}[^'"]*['"]`).exec(
5311
+ route,
5312
+ );
5313
+ if (!m || !m[1].startsWith('.')) return null;
5314
+ const found = path.resolve(dir, m[1]);
5315
+ return fs.existsSync(path.join(found, `${slug}.settings.json`))
5316
+ ? found
5317
+ : null;
5318
+ }
5319
+
5320
+ /**
5321
+ * The previews a theme may have: the ones recorded with it (added with
5322
+ * --path) and every preview in the routes folders (one renamed by hand, or
5323
+ * one whose record was lost). The one list `see`, a change's refresh and
5324
+ * the preview commands read; each reads a preview's record for its theme.
5325
+ * @param {string} cwd
5326
+ * @param {string} slug
5327
+ * @returns {string[]}
5328
+ */
5329
+ function themePreviews(cwd, slug) {
5330
+ return [...new Set([...recordedPreviews(cwd, slug), ...previewsIn(cwd)])];
5331
+ }
5332
+
5333
+ /**
5334
+ * Every preview in the app, of any editor theme: the previews of each, by
5335
+ * {@link themePreviews}, that are there.
5336
+ * @param {string} cwd
5337
+ * @returns {string[]}
5338
+ */
5339
+ function allPreviews(cwd) {
5340
+ return [
5341
+ ...new Set([
5342
+ ...editedThemes(cwd).flatMap(t => themePreviews(cwd, t)),
5343
+ ...previewsIn(cwd),
5344
+ ]),
5345
+ ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
4947
5346
  }
4948
5347
 
4949
5348
  /**
@@ -4994,6 +5393,24 @@ async function removePreview(page, options, box) {
4994
5393
  const retry = (/** @type {string | null} */ p) =>
4995
5394
  `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4996
5395
  const at = previewDir(cwd, options.path, {retry});
5396
+ // A file given for the preview's folder: its folder when the file is a
5397
+ // preview's own, else the previews there are (as add refuses a file).
5398
+ if (fs.existsSync(at.dir) && !fs.statSync(at.dir).isDirectory()) {
5399
+ const parent = path.dirname(at.dir);
5400
+ const own = fs.existsSync(path.join(parent, PREVIEW_DATA));
5401
+ const others = previewsIn(cwd);
5402
+ refuse(
5403
+ E.ERR_INVALID_ARGUMENT,
5404
+ `${shown(cwd, at.dir)} is a file; a preview is a folder${own ? `, and this file is in the preview ${shownDir(cwd, parent)}/` : ''}.`,
5405
+ {
5406
+ run: own
5407
+ ? [retry(shownDir(cwd, parent))]
5408
+ : others.length
5409
+ ? others.slice(0, 3).map(d => retry(shownDir(cwd, d)))
5410
+ : [`${PREVIEW} list`],
5411
+ },
5412
+ );
5413
+ }
4997
5414
  // The pages a stopped change was removing, read before it is finished.
4998
5415
  /** @type {string[]} */
4999
5416
  let removing = [];
@@ -5130,11 +5547,17 @@ async function removePreview(page, options, box) {
5130
5547
  .map(f => path.join(at.dir, f.replace(/\.[a-z]+$/, '')))
5131
5548
  : []),
5132
5549
  ];
5133
- const {importers, tooBig} = pageImporters(cwd, data, at.dir, targets);
5550
+ const {importers, tooBig, limit} = pageImporters(
5551
+ cwd,
5552
+ data,
5553
+ at.dir,
5554
+ targets,
5555
+ {aliases: tsconfigAliases(cwd), limit: IMPORTER_SCAN_MAX},
5556
+ );
5134
5557
  if (tooBig)
5135
5558
  refuse(
5136
5559
  E.ERR_INVALID_ARGUMENT,
5137
- `This project holds more than ${IMPORTER_SCAN_MAX} source files, too many to check that none of them imports ${going.length > 1 ? 'the preview pages' : 'the page'}, so nothing was removed.`,
5560
+ `This project holds more than ${limit} source files, too many to check that none of them imports ${going.length > 1 ? 'the preview pages' : 'the page'}, so nothing was removed.`,
5138
5561
  {
5139
5562
  fix: `delete ${folder}/ by hand once nothing imports from it`,
5140
5563
  },
@@ -5179,6 +5602,7 @@ async function removePreview(page, options, box) {
5179
5602
  const wore = data.theme;
5180
5603
  /** @type {string | null} */
5181
5604
  let gone = null;
5605
+ if (wore) refuseThemeAway(cwd, at.dir, wore, retry);
5182
5606
  if (wore && !fs.existsSync(themeFiles(cwd, wore).dir)) {
5183
5607
  gone = wore;
5184
5608
  data.theme = null;
@@ -5214,26 +5638,10 @@ async function removePreview(page, options, box) {
5214
5638
  let planned;
5215
5639
  /** @type {Awaited<ReturnType<typeof routeTheme>>} */
5216
5640
  let theme;
5217
- try {
5218
- theme = await routeTheme(cwd, at.dir, data, {build: false});
5219
- planned = await routeWrites(cwd, at.dir, data, theme, {gone});
5220
- } catch (e) {
5221
- const err = /** @type {any} */ (e);
5222
- if (
5223
- [E.ERR_THEME_INVALID, E.ERR_UNKNOWN_THEME, E.ERR_THEME_LOAD].includes(
5224
- err?.code,
5225
- )
5226
- )
5227
- err.suggestions = [
5228
- {
5229
- name: `${PREVIEW} remove${pf}`,
5230
- reason:
5231
- 'do this instead: removes the whole preview, which needs no theme',
5232
- },
5233
- ...(err.suggestions ?? []),
5234
- ];
5235
- throw e;
5236
- }
5641
+ // A theme that does not load is refused with the whole-preview remove
5642
+ // named (themeEditPreviewRemove adds it to every such refusal).
5643
+ theme = await routeTheme(cwd, at.dir, data, {build: false});
5644
+ planned = await routeWrites(cwd, at.dir, data, theme, {gone});
5237
5645
  const elsewhere = `${PREVIEW} remove${pf}`;
5238
5646
  /** @type {Map<string, {rel: string, text: string, keepHash?: boolean}>} */
5239
5647
  const writes = new Map(move.writes.map(w => [w.rel, w]));