@astryxdesign/cli 0.7.16 → 0.7.17-canary.g49a475f

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 (354) 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 +75 -0
  79. package/api/theme/build/build.mjs +243 -58
  80. package/api/theme/build/font-warning.d.mts +7 -0
  81. package/api/theme/build/font-warning.mjs +17 -0
  82. package/api/theme/theme.type.d.mts +10 -0
  83. package/api/theme/theme.type.mjs +7 -1
  84. package/api/theme-edit/_adapter.d.mts +63 -2
  85. package/api/theme-edit/_adapter.mjs +771 -57
  86. package/api/theme-edit/_check.d.mts +40 -22
  87. package/api/theme-edit/_check.mjs +2029 -336
  88. package/api/theme-edit/_color.d.mts +10 -0
  89. package/api/theme-edit/_color.mjs +49 -1
  90. package/api/theme-edit/_compiler.mjs +9 -0
  91. package/api/theme-edit/_context.d.mts +3 -3
  92. package/api/theme-edit/_context.mjs +111 -48
  93. package/api/theme-edit/_css.d.mts +14 -0
  94. package/api/theme-edit/_css.mjs +46 -1
  95. package/api/theme-edit/_edit.d.mts +18 -4
  96. package/api/theme-edit/_edit.mjs +1685 -155
  97. package/api/theme-edit/_how-commands.d.mts +65 -0
  98. package/api/theme-edit/_how-commands.mjs +633 -1
  99. package/api/theme-edit/_how-question.d.mts +84 -0
  100. package/api/theme-edit/_how-question.mjs +5124 -281
  101. package/api/theme-edit/_how.mjs +140 -29
  102. package/api/theme-edit/_marks.d.mts +31 -5
  103. package/api/theme-edit/_marks.mjs +57 -5
  104. package/api/theme-edit/_name-rule.d.mts +11 -0
  105. package/api/theme-edit/_name-rule.mjs +12 -0
  106. package/api/theme-edit/_normal.d.mts +257 -0
  107. package/api/theme-edit/_normal.mjs +1252 -0
  108. package/api/theme-edit/_palette.mjs +10 -4
  109. package/api/theme-edit/_parts.d.mts +10 -1
  110. package/api/theme-edit/_parts.mjs +179 -3
  111. package/api/theme-edit/_preview-app.d.mts +7 -1
  112. package/api/theme-edit/_preview-app.mjs +515 -148
  113. package/api/theme-edit/_preview.d.mts +100 -14
  114. package/api/theme-edit/_preview.mjs +549 -137
  115. package/api/theme-edit/_settings.d.mts +347 -30
  116. package/api/theme-edit/_settings.mjs +2971 -327
  117. package/api/theme-edit/_tables.d.mts +6 -0
  118. package/api/theme-edit/_tables.mjs +44 -1
  119. package/api/theme-edit/_vet.d.mts +18 -0
  120. package/api/theme-edit/_vet.mjs +32 -0
  121. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  122. package/api/theme-edit/theme-edit.type.mjs +4 -1
  123. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  124. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  125. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  126. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  127. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  128. package/api/upgrade/run/run.mjs +4 -3
  129. package/assets/codemods/integration-discovery.mjs +2 -1
  130. package/assets/codemods/run-codemod.mjs +87 -7
  131. package/assets/codemods/transforms/next/index.mjs +11 -1
  132. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  133. package/assets/component-list.generated.json +1 -0
  134. package/assets/docs/author-a-theme.doc.mjs +1 -0
  135. package/assets/docs/theme.doc.dense.mjs +2 -2
  136. package/assets/docs/theme.doc.mjs +1 -1
  137. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  138. package/assets/docs/tree/checks.doc.mjs +1 -1
  139. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  140. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  141. package/assets/docs/tree/single-component.doc.mjs +4 -0
  142. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  143. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  144. package/assets/docs/use-a-theme.doc.mjs +1 -1
  145. package/assets/docs.generated.json +2 -2
  146. package/assets/search-catalog.generated.json +2 -0
  147. package/assets/self-audit.generated.json +1 -1
  148. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  149. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  150. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  151. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  152. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  153. package/assets/templates/components.generated.json +1 -1
  154. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  155. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  156. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  157. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  158. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  159. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  160. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  161. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  162. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  163. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  164. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  165. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  166. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  167. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  168. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  169. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  170. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  171. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  172. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  173. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  174. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  175. package/assets/templates/pages/ide/page.tsx +24 -2
  176. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  177. package/assets/templates/pages/library/template.doc.mjs +4 -1
  178. package/assets/templates/pages/login/template.doc.mjs +2 -1
  179. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  180. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  181. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  182. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  183. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  184. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  185. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  186. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  187. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  188. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  189. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  190. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  191. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  192. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  193. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  194. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  195. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  196. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  197. package/assets/theme.template.ts +6 -0
  198. package/authoring/debug/parse.d.mts +3 -3
  199. package/authoring/doctypes/_schema.d.mts +3 -3
  200. package/authoring/doctypes/command/command.doc.mjs +1 -1
  201. package/authoring/doctypes/component/categories.d.mts +37 -0
  202. package/authoring/doctypes/component/categories.mjs +54 -0
  203. package/authoring/doctypes/template/template.doc.mjs +1 -1
  204. package/authoring/doctypes/template/type.ts +9 -0
  205. package/authoring/example/example.doc.d.mts +12 -0
  206. package/authoring/example/example.doc.mjs +69 -0
  207. package/authoring/example/preview.d.mts +92 -0
  208. package/authoring/example/preview.mjs +994 -0
  209. package/authoring/example/type.ts +102 -0
  210. package/authoring/index.d.mts +1 -0
  211. package/authoring/index.d.ts +12 -0
  212. package/authoring/index.mjs +3 -1
  213. package/clients/cli/bin/astryx.mjs +6 -9
  214. package/clients/cli/build-id.generated.json +1 -1
  215. package/clients/cli/commands/component.doc.mjs +1 -1
  216. package/clients/cli/commands/component.mjs +22 -3
  217. package/clients/cli/commands/docs.doc.mjs +7 -1
  218. package/clients/cli/commands/docs.mjs +3 -1
  219. package/clients/cli/commands/doctor.mjs +32 -14
  220. package/clients/cli/commands/experimental/render.mjs +42 -1
  221. package/clients/cli/commands/experimental/theme.mjs +163 -28
  222. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  223. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  224. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  225. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  226. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  227. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  228. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  229. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  230. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  231. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  232. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  233. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  234. package/clients/cli/commands/search.doc.mjs +2 -1
  235. package/clients/cli/commands/search.mjs +6 -1
  236. package/clients/cli/commands/template.mjs +4 -2
  237. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  238. package/clients/cli/commands/theme.doc.mjs +1 -1
  239. package/clients/cli/commands/theme.mjs +209 -8
  240. package/clients/cli/commands/upgrade.mjs +42 -7
  241. package/clients/cli/index.mjs +1 -1
  242. package/clients/cli/lib/cli-error.mjs +2 -1
  243. package/clients/cli/lib/component-format.mjs +205 -98
  244. package/clients/cli/lib/hook-format.mjs +9 -19
  245. package/clients/cli/lib/json-shim.mjs +77 -21
  246. package/clients/cli/lib/manifest.mjs +3 -2
  247. package/clients/cli/manifest.generated.json +1 -1
  248. package/foundation/agent-docs/agent-docs.mjs +1 -1
  249. package/foundation/config/theme-state.d.mts +13 -1
  250. package/foundation/config/theme-state.mjs +47 -7
  251. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  252. package/foundation/discovery/component-discovery.d.mts +11 -0
  253. package/foundation/discovery/component-discovery.mjs +56 -8
  254. package/foundation/discovery/component-replacement.mjs +130 -1
  255. package/foundation/discovery/copied-passages.mjs +2 -1
  256. package/foundation/discovery/doc-types.mjs +4 -3
  257. package/foundation/discovery/entry-name-files.d.mts +43 -0
  258. package/foundation/discovery/entry-name-files.mjs +264 -0
  259. package/foundation/discovery/hook-discovery.d.mts +8 -2
  260. package/foundation/discovery/hook-discovery.mjs +22 -8
  261. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  262. package/foundation/discovery/icon-set-checks.mjs +2 -1
  263. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  264. package/foundation/discovery/integration-doc-files.mjs +2 -1
  265. package/foundation/discovery/package-exports.d.mts +10 -0
  266. package/foundation/discovery/package-exports.mjs +56 -3
  267. package/foundation/discovery/prop-drift.mjs +9 -9
  268. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  269. package/foundation/discovery/runner-allowlist.mjs +2 -0
  270. package/foundation/discovery/stored-component-list.d.mts +43 -0
  271. package/foundation/discovery/stored-component-list.mjs +90 -0
  272. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  273. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  274. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  275. package/foundation/discovery/stored-self-audit.mjs +38 -18
  276. package/foundation/discovery/template-adapter.d.mts +52 -0
  277. package/foundation/discovery/template-adapter.mjs +176 -12
  278. package/foundation/discovery/template-icons.mjs +2 -1
  279. package/foundation/discovery/theme-discovery.mjs +3 -2
  280. package/foundation/discovery/theme-imports.d.mts +14 -0
  281. package/foundation/discovery/theme-imports.mjs +43 -1
  282. package/foundation/discovery/theming-targets.mjs +3 -2
  283. package/foundation/doc-compiler/import.mjs +7 -1
  284. package/foundation/doc-compiler/inputs.mjs +3 -2
  285. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  286. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  287. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  288. package/foundation/env/semver.mjs +3 -1
  289. package/foundation/fonts/font-stylesheet.d.mts +31 -0
  290. package/foundation/fonts/font-stylesheet.mjs +115 -0
  291. package/foundation/fs/cache-eviction.d.mts +21 -0
  292. package/foundation/fs/cache-eviction.mjs +73 -0
  293. package/foundation/fs/file-protection.mjs +4 -3
  294. package/foundation/fs/gather-cache.d.mts +25 -4
  295. package/foundation/fs/gather-cache.mjs +164 -55
  296. package/foundation/fs/jiti-cache.d.mts +19 -1
  297. package/foundation/fs/jiti-cache.mjs +130 -6
  298. package/foundation/fs/kept-tree.d.mts +60 -0
  299. package/foundation/fs/kept-tree.mjs +154 -0
  300. package/foundation/fs/listing-cache.d.mts +7 -0
  301. package/foundation/fs/listing-cache.mjs +10 -0
  302. package/foundation/fs/module-loader.d.mts +24 -2
  303. package/foundation/fs/module-loader.mjs +94 -21
  304. package/foundation/fs/paths.d.mts +18 -0
  305. package/foundation/fs/paths.mjs +15 -2
  306. package/foundation/identity/provider-identity.d.mts +6 -0
  307. package/foundation/identity/provider-identity.mjs +10 -1
  308. package/foundation/integrations/contribution-inventory.mjs +4 -3
  309. package/foundation/integrations/example-code.d.mts +63 -0
  310. package/foundation/integrations/example-code.mjs +416 -0
  311. package/foundation/integrations/public-imports.d.mts +9 -0
  312. package/foundation/integrations/public-imports.mjs +3 -2
  313. package/foundation/integrations/validate-contributions.mjs +17 -45
  314. package/foundation/render/embedded-files.d.mts +6 -0
  315. package/foundation/render/embedded-files.mjs +25 -5
  316. package/foundation/render/embedded-imports.d.mts +39 -7
  317. package/foundation/render/embedded-imports.mjs +66 -27
  318. package/foundation/render/file-header.d.mts +66 -0
  319. package/foundation/render/file-header.mjs +118 -0
  320. package/foundation/render/host-answer.d.mts +18 -0
  321. package/foundation/render/host-answer.mjs +46 -0
  322. package/foundation/render/host-exit.d.mts +1 -0
  323. package/foundation/render/host-exit.mjs +6 -1
  324. package/foundation/render/html-reader.d.mts +55 -2
  325. package/foundation/render/html-reader.mjs +145 -26
  326. package/foundation/render/markup-edits.d.mts +57 -0
  327. package/foundation/render/markup-edits.mjs +182 -0
  328. package/foundation/render/page-host.mjs +29 -12
  329. package/foundation/render/page-worker.mjs +121 -13
  330. package/foundation/render/picture-chrome.d.mts +4 -0
  331. package/foundation/render/picture-chrome.mjs +185 -0
  332. package/foundation/render/picture-playwright.d.mts +4 -0
  333. package/foundation/render/picture-playwright.mjs +34 -0
  334. package/foundation/render/rebuild.mjs +2 -1
  335. package/foundation/render/render-page.d.mts +35 -3
  336. package/foundation/render/render-page.mjs +316 -42
  337. package/foundation/render/source-block.d.mts +85 -6
  338. package/foundation/render/source-block.mjs +211 -20
  339. package/foundation/render/ts-paths.d.mts +69 -6
  340. package/foundation/render/ts-paths.mjs +326 -40
  341. package/foundation/response/error-codes.d.mts +3 -1
  342. package/foundation/response/error-codes.d.ts +1 -0
  343. package/foundation/response/error-codes.doc.mjs +12 -1
  344. package/foundation/response/error-codes.mjs +11 -1
  345. package/foundation/response/response-types.doc.mjs +2 -2
  346. package/foundation/text/compare-text.d.mts +14 -0
  347. package/foundation/text/compare-text.mjs +68 -0
  348. package/foundation/text/string-utils.d.mts +3 -2
  349. package/foundation/text/string-utils.mjs +18 -4
  350. package/foundation/text/suggest-order.d.mts +9 -0
  351. package/foundation/text/suggest-order.mjs +15 -1
  352. package/foundation/xle/expand.mjs +2 -1
  353. package/host/index.mjs +8 -6
  354. package/package.json +7 -6
@@ -63,6 +63,7 @@ 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
69
  import {requireProject, context} from './_context.mjs';
@@ -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));
@@ -588,6 +571,21 @@ function reservedFolder(cwd, dir) {
588
571
  return null;
589
572
  }
590
573
 
574
+ /**
575
+ * The compile of an editor theme as it runs from the folder the command ran
576
+ * in: an editor theme compiles from the app root, so from a subfolder the
577
+ * line goes there first.
578
+ * @param {string} cwd the app root
579
+ * @param {string} slug
580
+ */
581
+ function compileFromHere(cwd, slug) {
582
+ const line = `${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)}`;
583
+ const up = path.relative(process.cwd(), cwd);
584
+ return up && path.resolve(process.cwd()) !== path.resolve(cwd)
585
+ ? `cd ${quoteCommandArgument(up.split(path.sep).join('/'))} && ${line}`
586
+ : line;
587
+ }
588
+
591
589
  /**
592
590
  * The app's tsconfig.json compiler options (comments and trailing commas
593
591
  * allowed), or null when there is none.
@@ -999,7 +997,12 @@ function checkPlacement(cwd, dir, where, retry) {
999
997
  if (served && app !== served)
1000
998
  refuse(
1001
999
  E.ERR_INVALID_ARGUMENT,
1002
- `${where} is in ${shown(cwd, app)}/, and Next serves ${shown(cwd, served)}/ instead when both are there.`,
1000
+ // Next serves the root app/ when both are there: a preview in src/app/
1001
+ // under a root app/ is not served, and a new root app/ beside the
1002
+ // app's src/app/ would hide the whole app.
1003
+ path.resolve(app) === path.join(path.resolve(cwd), 'app')
1004
+ ? `${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.`
1005
+ : `${where} is in ${shown(cwd, app)}/, and Next serves ${shown(cwd, served)}/ instead when both are there.`,
1003
1006
  {
1004
1007
  run: fs.existsSync(path.join(dir, PREVIEW_DATA))
1005
1008
  ? [
@@ -1010,9 +1013,7 @@ function checkPlacement(cwd, dir, where, retry) {
1010
1013
  );
1011
1014
  const exts = readNextConfig(cwd).pageExtensions;
1012
1015
  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}`;
1016
+ const free = freeAppFolder(cwd);
1016
1017
  refuse(
1017
1018
  E.ERR_INVALID_ARGUMENT,
1018
1019
  `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx, the route file the preview writes.`,
@@ -1031,9 +1032,7 @@ function checkPlacement(cwd, dir, where, retry) {
1031
1032
  !rootLayouts.length &&
1032
1033
  !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)))
1033
1034
  ) {
1034
- let free = 'theme-app';
1035
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1036
- free = `theme-app-${n}`;
1035
+ const free = freeAppFolder(cwd);
1037
1036
  refuse(
1038
1037
  E.ERR_INVALID_ARGUMENT,
1039
1038
  `${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}.`,
@@ -1098,11 +1097,30 @@ function previewDir(cwd, where, opts = {}) {
1098
1097
  checkFolderName(where, '--path', retry);
1099
1098
  /** @type {string} */
1100
1099
  let dir;
1100
+ // A --path read from the folder the command ran in; one that names a
1101
+ // preview from the project root (as every printed folder is) is read
1102
+ // from there, so a printed tip works from a subfolder too.
1103
+ const fromRoot = (() => {
1104
+ // The --path as given from the subfolder the command ran in, rebased
1105
+ // onto the project root by the caller: when that names no folder and
1106
+ // the path without the subfolder names a preview, that one.
1107
+ const sub = path.relative(cwd, process.cwd());
1108
+ if (!sub || sub.startsWith('..') || path.isAbsolute(where)) return null;
1109
+ const given = path.normalize(where);
1110
+ if (!given.startsWith(sub + path.sep)) return null;
1111
+ const there = path.resolve(cwd, given.slice(sub.length + 1));
1112
+ return !fs.existsSync(path.resolve(cwd, where)) &&
1113
+ fs.existsSync(path.join(there, PREVIEW_DATA))
1114
+ ? there
1115
+ : null;
1116
+ })();
1101
1117
  try {
1102
- dir = assertWithin(path.resolve(cwd, where), cwd, {
1103
- allowAbsolute: true,
1104
- label: '--path',
1105
- });
1118
+ dir =
1119
+ fromRoot ??
1120
+ assertWithin(path.resolve(cwd, where), cwd, {
1121
+ allowAbsolute: true,
1122
+ label: '--path',
1123
+ });
1106
1124
  } catch (e) {
1107
1125
  if (e instanceof PathSafetyError)
1108
1126
  refuse(
@@ -1164,11 +1182,11 @@ function previewDir(cwd, where, opts = {}) {
1164
1182
  const candidates = routes.map(r => path.join(r, 'theme-preview'));
1165
1183
  const known = candidates.find(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
1166
1184
  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)));
1185
+ // A preview added with --path is recorded with its theme, and one
1186
+ // renamed by hand is found in the routes folders (as list, remove and
1187
+ // see find it), so a later command uses it instead of starting a second
1188
+ // one.
1189
+ const recorded = allPreviews(cwd);
1172
1190
  if (recorded.length === 1) {
1173
1191
  inProjectOrRefuse(cwd, recorded[0], retry);
1174
1192
  if (opts.write)
@@ -1207,14 +1225,15 @@ function previewDir(cwd, where, opts = {}) {
1207
1225
  ? `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
1226
  : 'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
1209
1227
  {
1228
+ // Each app's own folder is where a preview command for it runs.
1210
1229
  run: [
1211
1230
  ...apps
1212
1231
  .slice(0, 3)
1213
1232
  .map(
1214
1233
  a =>
1215
- `${PREVIEW} add --path ${quoteCommandArgument(shown(cwd, path.join(a.routes, 'theme-preview')))}`,
1234
+ `cd ${quoteCommandArgument(shown(cwd, a.root))} && ${PREVIEW} add`,
1216
1235
  ),
1217
- `${PREVIEW} app theme-app # a new starter app with the preview in it`,
1236
+ `${PREVIEW} app ${quoteCommandArgument(freeAppFolder(cwd))} # a new starter app with the preview in it`,
1218
1237
  ],
1219
1238
  },
1220
1239
  );
@@ -1224,6 +1243,18 @@ function previewDir(cwd, where, opts = {}) {
1224
1243
  return {dir, app: appOf(dir)};
1225
1244
  }
1226
1245
 
1246
+ /**
1247
+ * A folder name for a new starter app that is free in `cwd`: theme-app, else
1248
+ * theme-app-2, theme-app-3 and so on.
1249
+ * @param {string} cwd
1250
+ */
1251
+ function freeAppFolder(cwd) {
1252
+ let free = 'theme-app';
1253
+ for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1254
+ free = `theme-app-${n}`;
1255
+ return free;
1256
+ }
1257
+
1227
1258
  /**
1228
1259
  * The Next apps in folders below `cwd` (a few levels, node_modules left
1229
1260
  * out): each folder with a package.json that depends on `next` and a routes
@@ -1258,7 +1289,7 @@ function nextAppsUnder(cwd) {
1258
1289
  }
1259
1290
  };
1260
1291
  walk(cwd, 1);
1261
- return out.sort((a, b) => a.root.localeCompare(b.root));
1292
+ return out.sort((a, b) => compareText(a.root, b.root));
1262
1293
  }
1263
1294
 
1264
1295
  /**
@@ -1281,7 +1312,7 @@ export function addWiring(cwd, slug, mode = 'system') {
1281
1312
  : [
1282
1313
  `${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
1314
  ]),
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`,
1315
+ `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
1316
  ];
1286
1317
  }
1287
1318
 
@@ -1324,7 +1355,7 @@ export function appWiring(ctx, slug, data) {
1324
1355
  return [
1325
1356
  ...(blocker
1326
1357
  ? [
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:`,
1358
+ `the app copy in src/themes/${slug}/ was not updated: ${blocker}; the steps by hand:`,
1328
1359
  ]
1329
1360
  : []),
1330
1361
  `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 +1365,7 @@ export function appWiring(ctx, slug, data) {
1334
1365
  `${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
1366
  ]
1336
1367
  : []),
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`,
1368
+ `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
1369
  ];
1339
1370
  }
1340
1371
 
@@ -1488,7 +1519,7 @@ export default function Home() {
1488
1519
  */
1489
1520
  function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1490
1521
  const again = (/** @type {string | null} */ p) =>
1491
- `${PREVIEW} app ${quoteCommandArgument(p ?? 'theme-app')}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`;
1522
+ `${PREVIEW} app ${quoteCommandArgument(p ?? freeAppFolder(cwd))}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`;
1492
1523
  checkFolderName(where, 'The app folder', again);
1493
1524
  /** @type {string} */
1494
1525
  let root;
@@ -1501,7 +1532,7 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1501
1532
  if (e instanceof PathSafetyError)
1502
1533
  refuse(
1503
1534
  E.ERR_PATH_TRAVERSAL,
1504
- `${where} is outside the current folder; make the app inside the folder you run the command from.`,
1535
+ `${where} is outside the project; make the app inside the project folder.`,
1505
1536
  {run: [again(null)]},
1506
1537
  );
1507
1538
  throw e;
@@ -1529,9 +1560,7 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1529
1560
  ? `${shownDir(cwd, t)}/ differs from it only in case, and on macOS and Windows they are one folder`
1530
1561
  : null)(sameCaseSibling(root));
1531
1562
  if (why) {
1532
- let free = 'theme-app';
1533
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1534
- free = `theme-app-${n}`;
1563
+ const free = freeAppFolder(cwd);
1535
1564
  refuse(
1536
1565
  E.ERR_INVALID_ARGUMENT,
1537
1566
  `${name} is no place for a new app: ${why}.`,
@@ -1590,7 +1619,7 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1590
1619
  file,
1591
1620
  text:
1592
1621
  key === 'package.json'
1593
- ? starterPackageJson(text, dependencies)
1622
+ ? starterPackageJson(text, dependencies, starterName(cwd, root))
1594
1623
  : key === 'src/app/page.tsx'
1595
1624
  ? STARTER_HOME
1596
1625
  : key === 'src/app/layout.tsx'
@@ -1623,18 +1652,34 @@ function starterLayout(text) {
1623
1652
  }
1624
1653
 
1625
1654
  /**
1626
- * The starter's package.json with the Astryx packages pinned to this CLI's
1627
- * release, and `dependencies` added.
1655
+ * The new app's package name, from its folder's path in the project: two
1656
+ * starter apps in one workspace never share a name, which would break the
1657
+ * whole workspace's install.
1658
+ * @param {string} cwd the project root
1659
+ * @param {string} root the new app's folder
1660
+ */
1661
+ function starterName(cwd, root) {
1662
+ const rel = (path.relative(cwd, root) || path.basename(root))
1663
+ .toLowerCase()
1664
+ .replace(/[^a-z0-9]+/g, '-')
1665
+ .replace(/^-+|-+$/g, '');
1666
+ return `astryx-theme-preview-${rel || 'app'}`;
1667
+ }
1668
+
1669
+ /**
1670
+ * The starter's package.json with its name, the Astryx packages pinned to
1671
+ * this CLI's release, and `dependencies` added.
1628
1672
  * @param {string} text
1629
1673
  * @param {Record<string, string>} dependencies
1674
+ * @param {string} name the package name
1630
1675
  */
1631
- function starterPackageJson(text, dependencies) {
1676
+ function starterPackageJson(text, dependencies, name) {
1632
1677
  const pinned = text.replaceAll('{{astryxVersion}}', cliVersion());
1633
- if (!Object.keys(dependencies).length) return pinned;
1634
1678
  const pkg = JSON.parse(pinned);
1679
+ pkg.name = name;
1635
1680
  pkg.dependencies = Object.fromEntries(
1636
1681
  Object.entries({...pkg.dependencies, ...dependencies}).sort(([a], [b]) =>
1637
- a.localeCompare(b),
1682
+ compareText(a, b),
1638
1683
  ),
1639
1684
  );
1640
1685
  return `${JSON.stringify(pkg, null, 2)}\n`;
@@ -3205,8 +3250,11 @@ function dirFlag(cwd, dir) {
3205
3250
  */
3206
3251
  export async function refreshPreviewRoute(cwd, slug) {
3207
3252
  const at = previewDir(cwd, undefined, {optional: true});
3253
+ // The same previews `see` names: the usual folder, the recorded ones,
3254
+ // and any in the routes folders that wear the theme (a folder renamed by
3255
+ // hand, or one whose record was lost).
3208
3256
  const dirs = [
3209
- ...new Set([...(at ? [at.dir] : []), ...recordedPreviews(cwd, slug)]),
3257
+ ...new Set([...(at ? [at.dir] : []), ...themePreviews(cwd, slug)]),
3210
3258
  ];
3211
3259
  let changed = false;
3212
3260
  /** @type {string[]} */
@@ -3244,7 +3292,7 @@ export async function refreshPreviewRoute(cwd, slug) {
3244
3292
  stale.push(
3245
3293
  standIn
3246
3294
  ? `${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),
3295
+ : `${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
3296
  );
3249
3297
  return false;
3250
3298
  }
@@ -3260,7 +3308,20 @@ export async function refreshPreviewRoute(cwd, slug) {
3260
3308
  `${shownDir(cwd, dir)}/ (${slug} has generated colors now; ${PREVIEW} add${dirFlag(cwd, dir)} adds its Colors page)`,
3261
3309
  );
3262
3310
  if (!writes.length) continue;
3263
- commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3311
+ // A route that cannot be written (its permissions, a folder in its
3312
+ // place) does not follow this change: said, never a quiet ok.
3313
+ try {
3314
+ commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3315
+ } catch (e) {
3316
+ const code =
3317
+ /\b(E[A-Z]{2,})\b/.exec(
3318
+ `${/** @type {any} */ (e)?.code ?? ''} ${e instanceof Error ? e.message : ''}`,
3319
+ )?.[1] ?? 'it could not be written';
3320
+ stale.push(
3321
+ `${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)`,
3322
+ );
3323
+ continue;
3324
+ }
3264
3325
  changed = true;
3265
3326
  }
3266
3327
  return {changed, stale};
@@ -3339,11 +3400,53 @@ function routesOf(cwd, at) {
3339
3400
  function previewPath(cwd, at) {
3340
3401
  const app = routesOf(cwd, at);
3341
3402
  if (!app) return null;
3403
+ // A folder Next does not serve (_private, @slot, an intercepting route):
3404
+ // no URL, as add refuses it.
3405
+ if (unservedWhy(cwd, at.dir)) return null;
3342
3406
  const segs = urlSegments(app, at.dir);
3343
3407
  if (segs.some(seg => /^\[.+\]$/.test(seg))) return null;
3344
3408
  const base = nextBasePath(cwd);
3345
3409
  if (base == null) return null;
3346
- return `${base}/${segs.map(seg => encodeURIComponent(seg)).join('/')}`;
3410
+ // A folder named %5F… is served at the decoded name (`_x`), encoded as a
3411
+ // URL segment needs it.
3412
+ const decoded = (/** @type {string} */ seg) => {
3413
+ try {
3414
+ return decodeURIComponent(seg);
3415
+ } catch {
3416
+ return seg;
3417
+ }
3418
+ };
3419
+ return `${base}/${segs.map(seg => encodeURIComponent(decoded(seg))).join('/')}`;
3420
+ }
3421
+
3422
+ /**
3423
+ * Why a preview folder found in the routes folder is not served, or null.
3424
+ * @param {string} cwd
3425
+ * @param {string} dir
3426
+ * @returns {string | null}
3427
+ */
3428
+ function unservedWhy(cwd, dir) {
3429
+ const app = routesOf(cwd, {dir, app: null});
3430
+ if (!app) return null;
3431
+ // The same rules add keeps: src/app/ while app/ is what Next serves, and
3432
+ // a next.config whose page extensions leave out page.tsx.
3433
+ const served = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(
3434
+ r => fs.existsSync(r) && fs.statSync(r).isDirectory(),
3435
+ );
3436
+ if (served && path.resolve(app) !== path.resolve(served))
3437
+ return `Next serves ${shown(cwd, served)}/ instead of ${shown(cwd, app)}/ when both are there`;
3438
+ try {
3439
+ const exts = readNextConfig(cwd).pageExtensions;
3440
+ if (exts && !exts.includes('tsx'))
3441
+ return `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx`;
3442
+ } catch {
3443
+ // A config this cannot read is not a reason to hide the URL.
3444
+ }
3445
+ // A [param] folder is served, with a value for it; only _private, @slot
3446
+ // and intercepting folders are not.
3447
+ const segs = path.relative(app, dir).split(path.sep);
3448
+ if (!segs.some(x => /^[_@]/.test(x) || INTERCEPT.test(x))) return null;
3449
+ return unroutedSegment(app, dir);
3347
3450
  }
3348
3451
 
3349
3452
  /**
@@ -3374,27 +3477,59 @@ function pageUrls(cwd, at, ids) {
3374
3477
  * @param {'colors' | 'components' | 'overview'} focus
3375
3478
  * @param {{code: string, cause: string} | null} [notChecked] why the change
3376
3479
  * could not be rendered
3480
+ * @param {{pictureProblem?: string | null, stale?: string[]}} [extra] this
3481
+ * result's picture problem (what kept --png from taking pictures) and its
3482
+ * previewStale entries (an in-app preview changed by hand)
3377
3483
  * @returns {string}
3378
3484
  */
3379
- export function seeLine(cwd, slug, focus, notChecked = null) {
3485
+ export function seeLine(cwd, slug, focus, notChecked = null, extra = {}) {
3380
3486
  /** @type {string[]} */
3381
3487
  const urls = [];
3382
3488
  /** Previews whose URL depends on the app's routing. @type {string[]} */
3383
3489
  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
- ];
3490
+ /** Previews in a folder Next does not serve. @type {string[]} */
3491
+ const unserved = [];
3492
+ /** Their folders, as --path takes them. @type {string[]} */
3493
+ const unservedDirs = [];
3494
+ /** @type {string[]} */
3495
+ const stale = extra.stale ?? [];
3496
+ /** Previews whose route was changed by hand. @type {string[]} */
3497
+ const handEdited = [];
3498
+ /** Previews whose record is damaged. @type {string[]} */
3499
+ const damaged = [];
3500
+ const dirs = themePreviews(cwd, slug);
3389
3501
  for (const dir of dirs) {
3390
3502
  /** @type {any} */
3391
3503
  let data;
3392
3504
  try {
3393
3505
  data = JSON.parse(fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'));
3394
- } catch {
3506
+ } catch (e) {
3507
+ // A record that is there but damaged: the preview commands refuse
3508
+ // it until it is fixed, so no add tip, the repair instead.
3509
+ if (
3510
+ fs.existsSync(path.join(dir, PREVIEW_DATA)) &&
3511
+ !(/** @type {any} */ (e)?.code)
3512
+ )
3513
+ damaged.push(shownDir(cwd, dir));
3395
3514
  continue;
3396
3515
  }
3397
3516
  if (data?.theme !== slug) continue;
3517
+ const why = unservedWhy(cwd, dir);
3518
+ if (why) {
3519
+ unserved.push(`${shownDir(cwd, dir)}/ (${why})`);
3520
+ unservedDirs.push(shownDir(cwd, dir));
3521
+ continue;
3522
+ }
3523
+ if (
3524
+ stale.some(
3525
+ f =>
3526
+ f.startsWith(`${shownDir(cwd, dir)}/`) &&
3527
+ /changed by hand|could not be written/.test(f),
3528
+ )
3529
+ ) {
3530
+ handEdited.push(shownDir(cwd, dir));
3531
+ continue;
3532
+ }
3398
3533
  const ids = Array.isArray(data?.pages)
3399
3534
  ? data.pages.map((/** @type {any} */ x) => String(x?.id))
3400
3535
  : [];
@@ -3408,16 +3543,56 @@ export function seeLine(cwd, slug, focus, notChecked = null) {
3408
3543
  );
3409
3544
  }
3410
3545
  const f = themeFiles(cwd, slug);
3546
+ // What keeps --png from taking pictures, when this result's own picture
3547
+ // run failed (a file of yours named like a picture).
3548
+ // A command that only takes pictures, whatever this one was (an undo run
3549
+ // again undoes another change; new refuses a theme that exists).
3550
+ const pngNote = extra.pictureProblem
3551
+ ? `--png took no pictures: ${extra.pictureProblem}`
3552
+ : `${EDITOR} show ${slug} --png takes pictures in ${shownDir(cwd, f.dir)}/ with no dev server (it needs a Playwright or a Chrome)`;
3411
3553
  const own = notChecked
3412
3554
  ? /could not be written/.test(notChecked.cause)
3413
3555
  ? `the change is saved, but ${notChecked.cause}; --png takes no pictures until that is fixed`
3414
3556
  : `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)`;
3557
+ : `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}`;
3558
+ const edited = handEdited.length
3559
+ ? `; 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)`
3560
+ : '';
3416
3561
  if (urls.length)
3417
- return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}`;
3562
+ return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}${edited}`;
3418
3563
  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`;
3564
+ return `${own}; the in-app preview is in ${unplain.slice(0, 2).join(', ')}, at a URL that depends on the app's routing${edited}`;
3565
+ if (unserved.length) {
3566
+ // What fixes it, by why it is not served: add's own answer for each.
3567
+ const why = unserved.join(' ');
3568
+ const fix = /Next serves .* when both are there/.test(why)
3569
+ ? `${PREVIEW} remove --path ${quoteCommandArgument(unservedDirs[0])}, then ${PREVIEW} add --theme ${slug} puts it in the folder Next serves`
3570
+ : /pageExtensions/.test(why)
3571
+ ? `add "tsx" to pageExtensions in next.config so Next serves the preview's page.tsx`
3572
+ : `move it back into a folder Next routes, or make one there with ${PREVIEW} add --theme ${slug} --path <a routed folder>`;
3573
+ return `${own}; the in-app preview is in ${unserved.slice(0, 2).join(', ')}, which the app does not serve: ${fix}${edited}`;
3574
+ }
3575
+ if (edited) return `${own}${edited}`;
3576
+ if (damaged.length)
3577
+ 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}` : ''}`;
3578
+ // With more than one editor theme, a bare add may wear another one.
3579
+ const many = editorThemeCount(cwd) > 1;
3580
+ return `${own}; to see it inside your app, ${PREVIEW} add${many ? ` --theme ${slug}` : ''} puts the preview pages there, each at its own URL`;
3581
+ }
3582
+
3583
+ /**
3584
+ * How many editor themes the project has.
3585
+ * @param {string} cwd
3586
+ */
3587
+ function editorThemeCount(cwd) {
3588
+ const root = themeFiles(cwd, 'x').root;
3589
+ try {
3590
+ return fs
3591
+ .readdirSync(root)
3592
+ .filter(d => fs.existsSync(themeFiles(cwd, d).settings)).length;
3593
+ } catch {
3594
+ return 0;
3595
+ }
3421
3596
  }
3422
3597
 
3423
3598
  /**
@@ -3473,6 +3648,52 @@ function skipReason(s) {
3473
3648
  ].join(' and ');
3474
3649
  }
3475
3650
 
3651
+ /**
3652
+ * Up to `n` of these page templates that this app can show: each one's
3653
+ * packages installed and no StyleX compiler needed, as add itself checks.
3654
+ * The only pages a suggestion names.
3655
+ * @param {string} cwd
3656
+ * @param {string} appRoot the app whose packages a page needs
3657
+ * @param {string[]} ids in order of preference
3658
+ * @param {number} n
3659
+ * @returns {Promise<string[]>}
3660
+ */
3661
+ async function showablePages(cwd, appRoot, ids, n) {
3662
+ /** @type {string[]} */
3663
+ const out = [];
3664
+ for (const id of ids) {
3665
+ if (out.length >= n) break;
3666
+ try {
3667
+ const shownTemplate = /** @type {any} */ (
3668
+ await template(id, {cwd, type: 'page'})
3669
+ );
3670
+ const needs = pageNeeds(appRoot, shownTemplate.data.source);
3671
+ if (
3672
+ !needs.missingPackages.length &&
3673
+ !needs.notInstalled.length &&
3674
+ !needs.stylexCompiler
3675
+ )
3676
+ out.push(id);
3677
+ } catch {
3678
+ // A template that does not load is not suggested.
3679
+ }
3680
+ }
3681
+ return out;
3682
+ }
3683
+
3684
+ /**
3685
+ * The page a refusal's example adds: the first page template this app can
3686
+ * show (app frames left out), or null when there is none.
3687
+ * @param {string} cwd
3688
+ * @returns {Promise<string | null>}
3689
+ */
3690
+ async function examplePage(cwd) {
3691
+ const pages = (await pageTemplates(cwd))
3692
+ .filter(t => !/^Shell\b/.test(t.category ?? ''))
3693
+ .map(t => t.id);
3694
+ return (await showablePages(cwd, appRootOf(cwd, cwd), pages, 1))[0] ?? null;
3695
+ }
3696
+
3476
3697
  /**
3477
3698
  * The page templates for a description, best first, each with why: the
3478
3699
  * build ranking's picks, then the template search's, so a page the app
@@ -3485,9 +3706,10 @@ function skipReason(s) {
3485
3706
  * @param {string} cwd
3486
3707
  * @param {string[]} notes notes for the result
3487
3708
  * @param {string} flags the caller's other flags, for the suggestions
3709
+ * @param {string | null} [appRoot] the app whose packages a page needs
3488
3710
  * @returns {Promise<Array<{name: string, displayName: string, why: string}>>}
3489
3711
  */
3490
- async function rankedPages(words, cwd, notes, flags) {
3712
+ async function rankedPages(words, cwd, notes, flags, appRoot = null) {
3491
3713
  const kit =
3492
3714
  /** @type {import('../build/build.type.mjs').BuildKitResponse} */ (
3493
3715
  await build(words, {cwd})
@@ -3571,15 +3793,8 @@ async function rankedPages(words, cwd, notes, flags) {
3571
3793
  const label = name => listed.find(t => t.id === name)?.name ?? name;
3572
3794
  const suggest = (/** @type {string[]} */ list) =>
3573
3795
  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
- ];
3796
+ /** @param {string[]} ids */
3797
+ const showableOf = ids => showablePages(cwd, appRoot ?? cwd, ids, 3);
3583
3798
  // No page relates when the ranking fell back to a frame with no direct
3584
3799
  // match, and no page the search found matches three words of the request
3585
3800
  // or two fifths of them.
@@ -3604,19 +3819,32 @@ async function rankedPages(words, cwd, notes, flags) {
3604
3819
  !found.some(
3605
3820
  (/** @type {any} */ r) => !frames.has(r.name) && termsMatched(r) >= 2,
3606
3821
  )));
3607
- if (unrelated)
3822
+ if (unrelated) {
3823
+ // With no page close, a few pages this app can show, and the list.
3824
+ const offered = await showableOf(
3825
+ pages.length
3826
+ ? pages
3827
+ : [
3828
+ ...['dashboard', 'settings', 'login'],
3829
+ ...listed.map(t => t.id),
3830
+ ].filter(
3831
+ (id, i, all) =>
3832
+ all.indexOf(id) === i &&
3833
+ listed.some(t => t.id === id) &&
3834
+ !frames.has(id),
3835
+ ),
3836
+ );
3608
3837
  refuse(
3609
3838
  E.ERR_NOT_FOUND,
3610
3839
  `No page template relates to "${words}". Name a page to add it anyway.`,
3611
3840
  {
3612
- run: pages.length
3613
- ? [
3614
- ...suggest(pages),
3615
- formatCliCommand('template --list --type page', cwd),
3616
- ]
3617
- : fallback,
3841
+ run: [
3842
+ ...suggest(offered),
3843
+ formatCliCommand('template --list --type page', cwd),
3844
+ ],
3618
3845
  },
3619
3846
  );
3847
+ }
3620
3848
  if (skippedFrames.length)
3621
3849
  notes.push(
3622
3850
  `left out ${skippedFrames.join(', ')}: app frames, not pages (add one with --template <id>)`,
@@ -4082,10 +4310,15 @@ async function addPreview(description, options, box) {
4082
4310
  const said = (description ?? '').trim();
4083
4311
  const named =
4084
4312
  options.template == null ? null : String(options.template).trim();
4313
+ // A refusal's example is a page this app can show.
4314
+ const example = async () => {
4315
+ const id = await examplePage(cwd);
4316
+ return id ? [`${PREVIEW} add --template ${id}${tf}${pf}`] : [];
4317
+ };
4085
4318
  if (named === '')
4086
4319
  refuse(E.ERR_INVALID_ARGUMENT, '--template needs a page template id.', {
4087
4320
  run: [
4088
- `${PREVIEW} add --template dashboard${tf}${pf}`,
4321
+ ...(await example()),
4089
4322
  formatCliCommand('template --list --type page', cwd),
4090
4323
  ],
4091
4324
  });
@@ -4106,9 +4339,9 @@ async function addPreview(description, options, box) {
4106
4339
  E.ERR_INVALID_ARGUMENT,
4107
4340
  `--top takes 1, 2 or 3, not "${String(options.top)}".`,
4108
4341
  {
4109
- run: [
4110
- `${PREVIEW} add ${quoteCommandArgument(said || 'a sales dashboard')} --top 2${tf}${pf}`,
4111
- ],
4342
+ run: said
4343
+ ? [`${PREVIEW} add ${quoteCommandArgument(said)} --top 2${tf}${pf}`]
4344
+ : await example(),
4112
4345
  },
4113
4346
  );
4114
4347
  if (options.top != null && !said)
@@ -4118,11 +4351,12 @@ async function addPreview(description, options, box) {
4118
4351
  ? '--top says how many ranked pages to add; --template names one page, so drop --top.'
4119
4352
  : '--top says how many pages to add for a description, and there is none.',
4120
4353
  {
4121
- run: [
4354
+ run:
4122
4355
  named != null
4123
- ? `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`
4124
- : `${PREVIEW} add 'a sales dashboard' --top ${String(options.top)}${tf}${pf}`,
4125
- ],
4356
+ ? [
4357
+ `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`,
4358
+ ]
4359
+ : await example(),
4126
4360
  },
4127
4361
  );
4128
4362
  /** @type {string[]} */
@@ -4145,7 +4379,7 @@ async function addPreview(description, options, box) {
4145
4379
  );
4146
4380
  }
4147
4381
  const retry = (/** @type {string | null} */ p) =>
4148
- `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4382
+ `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${options.top != null ? ` --top ${quoteCommandArgument(String(options.top))}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4149
4383
  const at = previewDir(cwd, options.path, {write: true, retry});
4150
4384
  const recovered = recoverPreview(cwd, at.dir);
4151
4385
  if (recovered) notes.push(recovered);
@@ -4185,6 +4419,8 @@ async function addPreview(description, options, box) {
4185
4419
  wornTheme(cwd, options.theme, againWith, without);
4186
4420
  data.theme = options.theme;
4187
4421
  } else if (data.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir)) {
4422
+ // Not gone when the route imports it from outside this project folder.
4423
+ refuseThemeAway(cwd, at.dir, data.theme, retry);
4188
4424
  const themes = editedThemes(cwd);
4189
4425
  data.theme = themes.length === 1 ? themes[0] : null;
4190
4426
  notes.push(
@@ -4287,7 +4523,7 @@ async function addPreview(description, options, box) {
4287
4523
  const flags = `${tf}${pf}`;
4288
4524
  const picks = explicit
4289
4525
  ? [await namedTemplate(cwd, /** @type {string} */ (named), flags)]
4290
- : await rankedPages(words, cwd, notes, flags);
4526
+ : await rankedPages(words, cwd, notes, flags, appRootOf(cwd, at.dir));
4291
4527
  for (const [i, pick] of picks.entries()) {
4292
4528
  if (add.length >= (explicit ? 1 : top)) break;
4293
4529
  const shownTemplate =
@@ -4491,10 +4727,17 @@ async function addPreview(description, options, box) {
4491
4727
  } catch {
4492
4728
  // A theme that does not load is reported where it is used.
4493
4729
  }
4494
- if (again)
4495
- notes.push(
4496
- `a default page's id brings back the default pages that are missing, as ${PREVIEW} add does`,
4730
+ // What happened: only the page asked for; the others come with a bare
4731
+ // add.
4732
+ if (again) {
4733
+ const stillMissing = DEFAULT_IDS.filter(
4734
+ id => !data.pages.some(p => p.id === id),
4497
4735
  );
4736
+ if (stillMissing.length)
4737
+ notes.push(
4738
+ `only ${askedId} was added; ${PREVIEW} add with no page brings back the other default pages that are missing (${stillMissing.join(', ')})`,
4739
+ );
4740
+ }
4498
4741
  notes.push(...typeScriptNotes(cwd, at.dir, added));
4499
4742
  if (
4500
4743
  askedId === COLORS_PAGE.id &&
@@ -4608,6 +4851,8 @@ export async function themeEditPreviewApp(dir, options = {}) {
4608
4851
  from.sheet,
4609
4852
  from.previewPng,
4610
4853
  from.sheetPng,
4854
+ // The record of pictures, none of which come along.
4855
+ from.pictures,
4611
4856
  ].map(f => path.basename(f)),
4612
4857
  );
4613
4858
  // The whole folder, tokens/ included, as bytes: a font or a picture
@@ -4622,6 +4867,12 @@ export async function themeEditPreviewApp(dir, options = {}) {
4622
4867
  else if (
4623
4868
  entry.isFile() &&
4624
4869
  !(rel === '' && skip.has(entry.name)) &&
4870
+ // No picture or preview page of any kind (dark pictures, section
4871
+ // sheets): the new app builds its own.
4872
+ !(
4873
+ rel === '' &&
4874
+ /^(preview|sheet)(-[a-z0-9-]+)?\.(html|png)$/.test(entry.name)
4875
+ ) &&
4625
4876
  // A temp file a stopped command left is no part of the theme.
4626
4877
  !isEditorTemp(entry.name)
4627
4878
  )
@@ -4854,7 +5105,9 @@ export async function themeEditPreviewList(options = {}) {
4854
5105
  /** @type {string[]} */
4855
5106
  const notes = [];
4856
5107
  const themeMissing = Boolean(
4857
- data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
5108
+ data?.theme &&
5109
+ !fs.existsSync(themeFiles(cwd, data.theme).dir) &&
5110
+ !(at && themeElsewhere(cwd, at.dir, data.theme)),
4858
5111
  );
4859
5112
  if (at && fs.existsSync(path.join(at.dir, PENDING)))
4860
5113
  notes.push(
@@ -4943,7 +5196,118 @@ export async function themeEditPreviewList(options = {}) {
4943
5196
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewRemoveResponse>}
4944
5197
  */
4945
5198
  export async function themeEditPreviewRemove(page, options = {}) {
4946
- return reportingRecovery(box => removePreview(page, options, box));
5199
+ try {
5200
+ return await reportingRecovery(box => removePreview(page, options, box));
5201
+ } catch (e) {
5202
+ // Removing a page needs the theme the route wears; removing the whole
5203
+ // preview needs none. Every refusal over a theme that does not load
5204
+ // names it, wherever the theme was read.
5205
+ const err = /** @type {any} */ (e);
5206
+ const pf =
5207
+ options.path != null
5208
+ ? ` --path ${quoteCommandArgument(options.path)}`
5209
+ : '';
5210
+ const whole = `${PREVIEW} remove${pf}`;
5211
+ if (
5212
+ page != null &&
5213
+ [E.ERR_THEME_INVALID, E.ERR_UNKNOWN_THEME, E.ERR_THEME_LOAD].includes(
5214
+ err?.code,
5215
+ ) &&
5216
+ !(err.suggestions ?? []).some((/** @type {any} */ x) => x?.name === whole)
5217
+ )
5218
+ err.suggestions = [
5219
+ {
5220
+ name: whole,
5221
+ reason:
5222
+ 'do this instead: removes the whole preview, which needs no theme',
5223
+ },
5224
+ ...(err.suggestions ?? []),
5225
+ ];
5226
+ throw e;
5227
+ }
5228
+ }
5229
+
5230
+ /**
5231
+ * Refuse a preview command run in a project folder below the one that holds
5232
+ * the theme the preview wears (a workspace app run from its own folder): the
5233
+ * theme is not gone, and no command rewrites it away. The refusal names
5234
+ * the same command, run from the folder that holds the theme.
5235
+ * @param {string} cwd
5236
+ * @param {string} dir the preview folder
5237
+ * @param {string} slug the theme the preview wears
5238
+ * @param {Retry} again the same command, with every argument it was given,
5239
+ * for a --path
5240
+ */
5241
+ function refuseThemeAway(cwd, dir, slug, again) {
5242
+ const away = themeElsewhere(cwd, dir, slug);
5243
+ if (!away) return;
5244
+ const root = path.dirname(path.dirname(away));
5245
+ refuse(
5246
+ E.ERR_INVALID_ARGUMENT,
5247
+ `The preview wears ${slug}, whose theme folder is ${away}/, outside this project folder (${cwd}). Run the command from the folder that holds themes/${slug}/.`,
5248
+ {
5249
+ run: [
5250
+ `cd ${quoteCommandArgument(root)} && ${again(path.relative(root, dir))}`,
5251
+ ],
5252
+ },
5253
+ );
5254
+ }
5255
+
5256
+ /**
5257
+ * The theme folder a preview's route imports when it is outside this
5258
+ * project's themes/ (a workspace app run from its own folder, its themes at
5259
+ * the workspace root), or null.
5260
+ * @param {string} cwd
5261
+ * @param {string} dir the preview folder
5262
+ * @param {string} slug
5263
+ * @returns {string | null}
5264
+ */
5265
+ function themeElsewhere(cwd, dir, slug) {
5266
+ if (fs.existsSync(themeFiles(cwd, slug).dir)) return null;
5267
+ /** @type {string} */
5268
+ let route;
5269
+ try {
5270
+ route = fs.readFileSync(path.join(dir, 'page.tsx'), 'utf8');
5271
+ } catch {
5272
+ return null;
5273
+ }
5274
+ const esc = slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5275
+ const m = new RegExp(`['"]([^'"]*themes/${esc})/${esc}[^'"]*['"]`).exec(
5276
+ route,
5277
+ );
5278
+ if (!m || !m[1].startsWith('.')) return null;
5279
+ const found = path.resolve(dir, m[1]);
5280
+ return fs.existsSync(path.join(found, `${slug}.settings.json`))
5281
+ ? found
5282
+ : null;
5283
+ }
5284
+
5285
+ /**
5286
+ * The previews a theme may have: the ones recorded with it (added with
5287
+ * --path) and every preview in the routes folders (one renamed by hand, or
5288
+ * one whose record was lost). The one list `see`, a change's refresh and
5289
+ * the preview commands read; each reads a preview's record for its theme.
5290
+ * @param {string} cwd
5291
+ * @param {string} slug
5292
+ * @returns {string[]}
5293
+ */
5294
+ function themePreviews(cwd, slug) {
5295
+ return [...new Set([...recordedPreviews(cwd, slug), ...previewsIn(cwd)])];
5296
+ }
5297
+
5298
+ /**
5299
+ * Every preview in the app, of any editor theme: the previews of each, by
5300
+ * {@link themePreviews}, that are there.
5301
+ * @param {string} cwd
5302
+ * @returns {string[]}
5303
+ */
5304
+ function allPreviews(cwd) {
5305
+ return [
5306
+ ...new Set([
5307
+ ...editedThemes(cwd).flatMap(t => themePreviews(cwd, t)),
5308
+ ...previewsIn(cwd),
5309
+ ]),
5310
+ ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
4947
5311
  }
4948
5312
 
4949
5313
  /**
@@ -4994,6 +5358,24 @@ async function removePreview(page, options, box) {
4994
5358
  const retry = (/** @type {string | null} */ p) =>
4995
5359
  `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4996
5360
  const at = previewDir(cwd, options.path, {retry});
5361
+ // A file given for the preview's folder: its folder when the file is a
5362
+ // preview's own, else the previews there are (as add refuses a file).
5363
+ if (fs.existsSync(at.dir) && !fs.statSync(at.dir).isDirectory()) {
5364
+ const parent = path.dirname(at.dir);
5365
+ const own = fs.existsSync(path.join(parent, PREVIEW_DATA));
5366
+ const others = previewsIn(cwd);
5367
+ refuse(
5368
+ E.ERR_INVALID_ARGUMENT,
5369
+ `${shown(cwd, at.dir)} is a file; a preview is a folder${own ? `, and this file is in the preview ${shownDir(cwd, parent)}/` : ''}.`,
5370
+ {
5371
+ run: own
5372
+ ? [retry(shownDir(cwd, parent))]
5373
+ : others.length
5374
+ ? others.slice(0, 3).map(d => retry(shownDir(cwd, d)))
5375
+ : [`${PREVIEW} list`],
5376
+ },
5377
+ );
5378
+ }
4997
5379
  // The pages a stopped change was removing, read before it is finished.
4998
5380
  /** @type {string[]} */
4999
5381
  let removing = [];
@@ -5179,6 +5561,7 @@ async function removePreview(page, options, box) {
5179
5561
  const wore = data.theme;
5180
5562
  /** @type {string | null} */
5181
5563
  let gone = null;
5564
+ if (wore) refuseThemeAway(cwd, at.dir, wore, retry);
5182
5565
  if (wore && !fs.existsSync(themeFiles(cwd, wore).dir)) {
5183
5566
  gone = wore;
5184
5567
  data.theme = null;
@@ -5214,26 +5597,10 @@ async function removePreview(page, options, box) {
5214
5597
  let planned;
5215
5598
  /** @type {Awaited<ReturnType<typeof routeTheme>>} */
5216
5599
  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
- }
5600
+ // A theme that does not load is refused with the whole-preview remove
5601
+ // named (themeEditPreviewRemove adds it to every such refusal).
5602
+ theme = await routeTheme(cwd, at.dir, data, {build: false});
5603
+ planned = await routeWrites(cwd, at.dir, data, theme, {gone});
5237
5604
  const elsewhere = `${PREVIEW} remove${pf}`;
5238
5605
  /** @type {Map<string, {rel: string, text: string, keepHash?: boolean}>} */
5239
5606
  const writes = new Map(move.writes.map(w => [w.rel, w]));