@kjanat/dreamcli 2.0.1 → 2.2.0

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.
@@ -0,0 +1,218 @@
1
+ #!/usr/bin/env pwsh
2
+
3
+ <#
4
+ .SYNOPSIS
5
+ Runs an end-to-end smoke test for DreamCLI PowerShell completions.
6
+
7
+ .DESCRIPTION
8
+ Generates the `pwsh-demo` PowerShell completion script, registers it in the
9
+ current session, executes a set of completion scenarios with `TabExpansion2`,
10
+ and fails if expected completion values are missing or hidden values leak into
11
+ the result set.
12
+ #>
13
+
14
+ $ErrorActionPreference = 'Stop'
15
+ Set-StrictMode -Version Latest
16
+
17
+ $root = Split-Path -Parent $MyInvocation.MyCommand.Path
18
+ $env:PATH = "$root;$env:PATH"
19
+
20
+ $completionScript = & bun "$root/src/main.ts" completions powershell | Out-String
21
+ $completionExitCode = $LASTEXITCODE
22
+ if ($completionExitCode -ne 0) {
23
+ throw "Direct Bun completion generation failed with exit code $completionExitCode."
24
+ }
25
+ $completionScript = $completionScript.TrimEnd()
26
+ if ([string]::IsNullOrWhiteSpace($completionScript)) {
27
+ throw 'No completion script was generated.'
28
+ }
29
+
30
+ $nativeCompletionScript = & pwsh-demo completions powershell | Out-String
31
+ $nativeCompletionExitCode = $LASTEXITCODE
32
+ if ($nativeCompletionExitCode -ne 0) {
33
+ throw "Native pwsh-demo completion generation failed with exit code $nativeCompletionExitCode."
34
+ }
35
+ $nativeCompletionScript = $nativeCompletionScript.TrimEnd()
36
+ if ([string]::IsNullOrWhiteSpace($nativeCompletionScript)) {
37
+ throw 'The native pwsh-demo launcher did not generate a completion script.'
38
+ }
39
+
40
+ if ($nativeCompletionScript -ne $completionScript) {
41
+ throw 'The native pwsh-demo launcher generated a different completion script than the direct Bun invocation.'
42
+ }
43
+
44
+ $nativeCompletionScript | Out-String | Invoke-Expression
45
+
46
+ <#
47
+ .SYNOPSIS
48
+ Returns completion texts for a PowerShell input string.
49
+
50
+ .DESCRIPTION
51
+ Invokes `TabExpansion2` for the provided input and returns only the
52
+ `CompletionText` values so smoke assertions can compare the visible completion
53
+ surface.
54
+
55
+ .PARAMETER InputScript
56
+ The exact PowerShell command line to expand.
57
+
58
+ .OUTPUTS
59
+ System.String[]
60
+ #>
61
+ function Get-CompletionTexts {
62
+ param([string]$InputScript)
63
+
64
+ $expanded = TabExpansion2 -inputScript $InputScript -cursorColumn $InputScript.Length
65
+ return @($expanded.CompletionMatches | ForEach-Object CompletionText)
66
+ }
67
+
68
+ <#
69
+ .SYNOPSIS
70
+ Fails when expected completion values are missing.
71
+
72
+ .DESCRIPTION
73
+ Compares the expected completion values to the actual completion results and
74
+ throws when any expected value is absent.
75
+
76
+ .PARAMETER Label
77
+ The scenario label used in the failure message.
78
+
79
+ .PARAMETER Actual
80
+ The completion texts returned by the expansion.
81
+
82
+ .PARAMETER Expected
83
+ The completion texts that must be present.
84
+ #>
85
+ function Assert-Contains {
86
+ param(
87
+ [string]$Label,
88
+ [string[]]$Actual,
89
+ [string[]]$Expected
90
+ )
91
+
92
+ $missing = @($Expected | Where-Object { $_ -notin $Actual })
93
+ if ($missing.Count -gt 0) {
94
+ throw "$Label is missing expected completions: $($missing -join ', ')"
95
+ }
96
+ }
97
+
98
+ <#
99
+ .SYNOPSIS
100
+ Fails when excluded completion values appear in the results.
101
+
102
+ .DESCRIPTION
103
+ Compares the actual completion results to a list of values that must remain
104
+ hidden and throws when any excluded value is present.
105
+
106
+ .PARAMETER Label
107
+ The scenario label used in the failure message.
108
+
109
+ .PARAMETER Actual
110
+ The completion texts returned by the expansion.
111
+
112
+ .PARAMETER Excluded
113
+ The completion texts that must not appear.
114
+ #>
115
+ function Assert-Excludes {
116
+ param(
117
+ [string]$Label,
118
+ [string[]]$Actual,
119
+ [string[]]$Excluded
120
+ )
121
+
122
+ $unexpected = @($Excluded | Where-Object { $_ -in $Actual })
123
+ if ($unexpected.Count -gt 0) {
124
+ throw "$Label included completions that should stay hidden: $($unexpected -join ', ')"
125
+ }
126
+ }
127
+
128
+ $cases = @(
129
+ @{
130
+ Label = 'Command name completion'
131
+ Input = 'pwsh-demo de'
132
+ Expected = @('deploy')
133
+ Excluded = @('debug-dump')
134
+ },
135
+ @{
136
+ Label = 'Command alias completion'
137
+ Input = 'pwsh-demo sh'
138
+ Expected = @('ship')
139
+ Excluded = @()
140
+ },
141
+ @{
142
+ Label = 'Root-surface flag completion'
143
+ Input = 'pwsh-demo --pro'
144
+ Expected = @('--profile')
145
+ Excluded = @('--account')
146
+ },
147
+ @{
148
+ Label = 'Deploy flag value completion'
149
+ Input = 'pwsh-demo deploy --region '
150
+ Expected = @('us', 'eu', 'ap')
151
+ Excluded = @()
152
+ },
153
+ @{
154
+ Label = 'Deploy flag value prefix completion'
155
+ Input = 'pwsh-demo deploy --region e'
156
+ Expected = @('eu')
157
+ Excluded = @('us', 'ap')
158
+ },
159
+ @{
160
+ Label = 'Deploy inline flag value completion'
161
+ Input = 'pwsh-demo deploy --region=e'
162
+ Expected = @('--region=eu')
163
+ Excluded = @('--region=us', '--region=ap')
164
+ },
165
+ @{
166
+ Label = 'Deploy strategy value completion'
167
+ Input = 'pwsh-demo ship --strategy '
168
+ Expected = @('rolling', 'blue-green', 'canary')
169
+ Excluded = @()
170
+ },
171
+ @{
172
+ Label = 'Status view value completion'
173
+ Input = 'pwsh-demo st --view '
174
+ Expected = @('summary', 'full', 'json')
175
+ Excluded = @()
176
+ },
177
+ @{
178
+ Label = 'Root default-command value completion'
179
+ Input = 'pwsh-demo --profile o'
180
+ Expected = @('ops')
181
+ Excluded = @('o', 'open')
182
+ },
183
+ @{
184
+ Label = 'Quoted root default-command value completion'
185
+ Input = 'pwsh-demo --profile q'
186
+ Expected = @("'qa ops'", "'qa''s'")
187
+ Excluded = @('qa ops', "qa's")
188
+ },
189
+ @{
190
+ Label = 'Quoted inline root default-command value completion'
191
+ Input = 'pwsh-demo --profile=q'
192
+ Expected = @("--profile='qa ops'", "--profile='qa''s'")
193
+ Excluded = @('--profile=qa ops', "--profile=qa's")
194
+ },
195
+ @{
196
+ Label = 'Nested subcommand completion'
197
+ Input = 'pwsh-demo config se'
198
+ Expected = @('set')
199
+ Excluded = @()
200
+ },
201
+ @{
202
+ Label = 'Option separator stops flag completion'
203
+ Input = 'pwsh-demo deploy -- --re'
204
+ Expected = @()
205
+ Excluded = @('--region', '--approval', '-r')
206
+ }
207
+ )
208
+
209
+ foreach ($case in $cases) {
210
+ $actual = Get-CompletionTexts -InputScript $case.Input
211
+ Assert-Contains -Label $case.Label -Actual $actual -Expected $case.Expected
212
+ Assert-Excludes -Label $case.Label -Actual $actual -Excluded $case.Excluded
213
+
214
+ Write-Host "`n$($case.Label):"
215
+ $actual | Sort-Object | ForEach-Object { Write-Host " $_" }
216
+ }
217
+
218
+ Write-Host "`nPowerShell completion smoke test passed."
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Smoke tests for the PowerShell completion playground.
3
+ *
4
+ * @module
5
+ */
6
+ /// <reference types="bun" />
7
+
8
+ import { describe, expect, it } from 'bun:test';
9
+
10
+ import { pwshDemo } from './main.ts';
11
+
12
+ describe('pwsh-demo example', () => {
13
+ it('generates a PowerShell script with native registration', async () => {
14
+ const result = await pwshDemo.execute(['completions', 'powershell']);
15
+
16
+ expect(result.exitCode).toBe(0);
17
+
18
+ const script = result.stdout.join('');
19
+ expect(script).toContain('# PowerShell completion for pwsh-demo');
20
+ expect(script).toContain('Register-ArgumentCompleter -Native -CommandName');
21
+ expect(script).toContain('ship');
22
+ expect(script).toContain('blue-green');
23
+ expect(script).not.toContain('debug-dump');
24
+ expect(script).toContain("Forms = @('--profile', '-p')");
25
+ });
26
+
27
+ it('keeps hidden commands executable', async () => {
28
+ const result = await pwshDemo.execute(['debug-dump', '--section', 'completions']);
29
+
30
+ expect(result.exitCode).toBe(0);
31
+ expect(result.stdout.join('')).toContain('"section": "completions"');
32
+ });
33
+
34
+ it('surfaces default-command flags at the root', async () => {
35
+ const help = await pwshDemo.execute(['--help']);
36
+
37
+ expect(help.exitCode).toBe(0);
38
+ expect(help.stdout.join('')).toContain('open');
39
+
40
+ const result = await pwshDemo.execute(['bravo', '--profile', 'ops', '--shell', 'cmd']);
41
+
42
+ expect(result.exitCode).toBe(0);
43
+ expect(result.stdout).toEqual([
44
+ 'Opening bravo with ops profile in cmd\n',
45
+ 'Format: table\n',
46
+ ]);
47
+ });
48
+ });
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * PowerShell completion playground for DreamCLI.
4
+ *
5
+ * Usage:
6
+ * bun --cwd=examples/pwsh-demo src/main.ts --help
7
+ * bun --cwd=examples/pwsh-demo src/main.ts completions powershell
8
+ * bun --cwd=examples/pwsh-demo src/main.ts deploy --region eu --strategy canary
9
+ * bun --cwd=examples/pwsh-demo src/main.ts config set theme midnight --scope workspace
10
+ *
11
+ * @module
12
+ */
13
+
14
+ import { arg, cli, command, flag, group } from '@kjanat/dreamcli';
15
+
16
+ const open = command('open')
17
+ .description('Open a workspace session')
18
+ .alias('o')
19
+ .arg(
20
+ 'workspace',
21
+ arg.enum(['alpha', 'bravo', 'charlie']).default('alpha').describe('Workspace to open'),
22
+ )
23
+ .flag(
24
+ 'profile',
25
+ flag
26
+ .enum(['default', 'ops', 'readonly', 'qa ops', "qa's"])
27
+ .alias('p')
28
+ .alias('account', { hidden: true })
29
+ .describe('Credential profile'),
30
+ )
31
+ .flag(
32
+ 'shell',
33
+ flag.enum(['powershell', 'cmd', 'bash']).default('powershell').describe('Interactive shell'),
34
+ )
35
+ .flag('format', flag.enum(['table', 'json', 'yaml']).alias('f').describe('Output format'))
36
+ .flag('verbose', flag.boolean().alias('v').describe('Verbose logging'))
37
+ .action(({ args, flags, out }) => {
38
+ out.log(`Opening ${args.workspace} with ${flags.profile ?? 'default'} profile in ${flags.shell}`);
39
+ out.log(`Format: ${flags.format ?? 'table'}`);
40
+ if (flags.verbose) out.log('Verbose output enabled');
41
+ });
42
+
43
+ const deploy = command('deploy')
44
+ .description('Deploy the selected workspace')
45
+ .alias('ship')
46
+ .arg(
47
+ 'target',
48
+ arg.enum(['dev', 'staging', 'prod']).default('staging').describe('Deployment target'),
49
+ )
50
+ .flag('region', flag.enum(['us', 'eu', 'ap']).alias('r').describe('Target region'))
51
+ .flag(
52
+ 'strategy',
53
+ flag.enum(['rolling', 'blue-green', 'canary']).alias('s').describe('Deployment strategy'),
54
+ )
55
+ .flag('approval', flag.enum(['manual', 'auto']).describe('Approval mode'))
56
+ .flag('dryRun', flag.boolean().alias('d').describe('Preview the rollout without applying it'))
57
+ .action(({ args, flags, out }) => {
58
+ out.log(`Deploying ${args.target} to ${flags.region ?? 'us'} with ${flags.strategy ?? 'rolling'}`);
59
+ out.log(`Approval: ${flags.approval ?? 'manual'}`);
60
+ if (flags.dryRun) out.log('Dry run only');
61
+ });
62
+
63
+ const status = command('status')
64
+ .description('Show workspace status')
65
+ .alias('st')
66
+ .flag('view', flag.enum(['summary', 'full', 'json']).default('summary').describe('Status view'))
67
+ .flag('watch', flag.boolean().alias('w').describe('Refresh continuously'))
68
+ .action(({ flags, out }) => {
69
+ out.log(`Status view: ${flags.view}`);
70
+ if (flags.watch) out.log('Watching for changes');
71
+ });
72
+
73
+ const configGet = command('get')
74
+ .description('Read a saved setting')
75
+ .alias('show')
76
+ .arg('key', arg.enum(['theme', 'region', 'profile']).describe('Setting to read'))
77
+ .action(({ args, out }) => {
78
+ out.log(`${args.key}=demo-value`);
79
+ });
80
+
81
+ const configSet = command('set')
82
+ .description('Write a saved setting')
83
+ .arg('key', arg.enum(['theme', 'region', 'profile']).describe('Setting to write'))
84
+ .arg('value', arg.string().describe('New value'))
85
+ .flag('scope', flag.enum(['user', 'workspace']).alias('s').default('user').describe('Config scope'))
86
+ .action(({ args, flags, out }) => {
87
+ out.log(`Saved ${args.key}=${args.value} to ${flags.scope} scope`);
88
+ });
89
+
90
+ const configReset = command('reset')
91
+ .description('Reset a saved setting')
92
+ .alias('rm')
93
+ .arg('key', arg.enum(['theme', 'region', 'profile']).describe('Setting to reset'))
94
+ .flag('scope', flag.enum(['user', 'workspace']).default('user').describe('Config scope'))
95
+ .action(({ args, flags, out }) => {
96
+ out.log(`Reset ${args.key} in ${flags.scope} scope`);
97
+ });
98
+
99
+ const config = group('config')
100
+ .description('Manage saved settings')
101
+ .command(configGet)
102
+ .command(configSet)
103
+ .command(configReset);
104
+
105
+ const debugDump = command('debug-dump')
106
+ .description('Dump internal playground state')
107
+ .hidden()
108
+ .flag(
109
+ 'section',
110
+ flag.enum(['schema', 'completions', 'runtime']).default('schema').describe('Section to inspect'),
111
+ )
112
+ .action(({ flags, out }) => {
113
+ out.log(JSON.stringify({ section: flags.section, hidden: true }, null, 2));
114
+ });
115
+
116
+ /**
117
+ * PowerShell completion playground CLI used by docs, smoke checks, and manual shell testing.
118
+ */
119
+ export const pwshDemo = cli('pwsh-demo')
120
+ .packageJson()
121
+ .default(open)
122
+ .command(deploy)
123
+ .command(status)
124
+ .command(config)
125
+ .command(debugDump)
126
+ .completions({ rootMode: 'surface' });
127
+
128
+ if (import.meta.main) {
129
+ pwshDemo.run();
130
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kjanat/dreamcli",
3
- "version": "2.0.1",
3
+ "version": "2.2.0",
4
4
  "description": "Schema-first, fully typed TypeScript CLI framework",
5
5
  "keywords": [
6
6
  "cli",
@@ -102,13 +102,16 @@
102
102
  "typecheck:tsc": "tsc --noEmit",
103
103
  "upgrade": "bun update --latest && bun add -D vitepress@next"
104
104
  },
105
+ "overrides": {
106
+ "vitepress": "next"
107
+ },
105
108
  "devDependencies": {
106
109
  "@arethetypeswrong/core": "^0.18.2",
107
110
  "@biomejs/biome": "^2.4.10",
108
111
  "@iarna/toml": "^2.2.5",
109
112
  "@shikijs/transformers": "^4.0.2",
110
113
  "@shikijs/vitepress-twoslash": "^4.0.2",
111
- "@types/bun": "^1.3.0",
114
+ "@types/bun": "^1.3.12",
112
115
  "@types/deno": "^2.5.0",
113
116
  "@types/node": ">=22.0.0, <23.0.0",
114
117
  "@typescript/native-preview": "^7.0.0-dev.20260406.1",
@@ -121,17 +124,15 @@
121
124
  "tsdown": "^0.21.7",
122
125
  "typedoc": "^0.28.18",
123
126
  "typescript": "^6.0.2",
127
+ "vite": "^8",
124
128
  "vitepress": "^2.0.0-alpha.17",
125
129
  "vitest": "^4.1.2",
126
130
  "wrangler": "^4.80.0",
127
131
  "yaml": "^2.8.3"
128
132
  },
129
- "optionalDependencies": {
130
- "vite": "^8"
131
- },
132
- "packageManager": "bun@1.3.11",
133
+ "packageManager": "bun@1.3.12",
133
134
  "engines": {
134
- "bun": ">=1.3.11",
135
+ "bun": ">=1.3",
135
136
  "deno": ">=2.6.0",
136
137
  "node": ">=22.22.2"
137
138
  },
@@ -146,7 +147,7 @@
146
147
  }
147
148
  },
148
149
  "volta": {
149
- "node": "25.8.2",
150
+ "node": "25.9.0",
150
151
  "npm": "11.12.1"
151
152
  },
152
153
  "publishConfig": {
@@ -154,7 +155,7 @@
154
155
  "provenance": true
155
156
  },
156
157
  "catalog": {
157
- "@types/bun": "^1.3.0",
158
+ "@types/bun": "^1.3.12",
158
159
  "@types/node": ">=22.0.0, <23.0.0",
159
160
  "typescript": "^6.0.2"
160
161
  }
@@ -12,6 +12,7 @@
12
12
  import type { CompletionOptions, Shell } from '#internals/core/completion/index.ts';
13
13
  import { generateCompletion, SHELLS } from '#internals/core/completion/index.ts';
14
14
  import type { FormatLoader } from '#internals/core/config/index.ts';
15
+ import type { PackageJsonData } from '#internals/core/config/package-json.ts';
15
16
  import { CLIError } from '#internals/core/errors/index.ts';
16
17
  import { buildRunResult, executeCommand } from '#internals/core/execution/index.ts';
17
18
  import type { HelpOptions } from '#internals/core/help/index.ts';
@@ -228,6 +229,26 @@ interface PackageJsonSettings {
228
229
  * @defaultValue `false`
229
230
  */
230
231
  readonly inferName: boolean;
232
+ /**
233
+ * Explicit filesystem anchor for discovery; overrides `adapter.cwd`.
234
+ *
235
+ * Resolved to a string path before storage. When set, `discoverPackageJson`
236
+ * walks up from here instead of the runtime cwd. Required for installable
237
+ * CLIs whose version should reflect THEIR OWN package, not the consumer's
238
+ * working directory.
239
+ */
240
+ readonly from: string | undefined;
241
+ /**
242
+ * Pre-loaded data; skips filesystem discovery, uses values verbatim.
243
+ *
244
+ * @example
245
+ * ```ts
246
+ * import pkg from './package.json' with { type: 'json' };
247
+ *
248
+ * cli('mycli').packageJson(pkg);
249
+ * ```
250
+ */
251
+ readonly data: PackageJsonData | undefined;
231
252
  }
232
253
 
233
254
  // --- Options for execute/run
@@ -429,6 +450,35 @@ class CLIBuilder {
429
450
  });
430
451
  }
431
452
 
453
+ /**
454
+ * Enable package.json metadata from pre-loaded data.
455
+ *
456
+ * Pass an already-imported `package.json` to skip filesystem discovery
457
+ * entirely — useful for bundled or installable CLIs where the version
458
+ * should be locked at build time. The data's `version`/`description` are
459
+ * merged into the CLI schema immediately, so this form works in **both**
460
+ * `.run()` and `.execute()` (the filesystem-free path). Explicit
461
+ * `.version()`/`.description()` calls still take precedence, and the data
462
+ * form does not infer the CLI name.
463
+ *
464
+ * Detected by field shape: an object carrying at least one of
465
+ * `name`/`version`/`description`/`bin`. An empty `{}` or a settings-shaped
466
+ * object falls through to the settings overload.
467
+ *
468
+ * @param data - Pre-loaded `package.json` metadata.
469
+ *
470
+ * @example
471
+ * ```ts
472
+ * import pkg from './package.json' with { type: 'json' };
473
+ *
474
+ * // No filesystem; works in .run() AND .execute():
475
+ * cli('mycli')
476
+ * .packageJson(pkg)
477
+ * .command(deploy)
478
+ * .run();
479
+ * ```
480
+ */
481
+ packageJson(data: PackageJsonData): CLIBuilder;
432
482
  /**
433
483
  * Enable automatic package.json metadata discovery.
434
484
  *
@@ -437,10 +487,15 @@ class CLIBuilder {
437
487
  * into the CLI schema. Explicit `.version()` and `.description()`
438
488
  * calls always take precedence over discovered values.
439
489
  *
440
- * Has no effect in `.execute()` (which is filesystem-free by design).
490
+ * Has no effect in `.execute()` (which is filesystem-free by design) —
491
+ * use the {@link CLIBuilder.packageJson | data overload} for that.
441
492
  *
442
- * @param settings - Optional settings. Pass `{ inferName: true }` to
443
- * also infer the CLI name from `bin` keys or the package `name` field.
493
+ * @param settings - Optional settings:
494
+ * - `inferName`: also infer the CLI name from `bin` keys or `name` field.
495
+ * - `from`: anchor discovery to a specific file/URL/path instead of `cwd`.
496
+ * Pass `import.meta.url` for installable CLIs that need to report
497
+ * THEIR OWN version (not the consumer's project version). Accepts
498
+ * string paths, `file:` URL strings, or `URL` instances.
444
499
  *
445
500
  * @example
446
501
  * ```ts
@@ -456,6 +511,12 @@ class CLIBuilder {
456
511
  * .command(deploy)
457
512
  * .run();
458
513
  *
514
+ * // Installable CLI; discover OUR package.json, not the consumer's:
515
+ * cli('mycli')
516
+ * .packageJson({ from: import.meta.url })
517
+ * .command(deploy)
518
+ * .run();
519
+ *
459
520
  * // Explicit values always win:
460
521
  * cli('mycli')
461
522
  * .packageJson()
@@ -463,11 +524,31 @@ class CLIBuilder {
463
524
  * .run();
464
525
  * ```
465
526
  */
466
- packageJson(settings?: { readonly inferName?: boolean }): CLIBuilder {
527
+ packageJson(settings?: { readonly inferName?: boolean; readonly from?: string | URL }): CLIBuilder;
528
+ packageJson(
529
+ input?: PackageJsonData | { readonly inferName?: boolean; readonly from?: string | URL },
530
+ ): CLIBuilder {
531
+ if (isPackageJsonData(input)) {
532
+ // Merge data into schema immediately so `.execute()` (which skips
533
+ // runtime preflight) still picks up version/description. Explicit
534
+ // `.version()`/`.description()` calls win, matching settings semantics.
535
+ return new CLIBuilder({
536
+ ...this.schema,
537
+ ...(this.schema.version === undefined && input.version !== undefined
538
+ ? { version: input.version }
539
+ : {}),
540
+ ...(this.schema.description === undefined && input.description !== undefined
541
+ ? { description: input.description }
542
+ : {}),
543
+ packageJsonSettings: { inferName: false, from: undefined, data: input },
544
+ });
545
+ }
467
546
  return new CLIBuilder({
468
547
  ...this.schema,
469
548
  packageJsonSettings: {
470
- inferName: settings?.inferName ?? false,
549
+ inferName: input?.inferName ?? false,
550
+ from: normalizeFromSetting(input?.from),
551
+ data: undefined,
471
552
  },
472
553
  });
473
554
  }
@@ -893,6 +974,58 @@ function inferInvocationName(argv: readonly string[]): string | undefined {
893
974
  return argv0 !== undefined ? basename(argv0) : undefined;
894
975
  }
895
976
 
977
+ // --- packageJson.from normalisation
978
+
979
+ /**
980
+ * Coerce a {@link PackageJsonSettings.from | `packageJson.from`} input
981
+ * (string path, `file:` URL string, or {@link URL} instance) to a plain
982
+ * filesystem path string. `undefined` passes through unchanged.
983
+ *
984
+ * Runtime-agnostic by design — relies only on the `URL` global (available in
985
+ * every JS runtime) rather than `node:url`, keeping core free of Node
986
+ * built-ins. Non-`file:` inputs are returned unchanged as paths.
987
+ *
988
+ * @internal
989
+ */
990
+ function normalizeFromSetting(from: string | URL | undefined): string | undefined {
991
+ if (from === undefined) return undefined;
992
+ if (from instanceof URL) {
993
+ // Only file: URLs map to a filesystem path; pass others through verbatim.
994
+ if (from.protocol !== 'file:') return from.href;
995
+ } else if (!from.startsWith('file:')) {
996
+ // Plain path (or non-file URL string) — already usable as-is.
997
+ return from;
998
+ }
999
+
1000
+ /*
1001
+ * `URL.pathname` strips the `file://` scheme/authority; `decodeURIComponent`
1002
+ * resolves percent-escapes. A leading-slash drive letter (`/C:/…`) marks a
1003
+ * Windows path — drop the slash and switch to backslashes; otherwise it is a
1004
+ * POSIX path already.
1005
+ */
1006
+ const decoded = decodeURIComponent(new URL(from).pathname);
1007
+ if (/^\/[A-Za-z]:/.test(decoded)) {
1008
+ return decoded.slice(1).replace(/\//g, '\\');
1009
+ }
1010
+ return decoded;
1011
+ }
1012
+
1013
+ /**
1014
+ * Predicate distinguishing the {@link PackageJsonData | data} overload of
1015
+ * `.packageJson()` from the settings overload at runtime.
1016
+ *
1017
+ * A value is treated as `PackageJsonData` when it's a plain object that
1018
+ * carries at least one recognised field (`name`, `version`, `description`,
1019
+ * or `bin`). An empty `{}` or a settings-shaped object (`inferName` /
1020
+ * `from`) falls through to the settings overload.
1021
+ *
1022
+ * @internal
1023
+ */
1024
+ function isPackageJsonData(value: unknown): value is PackageJsonData {
1025
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
1026
+ return 'name' in value || 'version' in value || 'description' in value || 'bin' in value;
1027
+ }
1028
+
896
1029
  // --- Factory function
897
1030
 
898
1031
  /**
@@ -11,6 +11,7 @@
11
11
 
12
12
  import type { FormatLoader } from '#internals/core/config/index.ts';
13
13
  import { discoverConfig } from '#internals/core/config/index.ts';
14
+ import type { PackageJsonData } from '#internals/core/config/package-json.ts';
14
15
  import { discoverPackageJson, inferCliName } from '#internals/core/config/package-json.ts';
15
16
  import { CLIError, ParseError } from '#internals/core/errors/index.ts';
16
17
  import type { Verbosity } from '#internals/core/output/index.ts';
@@ -34,6 +35,10 @@ interface RuntimeConfigSettings {
34
35
  interface RuntimePackageJsonSettings {
35
36
  /** Whether to infer the CLI binary name from `package.json` `bin` field. */
36
37
  readonly inferName: boolean;
38
+ /** Explicit anchor (resolved path) for discovery; `undefined` falls back to `adapter.cwd`. */
39
+ readonly from: string | undefined;
40
+ /** Pre-loaded data; when set, discovery is skipped entirely. */
41
+ readonly data: PackageJsonData | undefined;
37
42
  }
38
43
 
39
44
  /**
@@ -276,7 +281,9 @@ async function applyPackageJsonDiscovery(
276
281
  const packageSchema =
277
282
  packageJsonSettings !== undefined && !isCompletions
278
283
  ? await (async (): Promise<RuntimePreflightSchemaLike> => {
279
- const pkg = await discoverPackageJson(adapter);
284
+ // Pre-loaded data short-circuits filesystem discovery entirely.
285
+ const pkg =
286
+ packageJsonSettings.data ?? (await discoverPackageJson(adapter, packageJsonSettings.from));
280
287
  if (pkg === null) return schema;
281
288
 
282
289
  const inferredName = packageJsonSettings.inferName ? inferCliName(pkg) : undefined;