@astryxdesign/cli 0.6.6-canary.fa4c5fc → 0.6.6-canary.fb78fa1

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 (82) hide show
  1. package/README.md +83 -83
  2. package/api/build/_adapter.d.mts +15 -0
  3. package/api/build/_adapter.mjs +22 -0
  4. package/api/build/build.doc.mjs +1 -1
  5. package/api/build/build.type.d.mts +4 -0
  6. package/api/build/build.type.mjs +1 -0
  7. package/api/build/help/help.mjs +1 -1
  8. package/api/build/kit/kit.mjs +12 -1
  9. package/api/doctor/_adapter.d.mts +7 -0
  10. package/api/doctor/_adapter.mjs +48 -0
  11. package/api/doctor/doctor.mjs +5 -3
  12. package/api/doctor/theme-checks.d.mts +12 -0
  13. package/api/doctor/theme-checks.mjs +115 -1
  14. package/api/doctor/theme-checks.test.mjs +142 -1
  15. package/api/init/run/run.mjs +1 -0
  16. package/api/layout/check/check.d.mts +1 -0
  17. package/api/layout/check/check.mjs +1 -0
  18. package/api/layout/expand/expand.d.mts +1 -0
  19. package/api/layout/expand/expand.mjs +1 -0
  20. package/api/layout/grammar/grammar.d.mts +1 -0
  21. package/api/layout/grammar/grammar.mjs +1 -0
  22. package/api/layout/layoutCheck.doc.mjs +1 -1
  23. package/api/layout/layoutExpand.doc.mjs +1 -1
  24. package/api/layout/layoutGrammar.doc.mjs +1 -1
  25. package/api/search/search.d.mts +43 -0
  26. package/api/search/search.domain-priority.test.mjs +247 -0
  27. package/api/search/search.mjs +170 -29
  28. package/api/template/copy/copy.mjs +12 -0
  29. package/api/template/template.doc.mjs +1 -1
  30. package/api/template/template.type.d.mts +3 -0
  31. package/api/template/template.type.mjs +3 -0
  32. package/api/theme/build/build.d.mts +70 -0
  33. package/api/theme/build/build.mjs +205 -41
  34. package/api/theme/build/font-warning.d.mts +11 -0
  35. package/api/theme/build/font-warning.mjs +28 -3
  36. package/assets/docs/author-a-theme.doc.mjs +13 -8
  37. package/assets/docs/styling-overview.doc.mjs +1 -1
  38. package/assets/docs/theme.doc.dense.mjs +1 -1
  39. package/assets/docs/theme.doc.zh.mjs +1 -1
  40. package/assets/docs/tree/layout.doc.mjs +20 -0
  41. package/assets/docs/use-a-theme.doc.mjs +6 -3
  42. package/assets/templates/pages/incident-console/page.tsx +1 -1
  43. package/assets/templates/pages/table-comparison/template.doc.mjs +1 -1
  44. package/authoring/doctypes/template/type.ts +1 -0
  45. package/clients/cli/commands/blog.mjs +3 -3
  46. package/clients/cli/commands/build-theme.adaptations.test.mjs +1 -1
  47. package/clients/cli/commands/build-theme.ascii-output.test.mjs +11 -1
  48. package/clients/cli/commands/build-theme.batch-report.test.mjs +335 -0
  49. package/clients/cli/commands/build-theme.font-warning.test.mjs +36 -7
  50. package/clients/cli/commands/build-theme.import-path.test.mjs +3 -3
  51. package/clients/cli/commands/build-theme.mjs +68 -18
  52. package/clients/cli/commands/build-theme.watch.test.mjs +33 -0
  53. package/clients/cli/commands/build.mjs +1 -0
  54. package/clients/cli/commands/docs.test.mjs +2 -1
  55. package/clients/cli/commands/doctor.doc.mjs +1 -1
  56. package/clients/cli/commands/doctor.test.mjs +17 -1
  57. package/clients/cli/commands/import-hint-correctness.test.mjs +23 -0
  58. package/clients/cli/commands/layout-check.doc.mjs +1 -0
  59. package/clients/cli/commands/layout-expand.doc.mjs +1 -0
  60. package/clients/cli/commands/layout-grammar.doc.mjs +1 -0
  61. package/clients/cli/commands/layout.deprecation-lifecycle.test.mjs +140 -0
  62. package/clients/cli/commands/layout.doc.mjs +1 -0
  63. package/clients/cli/commands/layout.mjs +6 -11
  64. package/clients/cli/commands/search.test.mjs +6 -2
  65. package/clients/cli/commands/swizzle.routing.test.mjs +2 -1
  66. package/clients/cli/commands/template.mjs +4 -3
  67. package/clients/cli/commands/theme-add-lifecycle.test.mjs +9 -6
  68. package/clients/cli/commands/theme-build.doc.mjs +3 -1
  69. package/clients/cli/commands/upgrade.config-ordering.test.mjs +2 -1
  70. package/clients/cli/index.mjs +1 -1
  71. package/clients/cli/lib/component-format.test.mjs +1 -1
  72. package/clients/cli/lib/define-command.mjs +4 -0
  73. package/foundation/agent-docs/agent-docs.mjs +4 -1
  74. package/foundation/agent-docs/agent-docs.test.mjs +18 -0
  75. package/foundation/discovery/template-needs.d.mts +31 -0
  76. package/foundation/discovery/template-needs.mjs +156 -0
  77. package/foundation/discovery/template-needs.test.mjs +203 -0
  78. package/foundation/env/package-manager.d.mts +28 -8
  79. package/foundation/env/package-manager.mjs +49 -10
  80. package/foundation/env/package-manager.test.mjs +93 -1
  81. package/foundation/response/response-types.doc.mjs +4 -4
  82. package/package.json +9 -9
@@ -0,0 +1,156 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Analyze what a scaffolded template needs that the target project lacks.
5
+ *
6
+ * Derives needs from the template's own source — its bare import specifiers —
7
+ * rather than from a hand-maintained list. Every import that is not an Astryx
8
+ * package, react/react-dom, or @stylexjs/stylex is external; the source is the
9
+ * only authority on what a template uses.
10
+ *
11
+ * Shared between `api/template/copy` (the scaffold receipt) and
12
+ * `api/build/kit` (the start recommendation).
13
+ *
14
+ * @position packages/cli/foundation/discovery — template discovery helpers;
15
+ * consumed by the template and build API leaves.
16
+ */
17
+
18
+ import * as fs from 'node:fs';
19
+ import * as path from 'node:path';
20
+ import module from 'node:module';
21
+ import {CLI_ROOT} from '../fs/paths.mjs';
22
+ import {detectStylingSystem} from '../agent-docs/agent-docs.mjs';
23
+
24
+ // ── Known packages that a template may import without the user installing them.
25
+ // react and react-dom are the framework; @astryxdesign/* is the design system
26
+ // the CLI already told the user to install; @stylexjs/stylex is a peer of Core.
27
+ const FRAMEWORK_PREFIXES = ['react', 'react-dom'];
28
+ const DESIGN_SYSTEM_SCOPE = '@astryxdesign/';
29
+ const STYLEX_RUNTIME = '@stylexjs/stylex';
30
+
31
+ // Node builtins: anything with a `node:` prefix or in builtinModules.
32
+ const NODE_BUILTINS = new Set(module.builtinModules);
33
+
34
+ /**
35
+ * Extract bare (non-relative) package names from ES import statements.
36
+ *
37
+ * @param {string} source Template source code
38
+ * @returns {Set<string>} Unique package names (scoped packages normalized to
39
+ * `@scope/name`, unscoped to the first path segment).
40
+ */
41
+ export function extractImportedPackages(source) {
42
+ // Matches `import … from '<specifier>'`, `import '<specifier>'`, and
43
+ // dynamic `import('<specifier>')`. Only bare specifiers (not starting with
44
+ // `.` or `/`).
45
+ const re = /(?:from\s+|import\s*\(?)['"]((?:@[^/'"]+\/)?[^./'"@][^'"]*)['"]/g;
46
+ /** @type {Set<string>} */
47
+ const pkgs = new Set();
48
+ let m;
49
+ while ((m = re.exec(source)) !== null) {
50
+ const spec = m[1];
51
+ // Skip Node builtins: `node:fs`, `fs`, `fs/promises`, etc.
52
+ if (spec.startsWith('node:')) continue;
53
+ const name = spec.startsWith('@')
54
+ ? spec.split('/').slice(0, 2).join('/')
55
+ : spec.split('/')[0];
56
+ if (NODE_BUILTINS.has(name)) continue;
57
+ pkgs.add(name);
58
+ }
59
+ return pkgs;
60
+ }
61
+
62
+ /**
63
+ * Detect which package manager the project uses, from its lockfile.
64
+ * @param {string} cwd Project root
65
+ * @returns {'pnpm add' | 'yarn add' | 'bun add' | 'npm install'}
66
+ */
67
+ function detectInstallCommand(cwd) {
68
+ if (fs.existsSync(path.join(cwd, 'pnpm-lock.yaml'))) return 'pnpm add';
69
+ if (fs.existsSync(path.join(cwd, 'yarn.lock'))) return 'yarn add';
70
+ if (fs.existsSync(path.join(cwd, 'bun.lockb'))) return 'bun add';
71
+ return 'npm install';
72
+ }
73
+
74
+ /**
75
+ * Read the CLI package's own devDependencies for authoritative version ranges
76
+ * of external packages the templates use.
77
+ * @returns {Record<string, string>}
78
+ */
79
+ function cliPackageRanges() {
80
+ try {
81
+ const pkgPath = path.join(CLI_ROOT, 'package.json');
82
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
83
+ return {...pkg.devDependencies};
84
+ } catch {
85
+ return {};
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Analyze what a template source needs that the target project lacks.
91
+ *
92
+ * Returns a `notes` array of human-readable setup notes, a structured
93
+ * `missingPackages` list, and an `installCommand` string ready to print.
94
+ * Each note is one actionable line.
95
+ *
96
+ * @param {string} source Template source code
97
+ * @param {string} cwd Target project directory
98
+ * @returns {{
99
+ * notes: string[],
100
+ * missingPackages: string[],
101
+ * installCommand: string | null,
102
+ * }}
103
+ */
104
+ export function analyzeTemplateNeeds(source, cwd) {
105
+ const imported = extractImportedPackages(source);
106
+
107
+ // ── External packages (not framework / design system / stylex runtime) ──
108
+ const external = [...imported].filter(
109
+ name =>
110
+ !FRAMEWORK_PREFIXES.includes(name) &&
111
+ !name.startsWith(DESIGN_SYSTEM_SCOPE) &&
112
+ name !== STYLEX_RUNTIME,
113
+ );
114
+
115
+ // Read the project's installed packages.
116
+ /** @type {Record<string, string>} */
117
+ let projectDeps = {};
118
+ try {
119
+ const pkg = JSON.parse(
120
+ fs.readFileSync(path.join(cwd, 'package.json'), 'utf-8'),
121
+ );
122
+ projectDeps = {...pkg.dependencies, ...pkg.devDependencies};
123
+ } catch {
124
+ // No package.json or unreadable — treat everything as missing.
125
+ }
126
+
127
+ const missing = external.filter(p => !(p in projectDeps));
128
+
129
+ // Build the install command with version ranges from the CLI workspace.
130
+ let installCommand = null;
131
+ if (missing.length > 0) {
132
+ const pm = detectInstallCommand(cwd);
133
+ const ranges = cliPackageRanges();
134
+ const specs = missing.map(p => (ranges[p] ? `${p}@"${ranges[p]}"` : p));
135
+ installCommand = `${pm} ${specs.join(' ')}`;
136
+ }
137
+
138
+ // ── StyleX compiler ────────────────────────────────────────────────────
139
+ const usesStylex = imported.has(STYLEX_RUNTIME);
140
+ const stylexCompilerNeeded =
141
+ usesStylex && detectStylingSystem(cwd) !== 'stylex';
142
+
143
+ // ── Notes ──────────────────────────────────────────────────────────────
144
+ /** @type {string[]} */
145
+ const notes = [];
146
+ if (missing.length > 0) {
147
+ notes.push(`Install missing dependencies: ${installCommand}`);
148
+ }
149
+ if (stylexCompilerNeeded) {
150
+ notes.push(
151
+ 'This template uses StyleX. Your project needs a StyleX compiler plugin \u2014 see `astryx docs styling-overview` for setup steps.',
152
+ );
153
+ }
154
+
155
+ return {notes, missingPackages: missing, installCommand};
156
+ }
@@ -0,0 +1,203 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file Tests for template-needs analysis: external package detection, StyleX
5
+ * compiler warning, and install command generation.
6
+ */
7
+
8
+ import {describe, it, expect, beforeEach, afterEach} from 'vitest';
9
+ import * as fs from 'node:fs';
10
+ import * as os from 'node:os';
11
+ import * as path from 'node:path';
12
+ import {
13
+ extractImportedPackages,
14
+ analyzeTemplateNeeds,
15
+ } from './template-needs.mjs';
16
+
17
+ // ── extractImportedPackages ─────────────────────────────────────────────────
18
+
19
+ describe('extractImportedPackages', () => {
20
+ it('extracts bare package names from static imports', () => {
21
+ const source = `
22
+ import {Button} from '@astryxdesign/core';
23
+ import {ArrowIcon} from '@heroicons/react/24/outline';
24
+ import * as stylex from '@stylexjs/stylex';
25
+ import {useState} from 'react';
26
+ import recharts from 'recharts';
27
+ `;
28
+ const pkgs = extractImportedPackages(source);
29
+ expect(pkgs).toEqual(
30
+ new Set([
31
+ '@astryxdesign/core',
32
+ '@heroicons/react',
33
+ '@stylexjs/stylex',
34
+ 'react',
35
+ 'recharts',
36
+ ]),
37
+ );
38
+ });
39
+
40
+ it('ignores relative and absolute imports', () => {
41
+ const source = `
42
+ import {foo} from './bar';
43
+ import {baz} from '../qux';
44
+ import {thing} from '/absolute/path';
45
+ `;
46
+ expect(extractImportedPackages(source).size).toBe(0);
47
+ });
48
+
49
+ it('ignores Node builtins with the node: prefix', () => {
50
+ const source = `
51
+ import * as fs from 'node:fs';
52
+ import * as path from 'node:path';
53
+ import {createRequire} from 'node:module';
54
+ `;
55
+ expect(extractImportedPackages(source).size).toBe(0);
56
+ });
57
+
58
+ it('ignores bare Node builtins and their subpaths', () => {
59
+ const source = `
60
+ import * as fs from 'fs';
61
+ import {join} from 'path';
62
+ import {createReadStream} from 'fs/promises';
63
+ `;
64
+ expect(extractImportedPackages(source).size).toBe(0);
65
+ });
66
+
67
+ it('handles type imports', () => {
68
+ const source = `import type {Props} from 'some-package';`;
69
+ expect(extractImportedPackages(source)).toEqual(new Set(['some-package']));
70
+ });
71
+
72
+ it('deduplicates multiple imports from the same package', () => {
73
+ const source = `
74
+ import {A} from '@heroicons/react/24/outline';
75
+ import {B} from '@heroicons/react/24/solid';
76
+ `;
77
+ expect(extractImportedPackages(source)).toEqual(
78
+ new Set(['@heroicons/react']),
79
+ );
80
+ });
81
+
82
+ it('maps subpath imports to the package root', () => {
83
+ const source = `
84
+ import debounce from 'lodash/debounce';
85
+ import {Chart} from 'recharts/es6';
86
+ `;
87
+ const pkgs = extractImportedPackages(source);
88
+ expect(pkgs).toEqual(new Set(['lodash', 'recharts']));
89
+ });
90
+ });
91
+
92
+ // ── analyzeTemplateNeeds ────────────────────────────────────────────────────
93
+
94
+ describe('analyzeTemplateNeeds', () => {
95
+ let dir;
96
+ beforeEach(() => {
97
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tmpl-needs-'));
98
+ });
99
+ afterEach(() => fs.rmSync(dir, {recursive: true, force: true}));
100
+
101
+ it('reports missing external packages with an install command', () => {
102
+ fs.writeFileSync(
103
+ path.join(dir, 'package.json'),
104
+ JSON.stringify({dependencies: {'react': '^19.0.0', '@astryxdesign/core': '^0.6.0'}}),
105
+ );
106
+ const source = `
107
+ import {Button} from '@astryxdesign/core';
108
+ import {ArrowIcon} from '@heroicons/react/24/outline';
109
+ import {useState} from 'react';
110
+ `;
111
+ const result = analyzeTemplateNeeds(source, dir);
112
+ expect(result.missingPackages).toEqual(['@heroicons/react']);
113
+ expect(result.installCommand).toMatch(/npm install @heroicons\/react/);
114
+ expect(result.notes.length).toBeGreaterThanOrEqual(1);
115
+ expect(result.notes[0]).toMatch(/Install missing dependencies/);
116
+ });
117
+
118
+ it('reports nothing when all packages are installed', () => {
119
+ fs.writeFileSync(
120
+ path.join(dir, 'package.json'),
121
+ JSON.stringify({
122
+ dependencies: {
123
+ 'react': '^19.0.0',
124
+ '@astryxdesign/core': '^0.6.0',
125
+ '@heroicons/react': '^2.2.0',
126
+ },
127
+ }),
128
+ );
129
+ const source = `
130
+ import {Button} from '@astryxdesign/core';
131
+ import {ArrowIcon} from '@heroicons/react/24/outline';
132
+ `;
133
+ const result = analyzeTemplateNeeds(source, dir);
134
+ expect(result.missingPackages).toEqual([]);
135
+ expect(result.installCommand).toBeNull();
136
+ expect(result.notes).toEqual([]);
137
+ });
138
+
139
+ it('warns about StyleX compiler when template uses it and project lacks one', () => {
140
+ fs.writeFileSync(
141
+ path.join(dir, 'package.json'),
142
+ JSON.stringify({dependencies: {'@stylexjs/stylex': '^0.10.0'}}),
143
+ );
144
+ const source = `import * as stylex from '@stylexjs/stylex';`;
145
+ const result = analyzeTemplateNeeds(source, dir);
146
+ expect(result.notes).toEqual(
147
+ expect.arrayContaining([
148
+ expect.stringContaining('StyleX'),
149
+ expect.stringContaining('styling-overview'),
150
+ ]),
151
+ );
152
+ });
153
+
154
+ it('does NOT warn about StyleX when the project has a compiler', () => {
155
+ fs.writeFileSync(
156
+ path.join(dir, 'package.json'),
157
+ JSON.stringify({
158
+ devDependencies: {
159
+ '@stylexjs/stylex': '^0.10.0',
160
+ '@stylexjs/rollup-plugin': '^0.10.0',
161
+ },
162
+ }),
163
+ );
164
+ const source = `import * as stylex from '@stylexjs/stylex';`;
165
+ const result = analyzeTemplateNeeds(source, dir);
166
+ const stylexNotes = result.notes.filter(n => n.includes('StyleX'));
167
+ expect(stylexNotes).toEqual([]);
168
+ });
169
+
170
+ it('detects pnpm from lockfile', () => {
171
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
172
+ fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
173
+ const source = `import {Chart} from 'recharts';`;
174
+ const result = analyzeTemplateNeeds(source, dir);
175
+ expect(result.installCommand).toMatch(/^pnpm add /);
176
+ });
177
+
178
+ it('detects yarn from lockfile', () => {
179
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
180
+ fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
181
+ const source = `import {Chart} from 'recharts';`;
182
+ const result = analyzeTemplateNeeds(source, dir);
183
+ expect(result.installCommand).toMatch(/^yarn add /);
184
+ });
185
+
186
+ it('excludes @stylexjs/stylex from missing packages (it is a Core peer)', () => {
187
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
188
+ const source = `import * as stylex from '@stylexjs/stylex';`;
189
+ const result = analyzeTemplateNeeds(source, dir);
190
+ expect(result.missingPackages).not.toContain('@stylexjs/stylex');
191
+ });
192
+
193
+ it('handles a template with no external imports', () => {
194
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
195
+ const source = `
196
+ import {useState} from 'react';
197
+ import {Button} from '@astryxdesign/core';
198
+ `;
199
+ const result = analyzeTemplateNeeds(source, dir);
200
+ expect(result.notes).toEqual([]);
201
+ expect(result.missingPackages).toEqual([]);
202
+ });
203
+ });
@@ -90,22 +90,42 @@ export function getDlxPrefix(targetDir?: string): string;
90
90
  *
91
91
  * We sniff the entry path (`process.argv[1]`) for well-known runner-cache
92
92
  * markers. This errs safe in both directions: a false negative falls back to
93
- * the installed form (`<prefix> astryx`, the historical behavior), and a false
94
- * positive emits the always-valid scoped form (`<dlx> @astryxdesign/cli`).
93
+ * {@link getCliInvocation}'s on-disk check, and a false positive emits the
94
+ * always-valid scoped form (`<dlx> @astryxdesign/cli`).
95
95
  *
96
96
  * @returns {boolean}
97
97
  */
98
98
  export function isCliOneOff(): boolean;
99
+ /**
100
+ * Does the bare `astryx` bin resolve from `targetDir`?
101
+ *
102
+ * A package runner finds an installed bin in `node_modules/.bin`, in the
103
+ * project or in a folder above it (a workspace root). When no such link
104
+ * exists, `npx astryx` and `bunx astryx` fetch the unrelated registry package
105
+ * named `astryx` instead of running this CLI, and `pnpm exec astryx` or
106
+ * `yarn astryx` fail. A global install, or a workspace install running in a
107
+ * fresh package, is exactly that case.
108
+ *
109
+ * A false negative (a layout without `node_modules/.bin`, such as Yarn Plug'n'Play)
110
+ * is safe: the caller suggests the scoped package, which always resolves.
111
+ *
112
+ * @param {string} [targetDir=process.cwd()]
113
+ * @returns {boolean}
114
+ */
115
+ export function cliBinResolves(targetDir?: string): boolean;
99
116
  /**
100
117
  * The safe, install-aware CLI invocation stem to suggest to users.
101
118
  *
102
- * - Installed / global / dev: `<run-prefix> astryx` (e.g. `pnpm exec astryx`).
103
- * Bare `astryx` resolves to the local (or global) binary.
104
- * - One-off (npx/dlx cache): `<dlx-prefix> @astryxdesign/cli` — the bare
105
- * `astryx` name isn't on disk, so npm would fetch an unrelated registry
106
- * package; the scoped package always resolves to us.
119
+ * - The `astryx` bin resolves from `targetDir`: `<run-prefix> astryx`
120
+ * (e.g. `pnpm exec astryx`).
121
+ * - Launched one-off (npx/dlx cache), or the bin does not resolve from
122
+ * `targetDir` (a global install, a fresh package in a workspace):
123
+ * `<dlx-prefix> @astryxdesign/cli`. The bare `astryx` name would make npm
124
+ * fetch an unrelated registry package; the scoped package always resolves
125
+ * to this CLI.
107
126
  *
108
- * @param {string} [targetDir]
127
+ * @param {string} [targetDir] the project the printed command runs in;
128
+ * defaults to the working directory
109
129
  * @returns {string}
110
130
  */
111
131
  export function getCliInvocation(targetDir?: string): string;
@@ -6,7 +6,9 @@
6
6
  * The order is: the `packageManager` field a project DECLARES, then the
7
7
  * lockfiles it happens to have, then a committed package-manager config, then
8
8
  * the runner that launched us. Returns the correct command prefix for running
9
- * package binaries (e.g. 'npx astryx', 'yarn astryx', 'pnpm exec astryx').
9
+ * package binaries (e.g. 'npx astryx', 'yarn astryx', 'pnpm exec astryx'), and
10
+ * the scoped one-off form ('npx @astryxdesign/cli') when the `astryx` bin does
11
+ * not resolve from the project.
10
12
  */
11
13
 
12
14
  import * as fs from 'node:fs';
@@ -319,8 +321,8 @@ export function getDlxPrefix(targetDir) {
319
321
  *
320
322
  * We sniff the entry path (`process.argv[1]`) for well-known runner-cache
321
323
  * markers. This errs safe in both directions: a false negative falls back to
322
- * the installed form (`<prefix> astryx`, the historical behavior), and a false
323
- * positive emits the always-valid scoped form (`<dlx> @astryxdesign/cli`).
324
+ * {@link getCliInvocation}'s on-disk check, and a false positive emits the
325
+ * always-valid scoped form (`<dlx> @astryxdesign/cli`).
324
326
  *
325
327
  * @returns {boolean}
326
328
  */
@@ -329,20 +331,57 @@ export function isCliOneOff() {
329
331
  return /\/_npx\/|\/dlx[-/]|\/\.bun\/install\/cache\/|\/bunx-/.test(entry);
330
332
  }
331
333
 
334
+ /** The `astryx` bin as package managers link it, including the Windows shims. */
335
+ const CLI_BIN_LINKS = [CLI_BIN, `${CLI_BIN}.cmd`, `${CLI_BIN}.ps1`];
336
+
337
+ /**
338
+ * Does the bare `astryx` bin resolve from `targetDir`?
339
+ *
340
+ * A package runner finds an installed bin in `node_modules/.bin`, in the
341
+ * project or in a folder above it (a workspace root). When no such link
342
+ * exists, `npx astryx` and `bunx astryx` fetch the unrelated registry package
343
+ * named `astryx` instead of running this CLI, and `pnpm exec astryx` or
344
+ * `yarn astryx` fail. A global install, or a workspace install running in a
345
+ * fresh package, is exactly that case.
346
+ *
347
+ * A false negative (a layout without `node_modules/.bin`, such as Yarn Plug'n'Play)
348
+ * is safe: the caller suggests the scoped package, which always resolves.
349
+ *
350
+ * @param {string} [targetDir=process.cwd()]
351
+ * @returns {boolean}
352
+ */
353
+ export function cliBinResolves(targetDir = process.cwd()) {
354
+ let dir = path.resolve(targetDir);
355
+ for (;;) {
356
+ const binDir = path.join(dir, 'node_modules', '.bin');
357
+ if (CLI_BIN_LINKS.some(name => fs.existsSync(path.join(binDir, name)))) {
358
+ return true;
359
+ }
360
+ const parent = path.dirname(dir);
361
+ if (parent === dir) return false;
362
+ dir = parent;
363
+ }
364
+ }
365
+
332
366
  /**
333
367
  * The safe, install-aware CLI invocation stem to suggest to users.
334
368
  *
335
- * - Installed / global / dev: `<run-prefix> astryx` (e.g. `pnpm exec astryx`).
336
- * Bare `astryx` resolves to the local (or global) binary.
337
- * - One-off (npx/dlx cache): `<dlx-prefix> @astryxdesign/cli` — the bare
338
- * `astryx` name isn't on disk, so npm would fetch an unrelated registry
339
- * package; the scoped package always resolves to us.
369
+ * - The `astryx` bin resolves from `targetDir`: `<run-prefix> astryx`
370
+ * (e.g. `pnpm exec astryx`).
371
+ * - Launched one-off (npx/dlx cache), or the bin does not resolve from
372
+ * `targetDir` (a global install, a fresh package in a workspace):
373
+ * `<dlx-prefix> @astryxdesign/cli`. The bare `astryx` name would make npm
374
+ * fetch an unrelated registry package; the scoped package always resolves
375
+ * to this CLI.
340
376
  *
341
- * @param {string} [targetDir]
377
+ * @param {string} [targetDir] the project the printed command runs in;
378
+ * defaults to the working directory
342
379
  * @returns {string}
343
380
  */
344
381
  export function getCliInvocation(targetDir) {
345
- if (isCliOneOff()) return `${getDlxPrefix(targetDir)} ${CLI_PACKAGE}`;
382
+ if (isCliOneOff() || !cliBinResolves(targetDir)) {
383
+ return `${getDlxPrefix(targetDir)} ${CLI_PACKAGE}`;
384
+ }
346
385
  return `${getRunPrefix(targetDir)} ${CLI_BIN}`;
347
386
  }
348
387
 
@@ -9,6 +9,7 @@ import {
9
9
  explainPackageManager,
10
10
  getDlxPrefix,
11
11
  isCliOneOff,
12
+ cliBinResolves,
12
13
  getCliInvocation,
13
14
  formatCliCommand,
14
15
  } from './package-manager.mjs';
@@ -31,6 +32,16 @@ function makeTmpDir() {
31
32
  return tmpDir;
32
33
  }
33
34
 
35
+ /** Install the CLI's bin link in `dir`, the way a package manager does. */
36
+ function linkCliBin(dir, name = 'astryx') {
37
+ const binDir = path.join(dir, 'node_modules', '.bin');
38
+ fs.mkdirSync(binDir, {recursive: true});
39
+ fs.writeFileSync(path.join(binDir, name), '');
40
+ }
41
+
42
+ /** An installed CLI's entry, outside any runner cache (a global or workspace install). */
43
+ const INSTALLED_ENTRY = '/usr/local/lib/node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs';
44
+
34
45
  describe('detectPackageManager', () => {
35
46
  it('detects yarn from yarn.lock', () => {
36
47
  const dir = makeTmpDir();
@@ -79,6 +90,7 @@ describe('detectPackageManager', () => {
79
90
  const dir = makeTmpDir();
80
91
  fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
81
92
  fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
93
+ linkCliBin(dir);
82
94
  process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
83
95
  expect(detectPackageManager(dir)).not.toBe('yarn');
84
96
  expect(getCliInvocation(dir)).toBe('npx astryx');
@@ -90,6 +102,7 @@ describe('detectPackageManager', () => {
90
102
  try {
91
103
  fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
92
104
  fs.writeFileSync(path.join(dir, 'yarn.lock'), '');
105
+ linkCliBin(dir);
93
106
  process.env.npm_config_user_agent = 'yarn/1.22.21 npm/? node/v22.0.0';
94
107
  process.argv[1] = path.join(dir, 'node_modules/.bin/astryx');
95
108
  expect(getCliInvocation(dir)).toBe('npx astryx');
@@ -198,6 +211,7 @@ describe('detectPackageManager', () => {
198
211
  path.join(dir, 'package.json'),
199
212
  JSON.stringify({packageManager: 'pnpm@8.0.0'}),
200
213
  );
214
+ linkCliBin(dir);
201
215
  expect(detectPackageManager(dir)).toBe('pnpm');
202
216
  expect(getCliInvocation(dir)).toBe('pnpm exec astryx');
203
217
  });
@@ -351,14 +365,90 @@ describe('isCliOneOff', () => {
351
365
  });
352
366
  });
353
367
 
368
+ describe('cliBinResolves', () => {
369
+ it('finds the bin link in the project', () => {
370
+ const dir = makeTmpDir();
371
+ linkCliBin(dir);
372
+ expect(cliBinResolves(dir)).toBe(true);
373
+ });
374
+
375
+ it('finds it in a folder above the project (a workspace root)', () => {
376
+ const root = makeTmpDir();
377
+ linkCliBin(root);
378
+ const pkg = path.join(root, 'packages', 'app');
379
+ fs.mkdirSync(pkg, {recursive: true});
380
+ expect(cliBinResolves(pkg)).toBe(true);
381
+ });
382
+
383
+ it('finds a Windows shim', () => {
384
+ const dir = makeTmpDir();
385
+ linkCliBin(dir, 'astryx.cmd');
386
+ expect(cliBinResolves(dir)).toBe(true);
387
+ });
388
+
389
+ it('is false when no bin link exists up the tree', () => {
390
+ const dir = makeTmpDir();
391
+ fs.mkdirSync(path.join(dir, 'node_modules', '.bin'), {recursive: true});
392
+ expect(cliBinResolves(dir)).toBe(false);
393
+ });
394
+ });
395
+
354
396
  describe('getCliInvocation', () => {
355
- it('uses the run-prefix + bare bin when installed (not one-off)', () => {
397
+ it('uses the run-prefix + bare bin when the bin resolves from the project', () => {
356
398
  process.argv[1] = '/proj/node_modules/@astryxdesign/cli/bin/astryx.mjs';
357
399
  const dir = makeTmpDir();
358
400
  fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
401
+ linkCliBin(dir);
359
402
  expect(getCliInvocation(dir)).toBe('pnpm exec astryx');
360
403
  });
361
404
 
405
+ it('keeps `npx astryx` for a project with a local CLI', () => {
406
+ process.argv[1] = INSTALLED_ENTRY;
407
+ const dir = makeTmpDir();
408
+ fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
409
+ linkCliBin(dir);
410
+ expect(getCliInvocation(dir)).toBe('npx astryx');
411
+ });
412
+
413
+ it('keeps the installed form in a workspace package when the root has the bin', () => {
414
+ process.argv[1] = INSTALLED_ENTRY;
415
+ const root = makeTmpDir();
416
+ fs.writeFileSync(path.join(root, 'pnpm-lock.yaml'), '');
417
+ linkCliBin(root);
418
+ const pkg = path.join(root, 'packages', 'app');
419
+ fs.mkdirSync(pkg, {recursive: true});
420
+ fs.writeFileSync(path.join(pkg, 'package.json'), '{"name":"app"}');
421
+ expect(getCliInvocation(pkg)).toBe('pnpm exec astryx');
422
+ });
423
+
424
+ // The hazard: the npm package named `astryx` is not this CLI. Launched from
425
+ // an installed path (a global install, or a workspace install running in a
426
+ // fresh package), the CLI used to print `npx astryx` for a project where that
427
+ // bin does not resolve, so following the hint fetched someone else's package.
428
+ it.each([
429
+ ['package-lock.json', '{}', 'npx @astryxdesign/cli'],
430
+ ['pnpm-lock.yaml', '', 'pnpm dlx @astryxdesign/cli'],
431
+ ['yarn.lock', '', 'yarn dlx @astryxdesign/cli'],
432
+ ['bun.lockb', '', 'bunx @astryxdesign/cli'],
433
+ ])(
434
+ 'prints the scoped package for a project with no local CLI (%s), launched from an installed path',
435
+ (lockfile, contents, expected) => {
436
+ process.argv[1] = INSTALLED_ENTRY;
437
+ const dir = makeTmpDir();
438
+ fs.writeFileSync(path.join(dir, lockfile), contents);
439
+ expect(isCliOneOff()).toBe(false);
440
+ expect(getCliInvocation(dir)).toBe(expected);
441
+ },
442
+ );
443
+
444
+ it('prints the scoped package for a fresh package with no lockfile or install', () => {
445
+ process.argv[1] = INSTALLED_ENTRY;
446
+ const dir = makeTmpDir();
447
+ delete process.env.npm_config_user_agent;
448
+ fs.writeFileSync(path.join(dir, 'package.json'), '{"name":"fresh"}');
449
+ expect(getCliInvocation(dir)).toBe('npx @astryxdesign/cli');
450
+ });
451
+
362
452
  it('uses the dlx runner + scoped package when run one-off', () => {
363
453
  process.argv[1] = '/home/u/.npm/_npx/a1b2/node_modules/.bin/astryx';
364
454
  const dir = makeTmpDir();
@@ -379,6 +469,7 @@ describe('formatCliCommand', () => {
379
469
  process.argv[1] = '/proj/node_modules/@astryxdesign/cli/bin/astryx.mjs';
380
470
  const dir = makeTmpDir();
381
471
  fs.writeFileSync(path.join(dir, 'pnpm-lock.yaml'), '');
472
+ linkCliBin(dir);
382
473
  expect(formatCliCommand('astryx component Button', dir)).toBe('pnpm exec astryx component Button');
383
474
  });
384
475
 
@@ -386,6 +477,7 @@ describe('formatCliCommand', () => {
386
477
  process.argv[1] = '/proj/node_modules/@astryxdesign/cli/bin/astryx.mjs';
387
478
  const dir = makeTmpDir();
388
479
  fs.writeFileSync(path.join(dir, 'package-lock.json'), '{}');
480
+ linkCliBin(dir);
389
481
  expect(formatCliCommand('docs tokens', dir)).toBe('npx astryx docs tokens');
390
482
  });
391
483