@astryxdesign/cli 0.7.3-canary.ea68606 → 0.7.3-canary.f8fad28

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.
@@ -70,7 +70,12 @@ import {
70
70
  rootProblem,
71
71
  } from '../../foundation/integrations/validate-contributions.mjs';
72
72
  import {formatCliCommand} from '../../foundation/env/package-manager.mjs';
73
+ import {cliPeerVersionProblem} from '../../foundation/integrations/cli-peer-version.mjs';
73
74
  import {publicImportIssues} from '../../foundation/integrations/public-imports.mjs';
75
+ import {runChoice} from '../../foundation/release/run-context.mjs';
76
+
77
+ /** The running CLI is outside the package's `@astryxdesign/cli` peer range. */
78
+ const CLI_PEER_VERSION = 'cli_peer_version';
74
79
 
75
80
  export {validateLoadedIntegration, isListedIssue};
76
81
 
@@ -281,13 +286,15 @@ async function findUnreachableContributionIssues(
281
286
  * Shared core for the local and installed entry points.
282
287
  * @param {string} packageDir
283
288
  * @param {{name: string, version?: string}} identity
284
- * @param {{scanUnreachable?: boolean}} [options]
289
+ * @param {{scanUnreachable?: boolean, own?: boolean, cwd?: string}} [options]
290
+ * `own`: the package is the one being authored in the current folder;
291
+ * `cwd`: the folder whose package manager an install command names
285
292
  * @returns {Promise<ValidateResult>}
286
293
  */
287
294
  async function validateAtPackageDir(
288
295
  packageDir,
289
296
  identity,
290
- {scanUnreachable = false} = {},
297
+ {scanUnreachable = false, own = false, cwd = packageDir} = {},
291
298
  ) {
292
299
  /** @type {Issue[]} */
293
300
  const issues = [];
@@ -429,6 +436,24 @@ async function validateAtPackageDir(
429
436
  issues.push(issue);
430
437
  }
431
438
  }
439
+ // The running CLI outside the package's `@astryxdesign/cli` peer range is a
440
+ // note for the same reason. It is built here, not among the contribution
441
+ // checks, so `integration verify` (which reports their layout findings)
442
+ // does not see it.
443
+ // The version an upgrade starts from is the project's: its own CLI's, or,
444
+ // with none, its Core's, as the project-upgrade notice takes it.
445
+ const choice = runChoice(cwd);
446
+ const from =
447
+ choice.inProject && choice.copy === 'starting' && choice.coreVersion
448
+ ? choice.coreVersion
449
+ : undefined;
450
+ const peerProblem = cliPeerVersionProblem(loaded, undefined, cwd, {
451
+ own,
452
+ from,
453
+ });
454
+ if (peerProblem) {
455
+ (result.notes ??= []).push({code: CLI_PEER_VERSION, message: peerProblem});
456
+ }
432
457
  if (loaded.themes && !rootProblem(loaded.themes))
433
458
  issues.push(...unreadThemeFolderIssues(packageDir, loaded));
434
459
  // What the docs say that no reader serves: a prop listed twice, an
@@ -518,7 +543,7 @@ export async function validateLocalIntegration(cwd = process.cwd()) {
518
543
  const result = await validateAtPackageDir(
519
544
  packageDir,
520
545
  {name, version: pkg.version},
521
- {scanUnreachable: true},
546
+ {scanUnreachable: true, own: true},
522
547
  );
523
548
  (result.listed ??= []).unshift(
524
549
  ...fields,
@@ -653,10 +678,11 @@ export async function validateInstalledIntegration(spec, cwd = process.cwd()) {
653
678
  };
654
679
  }
655
680
 
656
- return validateAtPackageDir(packageDir, {
657
- name: pkg.name ?? spec,
658
- version: pkg.version,
659
- });
681
+ return validateAtPackageDir(
682
+ packageDir,
683
+ {name: pkg.name ?? spec, version: pkg.version},
684
+ {cwd},
685
+ );
660
686
  }
661
687
 
662
688
  /**
@@ -37,7 +37,9 @@ export type ValidateIntegrationResponse = {
37
37
  type: "integration.validate";
38
38
  /**
39
39
  * `notes`: information beside the issues that fails nothing, such as
40
- * `invalid_cli_command`, a `cliCommand` that was ignored as malformed, and
40
+ * `invalid_cli_command`, a `cliCommand` that was ignored as malformed;
41
+ * `cli_peer_version`, the running CLI outside the package's
42
+ * `@astryxdesign/cli` peer range; and
41
43
  * the package layout findings added after the last minor release, each with
42
44
  * its fix in the message: two docs for one component
43
45
  * (`duplicate_component_doc`), a root reached through a symlink
@@ -41,7 +41,9 @@
41
41
  * @property {'integration.validate'} type
42
42
  * @property {{validated: boolean, name: string | null, version: string | null, issues: import('../../foundation/integrations/issue').AstryxIntegrationIssue[], notes?: Array<{code: string, message: string}>, docTypes?: DocTypesReport, docNames?: DocNamesReport, blockComponents?: BlockComponentsReport, publicImports?: PublicImportsReport}} data
43
43
  * `notes`: information beside the issues that fails nothing, such as
44
- * `invalid_cli_command`, a `cliCommand` that was ignored as malformed, and
44
+ * `invalid_cli_command`, a `cliCommand` that was ignored as malformed;
45
+ * `cli_peer_version`, the running CLI outside the package's
46
+ * `@astryxdesign/cli` peer range; and
45
47
  * the package layout findings added after the last minor release, each with
46
48
  * its fix in the message: two docs for one component
47
49
  * (`duplicate_component_doc`), a root reached through a symlink
@@ -62,7 +62,7 @@ export const doc = {
62
62
  {
63
63
  type: 'integration.validate',
64
64
  description:
65
- 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. A `runner_command` note lists each Astryx command a topic writes with a package runner, with its file, line and the bare command to write. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed). Since 0.7.3 each import apps cannot use is a note in `data.notes`, its fix inside the message, listed only: it does not fail this command or `integration check --strict`, and fails `--strict` from the next minor release. The codes are `component_import_not_exported`, `component_import_other_package`, `example_import_not_exported`, `template_import_not_exported`, `template_import_outside_root` and `template_private_import`. When the manifest loads, `data.publicImports` is `{status: \'checked\', findings: [], unchecked}`: `unchecked` lists each import the check could not judge, as {file, specifier, reason}, the reason starting `example <label>:` for an import in a component example: a deep path into build output not built yet in a package with no `exports`; a template import of Core when `@astryxdesign/core` is not installed beside the package (a `packages/core` of the workspace under another name does not count); every import of the package\'s own name when package.json has no `name` or a `name` that is not a bare package name; one entry for the whole check when package.json cannot be read; and an import of a subpath whose `exports` entry has only a `types` target, unless it is `import type`, every binding is an inline `type`, or every name it imports is a type its types file declares: a value import of a name that file does not declare as a type, a namespace or side-effect import, or any import when the types file cannot be read (it may be build output). `integration check` counts the unchecked as not compared; they never fail it.',
65
+ 'The result envelope: `data.validated`, false when nothing was validated — with no `package.json` at all, `data.issues` carries one `no_package` error-severity issue so the command exits 1; with a `package.json` but no integration manifest, `data.issues` is empty, which means "not looked at", not "healthy"; `data.name` and `data.version` of the validated package (both null when `data.validated` is false; `data.name` is `(local package)` when the local package.json has no readable name), plus `data.issues`, an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message, fix?, file?, line?}: `fix` is the change that resolves the issue, and `file` and `line` where it is, relative to the package, when the check knows them; and `data.notes` when there are any: {code, message} information that fails nothing, such as `invalid_cli_command` for a `cliCommand` that was ignored as malformed and `cli_peer_version` when the running CLI is outside the `@astryxdesign/cli` peer range of the package, and the package layout findings added after the last minor release, each with its fix in the message: `duplicate_component_doc`, `symlinked_root`, `unreadable_file`, `invalid_package_json` (no `name` or `version`), `no_provider_id`, and `source_without_component_doc` for a doc whose file name differs from its source only in letter case where the two still pair; and `doc_name_mismatch` and `unknown_block_component` (see `docNames` and `blockComponents`); they become warnings in the next minor release. A `runner_command` note lists each Astryx command a topic writes with a package runner, with its file, line and the bare command to write. When the manifest loads, `data.docTypes` holds the doc type check: `status` (`checked` | `skipped`), `reason` when skipped, `typescript`, `docs` (doc values checked), `findings` ({doc, line, export, type, field, problem: `unknown_field` | `missing_field` | `wrong_type`, severity: `warning`, message, fix}), `unchecked` ({doc, reason}: a doc that could not be fully checked, or a root its reader cannot read), and `fixtures` when the components or docs root holds test fixture docs under `__tests__`: how many, none of them checked. When the manifest loads, `data.docNames` lists the component doc names it could not judge: `status` (`checked`), `findings` (always empty; a doc name the module its import names provably does not export is a `doc_name_mismatch` note, with its fix in the message) and `unchecked` ({file, name, reason}: a doc whose `name` differs from the name it is listed under and whose source exports cannot all be read, such as a re-export from another package). When the manifest loads, `data.blockComponents` lists the component names templates give in `exampleFor` or `componentsUsed` that could not be judged: `status` (`checked`), `findings` (always empty; a name neither the package nor Core has, and the template does not import, is an `unknown_block_component` note, with its fix in the message) and `unchecked` ({file, name, reason}: a name the template may reach through anything other than named imports and re-exports from Core, React, StyleX, local helpers or the entry of the package itself, such as an import from another package, a default or namespace import, an alias of or member read off an imported binding, require() or a dynamic import(), or a local module that cannot be read, or any name Core would have to resolve when Core is not installed). Since 0.7.3 each import apps cannot use is a note in `data.notes`, its fix inside the message, listed only: it does not fail this command or `integration check --strict`, and fails `--strict` from the next minor release. The codes are `component_import_not_exported`, `component_import_other_package`, `example_import_not_exported`, `template_import_not_exported`, `template_import_outside_root` and `template_private_import`. When the manifest loads, `data.publicImports` is `{status: \'checked\', findings: [], unchecked}`: `unchecked` lists each import the check could not judge, as {file, specifier, reason}, the reason starting `example <label>:` for an import in a component example: a deep path into build output not built yet in a package with no `exports`; a template import of Core when `@astryxdesign/core` is not installed beside the package (a `packages/core` of the workspace under another name does not count); every import of the package\'s own name when package.json has no `name` or a `name` that is not a bare package name; one entry for the whole check when package.json cannot be read; and an import of a subpath whose `exports` entry has only a `types` target, unless it is `import type`, every binding is an inline `type`, or every name it imports is a type its types file declares: a value import of a name that file does not declare as a type, a namespace or side-effect import, or any import when the types file cannot be read (it may be build output). `integration check` counts the unchecked as not compared; they never fail it.',
66
66
  },
67
67
  ],
68
68
  examples: [
@@ -13,6 +13,16 @@ export function entryTable(all: any[], cards: Record<string, {
13
13
  synonyms?: string[];
14
14
  props?: string[];
15
15
  }>): EntryTable;
16
+ /**
17
+ * @param {any[]} all
18
+ * @param {Record<string, {what?: string, synonyms?: string[], props?: string[]}>} cards
19
+ * @returns {EntryTable}
20
+ */
21
+ export function buildTable(all: any[], cards: Record<string, {
22
+ what?: string;
23
+ synonyms?: string[];
24
+ props?: string[];
25
+ }>): EntryTable;
16
26
  export function entryOf(table: {
17
27
  index: Map<string, number>;
18
28
  }, res: {
@@ -22,6 +32,7 @@ export function entryOf(table: {
22
32
  section?: string;
23
33
  }): number | undefined;
24
34
  export function entryId(c: any): string;
35
+ export const HASHED_FIELDS: readonly string[];
25
36
  export type EntryTable = {
26
37
  /**
27
38
  * every returnable `<domain>:<name>`, in code-point order
@@ -77,6 +77,29 @@ let last = null;
77
77
  const cardIds = new WeakMap();
78
78
  let nextCardId = 0;
79
79
 
80
+ /**
81
+ * The candidate fields buildTable reads, all of them hashed by fingerprint;
82
+ * `_entries.test.mjs` fails if buildTable starts reading another.
83
+ */
84
+ /** How many guidance lines and prose paragraphs of a candidate the index reads. */
85
+ const GUIDANCE_LINES = 10;
86
+ const PROSE_PARAGRAPHS = 4;
87
+
88
+ export const HASHED_FIELDS = Object.freeze([
89
+ 'domain',
90
+ 'name',
91
+ '_topic',
92
+ '_section',
93
+ '_resultName',
94
+ '_package',
95
+ 'description',
96
+ 'keywords',
97
+ 'aliases',
98
+ 'titles',
99
+ 'guidance',
100
+ 'prose',
101
+ ]);
102
+
80
103
  /**
81
104
  * Everything the table reads from the catalog, hashed.
82
105
  * @param {any[]} all
@@ -89,20 +112,15 @@ function fingerprint(all, cards) {
89
112
  h.update(String(cardIds.get(cards)));
90
113
  for (const c of all) {
91
114
  h.update(
92
- JSON.stringify([
93
- c.domain,
94
- c.name,
95
- c._topic,
96
- c._section,
97
- c._resultName,
98
- c._package,
99
- c.description,
100
- c.keywords,
101
- c.aliases,
102
- c.titles,
103
- (c.guidance ?? []).slice(0, 10),
104
- (c.prose ?? []).slice(0, 4),
105
- ]),
115
+ JSON.stringify(
116
+ HASHED_FIELDS.map(f =>
117
+ f === 'guidance'
118
+ ? (c.guidance ?? []).slice(0, GUIDANCE_LINES)
119
+ : f === 'prose'
120
+ ? (c.prose ?? []).slice(0, PROSE_PARAGRAPHS)
121
+ : c[f],
122
+ ),
123
+ ),
106
124
  );
107
125
  }
108
126
  return h.digest('hex');
@@ -113,7 +131,7 @@ function fingerprint(all, cards) {
113
131
  * @param {Record<string, {what?: string, synonyms?: string[], props?: string[]}>} cards
114
132
  * @returns {EntryTable}
115
133
  */
116
- function buildTable(all, cards) {
134
+ export function buildTable(all, cards) {
117
135
  /** @type {Map<string, any[]>} */
118
136
  const by = new Map();
119
137
  /** @type {Map<string, string>} each id's first package */
@@ -164,8 +182,8 @@ function buildTable(all, cards) {
164
182
  ...(c.titles ?? []),
165
183
  );
166
184
  text.push(
167
- ...(c.guidance ?? []).slice(0, 10),
168
- ...(c.prose ?? []).slice(0, 4),
185
+ ...(c.guidance ?? []).slice(0, GUIDANCE_LINES),
186
+ ...(c.prose ?? []).slice(0, PROSE_PARAGRAPHS),
169
187
  );
170
188
  }
171
189
  const card =
@@ -0,0 +1,48 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The entry index is reused while the catalog's text is unchanged, so
5
+ * every field it reads must be part of the hash that decides reuse.
6
+ */
7
+
8
+ import {describe, it, expect} from 'vitest';
9
+ import * as path from 'node:path';
10
+ import {fileURLToPath} from 'node:url';
11
+ import {gatherCandidates, loadSearchData} from './_adapter.mjs';
12
+ import {HASHED_FIELDS, buildTable, entryTable} from './_entries.mjs';
13
+
14
+ const cwd = path.resolve(
15
+ path.dirname(fileURLToPath(import.meta.url)),
16
+ '../../../..',
17
+ );
18
+
19
+ describe('entry index cache', () => {
20
+ it('hashes every candidate field the index reads', async () => {
21
+ const {all} = await gatherCandidates({cwd});
22
+ /** @type {Set<string>} */
23
+ const read = new Set();
24
+ const watched = all.map(
25
+ c =>
26
+ new Proxy(c, {
27
+ get(target, key, receiver) {
28
+ if (typeof key === 'string') read.add(key);
29
+ return Reflect.get(target, key, receiver);
30
+ },
31
+ }),
32
+ );
33
+ buildTable(watched, loadSearchData().cards);
34
+ const unhashed = [...read].filter(k => !HASHED_FIELDS.includes(k));
35
+ expect(unhashed).toEqual([]);
36
+ }, 60_000);
37
+
38
+ it('rebuilds when a candidate text changes and reuses it otherwise', async () => {
39
+ const {all} = await gatherCandidates({cwd});
40
+ const {cards} = loadSearchData();
41
+ const first = entryTable([...all], cards);
42
+ expect(entryTable([...all], cards)).toBe(first);
43
+ const changed = all.map((c, i) =>
44
+ i === 0 ? {...c, description: `${c.description ?? ''} changed`} : c,
45
+ );
46
+ expect(entryTable(changed, cards)).not.toBe(first);
47
+ }, 60_000);
48
+ });
@@ -120,6 +120,10 @@ export const docs = {
120
120
  type: 'prose',
121
121
  text: '`integration verify` fails a package that needs the CLI peer and lacks it, or whose range admits a stable CLI too old for what it ships. `integration add doc --parent` and `integration add theme` write the peer for you.',
122
122
  },
123
+ {
124
+ type: 'prose',
125
+ text: "When the CLI is outside that range, `doctor integration validate` and `integration check` list a `cli_peer_version` note naming your package. A note fails nothing, `--strict` included, and `integration verify` does not report it. Below the range the note gives the commands that install a newer Core and CLI together, as dev dependencies in your own package folder, and then run `upgrade --apply`. Above it, in an app the note asks for a release of your package that supports that CLI, and in your own package folder it asks you to test your package with that CLI and widen the range.",
126
+ },
123
127
  ],
124
128
  },
125
129
  {
@@ -0,0 +1,36 @@
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 running CLI version.
6
+ * @returns {string}
7
+ */
8
+ export function cliVersion(): string;
9
+ /**
10
+ * Why the running CLI is outside an integration's declared
11
+ * `@astryxdesign/cli` peer range, or null when it is inside it (or when no
12
+ * peer is declared or the package.json cannot be read).
13
+ *
14
+ * A CLI below the range is told to upgrade Core and the CLI together, with
15
+ * the project's own install command, and then to run the upgrade codemods.
16
+ * A CLI above it (the range has an upper bound, such as `^0.6.0`) is
17
+ * told to look for a release of the package that supports it, since
18
+ * upgrading the CLI cannot help there; the author of the package in the
19
+ * current folder is told to test with this CLI and widen the range.
20
+ *
21
+ * @param {import('./integrations.mjs').LoadedIntegration} integration
22
+ * @param {string} [version] the running CLI version; defaults to this CLI's
23
+ * own package.json version
24
+ * @param {string} [cwd] where the install command would run; decides the
25
+ * package manager it names
26
+ * @param {{own?: boolean, from?: string}} [options] `own`: the package is
27
+ * the one being authored in the current folder, so above the range its
28
+ * author is told to test with this CLI and widen the range instead; `from`:
29
+ * the version the project's upgrade starts from when it is not the running
30
+ * CLI's, such as the Core of a project with no CLI of its own
31
+ * @returns {string | null}
32
+ */
33
+ export function cliPeerVersionProblem(integration: import("./integrations.mjs").LoadedIntegration, version?: string, cwd?: string, { own, from }?: {
34
+ own?: boolean;
35
+ from?: string;
36
+ }): string | null;
@@ -0,0 +1,132 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Warn when the running CLI is outside an integration's declared peer
5
+ * range.
6
+ *
7
+ * An integration published against a newer CLI declares
8
+ * `"@astryxdesign/cli": ">=X.Y.Z"` in peerDependencies. When the running CLI
9
+ * does not satisfy that range, the integration's newer contributions may not
10
+ * load correctly. This module detects that mismatch and says why, naming the
11
+ * package, the range, the running version, and what to do.
12
+ *
13
+ * @input A loaded integration (with __packageDir) and the running CLI version.
14
+ * @output The message, or null when the CLI is inside the range.
15
+ * @position foundation/integrations — read by api/integration/validate-integration,
16
+ * which reports it as a `cli_peer_version` note in `doctor integration
17
+ * validate` and `integration check`, never a warning, so it fails nothing
18
+ * (architecture:cli-surface INV35).
19
+ */
20
+
21
+ import * as fs from 'node:fs';
22
+ import * as path from 'node:path';
23
+ import {satisfiesRange, semverCompare} from '../env/semver.mjs';
24
+ import {
25
+ detectPackageManager,
26
+ getCliInvocation,
27
+ } from '../env/package-manager.mjs';
28
+ import {CLI_PACKAGE, lowestAdmitted} from './cli-requirement.mjs';
29
+
30
+ /** The command that adds a package, by package manager. */
31
+ const ADD_VERB = /** @type {Record<string, string>} */ ({
32
+ pnpm: 'pnpm add',
33
+ yarn: 'yarn add',
34
+ bun: 'bun add',
35
+ npm: 'npm install',
36
+ });
37
+
38
+ /**
39
+ * Read the CLI's own version from its package.json.
40
+ * @returns {string}
41
+ */
42
+ function readCliVersion() {
43
+ const cliPkg = path.resolve(import.meta.dirname, '..', '..', 'package.json');
44
+ return JSON.parse(fs.readFileSync(cliPkg, 'utf8')).version;
45
+ }
46
+
47
+ /** Cached CLI version, read once. @type {string | undefined} */
48
+ let _cliVersion;
49
+
50
+ /**
51
+ * The running CLI version.
52
+ * @returns {string}
53
+ */
54
+ export function cliVersion() {
55
+ if (_cliVersion == null) _cliVersion = readCliVersion();
56
+ return _cliVersion;
57
+ }
58
+
59
+ /**
60
+ * Why the running CLI is outside an integration's declared
61
+ * `@astryxdesign/cli` peer range, or null when it is inside it (or when no
62
+ * peer is declared or the package.json cannot be read).
63
+ *
64
+ * A CLI below the range is told to upgrade Core and the CLI together, with
65
+ * the project's own install command, and then to run the upgrade codemods.
66
+ * A CLI above it (the range has an upper bound, such as `^0.6.0`) is
67
+ * told to look for a release of the package that supports it, since
68
+ * upgrading the CLI cannot help there; the author of the package in the
69
+ * current folder is told to test with this CLI and widen the range.
70
+ *
71
+ * @param {import('./integrations.mjs').LoadedIntegration} integration
72
+ * @param {string} [version] the running CLI version; defaults to this CLI's
73
+ * own package.json version
74
+ * @param {string} [cwd] where the install command would run; decides the
75
+ * package manager it names
76
+ * @param {{own?: boolean, from?: string}} [options] `own`: the package is
77
+ * the one being authored in the current folder, so above the range its
78
+ * author is told to test with this CLI and widen the range instead; `from`:
79
+ * the version the project's upgrade starts from when it is not the running
80
+ * CLI's, such as the Core of a project with no CLI of its own
81
+ * @returns {string | null}
82
+ */
83
+ export function cliPeerVersionProblem(
84
+ integration,
85
+ version,
86
+ cwd = process.cwd(),
87
+ {own = false, from} = {},
88
+ ) {
89
+ const ver = version ?? cliVersion();
90
+ if (!integration.__packageDir) return null;
91
+
92
+ let pkg;
93
+ try {
94
+ pkg = JSON.parse(
95
+ fs.readFileSync(path.join(integration.__packageDir, 'package.json'), 'utf8'),
96
+ );
97
+ } catch {
98
+ return null;
99
+ }
100
+
101
+ const range = pkg?.peerDependencies?.[CLI_PACKAGE];
102
+ if (typeof range !== 'string') return null;
103
+ if (satisfiesRange(ver, range)) return null;
104
+
105
+ const name = integration.name ?? pkg.name ?? '(integration)';
106
+ const lowest = lowestAdmitted(range);
107
+ if (lowest != null && semverCompare(ver, lowest) < 0) {
108
+ // Core and the CLI move together, then the upgrade codemods run, as the
109
+ // project-upgrade notice does: moving only the CLI would leave it ahead of
110
+ // Core. A package's own folder holds them as dev dependencies.
111
+ const verb = ADD_VERB[detectPackageManager(cwd)] ?? ADD_VERB.npm;
112
+ const install = `${verb}${own ? ' -D' : ''} @astryxdesign/core@latest ${CLI_PACKAGE}@latest`;
113
+ const upgrade = `${getCliInvocation(cwd, {installed: true})} upgrade --from ${from ?? ver} --apply`;
114
+ return (
115
+ `${name} needs ${CLI_PACKAGE} ${range}, but this CLI is ${ver}, so ` +
116
+ `some of what it ships may not load. Upgrade Core and the CLI ` +
117
+ `together: \`${install}\`, then \`${upgrade}\`.`
118
+ );
119
+ }
120
+ if (own) {
121
+ return (
122
+ `${name} declares ${CLI_PACKAGE} ${range}, but this CLI is ${ver}, ` +
123
+ `outside that range. Test the package with this CLI, and if it works, ` +
124
+ `widen the ${CLI_PACKAGE} range in its peerDependencies.`
125
+ );
126
+ }
127
+ return (
128
+ `${name} supports ${CLI_PACKAGE} ${range}, but this CLI is ${ver}, ` +
129
+ `outside that range, so some of what it ships may not work as its ` +
130
+ `author tested. Look for a release of ${name} that supports ${ver}.`
131
+ );
132
+ }