@astryxdesign/cli 0.7.16 → 0.7.17-canary.g0135e03

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 (369) 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 +26 -2
  29. package/api/docs/_adapter.mjs +219 -6
  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 +122 -1
  79. package/api/theme/build/build.mjs +412 -84
  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 +23 -3
  83. package/api/theme/build/font-warning.mjs +54 -5
  84. package/api/theme/build/icon-imports.mjs +25 -2
  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 +103 -3
  88. package/api/theme-edit/_adapter.mjs +961 -82
  89. package/api/theme-edit/_catalog.mjs +19 -4
  90. package/api/theme-edit/_check.d.mts +63 -24
  91. package/api/theme-edit/_check.mjs +2467 -362
  92. package/api/theme-edit/_color.d.mts +10 -0
  93. package/api/theme-edit/_color.mjs +49 -1
  94. package/api/theme-edit/_compiler.mjs +89 -6
  95. package/api/theme-edit/_context.d.mts +3 -3
  96. package/api/theme-edit/_context.mjs +165 -54
  97. package/api/theme-edit/_css.d.mts +14 -0
  98. package/api/theme-edit/_css.mjs +46 -1
  99. package/api/theme-edit/_edit.d.mts +31 -4
  100. package/api/theme-edit/_edit.mjs +2433 -204
  101. package/api/theme-edit/_how-commands.d.mts +72 -1
  102. package/api/theme-edit/_how-commands.mjs +759 -9
  103. package/api/theme-edit/_how-question.d.mts +82 -5
  104. package/api/theme-edit/_how-question.mjs +6473 -553
  105. package/api/theme-edit/_how.d.mts +2 -1
  106. package/api/theme-edit/_how.mjs +237 -41
  107. package/api/theme-edit/_marks.d.mts +31 -5
  108. package/api/theme-edit/_marks.mjs +57 -5
  109. package/api/theme-edit/_name-rule.d.mts +11 -0
  110. package/api/theme-edit/_name-rule.mjs +12 -0
  111. package/api/theme-edit/_normal.d.mts +292 -0
  112. package/api/theme-edit/_normal.mjs +1454 -0
  113. package/api/theme-edit/_palette.mjs +10 -4
  114. package/api/theme-edit/_part-words.d.mts +31 -0
  115. package/api/theme-edit/_part-words.mjs +126 -0
  116. package/api/theme-edit/_parts.d.mts +18 -1
  117. package/api/theme-edit/_parts.mjs +246 -23
  118. package/api/theme-edit/_preview-app.d.mts +7 -1
  119. package/api/theme-edit/_preview-app.mjs +776 -187
  120. package/api/theme-edit/_preview.d.mts +100 -14
  121. package/api/theme-edit/_preview.mjs +582 -139
  122. package/api/theme-edit/_project.d.mts +4 -0
  123. package/api/theme-edit/_project.mjs +3 -1
  124. package/api/theme-edit/_settings.d.mts +417 -42
  125. package/api/theme-edit/_settings.mjs +3262 -424
  126. package/api/theme-edit/_tables.d.mts +15 -0
  127. package/api/theme-edit/_tables.mjs +63 -1
  128. package/api/theme-edit/_vet.d.mts +20 -0
  129. package/api/theme-edit/_vet.mjs +47 -2
  130. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  131. package/api/theme-edit/theme-edit.type.mjs +4 -1
  132. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  133. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  134. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  135. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  136. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  137. package/api/upgrade/run/run.mjs +4 -3
  138. package/assets/codemods/integration-discovery.mjs +2 -1
  139. package/assets/codemods/run-codemod.mjs +87 -7
  140. package/assets/codemods/transforms/next/index.mjs +11 -1
  141. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  142. package/assets/component-list.generated.json +1 -0
  143. package/assets/docs/author-a-theme.doc.mjs +1 -0
  144. package/assets/docs/theme.doc.dense.mjs +2 -2
  145. package/assets/docs/theme.doc.mjs +1 -1
  146. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  147. package/assets/docs/tree/checks.doc.mjs +1 -1
  148. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  149. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  150. package/assets/docs/tree/single-component.doc.mjs +4 -0
  151. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  152. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  153. package/assets/docs/use-a-theme.doc.mjs +1 -1
  154. package/assets/docs.generated.json +2 -2
  155. package/assets/search-catalog.generated.json +2 -0
  156. package/assets/self-audit.generated.json +1 -1
  157. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  158. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  159. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  160. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  161. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  162. package/assets/templates/components.generated.json +1 -1
  163. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  164. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  165. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  166. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  167. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  168. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  169. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  170. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  171. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  172. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  173. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  174. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  175. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  176. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  177. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  178. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  179. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  180. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  181. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  182. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  183. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  184. package/assets/templates/pages/ide/page.tsx +24 -2
  185. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  186. package/assets/templates/pages/library/template.doc.mjs +4 -1
  187. package/assets/templates/pages/login/template.doc.mjs +2 -1
  188. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  189. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  190. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  191. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  192. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  193. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  194. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  195. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  196. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  197. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  198. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  199. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  200. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  201. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  202. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  203. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  204. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  205. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  206. package/assets/theme.template.ts +6 -0
  207. package/authoring/debug/parse.d.mts +3 -3
  208. package/authoring/doctypes/_schema.d.mts +3 -3
  209. package/authoring/doctypes/command/command.doc.mjs +1 -1
  210. package/authoring/doctypes/component/categories.d.mts +37 -0
  211. package/authoring/doctypes/component/categories.mjs +54 -0
  212. package/authoring/doctypes/template/template.doc.mjs +1 -1
  213. package/authoring/doctypes/template/type.ts +9 -0
  214. package/authoring/example/example.doc.d.mts +12 -0
  215. package/authoring/example/example.doc.mjs +69 -0
  216. package/authoring/example/preview.d.mts +92 -0
  217. package/authoring/example/preview.mjs +994 -0
  218. package/authoring/example/type.ts +102 -0
  219. package/authoring/index.d.mts +1 -0
  220. package/authoring/index.d.ts +12 -0
  221. package/authoring/index.mjs +3 -1
  222. package/clients/cli/bin/astryx.mjs +6 -9
  223. package/clients/cli/build-id.generated.json +1 -1
  224. package/clients/cli/commands/component.doc.mjs +1 -1
  225. package/clients/cli/commands/component.mjs +22 -3
  226. package/clients/cli/commands/docs.doc.mjs +7 -1
  227. package/clients/cli/commands/docs.mjs +3 -1
  228. package/clients/cli/commands/doctor.mjs +32 -14
  229. package/clients/cli/commands/experimental/render.mjs +42 -1
  230. package/clients/cli/commands/experimental/theme.mjs +358 -63
  231. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  232. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  233. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  234. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  235. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  236. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  237. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  238. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  239. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  240. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  241. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  242. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  243. package/clients/cli/commands/search.doc.mjs +2 -1
  244. package/clients/cli/commands/search.mjs +6 -1
  245. package/clients/cli/commands/template.mjs +4 -2
  246. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  247. package/clients/cli/commands/theme.doc.mjs +1 -1
  248. package/clients/cli/commands/theme.mjs +317 -47
  249. package/clients/cli/commands/upgrade.mjs +42 -7
  250. package/clients/cli/index.mjs +1 -1
  251. package/clients/cli/lib/cli-error.mjs +2 -1
  252. package/clients/cli/lib/component-format.mjs +205 -98
  253. package/clients/cli/lib/hook-format.mjs +9 -19
  254. package/clients/cli/lib/json-shim.mjs +92 -21
  255. package/clients/cli/lib/manifest.mjs +3 -2
  256. package/clients/cli/manifest.generated.json +1 -1
  257. package/foundation/agent-docs/agent-docs.mjs +1 -1
  258. package/foundation/config/theme-state.d.mts +13 -1
  259. package/foundation/config/theme-state.mjs +47 -7
  260. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  261. package/foundation/discovery/component-discovery.d.mts +11 -0
  262. package/foundation/discovery/component-discovery.mjs +56 -8
  263. package/foundation/discovery/component-replacement.mjs +130 -1
  264. package/foundation/discovery/copied-passages.mjs +2 -1
  265. package/foundation/discovery/doc-types.mjs +4 -3
  266. package/foundation/discovery/entry-name-files.d.mts +43 -0
  267. package/foundation/discovery/entry-name-files.mjs +264 -0
  268. package/foundation/discovery/hook-discovery.d.mts +8 -2
  269. package/foundation/discovery/hook-discovery.mjs +22 -8
  270. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  271. package/foundation/discovery/icon-set-checks.mjs +2 -1
  272. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  273. package/foundation/discovery/integration-doc-files.mjs +2 -1
  274. package/foundation/discovery/package-exports.d.mts +10 -0
  275. package/foundation/discovery/package-exports.mjs +56 -3
  276. package/foundation/discovery/prop-drift.mjs +9 -9
  277. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  278. package/foundation/discovery/runner-allowlist.mjs +2 -0
  279. package/foundation/discovery/stored-component-list.d.mts +43 -0
  280. package/foundation/discovery/stored-component-list.mjs +90 -0
  281. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  282. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  283. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  284. package/foundation/discovery/stored-self-audit.mjs +38 -18
  285. package/foundation/discovery/template-adapter.d.mts +53 -1
  286. package/foundation/discovery/template-adapter.mjs +176 -12
  287. package/foundation/discovery/template-icons.mjs +2 -1
  288. package/foundation/discovery/theme-discovery.mjs +31 -4
  289. package/foundation/discovery/theme-imports.d.mts +14 -0
  290. package/foundation/discovery/theme-imports.mjs +43 -1
  291. package/foundation/discovery/theming-targets.mjs +3 -2
  292. package/foundation/doc-compiler/import.mjs +7 -1
  293. package/foundation/doc-compiler/inputs.mjs +3 -2
  294. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  295. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  296. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  297. package/foundation/env/semver.mjs +3 -1
  298. package/foundation/fonts/font-stylesheet.d.mts +31 -0
  299. package/foundation/fonts/font-stylesheet.mjs +115 -0
  300. package/foundation/fs/cache-eviction.d.mts +21 -0
  301. package/foundation/fs/cache-eviction.mjs +73 -0
  302. package/foundation/fs/exact-codec.d.mts +12 -2
  303. package/foundation/fs/exact-codec.mjs +23 -6
  304. package/foundation/fs/file-protection.mjs +4 -3
  305. package/foundation/fs/gather-cache.d.mts +62 -4
  306. package/foundation/fs/gather-cache.mjs +512 -91
  307. package/foundation/fs/jiti-cache.d.mts +19 -1
  308. package/foundation/fs/jiti-cache.mjs +130 -6
  309. package/foundation/fs/kept-tree.d.mts +60 -0
  310. package/foundation/fs/kept-tree.mjs +154 -0
  311. package/foundation/fs/listing-cache.d.mts +7 -0
  312. package/foundation/fs/listing-cache.mjs +10 -0
  313. package/foundation/fs/module-loader.d.mts +24 -2
  314. package/foundation/fs/module-loader.mjs +94 -21
  315. package/foundation/fs/paths.d.mts +18 -0
  316. package/foundation/fs/paths.mjs +15 -2
  317. package/foundation/fs/read-record.d.mts +9 -0
  318. package/foundation/fs/read-record.mjs +19 -11
  319. package/foundation/fs/stop-cleanup.d.mts +12 -0
  320. package/foundation/fs/stop-cleanup.mjs +66 -0
  321. package/foundation/identity/provider-identity.d.mts +6 -0
  322. package/foundation/identity/provider-identity.mjs +10 -1
  323. package/foundation/integrations/contribution-inventory.mjs +4 -3
  324. package/foundation/integrations/example-code.d.mts +63 -0
  325. package/foundation/integrations/example-code.mjs +416 -0
  326. package/foundation/integrations/public-imports.d.mts +9 -0
  327. package/foundation/integrations/public-imports.mjs +3 -2
  328. package/foundation/integrations/validate-contributions.mjs +17 -45
  329. package/foundation/render/embedded-files.d.mts +6 -0
  330. package/foundation/render/embedded-files.mjs +25 -5
  331. package/foundation/render/embedded-imports.d.mts +39 -7
  332. package/foundation/render/embedded-imports.mjs +66 -27
  333. package/foundation/render/file-header.d.mts +66 -0
  334. package/foundation/render/file-header.mjs +118 -0
  335. package/foundation/render/host-answer.d.mts +18 -0
  336. package/foundation/render/host-answer.mjs +46 -0
  337. package/foundation/render/host-exit.d.mts +1 -0
  338. package/foundation/render/host-exit.mjs +6 -1
  339. package/foundation/render/html-reader.d.mts +55 -2
  340. package/foundation/render/html-reader.mjs +145 -26
  341. package/foundation/render/markup-edits.d.mts +57 -0
  342. package/foundation/render/markup-edits.mjs +182 -0
  343. package/foundation/render/page-host.mjs +29 -12
  344. package/foundation/render/page-worker.mjs +121 -13
  345. package/foundation/render/picture-chrome.d.mts +4 -0
  346. package/foundation/render/picture-chrome.mjs +185 -0
  347. package/foundation/render/picture-playwright.d.mts +4 -0
  348. package/foundation/render/picture-playwright.mjs +34 -0
  349. package/foundation/render/rebuild.mjs +2 -1
  350. package/foundation/render/render-page.d.mts +35 -3
  351. package/foundation/render/render-page.mjs +641 -96
  352. package/foundation/render/source-block.d.mts +85 -6
  353. package/foundation/render/source-block.mjs +211 -20
  354. package/foundation/render/ts-paths.d.mts +69 -6
  355. package/foundation/render/ts-paths.mjs +326 -40
  356. package/foundation/response/error-codes.d.mts +3 -1
  357. package/foundation/response/error-codes.d.ts +1 -0
  358. package/foundation/response/error-codes.doc.mjs +12 -1
  359. package/foundation/response/error-codes.mjs +11 -1
  360. package/foundation/response/response-types.doc.mjs +2 -2
  361. package/foundation/text/compare-text.d.mts +14 -0
  362. package/foundation/text/compare-text.mjs +68 -0
  363. package/foundation/text/string-utils.d.mts +3 -2
  364. package/foundation/text/string-utils.mjs +18 -4
  365. package/foundation/text/suggest-order.d.mts +9 -0
  366. package/foundation/text/suggest-order.mjs +15 -1
  367. package/foundation/xle/expand.mjs +2 -1
  368. package/host/index.mjs +8 -6
  369. package/package.json +7 -6
@@ -63,9 +63,10 @@ import {template} from '../template/template.mjs';
63
63
  import {
64
64
  analyzeTemplateNeeds,
65
65
  extractImportedPackages,
66
+ parsedSpecifiers,
66
67
  } from '../../foundation/discovery/template-needs.mjs';
67
68
  import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
68
- import {requireProject, context} from './_context.mjs';
69
+ import {coreApp, requireProject, context} from './_context.mjs';
69
70
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
70
71
  import {
71
72
  formatCliCommand,
@@ -73,6 +74,7 @@ import {
73
74
  } from '../../foundation/env/package-manager.mjs';
74
75
  import {sha256} from '../../foundation/render/source-block.mjs';
75
76
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
77
+ import {compareText} from '../../foundation/text/compare-text.mjs';
76
78
 
77
79
  const E = ERROR_CODES;
78
80
 
@@ -179,11 +181,9 @@ function layoutImportsSheet(cwd, app, sheet, dir = app) {
179
181
  } catch {
180
182
  return false;
181
183
  }
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];
184
+ const specs = importSpecifiers(file, text);
185
+ if (specs.some(spec => sheet.test(spec))) return true;
186
+ for (const spec of specs) {
187
187
  // An alias the tsconfig sets; else `@/` is the src folder or the
188
188
  // project root.
189
189
  const alias = aliases.find(a => spec.startsWith(a.prefix));
@@ -209,6 +209,25 @@ function layoutImportsSheet(cwd, app, sheet, dir = app) {
209
209
  return starts.some(start => reads(start, 0));
210
210
  }
211
211
 
212
+ /**
213
+ * The modules a file imports, from its import statements: a script's
214
+ * through the shared reader of import statements (its syntax tree, so a
215
+ * comment or a string says nothing), or the `@import` rules of a stylesheet
216
+ * (comments left out).
217
+ * @param {string} file
218
+ * @param {string} text
219
+ * @returns {string[]}
220
+ */
221
+ function importSpecifiers(file, text) {
222
+ if (/\.(css|scss)$/.test(file))
223
+ return [
224
+ ...text
225
+ .replace(/\/\*[\s\S]*?\*\//g, '')
226
+ .matchAll(/@import\s+(?:url\()?\s*['"]([^'"]+)['"]/g),
227
+ ].map(m => m[1]);
228
+ return parsedSpecifiers(text);
229
+ }
230
+
212
231
  /**
213
232
  * The import aliases the app's tsconfig `paths` set (`~/*`, `#app/*`), each
214
233
  * with the folders it stands for.
@@ -238,55 +257,19 @@ function tsconfigAliases(cwd) {
238
257
  }
239
258
 
240
259
  /**
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).
260
+ * A note when the preview's layouts never import Core's stylesheet, or
261
+ * null: without it, components render unstyled, and some show nothing.
262
+ * Judged by the real import statements of the layouts over the preview and
263
+ * the files they import, never by text in a comment or in a file the route
264
+ * does not reach.
244
265
  * @param {string} cwd
245
266
  * @param {{dir: string, app: string | null}} at
246
267
  * @returns {string | null}
247
268
  */
248
269
  function coreStylesheetMissing(cwd, at) {
249
270
  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;
271
+ const SHEET = /^@astryxdesign\/core\/astryx\.css$/;
272
+ if (layoutImportsSheet(cwd, at.app, SHEET, at.dir)) return null;
290
273
  const layout = ['tsx', 'ts', 'jsx', 'js']
291
274
  .map(x => path.join(at.app ?? '', `layout.${x}`))
292
275
  .find(f => fs.existsSync(f));
@@ -562,6 +545,56 @@ function nextConfigNotes(cwd) {
562
545
  * @param {string} dir
563
546
  */
564
547
  function reservedFolder(cwd, dir) {
548
+ // The rules of every app the folder is in: the project's, and a Next app
549
+ // below it that holds the folder (a workspace app, from the root).
550
+ for (const owner of appsOver(cwd, dir)) {
551
+ const why = reservedIn(owner, dir);
552
+ if (why) return why;
553
+ }
554
+ return null;
555
+ }
556
+
557
+ /**
558
+ * The app folders that hold `dir`, nearest first: each Next app between it
559
+ * and the project root (a workspace app, a starter app an earlier
560
+ * `preview app` made), then the project root itself.
561
+ * @param {string} cwd
562
+ * @param {string} dir
563
+ * @returns {string[]}
564
+ */
565
+ function appsOver(cwd, dir) {
566
+ /** @type {string[]} */
567
+ const out = [];
568
+ for (
569
+ let at = path.dirname(path.resolve(dir));
570
+ at.startsWith(path.resolve(cwd) + path.sep);
571
+ at = path.dirname(at)
572
+ )
573
+ if (nextAppAt(at)) out.push(at);
574
+ return [...out, cwd];
575
+ }
576
+
577
+ /**
578
+ * Whether a folder is a Next app: its package.json depends on `next`.
579
+ * @param {string} dir
580
+ */
581
+ function nextAppAt(dir) {
582
+ try {
583
+ const pkg = JSON.parse(
584
+ fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),
585
+ );
586
+ return ['dependencies', 'devDependencies'].some(k => pkg?.[k]?.next);
587
+ } catch {
588
+ return false;
589
+ }
590
+ }
591
+
592
+ /**
593
+ * {@link reservedFolder} for one app folder.
594
+ * @param {string} cwd the app folder
595
+ * @param {string} dir
596
+ */
597
+ function reservedIn(cwd, dir) {
565
598
  const segs = shown(cwd, dir).split('/').filter(Boolean);
566
599
  if (segs[0] === 'themes')
567
600
  return 'themes/ holds the themes, and everything in a theme folder is copied with the theme';
@@ -588,6 +621,21 @@ function reservedFolder(cwd, dir) {
588
621
  return null;
589
622
  }
590
623
 
624
+ /**
625
+ * The compile of an editor theme as it runs from the folder the command ran
626
+ * in: an editor theme compiles from the app root, so from a subfolder the
627
+ * line goes there first.
628
+ * @param {string} cwd the app root
629
+ * @param {string} slug
630
+ */
631
+ function compileFromHere(cwd, slug) {
632
+ const line = `${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)}`;
633
+ const up = path.relative(process.cwd(), cwd);
634
+ return up && path.resolve(process.cwd()) !== path.resolve(cwd)
635
+ ? `cd ${quoteCommandArgument(up.split(path.sep).join('/'))} && ${line}`
636
+ : line;
637
+ }
638
+
591
639
  /**
592
640
  * The app's tsconfig.json compiler options (comments and trailing commas
593
641
  * allowed), or null when there is none.
@@ -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,
@@ -3205,8 +3438,11 @@ function dirFlag(cwd, dir) {
3205
3438
  */
3206
3439
  export async function refreshPreviewRoute(cwd, slug) {
3207
3440
  const at = previewDir(cwd, undefined, {optional: true});
3441
+ // The same previews `see` names: the usual folder, the recorded ones,
3442
+ // and any in the routes folders that wear the theme (a folder renamed by
3443
+ // hand, or one whose record was lost).
3208
3444
  const dirs = [
3209
- ...new Set([...(at ? [at.dir] : []), ...recordedPreviews(cwd, slug)]),
3445
+ ...new Set([...(at ? [at.dir] : []), ...themePreviews(cwd, slug)]),
3210
3446
  ];
3211
3447
  let changed = false;
3212
3448
  /** @type {string[]} */
@@ -3244,7 +3480,7 @@ export async function refreshPreviewRoute(cwd, slug) {
3244
3480
  stale.push(
3245
3481
  standIn
3246
3482
  ? `${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),
3483
+ : `${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
3484
  );
3249
3485
  return false;
3250
3486
  }
@@ -3260,7 +3496,20 @@ export async function refreshPreviewRoute(cwd, slug) {
3260
3496
  `${shownDir(cwd, dir)}/ (${slug} has generated colors now; ${PREVIEW} add${dirFlag(cwd, dir)} adds its Colors page)`,
3261
3497
  );
3262
3498
  if (!writes.length) continue;
3263
- commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3499
+ // A route that cannot be written (its permissions, a folder in its
3500
+ // place) does not follow this change: said, never a quiet ok.
3501
+ try {
3502
+ commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3503
+ } catch (e) {
3504
+ const code =
3505
+ /\b(E[A-Z]{2,})\b/.exec(
3506
+ `${/** @type {any} */ (e)?.code ?? ''} ${e instanceof Error ? e.message : ''}`,
3507
+ )?.[1] ?? 'it could not be written';
3508
+ stale.push(
3509
+ `${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)`,
3510
+ );
3511
+ continue;
3512
+ }
3264
3513
  changed = true;
3265
3514
  }
3266
3515
  return {changed, stale};
@@ -3339,11 +3588,53 @@ function routesOf(cwd, at) {
3339
3588
  function previewPath(cwd, at) {
3340
3589
  const app = routesOf(cwd, at);
3341
3590
  if (!app) return null;
3591
+ // A folder Next does not serve (_private, @slot, an intercepting route):
3592
+ // no URL, as add refuses it.
3593
+ if (unservedWhy(cwd, at.dir)) return null;
3342
3594
  const segs = urlSegments(app, at.dir);
3343
3595
  if (segs.some(seg => /^\[.+\]$/.test(seg))) return null;
3344
3596
  const base = nextBasePath(cwd);
3345
3597
  if (base == null) return null;
3346
- return `${base}/${segs.map(seg => encodeURIComponent(seg)).join('/')}`;
3598
+ // A folder named %5F… is served at the decoded name (`_x`), encoded as a
3599
+ // URL segment needs it.
3600
+ const decoded = (/** @type {string} */ seg) => {
3601
+ try {
3602
+ return decodeURIComponent(seg);
3603
+ } catch {
3604
+ return seg;
3605
+ }
3606
+ };
3607
+ return `${base}/${segs.map(seg => encodeURIComponent(decoded(seg))).join('/')}`;
3608
+ }
3609
+
3610
+ /**
3611
+ * Why a preview folder found in the routes folder is not served, or null.
3612
+ * @param {string} cwd
3613
+ * @param {string} dir
3614
+ * @returns {string | null}
3615
+ */
3616
+ function unservedWhy(cwd, dir) {
3617
+ const app = routesOf(cwd, {dir, app: null});
3618
+ if (!app) return null;
3619
+ // The same rules add keeps: src/app/ while app/ is what Next serves, and
3620
+ // a next.config whose page extensions leave out page.tsx.
3621
+ const served = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(
3622
+ r => fs.existsSync(r) && fs.statSync(r).isDirectory(),
3623
+ );
3624
+ if (served && path.resolve(app) !== path.resolve(served))
3625
+ return `Next serves ${shown(cwd, served)}/ instead of ${shown(cwd, app)}/ when both are there`;
3626
+ try {
3627
+ const exts = readNextConfig(cwd).pageExtensions;
3628
+ if (exts && !exts.includes('tsx'))
3629
+ return `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx`;
3630
+ } catch {
3631
+ // A config this cannot read is not a reason to hide the URL.
3632
+ }
3633
+ // A [param] folder is served, with a value for it; only _private, @slot
3634
+ // and intercepting folders are not.
3635
+ const segs = path.relative(app, dir).split(path.sep);
3636
+ if (!segs.some(x => /^[_@]/.test(x) || INTERCEPT.test(x))) return null;
3637
+ return unroutedSegment(app, dir);
3347
3638
  }
3348
3639
 
3349
3640
  /**
@@ -3374,27 +3665,59 @@ function pageUrls(cwd, at, ids) {
3374
3665
  * @param {'colors' | 'components' | 'overview'} focus
3375
3666
  * @param {{code: string, cause: string} | null} [notChecked] why the change
3376
3667
  * could not be rendered
3668
+ * @param {{pictureProblem?: string | null, stale?: string[]}} [extra] this
3669
+ * result's picture problem (what kept --png from taking pictures) and its
3670
+ * previewStale entries (an in-app preview changed by hand)
3377
3671
  * @returns {string}
3378
3672
  */
3379
- export function seeLine(cwd, slug, focus, notChecked = null) {
3673
+ export function seeLine(cwd, slug, focus, notChecked = null, extra = {}) {
3380
3674
  /** @type {string[]} */
3381
3675
  const urls = [];
3382
3676
  /** Previews whose URL depends on the app's routing. @type {string[]} */
3383
3677
  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
- ];
3678
+ /** Previews in a folder Next does not serve. @type {string[]} */
3679
+ const unserved = [];
3680
+ /** Their folders, as --path takes them. @type {string[]} */
3681
+ const unservedDirs = [];
3682
+ /** @type {string[]} */
3683
+ const stale = extra.stale ?? [];
3684
+ /** Previews whose route was changed by hand. @type {string[]} */
3685
+ const handEdited = [];
3686
+ /** Previews whose record is damaged. @type {string[]} */
3687
+ const damaged = [];
3688
+ const dirs = themePreviews(cwd, slug);
3389
3689
  for (const dir of dirs) {
3390
3690
  /** @type {any} */
3391
3691
  let data;
3392
3692
  try {
3393
3693
  data = JSON.parse(fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'));
3394
- } catch {
3694
+ } catch (e) {
3695
+ // A record that is there but damaged: the preview commands refuse
3696
+ // it until it is fixed, so no add tip, the repair instead.
3697
+ if (
3698
+ fs.existsSync(path.join(dir, PREVIEW_DATA)) &&
3699
+ !(/** @type {any} */ (e)?.code)
3700
+ )
3701
+ damaged.push(shownDir(cwd, dir));
3395
3702
  continue;
3396
3703
  }
3397
3704
  if (data?.theme !== slug) continue;
3705
+ const why = unservedWhy(cwd, dir);
3706
+ if (why) {
3707
+ unserved.push(`${shownDir(cwd, dir)}/ (${why})`);
3708
+ unservedDirs.push(shownDir(cwd, dir));
3709
+ continue;
3710
+ }
3711
+ if (
3712
+ stale.some(
3713
+ f =>
3714
+ f.startsWith(`${shownDir(cwd, dir)}/`) &&
3715
+ /changed by hand|could not be written/.test(f),
3716
+ )
3717
+ ) {
3718
+ handEdited.push(shownDir(cwd, dir));
3719
+ continue;
3720
+ }
3398
3721
  const ids = Array.isArray(data?.pages)
3399
3722
  ? data.pages.map((/** @type {any} */ x) => String(x?.id))
3400
3723
  : [];
@@ -3408,16 +3731,59 @@ export function seeLine(cwd, slug, focus, notChecked = null) {
3408
3731
  );
3409
3732
  }
3410
3733
  const f = themeFiles(cwd, slug);
3734
+ // What keeps --png from taking pictures, when this result's own picture
3735
+ // run failed (a file of yours named like a picture).
3736
+ // A command that only takes pictures, whatever this one was (an undo run
3737
+ // again undoes another change; new refuses a theme that exists).
3738
+ const pngNote = extra.pictureProblem
3739
+ ? `--png took no pictures: ${extra.pictureProblem}`
3740
+ : `${EDITOR} show ${slug} --png takes pictures in ${shownDir(cwd, f.dir)}/ with no dev server (it needs a Playwright or a Chrome)`;
3411
3741
  const own = notChecked
3412
3742
  ? /could not be written/.test(notChecked.cause)
3413
3743
  ? `the change is saved, but ${notChecked.cause}; --png takes no pictures until that is fixed`
3414
3744
  : `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)`;
3745
+ : `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}`;
3746
+ const edited = handEdited.length
3747
+ ? `; 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)`
3748
+ : '';
3416
3749
  if (urls.length)
3417
- return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}`;
3750
+ return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}${edited}`;
3418
3751
  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`;
3752
+ return `${own}; the in-app preview is in ${unplain.slice(0, 2).join(', ')}, at a URL that depends on the app's routing${edited}`;
3753
+ if (unserved.length) {
3754
+ // What fixes it, by why it is not served: add's own answer for each.
3755
+ const why = unserved.join(' ');
3756
+ const fix = /Next serves .* when both are there/.test(why)
3757
+ ? `${PREVIEW} remove --path ${quoteCommandArgument(unservedDirs[0])}, then ${PREVIEW} add --theme ${slug} puts it in the folder Next serves`
3758
+ : /pageExtensions/.test(why)
3759
+ ? `add "tsx" to pageExtensions in next.config so Next serves the preview's page.tsx`
3760
+ : `move it back into a folder Next routes, or make one there with ${PREVIEW} add --theme ${slug} --path <a routed folder>`;
3761
+ return `${own}; the in-app preview is in ${unserved.slice(0, 2).join(', ')}, which the app does not serve: ${fix}${edited}`;
3762
+ }
3763
+ if (edited) return `${own}${edited}`;
3764
+ if (damaged.length)
3765
+ 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}` : ''}`;
3766
+ // With more than one editor theme, a bare add may wear another one.
3767
+ const many = editorThemeCount(cwd) > 1;
3768
+ // An add this app takes; else a new app of its own, with the preview.
3769
+ return addTakes(cwd, null)
3770
+ ? `${own}; to see it inside your app, ${PREVIEW} add${many ? ` --theme ${slug}` : ''} puts the preview pages there, each at its own URL`
3771
+ : `${own}; this app has no routes folder for the preview pages, so ${appCommand(freeAppFolder(cwd), slug)} makes a new app with them`;
3772
+ }
3773
+
3774
+ /**
3775
+ * How many editor themes the project has.
3776
+ * @param {string} cwd
3777
+ */
3778
+ function editorThemeCount(cwd) {
3779
+ const root = themeFiles(cwd, 'x').root;
3780
+ try {
3781
+ return fs
3782
+ .readdirSync(root)
3783
+ .filter(d => fs.existsSync(themeFiles(cwd, d).settings)).length;
3784
+ } catch {
3785
+ return 0;
3786
+ }
3421
3787
  }
3422
3788
 
3423
3789
  /**
@@ -3473,6 +3839,52 @@ function skipReason(s) {
3473
3839
  ].join(' and ');
3474
3840
  }
3475
3841
 
3842
+ /**
3843
+ * Up to `n` of these page templates that this app can show: each one's
3844
+ * packages installed and no StyleX compiler needed, as add itself checks.
3845
+ * The only pages a suggestion names.
3846
+ * @param {string} cwd
3847
+ * @param {string} appRoot the app whose packages a page needs
3848
+ * @param {string[]} ids in order of preference
3849
+ * @param {number} n
3850
+ * @returns {Promise<string[]>}
3851
+ */
3852
+ async function showablePages(cwd, appRoot, ids, n) {
3853
+ /** @type {string[]} */
3854
+ const out = [];
3855
+ for (const id of ids) {
3856
+ if (out.length >= n) break;
3857
+ try {
3858
+ const shownTemplate = /** @type {any} */ (
3859
+ await template(id, {cwd, type: 'page'})
3860
+ );
3861
+ const needs = pageNeeds(appRoot, shownTemplate.data.source);
3862
+ if (
3863
+ !needs.missingPackages.length &&
3864
+ !needs.notInstalled.length &&
3865
+ !needs.stylexCompiler
3866
+ )
3867
+ out.push(id);
3868
+ } catch {
3869
+ // A template that does not load is not suggested.
3870
+ }
3871
+ }
3872
+ return out;
3873
+ }
3874
+
3875
+ /**
3876
+ * The page a refusal's example adds: the first page template this app can
3877
+ * show (app frames left out), or null when there is none.
3878
+ * @param {string} cwd
3879
+ * @returns {Promise<string | null>}
3880
+ */
3881
+ async function examplePage(cwd) {
3882
+ const pages = (await pageTemplates(cwd))
3883
+ .filter(t => !/^Shell\b/.test(t.category ?? ''))
3884
+ .map(t => t.id);
3885
+ return (await showablePages(cwd, appRootOf(cwd, cwd), pages, 1))[0] ?? null;
3886
+ }
3887
+
3476
3888
  /**
3477
3889
  * The page templates for a description, best first, each with why: the
3478
3890
  * build ranking's picks, then the template search's, so a page the app
@@ -3485,9 +3897,10 @@ function skipReason(s) {
3485
3897
  * @param {string} cwd
3486
3898
  * @param {string[]} notes notes for the result
3487
3899
  * @param {string} flags the caller's other flags, for the suggestions
3900
+ * @param {string | null} [appRoot] the app whose packages a page needs
3488
3901
  * @returns {Promise<Array<{name: string, displayName: string, why: string}>>}
3489
3902
  */
3490
- async function rankedPages(words, cwd, notes, flags) {
3903
+ async function rankedPages(words, cwd, notes, flags, appRoot = null) {
3491
3904
  const kit =
3492
3905
  /** @type {import('../build/build.type.mjs').BuildKitResponse} */ (
3493
3906
  await build(words, {cwd})
@@ -3571,15 +3984,8 @@ async function rankedPages(words, cwd, notes, flags) {
3571
3984
  const label = name => listed.find(t => t.id === name)?.name ?? name;
3572
3985
  const suggest = (/** @type {string[]} */ list) =>
3573
3986
  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
- ];
3987
+ /** @param {string[]} ids */
3988
+ const showableOf = ids => showablePages(cwd, appRoot ?? cwd, ids, 3);
3583
3989
  // No page relates when the ranking fell back to a frame with no direct
3584
3990
  // match, and no page the search found matches three words of the request
3585
3991
  // or two fifths of them.
@@ -3604,19 +4010,32 @@ async function rankedPages(words, cwd, notes, flags) {
3604
4010
  !found.some(
3605
4011
  (/** @type {any} */ r) => !frames.has(r.name) && termsMatched(r) >= 2,
3606
4012
  )));
3607
- if (unrelated)
4013
+ if (unrelated) {
4014
+ // With no page close, a few pages this app can show, and the list.
4015
+ const offered = await showableOf(
4016
+ pages.length
4017
+ ? pages
4018
+ : [
4019
+ ...['dashboard', 'settings', 'login'],
4020
+ ...listed.map(t => t.id),
4021
+ ].filter(
4022
+ (id, i, all) =>
4023
+ all.indexOf(id) === i &&
4024
+ listed.some(t => t.id === id) &&
4025
+ !frames.has(id),
4026
+ ),
4027
+ );
3608
4028
  refuse(
3609
4029
  E.ERR_NOT_FOUND,
3610
4030
  `No page template relates to "${words}". Name a page to add it anyway.`,
3611
4031
  {
3612
- run: pages.length
3613
- ? [
3614
- ...suggest(pages),
3615
- formatCliCommand('template --list --type page', cwd),
3616
- ]
3617
- : fallback,
4032
+ run: [
4033
+ ...suggest(offered),
4034
+ formatCliCommand('template --list --type page', cwd),
4035
+ ],
3618
4036
  },
3619
4037
  );
4038
+ }
3620
4039
  if (skippedFrames.length)
3621
4040
  notes.push(
3622
4041
  `left out ${skippedFrames.join(', ')}: app frames, not pages (add one with --template <id>)`,
@@ -3866,6 +4285,17 @@ function wornTheme(cwd, slug, again, without) {
3866
4285
  },
3867
4286
  );
3868
4287
  }
4288
+ // A theme of a workspace app below (from the workspace root): the same
4289
+ // command, run from that app.
4290
+ const owners = nextAppsUnder(cwd).filter(a =>
4291
+ fs.existsSync(themeFiles(a.root, name).settings),
4292
+ );
4293
+ if (!themes.includes(name) && owners.length)
4294
+ refuse(
4295
+ E.ERR_UNKNOWN_THEME,
4296
+ `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.`,
4297
+ {run: owners.map(a => `${cdTo(shown(cwd, a.root))} && ${again(name)}`)},
4298
+ );
3869
4299
  const near = themes.includes(name) ? [name] : nearest(name, themes);
3870
4300
  if (near.length)
3871
4301
  refuse(
@@ -4082,10 +4512,15 @@ async function addPreview(description, options, box) {
4082
4512
  const said = (description ?? '').trim();
4083
4513
  const named =
4084
4514
  options.template == null ? null : String(options.template).trim();
4515
+ // A refusal's example is a page this app can show.
4516
+ const example = async () => {
4517
+ const id = await examplePage(cwd);
4518
+ return id ? [`${PREVIEW} add --template ${id}${tf}${pf}`] : [];
4519
+ };
4085
4520
  if (named === '')
4086
4521
  refuse(E.ERR_INVALID_ARGUMENT, '--template needs a page template id.', {
4087
4522
  run: [
4088
- `${PREVIEW} add --template dashboard${tf}${pf}`,
4523
+ ...(await example()),
4089
4524
  formatCliCommand('template --list --type page', cwd),
4090
4525
  ],
4091
4526
  });
@@ -4106,9 +4541,9 @@ async function addPreview(description, options, box) {
4106
4541
  E.ERR_INVALID_ARGUMENT,
4107
4542
  `--top takes 1, 2 or 3, not "${String(options.top)}".`,
4108
4543
  {
4109
- run: [
4110
- `${PREVIEW} add ${quoteCommandArgument(said || 'a sales dashboard')} --top 2${tf}${pf}`,
4111
- ],
4544
+ run: said
4545
+ ? [`${PREVIEW} add ${quoteCommandArgument(said)} --top 2${tf}${pf}`]
4546
+ : await example(),
4112
4547
  },
4113
4548
  );
4114
4549
  if (options.top != null && !said)
@@ -4118,11 +4553,12 @@ async function addPreview(description, options, box) {
4118
4553
  ? '--top says how many ranked pages to add; --template names one page, so drop --top.'
4119
4554
  : '--top says how many pages to add for a description, and there is none.',
4120
4555
  {
4121
- run: [
4556
+ run:
4122
4557
  named != null
4123
- ? `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`
4124
- : `${PREVIEW} add 'a sales dashboard' --top ${String(options.top)}${tf}${pf}`,
4125
- ],
4558
+ ? [
4559
+ `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`,
4560
+ ]
4561
+ : await example(),
4126
4562
  },
4127
4563
  );
4128
4564
  /** @type {string[]} */
@@ -4145,8 +4581,12 @@ async function addPreview(description, options, box) {
4145
4581
  );
4146
4582
  }
4147
4583
  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});
4584
+ `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${options.top != null ? ` --top ${quoteCommandArgument(String(options.top))}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4585
+ const at = previewDir(cwd, options.path, {
4586
+ write: true,
4587
+ retry,
4588
+ theme: options.theme ?? null,
4589
+ });
4150
4590
  const recovered = recoverPreview(cwd, at.dir);
4151
4591
  if (recovered) notes.push(recovered);
4152
4592
  const unstyled = coreStylesheetMissing(cwd, at);
@@ -4185,6 +4625,8 @@ async function addPreview(description, options, box) {
4185
4625
  wornTheme(cwd, options.theme, againWith, without);
4186
4626
  data.theme = options.theme;
4187
4627
  } else if (data.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir)) {
4628
+ // Not gone when the route imports it from outside this project folder.
4629
+ refuseThemeAway(cwd, at.dir, data.theme, retry);
4188
4630
  const themes = editedThemes(cwd);
4189
4631
  data.theme = themes.length === 1 ? themes[0] : null;
4190
4632
  notes.push(
@@ -4287,7 +4729,7 @@ async function addPreview(description, options, box) {
4287
4729
  const flags = `${tf}${pf}`;
4288
4730
  const picks = explicit
4289
4731
  ? [await namedTemplate(cwd, /** @type {string} */ (named), flags)]
4290
- : await rankedPages(words, cwd, notes, flags);
4732
+ : await rankedPages(words, cwd, notes, flags, appRootOf(cwd, at.dir));
4291
4733
  for (const [i, pick] of picks.entries()) {
4292
4734
  if (add.length >= (explicit ? 1 : top)) break;
4293
4735
  const shownTemplate =
@@ -4491,10 +4933,17 @@ async function addPreview(description, options, box) {
4491
4933
  } catch {
4492
4934
  // A theme that does not load is reported where it is used.
4493
4935
  }
4494
- if (again)
4495
- notes.push(
4496
- `a default page's id brings back the default pages that are missing, as ${PREVIEW} add does`,
4936
+ // What happened: only the page asked for; the others come with a bare
4937
+ // add.
4938
+ if (again) {
4939
+ const stillMissing = DEFAULT_IDS.filter(
4940
+ id => !data.pages.some(p => p.id === id),
4497
4941
  );
4942
+ if (stillMissing.length)
4943
+ notes.push(
4944
+ `only ${askedId} was added; ${PREVIEW} add with no page brings back the other default pages that are missing (${stillMissing.join(', ')})`,
4945
+ );
4946
+ }
4498
4947
  notes.push(...typeScriptNotes(cwd, at.dir, added));
4499
4948
  if (
4500
4949
  askedId === COLORS_PAGE.id &&
@@ -4546,7 +4995,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4546
4995
  refuse(
4547
4996
  E.ERR_INVALID_ARGUMENT,
4548
4997
  'Name the folder for the new app: a new or empty folder inside the current one.',
4549
- {run: [`${PREVIEW} app theme-app`]},
4998
+ {run: [appCommand(freeAppFolder(cwd))]},
4550
4999
  );
4551
5000
  options = {...options, theme: themeArg(options.theme)};
4552
5001
  const slug = options.theme ?? null;
@@ -4556,8 +5005,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4556
5005
  : wornTheme(
4557
5006
  cwd,
4558
5007
  slug,
4559
- t =>
4560
- `${PREVIEW} app ${quoteCommandArgument(dir)}${t == null ? '' : ` --theme ${t}`}`,
5008
+ t => appCommand(dir, t),
4561
5009
  'leave out --theme and the app wears the neutral theme',
4562
5010
  );
4563
5011
  // A new app has no Core installed yet: its pages come from this CLI's own
@@ -4608,6 +5056,8 @@ export async function themeEditPreviewApp(dir, options = {}) {
4608
5056
  from.sheet,
4609
5057
  from.previewPng,
4610
5058
  from.sheetPng,
5059
+ // The record of pictures, none of which come along.
5060
+ from.pictures,
4611
5061
  ].map(f => path.basename(f)),
4612
5062
  );
4613
5063
  // The whole folder, tokens/ included, as bytes: a font or a picture
@@ -4622,6 +5072,12 @@ export async function themeEditPreviewApp(dir, options = {}) {
4622
5072
  else if (
4623
5073
  entry.isFile() &&
4624
5074
  !(rel === '' && skip.has(entry.name)) &&
5075
+ // No picture or preview page of any kind (dark pictures, section
5076
+ // sheets): the new app builds its own.
5077
+ !(
5078
+ rel === '' &&
5079
+ /^(preview|sheet)(-[a-z0-9-]+)?\.(html|png)$/.test(entry.name)
5080
+ ) &&
4625
5081
  // A temp file a stopped command left is no part of the theme.
4626
5082
  !isEditorTemp(entry.name)
4627
5083
  )
@@ -4632,6 +5088,30 @@ export async function themeEditPreviewApp(dir, options = {}) {
4632
5088
  }
4633
5089
  };
4634
5090
  copyDir('');
5091
+ // A source file of the theme that imports a file outside its folder
5092
+ // would not build in the new app, where that file is not: refused,
5093
+ // naming the import, before anything is written.
5094
+ const outside = themeCopy.flatMap(c => {
5095
+ const rel = path.relative(to.dir, c.rel);
5096
+ if (!/\.(mjs|cjs|js|mts|cts|ts|tsx|jsx)$/.test(rel)) return [];
5097
+ const file = path.join(from.dir, rel);
5098
+ return importSpecifiers(file, String(c.text))
5099
+ .filter(spec => spec.startsWith('.'))
5100
+ .filter(spec => {
5101
+ const at = path.resolve(path.dirname(file), spec);
5102
+ return at !== from.dir && !at.startsWith(from.dir + path.sep);
5103
+ })
5104
+ .map(spec => `${shown(cwd, file)} imports '${spec}'`);
5105
+ });
5106
+ if (outside.length)
5107
+ refuse(
5108
+ E.ERR_INVALID_ARGUMENT,
5109
+ `${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.`,
5110
+ {
5111
+ fix: `move what it imports into ${shown(cwd, from.dir)}/ (and import it from there), then run the command again`,
5112
+ run: [appCommand(dir, slug)],
5113
+ },
5114
+ );
4635
5115
  if (theme.like && theme.like !== 'neutral')
4636
5116
  dependencies[`@astryxdesign/theme-${theme.like}`] = cliVersion();
4637
5117
  // The copied build was made on this project's Core and base theme: the
@@ -4662,7 +5142,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4662
5142
  };
4663
5143
  // The new app installs its own packages, so every open font the theme
4664
5144
  // names is added, at the version this project has, else a known one.
4665
- const fonts = fontPackages(ctx, theme);
5145
+ const fonts = fontPackages(ctx, theme, {forNewApp: true});
4666
5146
  for (const font of fonts)
4667
5147
  dependencies[font.pkg] =
4668
5148
  readVersion(project, font.pkg) ?? OPEN_FONT_RANGE;
@@ -4738,12 +5218,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4738
5218
  dependencies,
4739
5219
  slug,
4740
5220
  );
4741
- const files = writeStarterApp(
4742
- cwd,
4743
- plan,
4744
- d =>
4745
- `${PREVIEW} app ${quoteCommandArgument(d)}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`,
4746
- );
5221
+ const files = writeStarterApp(cwd, plan, d => appCommand(d, slug));
4747
5222
  const folder = shownDir(cwd, plan.root);
4748
5223
  if (
4749
5224
  plan.root !== cwd &&
@@ -4765,7 +5240,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4765
5240
  files,
4766
5241
  notes,
4767
5242
  // 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`,
5243
+ open: `${cdTo(folder)} && npm install && npm run dev, then open /theme-preview`,
4769
5244
  },
4770
5245
  };
4771
5246
  }
@@ -4854,7 +5329,9 @@ export async function themeEditPreviewList(options = {}) {
4854
5329
  /** @type {string[]} */
4855
5330
  const notes = [];
4856
5331
  const themeMissing = Boolean(
4857
- data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
5332
+ data?.theme &&
5333
+ !fs.existsSync(themeFiles(cwd, data.theme).dir) &&
5334
+ !(at && themeElsewhere(cwd, at.dir, data.theme)),
4858
5335
  );
4859
5336
  if (at && fs.existsSync(path.join(at.dir, PENDING)))
4860
5337
  notes.push(
@@ -4943,7 +5420,116 @@ export async function themeEditPreviewList(options = {}) {
4943
5420
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewRemoveResponse>}
4944
5421
  */
4945
5422
  export async function themeEditPreviewRemove(page, options = {}) {
4946
- return reportingRecovery(box => removePreview(page, options, box));
5423
+ try {
5424
+ return await reportingRecovery(box => removePreview(page, options, box));
5425
+ } catch (e) {
5426
+ // Removing a page needs the theme the route wears; removing the whole
5427
+ // preview needs none. Every refusal over a theme that does not load
5428
+ // names it, wherever the theme was read.
5429
+ const err = /** @type {any} */ (e);
5430
+ const pf =
5431
+ options.path != null
5432
+ ? ` --path ${quoteCommandArgument(options.path)}`
5433
+ : '';
5434
+ const whole = `${PREVIEW} remove${pf}`;
5435
+ if (
5436
+ page != null &&
5437
+ [E.ERR_THEME_INVALID, E.ERR_UNKNOWN_THEME, E.ERR_THEME_LOAD].includes(
5438
+ err?.code,
5439
+ ) &&
5440
+ !(err.suggestions ?? []).some((/** @type {any} */ x) => x?.name === whole)
5441
+ )
5442
+ err.suggestions = [
5443
+ {
5444
+ name: whole,
5445
+ reason:
5446
+ 'do this instead: removes the whole preview, which needs no theme',
5447
+ },
5448
+ ...(err.suggestions ?? []),
5449
+ ];
5450
+ throw e;
5451
+ }
5452
+ }
5453
+
5454
+ /**
5455
+ * Refuse a preview command run in a project folder below the one that holds
5456
+ * the theme the preview wears (a workspace app run from its own folder): the
5457
+ * theme is not gone, and no command rewrites it away. The refusal names
5458
+ * the same command, run from the folder that holds the theme.
5459
+ * @param {string} cwd
5460
+ * @param {string} dir the preview folder
5461
+ * @param {string} slug the theme the preview wears
5462
+ * @param {Retry} again the same command, with every argument it was given,
5463
+ * for a --path
5464
+ */
5465
+ function refuseThemeAway(cwd, dir, slug, again) {
5466
+ const away = themeElsewhere(cwd, dir, slug);
5467
+ if (!away) return;
5468
+ const root = path.dirname(path.dirname(away));
5469
+ refuse(
5470
+ E.ERR_INVALID_ARGUMENT,
5471
+ `The preview wears ${slug}, whose theme folder is ${away}/, outside this project folder (${cwd}). Run the command from the folder that holds themes/${slug}/.`,
5472
+ {
5473
+ run: [`${cdTo(root)} && ${again(path.relative(root, dir))}`],
5474
+ },
5475
+ );
5476
+ }
5477
+
5478
+ /**
5479
+ * The theme folder a preview's route imports when it is outside this
5480
+ * project's themes/ (a workspace app run from its own folder, its themes at
5481
+ * the workspace root), or null.
5482
+ * @param {string} cwd
5483
+ * @param {string} dir the preview folder
5484
+ * @param {string} slug
5485
+ * @returns {string | null}
5486
+ */
5487
+ function themeElsewhere(cwd, dir, slug) {
5488
+ if (fs.existsSync(themeFiles(cwd, slug).dir)) return null;
5489
+ /** @type {string} */
5490
+ let route;
5491
+ try {
5492
+ route = fs.readFileSync(path.join(dir, 'page.tsx'), 'utf8');
5493
+ } catch {
5494
+ return null;
5495
+ }
5496
+ const esc = slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5497
+ const m = new RegExp(`['"]([^'"]*themes/${esc})/${esc}[^'"]*['"]`).exec(
5498
+ route,
5499
+ );
5500
+ if (!m || !m[1].startsWith('.')) return null;
5501
+ const found = path.resolve(dir, m[1]);
5502
+ return fs.existsSync(path.join(found, `${slug}.settings.json`))
5503
+ ? found
5504
+ : null;
5505
+ }
5506
+
5507
+ /**
5508
+ * The previews a theme may have: the ones recorded with it (added with
5509
+ * --path) and every preview in the routes folders (one renamed by hand, or
5510
+ * one whose record was lost). The one list `see`, a change's refresh and
5511
+ * the preview commands read; each reads a preview's record for its theme.
5512
+ * @param {string} cwd
5513
+ * @param {string} slug
5514
+ * @returns {string[]}
5515
+ */
5516
+ function themePreviews(cwd, slug) {
5517
+ return [...new Set([...recordedPreviews(cwd, slug), ...previewsIn(cwd)])];
5518
+ }
5519
+
5520
+ /**
5521
+ * Every preview in the app, of any editor theme: the previews of each, by
5522
+ * {@link themePreviews}, that are there.
5523
+ * @param {string} cwd
5524
+ * @returns {string[]}
5525
+ */
5526
+ function allPreviews(cwd) {
5527
+ return [
5528
+ ...new Set([
5529
+ ...editedThemes(cwd).flatMap(t => themePreviews(cwd, t)),
5530
+ ...previewsIn(cwd),
5531
+ ]),
5532
+ ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
4947
5533
  }
4948
5534
 
4949
5535
  /**
@@ -4994,6 +5580,24 @@ async function removePreview(page, options, box) {
4994
5580
  const retry = (/** @type {string | null} */ p) =>
4995
5581
  `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4996
5582
  const at = previewDir(cwd, options.path, {retry});
5583
+ // A file given for the preview's folder: its folder when the file is a
5584
+ // preview's own, else the previews there are (as add refuses a file).
5585
+ if (fs.existsSync(at.dir) && !fs.statSync(at.dir).isDirectory()) {
5586
+ const parent = path.dirname(at.dir);
5587
+ const own = fs.existsSync(path.join(parent, PREVIEW_DATA));
5588
+ const others = previewsIn(cwd);
5589
+ refuse(
5590
+ E.ERR_INVALID_ARGUMENT,
5591
+ `${shown(cwd, at.dir)} is a file; a preview is a folder${own ? `, and this file is in the preview ${shownDir(cwd, parent)}/` : ''}.`,
5592
+ {
5593
+ run: own
5594
+ ? [retry(shownDir(cwd, parent))]
5595
+ : others.length
5596
+ ? others.slice(0, 3).map(d => retry(shownDir(cwd, d)))
5597
+ : [`${PREVIEW} list`],
5598
+ },
5599
+ );
5600
+ }
4997
5601
  // The pages a stopped change was removing, read before it is finished.
4998
5602
  /** @type {string[]} */
4999
5603
  let removing = [];
@@ -5179,6 +5783,7 @@ async function removePreview(page, options, box) {
5179
5783
  const wore = data.theme;
5180
5784
  /** @type {string | null} */
5181
5785
  let gone = null;
5786
+ if (wore) refuseThemeAway(cwd, at.dir, wore, retry);
5182
5787
  if (wore && !fs.existsSync(themeFiles(cwd, wore).dir)) {
5183
5788
  gone = wore;
5184
5789
  data.theme = null;
@@ -5214,26 +5819,10 @@ async function removePreview(page, options, box) {
5214
5819
  let planned;
5215
5820
  /** @type {Awaited<ReturnType<typeof routeTheme>>} */
5216
5821
  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
- }
5822
+ // A theme that does not load is refused with the whole-preview remove
5823
+ // named (themeEditPreviewRemove adds it to every such refusal).
5824
+ theme = await routeTheme(cwd, at.dir, data, {build: false});
5825
+ planned = await routeWrites(cwd, at.dir, data, theme, {gone});
5237
5826
  const elsewhere = `${PREVIEW} remove${pf}`;
5238
5827
  /** @type {Map<string, {rel: string, text: string, keepHash?: boolean}>} */
5239
5828
  const writes = new Map(move.writes.map(w => [w.rel, w]));