@astryxdesign/cli 0.7.14-canary.gfdb9213 → 0.7.14

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 (95) hide show
  1. package/CHANGELOG.md +197 -0
  2. package/api/theme/_adapter.d.mts +33 -0
  3. package/api/theme/_adapter.mjs +352 -16
  4. package/api/theme/build/build.mjs +261 -10
  5. package/api/theme/eject/eject.mjs +13 -1
  6. package/api/theme/list/list.mjs +11 -2
  7. package/api/theme/template/template.mjs +139 -6
  8. package/api/theme/theme.type.d.mts +15 -1
  9. package/api/theme/theme.type.mjs +9 -3
  10. package/api/theme/themeAdd.doc.mjs +1 -1
  11. package/api/theme/themeBuild.doc.mjs +10 -2
  12. package/api/theme/themeEject.doc.mjs +2 -2
  13. package/api/theme/themeListAvailable.doc.mjs +1 -1
  14. package/api/theme/themeRemove.doc.mjs +1 -1
  15. package/api/theme/themeTemplate.doc.mjs +8 -0
  16. package/api/theme/themeUse.doc.mjs +1 -1
  17. package/api/theme-edit/_adapter.d.mts +10 -2
  18. package/api/theme-edit/_adapter.mjs +52 -31
  19. package/api/theme-edit/_check.d.mts +28 -25
  20. package/api/theme-edit/_check.mjs +586 -548
  21. package/api/theme-edit/_color.d.mts +28 -2
  22. package/api/theme-edit/_color.mjs +306 -68
  23. package/api/theme-edit/_compiler.d.mts +8 -4
  24. package/api/theme-edit/_compiler.mjs +30 -27
  25. package/api/theme-edit/_context.d.mts +10 -4
  26. package/api/theme-edit/_context.mjs +21 -4
  27. package/api/theme-edit/_edit.mjs +300 -43
  28. package/api/theme-edit/_how-commands.d.mts +91 -0
  29. package/api/theme-edit/_how-commands.mjs +269 -0
  30. package/api/theme-edit/_how-question.d.mts +57 -0
  31. package/api/theme-edit/_how-question.mjs +2574 -0
  32. package/api/theme-edit/_how.d.mts +25 -17
  33. package/api/theme-edit/_how.mjs +727 -305
  34. package/api/theme-edit/_palette.d.mts +127 -19
  35. package/api/theme-edit/_palette.mjs +1313 -399
  36. package/api/theme-edit/_parts.mjs +36 -3
  37. package/api/theme-edit/_png.d.mts +18 -6
  38. package/api/theme-edit/_png.mjs +135 -25
  39. package/api/theme-edit/_preview-app.d.mts +26 -7
  40. package/api/theme-edit/_preview-app.mjs +1611 -280
  41. package/api/theme-edit/_preview.d.mts +4 -2
  42. package/api/theme-edit/_preview.mjs +18 -7
  43. package/api/theme-edit/_settings.d.mts +56 -5
  44. package/api/theme-edit/_settings.mjs +197 -49
  45. package/api/theme-edit/_tables.d.mts +0 -12
  46. package/api/theme-edit/_tables.mjs +24 -97
  47. package/api/theme-edit/theme-edit.type.d.mts +22 -5
  48. package/api/theme-edit/theme-edit.type.mjs +17 -6
  49. package/api/theme-edit/themeEditHow.doc.mjs +13 -3
  50. package/api/theme-edit/themeEditNew.doc.mjs +2 -1
  51. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +16 -4
  52. package/api/theme-edit/themeEditPreviewApp.doc.mjs +12 -4
  53. package/api/theme-edit/themeEditPreviewList.doc.mjs +9 -1
  54. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +27 -2
  55. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  56. package/assets/docs.generated.json +1 -0
  57. package/assets/preview-app/gitignore +3 -0
  58. package/assets/templates/components.generated.json +1 -0
  59. package/clients/cli/bin/astryx.mjs +37 -5
  60. package/clients/cli/commands/experimental/theme.mjs +231 -31
  61. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +14 -5
  62. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +0 -1
  63. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  64. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +3 -2
  65. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  66. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +2 -2
  67. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  68. package/clients/cli/commands/experimental-theme-targets.doc.mjs +1 -1
  69. package/clients/cli/commands/experimental-theme.doc.mjs +2 -2
  70. package/clients/cli/commands/theme-build.doc.mjs +1 -1
  71. package/clients/cli/commands/theme-eject.doc.mjs +3 -3
  72. package/clients/cli/commands/theme-remove.doc.mjs +2 -2
  73. package/clients/cli/commands/theme-template.doc.mjs +11 -4
  74. package/clients/cli/commands/theme.mjs +104 -40
  75. package/clients/cli/commands.generated.json +1 -0
  76. package/clients/cli/index.mjs +96 -4
  77. package/clients/cli/lib/json-shim.mjs +29 -1
  78. package/foundation/config/project.d.mts +16 -2
  79. package/foundation/config/project.mjs +40 -6
  80. package/foundation/config/theme-state.d.mts +9 -0
  81. package/foundation/config/theme-state.mjs +20 -1
  82. package/foundation/discovery/template-adapter.d.mts +12 -1
  83. package/foundation/discovery/template-adapter.mjs +24 -1
  84. package/foundation/discovery/template-needs.d.mts +7 -0
  85. package/foundation/discovery/template-needs.mjs +117 -8
  86. package/foundation/discovery/template-source-tree.d.mts +5 -1
  87. package/foundation/discovery/template-source-tree.mjs +6 -4
  88. package/foundation/discovery/theme-discovery.d.mts +14 -3
  89. package/foundation/discovery/theme-discovery.mjs +45 -12
  90. package/foundation/doc-compiler/import.mjs +68 -3
  91. package/foundation/doc-compiler/stored-docs.d.mts +27 -0
  92. package/foundation/doc-compiler/stored-docs.mjs +65 -0
  93. package/foundation/fs/fs-error.d.mts +17 -0
  94. package/foundation/fs/fs-error.mjs +34 -0
  95. package/package.json +6 -6
@@ -9,12 +9,16 @@
9
9
  * regeneration through the shared atomic write transaction.
10
10
  */
11
11
 
12
+ import * as crypto from 'node:crypto';
12
13
  import * as fs from 'node:fs';
13
14
  import * as path from 'node:path';
15
+ import {createRequire} from 'node:module';
14
16
  import {
15
17
  findCarriedCoreDir,
18
+ findPackageRoot,
16
19
  requireCoreDir,
17
20
  } from '../../foundation/fs/paths.mjs';
21
+ import {tryLock, userCacheDir} from '../../foundation/release/cache.mjs';
18
22
  import {Project} from '../../foundation/config/project.mjs';
19
23
  import {
20
24
  BUNDLED_THEME_PACKAGE,
@@ -30,7 +34,9 @@ import {
30
34
  } from '../../foundation/discovery/theme-imports.mjs';
31
35
  import {
32
36
  findThemeProject,
37
+ editorThemeRecord,
33
38
  isLocalThemeOwner,
39
+ LOCAL_THEME_ROOT,
34
40
  ThemeStateError,
35
41
  planThemeAppWrite,
36
42
  readThemeState,
@@ -46,6 +52,8 @@ import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';
46
52
  import {importThemeArtifact} from '../../foundation/fs/module-loader.mjs';
47
53
  import {applyWrites} from '../integration/add-helpers.mjs';
48
54
  import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
55
+ import {fsErrorMessage} from '../../foundation/fs/fs-error.mjs';
56
+ import {analyzeTemplateNeeds} from '../../foundation/discovery/template-needs.mjs';
49
57
 
50
58
  export {BUNDLED_THEME_PACKAGE, THEMES_DIR};
51
59
 
@@ -95,23 +103,44 @@ function availableBundledThemes() {
95
103
  * absent theme from an installed package whose theme descriptors are broken.
96
104
  * @param {string} cwd
97
105
  * @param {{includeLocal?: boolean}} [options]
98
- * @returns {Promise<{themes: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[], issues: Array<import('../../foundation/integrations/issue').AstryxIntegrationIssue & {package: string}>}>}
106
+ * @returns {Promise<{themes: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[], issues: Array<import('../../foundation/integrations/issue').AstryxIntegrationIssue & {package: string}>, skipped: SkippedLocalTheme[]}>}
99
107
  */
100
108
  async function availableThemeState(cwd, {includeLocal = true} = {}) {
101
109
  let project;
102
110
  try {
103
111
  project = await Project.load(cwd);
104
112
  } catch {
105
- return {themes: availableBundledThemes(), issues: []};
113
+ return {themes: availableBundledThemes(), issues: [], skipped: []};
106
114
  }
107
115
  try {
108
- const themes = await project.themes({includeLocal});
109
- return {themes, issues: await project.issues()};
116
+ // One broken local folder must not hide every other theme: it is
117
+ // skipped with its reason, and only a lookup of that slug fails.
118
+ const themes = await project.themes({includeLocal, skipBrokenLocal: true});
119
+ return {
120
+ themes,
121
+ issues: await project.issues(),
122
+ skipped: project.skippedLocalThemes(),
123
+ };
110
124
  } catch (error) {
111
125
  throw asThemeError(error);
112
126
  }
113
127
  }
114
128
 
129
+ /**
130
+ * A local theme folder that failed validation and was left out.
131
+ * @typedef {{slug: string, path: string, reason: string}} SkippedLocalTheme
132
+ */
133
+
134
+ /**
135
+ * Available themes, and the local folders left out because they are broken.
136
+ * @param {string} [cwd]
137
+ * @returns {Promise<{themes: import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[], skipped: SkippedLocalTheme[]}>}
138
+ */
139
+ export async function listAvailableThemeState(cwd = process.cwd()) {
140
+ const {themes, skipped} = await availableThemeState(cwd);
141
+ return {themes, skipped};
142
+ }
143
+
115
144
  /**
116
145
  * Bundled themes plus local and installed integration themes available to the
117
146
  * project.
@@ -120,7 +149,28 @@ async function availableThemeState(cwd, {includeLocal = true} = {}) {
120
149
  * @returns {Promise<import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]>}
121
150
  */
122
151
  export async function listAvailableThemes(cwd = process.cwd(), options = {}) {
123
- return (await availableThemeState(cwd, options)).themes;
152
+ const {themes, skipped} = await availableThemeState(cwd, options);
153
+ skippedLocalThemesOf.set(themes, skipped);
154
+ return themes;
155
+ }
156
+
157
+ /**
158
+ * The broken local folders left out of each list `listAvailableThemes`
159
+ * returned, so a recorded theme that is only broken reports its reason.
160
+ * @type {WeakMap<object, SkippedLocalTheme[]>}
161
+ */
162
+ const skippedLocalThemesOf = new WeakMap();
163
+
164
+ /**
165
+ * The error for a local theme folder that fails validation.
166
+ * @param {SkippedLocalTheme} broken
167
+ */
168
+ function brokenLocalThemeError(broken) {
169
+ return new AstryxError(
170
+ `Local theme "${broken.slug}" in ${broken.path} is broken: ${broken.reason}`,
171
+ undefined,
172
+ ERROR_CODES.ERR_THEME_INVALID,
173
+ );
124
174
  }
125
175
 
126
176
  /** @param {unknown} error */
@@ -344,6 +394,77 @@ export default {
344
394
  `;
345
395
  }
346
396
 
397
+ /**
398
+ * Refuse a fork folder that already belongs to something else. `--overwrite`
399
+ * replaces the files of a re-fork of the SAME theme. It never writes into a
400
+ * theme that the theme editor made (its `palette.config.json` is the editor's
401
+ * state), and never mixes two forks, whose shared file names (`icons.tsx`,
402
+ * `palette.config.json`) would break the first one.
403
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
404
+ * @param {string} dir
405
+ * @param {string} cwd
406
+ */
407
+ function assertEjectTargetFree(theme, dir, cwd) {
408
+ /** @type {string[]} */
409
+ let entries;
410
+ try {
411
+ if (!fs.statSync(dir).isDirectory()) return;
412
+ entries = fs.readdirSync(dir);
413
+ } catch {
414
+ return;
415
+ }
416
+ const rel = path.relative(cwd, dir) || '.';
417
+ const isDefault =
418
+ path.resolve(cwd, defaultEjectTarget(theme.slug)) === path.resolve(dir);
419
+ const suggestion = isDefault
420
+ ? undefined
421
+ : [
422
+ {
423
+ name: formatCliCommand(`theme eject ${theme.slug}`, cwd),
424
+ reason: `fork into ${defaultEjectTarget(theme.slug).split(path.sep).join('/')}`,
425
+ },
426
+ ];
427
+ const editorRecord = editorThemeRecord(dir);
428
+ if (editorRecord) {
429
+ throw new AstryxError(
430
+ `${rel} holds a theme made by the theme editor (${editorRecord}). Eject does not write into it, even with --overwrite.`,
431
+ suggestion,
432
+ ERROR_CODES.ERR_FILE_EXISTS,
433
+ );
434
+ }
435
+ const ownFiles = new Set(theme.files.map(name => path.basename(name)));
436
+ for (const name of entries) {
437
+ const otherDescriptor =
438
+ name.endsWith('.doc.mjs') && !ownFiles.has(name)
439
+ ? themeDescriptorName(path.join(dir, name))
440
+ : null;
441
+ const otherEntry =
442
+ /Theme\.(?:ts|tsx|mts)$/.test(name) && !ownFiles.has(name);
443
+ if ((otherDescriptor && otherDescriptor !== theme.slug) || otherEntry) {
444
+ throw new AstryxError(
445
+ `${rel} holds another theme (${name}). Eject does not mix two themes in one folder, even with --overwrite.`,
446
+ suggestion,
447
+ ERROR_CODES.ERR_FILE_EXISTS,
448
+ );
449
+ }
450
+ }
451
+ }
452
+
453
+ /**
454
+ * The `name` of a theme descriptor, read as text so a broken file cannot run.
455
+ * @param {string} file
456
+ * @returns {string | null}
457
+ */
458
+ function themeDescriptorName(file) {
459
+ try {
460
+ const text = fs.readFileSync(file, 'utf-8');
461
+ if (!/type:\s*['"]theme['"]/.test(text)) return null;
462
+ return /\bname:\s*['"]([^'"]+)['"]/.exec(text)?.[1] ?? null;
463
+ } catch {
464
+ return null;
465
+ }
466
+ }
467
+
347
468
  /**
348
469
  * Publish one theme's complete source inventory as an atomic local fork.
349
470
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme} theme
@@ -400,6 +521,8 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
400
521
  }
401
522
  }
402
523
 
524
+ assertEjectTargetFree(theme, resolvedDir, cwd);
525
+
403
526
  if (!overwrite) {
404
527
  const existing = writes.find(write => fs.existsSync(write.dest));
405
528
  if (existing) {
@@ -439,17 +562,41 @@ export function ejectThemeFiles(theme, {cwd, targetPath, overwrite = false}) {
439
562
  ERROR_CODES.ERR_PATH_TRAVERSAL,
440
563
  );
441
564
  }
442
- const message = error instanceof Error ? error.message : String(error);
443
- throw new AstryxError(
444
- `Failed to write theme files: ${message}`,
445
- undefined,
446
- ERROR_CODES.ERR_WRITE_FAILED,
447
- );
565
+ const message =
566
+ fsErrorMessage(error, path.relative(cwd, resolvedDir) || '.') ??
567
+ `Failed to write theme files: ${error instanceof Error ? error.message : String(error)}`;
568
+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
448
569
  }
449
570
 
450
571
  return path.relative(cwd, resolvedDir) || '.';
451
572
  }
452
573
 
574
+ /**
575
+ * The packages the fork imports that the app does not declare. A fork that
576
+ * imports a missing package (bundled icon sets use `lucide-react`) fails to
577
+ * build, so the receipt names them with an install command.
578
+ * @param {string} outputDir fork folder, relative to cwd
579
+ * @param {string[]} files
580
+ * @param {string} cwd
581
+ */
582
+ export function forkNeeds(outputDir, files, cwd) {
583
+ const source = files
584
+ .filter(name => /\.(?:[cm]?[jt]sx?)$/.test(name))
585
+ .map(name => {
586
+ try {
587
+ return fs.readFileSync(path.resolve(cwd, outputDir, name), 'utf-8');
588
+ } catch {
589
+ return '';
590
+ }
591
+ })
592
+ .join('\n');
593
+ const {missingPackages, installCommand} = analyzeTemplateNeeds(
594
+ source,
595
+ findPackageRoot(cwd) ?? path.resolve(cwd),
596
+ );
597
+ return {missingPackages, installCommand};
598
+ }
599
+
453
600
  /** @param {unknown} error */
454
601
  function asThemeError(error) {
455
602
  if (error instanceof AstryxError) return error;
@@ -472,7 +619,7 @@ function asThemeError(error) {
472
619
  */
473
620
  export async function findTheme(slug, options = {}) {
474
621
  if (!slug) return undefined;
475
- const {themes, issues} = await availableThemeState(
622
+ const {themes, issues, skipped} = await availableThemeState(
476
623
  options.cwd ?? process.cwd(),
477
624
  {includeLocal: options.includeLocal},
478
625
  );
@@ -482,6 +629,14 @@ export async function findTheme(slug, options = {}) {
482
629
  theme.slug.toLowerCase() === normalized &&
483
630
  (options.package == null || theme.package === options.package),
484
631
  );
632
+ const broken = skipped.find(entry => entry.slug.toLowerCase() === normalized);
633
+ if (
634
+ matches.length === 0 &&
635
+ broken &&
636
+ (options.package == null || options.package === LOCAL_THEME_ROOT)
637
+ ) {
638
+ throw brokenLocalThemeError(broken);
639
+ }
485
640
  if (matches.length === 0 && options.package != null) {
486
641
  const packageIssue = issues.find(
487
642
  issue => issue.package === options.package && issue.severity === 'error',
@@ -568,9 +723,13 @@ export function resolveRecordedThemes(state, available) {
568
723
  candidate =>
569
724
  candidate.slug === slug && themeImportPackage(candidate) === owner,
570
725
  );
726
+ const broken = isLocalThemeOwner(owner)
727
+ ? skippedLocalThemesOf.get(available)?.find(entry => entry.slug === slug)
728
+ : undefined;
729
+ if (!theme && broken) throw brokenLocalThemeError(broken);
571
730
  if (!theme) {
572
731
  throw new AstryxError(
573
- `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, then run \`${formatCliCommand(`theme add ${slug} --package ${owner}`, state.projectDir)}\`.`,
732
+ `Added theme "${slug}" from ${owner} is unavailable. Reinstall the package or restore the local theme, or drop it with \`${formatCliCommand(`theme remove ${slug}`, state.projectDir)}\`.`,
574
733
  undefined,
575
734
  ERROR_CODES.ERR_UNKNOWN_THEME,
576
735
  );
@@ -608,6 +767,7 @@ export async function resolveThemeApp(cwd = process.cwd()) {
608
767
  * @param {string} slug
609
768
  * @param {boolean} changed
610
769
  * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} available
770
+ * @param {string[]} [notes] what the command did beyond its change
611
771
  * @returns {Promise<import('./theme.type.mjs').ThemeAppResponse>}
612
772
  */
613
773
  async function writeThemeApp(
@@ -618,7 +778,26 @@ async function writeThemeApp(
618
778
  slug,
619
779
  changed,
620
780
  available,
781
+ notes = [],
621
782
  ) {
783
+ // A recorded theme whose folder or package is gone would make every later
784
+ // add, use and remove fail, and the record is generated, so it cannot be
785
+ // fixed by hand. Leave it out and say so. A theme that is only broken or
786
+ // not installed yet stays, and its refusal says how to fix it.
787
+ const kept = {...themes};
788
+ for (const [recorded, owner] of Object.entries(themes)) {
789
+ if (
790
+ recorded === defaultSlug ||
791
+ isRecordedThemeAvailable(recorded, owner, available) ||
792
+ !isRecordedThemeGone(recorded, owner, state.projectDir)
793
+ )
794
+ continue;
795
+ delete kept[recorded];
796
+ notes.push(
797
+ `Removed "${recorded}" from the app themes: ${owner} no longer provides it. Restore it, then run \`${formatCliCommand(`theme add ${recorded}`, state.projectDir)}\` to add it again.`,
798
+ );
799
+ }
800
+ themes = kept;
622
801
  const finalState = {...state, themes, defaultSlug, configured: true};
623
802
  const resolved = resolveRecordedThemes(finalState, available);
624
803
  let prepared;
@@ -665,10 +844,125 @@ async function writeThemeApp(
665
844
  changed,
666
845
  firstAdd: action === 'add' && !state.configured,
667
846
  },
847
+ ...(notes.length > 0 ? {notes} : {}),
668
848
  },
669
849
  };
670
850
  }
671
851
 
852
+ /**
853
+ * @param {string} slug
854
+ * @param {string} owner
855
+ * @param {import('../../foundation/discovery/theme-discovery.mjs').DiscoveredTheme[]} available
856
+ */
857
+ function isRecordedThemeAvailable(slug, owner, available) {
858
+ return available.some(
859
+ theme => theme.slug === slug && themeImportPackage(theme) === owner,
860
+ );
861
+ }
862
+
863
+ /**
864
+ * Is a recorded theme's source gone, not just broken? A local theme is gone
865
+ * when its folder is; a package theme when the app neither declares the
866
+ * package nor can resolve it.
867
+ * @param {string} slug
868
+ * @param {string} owner
869
+ * @param {string} projectDir
870
+ */
871
+ function isRecordedThemeGone(slug, owner, projectDir) {
872
+ if (isLocalThemeOwner(owner)) {
873
+ return !fs.existsSync(path.resolve(projectDir, owner, slug));
874
+ }
875
+ let declared = false;
876
+ try {
877
+ const pkg = JSON.parse(
878
+ fs.readFileSync(path.join(projectDir, 'package.json'), 'utf-8'),
879
+ );
880
+ declared = [
881
+ pkg.dependencies,
882
+ pkg.devDependencies,
883
+ pkg.peerDependencies,
884
+ pkg.optionalDependencies,
885
+ ].some(deps => deps != null && Object.hasOwn(deps, owner));
886
+ } catch {
887
+ // An unreadable package.json declares nothing.
888
+ }
889
+ if (declared) return false;
890
+ try {
891
+ createRequire(path.join(projectDir, 'package.json')).resolve(
892
+ `${owner}/package.json`,
893
+ );
894
+ return false;
895
+ } catch (error) {
896
+ // A package whose exports hide package.json is still installed.
897
+ return (
898
+ /** @type {NodeJS.ErrnoException} */ (error).code !==
899
+ 'ERR_PACKAGE_PATH_NOT_EXPORTED'
900
+ );
901
+ }
902
+ }
903
+
904
+ /** How long a theme command waits for another one changing the same app. */
905
+ const THEME_APP_LOCK_WAIT_MS = 15_000;
906
+
907
+ /**
908
+ * Run one read-modify-write of the app theme record at a time per project.
909
+ * Two commands at once would each read the old record, and the second write
910
+ * would drop the first one's change. The lock folder lives in the per-user
911
+ * cache folder, so nothing is left in the project.
912
+ * @template T
913
+ * @param {string} cwd
914
+ * @param {() => Promise<T>} fn
915
+ * @returns {Promise<T>}
916
+ */
917
+ async function withThemeAppLock(cwd, fn) {
918
+ let projectDir;
919
+ try {
920
+ ({projectDir} = findThemeProject(cwd));
921
+ } catch {
922
+ // Outside a project the command refuses before it writes anything.
923
+ return fn();
924
+ }
925
+ const key = crypto
926
+ .createHash('sha256')
927
+ .update(fs.realpathSync(projectDir))
928
+ .digest('hex')
929
+ .slice(0, 24);
930
+ const lockDir = path.join(userCacheDir(), 'theme-app-locks', key);
931
+ const lockFailed = (/** @type {unknown} */ error) =>
932
+ new AstryxError(
933
+ `Could not take the lock that keeps two theme commands from changing this app's themes at once (${lockDir}): ${error instanceof Error ? error.message : String(error)}. Check that the folder can be written, then run this command again.`,
934
+ undefined,
935
+ ERROR_CODES.ERR_WRITE_FAILED,
936
+ );
937
+ const deadline = Date.now() + THEME_APP_LOCK_WAIT_MS;
938
+ for (;;) {
939
+ let taken;
940
+ try {
941
+ taken = tryLock(lockDir);
942
+ } catch (error) {
943
+ throw lockFailed(error);
944
+ }
945
+ if (taken) break;
946
+ if (Date.now() > deadline) {
947
+ throw new AstryxError(
948
+ "Another theme command is changing this app's themes. Run this command again when it ends.",
949
+ undefined,
950
+ ERROR_CODES.ERR_WRITE_FAILED,
951
+ );
952
+ }
953
+ await new Promise(resolve => setTimeout(resolve, 50));
954
+ }
955
+ try {
956
+ return await fn();
957
+ } finally {
958
+ try {
959
+ fs.rmSync(lockDir, {recursive: true, force: true});
960
+ } catch {
961
+ // A lock left behind expires: tryLock takes over a lock whose holder is gone.
962
+ }
963
+ }
964
+ }
965
+
672
966
  /**
673
967
  * Add one available built theme to the app record.
674
968
  * @param {string} slug
@@ -677,6 +971,15 @@ async function writeThemeApp(
677
971
  */
678
972
  export async function addThemeToApp(slug, options = {}) {
679
973
  const cwd = options.cwd ?? process.cwd();
974
+ return withThemeAppLock(cwd, () => addThemeToAppLocked(slug, cwd, options));
975
+ }
976
+
977
+ /**
978
+ * @param {string} slug
979
+ * @param {string} cwd
980
+ * @param {{package?: string}} options
981
+ */
982
+ async function addThemeToAppLocked(slug, cwd, options) {
680
983
  const match = await findTheme(slug, {cwd, package: options.package});
681
984
  if (!match) {
682
985
  const available = await listAvailableThemes(cwd);
@@ -697,8 +1000,28 @@ export async function addThemeToApp(slug, options = {}) {
697
1000
  const state = readAppThemeState(cwd);
698
1001
  const available = await listAvailableThemes(state.projectDir);
699
1002
  const owner = themeImportPackage(match);
1003
+ /** @type {string[]} */
1004
+ const notes = [];
1005
+ const previous = state.themes[match.slug];
1006
+ if (previous != null && previous !== owner) {
1007
+ notes.push(
1008
+ `"${match.slug}" now comes from ${owner}${match.source === 'local' ? ' (local theme)' : ''}, replacing ${previous}.`,
1009
+ );
1010
+ }
1011
+ if (options.package == null) {
1012
+ // A local theme shadows a package theme with the same slug; say which
1013
+ // one this add chose, and how to pick the other.
1014
+ const others = available.filter(
1015
+ theme => theme.slug === match.slug && themeImportPackage(theme) !== owner,
1016
+ );
1017
+ for (const other of others) {
1018
+ notes.push(
1019
+ `Chose ${owner}${match.source === 'local' ? ' (local theme)' : ''} for "${match.slug}". To use the one from ${other.package} instead: \`${formatCliCommand(`theme add ${match.slug} --package ${other.package}`, state.projectDir)}\`.`,
1020
+ );
1021
+ }
1022
+ }
700
1023
  const themes = {...state.themes, [match.slug]: owner};
701
- const changed = state.themes[match.slug] !== owner;
1024
+ const changed = previous !== owner;
702
1025
  const defaultSlug =
703
1026
  state.configured && state.defaultSlug != null
704
1027
  ? state.defaultSlug
@@ -711,6 +1034,7 @@ export async function addThemeToApp(slug, options = {}) {
711
1034
  match.slug,
712
1035
  changed,
713
1036
  available,
1037
+ notes,
714
1038
  );
715
1039
  }
716
1040
 
@@ -733,7 +1057,13 @@ function recordedThemeSlug(state, slug) {
733
1057
  * @returns {Promise<import('./theme.type.mjs').ThemeAppResponse>}
734
1058
  */
735
1059
  export async function removeThemeFromApp(slug, options = {}) {
736
- const state = readAppThemeState(options.cwd ?? process.cwd());
1060
+ const cwd = options.cwd ?? process.cwd();
1061
+ return withThemeAppLock(cwd, () => removeThemeFromAppLocked(slug, cwd));
1062
+ }
1063
+
1064
+ /** @param {string} slug @param {string} cwd */
1065
+ async function removeThemeFromAppLocked(slug, cwd) {
1066
+ const state = readAppThemeState(cwd);
737
1067
  const recordedSlug = recordedThemeSlug(state, slug);
738
1068
  if (!state.configured || recordedSlug == null) {
739
1069
  throw new AstryxError(
@@ -777,7 +1107,13 @@ export async function removeThemeFromApp(slug, options = {}) {
777
1107
  * @returns {Promise<import('./theme.type.mjs').ThemeAppResponse>}
778
1108
  */
779
1109
  export async function useThemeInApp(slug, options = {}) {
780
- const state = readAppThemeState(options.cwd ?? process.cwd());
1110
+ const cwd = options.cwd ?? process.cwd();
1111
+ return withThemeAppLock(cwd, () => useThemeInAppLocked(slug, cwd));
1112
+ }
1113
+
1114
+ /** @param {string} slug @param {string} cwd */
1115
+ async function useThemeInAppLocked(slug, cwd) {
1116
+ const state = readAppThemeState(cwd);
781
1117
  const recordedSlug = recordedThemeSlug(state, slug);
782
1118
  if (!state.configured || recordedSlug == null) {
783
1119
  throw new AstryxError(