@astryxdesign/cli 0.7.16 → 0.7.17-canary.g16fe6a8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/README.md +76 -86
  2. package/api/build/_adapter.d.mts +12 -0
  3. package/api/build/_adapter.mjs +51 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +4 -3
  7. package/api/build/build.type.d.mts +2 -2
  8. package/api/build/build.type.mjs +3 -3
  9. package/api/build/kit/kind.d.mts +2 -1
  10. package/api/build/kit/kind.mjs +199 -10
  11. package/api/build/kit/kit.mjs +6 -4
  12. package/api/build/kit/rank.d.mts +4 -2
  13. package/api/build/kit/rank.mjs +125 -24
  14. package/api/build/kit/start.d.mts +5 -4
  15. package/api/build/kit/start.mjs +12 -8
  16. package/api/build/kit/weights.d.mts +39 -3
  17. package/api/build/kit/weights.json +1 -1
  18. package/api/build/kit/weights.mjs +340 -43
  19. package/api/build/kit/word-model.d.mts +23 -0
  20. package/api/build/kit/word-model.mjs +46 -0
  21. package/api/build/kit/words.d.mts +48 -0
  22. package/api/build/kit/words.mjs +90 -1
  23. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  24. package/api/component/list/list.d.mts +1 -1
  25. package/api/component/list/list.mjs +48 -6
  26. package/api/discover/_adapter.d.mts +1 -1
  27. package/api/discover/search/search.mjs +3 -2
  28. package/api/docs/_adapter.d.mts +28 -2
  29. package/api/docs/_adapter.mjs +249 -10
  30. package/api/docs/docs.d.mts +3 -0
  31. package/api/docs/docs.doc.mjs +7 -1
  32. package/api/docs/docs.mjs +12 -0
  33. package/api/docs/docs.type.d.mts +5 -0
  34. package/api/docs/docs.type.mjs +2 -0
  35. package/api/docs/node/node.mjs +1 -1
  36. package/api/doctor/_adapter.d.mts +27 -5
  37. package/api/doctor/_adapter.mjs +83 -10
  38. package/api/doctor/built-checks.mjs +40 -14
  39. package/api/doctor/doctor.d.mts +4 -3
  40. package/api/doctor/doctor.mjs +14 -7
  41. package/api/doctor/theme-checks.mjs +121 -17
  42. package/api/icon/_records.mjs +2 -1
  43. package/api/index.d.mts +2 -0
  44. package/api/index.mjs +2 -0
  45. package/api/integration/_adapter.d.mts +44 -0
  46. package/api/integration/_adapter.mjs +77 -1
  47. package/api/integration/authoring-checks.mjs +6 -6
  48. package/api/integration/example-scope.d.mts +14 -0
  49. package/api/integration/example-scope.mjs +44 -0
  50. package/api/integration/example-scope.type.d.mts +29 -0
  51. package/api/integration/example-scope.type.mjs +25 -0
  52. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  53. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  54. package/api/integration/validate-integration.mjs +19 -1
  55. package/api/integration/validate-integration.type.d.mts +9 -0
  56. package/api/integration/validate-integration.type.mjs +1 -1
  57. package/api/integration/validateIntegration.doc.mjs +1 -1
  58. package/api/render/_adapter.mjs +591 -195
  59. package/api/render/render.doc.mjs +11 -3
  60. package/api/render/render.type.d.mts +52 -0
  61. package/api/render/render.type.mjs +31 -1
  62. package/api/search/ORDERING.md +1 -1
  63. package/api/search/_adapter.d.mts +9 -0
  64. package/api/search/_adapter.mjs +85 -0
  65. package/api/search/_candidate-score.mjs +51 -32
  66. package/api/search/_fit-order.mjs +3 -3
  67. package/api/search/_gather-components.d.mts +3 -2
  68. package/api/search/_gather-components.mjs +12 -3
  69. package/api/search/_lexical.d.mts +5 -0
  70. package/api/search/_lexical.mjs +8 -2
  71. package/api/search/_result.d.mts +11 -9
  72. package/api/search/_result.mjs +4 -4
  73. package/api/search/_score.d.mts +6 -1
  74. package/api/search/_score.mjs +15 -3
  75. package/api/search/search-index.mjs +7 -1
  76. package/api/search/search.d.mts +1 -1
  77. package/api/theme/_adapter.mjs +12 -1
  78. package/api/theme/build/build.d.mts +132 -1
  79. package/api/theme/build/build.mjs +482 -157
  80. package/api/theme/build/core-interception.d.mts +10 -0
  81. package/api/theme/build/core-interception.mjs +10 -0
  82. package/api/theme/build/font-warning.d.mts +44 -5
  83. package/api/theme/build/font-warning.mjs +118 -10
  84. package/api/theme/build/icon-imports.mjs +51 -9
  85. package/api/theme/theme.type.d.mts +10 -0
  86. package/api/theme/theme.type.mjs +7 -1
  87. package/api/theme-edit/_adapter.d.mts +115 -4
  88. package/api/theme-edit/_adapter.mjs +997 -83
  89. package/api/theme-edit/_catalog.d.mts +20 -2
  90. package/api/theme-edit/_catalog.mjs +50 -10
  91. package/api/theme-edit/_check.d.mts +75 -24
  92. package/api/theme-edit/_check.mjs +2672 -422
  93. package/api/theme-edit/_color.d.mts +10 -0
  94. package/api/theme-edit/_color.mjs +54 -1
  95. package/api/theme-edit/_compiler.d.mts +1 -0
  96. package/api/theme-edit/_compiler.mjs +133 -15
  97. package/api/theme-edit/_context.d.mts +14 -3
  98. package/api/theme-edit/_context.mjs +225 -65
  99. package/api/theme-edit/_css.d.mts +14 -0
  100. package/api/theme-edit/_css.mjs +46 -1
  101. package/api/theme-edit/_edit.d.mts +54 -4
  102. package/api/theme-edit/_edit.mjs +2966 -286
  103. package/api/theme-edit/_how-commands.d.mts +72 -1
  104. package/api/theme-edit/_how-commands.mjs +770 -9
  105. package/api/theme-edit/_how-question.d.mts +82 -5
  106. package/api/theme-edit/_how-question.mjs +6983 -701
  107. package/api/theme-edit/_how.d.mts +2 -1
  108. package/api/theme-edit/_how.mjs +237 -41
  109. package/api/theme-edit/_importers.d.mts +38 -0
  110. package/api/theme-edit/_importers.mjs +188 -0
  111. package/api/theme-edit/_marks.d.mts +31 -5
  112. package/api/theme-edit/_marks.mjs +57 -5
  113. package/api/theme-edit/_name-rule.d.mts +11 -0
  114. package/api/theme-edit/_name-rule.mjs +12 -0
  115. package/api/theme-edit/_normal.d.mts +303 -0
  116. package/api/theme-edit/_normal.mjs +1517 -0
  117. package/api/theme-edit/_palette.d.mts +12 -0
  118. package/api/theme-edit/_palette.mjs +37 -4
  119. package/api/theme-edit/_part-words.d.mts +31 -0
  120. package/api/theme-edit/_part-words.mjs +126 -0
  121. package/api/theme-edit/_parts.d.mts +28 -2
  122. package/api/theme-edit/_parts.mjs +267 -31
  123. package/api/theme-edit/_preview-app.d.mts +7 -13
  124. package/api/theme-edit/_preview-app.mjs +814 -406
  125. package/api/theme-edit/_preview.d.mts +116 -16
  126. package/api/theme-edit/_preview.mjs +649 -152
  127. package/api/theme-edit/_project.d.mts +22 -1
  128. package/api/theme-edit/_project.mjs +83 -3
  129. package/api/theme-edit/_settings.d.mts +467 -42
  130. package/api/theme-edit/_settings.mjs +3527 -468
  131. package/api/theme-edit/_tables.d.mts +21 -0
  132. package/api/theme-edit/_tables.mjs +97 -3
  133. package/api/theme-edit/_vet.d.mts +31 -0
  134. package/api/theme-edit/_vet.mjs +114 -8
  135. package/api/theme-edit/theme-edit.type.d.mts +16 -2
  136. package/api/theme-edit/theme-edit.type.mjs +6 -3
  137. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  138. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  139. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  140. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  141. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  142. package/api/upgrade/run/run.mjs +4 -3
  143. package/assets/codemods/integration-discovery.mjs +2 -1
  144. package/assets/codemods/run-codemod.mjs +87 -7
  145. package/assets/codemods/transforms/next/index.mjs +11 -1
  146. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  147. package/assets/component-list.generated.json +1 -0
  148. package/assets/docs/author-a-theme.doc.mjs +1 -0
  149. package/assets/docs/theme.doc.dense.mjs +2 -2
  150. package/assets/docs/theme.doc.mjs +1 -1
  151. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  152. package/assets/docs/tree/checks.doc.mjs +1 -1
  153. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  154. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  155. package/assets/docs/tree/share-a-page.doc.mjs +157 -0
  156. package/assets/docs/tree/single-component.doc.mjs +4 -0
  157. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  158. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  159. package/assets/docs/use-a-theme.doc.mjs +1 -1
  160. package/assets/docs.generated.json +2 -2
  161. package/assets/search-catalog.generated.json +2 -0
  162. package/assets/self-audit.generated.json +1 -1
  163. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  164. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  165. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  166. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  167. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  168. package/assets/templates/components.generated.json +1 -1
  169. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  170. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  171. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  172. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  173. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  174. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  175. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  176. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  177. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  178. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  179. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  180. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  181. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  182. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  183. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  184. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  185. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  186. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  187. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  188. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  189. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  190. package/assets/templates/pages/ide/page.tsx +24 -2
  191. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  192. package/assets/templates/pages/library/template.doc.mjs +4 -1
  193. package/assets/templates/pages/login/template.doc.mjs +2 -1
  194. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  195. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  196. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  197. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  198. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  199. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  200. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  201. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  202. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  203. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  204. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  205. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  206. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  207. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  208. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  209. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  210. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  211. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  212. package/assets/theme.template.ts +6 -0
  213. package/authoring/debug/parse.d.mts +3 -3
  214. package/authoring/doctypes/_schema.d.mts +3 -3
  215. package/authoring/doctypes/command/command.doc.mjs +1 -1
  216. package/authoring/doctypes/component/categories.d.mts +37 -0
  217. package/authoring/doctypes/component/categories.mjs +54 -0
  218. package/authoring/doctypes/template/template.doc.mjs +1 -1
  219. package/authoring/doctypes/template/type.ts +9 -0
  220. package/authoring/example/example.doc.d.mts +12 -0
  221. package/authoring/example/example.doc.mjs +69 -0
  222. package/authoring/example/preview.d.mts +92 -0
  223. package/authoring/example/preview.mjs +994 -0
  224. package/authoring/example/type.ts +102 -0
  225. package/authoring/index.d.mts +1 -0
  226. package/authoring/index.d.ts +12 -0
  227. package/authoring/index.mjs +3 -1
  228. package/clients/cli/bin/astryx.mjs +6 -9
  229. package/clients/cli/build-id.generated.json +1 -1
  230. package/clients/cli/commands/component.doc.mjs +1 -1
  231. package/clients/cli/commands/component.mjs +22 -3
  232. package/clients/cli/commands/docs.doc.mjs +7 -1
  233. package/clients/cli/commands/docs.mjs +3 -1
  234. package/clients/cli/commands/doctor.mjs +32 -14
  235. package/clients/cli/commands/experimental/render.mjs +42 -1
  236. package/clients/cli/commands/experimental/theme.mjs +573 -119
  237. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  238. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  239. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  240. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  241. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  242. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  243. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  244. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  245. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  246. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  247. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  248. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  249. package/clients/cli/commands/search.doc.mjs +2 -1
  250. package/clients/cli/commands/search.mjs +6 -1
  251. package/clients/cli/commands/template.mjs +4 -2
  252. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  253. package/clients/cli/commands/theme.doc.mjs +1 -1
  254. package/clients/cli/commands/theme.mjs +718 -438
  255. package/clients/cli/commands/upgrade.mjs +42 -7
  256. package/clients/cli/index.mjs +1 -1
  257. package/clients/cli/lib/cli-error.mjs +2 -1
  258. package/clients/cli/lib/component-format.mjs +205 -98
  259. package/clients/cli/lib/hook-format.mjs +9 -19
  260. package/clients/cli/lib/json-shim.mjs +132 -24
  261. package/clients/cli/lib/manifest.mjs +3 -2
  262. package/clients/cli/manifest.generated.json +1 -1
  263. package/foundation/agent-docs/agent-docs.mjs +1 -1
  264. package/foundation/config/theme-state.d.mts +13 -1
  265. package/foundation/config/theme-state.mjs +47 -7
  266. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  267. package/foundation/discovery/component-discovery.d.mts +11 -0
  268. package/foundation/discovery/component-discovery.mjs +56 -8
  269. package/foundation/discovery/component-replacement.mjs +130 -1
  270. package/foundation/discovery/copied-passages.mjs +2 -1
  271. package/foundation/discovery/core-component-docs.d.mts +29 -0
  272. package/foundation/discovery/core-component-docs.mjs +83 -0
  273. package/foundation/discovery/doc-types.mjs +4 -3
  274. package/foundation/discovery/entry-name-files.d.mts +43 -0
  275. package/foundation/discovery/entry-name-files.mjs +264 -0
  276. package/foundation/discovery/hook-discovery.d.mts +8 -2
  277. package/foundation/discovery/hook-discovery.mjs +22 -8
  278. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  279. package/foundation/discovery/icon-set-checks.mjs +2 -1
  280. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  281. package/foundation/discovery/integration-doc-files.mjs +2 -1
  282. package/foundation/discovery/package-exports.d.mts +10 -0
  283. package/foundation/discovery/package-exports.mjs +56 -3
  284. package/foundation/discovery/prop-drift.mjs +9 -9
  285. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  286. package/foundation/discovery/runner-allowlist.mjs +2 -0
  287. package/foundation/discovery/stored-component-list.d.mts +43 -0
  288. package/foundation/discovery/stored-component-list.mjs +90 -0
  289. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  290. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  291. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  292. package/foundation/discovery/stored-self-audit.mjs +38 -18
  293. package/foundation/discovery/template-adapter.d.mts +53 -1
  294. package/foundation/discovery/template-adapter.mjs +176 -12
  295. package/foundation/discovery/template-icons.mjs +2 -1
  296. package/foundation/discovery/theme-discovery.mjs +31 -4
  297. package/foundation/discovery/theme-imports.d.mts +14 -0
  298. package/foundation/discovery/theme-imports.mjs +43 -1
  299. package/foundation/discovery/theming-targets.d.mts +6 -5
  300. package/foundation/discovery/theming-targets.mjs +31 -47
  301. package/foundation/doc-compiler/import.mjs +7 -1
  302. package/foundation/doc-compiler/inputs.mjs +3 -2
  303. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  304. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  305. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  306. package/foundation/env/semver.mjs +3 -1
  307. package/foundation/fonts/font-stylesheet.d.mts +38 -0
  308. package/foundation/fonts/font-stylesheet.mjs +141 -0
  309. package/foundation/fs/cache-eviction.d.mts +21 -0
  310. package/foundation/fs/cache-eviction.mjs +73 -0
  311. package/foundation/fs/exact-codec.d.mts +12 -2
  312. package/foundation/fs/exact-codec.mjs +23 -6
  313. package/foundation/fs/file-protection.mjs +4 -3
  314. package/foundation/fs/gather-cache.d.mts +62 -4
  315. package/foundation/fs/gather-cache.mjs +517 -91
  316. package/foundation/fs/jiti-cache.d.mts +19 -1
  317. package/foundation/fs/jiti-cache.mjs +130 -6
  318. package/foundation/fs/kept-tree.d.mts +60 -0
  319. package/foundation/fs/kept-tree.mjs +154 -0
  320. package/foundation/fs/listing-cache.d.mts +7 -0
  321. package/foundation/fs/listing-cache.mjs +10 -0
  322. package/foundation/fs/module-loader.d.mts +24 -2
  323. package/foundation/fs/module-loader.mjs +94 -21
  324. package/foundation/fs/paths.d.mts +18 -0
  325. package/foundation/fs/paths.mjs +15 -2
  326. package/foundation/fs/read-record.d.mts +9 -0
  327. package/foundation/fs/read-record.mjs +19 -11
  328. package/foundation/fs/stop-cleanup.d.mts +12 -0
  329. package/foundation/fs/stop-cleanup.mjs +66 -0
  330. package/foundation/identity/provider-identity.d.mts +6 -0
  331. package/foundation/identity/provider-identity.mjs +10 -1
  332. package/foundation/integrations/contribution-inventory.mjs +4 -3
  333. package/foundation/integrations/example-code.d.mts +63 -0
  334. package/foundation/integrations/example-code.mjs +416 -0
  335. package/foundation/integrations/public-imports.d.mts +9 -0
  336. package/foundation/integrations/public-imports.mjs +3 -2
  337. package/foundation/integrations/validate-contributions.mjs +17 -45
  338. package/foundation/render/embedded-files.d.mts +6 -0
  339. package/foundation/render/embedded-files.mjs +25 -5
  340. package/foundation/render/embedded-imports.d.mts +39 -7
  341. package/foundation/render/embedded-imports.mjs +66 -27
  342. package/foundation/render/file-header.d.mts +66 -0
  343. package/foundation/render/file-header.mjs +118 -0
  344. package/foundation/render/host-answer.d.mts +18 -0
  345. package/foundation/render/host-answer.mjs +46 -0
  346. package/foundation/render/host-exit.d.mts +1 -0
  347. package/foundation/render/host-exit.mjs +6 -1
  348. package/foundation/render/html-reader.d.mts +55 -2
  349. package/foundation/render/html-reader.mjs +145 -26
  350. package/foundation/render/markup-edits.d.mts +57 -0
  351. package/foundation/render/markup-edits.mjs +182 -0
  352. package/foundation/render/page-host.mjs +29 -12
  353. package/foundation/render/page-worker.mjs +121 -13
  354. package/foundation/render/picture-chrome.d.mts +4 -0
  355. package/foundation/render/picture-chrome.mjs +185 -0
  356. package/foundation/render/picture-playwright.d.mts +4 -0
  357. package/foundation/render/picture-playwright.mjs +34 -0
  358. package/foundation/render/rebuild.mjs +2 -1
  359. package/foundation/render/render-page.d.mts +35 -3
  360. package/foundation/render/render-page.mjs +641 -96
  361. package/foundation/render/source-block.d.mts +85 -6
  362. package/foundation/render/source-block.mjs +211 -20
  363. package/foundation/render/ts-paths.d.mts +69 -6
  364. package/foundation/render/ts-paths.mjs +326 -40
  365. package/foundation/response/error-codes.d.mts +3 -1
  366. package/foundation/response/error-codes.d.ts +1 -0
  367. package/foundation/response/error-codes.doc.mjs +12 -1
  368. package/foundation/response/error-codes.mjs +11 -1
  369. package/foundation/response/response-types.doc.mjs +2 -2
  370. package/foundation/text/compare-text.d.mts +14 -0
  371. package/foundation/text/compare-text.mjs +68 -0
  372. package/foundation/text/css-escape.d.mts +18 -0
  373. package/foundation/text/css-escape.mjs +35 -0
  374. package/foundation/text/string-utils.d.mts +3 -2
  375. package/foundation/text/string-utils.mjs +18 -4
  376. package/foundation/text/suggest-order.d.mts +9 -0
  377. package/foundation/text/suggest-order.mjs +15 -1
  378. package/foundation/xle/expand.mjs +2 -1
  379. package/host/index.mjs +8 -6
  380. package/package.json +7 -6
@@ -9,11 +9,26 @@
9
9
  * @position api/theme-edit — imported only by _adapter.mjs
10
10
  */
11
11
 
12
+ import {THEME_SLUG_RE} from '../../foundation/discovery/theme-discovery.mjs';
12
13
  import * as fs from 'node:fs';
13
- import {coversProperty} from './_css.mjs';
14
+ import {coversProperty, cssProperties, matchValue} from './_css.mjs';
14
15
  import * as path from 'node:path';
15
16
  import {AstryxError} from '../error.mjs';
16
- import {vetSuggestions} from './_vet.mjs';
17
+ import {
18
+ followLine,
19
+ readSetLine,
20
+ splitCommand,
21
+ vetSuggestions,
22
+ repairGate,
23
+ } from './_vet.mjs';
24
+ import {
25
+ allowedLine,
26
+ colorPair,
27
+ coversTyped,
28
+ readsTyped,
29
+ withoutCopyDebris,
30
+ baseWord,
31
+ } from './_normal.mjs';
17
32
  import {
18
33
  AUTO_SPREAD,
19
34
  CORNERS,
@@ -38,6 +53,8 @@ import {
38
53
  radiusTokenOf,
39
54
  contrastProblems,
40
55
  describe,
56
+ entryDamage,
57
+ entryNotes,
41
58
  keyOf,
42
59
  loadTheme,
43
60
  maskedSettings,
@@ -59,40 +76,58 @@ import {
59
76
  buildTheme,
60
77
  staleBuild,
61
78
  EDITOR_SUFFIXES,
62
- madeByEditor,
63
79
  outputsDrift,
64
80
  kebab,
65
81
  camel,
66
82
  NEW_MARKER,
67
83
  clearNewMarker,
68
84
  refuseThemeSource,
69
- settingsShapeOk,
85
+ settingsRemade,
86
+ entriesReadable,
87
+ readAsMeant,
88
+ editorMadeFolder,
89
+ builtOnBase,
90
+ onBuiltIn,
91
+ onBuiltInSteps,
92
+ readFields,
93
+ settingsJson,
70
94
  slugFor,
95
+ typedThemeName,
96
+ themeNameReadings,
71
97
  themeSource,
72
98
  themeSourceProblem,
73
99
  refuseThemeParse,
74
100
  ownSourceTokens,
75
101
  ownSourceTokenValues,
102
+ ownTokenEntries,
103
+ ownThemeInput,
104
+ describeValue,
105
+ settingsThemeName,
106
+ nonTextMessage,
76
107
  ownPartTokens,
108
+ PHONE_RULE_WHEN,
109
+ builtTouchTokens,
77
110
  PHONE_TYPE,
78
111
  refreshSourceStamp,
79
112
  sourceChangedReason,
80
- builtPairs,
81
- ownPairMessage,
113
+ setOwnTokenCheck,
82
114
  freeThemeName,
83
115
  refuseLinks,
84
116
  usableNewName,
85
117
  FOLDER_JUNK,
118
+ folderIsEmpty,
86
119
  dialValueFits,
87
120
  holdAfterBuild,
121
+ setArgs,
88
122
  } from './_settings.mjs';
89
123
  import {
90
124
  checkSetting,
91
- exampleOf,
92
125
  normalizeEntry,
126
+ propertyValueProblem,
93
127
  storedProblems,
94
128
  } from './_check.mjs';
95
- import {MODAL} from './_compiler.mjs';
129
+ import {MODAL, isColorToken} from './_compiler.mjs';
130
+ import {colorProblem} from './_color.mjs';
96
131
  import {
97
132
  PALETTE_DIALS,
98
133
  VIBRANCY_DEFAULT,
@@ -105,18 +140,31 @@ import {
105
140
  writeWhole,
106
141
  isGraySeed,
107
142
  seedOf,
143
+ isEditorTemp,
108
144
  } from './_palette.mjs';
109
145
  import {
110
146
  renderPreview,
111
147
  renderSheet,
112
148
  previewIsCurrent,
113
149
  takeFirstAppCopy,
150
+ appCopyBehind,
151
+ appCopyStale,
152
+ copyFontsCss,
114
153
  writeAppCopy,
115
154
  } from './_preview.mjs';
116
155
  import {appWiring, refreshPreviewRoute, seeLine} from './_preview-app.mjs';
117
- import {baseInstalled, baseResolved, installLine} from './_project.mjs';
156
+ /** The preview command, as a person runs it. */
157
+ const PREVIEW_CMD = `${P.replace(/ editor$/, '')} preview`;
158
+ import {
159
+ baseInstalled,
160
+ baseResolved,
161
+ copiesLine,
162
+ installLine,
163
+ themeCacheRoot,
164
+ } from './_project.mjs';
118
165
  import {reactMissing} from './_parts.mjs';
119
166
  import {
167
+ reactCopies,
120
168
  renderCause,
121
169
  requireProject,
122
170
  context,
@@ -128,7 +176,9 @@ import {
128
176
  stampSheet,
129
177
  } from './_context.mjs';
130
178
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
179
+ import {readThemeState} from '../../foundation/config/theme-state.mjs';
131
180
  import {
181
+ formatCliCommand,
132
182
  getCliInvocation,
133
183
  quoteCommandArgument,
134
184
  } from '../../foundation/env/package-manager.mjs';
@@ -147,23 +197,18 @@ const E = ERROR_CODES;
147
197
  * for that name, the source only exactly as it writes it); `keep` is every
148
198
  * other file, which is never touched. Null when the editor did not make
149
199
  * the folder. System files (.DS_Store) are in neither.
200
+ * @param {string} cwd
150
201
  * @param {string} dir
151
202
  * @param {string} slug
152
203
  * @param {boolean} [damaged] its settings are there but not valid JSON
153
204
  * @returns {{clear: string[], keep: string[]} | null}
154
205
  */
155
- function editorLeftovers(dir, slug, damaged = false) {
206
+ function editorLeftovers(cwd, dir, slug, damaged = false) {
156
207
  // The editor made this folder: a stopped `new` left its marker, the
157
208
  // generated settings module (which carries the editor's header) is there
158
209
  // without its settings, or its settings are there but damaged (kept
159
210
  // aside by `new`, so neither cleared nor kept here).
160
- const marked = fs.existsSync(path.join(dir, NEW_MARKER));
161
- if (
162
- !marked &&
163
- !damaged &&
164
- !madeByEditor(path.join(dir, `${slug}.settings.ts`))
165
- )
166
- return null;
211
+ if (!damaged && !editorMadeFolder(cwd, slug)) return null;
167
212
  /** @type {string[]} */
168
213
  const clear = [];
169
214
  /** @type {string[]} */
@@ -171,12 +216,11 @@ function editorLeftovers(dir, slug, damaged = false) {
171
216
  const named = (/** @type {string} */ n) =>
172
217
  n === NEW_MARKER ||
173
218
  EDITOR_SUFFIXES.some(x => n === `${slug}.${x}`) ||
174
- /^(preview(-[a-z]+)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config\.json)$/.test(
219
+ /^(preview(-dark)?\.(html|png)|sheet(-[a-z-]+)?\.(html|png)|palette\.config\.json)$/.test(
175
220
  n,
176
221
  ) ||
177
- // The editor's temp names: `.<name>.astryx-<pid>-<rand>.tmp`, and the
178
- // build's `.<name>.tmp-<id>`.
179
- /^\..+\.(astryx-\d+-[a-z0-9]+\.tmp|tmp-[\w-]+)$/.test(n);
222
+ // The editor's temp names (writes, builds, pictures).
223
+ isEditorTemp(n);
180
224
  for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
181
225
  const p = path.join(dir, e.name);
182
226
  if (FOLDER_JUNK.has(e.name)) continue;
@@ -209,9 +253,9 @@ function editorLeftovers(dir, slug, damaged = false) {
209
253
  /** Whether a settings file parses, in the shape the editor reads. @param {string} file */
210
254
  function readableJson(file) {
211
255
  try {
212
- return settingsShapeOk(
213
- JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')),
214
- );
256
+ // An entry with no thing or no source is damage too: `new` keeps the
257
+ // file aside, as the refusal for it says.
258
+ return !settingsRemade(settingsJson(fs.readFileSync(file, 'utf8')));
215
259
  } catch {
216
260
  return false;
217
261
  }
@@ -262,9 +306,238 @@ function putBack(kept, tokensDir) {
262
306
  */
263
307
 
264
308
  export async function themeEditNew(name, options = {}) {
309
+ try {
310
+ // The public call always makes the theme: only checkedNewLines asks
311
+ // for the checks alone.
312
+ return /** @type {import('./theme-edit.type.mjs').ThemeEditNewResponse} */ (
313
+ await newTheme(name, options)
314
+ );
315
+ } catch (e) {
316
+ throw await vetNewLines(
317
+ e,
318
+ options.cwd ?? process.cwd(),
319
+ options.settings ?? {},
320
+ options.like,
321
+ );
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Every `new` a refusal offers, checked as `new` checks its options (in
327
+ * memory, nothing written) before it is offered: a dial value the line
328
+ * gives in place of one typed passes only as an exact reading of what was
329
+ * typed (never a stock value); a flag `new` refuses is left out, and the
330
+ * reason names it; a line that adds a setting nobody typed, or is still
331
+ * refused, is not offered; a did-you-mean reads a whole value typed. The
332
+ * one gate for `new` lines, as set's lines have theirs.
333
+ * @param {unknown} e
334
+ * @param {string} cwd
335
+ * @param {Record<string, string | string[] | undefined>} typed the dial options given
336
+ * @param {string} [like] the base given (--like), which a did-you-mean may read
337
+ * @returns {Promise<unknown>}
338
+ */
339
+ async function vetNewLines(e, cwd, typed, like) {
340
+ if (!(e instanceof AstryxError) || !(e.suggestions ?? []).length) return e;
341
+ const prefix = `${P} new `;
342
+ /** @type {import('./_settings.mjs').Ctx | null} */
343
+ let ctx = null;
344
+ try {
345
+ ctx = /** @type {import('./_settings.mjs').Ctx} */ (await context(cwd));
346
+ } catch {
347
+ return e;
348
+ }
349
+ /** @param {string} line */
350
+ const read = line => {
351
+ const args = splitCommand(line.slice(prefix.length));
352
+ if (!args || !args.length || args[0].startsWith('-')) return null;
353
+ const [slug, ...rest] = args;
354
+ /** @type {Array<[string, string]>} */
355
+ const flags = [];
356
+ let like = /** @type {string | undefined} */ (undefined);
357
+ let png = false;
358
+ for (let j = 0; j < rest.length; j += 1) {
359
+ const m = /^--([a-z-]+)$/.exec(rest[j]);
360
+ if (m?.[1] === 'png') png = true;
361
+ else if (m && rest[j + 1] != null) {
362
+ const v = rest[(j += 1)];
363
+ if (m[1] === 'like') like = v;
364
+ else flags.push([m[1], v]);
365
+ } else return null;
366
+ }
367
+ return {slug, like, png, flags};
368
+ };
369
+ /**
370
+ * The refusal `new` gives these flags, or null.
371
+ * @param {string} slug @param {string | undefined} like
372
+ * @param {Array<[string, string]>} flags @param {boolean} png
373
+ */
374
+ const problem = async (slug, like, flags, png) => {
375
+ /** @type {Record<string, string | string[]>} */
376
+ const settings = {};
377
+ for (const [k, v] of flags) {
378
+ const had = settings[k];
379
+ settings[k] = had == null ? v : [...[had].flat(), v];
380
+ }
381
+ const base = like && like !== 'none' ? like : undefined;
382
+ try {
383
+ /** @type {any} */ (ctx).base = await baseResolved(
384
+ /** @type {any} */ (ctx).project,
385
+ base,
386
+ );
387
+ } catch {
388
+ /** @type {any} */ (ctx).base = await baseResolved(
389
+ /** @type {any} */ (ctx).project,
390
+ undefined,
391
+ );
392
+ }
393
+ try {
394
+ applyNewSettings(
395
+ /** @type {any} */ (ctx),
396
+ slug,
397
+ {name: slug, ...(base ? {like: base} : {}), mode: 'both', settings: []},
398
+ settings,
399
+ png,
400
+ like,
401
+ );
402
+ return null;
403
+ } catch (err) {
404
+ if (err instanceof AstryxError) return err;
405
+ throw err;
406
+ }
407
+ };
408
+ // A light and a dark color typed as one value is read as that pair.
409
+ const typedValues = (/** @type {string} */ k) =>
410
+ [typed[k]]
411
+ .flat()
412
+ .filter(v => v != null)
413
+ .map(String)
414
+ .map(v => {
415
+ const pair = colorPair(v) ?? modeColorsOf(v);
416
+ return pair.light && pair.dark
417
+ ? `light-dark(${pair.light}, ${pair.dark})`
418
+ : v;
419
+ });
420
+ /** @type {Array<{name: string, reason?: string}>} */
421
+ const out = [];
422
+ const typedKeys = Object.keys(typed).filter(k => typed[k] != null);
423
+ /** Settings whose typed value no reading makes work. @type {Set<string>} */
424
+ const unread = new Set();
425
+ for (const x of e.suggestions ?? []) {
426
+ // A did-you-mean value passes the same gate as a line: a reading of a
427
+ // whole value typed, never one word of it.
428
+ if (x.reason === 'did you mean') {
429
+ if (
430
+ (typeof like === 'string' &&
431
+ allowedLine({offered: x.name, typed: like, thing: 'base'})) ||
432
+ typedKeys.some(k =>
433
+ typedValues(k).some(t =>
434
+ allowedLine({offered: x.name, typed: t, thing: k}),
435
+ ),
436
+ )
437
+ )
438
+ out.push(x);
439
+ continue;
440
+ }
441
+ const line = x.name.startsWith(prefix) ? read(x.name) : null;
442
+ if (!line) {
443
+ out.push(x);
444
+ continue;
445
+ }
446
+ // A line that adds a setting nobody typed (a mode read from a color's
447
+ // words) is another command, never offered.
448
+ if (line.flags.some(([k]) => !typedKeys.includes(k))) continue;
449
+ /** @type {string[]} */
450
+ const untyped = [];
451
+ /** @type {string[]} */
452
+ const refused = [];
453
+ const shown = (/** @type {[string, string]} */ [k, v]) =>
454
+ `--${k} ${quoteCommandArgument(v)}`;
455
+ // A value in place of one typed is offered only as an exact reading of
456
+ // what was typed.
457
+ const lineMode = line.flags.find(([k]) => k === 'mode')?.[1];
458
+ const typedOnly = line.flags.filter(f => {
459
+ const was = typedValues(f[0]);
460
+ const ok =
461
+ !was.length ||
462
+ was.includes(f[1]) ||
463
+ was.some(t =>
464
+ allowedLine({
465
+ offered: f[1],
466
+ typed: t,
467
+ thing: f[0],
468
+ ...(lineMode ? {saved: new Map([['mode', [lineMode]]])} : {}),
469
+ }),
470
+ );
471
+ if (!ok) {
472
+ untyped.push(shown([f[0], was[0]]));
473
+ unread.add(f[0]);
474
+ }
475
+ return ok;
476
+ });
477
+ // Each flag in turn is kept when new still takes the line with it, so a
478
+ // flag new refuses (alone, or beside one kept before it) is left out.
479
+ /** @type {Array<[string, string]>} */
480
+ const flags = [];
481
+ for (const f of typedOnly)
482
+ if (await problem(line.slug, line.like, [...flags, f], false))
483
+ refused.push(shown(f));
484
+ else flags.push(f);
485
+ if (await problem(line.slug, line.like, flags, line.png)) continue;
486
+ const dropped = [
487
+ ...(untyped.length
488
+ ? [`${untyped.join(' and ')}, which no reading makes work`]
489
+ : []),
490
+ ...(refused.length
491
+ ? [`${refused.join(' and ')}, which new refuses`]
492
+ : []),
493
+ ];
494
+ const name = `${prefix}${line.slug}${newFlags(
495
+ line.like,
496
+ Object.fromEntries(
497
+ flags.reduce((/** @type {Map<string, string[]>} */ m, [k, v]) => {
498
+ m.set(k, [...(m.get(k) ?? []), v]);
499
+ return m;
500
+ }, new Map()),
501
+ ),
502
+ line.png,
503
+ )}`;
504
+ if (out.some(y => y.name === name)) continue;
505
+ out.push(
506
+ dropped.length
507
+ ? {
508
+ name,
509
+ reason: `do this instead, without ${dropped.join('; and without ')}`,
510
+ }
511
+ : {...x, name},
512
+ );
513
+ }
514
+ // What such a setting takes, as set ends for the same value.
515
+ for (const k of unread)
516
+ if (!out.some(y => y.name === `${P} how ${k}`))
517
+ out.push({name: `${P} how ${k}`, reason: 'what it takes'});
518
+ e.suggestions = out;
519
+ return e;
520
+ }
521
+
522
+ /**
523
+ * {@link themeEditNew}'s work; with `check` (an argument of its own, never
524
+ * one of the public options), its checks only (null when they pass,
525
+ * nothing written).
526
+ * @param {string} name
527
+ * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} options
528
+ * @param {{check?: boolean}} [mode]
529
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditNewResponse | null>}
530
+ */
531
+ async function newTheme(name, options, {check = false} = {}) {
265
532
  const {cwd = process.cwd(), png = false, settings = {}} = options;
266
- // `--like none` builds on no base, as `set <theme> base none` does.
267
- const like = options.like === 'none' ? undefined : options.like;
533
+ // --like reads a base in any case, by the one case rule of every dial
534
+ // (`set <theme> base Neutral` is neutral); `--like none` builds on no
535
+ // base, as `set <theme> base none` does.
536
+ const likeWord =
537
+ typeof options.like === 'string'
538
+ ? baseWord(options.like) || options.like
539
+ : options.like;
540
+ const like = likeWord === 'none' ? undefined : likeWord;
268
541
  requireProject(cwd);
269
542
  // A corrected `new` keeps every option given, fixing only the bad one.
270
543
  // A --like in another case is the built-in theme it names.
@@ -275,21 +548,16 @@ export async function themeEditNew(name, options = {}) {
275
548
  // in other letters is the one meant, installed or not (its refusal then
276
549
  // offers the install, or the same new on no base).
277
550
  const have = LIKE.filter(b => baseInstalled(cwd, b));
278
- // `@astryxdesign/theme-butter`, `theme-butter`, `Butter`: butter.
279
- const baseName = (/** @type {unknown} */ v) =>
280
- String(v)
281
- .trim()
282
- .toLowerCase()
283
- .replace(/^@astryxdesign\/theme-/, '')
284
- .replace(/^theme-/, '');
551
+ // `@astryxdesign/theme-butter`, `butterTheme`, `Butter`: butter (the one
552
+ // base reader, baseWord, shared with set and the settings file).
285
553
  const likeFixed =
286
554
  like == null
287
- ? options.like === 'none'
555
+ ? likeWord === 'none'
288
556
  ? 'none'
289
557
  : undefined
290
- : LIKE.includes(baseName(like))
291
- ? baseName(like)
292
- : (nearest(baseName(like), have)[0] ?? null);
558
+ : LIKE.includes(like)
559
+ ? like
560
+ : (nearest(like, have)[0] ?? null);
293
561
  // A dial value the dial does not take is left out of a suggested `new`
294
562
  // (a corrected name must not repeat it), and the refusal says so.
295
563
  /** @type {Array<[string, string]>} */
@@ -345,21 +613,50 @@ export async function themeEditNew(name, options = {}) {
345
613
  /** @type {string} */ newName,
346
614
  /** @type {string | null | undefined} */ likeValue = likeFixed,
347
615
  ) => `${P} new ${newName}${newFlags(likeValue, fitSettings, png)}`;
616
+ // The same new as lines that run here: a built-in base the project has
617
+ // not installed is installed first.
618
+ const againLines = (
619
+ /** @type {string} */ newName,
620
+ /** @type {string | null | undefined} */ likeValue = likeFixed,
621
+ ) =>
622
+ likeValue && LIKE.includes(likeValue)
623
+ ? onBuiltIn(cwd, likeValue, again(newName, likeValue))
624
+ : [again(newName, likeValue)];
348
625
  if (!slugOk(name)) {
349
- const fixed = slugFor(name);
350
- // Only a name typed in another case is the theme here already.
351
- const sameName = String(name ?? '').toLowerCase() === fixed;
352
- const exists = sameName && fs.existsSync(themeFiles(cwd, fixed).settings);
626
+ // A path typed for the name (themes/brand, ./t, t/) names the theme the
627
+ // path ends in.
628
+ // A file name, the app copy's export (tTheme), camelCase or spaces
629
+ // (BrandDark, "Brand Dark") name the theme they read as: when it is
630
+ // here already, that is said, never a numbered second copy offered.
631
+ const typed = String(name ?? '');
632
+ const path_ = /[\\/]/.test(typed);
633
+ const readings = themeNameReadings(typed);
634
+ const present = readings.find(n =>
635
+ fs.existsSync(themeFiles(cwd, n).settings),
636
+ );
637
+ const fixed =
638
+ present ?? readings[0] ?? slugFor(path_ ? typedThemeName(typed) : typed);
639
+ const exists = Boolean(present);
353
640
  refuse(
354
641
  E.ERR_INVALID_ARGUMENT,
355
642
  `"${String(name ?? '').slice(0, 80)}" is not a theme name (${NAME_RULE})${exists ? `; ${fixed} is a theme here already` : ''}.${dropped}`,
356
643
  {
357
644
  run: exists
358
645
  ? [`${P} show ${fixed}`]
359
- : [again(usableNewName(cwd, fixed))],
646
+ : againLines(usableNewName(cwd, fixed)),
360
647
  },
361
648
  );
362
649
  }
650
+ // A name the theme commands' own discovery skips ("a--b", "b-") would
651
+ // make an app copy no `theme add`, `theme list` or doctor takes.
652
+ if (!THEME_SLUG_RE.test(name)) {
653
+ const cleaned = name.replace(/-{2,}/g, '-').replace(/-+$/, '');
654
+ refuse(
655
+ E.ERR_INVALID_ARGUMENT,
656
+ `"${name}" is not a theme name the theme commands take: a dash only between letters or digits (no two in a row, none at the end), so its app copy in src/themes/ would be skipped by theme add, theme list and doctor.${dropped}`,
657
+ {run: againLines(usableNewName(cwd, cleaned))},
658
+ );
659
+ }
363
660
  // A built-in theme's name would collide with the theme of that name the
364
661
  // app may also use.
365
662
  if (LIKE.includes(name))
@@ -367,16 +664,19 @@ export async function themeEditNew(name, options = {}) {
367
664
  E.ERR_FILE_EXISTS,
368
665
  `${name} is a built-in theme; an editor theme needs a name of its own. To start from ${name}, build on it.${dropped}`,
369
666
  {
370
- run: [
371
- again(
372
- fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
373
- ? freeThemeName(cwd, `my-${name}`)
374
- : `my-${name}`,
375
- // Built on the theme named when it is installed, unless another
376
- // base (or none) was given.
377
- likeFixed ?? name,
378
- ),
379
- ],
667
+ run: (() => {
668
+ const mine = fs.existsSync(themeFiles(cwd, `my-${name}`).dir)
669
+ ? freeThemeName(cwd, `my-${name}`)
670
+ : `my-${name}`;
671
+ // Built on the theme named (installed first when it is not),
672
+ // unless another base (or none) was given; or on no base.
673
+ return likeFixed !== undefined
674
+ ? againLines(mine, likeFixed)
675
+ : [
676
+ ...againLines(mine, name),
677
+ ...(baseInstalled(cwd, name) ? [] : [again(mine, null)]),
678
+ ];
679
+ })(),
380
680
  },
381
681
  );
382
682
  const f = themeFiles(cwd, name);
@@ -400,7 +700,7 @@ export async function themeEditNew(name, options = {}) {
400
700
  refuse(
401
701
  E.ERR_FILE_EXISTS,
402
702
  `themes/${name} is ${dirSt.isSymbolicLink() ? 'a link' : 'a file'}, so a theme is not made there.${dropped}`,
403
- {run: [again(freeThemeName(cwd, name))]},
703
+ {run: againLines(freeThemeName(cwd, name))},
404
704
  );
405
705
  // Settings that are not valid JSON are kept aside, and the theme is
406
706
  // made again beside them.
@@ -408,12 +708,15 @@ export async function themeEditNew(name, options = {}) {
408
708
  if (fs.existsSync(f.settings) && !damaged)
409
709
  refuse(E.ERR_FILE_EXISTS, `Theme "${name}" already exists.${dropped}`, {
410
710
  // What the command asked for, on the theme that exists or as a new one.
711
+ // A base's install line, when one is needed, is given once.
411
712
  run: [
412
- `${P} show ${name}`,
413
- ...(likeFixed && LIKE.includes(likeFixed)
414
- ? [`${P} set ${name} base ${likeFixed}`]
415
- : []),
416
- again(freeThemeName(cwd, name)),
713
+ ...new Set([
714
+ `${P} show ${name}`,
715
+ ...(likeFixed && LIKE.includes(likeFixed)
716
+ ? onBuiltIn(cwd, likeFixed, `${P} set ${name} base ${likeFixed}`)
717
+ : []),
718
+ ...againLines(freeThemeName(cwd, name)),
719
+ ]),
417
720
  ],
418
721
  });
419
722
  // A `new` stopped part way (killed, out of memory) leaves its own marker
@@ -421,17 +724,18 @@ export async function themeEditNew(name, options = {}) {
421
724
  // after every argument is checked. Anything else in the folder, or a
422
725
  // folder without the marker, is never touched.
423
726
  const left = fs.existsSync(f.dir)
424
- ? editorLeftovers(f.dir, name, damaged)
727
+ ? editorLeftovers(cwd, f.dir, name, damaged)
425
728
  : null;
426
729
  const holdsOther =
427
730
  fs.existsSync(f.dir) &&
428
731
  !left &&
429
- fs.readdirSync(f.dir).some(n => !FOLDER_JUNK.has(n));
732
+ // Empty folders (an empty tokens/) hold nothing of anyone's.
733
+ !folderIsEmpty(f.dir);
430
734
  if (holdsOther)
431
735
  refuse(
432
736
  E.ERR_FILE_EXISTS,
433
737
  `themes/${name}/ already holds files this command did not make; choose another name.${dropped}`,
434
- {run: [again(freeThemeName(cwd, name))]},
738
+ {run: againLines(freeThemeName(cwd, name))},
435
739
  );
436
740
  if (like != null && !LIKE.includes(like))
437
741
  refuse(
@@ -458,10 +762,11 @@ export async function themeEditNew(name, options = {}) {
458
762
  /** @type {import('./_settings.mjs').Ctx} */ (ctx).base =
459
763
  await baseResolved(ctx.project, data.like);
460
764
  } catch (e) {
461
- // A base that is not installed: install it, or the same new on no base.
462
- if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME)
765
+ // A base that is not installed: install it, then the same new on it
766
+ // (the one helper set's refusal uses too); or the same new on no base.
767
+ if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME && like)
463
768
  e.suggestions = [
464
- ...(e.suggestions ?? []),
769
+ ...onBuiltInSteps(cwd, like, again(name, like)),
465
770
  {name: again(name, null), reason: 'build on no theme'},
466
771
  ];
467
772
  throw e;
@@ -469,9 +774,24 @@ export async function themeEditNew(name, options = {}) {
469
774
  // Every check comes before the first change to the folder: the settings,
470
775
  // and a source of the user's own kept from before (it must still extend
471
776
  // the settings, or the build fails after the folder was cleared).
777
+ try {
778
+ applyNewSettings(
779
+ ctx,
780
+ name,
781
+ structuredClone(data),
782
+ settings,
783
+ png,
784
+ likeFixed ?? undefined,
785
+ );
786
+ } catch (e) {
787
+ throw await followNewLine(e, ctx, name, data);
788
+ }
789
+ // Checked only (checkedNewLines): every check has passed, and nothing
790
+ // is written.
791
+ if (check) return null;
472
792
  applyNewSettings(ctx, name, data, settings, png, likeFixed ?? undefined);
473
793
  if (left?.keep.some(p => path.basename(p) === `${name}.theme.ts`))
474
- refuseThemeSource(cwd, name);
794
+ await refuseThemeSource(cwd, name);
475
795
  /** @type {string[]} */
476
796
  const keptNotes = [];
477
797
  /** @type {string[]} */
@@ -576,7 +896,7 @@ export async function themeEditNew(name, options = {}) {
576
896
  }
577
897
  refuseIfLockLost();
578
898
  fs.rmSync(marker, {force: true});
579
- const p = await previewAndRoute(ctx, name, data, png);
899
+ const p = await previewAndRoute(ctx, name, data, png, 'overview', 'new');
580
900
  /** @type {string[]} */
581
901
  const notes = [
582
902
  ...keptNotes,
@@ -610,6 +930,78 @@ export async function themeEditNew(name, options = {}) {
610
930
  };
611
931
  }
612
932
 
933
+ /**
934
+ * A refused `new` whose suggestions include another `new` of the theme:
935
+ * that line is checked as `new` checks its dial flags (in memory, nothing
936
+ * written), and each repair a refusal of it offers is folded in, so the one
937
+ * line fixes or drops every bad flag. It comes first.
938
+ * @param {unknown} e
939
+ * @param {import('./_settings.mjs').Ctx} ctx
940
+ * @param {string} slug
941
+ * @param {import('./_settings.mjs').ThemeData} data the theme before any dial
942
+ * @returns {Promise<unknown>}
943
+ */
944
+ async function followNewLine(e, ctx, slug, data) {
945
+ if (!(e instanceof AstryxError)) return e;
946
+ const prefix = `${P} new ${slug}`;
947
+ const isNew = (/** @type {string} */ n) =>
948
+ n === prefix || n.startsWith(`${prefix} `);
949
+ const first = (e.suggestions ?? []).find(x => isNew(x.name));
950
+ if (!first) return e;
951
+ const followed = await followLine(
952
+ first.name,
953
+ line => {
954
+ const args = splitCommand(line.slice(prefix.length));
955
+ if (!args) return null;
956
+ /** @type {Record<string, string | string[]>} */
957
+ const settings = {};
958
+ /** @type {string | undefined} */
959
+ let like;
960
+ let png = false;
961
+ for (let j = 0; j < args.length; j += 1) {
962
+ const m = /^--([a-z-]+)$/.exec(args[j]);
963
+ if (m?.[1] === 'png') png = true;
964
+ else if (m && args[j + 1] != null) {
965
+ const v = args[(j += 1)];
966
+ if (m[1] === 'like') like = v;
967
+ else {
968
+ const had = settings[m[1]];
969
+ settings[m[1]] = had == null ? v : [...[had].flat(), v];
970
+ }
971
+ } else return null;
972
+ }
973
+ try {
974
+ applyNewSettings(
975
+ ctx,
976
+ slug,
977
+ structuredClone(data),
978
+ settings,
979
+ png,
980
+ like ?? data.like,
981
+ );
982
+ return null;
983
+ } catch (again) {
984
+ if (again instanceof AstryxError) return again;
985
+ throw again;
986
+ }
987
+ },
988
+ isNew,
989
+ );
990
+ // A line that is still refused is never offered as the fix.
991
+ if (followed.line === first.name || followed.why) return e;
992
+ e.suggestions = [
993
+ {
994
+ ...first,
995
+ name: followed.line,
996
+ reason: 'do this instead: every flag fixed',
997
+ },
998
+ ...(e.suggestions ?? []).filter(
999
+ x => x !== first && x.name !== followed.line,
1000
+ ),
1001
+ ];
1002
+ return e;
1003
+ }
1004
+
613
1005
  /**
614
1006
  * The dial settings of `new`, checked one at a time in dial order (mode
615
1007
  * first; a color before vibrancy, which needs one) into `data`.
@@ -655,15 +1047,34 @@ function applyNewSettings(
655
1047
  /** @type {import('./_settings.mjs').Setting} */
656
1048
  let s;
657
1049
  try {
658
- s = checkSetting(ctx, slug, data, thing, String(value), {}, false);
1050
+ // The same input cleanup set gives a typed value (quotes of any
1051
+ // kind around a font, invisible spaces, a pasted `name: value`).
1052
+ const typed = normalizeEntry(thing, String(value)).value;
1053
+ s = checkSetting(
1054
+ ctx,
1055
+ slug,
1056
+ data,
1057
+ thing,
1058
+ typed ?? String(value),
1059
+ {},
1060
+ false,
1061
+ );
659
1062
  } catch (e) {
660
- throw asNewRefusal(
661
- vetSuggestions(e, ctx, slug, data),
1063
+ throw newColorPair(
1064
+ asNewRefusal(
1065
+ vetSuggestions(e, ctx, slug, data),
1066
+ slug,
1067
+ settings,
1068
+ likeFlag,
1069
+ png,
1070
+ {thing, index},
1071
+ ),
662
1072
  slug,
663
1073
  settings,
664
1074
  likeFlag,
665
1075
  png,
666
- {thing, index},
1076
+ thing,
1077
+ String(value),
667
1078
  );
668
1079
  }
669
1080
  if (thing === 'mode')
@@ -737,11 +1148,22 @@ function newFlags(like, settings, png) {
737
1148
  function asNewRefusal(e, slug, settings, like, png = false, at = null) {
738
1149
  if (!(e instanceof AstryxError)) return e;
739
1150
  const setPrefix = `${P} set ${slug} `;
740
- e.suggestions = (e.suggestions ?? []).map(s => {
1151
+ /** @type {string[]} */
1152
+ const after = [];
1153
+ /** @type {Array<import('../../foundation/response/base').Suggestion | null>} */
1154
+ const mapped = (e.suggestions ?? []).map(s => {
741
1155
  if (s.name === `${P} set --help`) return {...s, name: `${P} new --help`};
742
1156
  if (!s.name.startsWith(setPrefix)) return s;
1157
+ const words = splitCommand(s.name.slice(setPrefix.length)) ?? [];
743
1158
  const [thing, ...rest] = s.name.slice(setPrefix.length).split(' ');
744
1159
  if (thing.startsWith('--') || !DIALS[thing]) return s;
1160
+ // A set with its own scope (`corners pill --on button`) is no option of
1161
+ // new: it is a change to make once the theme is made (said in the
1162
+ // message below).
1163
+ if (words.length !== 2) {
1164
+ after.push(s.name);
1165
+ return null;
1166
+ }
745
1167
  const fixed = unquoteWord(rest.join(' '));
746
1168
  // Only the refused value changes: a dial given several values
747
1169
  // (--headings tight --headings BOLD) keeps the others, in order.
@@ -756,6 +1178,12 @@ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
756
1178
  name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: next}, png)}`,
757
1179
  };
758
1180
  });
1181
+ e.suggestions = mapped.filter(x => x != null);
1182
+ if (after.length)
1183
+ e.message = e.message.replace(
1184
+ /( Nothing was changed\.)?$/,
1185
+ ` Once ${slug} is made, ${after.slice(0, 2).join(' or ')} does that.$1`,
1186
+ );
759
1187
  // A refused value with nothing to put in its place: the same new
760
1188
  // without it, every other option kept.
761
1189
  if (at && !e.suggestions.some(x => x.name.startsWith(`${P} new `))) {
@@ -771,6 +1199,88 @@ function asNewRefusal(e, slug, settings, like, png = false, at = null) {
771
1199
  return e;
772
1200
  }
773
1201
 
1202
+ /**
1203
+ * The color for each mode a value names in words (`light #111111 dark
1204
+ * #eeeeee`, `dark: navy`): the one reading of a light and a dark color
1205
+ * typed for a color dial on `new`.
1206
+ * @param {string} typed
1207
+ * @returns {Record<string, string>}
1208
+ */
1209
+ function modeColorsOf(typed) {
1210
+ /** @type {Record<string, string>} */
1211
+ const pair = {};
1212
+ for (const m of typed.matchAll(
1213
+ /\b(light|dark)\b\s*(?:mode\s*)?[:=]?\s*(#[0-9a-f]{3,8}\b|[a-z]+\([^)]*\)|[a-z]+)/gi,
1214
+ ))
1215
+ pair[m[1].toLowerCase()] = m[2];
1216
+ return pair;
1217
+ }
1218
+
1219
+ /**
1220
+ * A color dial on `new` given a light and a dark color ("light #111111 dark
1221
+ * #eeeeee"): the refusal offers the user's own colors, per mode, as set
1222
+ * does, never a stock color they did not type.
1223
+ * @param {unknown} e
1224
+ * @param {string} slug
1225
+ * @param {Record<string, any>} settings
1226
+ * @param {string | undefined} like
1227
+ * @param {boolean} png
1228
+ * @param {string} thing
1229
+ * @param {string} typed
1230
+ */
1231
+ function newColorPair(e, slug, settings, like, png, thing, typed) {
1232
+ if (!(e instanceof AstryxError) || !PALETTE_DIALS.includes(thing)) return e;
1233
+ // (A color the user did not type, such as a stock example, is left out
1234
+ // by the one gate every offered new line passes: vetNewLines.)
1235
+ // With no new line, the same new without that color, every other option
1236
+ // kept.
1237
+ if (!(e.suggestions ?? []).some(x => x.name.startsWith(`${P} new `)))
1238
+ (e.suggestions ??= []).push({
1239
+ name: `${P} new ${slug}${newFlags(like, {...settings, [thing]: undefined}, png)}`,
1240
+ reason: `without --${thing} ${quoteCommandArgument(typed)}`,
1241
+ });
1242
+ const pair = modeColorsOf(typed);
1243
+ if (!pair.light && !pair.dark) return e;
1244
+ const mode = String(
1245
+ Array.isArray(settings.mode) ? settings.mode[0] : (settings.mode ?? 'both'),
1246
+ );
1247
+ /** @type {Array<{name: string, reason: string}>} */
1248
+ const lines = [];
1249
+ /** @param {string} color @param {string} reason @param {Record<string, any>} [extra] */
1250
+ const line = (color, reason, extra = {}) =>
1251
+ lines.push({
1252
+ name: `${P} new ${slug}${newFlags(like, {...settings, ...extra, [thing]: color}, png)}`,
1253
+ reason,
1254
+ });
1255
+ if (mode === 'dark-only' && pair.dark)
1256
+ line(pair.dark, 'do this instead: the dark color you gave');
1257
+ else if (mode === 'light-only' && pair.light)
1258
+ line(pair.light, 'do this instead: the light color you gave');
1259
+ else if (mode === 'both') {
1260
+ if (pair.light)
1261
+ line(
1262
+ pair.light,
1263
+ `the light color you gave; then set ${slug} --color-${thing} ${pair.dark ?? '…'} --mode dark for the dark one`,
1264
+ );
1265
+ if (pair.dark)
1266
+ line(pair.dark, 'or a dark-only theme with the dark color you gave', {
1267
+ mode: 'dark-only',
1268
+ });
1269
+ }
1270
+ // No color for the mode the theme has: how the dial works, and the
1271
+ // same new without it, never a color made up.
1272
+ if (!lines.length)
1273
+ lines.push({
1274
+ name: `${P} how ${thing}`,
1275
+ reason: `no ${mode === 'light-only' ? 'light' : 'dark'} color was given for this ${mode} theme`,
1276
+ });
1277
+ e.suggestions = [
1278
+ ...lines,
1279
+ ...(e.suggestions ?? []).filter(x => !lines.some(l => l.name === x.name)),
1280
+ ];
1281
+ return e;
1282
+ }
1283
+
774
1284
  /**
775
1285
  * Headings values with every later value for an axis already given left
776
1286
  * out (the first weight and the first tracking stay); a word of neither
@@ -822,6 +1332,39 @@ function changeFocus(s) {
822
1332
  return 'overview';
823
1333
  }
824
1334
 
1335
+ /**
1336
+ * A signal handler for the checks and pictures after a change is saved: it
1337
+ * says what is saved (in the words of the command that ran) and how to run
1338
+ * what did not, with the project's own CLI invocation, then lets the
1339
+ * signal end the process (the render's own handler re-raises it; with none,
1340
+ * this one does).
1341
+ * @param {string} slug
1342
+ * @param {'set' | 'undo' | 'new'} [kind] the command that saved
1343
+ * @param {string} [cwd] the project, for the CLI invocation
1344
+ * @param {boolean} [png] pictures were asked for: the command named takes
1345
+ * them too
1346
+ * @returns {(sig: NodeJS.Signals) => void}
1347
+ */
1348
+ export function stoppedAfterSave(
1349
+ slug,
1350
+ kind = 'set',
1351
+ cwd = process.cwd(),
1352
+ png = false,
1353
+ ) {
1354
+ const done =
1355
+ kind === 'undo'
1356
+ ? `the undo is done: ${slug} is saved and built as it was before that change`
1357
+ : kind === 'new'
1358
+ ? `${slug} is made and built`
1359
+ : `the change to ${slug} is saved and built (and its undo step kept)`;
1360
+ return sig => {
1361
+ process.stderr.write(
1362
+ `Stopped: ${done}; its checks and pictures did not run. ${formatCliCommand(`${P} show ${slug}${png ? ' --png' : ''}`, cwd)} runs them.\n`,
1363
+ );
1364
+ if (process.listenerCount(sig) === 0) process.kill(process.pid, sig);
1365
+ };
1366
+ }
1367
+
825
1368
  /**
826
1369
  * The preview after a change, with the in-app preview route kept in step:
827
1370
  * its imports follow the theme, such as the stylesheet of a font package
@@ -832,13 +1375,34 @@ function changeFocus(s) {
832
1375
  * @param {boolean} png
833
1376
  * @param {'colors' | 'components' | 'overview'} [focus] the preview page
834
1377
  * most about the change: Colors for a color, Components for a part
1378
+ * @param {'set' | 'undo' | 'new'} [kind] the command that saved
835
1379
  */
836
- async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
837
- const p = await previewAfter(ctx, slug, data, png);
1380
+ async function previewAndRoute(
1381
+ ctx,
1382
+ slug,
1383
+ data,
1384
+ png,
1385
+ focus = 'overview',
1386
+ kind = /** @type {'set' | 'undo' | 'new'} */ ('set'),
1387
+ ) {
1388
+ // Stopped (Ctrl-C) while the checks and pictures run: the change is saved
1389
+ // and built already, which one line says before the process ends.
1390
+ const stopped = stoppedAfterSave(slug, kind, ctx.project.cwd, png);
1391
+ process.once('SIGINT', stopped);
1392
+ process.once('SIGTERM', stopped);
1393
+ /** @type {Awaited<ReturnType<typeof previewAfter>>} */
1394
+ let p;
1395
+ try {
1396
+ p = await previewAfter(ctx, slug, data, png);
1397
+ } finally {
1398
+ process.removeListener('SIGINT', stopped);
1399
+ process.removeListener('SIGTERM', stopped);
1400
+ }
838
1401
  const wrote = takeFirstAppCopy(ctx.project.cwd, slug);
1402
+ const previewStale = await keepPreviewRoute(ctx, slug);
839
1403
  return {
840
1404
  ...p,
841
- previewStale: await keepPreviewRoute(ctx, slug),
1405
+ previewStale,
842
1406
  // How to see the change: the page about it, at its own URL.
843
1407
  // A page not written this time (preview null) still shows the theme
844
1408
  // as it was; checks that failed with the page written do not.
@@ -852,9 +1416,18 @@ async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
852
1416
  cause: 'no preview was rendered',
853
1417
  })
854
1418
  : null,
1419
+ {
1420
+ // Only a run that took no picture failed: a note on pictures that
1421
+ // were taken (why an earlier browser did not) is not a failure.
1422
+ pictureProblem:
1423
+ png && !(p.pictures ?? []).length ? p.pictureProblem : null,
1424
+ stale: previewStale,
1425
+ },
855
1426
  ),
856
1427
  // The first time the theme's app copy is written, its files are named.
857
1428
  ...(wrote ? {appCopy: {wrote}} : {}),
1429
+ // A copy a file of yours kept from being written: said, never a quiet ok.
1430
+ ...appCopyStale(ctx.project.cwd, slug),
858
1431
  };
859
1432
  }
860
1433
 
@@ -870,12 +1443,93 @@ async function previewAndRoute(ctx, slug, data, png, focus = 'overview') {
870
1443
  async function keepPreviewRoute(ctx, slug) {
871
1444
  try {
872
1445
  return (await refreshPreviewRoute(ctx.project.cwd, slug)).stale;
873
- } catch {
874
- // A damaged or moved preview.
1446
+ } catch (e) {
1447
+ // A route that could not be written (its permissions, a folder in its
1448
+ // place) does not follow this change: said, never a quiet ok. A
1449
+ // damaged preview record is named by the preview commands themselves.
1450
+ const code = /** @type {any} */ (e)?.code;
1451
+ if (code && /^E[A-Z]+$/.test(code)) {
1452
+ const where = /** @type {any} */ (e)?.path;
1453
+ return [
1454
+ `${where ? path.relative(ctx.project.cwd, where) : 'the in-app preview route'} could not be written (${code}), so the in-app preview does not follow this change; fix its permissions, then ${PREVIEW_CMD} add writes it again`,
1455
+ ];
1456
+ }
875
1457
  return [];
876
1458
  }
877
1459
  }
878
1460
 
1461
+ /**
1462
+ * The app's theme state (the themes `theme add` put into its theme
1463
+ * module), or null when it cannot be read.
1464
+ * @param {string} cwd
1465
+ */
1466
+ function appThemeState(cwd) {
1467
+ try {
1468
+ return readThemeState(cwd);
1469
+ } catch {
1470
+ return null;
1471
+ }
1472
+ }
1473
+
1474
+ /**
1475
+ * Whether the app lists the theme (`theme add` put it into its module).
1476
+ * @param {string} cwd
1477
+ * @param {string} slug
1478
+ */
1479
+ const appListsTheme = (cwd, slug) =>
1480
+ Object.hasOwn(appThemeState(cwd)?.themes ?? {}, slug);
1481
+
1482
+ /**
1483
+ * For a theme `theme add` put into the app: the app's theme module gives
1484
+ * the app each theme's one color mode, written when the theme was added,
1485
+ * so a change of mode needs `theme add` again. Null for a theme the app
1486
+ * does not list (its mode is the app's own <Theme mode>).
1487
+ * @param {string} cwd
1488
+ * @param {string} slug
1489
+ * @param {'light' | 'dark' | null} now the one mode it has now
1490
+ * @returns {string | null}
1491
+ */
1492
+ function addedModeNote(cwd, slug, now) {
1493
+ const state = appThemeState(cwd);
1494
+ if (!state || !Object.hasOwn(state.themes, slug)) return null;
1495
+ const module = path
1496
+ .relative(cwd, state.module.path)
1497
+ .split(path.sep)
1498
+ .join('/');
1499
+ return `${module}, the app's theme module, gives the app ${slug}'s mode as it was when ${slug} was added; run \`theme add ${slug}\` to write it again, and the app ${now ? `shows ${slug} in ${now} mode` : 'follows the system again'}`;
1500
+ }
1501
+
1502
+ /**
1503
+ * What a change of mode asks of the app's wiring: a one-mode theme is
1504
+ * given its mode by the app's <Theme>, and one back to both modes no longer.
1505
+ * @param {string} cwd
1506
+ * @param {string} slug
1507
+ * @param {string | undefined} before
1508
+ * @param {string | undefined} after
1509
+ * @returns {string[]}
1510
+ */
1511
+ function modeWiringNotes(cwd, slug, before, after) {
1512
+ /** @param {string | undefined} m @returns {'light' | 'dark' | null} */
1513
+ const one = m =>
1514
+ m === 'light-only' ? 'light' : m === 'dark-only' ? 'dark' : null;
1515
+ const [was, now] = [one(before), one(after)];
1516
+ if (was === now) return [];
1517
+ const added = addedModeNote(cwd, slug, now);
1518
+ if (added) return [added];
1519
+ return [
1520
+ ...(was
1521
+ ? [
1522
+ `if the app's <Theme> was given mode="${was}" for ${slug}, take it out${now ? ` (or make it mode="${now}")` : ''}: with it the app stays ${was}, whatever the system asks for`,
1523
+ ]
1524
+ : []),
1525
+ ...(now && !was
1526
+ ? [
1527
+ `the app shows ${slug} in ${now} mode when its <Theme> is given mode="${now}" (<Theme theme={…} mode="${now}">), as the preview does; the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
1528
+ ]
1529
+ : []),
1530
+ ];
1531
+ }
1532
+
879
1533
  /**
880
1534
  * Change one thing in a theme: checked, built, previewed.
881
1535
  * @experimental
@@ -886,87 +1540,457 @@ async function keepPreviewRoute(ctx, slug) {
886
1540
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
887
1541
  */
888
1542
  export async function themeEditSet(theme, thing, value, options = {}) {
889
- return change('set', theme, thing, value, options);
1543
+ try {
1544
+ return await change('set', theme, thing, value, options);
1545
+ } catch (e) {
1546
+ throw await swappedThingValue(
1547
+ await swappedOrder(e, 'set', [theme, thing, value], options),
1548
+ theme,
1549
+ thing,
1550
+ value,
1551
+ options,
1552
+ );
1553
+ }
890
1554
  }
891
1555
 
892
1556
  /**
893
- * Refuse a theme whose saved exact tokens the type rules no longer take,
894
- * naming the undo that removes the one that fails.
895
- * @param {import('./_settings.mjs').Ctx} ctx
1557
+ * A refused set whose thing is no setting, with a value that names one
1558
+ * (`set t round corners`): the same set with the two in the other order,
1559
+ * checked by set, leads when it works.
1560
+ * @param {unknown} e
896
1561
  * @param {string} slug
897
- * @param {import('./_settings.mjs').ThemeData} data
898
- * @param {string | {thing: string, on?: string, when?: string, state?: string, mode?: string}} [skip]
1562
+ * @param {string} thing
1563
+ * @param {string | undefined} value
1564
+ * @param {{cwd?: string, on?: string, when?: string, state?: string, mode?: string, only?: boolean}} options
1565
+ * @returns {Promise<unknown>}
899
1566
  */
900
- function refuseStoredTokens(ctx, slug, data, skip) {
901
- const bad = storedProblems(ctx, slug, data, skip);
902
- if (!bad.length) return;
903
- const found = bad.length === 1 ? bad[0] : null;
904
- // A clean value is offered only when set takes it, so the line works.
905
- const takes = (/** @type {typeof found} */ b) => {
906
- if (!b?.fix) return true;
907
- try {
908
- checkSetting(
909
- ctx,
910
- slug,
911
- {...data, settings: data.settings.filter(x => x !== b.setting)},
912
- b.setting.thing,
913
- b.fix,
914
- {
915
- on: b.setting.on,
916
- when: b.setting.when,
917
- state: b.setting.state,
918
- mode: b.setting.mode,
919
- },
920
- false,
921
- );
922
- return true;
923
- } catch {
924
- return false;
925
- }
926
- };
927
- const one = found && takes(found) ? found : null;
928
- refuse(
929
- E.ERR_THEME_INVALID,
930
- `themes/${slug}/${slug}.settings.json: ${bad
931
- .map(
932
- b =>
933
- `${describe(b.setting)} ${b.scope ? 'applies where the editor does not accept it' : 'holds a value the editor no longer accepts'} (${b.why})`,
934
- )
935
- .join('; ')}.`,
936
- {
937
- // Each undo runs while the others are still saved: an undo of one
938
- // setting is never refused for another.
939
- run: [
940
- ...bad.slice(0, 5).map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
941
- // A value to set only for a token whose stored value has the wrong
942
- // type; any other thing `set` would refuse, or read as a dial.
943
- ...(one &&
944
- !one.scope &&
945
- one.setting.source === 'token' &&
946
- ctx.C.isToken(one.setting.thing)
947
- ? [
948
- // The value the check suggests for this value, else a stock
949
- // one of the token's type.
950
- `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix ?? exampleOf(ctx.C.typeOf(one.setting.thing), one.setting.thing))}`,
951
- ]
952
- : one && one.fix && one.setting.source === 'dial'
953
- ? [
954
- `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix)}`,
955
- ]
956
- : []),
957
- ],
958
- },
1567
+ async function swappedThingValue(e, slug, thing, value, options) {
1568
+ // The thing named no setting, or the value names one itself (`neutral
1569
+ // base`: a color dial given the base dial's name).
1570
+ if (
1571
+ !(e instanceof AstryxError) ||
1572
+ !value ||
1573
+ !slugOk(slug) ||
1574
+ !(
1575
+ e.code === E.ERR_THEME_UNKNOWN_THING ||
1576
+ (DIALS[value.trim().toLowerCase()] && e.code === E.ERR_THEME_BAD_VALUE)
1577
+ )
1578
+ )
1579
+ return e;
1580
+ const line = `${P} set ${slug} ${[
1581
+ value,
1582
+ thing,
1583
+ ...(options.on ? ['--on', options.on] : []),
1584
+ ...(options.when ? ['--when', options.when] : []),
1585
+ ...(options.state ? ['--state', options.state] : []),
1586
+ ...(options.mode ? ['--mode', options.mode] : []),
1587
+ ]
1588
+ .map(w => quoteCommandArgument(String(w)))
1589
+ .join(' ')}${options.only ? ' --only' : ''}`;
1590
+ const followed = await followChangeLine(
1591
+ 'set',
1592
+ slug,
1593
+ line,
1594
+ options.cwd ?? process.cwd(),
959
1595
  );
1596
+ // The swapped reading holds only when set takes the value typed as the
1597
+ // setting, with the scope typed, and the line carries the thing typed
1598
+ // as its value (the one gate): never a sample command from a refusal of
1599
+ // the swapped line (`bold` is no setting, and no part was named). A line
1600
+ // that works once a step is done (an install) is offered after that step.
1601
+ const read = readSetLine(followed.line, slug);
1602
+ if (
1603
+ !read ||
1604
+ read.thing.toLowerCase() !== String(value).trim().toLowerCase() ||
1605
+ (read.flags?.on ?? undefined) !== (options.on ?? undefined) ||
1606
+ !allowedLine({offered: read.value, typed: String(thing), thing: read.thing})
1607
+ )
1608
+ return e;
1609
+ const why = `do this instead: ${value} is the setting and ${thing} its value`;
1610
+ if (!readyLines(followed, why).length) return e;
1611
+ e.suggestions = [
1612
+ ...readyLines(followed, why),
1613
+ ...(e.suggestions ?? []).filter(x => x.name !== followed.line),
1614
+ ];
1615
+ return e;
960
1616
  }
961
1617
 
962
1618
  /**
963
- * For `compile`: the refusal `show` gives for saved settings the editor no
964
- * longer accepts (naming the undo that removes each), or null.
965
- * @param {string} root
1619
+ * The theme and the context a line is checked against (set's own check, in
1620
+ * memory), a saved entry not checked while the theme is read; null when
1621
+ * the theme does not load.
1622
+ * @param {string} cwd
966
1623
  * @param {string} slug
967
- * @returns {Promise<import('../error.mjs').AstryxError | null>}
1624
+ * @param {Partial<import('./_settings.mjs').Setting>} [skip]
968
1625
  */
969
- export async function editorStoredRefusal(root, slug) {
1626
+ async function loadedForCheck(cwd, slug, skip) {
1627
+ try {
1628
+ const data = loadTheme(cwd, slug, skip);
1629
+ const ctx = /** @type {import('./_settings.mjs').Ctx} */ (
1630
+ await context(cwd)
1631
+ );
1632
+ ctx.base = await baseResolved(ctx.project, data.like);
1633
+ return {data, ctx};
1634
+ } catch {
1635
+ return null;
1636
+ }
1637
+ }
1638
+
1639
+ /**
1640
+ * A refusal of a saved entry whose value the editor no longer accepts,
1641
+ * with the repair `set` offers for that value as typed (a typo, a unit, a
1642
+ * label read as set reads them) beside the undo: the line is followed as
1643
+ * set takes it, with the saved entry not checked while the theme is read,
1644
+ * and offered only when it carries the saved value (the one gate).
1645
+ * @param {unknown} e
1646
+ * @param {string} slug
1647
+ * @param {string} cwd
1648
+ */
1649
+ async function withSavedRepair(e, slug, cwd) {
1650
+ const bad = /** @type {any} */ (e)?.damaged;
1651
+ // The value as set reads a typed one: text, or a number written as JSON
1652
+ // (`8` on corners is the 8 typed).
1653
+ const saved =
1654
+ typeof bad?.value === 'string'
1655
+ ? bad.value
1656
+ : typeof bad?.value === 'number' && Number.isFinite(bad.value)
1657
+ ? String(bad.value)
1658
+ : null;
1659
+ if (
1660
+ !(e instanceof AstryxError) ||
1661
+ !bad ||
1662
+ saved == null ||
1663
+ ['mode', 'base'].includes(bad.thing)
1664
+ )
1665
+ return e;
1666
+ // The thing as set reads it (`CORNERS`, `corners ` are corners).
1667
+ const thing = String(normalizeEntry(String(bad.thing), saved).thing);
1668
+ const line = `${P} set ${slug} ${setArgs({...bad, thing}, saved)}`;
1669
+ // The lines set offers for the value, as for a typed one: each checked
1670
+ // as set checks it, and offered only when they carry the saved value
1671
+ // (the one gate; a family and its size may take two lines).
1672
+ const loaded = await loadedForCheck(cwd, slug, bad);
1673
+ if (!loaded) return e;
1674
+ /** @type {string[]} */
1675
+ let lines;
1676
+ try {
1677
+ checkSetting(
1678
+ loaded.ctx,
1679
+ slug,
1680
+ structuredClone(loaded.data),
1681
+ thing,
1682
+ saved,
1683
+ {on: bad.on, when: bad.when, state: bad.state, mode: bad.mode},
1684
+ false,
1685
+ );
1686
+ lines = [line];
1687
+ } catch (x) {
1688
+ if (!(x instanceof AstryxError)) throw x;
1689
+ lines = (x.suggestions ?? [])
1690
+ .map(y => y.name)
1691
+ .filter(n => n.startsWith(`${P} set ${slug} `));
1692
+ }
1693
+ /** @type {string[]} */
1694
+ const working = [];
1695
+ for (const l of lines) {
1696
+ const followed = await followChangeLine('set', slug, l, cwd, bad);
1697
+ if (!followed.why) working.push(followed.line);
1698
+ }
1699
+ const reads = working.map(l => {
1700
+ const read = readSetLine(l, slug);
1701
+ return read
1702
+ ? readsTyped({
1703
+ offered: read.value,
1704
+ typed: saved,
1705
+ thing: read.thing,
1706
+ typedThing: thing,
1707
+ })
1708
+ : false;
1709
+ });
1710
+ const covered = coversTyped(reads, saved, thing);
1711
+ const kept = working.filter(
1712
+ (_, i) =>
1713
+ reads[i] === true ||
1714
+ (reads[i] && typeof reads[i] === 'object' && covered),
1715
+ );
1716
+ if (!kept.length) return e;
1717
+ const list = e.suggestions ?? [];
1718
+ // A set line the refusal already offers (the value cleaned) stands.
1719
+ if (list.some(x => x.name.startsWith(`${P} set ${slug} `))) return e;
1720
+ const at = list.findIndex(x => x.name.startsWith(`${P} undo ${slug} `));
1721
+ e.suggestions = [
1722
+ ...list.slice(0, at + 1),
1723
+ ...kept.map(name => ({
1724
+ name,
1725
+ reason: 'or set the value it holds, as set reads it',
1726
+ })),
1727
+ ...list.slice(at + 1),
1728
+ ];
1729
+ return e;
1730
+ }
1731
+
1732
+ /**
1733
+ * The lines that carry out a `new` the CLI builds (words of a value read
1734
+ * back into it): the line when new takes it, else what new's own refusal
1735
+ * of it offers, vetted as every offered new line is. new's checks only:
1736
+ * nothing is written.
1737
+ * @param {string} line the whole command, `astryx experimental theme editor new <theme> …`
1738
+ * @param {string} name
1739
+ * @param {import('./theme-edit.type.mjs').ThemeEditNewOptions} options
1740
+ * @returns {Promise<import('../../foundation/response/base').Suggestion[]>}
1741
+ */
1742
+ export async function checkedNewLines(line, name, options) {
1743
+ try {
1744
+ await newTheme(name, options, {check: true});
1745
+ return [{name: line, reason: 'do this instead'}];
1746
+ } catch (e) {
1747
+ const vetted = await vetNewLines(
1748
+ e,
1749
+ options.cwd ?? process.cwd(),
1750
+ options.settings ?? {},
1751
+ options.like,
1752
+ );
1753
+ if (vetted instanceof AstryxError) return vetted.suggestions ?? [];
1754
+ throw vetted;
1755
+ }
1756
+ }
1757
+
1758
+ /**
1759
+ * A `set` or `undo` command line as set or undo takes it (a repair either
1760
+ * offers folded in, see followChangeLine), or null when it is refused with
1761
+ * no repair: the check every offered line passes, for lines the CLI builds
1762
+ * (a flag written with a value).
1763
+ * @param {'set' | 'undo'} sub
1764
+ * @param {string} line the whole command, `astryx experimental theme editor set <theme> …`
1765
+ * @param {string} cwd
1766
+ * @returns {Promise<string | null>}
1767
+ */
1768
+ export async function checkedChangeLine(sub, line, cwd) {
1769
+ const slug = splitCommand(line.slice(`${P} ${sub} `.length))?.[0];
1770
+ if (!line.startsWith(`${P} ${sub} `) || !slug) return null;
1771
+ const followed = await followChangeLine(sub, slug, line, cwd);
1772
+ return followed.why ? null : followed.line;
1773
+ }
1774
+
1775
+ /**
1776
+ * The lines that carry out a followed line: itself when it works; when its
1777
+ * own refusal offers it after a step (an install), that step and then the
1778
+ * line; else nothing.
1779
+ * @param {{line: string, why: string | null, next?: import('../../foundation/response/base').Suggestion[]}} followed
1780
+ * @param {string} reason
1781
+ * @returns {import('../../foundation/response/base').Suggestion[]}
1782
+ */
1783
+ function readyLines(followed, reason) {
1784
+ if (!followed.why) return [{name: followed.line, reason}];
1785
+ const at = (followed.next ?? []).findIndex(x => x.name === followed.line);
1786
+ return at > 0
1787
+ ? [
1788
+ ...(followed.next ?? []).slice(0, at),
1789
+ {
1790
+ name: followed.line,
1791
+ reason: `then ${reason.replace(/^do this instead: /, '')}`,
1792
+ },
1793
+ ]
1794
+ : [];
1795
+ }
1796
+
1797
+ /**
1798
+ * A refused theme name when the theme was typed after the setting (`set
1799
+ * --color-accent '#123457' t`): the same command with the theme first,
1800
+ * checked by that command, comes first, and no `new` of the setting's name
1801
+ * is offered.
1802
+ * @param {unknown} e
1803
+ * @param {'set' | 'undo'} sub
1804
+ * @param {Array<string | undefined>} words the positionals as typed
1805
+ * @param {{cwd?: string, on?: string, when?: string, state?: string, mode?: string, only?: boolean}} options
1806
+ * @returns {Promise<unknown>}
1807
+ */
1808
+ async function swappedOrder(e, sub, words, options) {
1809
+ if (
1810
+ !(e instanceof AstryxError) ||
1811
+ (e.code !== E.ERR_INVALID_ARGUMENT && e.code !== E.ERR_UNKNOWN_THEME)
1812
+ )
1813
+ return e;
1814
+ const cwd = options.cwd ?? process.cwd();
1815
+ const [first, ...rest] = words.map(w => (w == null ? '' : String(w)));
1816
+ if (slugOk(first) && fs.existsSync(themeFiles(cwd, first).settings)) return e;
1817
+ const at = rest.findIndex(
1818
+ w => slugOk(w) && fs.existsSync(themeFiles(cwd, w).settings),
1819
+ );
1820
+ if (at < 0) return e;
1821
+ const theme = rest[at];
1822
+ const moved = [first, ...rest.filter((_, i) => i !== at)].filter(
1823
+ w => w !== '',
1824
+ );
1825
+ const flags = [
1826
+ ...(options.on ? ['--on', options.on] : []),
1827
+ ...(options.when ? ['--when', options.when] : []),
1828
+ ...(options.state ? ['--state', options.state] : []),
1829
+ ...(options.mode ? ['--mode', options.mode] : []),
1830
+ ];
1831
+ // The line with the theme first, as set or undo checks it; for a set
1832
+ // whose other two words are also in the other order, the line with those
1833
+ // swapped too. Only a line that works is offered.
1834
+ const lineOf = (/** @type {string[]} */ ws) =>
1835
+ `${P} ${sub} ${theme} ${[...ws, ...flags]
1836
+ .map(w => quoteCommandArgument(w))
1837
+ .join(' ')}${options.only ? ' --only' : ''}`;
1838
+ let followed = await followChangeLine(sub, theme, lineOf(moved), cwd);
1839
+ if (followed.why && sub === 'set' && moved.length === 2)
1840
+ followed = await followChangeLine(
1841
+ sub,
1842
+ theme,
1843
+ lineOf([moved[1], moved[0]]),
1844
+ cwd,
1845
+ );
1846
+ const ready = readyLines(
1847
+ followed,
1848
+ `do this instead: ${theme} is the theme, so it comes first`,
1849
+ );
1850
+ // With the theme first and still refused, that refusal's reason and its
1851
+ // own next commands: never a `new` of the setting's name.
1852
+ if (!ready.length && followed.why)
1853
+ e.message = `${e.message.replace(/\s*Nothing was changed\.$/, '')} With ${theme} first: ${followed.why}. Nothing was changed.`;
1854
+ e.suggestions = [
1855
+ ...(ready.length
1856
+ ? ready
1857
+ : (followed.next ?? []).filter(x => !x.name.startsWith(`${P} new `))),
1858
+ ...(e.suggestions ?? []).filter(
1859
+ x => x.name !== followed.line && !x.name.startsWith(`${P} new `),
1860
+ ),
1861
+ ];
1862
+ return e;
1863
+ }
1864
+
1865
+ /**
1866
+ * Refuse a theme whose saved exact tokens the type rules no longer take,
1867
+ * naming the undo that removes the one that fails.
1868
+ * @param {import('./_settings.mjs').Ctx} ctx
1869
+ * @param {string} slug
1870
+ * @param {import('./_settings.mjs').ThemeData} data
1871
+ * @param {string | {thing: string, on?: string, when?: string, state?: string, mode?: string}} [skip]
1872
+ */
1873
+ function refuseStoredTokens(ctx, slug, data, skip) {
1874
+ const bad = storedProblems(ctx, slug, data, skip);
1875
+ if (!bad.length) return;
1876
+ // A repair offers only the value it holds, cleaned: never a stock value
1877
+ // the saved setting did not hold.
1878
+ for (const b of bad) {
1879
+ if (
1880
+ b.fix &&
1881
+ !allowedLine({
1882
+ offered: String(b.fix),
1883
+ typed: String(b.setting.value),
1884
+ thing: b.setting.thing,
1885
+ mode: b.setting.mode ?? '',
1886
+ })
1887
+ )
1888
+ delete b.fix;
1889
+ // A light and a dark color saved as one (`red / blue`) is that pair.
1890
+ const pair =
1891
+ !b.fix && isColorToken(b.setting.thing)
1892
+ ? colorPair(String(b.setting.value))
1893
+ : null;
1894
+ if (pair && !colorProblem(pair.light) && !colorProblem(pair.dark))
1895
+ b.fix = `light-dark(${pair.light}, ${pair.dark})`;
1896
+ }
1897
+ const found = bad.length === 1 ? bad[0] : null;
1898
+ // A clean value is offered only when set takes it, so the line works.
1899
+ const takes = (/** @type {typeof found} */ b) => {
1900
+ if (!b?.fix) return true;
1901
+ // A value whose only fault was curly quotes around it: without them,
1902
+ // when set takes that (`“#e11d48”` is #e11d48).
1903
+ const bare = /^(["'])(.*)\1$/.exec(b.fix)?.[2];
1904
+ if (
1905
+ bare &&
1906
+ b.setting.source === 'token' &&
1907
+ !/font|content/.test(b.setting.thing)
1908
+ ) {
1909
+ const was = b.fix;
1910
+ b.fix = bare;
1911
+ if (takesOne(b)) return true;
1912
+ b.fix = was;
1913
+ }
1914
+ return takesOne(b);
1915
+ };
1916
+ const takesOne = (/** @type {typeof found} */ b) => {
1917
+ if (!b?.fix) return true;
1918
+ try {
1919
+ checkSetting(
1920
+ ctx,
1921
+ slug,
1922
+ {...data, settings: data.settings.filter(x => x !== b.setting)},
1923
+ b.setting.thing,
1924
+ b.fix,
1925
+ {
1926
+ on: b.setting.on,
1927
+ when: b.setting.when,
1928
+ state: b.setting.state,
1929
+ mode: b.setting.mode,
1930
+ },
1931
+ false,
1932
+ );
1933
+ return true;
1934
+ } catch {
1935
+ return false;
1936
+ }
1937
+ };
1938
+ const one = found && takes(found) ? found : null;
1939
+ // One saved entry with no line of its own: the entry rides on the
1940
+ // refusal, and the change offers set's repair for its value beside the
1941
+ // undo (withSavedRepair).
1942
+ try {
1943
+ refuse(
1944
+ E.ERR_THEME_INVALID,
1945
+ `themes/${slug}/${slug}.settings.json: ${bad
1946
+ .map(
1947
+ b =>
1948
+ `${describe(b.setting)} ${b.scope ? 'applies where the editor does not accept it' : 'holds a value the editor no longer accepts'} (${b.why})`,
1949
+ )
1950
+ .join('; ')}.`,
1951
+ {
1952
+ // Each undo runs while the others are still saved: an undo of one
1953
+ // setting is never refused for another.
1954
+ run: [
1955
+ ...bad
1956
+ .slice(0, 5)
1957
+ .map(b => `${P} undo ${slug} ${undoArgs(b.setting)}`),
1958
+ // A value to set only for a token whose stored value has the wrong
1959
+ // type; any other thing `set` would refuse, or read as a dial.
1960
+ ...(one &&
1961
+ one.fix &&
1962
+ !one.scope &&
1963
+ one.setting.source === 'token' &&
1964
+ ctx.C.isToken(one.setting.thing)
1965
+ ? [
1966
+ // The value the check suggests for this value, else a stock
1967
+ // one of the token's type.
1968
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(String(one.fix))}${one.setting.mode ? ` --mode ${one.setting.mode}` : ''}`,
1969
+ ]
1970
+ : one && one.fix && one.setting.source === 'dial'
1971
+ ? [
1972
+ `${P} set ${slug} ${one.setting.thing} ${quoteCommandArgument(one.fix)}`,
1973
+ ]
1974
+ : []),
1975
+ ],
1976
+ },
1977
+ );
1978
+ } catch (e) {
1979
+ throw Object.assign(/** @type {object} */ (e), {
1980
+ aboutSaved: true,
1981
+ ...(found && !(one && one.fix) ? {damaged: found.setting} : {}),
1982
+ });
1983
+ }
1984
+ }
1985
+
1986
+ /**
1987
+ * For `compile`: the refusal `show` gives for saved settings the editor no
1988
+ * longer accepts (naming the undo that removes each), or null.
1989
+ * @param {string} root
1990
+ * @param {string} slug
1991
+ * @returns {Promise<import('../error.mjs').AstryxError | null>}
1992
+ */
1993
+ export async function editorStoredRefusal(root, slug) {
970
1994
  try {
971
1995
  const ctx = await context(root);
972
1996
  refuseStoredTokens(ctx, slug, loadTheme(root, slug));
@@ -978,47 +2002,967 @@ export async function editorStoredRefusal(root, slug) {
978
2002
  }
979
2003
 
980
2004
  /**
981
- * For `compile`: the refusal of [light, dark] pairs on tokens that are not
982
- * colors in what the theme builds now, or null.
983
- * @param {string} root
2005
+ * The token values the theme's own source gives that `set` refuses (a
2006
+ * radius of `banana`, a color of `12px`), each with why and the line of
2007
+ * the file that sets it; checked with the very rules `set` uses.
2008
+ * @param {import('./_settings.mjs').Ctx} ctx
984
2009
  * @param {string} slug
985
- * @returns {Promise<import('../error.mjs').AstryxError | null>}
2010
+ * @param {import('./_settings.mjs').ThemeData} data
2011
+ * @returns {Promise<Array<{token: string, value: string, why: string, line: number | null, file?: string | null}>>}
986
2012
  */
987
- export async function editorPairRefusal(root, slug) {
988
- const ctx = await context(root);
989
- const names = await builtPairs(ctx, slug);
990
- if (!names.length) return null;
2013
+ async function ownTokenProblems(ctx, slug, data) {
2014
+ const {cwd} = ctx.project;
2015
+ /** @type {Array<{token: string, value: string, why: string, line: number | null, file?: string | null}>} */
2016
+ const out = [];
2017
+ const known = ctx.project.core.tokenDefaults;
2018
+ /**
2019
+ * @param {string} token
2020
+ * @param {string} value
2021
+ * @param {ReadonlySet<string>} [reads] custom properties the theme sets where the value is read
2022
+ * @returns {string | null}
2023
+ */
2024
+ const refused = (token, value, reads) => {
2025
+ try {
2026
+ checkSetting(
2027
+ ctx,
2028
+ slug,
2029
+ {...data, settings: []},
2030
+ token,
2031
+ value,
2032
+ {},
2033
+ false,
2034
+ {
2035
+ reads,
2036
+ },
2037
+ );
2038
+ return null;
2039
+ } catch (e) {
2040
+ if (!(e instanceof AstryxError)) throw e;
2041
+ return e.message.replace(/ Nothing was changed\.$/, '');
2042
+ }
2043
+ };
2044
+ /** The file an entry is in, as the project names it; null for the theme file. @param {{file?: string}} e */
2045
+ const fileOf = e => (e.file ? path.relative(cwd, e.file) : null);
2046
+ /** @param {{line: number | null, file?: string}} e */
2047
+ const atOf = e => ({line: e.line, file: fileOf(e)});
2048
+ // Every value is judged as the source gives it to defineTheme(), the
2049
+ // module evaluated as a build evaluates it (an import, an expression, a
2050
+ // spread or a computed key is its value), in every place a build writes
2051
+ // tokens from: the page's tokens, a part's blocks, onDark and onLight,
2052
+ // adaptation rules, and the typography. The source's syntax is read to
2053
+ // name the file and line that hold each value, and for what evaluation
2054
+ // erases: a `tokens` key given twice (JavaScript keeps the last) and a
2055
+ // [light, dark] pair with other than two values written in the file.
2056
+ const entries = ownTokenEntries(cwd, slug).filter(e => !e.overridden);
2057
+ const tokensLine = entries.find(e => e.kind === 'unresolved')?.line ?? null;
2058
+ /** Where a page token's value comes from. @param {string} token */
2059
+ const whereOf = token => {
2060
+ const e = entries.find(
2061
+ x => x.token === token && x.kind !== 'scoped' && x.kind !== 'chain',
2062
+ );
2063
+ return e ? atOf(e) : {line: tokensLine, file: null};
2064
+ };
2065
+ /** Where a scoped token's value comes from. @param {string} scope @param {string} token */
2066
+ const whereIn = (scope, token) => {
2067
+ const e =
2068
+ entries.find(
2069
+ x => x.kind === 'scoped' && x.scope === scope && x.token === token,
2070
+ ) ??
2071
+ entries.find(x => x.kind === 'scope' && x.key === scope.split('.')[0]);
2072
+ return e ? atOf(e) : {line: null, file: null};
2073
+ };
2074
+ for (const e of entries) {
2075
+ if (e.kind === 'duplicate')
2076
+ out.push({
2077
+ token: 'tokens',
2078
+ value: '',
2079
+ why: `defineTheme is given tokens twice (lines ${(e.lines ?? []).join(' and ')}); the build keeps only the last, so the first does nothing: merge them into one`,
2080
+ ...atOf(e),
2081
+ });
2082
+ else if (e.notToken) {
2083
+ const key = e.key.replace(/^(["'`])(.*)\1$/, '$2');
2084
+ out.push({
2085
+ token: key,
2086
+ value: '',
2087
+ why: `${key} is no token: a token name starts with -- (such as --color-accent), and the build writes any other key as a CSS declaration on the theme's root, which styles every element; for one part, set it as a property on that part (\`${P} set ${slug} ${key} <value> --on <part>\`)`,
2088
+ ...atOf(e),
2089
+ });
2090
+ } else if (
2091
+ e.token?.startsWith('--_') &&
2092
+ e.kind !== 'scoped' &&
2093
+ e.kind !== 'chain'
2094
+ )
2095
+ out.push({
2096
+ token: e.token,
2097
+ value: '',
2098
+ why: `${e.token} is a private variable (--_*), which Core sets itself, so the build refuses a theme that sets one: remove it`,
2099
+ ...atOf(e),
2100
+ });
2101
+ else if (
2102
+ e.kind === 'pair' &&
2103
+ e.token &&
2104
+ e.token in known &&
2105
+ (e.halves ?? []).length !== 2
2106
+ ) {
2107
+ const halves = e.halves ?? [];
2108
+ out.push({
2109
+ token: e.token,
2110
+ value: `[${halves.map(h => (h === undefined ? '…' : JSON.stringify(h))).join(', ')}]`,
2111
+ why: `a [light, dark] pair holds exactly two values in quotes, and this holds ${halves.length}; the build would write ${halves.length < 2 ? 'light-dark() with an undefined half' : 'the first two and drop the rest'}`,
2112
+ ...atOf(e),
2113
+ });
2114
+ }
2115
+ }
2116
+ // A private variable stops the build itself: nothing more to judge.
2117
+ if (out.some(b => b.token.startsWith('--_'))) return out;
2118
+ const loaded = await ownThemeInput(ctx, slug, data.like ?? null);
2119
+ const input = loaded?.input;
2120
+ if (!input || typeof input !== 'object') return out;
2121
+ const named = new Set(out.map(b => b.token));
2122
+ /**
2123
+ * Why a token's value is refused, or null. Any token, a design token or
2124
+ * the theme's own, takes text or a pair of two texts; any other value
2125
+ * (null, a boolean, a number, a BigInt, a symbol, an object) is no text.
2126
+ * A design token's text is checked as `set` checks it, and only a color
2127
+ * takes a pair.
2128
+ * @param {string} token
2129
+ * @param {unknown} value
2130
+ * @param {string} file the file named in a pair's refusal
2131
+ * @param {ReadonlySet<string>} reads custom properties the theme sets where the value is read
2132
+ * @returns {string | null}
2133
+ */
2134
+ const judge = (token, value, file, reads) => {
2135
+ const custom = !(token in known);
2136
+ if (Array.isArray(value)) {
2137
+ if (value.length !== 2 || value.some(h => typeof h !== 'string'))
2138
+ return nonTextMessage(ctx, slug, [token, value]);
2139
+ if (custom) return null;
2140
+ if (!isColorToken(token)) {
2141
+ const unitless =
2142
+ ctx.C.typeOf(token) === 'size' &&
2143
+ value.every(h => /^\d*\.?\d+$/.test(String(h).trim()));
2144
+ return unitless
2145
+ ? nonTextMessage(ctx, slug, [token, value.map(Number), 'unit'])
2146
+ : `${file} gives ${token} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors; give it one value`;
2147
+ }
2148
+ for (const [i, h] of value.entries()) {
2149
+ const why = refused(token, String(h), reads);
2150
+ if (why) return `its ${i === 0 ? 'light' : 'dark'} half: ${why}`;
2151
+ }
2152
+ return null;
2153
+ }
2154
+ if (typeof value !== 'string')
2155
+ return nonTextMessage(
2156
+ ctx,
2157
+ slug,
2158
+ value && typeof value === 'object'
2159
+ ? [token, value, 'object']
2160
+ : [token, value],
2161
+ );
2162
+ if (custom) return null;
2163
+ if (/^light-dark\(/i.test(value) && !isColorToken(token))
2164
+ return `${file} gives ${token} a [light, dark] pair, but only colors differ by mode: the build would write light-dark(), which browsers take only for colors; give it one value`;
2165
+ return refused(token, value, reads);
2166
+ };
2167
+ /**
2168
+ * Why a part's CSS property value is refused, or null: text as `set`
2169
+ * checks it for that property; a number is written as it is, so it
2170
+ * stands only where the property takes a bare number; any other value is
2171
+ * no text.
2172
+ * @param {string} prop the property, as CSS names it
2173
+ * @param {unknown} value
2174
+ * @param {string} file
2175
+ * @param {ReadonlySet<string>} reads custom properties the theme sets where the value is read
2176
+ * @returns {string | null}
2177
+ */
2178
+ const judgeProperty = (prop, value, file, reads) => {
2179
+ if (typeof value === 'string')
2180
+ return propertyValueProblem(ctx, prop, value, known, reads);
2181
+ if (typeof value === 'number')
2182
+ return matchValue(prop, String(value))
2183
+ ? null
2184
+ : `${file} gives ${prop} the number ${value}, which the build writes as it is (${prop}: ${value}) and ${prop} does not take, so the browser drops it; write it with a unit, such as '${value}px'`;
2185
+ return `${file} gives ${prop} the value ${describeValue(value)}, which is not text: a part's property is a CSS value in quotes, such as '4px'`;
2186
+ };
2187
+ /** @param {{line: number | null, file: string | null}} at */
2188
+ const fileName = at => at.file ?? `${slug}.theme.ts`;
2189
+ /** A value as the build writes it, when it is text. @param {unknown} v */
2190
+ const asWritten = v =>
2191
+ typeof v === 'string'
2192
+ ? v
2193
+ : Array.isArray(v) &&
2194
+ v.length === 2 &&
2195
+ v.every(h => typeof h === 'string')
2196
+ ? `light-dark(${v.join(', ')})`
2197
+ : '';
2198
+ /** The custom properties a block of tokens sets. @param {any} node */
2199
+ const varsIn = node =>
2200
+ node && typeof node === 'object' && !Array.isArray(node)
2201
+ ? Object.keys(node).filter(k => k.startsWith('--'))
2202
+ : [];
2203
+ /** A scope path as the file writes it (`adaptations.rules[0].value`). @param {string[]} path */
2204
+ const labelOf = path => path.join('.').replace(/\.(\d+)(?=\.|$)/g, '[$1]');
2205
+ /** The camelCase name of each CSS property, for a misspelled one. */
2206
+ const camelNames = () =>
2207
+ [...cssProperties()].map(p =>
2208
+ p.replace(/-([a-z])/g, (_m, c) => c.toUpperCase()),
2209
+ );
2210
+ /**
2211
+ * Judge one block of what a theme gives: its tokens and local tokens,
2212
+ * its parts, its onDark and onLight surfaces, and each adaptation rule's
2213
+ * value, which is a block too. A var() reads the custom properties the
2214
+ * block and the blocks around it set.
2215
+ * @param {any} block
2216
+ * @param {string[]} path where the block is, as the file writes it
2217
+ * @param {Set<string>} around custom properties the blocks around it set
2218
+ * @param {(scope: string, key: string) => {line: number | null, file: string | null}} where
2219
+ * @param {string} prefix what names a value of this theme in a refusal
2220
+ */
2221
+ const judgeBlock = (block, path, around, where, prefix) => {
2222
+ if (!block || typeof block !== 'object') return;
2223
+ const reads = new Set([
2224
+ ...around,
2225
+ ...varsIn(block.tokens),
2226
+ ...varsIn(block.localTokens),
2227
+ ]);
2228
+ /**
2229
+ * @param {string[]} at
2230
+ * @param {string} key
2231
+ * @param {string} why
2232
+ * @param {string} [value]
2233
+ */
2234
+ const refuse = (at, key, why, value = '') => {
2235
+ const scope = at.join('.');
2236
+ const label = labelOf(at);
2237
+ out.push({
2238
+ token: `${prefix}${label ? `${label} ` : ''}${key}`.trim(),
2239
+ value,
2240
+ why,
2241
+ ...(at.length || prefix ? where(scope, key) : whereOf(key)),
2242
+ });
2243
+ };
2244
+ /**
2245
+ * A custom property and its value, wherever a block sets one.
2246
+ * @param {string[]} at @param {string} k @param {unknown} v @param {Set<string>} here
2247
+ * @param {boolean} dropsUndefined
2248
+ */
2249
+ const token = (at, k, v, here, dropsUndefined) => {
2250
+ const loc = at.length || prefix ? where(at.join('.'), k) : whereOf(k);
2251
+ if (k.startsWith('--_'))
2252
+ return refuse(
2253
+ at,
2254
+ k,
2255
+ `${k} is a private variable (--_*), which Core sets itself, so the build refuses a theme that sets one: remove it`,
2256
+ );
2257
+ if (v === undefined) {
2258
+ if (!dropsUndefined)
2259
+ refuse(
2260
+ at,
2261
+ k,
2262
+ `${fileName(loc)} gives ${k} the value undefined here, which the build writes as the text undefined in this rule, where the browser drops it: remove the key to leave it unset`,
2263
+ );
2264
+ return;
2265
+ }
2266
+ if (!at.length && !prefix && named.has(k)) return;
2267
+ const why = judge(k, v, fileName(loc), here);
2268
+ if (why) refuse(at, k, why, asWritten(v));
2269
+ };
2270
+ for (const map of ['tokens', 'localTokens']) {
2271
+ const m = block[map];
2272
+ if (!m || typeof m !== 'object') continue;
2273
+ // A theme's own tokens map: the build drops an undefined token there,
2274
+ // and the exported theme's are named by token alone.
2275
+ const top = path.length === 0 && map === 'tokens';
2276
+ const at = top && !prefix ? [] : [...path, map];
2277
+ for (const [k, v] of Object.entries(m)) token(at, k, v, reads, top);
2278
+ }
2279
+ /** A part's style block. @param {any} node @param {string[]} at @param {Set<string>} outer @param {number} depth */
2280
+ const part = (node, at, outer, depth) => {
2281
+ if (!node || typeof node !== 'object' || depth > 12) return;
2282
+ const here = new Set([...outer, ...varsIn(node)]);
2283
+ for (const [k, v] of Object.entries(node)) {
2284
+ if (k.startsWith('--')) {
2285
+ token(at, k, v, here, false);
2286
+ continue;
2287
+ }
2288
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
2289
+ part(v, [...at, k], here, depth + 1);
2290
+ continue;
2291
+ }
2292
+ const prop = k.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
2293
+ // A vendor-prefixed property is the browser's own: Core checks
2294
+ // that the declaration stays one.
2295
+ if (/^-|^(webkit|moz|ms|o)-/.test(prop)) continue;
2296
+ const loc = where(at.join('.'), k);
2297
+ if (v === undefined) {
2298
+ refuse(
2299
+ at,
2300
+ prop,
2301
+ `${fileName(loc)} gives ${k} the value undefined here, which the build writes as the text undefined in this rule, where the browser drops it: remove the key to leave it unset`,
2302
+ );
2303
+ continue;
2304
+ }
2305
+ if (!cssProperties().has(prop)) {
2306
+ const near = nearest(k, camelNames())[0];
2307
+ refuse(
2308
+ at,
2309
+ k,
2310
+ `${k} is not a CSS property, so the build writes a declaration no browser reads${near ? `; did you mean ${near}?` : ''}`,
2311
+ );
2312
+ continue;
2313
+ }
2314
+ const why = judgeProperty(prop, v, fileName(loc), here);
2315
+ if (why) refuse(at, prop, why, typeof v === 'string' ? v : '');
2316
+ }
2317
+ };
2318
+ const components = block.components;
2319
+ if (components && typeof components === 'object')
2320
+ for (const [name, styles] of Object.entries(components))
2321
+ part(styles, [...path, 'components', name], reads, 0);
2322
+ for (const surface of ['onDark', 'onLight'])
2323
+ judgeBlock(block[surface], [...path, surface], reads, where, prefix);
2324
+ const rules = block.adaptations?.rules;
2325
+ if (Array.isArray(rules))
2326
+ rules.forEach((rule, i) =>
2327
+ judgeBlock(
2328
+ rule?.value,
2329
+ [...path, 'adaptations', 'rules', String(i), 'value'],
2330
+ reads,
2331
+ where,
2332
+ prefix,
2333
+ ),
2334
+ );
2335
+ };
2336
+ judgeBlock(input, [], new Set(), whereIn, '');
2337
+ // The custom properties the theme's own page sets, which a typography
2338
+ // token Core builds may read.
2339
+ const pageVars = new Set([
2340
+ ...varsIn(input.tokens),
2341
+ ...varsIn(input.localTokens),
2342
+ ]);
2343
+ // Every theme the exported one extends that this source defines (one
2344
+ // between the editor's settings and the export), judged the same way:
2345
+ // the build writes what each gives.
2346
+ for (const parent of loaded?.chain ?? []) {
2347
+ if (parent?.name === settingsThemeName(slug)) break;
2348
+ const theme = String(parent?.name ?? '');
2349
+ /** @param {string} _scope @param {string} key */
2350
+ const whereChain = (_scope, key) => {
2351
+ const e =
2352
+ entries.find(
2353
+ x => x.kind === 'chain' && x.theme === theme && x.token === key,
2354
+ ) ??
2355
+ entries.find(x => x.kind === 'chain' && x.theme === theme && !x.token);
2356
+ return e ? atOf(e) : {line: null, file: null};
2357
+ };
2358
+ judgeBlock(parent, [], new Set(), whereChain, `theme '${theme}' `);
2359
+ }
2360
+ // Typography: each field the source gives, as given, then each token
2361
+ // Core builds from it, named by the field that gives it.
2362
+ const typo = entries.filter(e => e.kind === 'typography');
2363
+ /** @type {Set<string>} */
2364
+ const flagged = new Set();
2365
+ /** @param {any} node @param {string[]} path */
2366
+ const fields = (node, path) => {
2367
+ if (!node || typeof node !== 'object') return;
2368
+ for (const [k, v] of Object.entries(node)) {
2369
+ const key = [...path, k].join('.');
2370
+ if (v === undefined) continue;
2371
+ if (v && typeof v === 'object' && !Array.isArray(v))
2372
+ fields(v, [...path, k]);
2373
+ else {
2374
+ const why = typographyProblem(key, v);
2375
+ if (!why) continue;
2376
+ const e = typo.find(x => x.key === key) ?? typo[0];
2377
+ flagged.add(key.split('.')[0]);
2378
+ out.push({
2379
+ token: `typography.${key}`,
2380
+ value: typeof v === 'string' ? v : '',
2381
+ why,
2382
+ ...(e ? atOf(e) : {line: null, file: null}),
2383
+ });
2384
+ }
2385
+ }
2386
+ };
2387
+ fields(input.typography, []);
2388
+ // Core writes a role's weight only from a type scale: without one, a
2389
+ // weight builds nothing.
2390
+ if (
2391
+ input.typography &&
2392
+ typeof input.typography === 'object' &&
2393
+ !input.typography.scale
2394
+ )
2395
+ for (const role of ['body', 'heading', 'code']) {
2396
+ const r = input.typography[role];
2397
+ if (!r || typeof r !== 'object' || flagged.has(role)) continue;
2398
+ for (const field of ['weight', 'weights']) {
2399
+ if (r[field] === undefined) continue;
2400
+ const key = `${role}.${field}`;
2401
+ const e =
2402
+ typo.find(x => x.key === key || x.key.startsWith(`${key}.`)) ??
2403
+ typo[0];
2404
+ out.push({
2405
+ token: `typography.${key}`,
2406
+ value: typeof r[field] === 'string' ? r[field] : '',
2407
+ why: `Core writes a role's weight only from a type scale, and this typography has none, so ${key} builds nothing: add scale: {base: 16, ratio: 1.2} beside it`,
2408
+ ...(e ? atOf(e) : {line: null, file: null}),
2409
+ });
2410
+ }
2411
+ }
2412
+ const scale = input.typography?.scale;
2413
+ if (
2414
+ scale &&
2415
+ typeof scale === 'object' &&
2416
+ scale.base === undefined &&
2417
+ !flagged.has('scale')
2418
+ ) {
2419
+ flagged.add('scale');
2420
+ const e = typo.find(x => x.key.startsWith('scale.')) ?? typo[0];
2421
+ out.push({
2422
+ token: 'typography.scale',
2423
+ value: '',
2424
+ why: 'the type scale is given no base, and Core reads the sizes from the base and the ratio together: add the body size in pixels, such as scale: {base: 16, ratio: …}',
2425
+ ...(e ? atOf(e) : {line: null, file: null}),
2426
+ });
2427
+ }
2428
+ const tokens = loaded?.theme?.tokens;
2429
+ if (input.typography && tokens && typeof tokens === 'object') {
2430
+ /** @param {string} role */
2431
+ const roleEntry = role =>
2432
+ typo.find(e => e.key.startsWith(`${role}.`)) ??
2433
+ (role === 'heading'
2434
+ ? typo.find(e => e.key.startsWith('body.'))
2435
+ : undefined);
2436
+ /** The typography field that gives a token Core builds. @param {string} token */
2437
+ const typographyOf = token => {
2438
+ const family = /^--font-family-([a-z]+)$/.exec(token)?.[1];
2439
+ if (family) return roleEntry(family) ?? null;
2440
+ if (!/^--(font-size|text|heading)-/.test(token)) return null;
2441
+ if (/-weight$/.test(token)) {
2442
+ const role = /heading/.test(token)
2443
+ ? 'heading'
2444
+ : /code/.test(token)
2445
+ ? 'code'
2446
+ : 'body';
2447
+ return (
2448
+ typo.find(
2449
+ e =>
2450
+ e.key === `${role}.weight` || e.key.startsWith(`${role}.weights`),
2451
+ ) ??
2452
+ roleEntry(role) ??
2453
+ typo.find(e => /weight/.test(e.key)) ??
2454
+ typo[0] ??
2455
+ null
2456
+ );
2457
+ }
2458
+ return typo.find(e => e.key.startsWith('scale.')) ?? typo[0] ?? null;
2459
+ };
2460
+ /** @type {Set<any>} */
2461
+ const reported = new Set();
2462
+ for (const [token, value] of Object.entries(tokens)) {
2463
+ if (!(token in known) || token in (input.tokens ?? {})) continue;
2464
+ const owner = typographyOf(token);
2465
+ if (!owner || reported.has(owner) || flagged.has(owner.key.split('.')[0]))
2466
+ continue;
2467
+ // A token Core leaves as the base theme writes it is the base's.
2468
+ if (loaded?.base.get(token) === value) continue;
2469
+ const at = atOf(owner);
2470
+ const why = judge(token, value, fileName(at), pageVars);
2471
+ if (why) {
2472
+ reported.add(owner);
2473
+ out.push({
2474
+ token: `typography.${owner.key} (builds ${token})`,
2475
+ value: asWritten(value),
2476
+ why,
2477
+ ...at,
2478
+ });
2479
+ }
2480
+ }
2481
+ }
2482
+ return out;
2483
+ }
2484
+
2485
+ /**
2486
+ * A type scale field as the number Core reads, or NaN: a number, or text
2487
+ * that is a number; any other value (a boolean, a symbol, an array) is no
2488
+ * number of pixels, whatever Number() would make of it.
2489
+ * @param {unknown} value
2490
+ */
2491
+ const scaleNumber = value =>
2492
+ typeof value === 'number'
2493
+ ? value
2494
+ : typeof value === 'string' && value.trim() !== ''
2495
+ ? Number(value)
2496
+ : NaN;
2497
+
2498
+ /**
2499
+ * What is wrong with one typography field of a theme's own source, or
2500
+ * null: a family is one family name without quotes (Core quotes it whole)
2501
+ * and with nothing CSS would read as the end of the value; the scale's
2502
+ * ratio is above 1 and at most 4, its base a positive number of pixels.
2503
+ * @param {string} key the dotted field (`body.family`, `scale.ratio`)
2504
+ * @param {unknown} value
2505
+ * @returns {string | null}
2506
+ */
2507
+ function typographyProblem(key, value) {
2508
+ const field = key.split('.').pop();
2509
+ // A weight is a CSS value Core writes as it is: text, never a number.
2510
+ if (
2511
+ (field === 'weight' || key.split('.').includes('weights')) &&
2512
+ typeof value !== 'string'
2513
+ )
2514
+ return `a typography weight is a CSS value in quotes, which Core writes as it is; ${describeValue(value)} is not text: write ${typeof value === 'number' ? `'${value}'` : "'600'"} (or a weight token, such as 'var(--font-weight-bold)')`;
2515
+ if (field === 'family') {
2516
+ if (typeof value !== 'string')
2517
+ return 'a typography family is a family name in quotes, such as "Inter"';
2518
+ const v = value.trim();
2519
+ if (/[;{}<>]/.test(v))
2520
+ return `"${v}" holds a ; { } < or >, so the CSS writer drops the whole declaration; give the family name alone, such as "Inter"`;
2521
+ const quoted = /^(["'])(.*)\1$/.exec(v);
2522
+ if (quoted)
2523
+ return `the family is written in quotes, and Core adds its own, so it builds ${JSON.stringify(`"${v}"`)}, a name no font has; write it without them: family: '${quoted[2]}'`;
2524
+ // Core quotes a family with a space whole, so a list here is one
2525
+ // family by that whole name, which exists nowhere.
2526
+ if (v.includes(','))
2527
+ return `a typography family is one family name, which Core quotes whole ("${v}" is one family that exists nowhere); give the first as family and the rest as fallbacks, such as family: '${v
2528
+ .split(',')[0]
2529
+ .trim()
2530
+ .replace(
2531
+ /^["']|["']$/g,
2532
+ '',
2533
+ )}', fallbacks: '${v.split(',').slice(1).join(',').trim()}'`;
2534
+ if (!v || /^[-+]?\d/.test(v) || /^(inherit|initial|unset|revert)$/i.test(v))
2535
+ return `"${v}" is no font family name; give one such as "Inter"`;
2536
+ return null;
2537
+ }
2538
+ if (field === 'ratio') {
2539
+ const n = scaleNumber(value);
2540
+ if (!Number.isFinite(n) || n <= 1 || n > 4)
2541
+ return `the type scale's ratio is how much each size grows over the last, a number above 1 and at most 4 (such as 1.2); ${describeValue(value)} makes ${n <= 0 ? 'sizes that are not numbers' : n <= 1 ? 'every size the same or smaller' : 'sizes no page can use'}`;
2542
+ return null;
2543
+ }
2544
+ if (field === 'base') {
2545
+ const n = scaleNumber(value);
2546
+ if (!Number.isFinite(n) || n <= 0) {
2547
+ // A size with a unit builds NaNrem: the number of pixels it means.
2548
+ const m = /^\s*([0-9.]+)\s*(px|rem|em)\s*$/i.exec(String(value));
2549
+ const px = m ? Number(m[1]) * (/^r?em$/i.test(m[2]) ? 16 : 1) : null;
2550
+ return `the type scale's base is the body size, a positive number of pixels${px ? `, so ${describeValue(value)} is base: ${px}` : ' (such as 16)'}; ${describeValue(value)} builds sizes no page can use${m ? ' (NaNrem)' : ''}`;
2551
+ }
2552
+ return null;
2553
+ }
2554
+ return null;
2555
+ }
2556
+
2557
+ /**
2558
+ * Refuse a theme whose own source gives a token a value `set` refuses: the
2559
+ * build would write it as it is (a browser drops it), so it is named, with
2560
+ * the line of the file, before anything is written.
2561
+ * @param {import('./_settings.mjs').Ctx} ctx
2562
+ * @param {string} slug
2563
+ * @param {import('./_settings.mjs').ThemeData} data
2564
+ */
2565
+ async function refuseOwnTokenValues(ctx, slug, data) {
2566
+ const err = await ownTokenRefusal(ctx, slug, data);
2567
+ if (err) throw err;
2568
+ }
2569
+ setOwnTokenCheck(refuseOwnTokenValues);
2570
+
2571
+ /**
2572
+ * The refusal for own-source token values `set` refuses, or null.
2573
+ * @param {import('./_settings.mjs').Ctx} ctx
2574
+ * @param {string} slug
2575
+ * @param {import('./_settings.mjs').ThemeData} data
2576
+ * @returns {Promise<AstryxError | null>}
2577
+ */
2578
+ async function ownTokenRefusal(ctx, slug, data) {
2579
+ const bad = await ownTokenProblems(ctx, slug, data);
2580
+ if (!bad.length) return null;
2581
+ const own = `themes/${slug}/${slug}.theme.ts`;
2582
+ const file = bad[0].file ?? own;
991
2583
  return new AstryxError(
992
- ownPairMessage(slug, names),
2584
+ `${own} gives ${bad.length === 1 ? 'a token a value' : `${bad.length} tokens values`} the editor refuses, which the build would write as it is: ${bad
2585
+ .slice(0, 3)
2586
+ .map(
2587
+ b =>
2588
+ `${b.token}${b.value ? `: "${b.value}"` : ''}${b.file ? ` (in ${b.file}${b.line ? `, line ${b.line}` : ''})` : b.line ? ` (line ${b.line})` : ''}: ${b.why.replace(/\.+$/, '')}`,
2589
+ )
2590
+ .join(
2591
+ '; ',
2592
+ )}${bad.length > 3 ? `; and ${bad.length - 3} more` : ''}. Change it in ${file}. Nothing was changed.`,
993
2593
  [
994
- {
995
- name: `grep -n -- ${quoteCommandArgument(names[0])} ${quoteCommandArgument(`themes/${slug}/${slug}.theme.ts`)}`,
996
- reason: 'see where the file sets it',
997
- },
2594
+ bad[0].line
2595
+ ? {
2596
+ name: `sed -n ${bad[0].line}p ${quoteCommandArgument(file)}`,
2597
+ reason: 'see the line that sets it',
2598
+ }
2599
+ : {
2600
+ name: `grep -n -- ${quoteCommandArgument(bad[0].token)} ${quoteCommandArgument(file)}`,
2601
+ reason: 'see the line',
2602
+ },
998
2603
  ],
999
2604
  ERROR_CODES.ERR_THEME_INVALID,
1000
2605
  );
1001
2606
  }
1002
2607
 
2608
+ /**
2609
+ * The refusal `compile` gives an editor theme whose own source gives a
2610
+ * token a value `set` refuses, or null.
2611
+ * @param {string} root
2612
+ * @param {string} slug
2613
+ * @returns {Promise<AstryxError | null>}
2614
+ */
2615
+ export async function editorOwnTokenRefusal(root, slug) {
2616
+ const ctx = await context(root);
2617
+ /** @type {import('./_settings.mjs').ThemeData} */
2618
+ let data;
2619
+ try {
2620
+ data = loadTheme(root, slug);
2621
+ } catch {
2622
+ return null;
2623
+ }
2624
+ return ownTokenRefusal(ctx, slug, data);
2625
+ }
2626
+
1003
2627
  /**
1004
2628
  * A note for type scale steps that land outside 9 to 200 pixels.
1005
2629
  * @param {Record<string, string>} res resolved light tokens
1006
2630
  * @returns {string[]}
1007
2631
  */
1008
- function extremeSteps(res) {
1009
- const out = Object.entries(res)
1010
- .filter(([k]) => /^--font-size-/.test(k))
1011
- .map(([k, v]) => {
1012
- const n = Number.parseFloat(v);
1013
- return /** @type {[string, number]} */ ([k, /rem$/.test(v) ? n * 16 : n]);
1014
- })
1015
- .filter(([, px]) => Number.isFinite(px) && (px < 9 || px > 200))
1016
- .map(([k, px]) => `${k} ${Math.round(px)}px`);
1017
- return out.length
1018
- ? [
1019
- `some scale steps are outside reading sizes (9 to 200px): ${out.slice(0, 4).join(', ')}`,
1020
- ]
1021
- : [];
2632
+ function extremeSteps(res) {
2633
+ const out = Object.entries(res)
2634
+ .filter(([k]) => /^--font-size-/.test(k))
2635
+ .map(([k, v]) => {
2636
+ const n = Number.parseFloat(v);
2637
+ return /** @type {[string, number]} */ ([k, /rem$/.test(v) ? n * 16 : n]);
2638
+ })
2639
+ .filter(([, px]) => Number.isFinite(px) && (px < 9 || px > 200))
2640
+ .map(([k, px]) => `${k} ${Math.round(px)}px`);
2641
+ return out.length
2642
+ ? [
2643
+ `some scale steps are outside reading sizes (9 to 200px): ${out.slice(0, 4).join(', ')}`,
2644
+ ]
2645
+ : [];
2646
+ }
2647
+
2648
+ /**
2649
+ * An object of settings written as JSON, with single quotes, or as its
2650
+ * entries with no braces (`"accent": "#e11d48", "corners": "pill"`).
2651
+ * Throws when it is none of these.
2652
+ * @param {string} text
2653
+ * @returns {any}
2654
+ */
2655
+ function looseObject(text) {
2656
+ const t = text.trim();
2657
+ const braced = t.startsWith('{') ? t : `{${t}}`;
2658
+ try {
2659
+ return JSON.parse(braced);
2660
+ } catch {
2661
+ return JSON.parse(
2662
+ braced.replace(/'((?:[^'\\]|\\.)*)'/g, (_, x) =>
2663
+ JSON.stringify(x.replace(/\\'/g, "'")),
2664
+ ),
2665
+ );
2666
+ }
2667
+ }
2668
+
2669
+ /**
2670
+ * A refusal with each line that sets the typed setting again kept only
2671
+ * when it carries the value typed; with none left, `how` for the setting.
2672
+ * Another setting's line, an undo or a look stays.
2673
+ * @param {any} e
2674
+ * @param {'set' | 'undo'} sub
2675
+ * @param {string} slug
2676
+ * @param {string} thing
2677
+ * @param {unknown} typed
2678
+ * @param {import('./_settings.mjs').ThemeData} [data] the theme, whose saved
2679
+ * values a keep line may carry
2680
+ */
2681
+ function carryTyped(e, sub, slug, thing, typed, data, cwd = process.cwd()) {
2682
+ if (
2683
+ sub !== 'set' ||
2684
+ !(e instanceof AstryxError) ||
2685
+ // A refusal about what the settings file holds: its lines carry the
2686
+ // saved value (checked where they are made), not the typed one.
2687
+ /** @type {any} */ (e).aboutSaved ||
2688
+ typeof typed !== 'string' ||
2689
+ !e.suggestions?.length
2690
+ )
2691
+ return e;
2692
+ const head = new RegExp(
2693
+ `^.* set \\S+ (?:'([^']+)'|(\\S+)) (?:'((?:[^']|'\\\\'')*)'|(\\S+))`,
2694
+ );
2695
+ // Every set line, of this setting or another (a dial's other name, a
2696
+ // label, a theme-wide equivalent), offers a value only through the gate's
2697
+ // declared sources (readsTyped): never a stock, reset or nearest value.
2698
+ // A line that carries only part of the value is offered only when the
2699
+ // refusal's lines together carry all of it (a family and its weight).
2700
+ // With no value typed, the thing held it (`accent: red`).
2701
+ const typedText = typed.trim() ? typed : String(thing);
2702
+ /** @type {Map<string, string[]>} */
2703
+ const saved = new Map();
2704
+ for (const x of data?.settings ?? [])
2705
+ saved.set(x.thing, [...(saved.get(x.thing) ?? []), String(x.value ?? '')]);
2706
+ // The base the theme was built on is a saved value of its base too (the
2707
+ // module's header holds it when the file's base is damaged).
2708
+ const builtOn = builtOnBase(cwd, slug);
2709
+ saved.set(
2710
+ 'base',
2711
+ /** @type {string[]} */ (
2712
+ [data?.like, builtOn].filter(b => typeof b === 'string' && b !== '')
2713
+ ),
2714
+ );
2715
+ if (data?.mode) saved.set('mode', [data.mode]);
2716
+ const reads = e.suggestions.map(x => {
2717
+ const m = head.exec(x.name);
2718
+ if (!m) return /** @type {true | number[] | false} */ (true);
2719
+ return readsTyped({
2720
+ offered: m[3] ?? m[4],
2721
+ typed: typedText,
2722
+ thing: (m[1] ?? m[2]).replace(/^'(.*)'$/, '$1'),
2723
+ typedThing: String(thing),
2724
+ saved,
2725
+ mode: / --mode (light|dark)\b/.exec(x.name)?.[1] ?? '',
2726
+ });
2727
+ });
2728
+ const covered = coversTyped(reads, typedText, String(thing));
2729
+ /** @type {Set<string>} */
2730
+ const dropped = new Set();
2731
+ const lines = e.suggestions.filter((x, i) => {
2732
+ const read = reads[i];
2733
+ if (read === true || (read && typeof read === 'object' && covered))
2734
+ return true;
2735
+ const m = head.exec(x.name);
2736
+ if (m) dropped.add(String(m[3] ?? m[4]).toLowerCase());
2737
+ return false;
2738
+ });
2739
+ // A value named as a did-you-mean goes with its line.
2740
+ const kept = lines.filter(
2741
+ x => !(x.reason === 'did you mean' && dropped.has(x.name.toLowerCase())),
2742
+ );
2743
+ // A refusal always names a command that works: with no set, undo, new or
2744
+ // how line left, how for the setting.
2745
+ const runnable = kept.some(
2746
+ x => x.reason !== 'did you mean' && !/ --help$/.test(x.name),
2747
+ );
2748
+ if (kept.length === e.suggestions.length && runnable) return e;
2749
+ e.suggestions = runnable
2750
+ ? kept
2751
+ : [
2752
+ ...kept.filter(x => !/ --help$/.test(x.name)),
2753
+ {
2754
+ name: `${P} how ${quoteCommandArgument(String(thing))}`,
2755
+ reason: 'what it takes',
2756
+ },
2757
+ ];
2758
+ return e;
2759
+ }
2760
+
2761
+ /**
2762
+ * A theme's settings file as written, for the values a keep line may carry
2763
+ * when the theme does not load (a damaged entry); null when it cannot be
2764
+ * read.
2765
+ * @param {string} cwd
2766
+ * @param {string} slug
2767
+ * @returns {import('./_settings.mjs').ThemeData | undefined}
2768
+ */
2769
+ function savedAsWritten(cwd, slug) {
2770
+ try {
2771
+ const data = settingsJson(
2772
+ fs.readFileSync(themeFiles(cwd, slug).settings, 'utf8'),
2773
+ );
2774
+ return entriesReadable(data) ? data : undefined;
2775
+ } catch {
2776
+ return undefined;
2777
+ }
2778
+ }
2779
+
2780
+ /**
2781
+ * A refusal of the settings file (a setting listed twice, a damaged
2782
+ * entry) with every `set` it suggests checked as set checks it, against
2783
+ * the file as written: a keep line whose value set refuses is dropped.
2784
+ * @param {unknown} e
2785
+ * @param {string} cwd
2786
+ * @param {string} slug
2787
+ * @returns {Promise<unknown>}
2788
+ */
2789
+ async function vetLoadRefusal(e, cwd, slug) {
2790
+ if (!(e instanceof AstryxError) || e.code !== E.ERR_THEME_INVALID) return e;
2791
+ const data = savedAsWritten(cwd, slug);
2792
+ if (!data) return e;
2793
+ try {
2794
+ const ctx = /** @type {import('./_settings.mjs').Ctx} */ (
2795
+ await context(cwd)
2796
+ );
2797
+ ctx.base = await baseResolved(ctx.project, data.like ?? undefined);
2798
+ return vetSuggestions(e, ctx, slug, data);
2799
+ } catch {
2800
+ return e;
2801
+ }
2802
+ }
2803
+
2804
+ /**
2805
+ * The lines of a repair that work: each run through set's own check (in
2806
+ * memory) and offered only when set takes it as offered and its value
2807
+ * passes the allowlist of exact readings of what was typed. A line left
2808
+ * out that names its own setting points to how for it; with no line left,
2809
+ * how for the thing (or the command's help when there is no one thing).
2810
+ * @param {'set' | 'undo'} sub
2811
+ * @param {string} slug
2812
+ * @param {Array<string | [string, string] | [string, string, string]>} lines
2813
+ * each line, or each line with the typed text it carries (and, for an
2814
+ * entry of a pasted object, its setting)
2815
+ * @param {string} cwd
2816
+ * @param {string} typed
2817
+ * @param {string} thing
2818
+ * @returns {Promise<string[]>}
2819
+ */
2820
+ async function workingLines(sub, slug, lines, cwd, typed, thing) {
2821
+ /** @type {string[]} */
2822
+ const out = [];
2823
+ for (const item of lines) {
2824
+ const [line, own, subject] = Array.isArray(item)
2825
+ ? item
2826
+ : [item, typed, undefined];
2827
+ // A line left out points to how for its own setting, when it names one
2828
+ // (an entry of a pasted object).
2829
+ const left = () => {
2830
+ if (subject) out.push(`${P} how ${quoteCommandArgument(subject)}`);
2831
+ };
2832
+ // The line as set takes it (a repair set offers for it folded in).
2833
+ const followed = await followChangeLine(sub, slug, line, cwd);
2834
+ if (followed.why) {
2835
+ left();
2836
+ continue;
2837
+ }
2838
+ const read = readSetLine(followed.line, slug);
2839
+ if (
2840
+ sub === 'set' &&
2841
+ read &&
2842
+ !allowedLine({
2843
+ offered: read.value,
2844
+ typed: own,
2845
+ thing: read.thing,
2846
+ mode: String(read.flags?.mode ?? ''),
2847
+ })
2848
+ ) {
2849
+ left();
2850
+ continue;
2851
+ }
2852
+ out.push(followed.line);
2853
+ }
2854
+ return out.length
2855
+ ? [...new Set(out)]
2856
+ : [
2857
+ thing
2858
+ ? `${P} how ${quoteCommandArgument(thing)}`
2859
+ : `${P} ${sub} --help`,
2860
+ ];
2861
+ }
2862
+
2863
+ /**
2864
+ * A `set` or `undo` line for the theme a path or other letters named, run
2865
+ * through that command's own check (in memory, nothing written). Each
2866
+ * repair a refusal of it offers is folded into the one line, so the line
2867
+ * runs as offered; `why` names what is still refused when no repair is
2868
+ * offered.
2869
+ * @param {'set' | 'undo'} sub
2870
+ * @param {string} slug
2871
+ * @param {string} line
2872
+ * @param {string} cwd
2873
+ * @param {Partial<import('./_settings.mjs').Setting>} [skip] a saved entry
2874
+ * the line replaces, whose value is not checked when the theme is read
2875
+ * @returns {Promise<{line: string, why: string | null, next?: import("../../foundation/response/base").Suggestion[]}>}
2876
+ */
2877
+ async function followChangeLine(sub, slug, line, cwd, skip) {
2878
+ const loaded = await loadedForCheck(cwd, slug, skip);
2879
+ if (!loaded) return {line, why: null};
2880
+ const {data, ctx} = loaded;
2881
+ return followLine(
2882
+ line,
2883
+ now => {
2884
+ const read = readSetLine(
2885
+ sub === 'undo' ? now.replace(`${P} undo `, `${P} set `) : now,
2886
+ slug,
2887
+ );
2888
+ if (!read) return null;
2889
+ try {
2890
+ const s = checkSetting(
2891
+ ctx,
2892
+ slug,
2893
+ structuredClone(data),
2894
+ read.thing,
2895
+ read.value,
2896
+ read.flags,
2897
+ sub === 'undo',
2898
+ );
2899
+ return sub === 'undo' && !data.settings.some(x => keyOf(x) === keyOf(s))
2900
+ ? new AstryxError(
2901
+ `${slug} does not set ${describe({...s, value: '?'}).replace(' = ?', '')}`,
2902
+ [{name: `${P} show ${slug}`, reason: 'see what it sets'}],
2903
+ )
2904
+ : null;
2905
+ } catch (e) {
2906
+ if (e instanceof AstryxError) return e;
2907
+ throw e;
2908
+ }
2909
+ },
2910
+ name => repairGate(sub, slug, line, name),
2911
+ );
2912
+ }
2913
+
2914
+ /**
2915
+ * The record of the last change command refused for a theme, kept in the
2916
+ * project's theme cache: the command and when it was refused.
2917
+ * @param {string} cwd
2918
+ * @param {string} slug
2919
+ */
2920
+ const refusedFile = (cwd, slug) => {
2921
+ const root = themeCacheRoot(cwd);
2922
+ return root ? path.join(root, 'refused', `${slug}.json`) : null;
2923
+ };
2924
+
2925
+ /**
2926
+ * Note a change command refused for a theme that exists, so a later undo
2927
+ * can say the refused command changed nothing. Best effort: a cache that
2928
+ * cannot be written leaves the note out.
2929
+ * @param {string} cwd
2930
+ * @param {string} slug
2931
+ * @param {string} command the command as typed, after the CLI name
2932
+ */
2933
+ function noteRefused(cwd, slug, command) {
2934
+ try {
2935
+ if (!slugOk(slug) || !fs.existsSync(themeFiles(cwd, slug).settings)) return;
2936
+ const file = refusedFile(cwd, slug);
2937
+ if (!file) return;
2938
+ fs.mkdirSync(path.dirname(file), {recursive: true});
2939
+ fs.writeFileSync(file, JSON.stringify({at: Date.now(), command}));
2940
+ } catch {
2941
+ // No note.
2942
+ }
2943
+ }
2944
+
2945
+ /**
2946
+ * The change command refused for a theme since its last change (the
2947
+ * history's last write), or null.
2948
+ * @param {string} cwd
2949
+ * @param {string} slug
2950
+ * @param {string} history the theme's history file
2951
+ * @returns {string | null}
2952
+ */
2953
+ function refusedAfter(cwd, slug, history) {
2954
+ try {
2955
+ const file = refusedFile(cwd, slug);
2956
+ if (!file) return null;
2957
+ const note = JSON.parse(fs.readFileSync(file, 'utf8'));
2958
+ return typeof note?.command === 'string' &&
2959
+ typeof note.at === 'number' &&
2960
+ note.at > fs.statSync(history).mtimeMs
2961
+ ? note.command
2962
+ : null;
2963
+ } catch {
2964
+ return null;
2965
+ }
1022
2966
  }
1023
2967
 
1024
2968
  /**
@@ -1033,21 +2977,218 @@ async function change(sub, slug, thing, value, options) {
1033
2977
  // As typed: an undo of a saved entry written in a form the cleanup below
1034
2978
  // repairs (`Corners`, `var(--radius-page)`) removes that exact entry.
1035
2979
  const typedThing = thing;
2980
+ const typedValue = value;
2981
+ // An object of several settings pasted as one (JSON, single quotes, or
2982
+ // its entries with no braces, split at the first colon on the way): one
2983
+ // set line each.
2984
+ const objectText =
2985
+ typeof thing !== 'string'
2986
+ ? null
2987
+ : value == null || value === ''
2988
+ ? /^\s*\{[\s\S]*\}\s*$/.test(thing)
2989
+ ? thing
2990
+ : null
2991
+ : /^\s*\{?\s*["']/.test(thing) && /["']\s*:/.test(String(value))
2992
+ ? `${thing}:${value}`
2993
+ : null;
2994
+ // A pasted object of one entry is that entry, as read below: its repair
2995
+ // carries the entry's value, and how names its setting.
2996
+ let oneEntry = false;
2997
+ if (objectText != null) {
2998
+ /** @type {any} */
2999
+ let obj = null;
3000
+ try {
3001
+ obj = looseObject(objectText);
3002
+ } catch {
3003
+ // Not an object: read as typed.
3004
+ }
3005
+ oneEntry = Boolean(
3006
+ obj && typeof obj === 'object' && Object.keys(obj).length === 1,
3007
+ );
3008
+ if (obj && typeof obj === 'object' && Object.keys(obj).length > 1)
3009
+ refuse(
3010
+ E.ERR_INVALID_ARGUMENT,
3011
+ `This holds ${Object.keys(obj).length} settings; ${sub} changes one at a time.`,
3012
+ {
3013
+ // Each entry as its own line, a nested value (`{"$value": …}`, a
3014
+ // light and dark pair) written back as typed; each line checked,
3015
+ // and one set refuses is left out.
3016
+ run: await workingLines(
3017
+ sub,
3018
+ slug,
3019
+ Object.entries(obj)
3020
+ .slice(0, 6)
3021
+ .map(([k, x]) => {
3022
+ const entry =
3023
+ x != null && typeof x === 'object'
3024
+ ? JSON.stringify(x)
3025
+ : String(x);
3026
+ const read = String(normalizeEntry(k, entry).value ?? '');
3027
+ // Each line with the entry it carries, as typed.
3028
+ return /** @type {[string, string, string]} */ ([
3029
+ `${P} ${sub} ${slug} ${quoteCommandArgument(k)}${sub === 'set' ? ` ${quoteCommandArgument(read)}` : ''}`,
3030
+ read,
3031
+ k,
3032
+ ]);
3033
+ }),
3034
+ options.cwd ?? process.cwd(),
3035
+ objectText,
3036
+ // No one setting: each entry left out points to how for its
3037
+ // own (above), else set's help.
3038
+ '',
3039
+ ),
3040
+ },
3041
+ );
3042
+ }
3043
+ // A flag typed inside the value (`'red --mode dark'`, `'4px --state
3044
+ // hover'`, `'pill --on button'`): the same command with the flag lifted
3045
+ // out, never the value alone, which would change another scope.
3046
+ if (typeof value === 'string' && /\s--(mode|state|on|when)\b/.test(value)) {
3047
+ /** @type {Record<string, string>} */
3048
+ const lifted = {};
3049
+ // The rest is cleaned as any value is (a trailing `;`, `!important`,
3050
+ // a comment).
3051
+ const bare = withoutCopyDebris(
3052
+ value.replace(
3053
+ /\s+--(mode|state|on|when)(?:\s*=\s*|\s+)("[^"]*"|'[^']*'|\S+)/g,
3054
+ (_, f, x) => {
3055
+ lifted[f] = x.replace(/^(["'])(.*)\1$/, '$2');
3056
+ return '';
3057
+ },
3058
+ ),
3059
+ );
3060
+ if (bare && Object.keys(lifted).length) {
3061
+ const opts = /** @type {Record<string, unknown>} */ ({
3062
+ ...options,
3063
+ ...lifted,
3064
+ });
3065
+ const flagText = ['on', 'when', 'state', 'mode']
3066
+ .filter(f => opts[f])
3067
+ .map(f => ` --${f} ${quoteCommandArgument(String(opts[f]))}`)
3068
+ .join('');
3069
+ refuse(
3070
+ E.ERR_INVALID_ARGUMENT,
3071
+ `"${value}" holds ${Object.keys(lifted)
3072
+ .map(f => `--${f}`)
3073
+ .join(' and ')} inside the value; a flag goes outside the quotes.`,
3074
+ {
3075
+ // The line is checked as set checks it; one set refuses is left
3076
+ // out, and how is named instead.
3077
+ run: await workingLines(
3078
+ sub,
3079
+ slug,
3080
+ [
3081
+ `${P} ${sub} ${slug} ${quoteCommandArgument(String(thing))}${sub === 'set' ? ` ${quoteCommandArgument(bare)}` : ''}${flagText}${options.only ? ' --only' : ''}`,
3082
+ ],
3083
+ options.cwd ?? process.cwd(),
3084
+ value,
3085
+ String(thing),
3086
+ ),
3087
+ },
3088
+ );
3089
+ }
3090
+ }
1036
3091
  // How it was typed, put right before anything reads it (a pasted
1037
3092
  // declaration, a dash, a var(), invisible spaces).
3093
+ /** @type {string | undefined} */
3094
+ let dropped;
1038
3095
  if (typeof thing === 'string') {
1039
3096
  const entry = normalizeEntry(thing, value);
1040
3097
  thing = entry.thing;
1041
3098
  value = entry.value;
3099
+ dropped = entry.dropped;
1042
3100
  }
1043
3101
  /** @type {{ctx?: import('./_settings.mjs').Ctx, data?: import('./_settings.mjs').ThemeData}} */
1044
3102
  const seen = {};
1045
3103
  try {
1046
- return await changeOnce(sub, slug, thing, value, options, seen, typedThing);
3104
+ const r = await changeOnce(
3105
+ sub,
3106
+ slug,
3107
+ thing,
3108
+ value,
3109
+ options,
3110
+ seen,
3111
+ typedThing,
3112
+ );
3113
+ // A second declaration pasted after the first is not set: said, with
3114
+ // its own set line.
3115
+ if (dropped && sub === 'set') {
3116
+ const m = /^([^:]+):\s*(.*?);?\s*$/.exec(dropped);
3117
+ const flags = [
3118
+ ...(options.on ? [`--on ${options.on}`] : []),
3119
+ ...(options.when ? [`--when ${options.when}`] : []),
3120
+ ...(options.state ? [`--state ${options.state}`] : []),
3121
+ ].join(' ');
3122
+ // Its line goes through the one gate as a repair does: checked as set
3123
+ // checks it (a repair set offers for it folded in) and carrying what
3124
+ // was pasted; else no line is named.
3125
+ const [line] = m
3126
+ ? await workingLines(
3127
+ 'set',
3128
+ slug,
3129
+ [
3130
+ `${P} set ${slug} ${quoteCommandArgument(m[1].trim())} ${quoteCommandArgument(m[2].trim())}${flags ? ` ${flags}` : ''}`,
3131
+ ],
3132
+ options.cwd ?? process.cwd(),
3133
+ m[2].trim(),
3134
+ m[1].trim(),
3135
+ )
3136
+ : [];
3137
+ /** @type {any} */ (r.data).notes = [
3138
+ ...(r.data.notes ?? []),
3139
+ `the pasted text also held "${dropped}", which this did not set${line && / set /.test(line) ? `: ${line} sets it` : ''}`,
3140
+ ];
3141
+ }
3142
+ // A mode or base entry in the settings list does nothing: said after
3143
+ // every change, with the undo that removes it.
3144
+ if (seen.ctx && r.data.theme) {
3145
+ /** @type {import('./_settings.mjs').ThemeData | null} */
3146
+ let now = null;
3147
+ try {
3148
+ now = loadTheme(seen.ctx.project.cwd, r.data.theme);
3149
+ } catch {
3150
+ now = null;
3151
+ }
3152
+ const left = now ? misplacedNotes(r.data.theme, now) : [];
3153
+ if (left.length)
3154
+ /** @type {any} */ (r.data).notes = [...left, ...(r.data.notes ?? [])];
3155
+ }
3156
+ return r;
1047
3157
  } catch (e) {
1048
- // A theme name one letter off an existing theme: the same command with
1049
- // that name comes first, before making a theme of the typo.
1050
- if (e instanceof AstryxError && e.code === E.ERR_UNKNOWN_THEME) {
3158
+ // A refused change changed nothing: noted, for a later undo to say so.
3159
+ if (e instanceof AstryxError)
3160
+ noteRefused(
3161
+ options.cwd ?? process.cwd(),
3162
+ slug,
3163
+ [
3164
+ `${P.replace(/^astryx /, '')} ${sub} ${slug}`,
3165
+ ...[typedThing, typedValue]
3166
+ .filter(w => w != null && w !== '')
3167
+ .map(w => quoteCommandArgument(String(w))),
3168
+ ...(options.on ? [`--on ${options.on}`] : []),
3169
+ ...(options.when ? [`--when ${options.when}`] : []),
3170
+ ...(options.state ? [`--state ${options.state}`] : []),
3171
+ ...(options.mode ? [`--mode ${options.mode}`] : []),
3172
+ ...(options.only ? ['--only'] : []),
3173
+ ].join(' '),
3174
+ );
3175
+ // A theme name one letter off an existing theme, or typed in other
3176
+ // letters or as a path (T, ./t, themes/t): the same command with that
3177
+ // name comes first, never a bare look at the theme that drops the change.
3178
+ const named =
3179
+ e instanceof AstryxError &&
3180
+ (e.code === E.ERR_UNKNOWN_THEME ||
3181
+ (e.code === E.ERR_INVALID_ARGUMENT &&
3182
+ (e.suggestions ?? []).some(
3183
+ x =>
3184
+ x.reason === 'did you mean' &&
3185
+ slugOk(x.name) &&
3186
+ x.name !== slug &&
3187
+ fs.existsSync(
3188
+ themeFiles(options.cwd ?? process.cwd(), x.name).settings,
3189
+ ),
3190
+ )));
3191
+ if (named) {
1051
3192
  const near = (e.suggestions ?? []).find(x => x.reason === 'did you mean');
1052
3193
  if (near && slugOk(near.name)) {
1053
3194
  const flags = [
@@ -1062,18 +3203,47 @@ async function change(sub, slug, thing, value, options) {
1062
3203
  .map(w =>
1063
3204
  String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
1064
3205
  );
3206
+ const followed = await followChangeLine(
3207
+ sub,
3208
+ near.name,
3209
+ `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
3210
+ options.cwd ?? process.cwd(),
3211
+ );
1065
3212
  e.suggestions = [
1066
3213
  {
1067
- name: `${P} ${sub} ${near.name}${words.length ? ` ${words.join(' ')}` : ''}`,
1068
- reason: `do this instead: ${near.name} is a theme here`,
3214
+ name: followed.line,
3215
+ reason: `do this instead: ${near.name} is a theme here${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
1069
3216
  },
1070
- ...(e.suggestions ?? []).filter(x => x !== near),
3217
+ ...(e.suggestions ?? []).filter(
3218
+ x => x !== near && x.name !== `${P} show ${near.name}`,
3219
+ ),
1071
3220
  ];
1072
3221
  }
1073
3222
  throw e;
1074
3223
  }
1075
- // Every `set` the refusal suggests is checked as `set` checks it.
1076
- throw vetSuggestions(e, seen.ctx, slug, seen.data);
3224
+ // Every `set` the refusal suggests is checked as `set` checks it, and
3225
+ // carries the value typed (cleaned), never a stock value.
3226
+ throw misplacedFirst(
3227
+ carryTyped(
3228
+ // A refusal of a saved entry gets set's repair for its value
3229
+ // beside the undo.
3230
+ await withSavedRepair(
3231
+ seen.ctx
3232
+ ? vetSuggestions(e, seen.ctx, slug, seen.data)
3233
+ : await vetLoadRefusal(e, options.cwd ?? process.cwd(), slug),
3234
+ slug,
3235
+ options.cwd ?? process.cwd(),
3236
+ ),
3237
+ sub,
3238
+ slug,
3239
+ oneEntry ? thing : typedThing,
3240
+ oneEntry ? value : typedValue,
3241
+ seen.data ?? savedAsWritten(options.cwd ?? process.cwd(), slug),
3242
+ options.cwd ?? process.cwd(),
3243
+ ),
3244
+ seen.data?.name ?? slug,
3245
+ seen.data,
3246
+ );
1077
3247
  }
1078
3248
  }
1079
3249
 
@@ -1107,29 +3277,33 @@ async function changeOnce(
1107
3277
  when: options.when,
1108
3278
  state: options.state,
1109
3279
  mode: options.mode,
3280
+ // An undo removes the entry it names even when that entry's mode or
3281
+ // source means nothing.
3282
+ ...(sub === 'undo' ? {removing: true} : {}),
1110
3283
  });
1111
- const data = loadTheme(cwd, slug, target);
1112
- /** @type {string[]} */
1113
- const fieldNotes = [];
1114
- if (sub === 'set' && (thing === 'base' || thing === 'mode')) {
1115
- // The other field, when it is damaged too, goes back to its default,
1116
- // so the theme loads again.
1117
- if (
1118
- thing !== 'mode' &&
1119
- !['both', 'light-only', 'dark-only'].includes(data.mode)
1120
- ) {
1121
- data.mode = 'both';
1122
- fieldNotes.push('mode was missing or damaged, so it is both again');
1123
- }
1124
- if (thing !== 'base' && data.like != null && !LIKE.includes(data.like)) {
1125
- delete data.like;
1126
- fieldNotes.push('base was not a built-in theme, so it is none again');
1127
- }
3284
+ /** @type {import('./_settings.mjs').ThemeData} */
3285
+ let data;
3286
+ try {
3287
+ data = loadTheme(cwd, slug, target);
3288
+ } catch (e) {
3289
+ throw await withSavedRepair(e, slug, cwd);
1128
3290
  }
3291
+ /** @type {string[]} */
3292
+ // A damaged mode or base the command does not set itself is read as
3293
+ // meant, or goes back to its default, so the theme loads again.
3294
+ const fieldNotes = [
3295
+ ...entryNotes(data),
3296
+ ...readFields(
3297
+ data,
3298
+ cwd,
3299
+ thing === 'mode' || thing === 'base' ? thing : undefined,
3300
+ slug,
3301
+ ),
3302
+ ];
1129
3303
  const ctx = await context(cwd);
1130
3304
  // An undo of one setting only removes it, so it never waits on the
1131
3305
  // others being fixed.
1132
- if (sub !== 'undo')
3306
+ if (sub !== 'undo') {
1133
3307
  refuseStoredTokens(ctx, slug, data, {
1134
3308
  thing,
1135
3309
  on: options.on,
@@ -1137,6 +3311,7 @@ async function changeOnce(
1137
3311
  state: options.state,
1138
3312
  mode: options.mode,
1139
3313
  });
3314
+ }
1140
3315
  const flags = {
1141
3316
  on: options.on,
1142
3317
  when: options.when,
@@ -1175,8 +3350,25 @@ async function changeOnce(
1175
3350
  Boolean(x.only) === Boolean(flags.only),
1176
3351
  )
1177
3352
  : -1;
1178
- let rawIdx = -1;
1179
- if (exactIdx >= 0) {
3353
+ // An entry of this name whose mode or source means nothing is the one an
3354
+ // undo removes: only that entry, never a valid one beside it.
3355
+ const damagedIdx =
3356
+ sub === 'undo'
3357
+ ? data.settings.findIndex(
3358
+ x =>
3359
+ (x.thing === typedThing || x.thing === thing) &&
3360
+ (x.on ?? null) === (flags.on ?? null) &&
3361
+ (x.when ?? null) === (flags.when ?? null) &&
3362
+ (x.state ?? null) === (flags.state ?? null) &&
3363
+ (entryDamage(x) === 'only' ||
3364
+ Boolean(x.only) === Boolean(flags.only)) &&
3365
+ (entryDamage(x) === 'source' || entryDamage(x) === 'only'
3366
+ ? (x.mode ?? null) === (flags.mode ?? null)
3367
+ : entryDamage(x) === 'mode' && !flags.mode),
3368
+ )
3369
+ : -1;
3370
+ let rawIdx = damagedIdx;
3371
+ if (exactIdx >= 0 && rawIdx < 0) {
1180
3372
  // Only an entry the editor would not save as written: one it refuses,
1181
3373
  // or reads as another name, part or state.
1182
3374
  const entry = data.settings[exactIdx];
@@ -1282,12 +3474,29 @@ async function changeOnce(
1282
3474
  ...data.settings.map(x => x.thing.toLowerCase()),
1283
3475
  ]).length > 0;
1284
3476
  const steps = readHistory(themeFiles(cwd, slug).history).steps.length;
3477
+ // The setting whose scope is the one typed (no --on: the whole
3478
+ // theme's) leads; with none of that scope, the message says so and
3479
+ // the others are listed after it.
3480
+ const sameScope = (/** @type {any} */ x) =>
3481
+ (x.on ?? null) === (flags.on ?? null) &&
3482
+ (x.when ?? null) === (flags.when ?? null) &&
3483
+ (x.state ?? null) === (flags.state ?? null) &&
3484
+ (x.mode ?? null) === (flags.mode ?? null);
3485
+ const ordered = [
3486
+ ...matches.filter(sameScope),
3487
+ ...matches.filter(x => !sameScope(x)),
3488
+ ];
3489
+ const scoped = flags.on || flags.when || flags.state || flags.mode;
1285
3490
  throw new AstryxError(
1286
- e.message,
3491
+ matches.length && !matches.some(sameScope) && scoped
3492
+ ? `${e.message.replace(/\s*Nothing was changed\.$/, '')} ${slug} sets ${matches[0].thing} only where these lines name. Nothing was changed.`
3493
+ : e.message,
1287
3494
  matches.length
1288
- ? matches.slice(0, 5).map(x => ({
3495
+ ? ordered.slice(0, 5).map(x => ({
1289
3496
  name: `${P} undo ${slug} ${undoArgs(x)}`,
1290
- reason: 'do this instead',
3497
+ reason: sameScope(x)
3498
+ ? 'do this instead'
3499
+ : `do this instead: ${describe({...x, value: '?'}).replace(' = ?', '')}`,
1291
3500
  }))
1292
3501
  : [
1293
3502
  steps && !nearSetting
@@ -1341,6 +3550,9 @@ async function changeOnce(
1341
3550
  );
1342
3551
  }
1343
3552
  const compiledBefore = compileTheme(ctx, data, base);
3553
+ // The build notes the theme had before this change: only new ones are
3554
+ // this change's to report.
3555
+ const notesBefore = new Set(buildNotes(ctx));
1344
3556
  if (sub === 'set' && (s.thing === 'base' || s.thing === 'mode')) {
1345
3557
  const before = s.thing === 'base' ? (data.like ?? 'none') : data.mode;
1346
3558
  if (s.thing === 'base') {
@@ -1349,7 +3561,7 @@ async function changeOnce(
1349
3561
  } else
1350
3562
  data.mode = /** @type {'both' | 'light-only' | 'dark-only'} */ (s.value);
1351
3563
  const r = await commitTheme(ctx, slug, data, {history: true});
1352
- const p = await previewAndRoute(ctx, slug, data, png);
3564
+ const p = await previewAndRoute(ctx, slug, data, png, 'overview', sub);
1353
3565
  const after = await baseResolved(ctx.project, data.like).catch(() => base);
1354
3566
  return {
1355
3567
  type: 'themeEdit.set',
@@ -1377,8 +3589,34 @@ async function changeOnce(
1377
3589
  ]
1378
3590
  : []),
1379
3591
  ...otherModeNotes(data),
3592
+ // A theme the app lists takes its mode from the app's theme
3593
+ // module: `theme add` writes it again.
3594
+ ...(s.thing === 'mode' && before !== data.mode
3595
+ ? [
3596
+ addedModeNote(
3597
+ cwd,
3598
+ slug,
3599
+ data.mode === 'light-only'
3600
+ ? 'light'
3601
+ : data.mode === 'dark-only'
3602
+ ? 'dark'
3603
+ : null,
3604
+ ),
3605
+ ].filter(x => x !== null)
3606
+ : []),
3607
+ // Back to both modes: a mode the app's <Theme> was given for the
3608
+ // one-mode theme pins it still.
3609
+ ...(s.thing === 'mode' &&
3610
+ !appListsTheme(cwd, slug) &&
3611
+ data.mode === 'both' &&
3612
+ (before === 'light-only' || before === 'dark-only')
3613
+ ? [
3614
+ `if the app's <Theme> was given mode="${before === 'light-only' ? 'light' : 'dark'}" for ${slug}, take it out: with it the app stays ${before === 'light-only' ? 'light' : 'dark'}, whatever the system asks for`,
3615
+ ]
3616
+ : []),
1380
3617
  // Core has no mode inside a theme: the app's <Theme> is given it.
1381
3618
  ...(s.thing === 'mode' &&
3619
+ !appListsTheme(cwd, slug) &&
1382
3620
  (data.mode === 'light-only' || data.mode === 'dark-only')
1383
3621
  ? [
1384
3622
  `the app shows ${slug} in ${data.mode === 'light-only' ? 'light' : 'dark'} mode when its <Theme> is given mode="${data.mode === 'light-only' ? 'light' : 'dark'}" (<Theme theme={…} mode="${data.mode === 'light-only' ? 'light' : 'dark'}">), as the preview does; the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
@@ -1411,13 +3649,57 @@ async function changeOnce(
1411
3649
  }
1412
3650
  const k = keyOf(s);
1413
3651
  const prevIdx =
1414
- rawIdx >= 0 ? rawIdx : data.settings.findIndex(x => keyOf(x) === k);
3652
+ rawIdx >= 0
3653
+ ? rawIdx
3654
+ : // A setting listed twice by hand: the last entry is the one the
3655
+ // build reads, so it is the one this command changes.
3656
+ data.settings.map(x => keyOf(x)).lastIndexOf(k);
1415
3657
  /** @type {string | null} */
1416
3658
  let vibrancyGone = null;
1417
3659
  const prev = prevIdx >= 0 ? data.settings[prevIdx] : null;
3660
+ /** The other entries of a setting listed twice by hand that this command replaces or removes. @type {import('./_settings.mjs').Setting[]} */
3661
+ let alsoReplaced = [];
1418
3662
  if (sub === 'undo') {
1419
3663
  if (!prev) {
1420
- const near = data.settings.filter(x => x.thing === s.thing).map(describe);
3664
+ // A padding set in the other form (a side for the shorthand, or the
3665
+ // shorthand for a side) on the same part is a near one too.
3666
+ const PAD = /^padding(?:-(?:inline|block|top|right|bottom|left))?$/;
3667
+ const nearOnes = data.settings.filter(
3668
+ x =>
3669
+ x.thing === s.thing ||
3670
+ (PAD.test(s.thing) &&
3671
+ PAD.test(x.thing) &&
3672
+ (x.on ?? null) === (s.on ?? null)),
3673
+ );
3674
+ const near = nearOnes.map(describe);
3675
+ // A token the theme's own source sets: that file is where it is
3676
+ // changed, never the settings.
3677
+ const ownEntry =
3678
+ s.thing.startsWith('--') && !s.on && !s.when && !s.state
3679
+ ? ownTokenEntries(cwd, slug).find(
3680
+ x =>
3681
+ x.token === s.thing &&
3682
+ !x.overridden &&
3683
+ x.kind !== 'scoped' &&
3684
+ x.kind !== 'chain',
3685
+ )
3686
+ : undefined;
3687
+ if (ownEntry) {
3688
+ const file = ownEntry.file
3689
+ ? path.relative(cwd, ownEntry.file)
3690
+ : `themes/${slug}/${slug}.theme.ts`;
3691
+ refuse(
3692
+ E.ERR_THEME_NOT_SET,
3693
+ `The settings do not set ${s.thing}: ${file} sets it itself${ownEntry.line ? ` (line ${ownEntry.line})` : ''}, so undo has nothing to remove; change or remove it in ${file}.`,
3694
+ {
3695
+ run: [
3696
+ ownEntry.line
3697
+ ? `sed -n ${ownEntry.line}p ${quoteCommandArgument(file)}`
3698
+ : `grep -n -- ${quoteCommandArgument(s.thing)} ${quoteCommandArgument(file)}`,
3699
+ ],
3700
+ },
3701
+ );
3702
+ }
1421
3703
  // headings has two halves: name the one that is set.
1422
3704
  const otherHalf =
1423
3705
  s.thing === 'headings'
@@ -1430,11 +3712,12 @@ async function changeOnce(
1430
3712
  : `The theme does not set ${describe({...s, value: '?'}).replace(' = ?', '')}.`,
1431
3713
  {
1432
3714
  also: near.length
1433
- ? [`settings for ${s.thing}: ${near.join('; ')}`]
3715
+ ? [
3716
+ `settings for ${s.thing}: ${near.join('; ')}${nearOnes.some(x => x.thing === 'padding' && s.thing !== 'padding') ? ' (undoing padding removes all four sides)' : ''}`,
3717
+ ]
1434
3718
  : [],
1435
3719
  run: [
1436
- ...data.settings
1437
- .filter(x => x.thing === s.thing)
3720
+ ...nearOnes
1438
3721
  .slice(0, 3)
1439
3722
  .map(x => `${P} undo ${slug} ${undoArgs(x)}`),
1440
3723
  `${P} show ${slug}`,
@@ -1443,7 +3726,9 @@ async function changeOnce(
1443
3726
  );
1444
3727
  }
1445
3728
  data.settings.splice(prevIdx, 1);
1446
- // A setting listed twice by hand goes in full.
3729
+ // A setting listed twice by hand goes in full, and each entry removed
3730
+ // is named.
3731
+ alsoReplaced = data.settings.filter(x => keyOf(x) === k);
1447
3732
  data.settings = data.settings.filter(x => keyOf(x) !== k);
1448
3733
  // Vibrancy needs a color: undoing the last one takes it along, so the
1449
3734
  // theme never holds a state `set` refuses.
@@ -1480,9 +3765,11 @@ async function changeOnce(
1480
3765
  if (prev) data.settings.splice(prevIdx, 1);
1481
3766
  data.settings.push(s);
1482
3767
  }
1483
- // A setting listed twice by hand keeps only the entry this command left.
3768
+ // A setting listed twice by hand keeps only the entry this command left;
3769
+ // every other entry it replaces is named in the notes.
1484
3770
  if (sub === 'set') {
1485
3771
  const last = data.settings.map(x => keyOf(x)).lastIndexOf(k);
3772
+ alsoReplaced = data.settings.filter((x, i) => keyOf(x) === k && i !== last);
1486
3773
  data.settings = data.settings.filter(
1487
3774
  (x, i) => keyOf(x) !== k || i === last,
1488
3775
  );
@@ -1493,7 +3780,21 @@ async function changeOnce(
1493
3780
  const covered =
1494
3781
  sub === 'set' && !s.mode && s.source !== 'dial'
1495
3782
  ? data.settings.filter(
1496
- x => x !== s && x.mode && keyOf({...x, mode: undefined}) === k,
3783
+ x =>
3784
+ x !== s &&
3785
+ x.mode &&
3786
+ (keyOf({...x, mode: undefined}) === k ||
3787
+ // The background shorthand and its color are one property
3788
+ // here: a one-mode one is replaced by either for both modes.
3789
+ (s.source === 'property' &&
3790
+ x.source === 'property' &&
3791
+ x.on === s.on &&
3792
+ x.when === s.when &&
3793
+ x.state === s.state &&
3794
+ [x.thing, s.thing].every(t =>
3795
+ /^background(-color)?$/.test(kebab(t)),
3796
+ ) &&
3797
+ !/gradient\(|url\(/i.test(String(s.value)))),
1497
3798
  )
1498
3799
  : [];
1499
3800
  data.settings = data.settings.filter(x => !covered.includes(x));
@@ -1513,6 +3814,9 @@ async function changeOnce(
1513
3814
  ))) &&
1514
3815
  x.when === s.when &&
1515
3816
  x.state === s.state &&
3817
+ // A shorthand for one mode replaces longhands of that mode only:
3818
+ // a longhand set for both modes still holds the other mode.
3819
+ (!s.mode || x.mode === s.mode) &&
1516
3820
  // A longhand the shorthand really sets (MDN's data), never a
1517
3821
  // property that only shares its name (overflow-wrap).
1518
3822
  (coversProperty(s.thing, x.thing) ||
@@ -1537,6 +3841,12 @@ async function changeOnce(
1537
3841
  : [];
1538
3842
  const r = await commitTheme(ctx, slug, data, {history: true});
1539
3843
  const compiledAfter = compileTheme(ctx, data, base);
3844
+ // What the spacing dial said of the sizes it could not keep apart.
3845
+ // What the build said of settings it could not write as they are.
3846
+ const compileNotes = buildNotes(ctx).filter(n => !notesBefore.has(n));
3847
+ const sizeNotes =
3848
+ /** @type {{sizeNotes?: string[]}} */ (/** @type {unknown} */ (ctx))
3849
+ .sizeNotes ?? [];
1540
3850
  const styled = styledChanges(compiledBefore, compiledAfter, base);
1541
3851
  const parts = partsOf(ctx, s);
1542
3852
  // Exact whole-theme tokens that win over what this dial writes: the dial
@@ -1562,6 +3872,29 @@ async function changeOnce(
1562
3872
  !x.when &&
1563
3873
  x.thing === `--font-family-${s.on}`,
1564
3874
  );
3875
+ // A whole-theme spacing dial keeps a part's own exact control size too,
3876
+ // on that part.
3877
+ if (sub === 'set' && s.source === 'dial' && s.thing === 'spacing' && !s.on)
3878
+ exactWins.push(
3879
+ ...data.settings.filter(
3880
+ x =>
3881
+ x.source === 'token' &&
3882
+ !!x.on &&
3883
+ !x.state &&
3884
+ /^--size-element-/.test(x.thing),
3885
+ ),
3886
+ );
3887
+ // A spacing dial on a part keeps the exact spacing and sizes there too:
3888
+ // the whole theme's, and the part's own.
3889
+ if (sub === 'set' && s.source === 'dial' && s.thing === 'spacing' && s.on)
3890
+ exactWins = data.settings.filter(
3891
+ x =>
3892
+ x.source === 'token' &&
3893
+ !x.when &&
3894
+ !x.state &&
3895
+ /^--(size-element|spacing)-/.test(x.thing) &&
3896
+ (!x.on || x.on === s.on),
3897
+ );
1565
3898
  // The theme's own source wins over an exact setting, as the exact
1566
3899
  // setting does over a dial: an exact token the file also sets is named
1567
3900
  // as the file's below, never as the one that shows after an undo.
@@ -1762,6 +4095,12 @@ async function changeOnce(
1762
4095
  : null;
1763
4096
  /** @type {string[]} */
1764
4097
  const notes = [
4098
+ ...fieldNotes,
4099
+ ...(alsoReplaced.length && prev
4100
+ ? [
4101
+ `${describe({...prev, value: '?'}).replace(' = ?', '')} was listed ${alsoReplaced.length === 1 ? 'twice' : `${alsoReplaced.length + 1} times`} (${[...alsoReplaced, prev].map(x => x.value).join(', ')}); each is ${sub === 'set' ? 'replaced' : 'removed'}`,
4102
+ ]
4103
+ : []),
1765
4104
  ...(covered.length ? [`replaces ${covered.map(describe).join(', ')}`] : []),
1766
4105
  ...(ownPartHits.length
1767
4106
  ? [
@@ -1773,7 +4112,7 @@ async function changeOnce(
1773
4112
  )
1774
4113
  .join(
1775
4114
  ', ',
1776
- )}${ownPartHits.length > 3 ? ` and ${ownPartHits.length - 3} more` : ''}, and your own source wins over the settings, so this does not show there; change it in ${slug}.theme.ts${ownHitDirect ? `, or take this back with \`${P} undo ${slug} ${undoArgs(s)}\`` : ''}`,
4115
+ )}${ownPartHits.length > 3 ? ` and ${ownPartHits.length - 3} more` : ''}, and your own source wins over the settings, so this does not show ${/^padding(-|$)/.test(s.thing) && ownPartHits.every(h => /^padding-/.test(h.prop)) ? 'on the sides that sets; its other sides take this setting' : 'there'}; change it in ${slug}.theme.ts${ownHitDirect ? `, or take this back with \`${P} undo ${slug} ${undoArgs(s)}\`` : ''}`,
1777
4116
  ]
1778
4117
  : []),
1779
4118
  ...(ownOverToken
@@ -1786,6 +4125,8 @@ async function changeOnce(
1786
4125
  `keeps your exact ${exactWins.map(describe).join(', ')}: an exact setting wins over a dial, so ${exactWins.length > 1 ? 'those do' : 'that does'} not change; this shows after \`${P} undo ${slug} ${exactWins.map(x => undoArgs(x)).join(`\` and \`${P} undo ${slug} `)}\``,
1787
4126
  ]
1788
4127
  : []),
4128
+ ...(sub === 'set' && s.thing === 'spacing' ? sizeNotes : []),
4129
+ ...(sub === 'set' ? compileNotes : []),
1789
4130
  ...(covers.length
1790
4131
  ? [
1791
4132
  `comes after ${covers.map(describe).join(', ')}, so ${covers.length > 1 ? 'those parts show' : `${covers[0].on} shows`} this value now; set ${covers.length > 1 ? 'one' : 'it'} again to make it win`,
@@ -1831,9 +4172,18 @@ async function changeOnce(
1831
4172
  // An exact property on the same part wins over a dial there.
1832
4173
  ...(exactOver
1833
4174
  ? [
1834
- ownPartHits.length
1835
- ? `${describe(exactOver)} is an exact property and wins over ${s.thing} there too; undoing it does not make ${s.thing} show on ${[...new Set(ownPartHits.map(h => h.target))].join(', ')}, where ${slug}.theme.ts wins`
1836
- : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
4175
+ // The own source holding only some sides or corners there leaves
4176
+ // the dial the others once the exact property is undone.
4177
+ ownPartHits.length &&
4178
+ ownPartHits.every(h =>
4179
+ /(Top|Bottom|Left|Right|Start|End|Block|Inline)/.test(
4180
+ camel(String(h.prop)),
4181
+ ),
4182
+ )
4183
+ ? `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\`, and then not on the ${[...new Set(ownPartHits.map(h => kebab(String(h.prop))))].join(', ')} ${slug}.theme.ts sets itself`
4184
+ : ownPartHits.length
4185
+ ? `${describe(exactOver)} is an exact property and wins over ${s.thing} there too; undoing it does not make ${s.thing} show on ${[...new Set(ownPartHits.map(h => h.target))].join(', ')}, where ${slug}.theme.ts wins`
4186
+ : `${describe(exactOver)} is an exact property and wins over ${s.thing} there, so this shows only after \`${P} undo ${slug} ${undoArgs(exactOver)}\``,
1837
4187
  ]
1838
4188
  : []),
1839
4189
  // A whole-theme font under fonts set for each role shows only where no
@@ -1900,6 +4250,31 @@ async function changeOnce(
1900
4250
  : null
1901
4251
  : null;
1902
4252
  if (s.note) notes.push(s.note);
4253
+ // A value for the mode a one-mode theme does not show applies where Core
4254
+ // draws that mode.
4255
+ if (
4256
+ s.mode &&
4257
+ (data.mode === 'light-only' || data.mode === 'dark-only') &&
4258
+ data.mode !== `${s.mode}-only`
4259
+ )
4260
+ notes.push(
4261
+ `a ${data.mode} theme shows ${s.mode} mode only where Core draws a ${s.mode} region (a toast, a lightbox), so this value applies there`,
4262
+ );
4263
+ // A group kept alike (inputs share one height) loses that when one member
4264
+ // changes its height alone.
4265
+ const family = s.on && s.only ? familyOf(s.on) : null;
4266
+ if (
4267
+ family &&
4268
+ AUTO_SPREAD.includes(family) &&
4269
+ (s.thing === 'spacing' ||
4270
+ /^--size-element-/.test(s.thing) ||
4271
+ /^(min-|max-)?(height|block-size)$|^padding(-block(-start|-end)?|-top|-bottom)?$/.test(
4272
+ s.thing,
4273
+ ))
4274
+ )
4275
+ notes.push(
4276
+ `${s.on} alone now differs in height from the rest of ${family}, which are kept alike; --on ${family} changes them together`,
4277
+ );
1903
4278
  // A token the theme's own source sets itself wins over what this dial
1904
4279
  // writes, as an exact setting does.
1905
4280
  const ownWins = ownSourceTokens(cwd, slug).filter(
@@ -2000,7 +4375,14 @@ async function changeOnce(
2000
4375
  );
2001
4376
  notes.push(...unsetColorNotes(data, base, slug));
2002
4377
  }
2003
- if (s.thing === 'font' && sub === 'set')
4378
+ // A font set (the dial, a part's own font-family, a font token): how
4379
+ // it loads.
4380
+ if (
4381
+ (s.thing === 'font' ||
4382
+ s.thing === 'font-family' ||
4383
+ /^--font-family-/.test(s.thing)) &&
4384
+ sub === 'set'
4385
+ )
2004
4386
  notes.unshift(...fontNotes(ctx, {...data, settings: [s]}));
2005
4387
  if (s.thing === 'type' || s.thing === 'headings')
2006
4388
  for (const [m, why] of maskedSettings(data, ctx))
@@ -2018,6 +4400,12 @@ async function changeOnce(
2018
4400
  // once preview.html was rendered from the theme as it is now (a retry
2019
4401
  // after a render that failed renders it).
2020
4402
  const f0 = themeFiles(cwd, slug);
4403
+ // A change that changed nothing still writes back an app copy file that
4404
+ // is gone or not the current build.
4405
+ // Its font stylesheet follows the fonts the theme loads now (a font
4406
+ // package installed or removed since).
4407
+ if (r.unchanged && appCopyBehind(cwd, slug, copyFontsCss(ctx, slug, data)))
4408
+ writeAppCopy(ctx, slug, data);
2021
4409
  const p =
2022
4410
  r.unchanged &&
2023
4411
  !png &&
@@ -2030,8 +4418,10 @@ async function changeOnce(
2030
4418
  notChecked: null,
2031
4419
  previewStale: [],
2032
4420
  see: seeLine(cwd, slug, changeFocus(s)),
4421
+ // A copy something keeps behind is said here too.
4422
+ ...appCopyStale(cwd, slug),
2033
4423
  }
2034
- : await previewAndRoute(ctx, slug, data, png, changeFocus(s));
4424
+ : await previewAndRoute(ctx, slug, data, png, changeFocus(s), sub);
2035
4425
  return {
2036
4426
  type: sub === 'set' ? 'themeEdit.set' : 'themeEdit.undo',
2037
4427
  data: {
@@ -2105,6 +4495,65 @@ function unsetColorNotes(data, base, slug) {
2105
4495
  ];
2106
4496
  }
2107
4497
 
4498
+ /**
4499
+ * Whether a settings entry is a mode or base a hand edit put in the list:
4500
+ * it does nothing there (the theme's mode and base are its own fields).
4501
+ * @param {{thing: string}} s
4502
+ */
4503
+ const misplaced = s => s.thing === 'mode' || s.thing === 'base';
4504
+
4505
+ /**
4506
+ * The note for each misplaced entry: listed here only, never as a
4507
+ * setting, with the undo that removes it first.
4508
+ * @param {string} slug
4509
+ * @param {import('./_settings.mjs').ThemeData} data
4510
+ * @returns {string[]}
4511
+ */
4512
+ function misplacedNotes(slug, data) {
4513
+ return data.settings
4514
+ .filter(misplaced)
4515
+ .map(
4516
+ x =>
4517
+ `misplaced: the settings list holds ${x.thing} = ${x.value}, which does nothing there (the theme's ${x.thing} is ${x.thing === 'mode' ? data.mode : (data.like ?? 'none')}); \`${P} undo ${slug} ${x.thing}\` removes it, and \`${P} set ${slug} ${x.thing} <value>\` sets the theme's ${x.thing}`,
4518
+ );
4519
+ }
4520
+
4521
+ /**
4522
+ * A refusal for a theme with misplaced entries, its suggestions led by the
4523
+ * undo that removes each.
4524
+ * @param {unknown} e
4525
+ * @param {string} slug
4526
+ * @param {import('./_settings.mjs').ThemeData | undefined} data
4527
+ */
4528
+ function misplacedFirst(e, slug, data) {
4529
+ if (!(e instanceof AstryxError) || !data) return e;
4530
+ const undos = data.settings.filter(misplaced).map(x => ({
4531
+ name: `${P} undo ${slug} ${x.thing}`,
4532
+ reason: `removes the ${x.thing} entry that does nothing in the settings list`,
4533
+ }));
4534
+ if (!undos.length) return e;
4535
+ e.suggestions = [
4536
+ ...undos,
4537
+ ...(e.suggestions ?? []).filter(x => !undos.some(u => u.name === x.name)),
4538
+ ];
4539
+ return e;
4540
+ }
4541
+
4542
+ /**
4543
+ * The command that leads to the fix of a render that failed: installing
4544
+ * React when it is missing, listing React's copies when the app and Core
4545
+ * resolve two (the message says which), and otherwise doctor's install
4546
+ * checks.
4547
+ * @param {any} ctx
4548
+ * @param {string} cwd
4549
+ */
4550
+ function renderFix(ctx, cwd) {
4551
+ if (ctx.uncheckedCode === 'ERR_RENDER_MISSING_DEPENDENCY')
4552
+ return [installLine(cwd, ['react', 'react-dom'])];
4553
+ if (reactCopies(ctx.project)) return [copiesLine(cwd, 'react')];
4554
+ return [`${getCliInvocation(cwd)} doctor`];
4555
+ }
4556
+
2108
4557
  /**
2109
4558
  * Every setting of a theme, key resolved values, problems it caused, the
2110
4559
  * sample page and the theme-building page with every component.
@@ -2120,12 +4569,21 @@ export async function themeEditShow(theme, options = {}) {
2120
4569
  const readOnly = Boolean(/** @type {any} */ (options).readOnly);
2121
4570
  requireProject(cwd);
2122
4571
  const section = checkSection(options.section, theme);
2123
- const data = loadTheme(cwd, theme);
4572
+ /** What each build this show makes reports (the pictures it removed). @type {string[]} */
4573
+ const rebuiltNotes = [];
4574
+ /** @type {import('./_settings.mjs').ThemeData} */
4575
+ let data;
4576
+ try {
4577
+ data = loadTheme(cwd, theme);
4578
+ } catch (e) {
4579
+ throw await vetLoadRefusal(e, cwd, theme);
4580
+ }
2124
4581
  const ctx = await context(cwd);
2125
4582
  // The app copy is written once show succeeds (at its end), never by a
2126
4583
  // build a later refusal puts back.
2127
4584
  holdAfterBuild(ctx);
2128
4585
  refuseStoredTokens(ctx, theme, data);
4586
+ await refuseOwnTokenValues(ctx, theme, data);
2129
4587
  // Without React, show still lists the settings and builds the theme, as
2130
4588
  // set does; only the pages, pictures and the checks that render are
2131
4589
  // skipped, and the result says how to fix it.
@@ -2141,14 +4599,7 @@ export async function themeEditShow(theme, options = {}) {
2141
4599
  E.ERR_RENDER_FAILED,
2142
4600
  `${theme} cannot be shown: ${ctx.unchecked} Nothing was written.`,
2143
4601
  {
2144
- // Only a missing React is fixed by installing it; two copies or a
2145
- // component that throws are named in the message.
2146
- run:
2147
- ctx.uncheckedCode === 'ERR_RENDER_MISSING_DEPENDENCY'
2148
- ? [installLine(cwd, ['react', 'react-dom'])]
2149
- : // Two copies of React and other install problems are named by
2150
- // doctor; the same show would fail the same way.
2151
- [`${getCliInvocation(cwd)} doctor`],
4602
+ run: renderFix(ctx, cwd),
2152
4603
  },
2153
4604
  );
2154
4605
  const f = themeFiles(cwd, theme);
@@ -2157,7 +4608,7 @@ export async function themeEditShow(theme, options = {}) {
2157
4608
  // An own source that does not parse is refused before anything is
2158
4609
  // built, written or removed (the build would fail part way).
2159
4610
  if (!readOnly) refuseThemeParse(cwd, theme);
2160
- const brokenSource = themeSourceProblem(cwd, theme);
4611
+ const brokenSource = await themeSourceProblem(cwd, theme);
2161
4612
  // Every output, as `compile --check` reads them: one missing or edited by
2162
4613
  // hand is built again too.
2163
4614
  let stale = staleBuild(cwd, theme, data);
@@ -2214,7 +4665,7 @@ export async function themeEditShow(theme, options = {}) {
2214
4665
  const refs = path.join(tokensDir, `${theme}.palette-refs.ts`);
2215
4666
  if (!kept.has(refs)) kept.set(refs, null);
2216
4667
  try {
2217
- await buildTheme(ctx, theme, data);
4668
+ rebuiltNotes.push(...(await buildTheme(ctx, theme, data)).notes);
2218
4669
  } catch (e) {
2219
4670
  putBack(kept, tokensDir);
2220
4671
  if (e instanceof AstryxError && e.code !== E.ERR_THEME_LOAD) throw e;
@@ -2256,13 +4707,13 @@ export async function themeEditShow(theme, options = {}) {
2256
4707
  if (brokenSource)
2257
4708
  refuse(
2258
4709
  E.ERR_THEME_INVALID,
2259
- `${theme}.js could not be read, and it cannot be built again: ${brokenSource}. Put back the import of ${camel(theme)}Settings from './${theme}.settings', extends: ${camel(theme)}Settings and name: '${theme}' in ${shown(cwd, f.ts)}, then run show again.`,
4710
+ `${theme}.js could not be read, and it cannot be built again: ${brokenSource.problem}. ${brokenSource.fix} Then run show again.`,
2260
4711
  {
2261
4712
  run: [`cat ${quoteCommandArgument(shown(cwd, f.ts))}`],
2262
4713
  },
2263
4714
  );
2264
4715
  unreadable = `${theme}.js could not be read (${e instanceof Error ? e.message.split('\n')[0] : String(e)}), so it was built again from the settings`;
2265
- await buildTheme(ctx, theme, data);
4716
+ rebuiltNotes.push(...(await buildTheme(ctx, theme, data)).notes);
2266
4717
  return resolvedTokens(ctx, theme);
2267
4718
  });
2268
4719
  const ownOverNotes = ownOverSettingNotes(cwd, theme, data);
@@ -2287,10 +4738,20 @@ export async function themeEditShow(theme, options = {}) {
2287
4738
  if (!(e instanceof Error)) throw e;
2288
4739
  if (e instanceof AstryxError && e.code !== E.ERR_RENDER_FAILED) throw e;
2289
4740
  putBack(kept, tokensDir);
4741
+ // A folder it cannot write is no render failure: the folder is named.
4742
+ const code = /** @type {any} */ (e).code;
4743
+ if (['EACCES', 'EPERM', 'EROFS'].includes(code)) {
4744
+ const where = /** @type {any} */ (e).path;
4745
+ return refuse(
4746
+ E.ERR_WRITE_FAILED,
4747
+ `${theme} cannot be shown: ${where ? `${shown(cwd, path.dirname(where))}/` : 'its theme folder'} cannot be written (${code}). Fix its permissions, then run the command again. Nothing was written.`,
4748
+ {run: [`${P} show ${theme}`]},
4749
+ );
4750
+ }
2290
4751
  return refuse(
2291
4752
  E.ERR_RENDER_FAILED,
2292
4753
  `${theme} cannot be shown: ${renderCause(ctx.project, e.message)} ${[...kept.values()].some(Boolean) ? 'The build this show made again was put back as it was. ' : ''}Nothing was written.`,
2293
- {run: [`${getCliInvocation(cwd)} doctor`]},
4754
+ {run: renderFix(ctx, cwd)},
2294
4755
  );
2295
4756
  }
2296
4757
  };
@@ -2328,7 +4789,15 @@ export async function themeEditShow(theme, options = {}) {
2328
4789
  ],
2329
4790
  modes,
2330
4791
  )
2331
- : {files: [], problem: null};
4792
+ : // Pictures asked for but not taken: said, never a quiet none.
4793
+ {
4794
+ files: [],
4795
+ problem: png
4796
+ ? readOnly
4797
+ ? 'no picture was taken: show ran read-only (the project or its install cannot be written, so it could not hold the theme lock), and the pages the pictures are taken of were not made; run show --png where the project can be written'
4798
+ : 'no picture was taken: React is not installed here, so the pages the pictures are taken of could not be made; install react and react-dom, then run show --png again'
4799
+ : null,
4800
+ };
2332
4801
  // The app copy follows the build there now, also when the build was
2333
4802
  // current and only the copy is missing (a theme made before it existed).
2334
4803
  if (!readOnly)
@@ -2347,29 +4816,33 @@ export async function themeEditShow(theme, options = {}) {
2347
4816
  const looksBase = await baseResolved(ctx.project, data.like).catch(
2348
4817
  () => null,
2349
4818
  );
2350
- return data.settings.map(s => {
2351
- let masked = maskedSettings(data, ctx).get(s);
2352
- // A look dial (buttons, surfaces) under an exact property on a
2353
- // part it writes: named, as corners under border-radius is.
2354
- if (!masked && looksBase && s.source === 'dial' && !s.on) {
2355
- const writes = dialWrites(ctx, data, s, looksBase);
2356
- const exact = writes.size
2357
- ? data.settings.find(
2358
- x =>
2359
- x.source === 'property' &&
2360
- x.on &&
2361
- !x.when &&
2362
- !x.state &&
2363
- partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
2364
- )
2365
- : undefined;
2366
- if (exact)
2367
- masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
2368
- }
2369
- return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
2370
- });
4819
+ return data.settings
4820
+ .filter(s => !misplaced(s))
4821
+ .map(s => {
4822
+ let masked = maskedSettings(data, ctx).get(s);
4823
+ // A look dial (buttons, surfaces) under an exact property on a
4824
+ // part it writes: named, as corners under border-radius is.
4825
+ if (!masked && looksBase && s.source === 'dial' && !s.on) {
4826
+ const writes = dialWrites(ctx, data, s, looksBase);
4827
+ const exact = writes.size
4828
+ ? data.settings.find(
4829
+ x =>
4830
+ x.source === 'property' &&
4831
+ x.on &&
4832
+ !x.when &&
4833
+ !x.state &&
4834
+ partsOf(ctx, x).some(t => writes.has(`${t}\0${x.thing}`)),
4835
+ )
4836
+ : undefined;
4837
+ if (exact)
4838
+ masked = `${describe(exact)} is an exact property and wins over ${s.thing} on ${exact.on}`;
4839
+ }
4840
+ return {...s, parts: partsOf(ctx, s), ...(masked ? {masked} : {})};
4841
+ });
2371
4842
  })(),
2372
4843
  notes: [
4844
+ ...rebuiltNotes,
4845
+ ...misplacedNotes(theme, data),
2373
4846
  ...(noReact
2374
4847
  ? [
2375
4848
  `react and react-dom cannot be found from this app, so the pages and pictures were not made again and the checks that render components were skipped; install them (${installLine(cwd, ['react', 'react-dom'])}), then run show again`,
@@ -2391,7 +4864,7 @@ export async function themeEditShow(theme, options = {}) {
2391
4864
  ...(unreadable ? [unreadable] : []),
2392
4865
  ...(brokenSource
2393
4866
  ? [
2394
- `${brokenSource}, so settings cannot take effect; put back the import, extends and name lines in ${theme}.theme.ts${/no longer names the theme/.test(brokenSource) ? ` (a copy of another theme's source still names that theme: change its name to '${theme}')` : ''}`,
4867
+ `${brokenSource.problem}, so settings cannot take effect. ${brokenSource.fix}`,
2395
4868
  ]
2396
4869
  : []),
2397
4870
  // A setting the theme file wins over is not live: no contrast
@@ -2443,6 +4916,7 @@ export async function themeEditShow(theme, options = {}) {
2443
4916
  const wrote = takeFirstAppCopy(cwd, theme);
2444
4917
  return wrote ? {appCopy: {wrote}} : {};
2445
4918
  })(),
4919
+ ...appCopyStale(cwd, theme),
2446
4920
  colorFiles: pal ? colorFiles(theme) : null,
2447
4921
  },
2448
4922
  };
@@ -2492,6 +4966,10 @@ function dialWrites(ctx, data, dial, base) {
2492
4966
  * @returns {string}
2493
4967
  */
2494
4968
  function nowApplies(ctx, data, removed, base) {
4969
+ // Vibrancy has no base theme value: the colors are made again at the
4970
+ // default.
4971
+ if (removed.source === 'dial' && removed.thing === 'vibrancy')
4972
+ return `the default vibrancy, ${VIBRANCY_DEFAULT}`;
2495
4973
  // A token the theme's own source sets shows its value, whatever else
2496
4974
  // the settings give it.
2497
4975
  if (removed.source === 'token' && !removed.on && !removed.when) {
@@ -2647,8 +5125,9 @@ function nowApplies(ctx, data, removed, base) {
2647
5125
  }
2648
5126
 
2649
5127
  /**
2650
- * Settings saved for a mode a one-mode theme does not have: they stay saved
2651
- * and apply again when the theme has that mode.
5128
+ * Settings saved for the mode a one-mode theme does not show: they apply
5129
+ * where Core draws that mode (a toast, a lightbox), as the theme's other
5130
+ * halves of its colors do.
2652
5131
  * @param {import('./_settings.mjs').ThemeData} data
2653
5132
  * @returns {string[]}
2654
5133
  */
@@ -2659,7 +5138,7 @@ function otherModeNotes(data) {
2659
5138
  );
2660
5139
  if (!off.length) return [];
2661
5140
  return [
2662
- `not applied in a ${data.mode} theme, kept for when it has that mode again: ${off
5141
+ `a ${data.mode} theme shows the other mode only where Core draws it (a toast, a lightbox), so these apply there: ${off
2663
5142
  .slice(0, 4)
2664
5143
  .map(describe)
2665
5144
  .join(', ')}${off.length > 4 ? `, and ${off.length - 4} more` : ''}`,
@@ -2719,22 +5198,87 @@ function dialTouched(ctx, data, s, base) {
2719
5198
  * @param {import('./_settings.mjs').ThemeData} data
2720
5199
  * @returns {string[]}
2721
5200
  */
2722
- function ownPhoneNotes(cwd, slug, data) {
5201
+ export function ownPhoneNotes(cwd, slug, data) {
2723
5202
  if (!data.like) return [];
2724
5203
  const exact = new Set(
2725
5204
  data.settings
2726
5205
  .filter(x => x.source === 'token' && !x.on && !x.when && !x.state)
2727
5206
  .map(x => x.thing),
2728
5207
  );
5208
+ // A family or size the theme's typography sets is kept on phones (the
5209
+ // base theme's rule for those screens keeps the theme's typography); only
5210
+ // one the tokens map sets is lost there.
5211
+ const entries = ownTokenEntries(cwd, slug);
5212
+ const roles = new Set(
5213
+ entries.filter(e => e.kind === 'typography').map(e => e.key.split('.')[0]),
5214
+ );
5215
+ const inMap = new Set(
5216
+ entries
5217
+ .filter(
5218
+ e =>
5219
+ e.token && !e.overridden && e.kind !== 'scoped' && e.kind !== 'chain',
5220
+ )
5221
+ .map(e => e.token),
5222
+ );
5223
+ /** @param {string} k */
5224
+ const fromTypography = k => {
5225
+ const role = /^--font-family-([a-z]+)$/.exec(k)?.[1];
5226
+ if (role)
5227
+ return roles.has(role) || (role === 'heading' && roles.has('body'));
5228
+ return roles.has('scale') && !/^--font-family-/.test(k);
5229
+ };
5230
+ // A value the build already writes for those screens too (the theme's
5231
+ // own rule for them, say) is kept there.
5232
+ const touch = builtTouchTokens(cwd, slug);
5233
+ const ownValue = (/** @type {string} */ k) =>
5234
+ entries.find(x => x.token === k && typeof x.value === 'string')?.value;
2729
5235
  const lost = ownSourceTokens(cwd, slug).filter(
2730
- k => PHONE_TYPE.test(k) && !exact.has(k),
5236
+ k =>
5237
+ PHONE_TYPE.test(k) &&
5238
+ !exact.has(k) &&
5239
+ (!fromTypography(k) || inMap.has(k)) &&
5240
+ !(ownValue(k) !== undefined && touch.get(k) === ownValue(k)),
2731
5241
  );
2732
5242
  if (!lost.length) return [];
2733
5243
  const families = lost.filter(k => /^--font-family-/.test(k));
5244
+ const others = lost.filter(k => !/^--font-family-/.test(k));
2734
5245
  const role =
2735
5246
  /^--font-family-([a-z]+)$/.exec(families[0] ?? '')?.[1] ?? 'body';
5247
+ // A family the theme's typography sets is kept on those screens; a
5248
+ // weight is kept there only by a rule for the same screens (a role's
5249
+ // weight without a scale builds nothing), so the fix names that rule
5250
+ // with the theme's own values.
5251
+ const valueOf = (/** @type {string} */ k) => ownValue(k) ?? '...';
5252
+ /** A value as a theme source writes it. @param {any} v @returns {string} */
5253
+ const literal = v =>
5254
+ typeof v === 'string'
5255
+ ? `'${v}'`
5256
+ : `{${Object.entries(v)
5257
+ .map(
5258
+ ([k, x]) =>
5259
+ `${/^[a-z]\w*$/i.test(k) ? k : `'${k}'`}: ${literal(x)}`,
5260
+ )
5261
+ .join(', ')}}`;
5262
+ const rule = `adaptations: {rules: [${literal({
5263
+ when: PHONE_RULE_WHEN,
5264
+ value: {
5265
+ tokens: Object.fromEntries(others.slice(0, 3).map(k => [k, valueOf(k)])),
5266
+ },
5267
+ })}]}`;
5268
+ const fix = [
5269
+ ...(families.length
5270
+ ? [
5271
+ `set ${families.length > 1 ? 'the families' : 'the family'} on the theme's typography in ${slug}.theme.ts (such as typography: {${role}: {family: ...}}, which that rule then keeps)`,
5272
+ ]
5273
+ : []),
5274
+ ...(others.length
5275
+ ? [
5276
+ `give ${others.length > 1 ? 'the weights' : 'the weight'} in a rule for the same screens in ${slug}.theme.ts (${rule})`,
5277
+ ]
5278
+ : []),
5279
+ ].join(', and ');
2736
5280
  return [
2737
- `on ${PHONES}, the base theme's type shows for ${lost.slice(0, 4).join(', ')}${lost.length > 4 ? ` and ${lost.length - 4} more` : ''}, which ${slug}.theme.ts sets as plain tokens: the base theme's rule for those screens sets its type again, and a rule wins over plain tokens there. To keep yours on every screen, set ${lost.length > 1 ? 'them' : 'it'} on the theme's typography in ${slug}.theme.ts (such as typography: {${role}: {family: ...}}, which that rule then keeps), or in a rule for the same screens`,
5281
+ `on ${PHONES}, the base theme's type shows for ${lost.slice(0, 4).join(', ')}${lost.length > 4 ? ` and ${lost.length - 4} more` : ''}, which ${slug}.theme.ts sets as plain tokens: the base theme's rule for those screens sets its type again, and a rule wins over plain tokens there. To keep yours on every screen, ${fix}`,
2738
5282
  ];
2739
5283
  }
2740
5284
 
@@ -3038,10 +5582,98 @@ function colorFiles(slug) {
3038
5582
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditUndoResponse | import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
3039
5583
  */
3040
5584
  export async function themeEditUndo(theme, options = {}) {
5585
+ try {
5586
+ return await undoTheme(theme, options);
5587
+ } catch (e) {
5588
+ // A theme name typed in another form (tTheme, T, brand_dark, themes/t):
5589
+ // the same undo with the theme's name comes first, never a look at the
5590
+ // theme that drops the undo.
5591
+ if (
5592
+ e instanceof AstryxError &&
5593
+ (e.code === E.ERR_INVALID_ARGUMENT || e.code === E.ERR_UNKNOWN_THEME)
5594
+ ) {
5595
+ const cwd = options.cwd ?? process.cwd();
5596
+ const showOf = (/** @type {{name: string}} */ x) => {
5597
+ const rest = x.name.startsWith(`${P} show `)
5598
+ ? x.name.slice(`${P} show `.length)
5599
+ : null;
5600
+ return rest && !/\s/.test(rest) ? rest : null;
5601
+ };
5602
+ // A list of themes (t,u) stays a look at each: one theme at a time.
5603
+ const shows = (e.suggestions ?? []).filter(x => showOf(x) != null);
5604
+ const near = (shows.length === 1 ? shows : []).find(x => {
5605
+ const n = showOf(x);
5606
+ return (
5607
+ n != null &&
5608
+ n !== theme &&
5609
+ slugOk(n) &&
5610
+ fs.existsSync(themeFiles(cwd, n).settings)
5611
+ );
5612
+ });
5613
+ const name = near ? showOf(near) : null;
5614
+ if (near && name) {
5615
+ const words = [
5616
+ ...(options.thing ? [options.thing] : []),
5617
+ ...(options.value ? [options.value] : []),
5618
+ ...(options.on ? ['--on', options.on] : []),
5619
+ ...(options.when ? ['--when', options.when] : []),
5620
+ ...(options.state ? ['--state', options.state] : []),
5621
+ ...(options.mode ? ['--mode', options.mode] : []),
5622
+ ].map(w =>
5623
+ String(w).startsWith('--') ? w : quoteCommandArgument(String(w)),
5624
+ );
5625
+ const followed = await followChangeLine(
5626
+ 'undo',
5627
+ name,
5628
+ `${P} undo ${name}${words.length ? ` ${words.join(' ')}` : ''}`,
5629
+ cwd,
5630
+ );
5631
+ e.suggestions = [
5632
+ {
5633
+ name: followed.line,
5634
+ reason: `do this instead: ${name} is a theme here${followed.why ? `, but this still needs a fix: ${followed.why}` : ''}`,
5635
+ },
5636
+ ...(e.suggestions ?? []).filter(x => x !== near),
5637
+ ];
5638
+ }
5639
+ }
5640
+ // Then the theme typed after the setting (`undo corners t`).
5641
+ throw await swappedOrder(
5642
+ e,
5643
+ 'undo',
5644
+ [theme, options.thing, options.value],
5645
+ options,
5646
+ );
5647
+ }
5648
+ }
5649
+
5650
+ /**
5651
+ * {@link themeEditUndo}'s work.
5652
+ * @param {string} theme
5653
+ * @param {import('./theme-edit.type.mjs').ThemeEditUndoOptions} options
5654
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditUndoResponse | import('./theme-edit.type.mjs').ThemeEditChangeResponse>}
5655
+ */
5656
+ async function undoTheme(theme, options) {
3041
5657
  const {cwd = process.cwd(), png = false, thing} = options;
3042
5658
  // base and mode are not settings in the list: undoing one goes back to
3043
5659
  // what the theme was made with (the oldest step the history keeps).
3044
- if (thing === 'base' || thing === 'mode') {
5660
+ // A `base` or `mode` entry a hand edit put in the settings list is a
5661
+ // setting like any other there: undo removes it.
5662
+ const listed =
5663
+ (thing === 'base' || thing === 'mode') &&
5664
+ slugOk(theme) &&
5665
+ (() => {
5666
+ try {
5667
+ return JSON.parse(
5668
+ fs
5669
+ .readFileSync(themeFiles(cwd, theme).settings, 'utf8')
5670
+ .replace(/^\uFEFF/, ''),
5671
+ ).settings.some((/** @type {any} */ x) => x?.thing === thing);
5672
+ } catch {
5673
+ return false;
5674
+ }
5675
+ })();
5676
+ if ((thing === 'base' || thing === 'mode') && !listed) {
3045
5677
  requireProject(cwd);
3046
5678
  const now = loadTheme(cwd, theme, thing);
3047
5679
  const historyFile = themeFiles(cwd, theme).history;
@@ -3128,12 +5760,23 @@ export async function themeEditUndo(theme, options = {}) {
3128
5760
  // A link in the theme is refused as set refuses it, never read as an
3129
5761
  // empty history.
3130
5762
  if (slugOk(theme)) refuseLinks(cwd, theme);
5763
+ /** The command that works when the settings cannot be read. @type {string[] | null} */
5764
+ let repair = null;
3131
5765
  try {
3132
5766
  current = loadTheme(cwd, theme);
3133
5767
  } catch (e) {
3134
5768
  if (!(e instanceof AstryxError && e.code === E.ERR_THEME_INVALID)) throw e;
5769
+ // What the refusal itself names (make the theme again, keeping the
5770
+ // damaged file), never `show`, which fails the same way.
5771
+ repair = (e.suggestions ?? [])
5772
+ .map(x => x.name)
5773
+ .filter(n => !/ show /.test(` ${n} `) && !/ undo /.test(` ${n} `));
5774
+ if (!repair.length) repair = [`${P} new ${theme}`];
3135
5775
  }
3136
5776
  const f = themeFiles(cwd, theme);
5777
+ // A change command refused since the last change changed nothing: this
5778
+ // undo takes back the change before it, and says so.
5779
+ const refusedSince = refusedAfter(cwd, theme, f.history);
3137
5780
  const {steps: history, dropped} = readHistory(f.history);
3138
5781
  if (!history.length && dropped)
3139
5782
  refuse(
@@ -3141,35 +5784,26 @@ export async function themeEditUndo(theme, options = {}) {
3141
5784
  `${theme}.history.json is damaged, so there is no step to go back to.`,
3142
5785
  {
3143
5786
  fix: `move ${shown(cwd, f.history)} out of the theme folder (it is kept as it is): the next change starts a new history, and your settings stay as they are`,
3144
- run: [`${P} show ${theme}`],
5787
+ run: repair ?? [`${P} show ${theme}`],
3145
5788
  },
3146
5789
  );
3147
5790
  if (!history.length)
3148
5791
  refuse(
3149
5792
  E.ERR_THEME_NOTHING_TO_UNDO,
3150
- `Nothing to undo: ${theme} has no earlier change.`,
3151
- {run: [`${P} show ${theme}`]},
5793
+ `Nothing to undo: ${theme} has no earlier change${repair ? `, and ${theme}.settings.json cannot be read` : ''}.`,
5794
+ {run: repair ?? [`${P} show ${theme}`]},
3152
5795
  );
3153
5796
  // A top step equal to the settings now (left by an undo stopped between
3154
5797
  // its two writes) changes nothing: skip it.
3155
5798
  const nowText = fs.readFileSync(f.settings, 'utf8');
3156
5799
  const same = (/** @type {string} */ a, /** @type {string} */ b) => {
3157
- try {
3158
- return (
3159
- JSON.stringify({
3160
- ...JSON.parse(a.replace(/^\uFEFF/, '')),
3161
- lifted: 0,
3162
- built: 0,
3163
- }) ===
3164
- JSON.stringify({
3165
- ...JSON.parse(b.replace(/^\uFEFF/, '')),
3166
- lifted: 0,
3167
- built: 0,
3168
- })
3169
- );
3170
- } catch {
3171
- return false;
3172
- }
5800
+ const [x, y] = [settingsJson(a), settingsJson(b)];
5801
+ return (
5802
+ x !== undefined &&
5803
+ y !== undefined &&
5804
+ JSON.stringify({...x, lifted: 0, built: 0}) ===
5805
+ JSON.stringify({...y, lifted: 0, built: 0})
5806
+ );
3173
5807
  };
3174
5808
  while (history.length && same(history[history.length - 1], nowText))
3175
5809
  history.pop();
@@ -3182,8 +5816,10 @@ export async function themeEditUndo(theme, options = {}) {
3182
5816
  const ctx = await context(cwd);
3183
5817
  const prevText = /** @type {string} */ (history.pop());
3184
5818
  let prev = /** @type {import('./_settings.mjs').ThemeData} */ (
3185
- JSON.parse(prevText.replace(/^\uFEFF/, ''))
5819
+ settingsJson(prevText)
3186
5820
  );
5821
+ // A step is read as a change reads the settings file.
5822
+ readAsMeant(prev, cwd);
3187
5823
  // A step always restores into this theme, whatever name it holds.
3188
5824
  prev.name = theme;
3189
5825
  // What the step's build showed is restored with it, not saved as a
@@ -3278,8 +5914,10 @@ export async function themeEditUndo(theme, options = {}) {
3278
5914
  undone.push(
3279
5915
  `base ${current.like ?? 'none'} is back to ${prev.like ?? 'none'}`,
3280
5916
  );
3281
- if (current && current.mode !== prev.mode)
5917
+ if (current && current.mode !== prev.mode) {
3282
5918
  undone.push(`mode ${current.mode} is back to ${prev.mode}`);
5919
+ undone.push(...modeWiringNotes(cwd, theme, current.mode, prev.mode));
5920
+ }
3283
5921
  // The page most about what the step reverted: Colors for a color,
3284
5922
  // Components for a part setting, else Overview.
3285
5923
  const touched = [
@@ -3291,12 +5929,43 @@ export async function themeEditUndo(theme, options = {}) {
3291
5929
  : touched.includes('components')
3292
5930
  ? 'components'
3293
5931
  : 'overview';
3294
- const p = await previewAndRoute(ctx, theme, prev, png, focus);
5932
+ const p = await previewAndRoute(ctx, theme, prev, png, focus, 'undo');
5933
+ // What the step took back, for the headline: each setting, base and mode
5934
+ // it changed, in one line.
5935
+ /** @type {string[]} */
5936
+ const took = [];
5937
+ for (const [k, s] of was) {
5938
+ const back = now.get(k);
5939
+ if (!back) took.push(describe(s));
5940
+ else if (back.value !== s.value)
5941
+ took.push(`${describe(s)} (back to ${back.value})`);
5942
+ }
5943
+ if (current)
5944
+ for (const [k, s] of now)
5945
+ if (!was.has(k)) took.push(`the removal of ${describe(s)}`);
5946
+ if (current && (current.like ?? 'none') !== (prev.like ?? 'none'))
5947
+ took.push(
5948
+ `base ${current.like ?? 'none'} (back to ${prev.like ?? 'none'})`,
5949
+ );
5950
+ if (current && current.mode !== prev.mode)
5951
+ took.push(`mode ${current.mode} (back to ${prev.mode})`);
5952
+ const undid =
5953
+ took.length === 0
5954
+ ? 'the last change'
5955
+ : took.length === 1
5956
+ ? took[0]
5957
+ : `${took.length} changes: ${took.join('; ')}`;
3295
5958
  return {
3296
5959
  type: 'themeEdit.undo',
3297
5960
  data: {
3298
5961
  theme,
3299
5962
  action: 'step',
5963
+ undid,
5964
+ ...(refusedSince
5965
+ ? {
5966
+ refusedBefore: `the last command (${refusedSince}) was refused and changed nothing, so this undid the change before it`,
5967
+ }
5968
+ : {}),
3300
5969
  undone,
3301
5970
  settings: prev.settings.length,
3302
5971
  stepsLeft: stepsLeft,
@@ -3320,3 +5989,14 @@ export async function editorStale(cwd, slug) {
3320
5989
  const data = loadTheme(cwd, slug);
3321
5990
  return staleBuild(cwd, slug, data) || null;
3322
5991
  }
5992
+
5993
+ /**
5994
+ * The notes the last build of the theme left (settings it could not write
5995
+ * as they are).
5996
+ * @param {unknown} ctx
5997
+ * @returns {string[]}
5998
+ */
5999
+ function buildNotes(ctx) {
6000
+ const notes = /** @type {{compileNotes?: unknown}} */ (ctx)?.compileNotes;
6001
+ return Array.isArray(notes) ? notes.map(String) : [];
6002
+ }