@astryxdesign/cli 0.7.15 → 0.7.16-canary.g3aa244b

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 (163) hide show
  1. package/README.md +5 -3
  2. package/api/build/_adapter.d.mts +1 -0
  3. package/api/build/blocks/blocks.d.mts +1 -0
  4. package/api/build/blocks/blocks.mjs +18 -1
  5. package/api/component/_adapter.d.mts +1 -1
  6. package/api/component/_adapter.mjs +28 -1
  7. package/api/doctor/_adapter.d.mts +35 -0
  8. package/api/doctor/_adapter.mjs +69 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.d.mts +18 -0
  11. package/api/doctor/doctor.doc.mjs +1 -1
  12. package/api/doctor/doctor.mjs +104 -4
  13. package/api/doctor/theme-checks.mjs +6 -10
  14. package/api/integration/add-contribution.mjs +3 -3
  15. package/api/integration/pack-check.mjs +14 -8
  16. package/api/integration/validate-integration.mjs +1 -1
  17. package/api/search/_adapter.mjs +15 -16
  18. package/api/search/_entries.d.mts +2 -1
  19. package/api/search/_entries.mjs +28 -1
  20. package/api/swizzle/_moduleGraph.mjs +1 -1
  21. package/api/theme/_adapter.d.mts +5 -2
  22. package/api/theme/_adapter.mjs +43 -12
  23. package/api/theme/_fork.mjs +1 -1
  24. package/api/theme/build/build.d.mts +116 -32
  25. package/api/theme/build/build.mjs +449 -102
  26. package/api/theme/eject/eject.mjs +22 -1
  27. package/api/theme/template/template.d.mts +19 -0
  28. package/api/theme/template/template.mjs +102 -25
  29. package/api/theme/theme.type.d.mts +5 -1
  30. package/api/theme/theme.type.mjs +2 -1
  31. package/api/theme/themeBuild.doc.mjs +3 -3
  32. package/api/theme/themeEject.doc.mjs +1 -1
  33. package/api/theme/themeTemplate.doc.mjs +9 -3
  34. package/api/theme-edit/_adapter.d.mts +32 -2
  35. package/api/theme-edit/_adapter.mjs +264 -40
  36. package/api/theme-edit/_check.d.mts +93 -4
  37. package/api/theme-edit/_check.mjs +1727 -223
  38. package/api/theme-edit/_color.d.mts +2 -8
  39. package/api/theme-edit/_color.mjs +292 -219
  40. package/api/theme-edit/_compiler.d.mts +1 -0
  41. package/api/theme-edit/_compiler.mjs +20 -1
  42. package/api/theme-edit/_context.d.mts +31 -1
  43. package/api/theme-edit/_context.mjs +445 -41
  44. package/api/theme-edit/_css.d.mts +60 -1
  45. package/api/theme-edit/_css.mjs +404 -28
  46. package/api/theme-edit/_edit.d.mts +25 -0
  47. package/api/theme-edit/_edit.mjs +1532 -149
  48. package/api/theme-edit/_how-commands.d.mts +11 -26
  49. package/api/theme-edit/_how-commands.mjs +30 -2
  50. package/api/theme-edit/_how-question.d.mts +7 -0
  51. package/api/theme-edit/_how-question.mjs +1304 -176
  52. package/api/theme-edit/_how.mjs +144 -30
  53. package/api/theme-edit/_overview.mjs +2 -0
  54. package/api/theme-edit/_palette.d.mts +38 -0
  55. package/api/theme-edit/_palette.mjs +305 -71
  56. package/api/theme-edit/_parts.d.mts +33 -0
  57. package/api/theme-edit/_parts.mjs +138 -9
  58. package/api/theme-edit/_png.d.mts +18 -0
  59. package/api/theme-edit/_png.mjs +95 -14
  60. package/api/theme-edit/_preview-app.d.mts +36 -1
  61. package/api/theme-edit/_preview-app.mjs +1415 -96
  62. package/api/theme-edit/_preview.d.mts +64 -3
  63. package/api/theme-edit/_preview.mjs +514 -31
  64. package/api/theme-edit/_project.d.mts +11 -0
  65. package/api/theme-edit/_project.mjs +46 -12
  66. package/api/theme-edit/_settings.d.mts +278 -5
  67. package/api/theme-edit/_settings.mjs +2741 -195
  68. package/api/theme-edit/_tables.d.mts +24 -0
  69. package/api/theme-edit/_tables.mjs +211 -149
  70. package/api/theme-edit/_vet.d.mts +42 -0
  71. package/api/theme-edit/_vet.mjs +144 -0
  72. package/api/theme-edit/theme-edit.type.d.mts +20 -2
  73. package/api/theme-edit/theme-edit.type.mjs +6 -2
  74. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  75. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  76. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  77. package/api/upgrade/registry/registry.mjs +6 -1
  78. package/assets/codemods/parse.mjs +2 -2
  79. package/assets/docs/tree/single-component.doc.mjs +11 -2
  80. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  81. package/assets/docs.generated.json +2 -2
  82. package/assets/preview-app/next.config.mjs +7 -1
  83. package/assets/preview-app/package.json +1 -0
  84. package/assets/preview-app/src/app/globals.css +1 -0
  85. package/assets/self-audit.generated.json +1 -1
  86. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  87. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  88. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  89. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  90. package/assets/templates/components.generated.json +1 -1
  91. package/assets/templates/pages/dashboard/page.tsx +1 -1
  92. package/authoring/doctypes/_schema.d.mts +52 -5
  93. package/authoring/doctypes/_schema.mjs +62 -7
  94. package/authoring/doctypes/base/type.ts +10 -0
  95. package/authoring/doctypes/component/component.doc.mjs +1 -1
  96. package/authoring/doctypes/function/function.doc.mjs +6 -0
  97. package/authoring/doctypes/function/type.ts +3 -0
  98. package/authoring/doctypes/legacy.mjs +5 -1
  99. package/authoring/index.d.ts +1 -0
  100. package/authoring/shadcn/source-variants.d.mts +1 -1
  101. package/authoring/shadcn/source-variants.mjs +32 -10
  102. package/clients/cli/build-id.generated.json +1 -1
  103. package/clients/cli/commands/doctor.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental/theme.mjs +239 -45
  105. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  106. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  108. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  109. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  110. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  111. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  112. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  113. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  114. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  115. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  116. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  117. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  118. package/clients/cli/commands/theme.mjs +190 -46
  119. package/clients/cli/formatters/index.mjs +7 -4
  120. package/clients/cli/lib/cli-error.mjs +9 -3
  121. package/clients/cli/lib/component-format.mjs +27 -9
  122. package/clients/cli/lib/json-shim.mjs +72 -2
  123. package/clients/cli/manifest.generated.json +1 -1
  124. package/clients/cli/run.mjs +49 -0
  125. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  126. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  127. package/foundation/agent-docs/agent-docs.mjs +3 -2
  128. package/foundation/config/config-writer.mjs +2 -2
  129. package/foundation/config/project.mjs +60 -14
  130. package/foundation/discovery/component-discovery.mjs +5 -17
  131. package/foundation/discovery/icon-set-writer.mjs +1 -1
  132. package/foundation/discovery/module-exports.mjs +1 -15
  133. package/foundation/discovery/template-adapter.mjs +44 -19
  134. package/foundation/discovery/template-source-tree.mjs +3 -16
  135. package/foundation/discovery/theme-discovery.d.mts +5 -1
  136. package/foundation/discovery/theme-discovery.mjs +61 -43
  137. package/foundation/fs/exact-codec.d.mts +35 -0
  138. package/foundation/fs/exact-codec.mjs +148 -0
  139. package/foundation/fs/gather-cache.d.mts +15 -5
  140. package/foundation/fs/gather-cache.mjs +129 -31
  141. package/foundation/fs/paths.d.mts +39 -0
  142. package/foundation/fs/paths.mjs +44 -11
  143. package/foundation/fs/read-record.mjs +11 -1
  144. package/foundation/integrations/contribution-fixes.mjs +1 -16
  145. package/foundation/integrations/may-have-integrations.mjs +3 -2
  146. package/foundation/integrations/public-imports.mjs +1 -1
  147. package/foundation/render/embedded-imports.mjs +1 -1
  148. package/foundation/render/host-exit.d.mts +8 -0
  149. package/foundation/render/host-exit.mjs +11 -0
  150. package/foundation/render/page-host.mjs +56 -10
  151. package/foundation/render/page-worker.mjs +14 -0
  152. package/foundation/render/render-page.mjs +37 -2
  153. package/foundation/response/error-codes.d.mts +2 -1
  154. package/foundation/response/error-codes.d.ts +1 -0
  155. package/foundation/response/error-codes.doc.mjs +5 -0
  156. package/foundation/response/error-codes.mjs +3 -0
  157. package/foundation/response/json.d.mts +15 -0
  158. package/foundation/response/json.mjs +52 -1
  159. package/foundation/response/response-types.doc.mjs +1 -1
  160. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  161. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  162. package/foundation/xle/browser.d.mts +2 -2
  163. package/package.json +7 -6
@@ -8,14 +8,26 @@
8
8
  * @position api/theme-edit — imported only by the adapter's operation helpers
9
9
  */
10
10
 
11
+ import {createHash} from 'node:crypto';
11
12
  import * as fs from 'node:fs';
12
13
  import {createRequire} from 'node:module';
13
14
  import * as path from 'node:path';
15
+ import {pathToFileURL} from 'node:url';
14
16
  import {AstryxError} from '../error.mjs';
15
- import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
17
+ import {EDITOR_STAMP, withPngText} from './_png.mjs';
18
+ import {
19
+ findDeclaredWorkspaceRoot,
20
+ findNodeModulesPackage,
21
+ homeFolder,
22
+ } from '../../foundation/fs/paths.mjs';
23
+ import {
24
+ detectPackageManager,
25
+ quoteCommandArgument,
26
+ } from '../../foundation/env/package-manager.mjs';
16
27
  import {
17
28
  CLOSEST_OPEN_FONT,
18
29
  FONT_ROLES,
30
+ FONTS,
19
31
  OPEN_FONTS,
20
32
  isDesktopFamily,
21
33
  oneSystemOf,
@@ -32,7 +44,11 @@ import {
32
44
  modesOf,
33
45
  nearest,
34
46
  refuse,
47
+ adoptOlderPicture,
48
+ editorWrote,
49
+ recordWritten,
35
50
  themeFiles,
51
+ refuseThemesNotFolder,
36
52
  } from './_settings.mjs';
37
53
  import {SHOWCASE_GROUPS, renderPreview, screenshot} from './_preview.mjs';
38
54
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
@@ -45,10 +61,13 @@ const E = ERROR_CODES;
45
61
  * @param {string} cwd
46
62
  */
47
63
  export function requireProject(cwd) {
48
- if (!isOutsideProject(cwd)) return;
49
- const pkg = path.join(cwd, 'package.json');
50
- // Yarn Plug'n'Play has no node_modules for the editor to read Core from.
51
- if (fs.existsSync(path.join(cwd, '.pnp.cjs')))
64
+ // One rule: the app is the nearest folder at or above cwd whose
65
+ // package.json lists @astryxdesign/core.
66
+ const app = coreApp(cwd);
67
+ if (!app) refuseNoApp(cwd);
68
+ // Yarn Plug'n'Play has no node_modules for the editor to read Core from:
69
+ // its .pnp.cjs sits at the app or at the workspace root above it.
70
+ if (pnpAbove(app))
52
71
  throw new AstryxError(
53
72
  "This app uses Yarn Plug'n'Play, which astryx experimental theme does not support: it reads the installed Core from node_modules. Set `nodeLinker: node-modules` in .yarnrc.yml and run yarn install. Nothing was written.",
54
73
  [
@@ -59,21 +78,11 @@ export function requireProject(cwd) {
59
78
  ],
60
79
  E.ERR_PROJECT_REQUIRED,
61
80
  );
62
- // A package.json with no Core: an app (or a workspace root) that needs it.
63
- if (fs.existsSync(pkg))
64
- throw new AstryxError(
65
- `@astryxdesign/core is not installed in this app (package.json here does not use it). astryx experimental theme checks every change against the installed Core: install it, or run the command from the package that uses it. Nothing was written.`,
66
- [{name: 'npm install @astryxdesign/core', reason: 'do this first'}],
67
- E.ERR_PROJECT_REQUIRED,
68
- );
81
+ if (findNodeModulesPackage(app, '@astryxdesign/core')) return;
82
+ // The app lists Core but it is not installed.
69
83
  throw new AstryxError(
70
- 'No package.json found. astryx experimental theme works inside an app project, which it writes the theme into and whose installed Core it checks every change against. Nothing was written.',
71
- [
72
- {
73
- name: 'npm init -y',
74
- reason: 'make a package.json here, then install @astryxdesign/core',
75
- },
76
- ],
84
+ `${path.relative(path.resolve(cwd), app) || 'This app'}'s package.json lists @astryxdesign/core, but it is not installed. astryx experimental theme checks every change against the installed Core: install the app's packages, then run the command again. Nothing was written.`,
85
+ [{name: installAll(app), reason: 'do this first, in the app'}],
77
86
  E.ERR_PROJECT_REQUIRED,
78
87
  );
79
88
  }
@@ -86,6 +95,7 @@ export function requireProject(cwd) {
86
95
  */
87
96
  export async function context(cwd) {
88
97
  requireProject(cwd);
98
+ refuseThemesNotFolder(cwd);
89
99
  const project = await openProject(cwd);
90
100
  /** @type {import('./_parts.mjs').PartData} */
91
101
  let parts;
@@ -114,22 +124,221 @@ export async function context(cwd) {
114
124
  parts,
115
125
  unchecked,
116
126
  uncheckedCode,
127
+ derived: await derivedVars(project.coreDir),
117
128
  };
118
129
  }
119
130
 
131
+ /**
132
+ * Core's registry of the variables a part's plain border-radius or padding
133
+ * also writes (a card's inner corners), or empty on a Core without it.
134
+ * @param {string} coreDir
135
+ * @returns {Promise<Record<string, Array<{property: string, vars?: string[], replaces?: boolean, expand?: string}>>>}
136
+ */
137
+ async function derivedVars(coreDir) {
138
+ const file = path.join(coreDir, 'dist', 'theme', 'derivedVarRegistry.js');
139
+ if (!fs.existsSync(file)) return {};
140
+ try {
141
+ const mod = await import(pathToFileURL(file).href);
142
+ return mod.derivedVarRegistry ?? {};
143
+ } catch {
144
+ return {};
145
+ }
146
+ }
147
+
120
148
  /** @param {unknown} e */
121
149
  const isRenderFailure = e =>
122
150
  e instanceof AstryxError &&
123
151
  (e.code === E.ERR_RENDER_FAILED ||
124
152
  e.code === E.ERR_RENDER_MISSING_DEPENDENCY);
125
153
 
154
+ /**
155
+ * The app a folder belongs to: the nearest folder at or above it whose
156
+ * package.json lists @astryxdesign/core (dependencies, devDependencies or
157
+ * peerDependencies), never the home folder; null when there is none.
158
+ * @param {string} cwd
159
+ * @returns {string | null}
160
+ */
161
+ export function coreApp(cwd) {
162
+ const home = homeFolder();
163
+ let dir = path.resolve(cwd);
164
+ // An installed package is never the app: resume above the outermost
165
+ // node_modules.
166
+ const nm = dir.split(path.sep).indexOf('node_modules');
167
+ if (nm > 0) dir = dir.split(path.sep).slice(0, nm).join(path.sep) || path.sep;
168
+ // A repository below the home folder is its own project: the home folder
169
+ // is the app only when the search did not come up out of another repo.
170
+ let crossedRepo = false;
171
+ for (;;) {
172
+ const listsCore = usesCore(readJson(path.join(dir, 'package.json')));
173
+ if (home && dir === home) return listsCore && !crossedRepo ? dir : null;
174
+ if (listsCore) return dir;
175
+ if (fs.existsSync(path.join(dir, '.git'))) crossedRepo = true;
176
+ const up = path.dirname(dir);
177
+ if (up === dir) return null;
178
+ dir = up;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Whether a Yarn Plug'n'Play loader (.pnp.cjs) is at the app folder or above
184
+ * it, up to its workspace root (or, outside a workspace, the repository
185
+ * root).
186
+ * @param {string} app
187
+ */
188
+ function pnpAbove(app) {
189
+ const root = findDeclaredWorkspaceRoot(app);
190
+ for (let dir = app; ; dir = path.dirname(dir)) {
191
+ if (fs.existsSync(path.join(dir, '.pnp.cjs'))) return true;
192
+ if (dir === root || (!root && fs.existsSync(path.join(dir, '.git'))))
193
+ return false;
194
+ if (path.dirname(dir) === dir) return false;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * The command that installs an app's packages, in its package manager.
200
+ * @param {string} dir
201
+ */
202
+ function installAll(dir) {
203
+ const pm = detectPackageManager(dir);
204
+ return pm === 'npm' || pm === 'npx' ? 'npm install' : `${pm} install`;
205
+ }
206
+
207
+ /**
208
+ * Refuse a folder no app above lists Core for: say where Core resolves
209
+ * from (when it does) and, inside a workspace, name the folders below its
210
+ * root whose package.json lists Core, each with the `cd` to run from.
211
+ * @param {string} cwd
212
+ * @returns {never}
213
+ */
214
+ function refuseNoApp(cwd) {
215
+ const start = path.resolve(cwd);
216
+ // A repository inside a home-folder app (a submodule, a vendored clone) is
217
+ // its own project: name the app above instead of claiming there is none.
218
+ const home = homeFolder();
219
+ if (
220
+ home &&
221
+ !path.relative(home, start).startsWith('..') &&
222
+ usesCore(readJson(path.join(home, 'package.json')))
223
+ ) {
224
+ const rel = path.relative(start, home) || '.';
225
+ throw new AstryxError(
226
+ `This folder is inside its own repository, below the app at ${rel} (your home folder): the theme editor does not reach out of a repository into an app around it. Run the command from the app. Nothing was written.`,
227
+ [
228
+ {
229
+ name: `cd ${quoteCommandArgument(rel)}`,
230
+ reason: 'run the command from the app',
231
+ },
232
+ ],
233
+ E.ERR_PROJECT_REQUIRED,
234
+ );
235
+ }
236
+ // Where Core resolves from: the nearest node_modules above that holds it.
237
+ const resolved =
238
+ findNodeModulesPackage(start, '@astryxdesign/core')?.packageDir ?? null;
239
+ const root = findDeclaredWorkspaceRoot(start);
240
+ const where = resolved
241
+ ? ` @astryxdesign/core resolves from ${path.relative(start, resolved) || '.'}, but the theme editor needs the app's package.json to list it.`
242
+ : '';
243
+ if (root) {
244
+ const apps = appsBelow(root)
245
+ .map(a => path.relative(start, a) || '.')
246
+ .sort();
247
+ throw new AstryxError(
248
+ `${path.relative(start, root) || 'This folder'} is a workspace root${root === start ? '' : ` (${path.relative(root, start)} is not an app that uses @astryxdesign/core)`}, not an app: a theme belongs in an app whose package.json lists @astryxdesign/core.${where}${apps.length ? ` The workspace's apps that use it: ${apps.join(', ')}.` : ''} Run the command from the app that uses it. Nothing was written.`,
249
+ apps.slice(0, 4).map(a => ({
250
+ name: `cd ${quoteCommandArgument(a.startsWith('-') ? `./${a}` : a)}`,
251
+ reason: 'run the command from this app',
252
+ })),
253
+ E.ERR_PROJECT_REQUIRED,
254
+ );
255
+ }
256
+ if (fs.existsSync(path.join(start, 'package.json')) || resolved)
257
+ throw new AstryxError(
258
+ `${fs.existsSync(path.join(start, 'package.json')) ? '@astryxdesign/core is not installed in this app (package.json here does not use it).' : 'No package.json at or above this folder lists @astryxdesign/core.'}${where} astryx experimental theme checks every change against the installed Core: install it, or run the command from the package that uses it. Nothing was written.`,
259
+ [
260
+ {
261
+ name: installLine(start, ['@astryxdesign/core']),
262
+ reason: 'do this first',
263
+ },
264
+ ],
265
+ E.ERR_PROJECT_REQUIRED,
266
+ );
267
+ throw new AstryxError(
268
+ 'No package.json found. astryx experimental theme works inside an app project, which it writes the theme into and whose installed Core it checks every change against. Nothing was written.',
269
+ [
270
+ {
271
+ name: 'npm init -y',
272
+ reason: 'make a package.json here, then install @astryxdesign/core',
273
+ },
274
+ ],
275
+ E.ERR_PROJECT_REQUIRED,
276
+ );
277
+ }
278
+
279
+ /**
280
+ * The folders below a workspace root, up to three levels deep (node_modules
281
+ * and dot folders skipped), whose package.json lists Core.
282
+ * @param {string} root
283
+ * @returns {string[]}
284
+ */
285
+ function appsBelow(root) {
286
+ /** @type {string[]} */
287
+ const out = [];
288
+ /** @param {string} dir @param {number} depth */
289
+ const walk = (dir, depth) => {
290
+ if (depth > 6) return;
291
+ /** @type {fs.Dirent[]} */
292
+ let entries;
293
+ try {
294
+ entries = fs.readdirSync(dir, {withFileTypes: true});
295
+ } catch {
296
+ return;
297
+ }
298
+ for (const e of entries) {
299
+ if (
300
+ !e.isDirectory() ||
301
+ e.name === 'node_modules' ||
302
+ e.name.startsWith('.')
303
+ )
304
+ continue;
305
+ const sub = path.join(dir, e.name);
306
+ if (usesCore(readJson(path.join(sub, 'package.json')))) out.push(sub);
307
+ walk(sub, depth + 1);
308
+ }
309
+ };
310
+ walk(root, 1);
311
+ return out;
312
+ }
313
+
314
+ /** @param {string} file */
315
+ function readJson(file) {
316
+ try {
317
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
318
+ } catch {
319
+ return null;
320
+ }
321
+ }
322
+
323
+ /** Whether a package.json lists @astryxdesign/core itself. */
324
+ function usesCore(/** @type {any} */ json) {
325
+ if (!json || typeof json !== 'object') return false;
326
+ return ['dependencies', 'devDependencies', 'peerDependencies'].some(
327
+ k =>
328
+ json[k] != null &&
329
+ typeof json[k] === 'object' &&
330
+ !Array.isArray(json[k]) &&
331
+ Object.prototype.hasOwnProperty.call(json[k], '@astryxdesign/core'),
332
+ );
333
+ }
334
+
126
335
  /**
127
336
  * Why the components did not render, with the likely cause: two copies of
128
337
  * React (the app's and the one Core resolves) break every hook.
129
338
  * @param {import('./_project.mjs').ThemeProject} project
130
339
  * @param {string} message
131
340
  */
132
- function renderCause(project, message) {
341
+ export function renderCause(project, message) {
133
342
  /** @param {(id: string) => string} resolve */
134
343
  const reactOf = resolve => {
135
344
  try {
@@ -141,10 +350,15 @@ function renderCause(project, message) {
141
350
  const app = reactOf(project.req.resolve);
142
351
  let core = null;
143
352
  try {
144
- core = reactOf(
145
- createRequire(project.req.resolve('@astryxdesign/core/package.json'))
146
- .resolve,
147
- );
353
+ // Core's exports keep its package.json private: its folder is found by
354
+ // walking up from the entry the app resolves.
355
+ let dir = path.dirname(project.req.resolve('@astryxdesign/core'));
356
+ while (!fs.existsSync(path.join(dir, 'package.json'))) {
357
+ const up = path.dirname(dir);
358
+ if (up === dir) throw new Error('no package.json');
359
+ dir = up;
360
+ }
361
+ core = reactOf(createRequire(path.join(dir, 'package.json')).resolve);
148
362
  } catch {
149
363
  // No Core package file: nothing to compare.
150
364
  }
@@ -172,24 +386,78 @@ export async function pictures(project, shots, modes) {
172
386
  const files = [];
173
387
  /** @type {string[]} */
174
388
  const cut = [];
389
+ /** @param {string} png @param {'light' | 'dark'} m */
390
+ const outOf = (png, m) =>
391
+ modes.length > 1 && m === 'dark' ? png.replace(/\.png$/, '-dark.png') : png;
392
+ /** The theme a picture's folder is, when it is a theme folder. @param {string} out */
393
+ const themeOf = out => {
394
+ const slug = path.basename(path.dirname(out));
395
+ return path.resolve(path.dirname(out)) ===
396
+ path.resolve(themeFiles(project.cwd, slug).dir)
397
+ ? slug
398
+ : null;
399
+ };
400
+ // A picture is written only over a picture the editor took, unchanged
401
+ // since: a file of the user's by that name blocks every picture, and is
402
+ // named.
403
+ /** Pictures an older editor took, now recorded. @type {string[]} */
404
+ const adopted = [];
405
+ const blocked = shots
406
+ .flatMap(({png}) => modes.map(m => outOf(png, m)))
407
+ .filter(out => {
408
+ const slug = themeOf(out);
409
+ if (!slug || !fs.existsSync(out) || editorWrote(project.cwd, slug, out))
410
+ return false;
411
+ if (adoptOlderPicture(project.cwd, slug, out)) {
412
+ adopted.push(path.relative(project.cwd, out));
413
+ return false;
414
+ }
415
+ return true;
416
+ });
417
+ if (blocked.length)
418
+ return {
419
+ files,
420
+ problem: `${blocked.map(f => path.relative(project.cwd, f)).join(', ')} ${blocked.length === 1 ? 'is a file' : 'are files'} the editor did not write (or changed since it did), so no picture was taken and ${blocked.length === 1 ? 'it is' : 'they are'} left as ${blocked.length === 1 ? 'it is' : 'they are'}`,
421
+ };
175
422
  for (const {html, png} of shots) {
176
423
  for (const m of modes) {
177
- const out =
178
- modes.length > 1 && m === 'dark'
179
- ? png.replace(/\.png$/, '-dark.png')
180
- : png;
424
+ const out = outOf(png, m);
181
425
  const r = await screenshot(project, html, out, m);
182
426
  if (!r.ok) return {files, problem: r.reason};
183
427
  files.push(r.file);
428
+ // A picture in a theme folder is recorded as the editor's, so a later
429
+ // change removes it and never a picture of the user's.
430
+ const slug = themeOf(out);
431
+ if (slug) {
432
+ // Stamped with the editor's mark and the theme, then recorded.
433
+ try {
434
+ fs.writeFileSync(
435
+ out,
436
+ withPngText(fs.readFileSync(out), EDITOR_STAMP, slug),
437
+ );
438
+ } catch {
439
+ // An unstamped picture is still recorded below.
440
+ }
441
+ recordWritten(project.cwd, slug, [out]);
442
+ }
184
443
  if (r.cut) cut.push(r.file);
185
444
  }
186
445
  }
446
+ const adoptedNote = adopted.length
447
+ ? `${adopted.join(', ')} ${adopted.length === 1 ? 'was' : 'were'} taken by an earlier version of the editor and ${adopted.length === 1 ? 'is' : 'are'} now recorded as its own`
448
+ : null;
187
449
  return {
188
450
  files,
189
451
  // A picture of the window shows the top of a longer page only.
190
- problem: cut.length
191
- ? `${cut.join(', ')} show${cut.length === 1 ? 's' : ''} the top 2400 pixels of the page only (Chrome takes the window, not the whole page); open the .html beside ${cut.length === 1 ? 'it' : 'them'} to see all of it, or install Playwright (${installLine(project.cwd, ['playwright'])}) for whole-page pictures`
192
- : null,
452
+ problem:
453
+ [
454
+ adoptedNote,
455
+ cut.length
456
+ ? `${cut.join(', ')} show${cut.length === 1 ? 's' : ''} the top 2400 pixels of the page only (Chrome takes the window, not the whole page); open the .html beside ${cut.length === 1 ? 'it' : 'them'} to see all of it, or install Playwright (${installLine(project.cwd, ['playwright'])}) for whole-page pictures`
457
+ : null,
458
+ ]
459
+ .filter(Boolean)
460
+ .join('; ') || null,
193
461
  };
194
462
  }
195
463
 
@@ -219,6 +487,18 @@ export function fontNotes(ctx, data) {
219
487
  : `${family} is not installed, so it does not load: the previews and the app show the next font in the stack. Install it: ${installLine(ctx.project.cwd, [pkg])}. Then the preview imports it on the next set or show, and the app imports it once: import '${pkg}'; Until then, the closest font that needs no install is ${near}: ${P} set ${data.name} font ${near}`,
220
488
  );
221
489
  }
490
+ // A family the editor's own presets lead with, where the preset gets no
491
+ // note (Comic Sans MS, of comic), is no more a font to load typed by name.
492
+ const presetFamily = (/** @type {string} */ family) => {
493
+ const f = family.replace(/["']/g, '').trim().toLowerCase();
494
+ // A one-system font keeps its note, preset or not.
495
+ if (oneSystemOf(family.replace(/["']/g, '').trim())) return false;
496
+ return Object.entries(FONTS).some(
497
+ ([k, [first]]) =>
498
+ (SYSTEM_FONTS.includes(k) || k === 'comic' || k === 'rounded') &&
499
+ first.replace(/["']/g, '').trim().toLowerCase() === f,
500
+ );
501
+ };
222
502
  for (const s of data.settings) {
223
503
  if (
224
504
  s.thing !== 'font' ||
@@ -228,7 +508,8 @@ export function fontNotes(ctx, data) {
228
508
  fontOf(s.value).pkg ||
229
509
  packages.some(x => x.of === s) ||
230
510
  s.value === 'rounded' ||
231
- s.value === 'comic'
511
+ s.value === 'comic' ||
512
+ presetFamily(fontOf(s.value).family)
232
513
  )
233
514
  continue;
234
515
  const family = fontOf(s.value).family.replace(/["']/g, '').toLowerCase();
@@ -258,11 +539,21 @@ export function fontNotes(ctx, data) {
258
539
  * What a change did to part styles (component settings), one line each.
259
540
  * @param {any} before
260
541
  * @param {any} after
542
+ * @param {any} [base] the base theme, whose own values a write that repeats them does not change
261
543
  * @returns {string[]}
262
544
  */
263
- export function styledChanges(before, after) {
545
+ export function styledChanges(before, after, base) {
264
546
  /** @type {string[]} */
265
547
  const out = [];
548
+ /** A value as CSS reads it, for comparing. @param {any} v */
549
+ const plain = v =>
550
+ (Array.isArray(v) && v.length === 2
551
+ ? `light-dark(${v[0]}, ${v[1]})`
552
+ : String(v ?? '')
553
+ )
554
+ .replace(/\s+/g, ' ')
555
+ .trim()
556
+ .toLowerCase();
266
557
  const a = before?.components ?? {};
267
558
  const b = after?.components ?? {};
268
559
  for (const target of new Set([...Object.keys(a), ...Object.keys(b)])) {
@@ -279,6 +570,14 @@ export function styledChanges(before, after) {
279
570
  : p.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
280
571
  for (const prop of new Set([...Object.keys(x), ...Object.keys(y)])) {
281
572
  if (JSON.stringify(x[prop]) === JSON.stringify(y[prop])) continue;
573
+ // Writing what the base theme already shows there changes nothing.
574
+ const shown = base?.components?.[target]?.[key]?.[prop];
575
+ if (
576
+ x[prop] === undefined &&
577
+ shown !== undefined &&
578
+ plain(shown) === plain(y[prop])
579
+ )
580
+ continue;
282
581
  const where = `${target}${key === 'base' ? '' : ` ${key}`}`;
283
582
  // A state block (`:hover`) lists each property it changes.
284
583
  if (
@@ -314,8 +613,17 @@ export function styledChanges(before, after) {
314
613
  `typography ${role}: ${
315
614
  x
316
615
  ? Object.entries(x)
317
- .map(([k, v]) => `${k} ${v}`)
318
- .join(', ')
616
+ .map(
617
+ ([k, v]) =>
618
+ `${k} ${
619
+ v && typeof v === 'object'
620
+ ? Object.entries(v)
621
+ .map(([a, b]) => `${a}: ${b}`)
622
+ .join(', ')
623
+ : v
624
+ }`,
625
+ )
626
+ .join('; ')
319
627
  : '(removed)'
320
628
  }`,
321
629
  );
@@ -356,7 +664,21 @@ export async function previewAfter(ctx, slug, data, png) {
356
664
  const f = themeFiles(ctx.project.cwd, slug);
357
665
  // The sheet of every component is made by show only: after a change it
358
666
  // says, at its top, that it shows the theme as it was.
359
- const sheetStale = markSheetStale(f.sheet, slug);
667
+ const sheetStale = markSheetStale(f.sheet, slug, ctx.project.cwd);
668
+ // Section sheets the editor made (they carry its stamp) go out of date the
669
+ // same way; any other file is left as it is.
670
+ const sectionsStale = (
671
+ fs.existsSync(f.dir) ? fs.readdirSync(f.dir) : []
672
+ ).filter(n => {
673
+ if (!/^sheet-[a-z-]+\.html$/.test(n)) return false;
674
+ const file = path.join(f.dir, n);
675
+ try {
676
+ if (!SHEET_STAMP.test(fs.readFileSync(file, 'utf8'))) return false;
677
+ } catch {
678
+ return false;
679
+ }
680
+ return markSheetStale(file, slug, ctx.project.cwd);
681
+ });
360
682
  const shots =
361
683
  png && preview
362
684
  ? await pictures(
@@ -370,31 +692,113 @@ export async function previewAfter(ctx, slug, data, png) {
370
692
  pictures: shots.files,
371
693
  pictureProblem: shots.problem,
372
694
  notChecked: notChecked(cause),
373
- ...(sheetStale
695
+ ...(sheetStale && !sectionsStale.length
374
696
  ? {
375
697
  sheetStale: `sheet.html shows ${slug} as it was before this change; ${P} show ${slug} makes it again`,
376
698
  }
377
- : {}),
699
+ : sectionsStale.length
700
+ ? {
701
+ sheetStale: `${[...(sheetStale ? ['sheet.html'] : []), ...sectionsStale].join(', ')} show ${slug} as it was before this change; ${[
702
+ ...(sheetStale
703
+ ? [`${P} show ${slug} makes sheet.html again`]
704
+ : []),
705
+ ...sectionsStale.map(
706
+ n =>
707
+ `${P} show ${slug} --section ${n.replace(/^sheet-|\.html$/g, '')} makes ${n} again`,
708
+ ),
709
+ ].join(', ')}`,
710
+ }
711
+ : {}),
378
712
  };
379
713
  }
380
714
 
381
715
  const STALE_MARK = '<!-- astryx: sheet older than the theme -->';
382
716
 
717
+ /** The build a full sheet was made from, recorded in the sheet. */
718
+ const SHEET_STAMP = /<!-- astryx: sheet of build ([0-9a-f]{16}) -->/;
719
+
720
+ /** @param {string} s */
721
+ const escapeForRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
722
+
723
+ /**
724
+ * A hash of a theme's built stylesheet and module, or null when either is
725
+ * missing.
726
+ * @param {string} cwd
727
+ * @param {string} slug
728
+ */
729
+ function buildHash(cwd, slug) {
730
+ const f = themeFiles(cwd, slug);
731
+ try {
732
+ return createHash('sha256')
733
+ .update(fs.readFileSync(f.css))
734
+ .update('\0')
735
+ .update(fs.readFileSync(f.js))
736
+ .digest('hex')
737
+ .slice(0, 16);
738
+ } catch {
739
+ return null;
740
+ }
741
+ }
742
+
743
+ /**
744
+ * Record in a freshly made full sheet the build it shows.
745
+ * @param {string} file
746
+ * @param {string} slug
747
+ * @param {string} cwd
748
+ */
749
+ export function stampSheet(file, slug, cwd) {
750
+ const hash = buildHash(cwd, slug);
751
+ if (!hash) return;
752
+ try {
753
+ const html = fs.readFileSync(file, 'utf8').replace(SHEET_STAMP, '');
754
+ // At the end: a comment before the doctype would put the page in
755
+ // quirks mode.
756
+ writeWhole(
757
+ file,
758
+ `${html.trimEnd()}\n<!-- astryx: sheet of build ${hash} -->\n`,
759
+ );
760
+ } catch (e) {
761
+ if (/** @type {any} */ (e)?.lockLost) throw e;
762
+ }
763
+ }
764
+
383
765
  /**
384
766
  * Put a notice at the top of a sheet the last change made out of date
385
- * (once). Returns whether there is such a sheet.
767
+ * (once), or take it off a sheet made from the build there is now.
768
+ * Returns whether the sheet is out of date.
386
769
  * @param {string} file
387
770
  * @param {string} slug
771
+ * @param {string} cwd
388
772
  */
389
- function markSheetStale(file, slug) {
773
+ function markSheetStale(file, slug, cwd) {
390
774
  let html;
391
775
  try {
392
776
  html = fs.readFileSync(file, 'utf8');
393
777
  } catch {
394
778
  return false;
395
779
  }
780
+ // A sheet made from the build there is now (a change, then its undo)
781
+ // shows the theme as it is: no banner, and the result says nothing.
782
+ const made = SHEET_STAMP.exec(html)?.[1];
783
+ if (made && made === buildHash(cwd, slug)) {
784
+ if (html.includes(STALE_MARK)) {
785
+ const clean = html.replace(
786
+ new RegExp(`${escapeForRegExp(STALE_MARK)}<div[^>]*>[\\s\\S]*?</div>`),
787
+ '',
788
+ );
789
+ try {
790
+ writeWhole(file, clean);
791
+ } catch (e) {
792
+ if (/** @type {any} */ (e)?.lockLost) throw e;
793
+ }
794
+ }
795
+ return false;
796
+ }
396
797
  if (html.includes(STALE_MARK)) return true;
397
- const banner = `${STALE_MARK}<div style="position:sticky;top:0;z-index:9999;padding:8px 12px;background:#fff3cd;color:#3d2c00;font:14px system-ui,sans-serif;border-bottom:1px solid #e0c870">This sheet shows ${slug} as it was before the last change. Run ${P} show ${slug} to make it again.</div>`;
798
+ // A section's sheet is made again by its own show.
799
+ const section = /^sheet-([a-z-]+)\.html$/.exec(path.basename(file))?.[1];
800
+ const again = `${P} show ${slug}${section ? ` --section ${section}` : ''}`;
801
+ const banner = `${STALE_MARK}<div style="position:sticky;top:0;z-index:9999;padding:8px 12px;background:#fff3cd;color:#3d2c00;font:14px system-ui,sans-serif;border-bottom:1px solid #e0c870">This sheet shows ${slug} as it was before the last change. Run ${again} to make it again.</div>`;
398
802
  const at = html.search(/<body[^>]*>/i);
399
803
  const next =
400
804
  at < 0 ? banner + html : html.replace(/<body[^>]*>/i, m => `${m}${banner}`);