@astryxdesign/cli 0.7.15-canary.gf890983 → 0.7.15

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 (115) hide show
  1. package/CHANGELOG.md +353 -3
  2. package/api/doctor/_adapter.d.mts +2 -1
  3. package/api/doctor/_adapter.mjs +6 -1
  4. package/api/doctor/doctor.mjs +2 -2
  5. package/api/doctor/theme-checks.mjs +56 -21
  6. package/api/integration/add-helpers.mjs +5 -0
  7. package/api/integration/add-theme.mjs +15 -110
  8. package/api/theme/_adapter.d.mts +37 -5
  9. package/api/theme/_adapter.mjs +363 -50
  10. package/api/theme/_fork.d.mts +90 -0
  11. package/api/theme/_fork.mjs +246 -0
  12. package/api/theme/build/build.d.mts +25 -1
  13. package/api/theme/build/build.mjs +352 -41
  14. package/api/theme/eject/eject.mjs +36 -15
  15. package/api/theme/list/list.mjs +3 -6
  16. package/api/theme/palette/generate/generator.d.mts +13 -0
  17. package/api/theme/palette/generate/generator.mjs +32 -2
  18. package/api/theme/targets/targets.mjs +10 -3
  19. package/api/theme/template/template.mjs +48 -2
  20. package/api/theme/theme.type.d.mts +8 -0
  21. package/api/theme/theme.type.mjs +5 -1
  22. package/api/theme/themeBuild.doc.mjs +2 -2
  23. package/api/theme/themeRemove.doc.mjs +5 -2
  24. package/api/theme/themeTemplate.doc.mjs +2 -2
  25. package/api/theme/themeUse.doc.mjs +8 -2
  26. package/api/theme-edit/_adapter.mjs +157 -36
  27. package/api/theme-edit/_catalog.d.mts +1 -6
  28. package/api/theme-edit/_catalog.mjs +5 -268
  29. package/api/theme-edit/_check.d.mts +3 -1
  30. package/api/theme-edit/_check.mjs +733 -308
  31. package/api/theme-edit/_color.d.mts +19 -0
  32. package/api/theme-edit/_color.mjs +277 -33
  33. package/api/theme-edit/_compiler.d.mts +1 -0
  34. package/api/theme-edit/_compiler.mjs +25 -0
  35. package/api/theme-edit/_context.d.mts +2 -0
  36. package/api/theme-edit/_context.mjs +83 -9
  37. package/api/theme-edit/_css.d.mts +84 -0
  38. package/api/theme-edit/_css.mjs +700 -0
  39. package/api/theme-edit/_edit.mjs +370 -85
  40. package/api/theme-edit/_how-commands.d.mts +5 -0
  41. package/api/theme-edit/_how-commands.mjs +20 -13
  42. package/api/theme-edit/_how-question.d.mts +29 -0
  43. package/api/theme-edit/_how-question.mjs +1573 -182
  44. package/api/theme-edit/_how.mjs +306 -22
  45. package/api/theme-edit/_overview.mjs +2 -7
  46. package/api/theme-edit/_palette.d.mts +27 -5
  47. package/api/theme-edit/_palette.mjs +231 -97
  48. package/api/theme-edit/_parts.d.mts +42 -10
  49. package/api/theme-edit/_parts.mjs +224 -69
  50. package/api/theme-edit/_preview-app.d.mts +8 -0
  51. package/api/theme-edit/_preview-app.mjs +549 -96
  52. package/api/theme-edit/_preview.d.mts +7 -16
  53. package/api/theme-edit/_preview.mjs +77 -84
  54. package/api/theme-edit/_project.d.mts +20 -1
  55. package/api/theme-edit/_project.mjs +43 -13
  56. package/api/theme-edit/_settings.d.mts +96 -20
  57. package/api/theme-edit/_settings.mjs +646 -141
  58. package/api/theme-edit/_tables.d.mts +18 -12
  59. package/api/theme-edit/_tables.mjs +144 -147
  60. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  61. package/api/theme-edit/theme-edit.type.mjs +3 -1
  62. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  63. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  64. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  65. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  66. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  67. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  68. package/assets/docs/tree/publishing.doc.mjs +1 -0
  69. package/assets/docs.generated.json +2 -2
  70. package/assets/self-audit.generated.json +1 -1
  71. package/clients/cli/build-id.generated.json +1 -1
  72. package/clients/cli/commands/experimental/index.mjs +10 -10
  73. package/clients/cli/commands/experimental/theme.mjs +22 -3
  74. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  75. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  76. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  77. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  78. package/clients/cli/commands/integration.mjs +8 -0
  79. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  80. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  81. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  82. package/clients/cli/commands/theme.mjs +325 -48
  83. package/clients/cli/index.mjs +18 -3
  84. package/clients/cli/lib/cli-error.mjs +118 -3
  85. package/clients/cli/manifest.generated.json +1 -1
  86. package/foundation/config/project.mjs +34 -8
  87. package/foundation/config/theme-state.d.mts +16 -0
  88. package/foundation/config/theme-state.mjs +84 -13
  89. package/foundation/discovery/template-needs.d.mts +13 -0
  90. package/foundation/discovery/template-needs.mjs +30 -15
  91. package/foundation/discovery/theme-discovery.mjs +14 -2
  92. package/foundation/discovery/theme-imports.d.mts +16 -0
  93. package/foundation/discovery/theme-imports.mjs +30 -2
  94. package/foundation/doc-compiler/import.mjs +10 -4
  95. package/foundation/fs/gather-cache.mjs +82 -23
  96. package/foundation/fs/jiti-cache.d.mts +21 -0
  97. package/foundation/fs/jiti-cache.mjs +66 -0
  98. package/foundation/fs/module-loader.mjs +7 -2
  99. package/foundation/integrations/autolink.d.mts +1 -24
  100. package/foundation/integrations/autolink.mjs +7 -60
  101. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  102. package/foundation/integrations/declared-dependencies.mjs +73 -0
  103. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  104. package/foundation/integrations/may-have-integrations.mjs +47 -0
  105. package/foundation/release/cache.d.mts +21 -2
  106. package/foundation/release/cache.mjs +48 -8
  107. package/foundation/release/folder-lock.d.mts +7 -0
  108. package/foundation/release/folder-lock.mjs +60 -26
  109. package/foundation/release/lock-lease.d.mts +2 -1
  110. package/foundation/release/lock-lease.mjs +7 -2
  111. package/foundation/response/error-codes.doc.mjs +1 -1
  112. package/foundation/response/response-types.doc.mjs +4 -4
  113. package/package.json +6 -6
  114. package/api/theme-edit/_css-properties.d.mts +0 -10
  115. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -0,0 +1,66 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Where jiti keeps the code it transpiles from TypeScript (integration
5
+ * manifests, config files, codemods, TypeScript template docs).
6
+ * @input The per-user cache folder (foundation/env/user-dirs.mjs) and the
7
+ * private-folder check (foundation/env/private-dir.mjs).
8
+ * @output `jitiCacheOptions()`: the `fsCache` option for the CLI's jiti
9
+ * loaders: `{fsCache: <user cache>/jiti}` when that folder is the user's
10
+ * own and no one else can reach it; `{fsCache: false}` (transpiled in
11
+ * memory only) when it is not; `{}` (jiti's own default) where the system
12
+ * has no user ids (Windows), whose temp folder is the user's own.
13
+ * @position Read by module-loader.mjs, doc-compiler/import.mjs and
14
+ * gather-cache.mjs. jiti's default is a `jiti` folder in the system temp
15
+ * folder, which on Linux every account on a machine shares, and which the
16
+ * system empties from time to time: another account could leave transpiled
17
+ * code there under the name jiti looks for,
18
+ * and after each emptying every TypeScript file is transpiled again. jiti
19
+ * names each cached file for its source's path and checks a hash of its
20
+ * source content before using it, so an edited, upgraded or downgraded
21
+ * file is transpiled again wherever the cache is. A set JITI_FS_CACHE is
22
+ * jiti's own setting and left to jiti.
23
+ */
24
+
25
+ import * as fs from 'node:fs';
26
+ import * as path from 'node:path';
27
+ import {currentUid, isPrivateDir} from '../env/private-dir.mjs';
28
+ import {userCacheDir} from '../env/user-dirs.mjs';
29
+
30
+ /** @type {{fsCache?: string | false} | undefined} */
31
+ let options;
32
+
33
+ /**
34
+ * The per-user folder for jiti's transpiled code.
35
+ * @returns {string}
36
+ */
37
+ export function jitiCacheDir() {
38
+ return path.join(userCacheDir(), 'jiti');
39
+ }
40
+
41
+ /**
42
+ * The `fsCache` option for a jiti loader: the per-user folder, made (0700)
43
+ * on first use and used at once, while it is a real folder the user owns and
44
+ * no one else can reach (the kept catalogs' check). A folder that fails the
45
+ * check, or cannot be made, is not used and nothing is cached on disk. Where
46
+ * the system has no user ids (Windows) ownership cannot be checked, and jiti
47
+ * keeps its default, the user's own temp folder there. Worked out once per
48
+ * process.
49
+ * @returns {{fsCache?: string | false}}
50
+ */
51
+ export function jitiCacheOptions() {
52
+ if (options) return options;
53
+ options = {};
54
+ if (process.env.JITI_FS_CACHE !== undefined || currentUid() == null) {
55
+ return options;
56
+ }
57
+ options = {fsCache: false};
58
+ try {
59
+ const dir = jitiCacheDir();
60
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, {recursive: true, mode: 0o700});
61
+ if (isPrivateDir(dir)) options = {fsCache: dir};
62
+ } catch {
63
+ // No disk cache: every TypeScript file is transpiled in memory.
64
+ }
65
+ return options;
66
+ }
@@ -26,6 +26,7 @@ import {pathToFileURL} from 'node:url';
26
26
  import * as fs from 'node:fs';
27
27
  import {findPresentFiles} from './present-files.mjs';
28
28
  import {importUrl} from './import-url.mjs';
29
+ import {jitiCacheOptions} from './jiti-cache.mjs';
29
30
 
30
31
  export {findPresentFiles};
31
32
 
@@ -42,7 +43,7 @@ const requireFromHere = createRequire(import.meta.url);
42
43
  const createJiti = (...args) => requireFromHere('jiti').createJiti(...args);
43
44
  function getJiti() {
44
45
  if (!jitiInstance) {
45
- jitiInstance = createJiti(import.meta.url);
46
+ jitiInstance = createJiti(import.meta.url, jitiCacheOptions());
46
47
  }
47
48
  return jitiInstance;
48
49
  }
@@ -201,6 +202,7 @@ function isMissingPackageExport(error) {
201
202
  export async function importThemeArtifact(specifier, cwd) {
202
203
  let themeModule = path.join(cwd, 'package.json');
203
204
  const loader = createJiti(path.join(cwd, 'package.json'), {
205
+ ...jitiCacheOptions(),
204
206
  moduleCache: false,
205
207
  jsx: true,
206
208
  interopDefault: true,
@@ -232,7 +234,10 @@ export async function importThemeArtifact(specifier, cwd) {
232
234
  */
233
235
  async function importModule(file, fresh) {
234
236
  if (fresh && file.endsWith('.ts')) {
235
- return await createJiti(import.meta.url, {moduleCache: false}).import(file);
237
+ return await createJiti(import.meta.url, {
238
+ ...jitiCacheOptions(),
239
+ moduleCache: false,
240
+ }).import(file);
236
241
  }
237
242
  if (file.endsWith('.ts')) {
238
243
  return await getJiti().import(file);
@@ -1,20 +1,6 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
- /**
5
- * The dependency names this project declares, in field then declaration order,
6
- * each tagged with the field that declared it. A name declared twice keeps the
7
- * first field it appeared in.
8
- *
9
- * Only keys are read. See the file header for why values are never parsed.
10
- *
11
- * @param {string} projectDir directory holding the project's package.json
12
- * @returns {Array<{name: string, field: string}>}
13
- */
14
- export function readDeclaredDependencies(projectDir: string): Array<{
15
- name: string;
16
- field: string;
17
- }>;
18
4
  /**
19
5
  * @typedef {object} AutolinkCandidate
20
6
  * @property {string} spec
@@ -111,16 +97,6 @@ export function autolinkIntegrations({ projectDir, loaded, fresh, }: {
111
97
  fresh?: boolean | undefined;
112
98
  }): Promise<import("./integrations.mjs").LoadedIntegration[]>;
113
99
  export { resolveInstalledPackageDir };
114
- /**
115
- * package.json fields whose keys name a dependency this project installs.
116
- *
117
- * `peerDependencies` is deliberately absent: a peer is a requirement the
118
- * CONSUMER must satisfy, not something this project's install brings in, so a
119
- * peer that happens to be present is not a declaration that it belongs here.
120
- *
121
- * @type {readonly string[]}
122
- */
123
- export const DEPENDENCY_FIELDS: readonly string[];
124
100
  export type AutolinkCandidate = {
125
101
  spec: string;
126
102
  field: string;
@@ -133,3 +109,4 @@ export type AutolinkCandidate = {
133
109
  repeat?: boolean | undefined;
134
110
  };
135
111
  import { resolveInstalledPackageDir } from './installed-package.mjs';
112
+ export { DEPENDENCY_FIELDS, readDeclaredDependencies } from "./declared-dependencies.mjs";
@@ -41,68 +41,15 @@ import * as fs from 'node:fs';
41
41
  import * as path from 'node:path';
42
42
  import {findManifestPaths, loadIntegrations} from './integrations.mjs';
43
43
  import {resolveProviders} from './provider-resolution.mjs';
44
- import {
45
- isBarePackageName,
46
- resolveInstalledPackageDir,
47
- } from './installed-package.mjs';
44
+ import {resolveInstalledPackageDir} from './installed-package.mjs';
45
+ import {readDeclaredDependencies} from './declared-dependencies.mjs';
48
46
 
49
- export {resolveInstalledPackageDir};
50
-
51
- /**
52
- * package.json fields whose keys name a dependency this project installs.
53
- *
54
- * `peerDependencies` is deliberately absent: a peer is a requirement the
55
- * CONSUMER must satisfy, not something this project's install brings in, so a
56
- * peer that happens to be present is not a declaration that it belongs here.
57
- *
58
- * @type {readonly string[]}
59
- */
60
- export const DEPENDENCY_FIELDS = Object.freeze([
61
- 'dependencies',
62
- 'devDependencies',
63
- 'optionalDependencies',
64
- ]);
65
-
66
-
67
- /**
68
- * The dependency names this project declares, in field then declaration order,
69
- * each tagged with the field that declared it. A name declared twice keeps the
70
- * first field it appeared in.
71
- *
72
- * Only keys are read. See the file header for why values are never parsed.
73
- *
74
- * @param {string} projectDir directory holding the project's package.json
75
- * @returns {Array<{name: string, field: string}>}
76
- */
77
- export function readDeclaredDependencies(projectDir) {
78
- /** @type {Record<string, unknown>} */
79
- let pkg;
80
- try {
81
- pkg = JSON.parse(
82
- fs.readFileSync(path.join(projectDir, 'package.json'), 'utf-8'),
83
- );
84
- } catch {
85
- // No package.json, or unreadable/malformed — nothing is declared.
86
- return [];
87
- }
88
-
89
- /** @type {Array<{name: string, field: string}>} */
90
- const declared = [];
91
- const seen = new Set();
92
- for (const field of DEPENDENCY_FIELDS) {
93
- const entry = pkg?.[field];
94
- if (entry == null || typeof entry !== 'object' || Array.isArray(entry)) {
95
- continue;
96
- }
97
- for (const name of Object.keys(entry)) {
98
- if (seen.has(name) || !isBarePackageName(name)) continue;
99
- seen.add(name);
100
- declared.push({name, field});
101
- }
102
- }
103
- return declared;
104
- }
47
+ export {
48
+ DEPENDENCY_FIELDS,
49
+ readDeclaredDependencies,
50
+ } from './declared-dependencies.mjs';
105
51
 
52
+ export {resolveInstalledPackageDir};
106
53
 
107
54
  /**
108
55
  * Resolve a path through symlinks for identity comparison. pnpm links every
@@ -0,0 +1,27 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * The dependency names this project declares, in field then declaration order,
6
+ * each tagged with the field that declared it. A name declared twice keeps the
7
+ * first field it appeared in.
8
+ *
9
+ * Only keys are read; the file header says why values are never parsed.
10
+ *
11
+ * @param {string} projectDir directory holding the project's package.json
12
+ * @returns {Array<{name: string, field: string}>}
13
+ */
14
+ export function readDeclaredDependencies(projectDir: string): Array<{
15
+ name: string;
16
+ field: string;
17
+ }>;
18
+ /**
19
+ * package.json fields whose keys name a dependency this project installs.
20
+ *
21
+ * `peerDependencies` is deliberately absent: a peer is a requirement the
22
+ * CONSUMER must satisfy, not something this project's install brings in, so a
23
+ * peer that happens to be present is not a declaration that it belongs here.
24
+ *
25
+ * @type {readonly string[]}
26
+ */
27
+ export const DEPENDENCY_FIELDS: readonly string[];
@@ -0,0 +1,73 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The dependencies a project's package.json declares, as autolinking
5
+ * (autolink.mjs) and the recorder's cheap integration check
6
+ * (may-have-integrations.mjs) read them. Built-ins and path helpers only,
7
+ * so it loads before anything heavy.
8
+ *
9
+ * The KEY, never the VALUE: `"@acme/legacy-ui": "npm:@acme/ui@0.1.22"` is a
10
+ * real, installed shape; so are `workspace:*`, `file:../lib`, `link:` and
11
+ * `catalog:`. None of them is a semver range, and none of them has to be
12
+ * parsed: the key is the directory name under node_modules, which is the only
13
+ * thing resolution needs. Identity still comes from the resolved package's own
14
+ * package.json `name`.
15
+ */
16
+
17
+ import * as fs from 'node:fs';
18
+ import * as path from 'node:path';
19
+ import {isBarePackageName} from './installed-package.mjs';
20
+
21
+ /**
22
+ * package.json fields whose keys name a dependency this project installs.
23
+ *
24
+ * `peerDependencies` is deliberately absent: a peer is a requirement the
25
+ * CONSUMER must satisfy, not something this project's install brings in, so a
26
+ * peer that happens to be present is not a declaration that it belongs here.
27
+ *
28
+ * @type {readonly string[]}
29
+ */
30
+ export const DEPENDENCY_FIELDS = Object.freeze([
31
+ 'dependencies',
32
+ 'devDependencies',
33
+ 'optionalDependencies',
34
+ ]);
35
+
36
+ /**
37
+ * The dependency names this project declares, in field then declaration order,
38
+ * each tagged with the field that declared it. A name declared twice keeps the
39
+ * first field it appeared in.
40
+ *
41
+ * Only keys are read; the file header says why values are never parsed.
42
+ *
43
+ * @param {string} projectDir directory holding the project's package.json
44
+ * @returns {Array<{name: string, field: string}>}
45
+ */
46
+ export function readDeclaredDependencies(projectDir) {
47
+ /** @type {Record<string, unknown>} */
48
+ let pkg;
49
+ try {
50
+ pkg = JSON.parse(
51
+ fs.readFileSync(path.join(projectDir, 'package.json'), 'utf-8'),
52
+ );
53
+ } catch {
54
+ // No package.json, or unreadable/malformed — nothing is declared.
55
+ return [];
56
+ }
57
+
58
+ /** @type {Array<{name: string, field: string}>} */
59
+ const declared = [];
60
+ const seen = new Set();
61
+ for (const field of DEPENDENCY_FIELDS) {
62
+ const entry = pkg?.[field];
63
+ if (entry == null || typeof entry !== 'object' || Array.isArray(entry)) {
64
+ continue;
65
+ }
66
+ for (const name of Object.keys(entry)) {
67
+ if (seen.has(name) || !isBarePackageName(name)) continue;
68
+ seen.add(name);
69
+ declared.push({name, field});
70
+ }
71
+ }
72
+ return declared;
73
+ }
@@ -0,0 +1,8 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * @param {string} cwd
6
+ * @returns {boolean}
7
+ */
8
+ export function mayHaveIntegrations(cwd: string): boolean;
@@ -0,0 +1,47 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Whether a project may load an integration, decided from a few file
5
+ * checks before anything heavy loads.
6
+ * @input The working folder.
7
+ * @output `mayHaveIntegrations(cwd)`: false only when the project root (the
8
+ * nearest package.json's folder, else `cwd`) has no Astryx config, is no
9
+ * integration itself, declares no installed dependency that ships an
10
+ * integration manifest, and the run is inside a project (outside one, the
11
+ * integrations installed beside the running CLI load, spec AST-081 FR12),
12
+ * so no configured, self-resolved, autolinked or computer-level integration
13
+ * can load.
14
+ * @position Read by foundation/fs/gather-cache.mjs: `component`, `template`,
15
+ * `theme` and `discover` record a run only for their integrations' kept
16
+ * check results, so a project with none skips the recorder entirely. A true
17
+ * answer only means the run records, so a check that says true too often
18
+ * costs time, never an answer.
19
+ */
20
+
21
+ import {CONFIG_BASENAMES} from '../config/config-path.mjs';
22
+ import {isOutsideProject} from '../env/project-scope.mjs';
23
+ import {findPackageRoot} from '../fs/paths.mjs';
24
+ import {findPresentFiles} from '../fs/present-files.mjs';
25
+ import {readDeclaredDependencies} from './declared-dependencies.mjs';
26
+ import {resolveInstalledPackageDir} from './installed-package.mjs';
27
+ import {MANIFEST_BASENAMES} from './manifest-paths.mjs';
28
+
29
+ /**
30
+ * @param {string} cwd
31
+ * @returns {boolean}
32
+ */
33
+ export function mayHaveIntegrations(cwd) {
34
+ const root = findPackageRoot(cwd) ?? cwd;
35
+ if (findPresentFiles(root, CONFIG_BASENAMES).length > 0) return true;
36
+ if (findPresentFiles(root, MANIFEST_BASENAMES).length > 0) return true;
37
+ for (const {name} of readDeclaredDependencies(root)) {
38
+ const installed = resolveInstalledPackageDir(name, root);
39
+ if (
40
+ installed &&
41
+ findPresentFiles(installed.packageDir, MANIFEST_BASENAMES).length > 0
42
+ ) {
43
+ return true;
44
+ }
45
+ }
46
+ return isOutsideProject(cwd);
47
+ }
@@ -185,6 +185,12 @@ export function recentFailedInstall(version: string, cacheDir: string, now?: num
185
185
  failures: number;
186
186
  waitMs: number;
187
187
  } | null;
188
+ /**
189
+ * This process's process-id space (Linux: the pid namespace), or null where
190
+ * process ids are one space for the whole computer.
191
+ * @returns {string | null}
192
+ */
193
+ export function pidSpace(): string | null;
188
194
  /**
189
195
  * Is process `pid` on this computer still running?
190
196
  * @param {number} pid
@@ -197,12 +203,25 @@ export function isAlive(pid: number): boolean;
197
203
  * over at once, and one from another computer once its holder has stopped
198
204
  * renewing it. Throws when the cache folder cannot be written.
199
205
  * @param {string} lockDir
200
- * @param {{now?: number}} [options] the clock, for tests
206
+ * @param {{now?: number, leased?: boolean}} [options] the clock, for tests;
207
+ * `leased` for a lock whose holder renews it (lock-lease.mjs): its record
208
+ * names its process space, and a holder on this computer that looks gone
209
+ * from another space (a container with the same computer name) is taken
210
+ * over only once its record has stood unrenewed for three renewals.
201
211
  * @returns {boolean}
202
212
  */
203
- export function tryLock(lockDir: string, { now }?: {
213
+ export function tryLock(lockDir: string, { now, leased }?: {
204
214
  now?: number;
215
+ leased?: boolean;
205
216
  }): boolean;
217
+ /**
218
+ * Which lock folder this is: its device, inode and creation time, and its
219
+ * owner record. A rename keeps them all; a lock made again in its place
220
+ * differs, even before it has a record. Null when there is no folder.
221
+ * @param {string} lockDir
222
+ * @returns {string | null}
223
+ */
224
+ export function lockIdentity(lockDir: string): string | null;
206
225
  /**
207
226
  * Whether a process's arguments are this CLI's install of `version`, as
208
227
  * runNpm starts it: the program (`argv[0]`) is npm, or a Node running npm's
@@ -41,7 +41,7 @@ import {fileURLToPath} from 'node:url';
41
41
  import {satisfiesRange} from '../env/semver.mjs';
42
42
  import {readJson} from './project.mjs';
43
43
  import {userCacheDir as userCacheDirFor} from '../env/user-dirs.mjs';
44
- import {foreignLockIsSilent} from './lock-lease.mjs';
44
+ import {foreignLockIsSilent, LEASE_RENEW_MS} from './lock-lease.mjs';
45
45
  import {relativeWithin} from '../fs/path-compare.mjs';
46
46
 
47
47
  /**
@@ -649,6 +649,19 @@ const FOREIGN_LOCK_MS = 20 * 60_000;
649
649
  /** How long a lock with no owner record may stand: its holder died taking it. */
650
650
  const UNOWNED_LOCK_MS = 10_000;
651
651
 
652
+ /**
653
+ * This process's process-id space (Linux: the pid namespace), or null where
654
+ * process ids are one space for the whole computer.
655
+ * @returns {string | null}
656
+ */
657
+ export function pidSpace() {
658
+ try {
659
+ return fs.readlinkSync('/proc/self/ns/pid');
660
+ } catch {
661
+ return null;
662
+ }
663
+ }
664
+
652
665
  /**
653
666
  * Is process `pid` on this computer still running?
654
667
  * @param {number} pid
@@ -674,7 +687,7 @@ export function isAlive(pid) {
674
687
  * @param {number} now
675
688
  * @returns {boolean}
676
689
  */
677
- function lockIsStale(lockDir, now) {
690
+ function lockIsStale(lockDir, now, leased = false) {
678
691
  let age;
679
692
  try {
680
693
  age = now - fs.statSync(lockDir).mtimeMs;
@@ -688,7 +701,24 @@ function lockIsStale(lockDir, now) {
688
701
  return age > FOREIGN_LOCK_MS || foreignLockIsSilent(lockDir, now);
689
702
  }
690
703
  // A live holder on this computer is installing, however slowly.
691
- return !isAlive(owner.pid);
704
+ if (isAlive(owner.pid)) return false;
705
+ // A leased lock's holder renews its record while it runs. A process id
706
+ // that looks gone may only be out of sight (a container that shares this
707
+ // computer's name, in its own process space): the record must also have
708
+ // stood unrenewed for three renewals.
709
+ if (!leased) return true;
710
+ // Recorded from this process space (or by a version that records none):
711
+ // the process id is judged right.
712
+ const ns = pidSpace();
713
+ if (ns === null || !owner.ns || owner.ns === ns) return true;
714
+ try {
715
+ return (
716
+ now - fs.statSync(path.join(lockDir, 'owner.json')).mtimeMs >
717
+ 3 * LEASE_RENEW_MS
718
+ );
719
+ } catch {
720
+ return true;
721
+ }
692
722
  }
693
723
 
694
724
  /**
@@ -709,10 +739,14 @@ function ownerText(lockDir) {
709
739
  * over at once, and one from another computer once its holder has stopped
710
740
  * renewing it. Throws when the cache folder cannot be written.
711
741
  * @param {string} lockDir
712
- * @param {{now?: number}} [options] the clock, for tests
742
+ * @param {{now?: number, leased?: boolean}} [options] the clock, for tests;
743
+ * `leased` for a lock whose holder renews it (lock-lease.mjs): its record
744
+ * names its process space, and a holder on this computer that looks gone
745
+ * from another space (a container with the same computer name) is taken
746
+ * over only once its record has stood unrenewed for three renewals.
713
747
  * @returns {boolean}
714
748
  */
715
- export function tryLock(lockDir, {now = Date.now()} = {}) {
749
+ export function tryLock(lockDir, {now = Date.now(), leased = false} = {}) {
716
750
  fs.mkdirSync(path.dirname(lockDir), {recursive: true});
717
751
  try {
718
752
  fs.mkdirSync(lockDir);
@@ -725,7 +759,7 @@ export function tryLock(lockDir, {now = Date.now()} = {}) {
725
759
  // record, which a new lock lacks for a moment), or another run took the
726
760
  // lock in between.
727
761
  const judged = lockIdentity(lockDir);
728
- if (!judged || !lockIsStale(lockDir, now)) return false;
762
+ if (!judged || !lockIsStale(lockDir, now, leased)) return false;
729
763
  const aside = `${lockDir}.stale-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
730
764
  try {
731
765
  fs.renameSync(lockDir, aside);
@@ -761,7 +795,13 @@ export function tryLock(lockDir, {now = Date.now()} = {}) {
761
795
  try {
762
796
  fs.writeFileSync(
763
797
  path.join(lockDir, 'owner.json'),
764
- JSON.stringify({pid: process.pid, host: os.hostname(), at: Date.now()}),
798
+ JSON.stringify({
799
+ pid: process.pid,
800
+ host: os.hostname(),
801
+ at: Date.now(),
802
+ // A leased lock names the process space its id belongs to.
803
+ ...(leased && pidSpace() ? {ns: pidSpace()} : {}),
804
+ }),
765
805
  );
766
806
  } catch {
767
807
  // Without a record the lock still expires on its own.
@@ -776,7 +816,7 @@ export function tryLock(lockDir, {now = Date.now()} = {}) {
776
816
  * @param {string} lockDir
777
817
  * @returns {string | null}
778
818
  */
779
- function lockIdentity(lockDir) {
819
+ export function lockIdentity(lockDir) {
780
820
  try {
781
821
  const st = fs.statSync(lockDir, {bigint: true});
782
822
  return `${st.dev}:${st.ino}:${st.birthtimeNs}:${ownerText(lockDir)}`;
@@ -1,6 +1,13 @@
1
1
  // @generated by scripts/sync-api-types.mjs from the JSDoc in foundation/**/*.mjs.
2
2
  // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
3
 
4
+ /**
5
+ * Throw when the work running under withFolderLock no longer holds its lock
6
+ * (another run took it over while this one was stopped), so it writes
7
+ * nothing more. Outside withFolderLock it does nothing. Call it right
8
+ * before a write.
9
+ */
10
+ export function stillHolds(): void;
4
11
  /**
5
12
  * Run `fn` holding the lock folder `lockDir`. A run waits while another
6
13
  * holds it; the wait starts again each time the lock changes hands, and
@@ -14,21 +14,14 @@
14
14
 
15
15
  import * as fs from 'node:fs';
16
16
  import * as path from 'node:path';
17
- import {tryLock} from './cache.mjs';
18
- import {LEASE_RENEW_MS, renewLock} from './lock-lease.mjs';
17
+ import {AsyncLocalStorage} from 'node:async_hooks';
18
+ import * as os from 'node:os';
19
+ import {isAlive, lockIdentity, pidSpace, tryLock} from './cache.mjs';
20
+ import {foreignLockIsSilent, LEASE_RENEW_MS, renewLock} from './lock-lease.mjs';
19
21
 
20
22
  /** How long a held lock's record may stand unrenewed before it is taken over. */
21
23
  export const SILENT_MS = 3 * LEASE_RENEW_MS;
22
24
 
23
- /** @param {string} file @returns {string} */
24
- const recordText = file => {
25
- try {
26
- return fs.readFileSync(file, 'utf8');
27
- } catch {
28
- return '';
29
- }
30
- };
31
-
32
25
  /**
33
26
  * Move a silent lock aside and remove it; another run that moved it first
34
27
  * wins, and this one tries again.
@@ -42,19 +35,59 @@ function takeOver(lockDir, judged) {
42
35
  } catch {
43
36
  return;
44
37
  }
45
- // The lock moved aside must hold the record judged silent: a lock taken
46
- // or renewed in between is put back.
47
- if (recordText(path.join(aside, 'owner.json')) !== judged) {
38
+ // The lock moved aside must be the one judged silent (by its identity
39
+ // on disk and its record, as the release cache checks): a lock taken or
40
+ // renewed in between is put back. When its place is taken again, it
41
+ // stays aside for its run, and this run holds nothing.
42
+ if (lockIdentity(aside) !== judged) {
48
43
  try {
49
44
  fs.renameSync(aside, lockDir);
50
45
  } catch {
51
- // Its place is taken again.
46
+ // Left for its run.
52
47
  }
53
48
  return;
54
49
  }
55
50
  fs.rmSync(aside, {recursive: true, force: true});
56
51
  }
57
52
 
53
+ /**
54
+ * Whether a lock's holder runs on this computer, in this process space: a
55
+ * holder that is only stopped (Ctrl-Z, a sleeping laptop, a debugger) is
56
+ * alive, however long its record stands unrenewed.
57
+ * @param {any} owner
58
+ */
59
+ function aliveHere(owner) {
60
+ if (!owner || owner.host !== os.hostname() || !Number.isInteger(owner.pid))
61
+ return false;
62
+ const ns = pidSpace();
63
+ if (owner.ns && ns && owner.ns !== ns) return false;
64
+ return isAlive(owner.pid);
65
+ }
66
+
67
+ /** The lock the running work holds, for the check before each write. */
68
+ const holding = new AsyncLocalStorage();
69
+
70
+ /**
71
+ * Throw when the work running under withFolderLock no longer holds its lock
72
+ * (another run took it over while this one was stopped), so it writes
73
+ * nothing more. Outside withFolderLock it does nothing. Call it right
74
+ * before a write.
75
+ */
76
+ export function stillHolds() {
77
+ const h =
78
+ /** @type {{ownerFile: string, same: (o: any) => boolean} | undefined} */ (
79
+ holding.getStore()
80
+ );
81
+ if (!h || h.same(readOwner(h.ownerFile))) return;
82
+ const error = /** @type {Error & {code?: string}} */ (
83
+ new Error(
84
+ 'another command took over the lock while this one was stopped, so this one writes nothing more',
85
+ )
86
+ );
87
+ error.code = 'ERR_LOCK_LOST';
88
+ throw error;
89
+ }
90
+
58
91
  /** The lock folders this process holds now. */
59
92
  const HELD = new Set();
60
93
 
@@ -101,16 +134,17 @@ export async function withFolderLock(lockDir, fn, {waitMs = 30_000, onBusy}) {
101
134
  // not changed for three of those, as this run sees it, has stopped,
102
135
  // whatever computer or process id it names (pid 1 in a container, a
103
136
  // computer whose processes this run cannot check).
104
- let record = recordText(ownerFile);
105
- let since = Date.now();
106
- for (let waited = 0; !tryLock(lockDir); waited += 50) {
107
- const text = recordText(ownerFile);
108
- if (text !== record) {
109
- record = text;
110
- since = Date.now();
111
- } else if (Date.now() - since >= SILENT_MS) {
112
- takeOver(lockDir, record);
113
- since = Date.now();
137
+ for (let waited = 0; !tryLock(lockDir, {leased: true}); waited += 50) {
138
+ // The release cache's own judge of silence (what this process saw of
139
+ // the record), with the editor's shorter window. The lock is judged by
140
+ // its identity on disk, so the one moved aside is the one judged.
141
+ const judged = lockIdentity(lockDir);
142
+ if (
143
+ judged &&
144
+ foreignLockIsSilent(lockDir, Date.now(), SILENT_MS) &&
145
+ !aliveHere(readOwner(ownerFile))
146
+ ) {
147
+ takeOver(lockDir, judged);
114
148
  continue;
115
149
  }
116
150
  const now = holderOf();
@@ -153,7 +187,7 @@ export async function withFolderLock(lockDir, fn, {waitMs = 30_000, onBusy}) {
153
187
  process.once('SIGINT', onSignal);
154
188
  process.once('SIGTERM', onSignal);
155
189
  try {
156
- return await fn();
190
+ return await holding.run({ownerFile, same}, fn);
157
191
  } finally {
158
192
  clearInterval(lease);
159
193
  release();