@kjanat/dreamcli 2.1.0 → 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.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,24 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.2.0] - 2026-06-09
11
+
12
+ ### Added
13
+
14
+ - **`.packageJson(data)` — pre-loaded metadata** — `CLIBuilder.packageJson()` now accepts an
15
+ already-imported `package.json` object (e.g. `import pkg from './package.json' with { type: 'json' }`),
16
+ skipping filesystem discovery entirely. The data is detected via field shape (`name`/`version`/
17
+ `description`/`bin`), and its `version`/`description` are merged into the CLI schema at builder time
18
+ so the data form works in **both** `.run()` and `.execute()` (the filesystem-free path that
19
+ previously couldn't consume `.packageJson()` at all). Explicit `.version()`/`.description()` still
20
+ win; an empty `{}` or a settings-shaped object falls through to the settings overload, so this is a
21
+ non-breaking addition.
22
+ - **`.packageJson({ from })` — anchored discovery** — discovery can now be anchored to an explicit
23
+ location instead of the runtime cwd. Pass `{ from: import.meta.url }` (also accepts path strings,
24
+ `file:` URL strings, or `URL` instances) so installable CLIs (`npm i -g`, `bunx`, `npx`) report
25
+ their OWN version from any working directory. `discoverPackageJson(adapter, startDir?)` gained a
26
+ matching optional anchor parameter.
27
+
10
28
  ## [2.1.0] - 2026-04-16
11
29
 
12
30
  ### Added
@@ -746,7 +764,8 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
746
764
  - MIT License.
747
765
  - Markdownlint configuration.
748
766
 
749
- [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.1.0...HEAD
767
+ [Unreleased]: https://github.com/kjanat/dreamcli/compare/v2.2.0...HEAD
768
+ [2.2.0]: https://github.com/kjanat/dreamcli/compare/v2.1.0...v2.2.0
750
769
  [2.1.0]: https://github.com/kjanat/dreamcli/compare/v2.0.1...v2.1.0
751
770
  [2.0.1]: https://github.com/kjanat/dreamcli/compare/v2.0.0...v2.0.1
752
771
  [2.0.0]: https://github.com/kjanat/dreamcli/compare/v1.0.0...v2.0.0
@@ -5,6 +5,7 @@ import { RunOptions, RunResult } from "../schema/run.mjs";
5
5
  import { CommandBuilder, ErasedCommand } from "../schema/command.mjs";
6
6
  import { CompletionOptions } from "../completion/shells/shared.mjs";
7
7
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
8
+ import { PackageJsonData } from "../config/package-json.mjs";
8
9
  import { FormatLoader } from "../config/index.mjs";
9
10
  import { formatRootHelp } from "./root-help.mjs";
10
11
 
@@ -96,6 +97,26 @@ interface PackageJsonSettings {
96
97
  * @defaultValue `false`
97
98
  */
98
99
  readonly inferName: boolean;
100
+ /**
101
+ * Explicit filesystem anchor for discovery; overrides `adapter.cwd`.
102
+ *
103
+ * Resolved to a string path before storage. When set, `discoverPackageJson`
104
+ * walks up from here instead of the runtime cwd. Required for installable
105
+ * CLIs whose version should reflect THEIR OWN package, not the consumer's
106
+ * working directory.
107
+ */
108
+ readonly from: string | undefined;
109
+ /**
110
+ * Pre-loaded data; skips filesystem discovery, uses values verbatim.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * import pkg from './package.json' with { type: 'json' };
115
+ *
116
+ * cli('mycli').packageJson(pkg);
117
+ * ```
118
+ */
119
+ readonly data: PackageJsonData | undefined;
99
120
  }
100
121
  /**
101
122
  * Options for {@linkcode CLIBuilder.execute | .execute()} and {@linkcode CLIBuilder.run | .run()}.
@@ -219,6 +240,35 @@ declare class CLIBuilder {
219
240
  * ```
220
241
  */
221
242
  configLoader(loader: FormatLoader): CLIBuilder;
243
+ /**
244
+ * Enable package.json metadata from pre-loaded data.
245
+ *
246
+ * Pass an already-imported `package.json` to skip filesystem discovery
247
+ * entirely — useful for bundled or installable CLIs where the version
248
+ * should be locked at build time. The data's `version`/`description` are
249
+ * merged into the CLI schema immediately, so this form works in **both**
250
+ * `.run()` and `.execute()` (the filesystem-free path). Explicit
251
+ * `.version()`/`.description()` calls still take precedence, and the data
252
+ * form does not infer the CLI name.
253
+ *
254
+ * Detected by field shape: an object carrying at least one of
255
+ * `name`/`version`/`description`/`bin`. An empty `{}` or a settings-shaped
256
+ * object falls through to the settings overload.
257
+ *
258
+ * @param data - Pre-loaded `package.json` metadata.
259
+ *
260
+ * @example
261
+ * ```ts
262
+ * import pkg from './package.json' with { type: 'json' };
263
+ *
264
+ * // No filesystem; works in .run() AND .execute():
265
+ * cli('mycli')
266
+ * .packageJson(pkg)
267
+ * .command(deploy)
268
+ * .run();
269
+ * ```
270
+ */
271
+ packageJson(data: PackageJsonData): CLIBuilder;
222
272
  /**
223
273
  * Enable automatic package.json metadata discovery.
224
274
  *
@@ -227,10 +277,15 @@ declare class CLIBuilder {
227
277
  * into the CLI schema. Explicit `.version()` and `.description()`
228
278
  * calls always take precedence over discovered values.
229
279
  *
230
- * Has no effect in `.execute()` (which is filesystem-free by design).
280
+ * Has no effect in `.execute()` (which is filesystem-free by design) —
281
+ * use the {@link CLIBuilder.packageJson | data overload} for that.
231
282
  *
232
- * @param settings - Optional settings. Pass `{ inferName: true }` to
233
- * also infer the CLI name from `bin` keys or the package `name` field.
283
+ * @param settings - Optional settings:
284
+ * - `inferName`: also infer the CLI name from `bin` keys or `name` field.
285
+ * - `from`: anchor discovery to a specific file/URL/path instead of `cwd`.
286
+ * Pass `import.meta.url` for installable CLIs that need to report
287
+ * THEIR OWN version (not the consumer's project version). Accepts
288
+ * string paths, `file:` URL strings, or `URL` instances.
234
289
  *
235
290
  * @example
236
291
  * ```ts
@@ -246,6 +301,12 @@ declare class CLIBuilder {
246
301
  * .command(deploy)
247
302
  * .run();
248
303
  *
304
+ * // Installable CLI; discover OUR package.json, not the consumer's:
305
+ * cli('mycli')
306
+ * .packageJson({ from: import.meta.url })
307
+ * .command(deploy)
308
+ * .run();
309
+ *
249
310
  * // Explicit values always win:
250
311
  * cli('mycli')
251
312
  * .packageJson()
@@ -255,6 +316,7 @@ declare class CLIBuilder {
255
316
  */
256
317
  packageJson(settings?: {
257
318
  readonly inferName?: boolean;
319
+ readonly from?: string | URL;
258
320
  }): CLIBuilder;
259
321
  /**
260
322
  * Register a command with the CLI program.
@@ -1 +1 @@
1
- import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{buildRunResult as i,executeCommand as a}from"../execution/index.mjs";import{createCaptureOutput as o,createOutput as s}from"../output/index.mjs";import{arg as c}from"../schema/arg.mjs";import{command as l}from"../schema/command.mjs";import{runCommand as u}from"../testkit/index.mjs";import{createAdapter as d}from"../../runtime/auto.mjs";import{planInvocation as f}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as p}from"./root-help.mjs";import{prepareRuntimePreflight as m}from"./runtime-preflight.mjs";function h(e){return[e.name,...e.aliases]}function g(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function _(t,n){let r=new Map;for(let e of t)for(let t of h(e.schema))g(`root`,r,t,e.schema.name);for(let t of h(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function v(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=h(r.schema);for(let t of i)g(e.schema.name,n,t,r.schema.name);let a=v(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return u(e,t,n)}}}function y(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var b=class u{schema;constructor(e){this.schema=e}version(e){return new u({...this.schema,version:e})}description(e){return new u({...this.schema,description:e})}config(e,t){return new u({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new u({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return new u({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1}})}command(e){return _(this.schema.commands,e.schema),new u({...this.schema,commands:[...this.schema.commands,v(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});_(this.schema.commands,t.schema);let n=v(t);return new u({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new u({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=l(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,c.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new u({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=e.includes(`--json`)||t?.jsonMode===!0,s={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},c,l;t?.out===void 0?[c,l]=o(Object.keys(s).length>0?s:void 0):(c=t.out,l=t.captured??{stdout:[],stderr:[],activity:[]});let u={...t?.help,binName:t?.help?.binName??this.schema.name},d={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},m={jsonMode:n,isTTY:c.isTTY,verbosity:t?.verbosity??`normal`},h=f({schema:this.schema,argv:e,help:u,output:m});switch(h.kind){case`root-version`:return c.log(h.version),i({exitCode:0,error:void 0},l);case`root-help`:{let e=p(this.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`dispatch-error`:return n?c.json({error:h.error.toJSON()}):(c.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&c.error(`Suggestion: ${h.error.suggest}`)),i({exitCode:h.error.exitCode,error:h.error},l);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`match`:{let e=y(d,h.plan.help??u,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):i(await a({command:h.plan.command._command,argv:h.plan.argv,out:c,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),l)}}}async run(e){let t=e?.adapter??d(),n=this.schema.inheritName?w(t.argv):void 0,r=await m({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new u(r.schema),a={...e,...r.inputs,out:s({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const x=new Set([`bun`,`deno`,`node`,`tsx`]);function S(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function C(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return x.has(t)}function w(e){let t=e[0],n=e[1],r=t===void 0?void 0:S(t);if(r!==void 0&&C(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:S(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:S(n)}return t===void 0?void 0:S(t)}function T(e){return new b({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{b as CLIBuilder,T as cli};
1
+ import{CLIError as e}from"../errors/index.mjs";import{SHELLS as t,generateCompletion as n}from"../completion/index.mjs";import{formatHelp as r}from"../help/index.mjs";import{buildRunResult as i,executeCommand as a}from"../execution/index.mjs";import{createCaptureOutput as o,createOutput as s}from"../output/index.mjs";import{arg as c}from"../schema/arg.mjs";import{command as l}from"../schema/command.mjs";import{runCommand as u}from"../testkit/index.mjs";import{createAdapter as d}from"../../runtime/auto.mjs";import{planInvocation as f}from"./planner.mjs";import"./plugin.mjs";import{formatRootHelp as p}from"./root-help.mjs";import{prepareRuntimePreflight as m}from"./runtime-preflight.mjs";function h(e){return[e.name,...e.aliases]}function g(t,n,r,i){let a=n.get(r);if(a!==void 0)throw new e(`Duplicate command route '${r}' under '${t}' (${a} and ${i})`,{code:`DUPLICATE_COMMAND`,suggest:`Ensure sibling command names and aliases are unique`});n.set(r,i)}function _(t,n){let r=new Map;for(let e of t)for(let t of h(e.schema))g(`root`,r,t,e.schema.name);for(let t of h(n)){let i=r.get(t);if(i!==void 0)throw new e(`Command route '${t}' is already registered by '${i}'`,{code:`DUPLICATE_COMMAND`,suggest:i===n.name?`Ensure command '${n.name}' does not reuse route '${t}'`:`Rename '${n.name}' or remove route '${t}' from '${i}'`});r.set(t,n.name)}}function v(e){let t=new Map,n=new Map;for(let r of e._subcommands){let i=h(r.schema);for(let t of i)g(e.schema.name,n,t,r.schema.name);let a=v(r);for(let e of i)t.set(e,a)}return{schema:e.schema,subcommands:t,_command:e,_execute(t,n){return u(e,t,n)}}}function y(e,t,n){return{help:t,...n===void 0?{}:{meta:n},...e?.plugins===void 0?{}:{plugins:e.plugins},...e?.env===void 0?{}:{env:e.env},...e?.config===void 0?{}:{config:e.config},...e?.stdinData===void 0?{}:{stdinData:e.stdinData},...e?.prompter===void 0?{}:{prompter:e.prompter},...e?.answers===void 0?{}:{answers:e.answers},...e?.verbosity===void 0?{}:{verbosity:e.verbosity},...e?.jsonMode===void 0?{}:{jsonMode:e.jsonMode},...e?.isTTY===void 0?{}:{isTTY:e.isTTY},...e?.out===void 0?{}:{out:e.out},...e?.captured===void 0?{}:{captured:e.captured}}}var b=class u{schema;constructor(e){this.schema=e}version(e){return new u({...this.schema,version:e})}description(e){return new u({...this.schema,description:e})}config(e,t){return new u({...this.schema,configSettings:{appName:e,loaders:t}})}configLoader(t){if(this.schema.configSettings===void 0)throw new e(`.configLoader() requires .config() to be called first`,{code:`INVALID_BUILDER_STATE`,suggest:`Call .config(appName) before .configLoader()`});let n=this.schema.configSettings.loaders??[];return new u({...this.schema,configSettings:{...this.schema.configSettings,loaders:[...n,t]}})}packageJson(e){return E(e)?new u({...this.schema,...this.schema.version===void 0&&e.version!==void 0?{version:e.version}:{},...this.schema.description===void 0&&e.description!==void 0?{description:e.description}:{},packageJsonSettings:{inferName:!1,from:void 0,data:e}}):new u({...this.schema,packageJsonSettings:{inferName:e?.inferName??!1,from:T(e?.from),data:void 0}})}command(e){return _(this.schema.commands,e.schema),new u({...this.schema,commands:[...this.schema.commands,v(e)]})}default(t){if(this.schema.defaultCommand!==void 0)throw new e(`Only one default command is allowed`,{code:`DUPLICATE_DEFAULT`,suggest:`Call .default() only once when building the CLI`});_(this.schema.commands,t.schema);let n=v(t);return new u({...this.schema,commands:[...this.schema.commands,n],defaultCommand:n})}plugin(e){return new u({...this.schema,plugins:[...this.schema.plugins,e]})}completions(r){if(this.schema.hasBuiltInCompletions)throw new e(`.completions() has already been called`,{code:`DUPLICATE_COMMAND`,suggest:`Call .completions() only once when building the CLI`});let i=this.schema,a=r,o=new Map;for(let e of t)o.set(e,e);o.set(`pwsh`,`powershell`);let s=l(`completions`).alias(`completion`).description(`Generate shell completion script`).arg(`shell`,c.custom(e=>{let n=e.split(/[\\/]/),r=(n[n.length-1]??e).replace(/\.(?:exe|cmd|bat)$/i,``),i=o.get(r);if(i===void 0)throw Error(`Unknown shell '${r}'. Valid shells: ${t.join(`, `)}`);return i}).env(`SHELL`).describe(`Target shell (${t.join(`, `)})`)).action(({args:e,meta:t,out:r})=>{let o=n(t.bin===i.name?i:{...i,name:t.bin},e.shell,a);r.jsonMode?r.json({shell:e.shell,script:o}):r.log(o)});return new u({...this.command(s).schema,hasBuiltInCompletions:!0})}async execute(e,t){let n=e.includes(`--json`)||t?.jsonMode===!0,s={...t?.verbosity===void 0?{}:{verbosity:t.verbosity},...n?{jsonMode:n}:{},...t?.isTTY===void 0?{}:{isTTY:t.isTTY}},c,l;t?.out===void 0?[c,l]=o(Object.keys(s).length>0?s:void 0):(c=t.out,l=t.captured??{stdout:[],stderr:[],activity:[]});let u={...t?.help,binName:t?.help?.binName??this.schema.name},d={...t,plugins:this.schema.plugins,...n?{jsonMode:n}:{}},m={jsonMode:n,isTTY:c.isTTY,verbosity:t?.verbosity??`normal`},h=f({schema:this.schema,argv:e,help:u,output:m});switch(h.kind){case`root-version`:return c.log(h.version),i({exitCode:0,error:void 0},l);case`root-help`:{let e=p(this.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`dispatch-error`:return n?c.json({error:h.error.toJSON()}):(c.error(h.error.message),h.error.suggest!==void 0&&h.error.code!==`NO_ACTION`&&c.error(`Suggestion: ${h.error.suggest}`)),i({exitCode:h.error.exitCode,error:h.error},l);case`needs-subcommand`:{let e=r(h.command.schema,h.help);return c.log(e),i({exitCode:0,error:void 0},l)}case`match`:{let e=y(d,h.plan.help??u,h.plan.meta);return h.plan.command._command===void 0?h.plan.command._execute(h.plan.argv,{...e,mergedSchema:h.plan.mergedSchema}):i(await a({command:h.plan.command._command,argv:h.plan.argv,out:c,schema:h.plan.mergedSchema,meta:h.plan.meta,options:e}),l)}}}async run(e){let t=e?.adapter??d(),n=this.schema.inheritName?w(t.argv):void 0,r=await m({schema:this.schema,adapter:t,options:e,inheritedName:n});if(r.kind===`config-error`)return r.jsonMode?t.stdout(`${JSON.stringify({error:r.error.toJSON()})}\n`):(t.stderr(`Error: ${r.error.message}\n`),r.error.suggest!==void 0&&t.stderr(`Suggestion: ${r.error.suggest}\n`)),t.exit(r.error.exitCode);let i=r.schema===this.schema?this:new u(r.schema),a={...e,...r.inputs,out:s({stdout:t.stdout,stderr:t.stderr,jsonMode:r.inputs.jsonMode,isTTY:r.inputs.isTTY,...r.inputs.verbosity===`normal`?{}:{verbosity:r.inputs.verbosity}})},o=await i.execute(r.filteredArgv,a);for(let e of o.stdout)t.stdout(e);for(let e of o.stderr)t.stderr(e);return t.exit(o.exitCode)}};const x=new Set([`bun`,`deno`,`node`,`tsx`]);function S(e){let t=e.replace(/[\\/]+$/g,``);if(t.length===0)return;let n=Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`)),r=n>=0?t.slice(n+1):t;return r.length>0?r:void 0}function C(e){let t=e.toLowerCase().replace(/\.exe$/i,``);return x.has(t)}function w(e){let t=e[0],n=e[1],r=t===void 0?void 0:S(t);if(r!==void 0&&C(r)){if(r===`bun`&&n===`run`){let t=e[2];return t===void 0||t.startsWith(`-`)?void 0:S(t)}return r===`deno`&&n===`run`||n===void 0||n.startsWith(`-`)?void 0:S(n)}return t===void 0?void 0:S(t)}function T(e){if(e===void 0)return;if(e instanceof URL){if(e.protocol!==`file:`)return e.href}else if(!e.startsWith(`file:`))return e;let t=decodeURIComponent(new URL(e).pathname);return/^\/[A-Za-z]:/.test(t)?t.slice(1).replace(/\//g,`\\`):t}function E(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:`name`in e||`version`in e||`description`in e||`bin`in e}function D(e){return new b({name:typeof e==`string`?e:e.name??`cli`,inheritName:typeof e==`string`?!1:e.inherit??!1,version:void 0,description:void 0,commands:[],defaultCommand:void 0,configSettings:void 0,packageJsonSettings:void 0,hasBuiltInCompletions:!1,plugins:[]})}export{b as CLIBuilder,D as cli};
@@ -4,6 +4,7 @@ import { CLIPlugin } from "./plugin.mjs";
4
4
  import { CLIError } from "../errors/index.mjs";
5
5
  import { CommandSchema, ErasedCommand } from "../schema/command.mjs";
6
6
  import { RuntimeAdapter } from "../../runtime/adapter.mjs";
7
+ import { PackageJsonData } from "../config/package-json.mjs";
7
8
  import { FormatLoader } from "../config/index.mjs";
8
9
 
9
10
  //#region src/core/cli/runtime-preflight.d.ts
@@ -18,6 +19,10 @@ interface RuntimeConfigSettings {
18
19
  interface RuntimePackageJsonSettings {
19
20
  /** Whether to infer the CLI binary name from `package.json` `bin` field. */
20
21
  readonly inferName: boolean;
22
+ /** Explicit anchor (resolved path) for discovery; `undefined` falls back to `adapter.cwd`. */
23
+ readonly from: string | undefined;
24
+ /** Pre-loaded data; when set, discovery is skipped entirely. */
25
+ readonly data: PackageJsonData | undefined;
21
26
  }
22
27
  /**
23
28
  * Structural subset of CLISchema used by runtime preflight.
@@ -1 +1 @@
1
- import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{planInvocation as i}from"./planner.mjs";import{discoverPackageJson as a,inferCliName as o}from"../config/package-json.mjs";import{discoverConfig as s}from"../config/index.mjs";const c={jsonMode:!1,isTTY:!1,verbosity:`normal`};function l(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function u(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function d(e,t){let n=i({schema:e,argv:t,help:{binName:e.name},output:c});switch(n.kind){case`match`:return u(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function f(e,t){if(!e.hasBuiltInCompletions)return!1;let n=i({schema:e,argv:t,help:{binName:e.name},output:c});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function p(e,t,n,r){let i=e.packageJsonSettings,s=i!==void 0&&!r?await(async()=>{let n=await a(t);if(n===null)return e;let r=i.inferName?o(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r}}})():e;return n===void 0?s:{...s,name:n}}async function m(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await s(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function h(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:l(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=f(t.schema,a),c=await p(t.schema,t.adapter,t.inheritedName,s),u=await m(c,t.adapter,i,s,t.options?.config);if(u instanceof e)return{kind:`config-error`,error:u,jsonMode:o};let h=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&d(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?h===void 0?{}:{prompter:h}:{prompter:t.options.prompter},...u===void 0?{}:{config:u}}}}export{h as prepareRuntimePreflight};
1
+ import{CLIError as e,ParseError as t}from"../errors/index.mjs";import{parse as n}from"../parse/index.mjs";import{createTerminalPrompter as r}from"../prompt/index.mjs";import{planInvocation as i}from"./planner.mjs";import{discoverPackageJson as a,inferCliName as o}from"../config/package-json.mjs";import{discoverConfig as s}from"../config/index.mjs";const c={jsonMode:!1,isTTY:!1,verbosity:`normal`};function l(e){let t=[],n;for(let r=0;r<e.length;r+=1){let i=e[r];if(i!==void 0){if(i===`--`){t.push(...e.slice(r));break}if(n===void 0&&i.startsWith(`--config=`)){let e=i.slice(9);if(e.length>0){n=e;continue}t.push(i);continue}if(n===void 0&&i===`--config`){let a=e[r+1];if(a!==void 0&&!a.startsWith(`-`)&&a!==`--`){n=a,r+=1;continue}t.push(i);continue}t.push(i)}}return{configPath:n,filteredArgv:t}}function u(e,r){if(r.includes(`--help`)||r.includes(`-h`))return!1;try{let t=n(e,r);return e.args.some(({name:e,schema:n})=>{let r=t.args[e];return n.stdinMode&&(r===void 0||r===`-`)})}catch(e){if(e instanceof t)return!1;throw e}}function d(e,t){let n=i({schema:e,argv:t,help:{binName:e.name},output:c});switch(n.kind){case`match`:return u(n.plan.mergedSchema,n.plan.argv);case`dispatch-error`:case`needs-subcommand`:case`root-help`:case`root-version`:return!1}}function f(e,t){if(!e.hasBuiltInCompletions)return!1;let n=i({schema:e,argv:t,help:{binName:e.name},output:c});return n.kind===`match`&&n.plan.command.schema.name===`completions`}async function p(e,t,n,r){let i=e.packageJsonSettings,s=i!==void 0&&!r?await(async()=>{let n=i.data??await a(t,i.from);if(n===null)return e;let r=i.inferName?o(n):void 0;return{...e,...e.version===void 0&&n.version!==void 0?{version:n.version}:{},...e.description===void 0&&n.description!==void 0?{description:n.description}:{},...r===void 0?{}:{name:r}}})():e;return n===void 0?s:{...s,name:n}}async function m(t,n,r,i,a){if(t.configSettings===void 0||i||a!==void 0)return a;try{let e=await s(t.configSettings.appName,n,{...r===void 0?{}:{configPath:r},...t.configSettings.loaders===void 0?{}:{loaders:t.configSettings.loaders}});return e.found?e.data:void 0}catch(t){if(t instanceof e)return t;throw t}}async function h(t){let n=t.adapter.argv.slice(2),{configPath:i,filteredArgv:a}=t.schema.configSettings===void 0?{configPath:void 0,filteredArgv:n}:l(n),o=a.includes(`--json`)||t.options?.jsonMode===!0,s=f(t.schema,a),c=await p(t.schema,t.adapter,t.inheritedName,s),u=await m(c,t.adapter,i,s,t.options?.config);if(u instanceof e)return{kind:`config-error`,error:u,jsonMode:o};let h=t.options?.prompter===void 0&&t.adapter.stdinIsTTY?r(t.adapter.stdin,t.adapter.stderr):void 0,g=t.options?.stdinData===void 0&&d(c,a)?await t.adapter.readStdin():t.options?.stdinData;return{kind:`ready`,schema:c,filteredArgv:a,inputs:{env:t.options?.env??t.adapter.env,isTTY:t.options?.isTTY??t.adapter.isTTY,jsonMode:o,verbosity:t.options?.verbosity??`normal`,...g===void 0?{}:{stdinData:g},...t.options?.prompter===void 0?h===void 0?{}:{prompter:h}:{prompter:t.options.prompter},...u===void 0?{}:{config:u}}}}export{h as prepareRuntimePreflight};
@@ -24,7 +24,8 @@ interface PackageJsonData {
24
24
  */
25
25
  type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
26
26
  /**
27
- * Discover the nearest `package.json` by walking up from `adapter.cwd`.
27
+ * Discover the nearest `package.json` by walking up from `startDir` (or
28
+ * `adapter.cwd` when omitted).
28
29
  *
29
30
  * Convenience helper behind `CLIBuilder.packageJson()`. Most apps should let
30
31
  * the CLI runtime discover package metadata automatically; call this directly
@@ -34,6 +35,15 @@ type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
34
35
  * is found (not an error). Malformed JSON and non-object roots also
35
36
  * return `null` — the feature is a convenience, not a hard requirement.
36
37
  *
38
+ * @param adapter - Adapter providing `readFile` + `cwd`.
39
+ * @param startDir - Optional explicit directory or file path to walk up from.
40
+ * Pass an absolute path inside your own package (e.g.
41
+ * `fileURLToPath(import.meta.url)`) when authoring an installable CLI whose
42
+ * version should reflect the CLI's own package, not the consumer's working
43
+ * directory. Defaults to `adapter.cwd` when `undefined`. A file path is
44
+ * probed as a directory first (yielding nothing) before the walk-up reaches
45
+ * its real parent directory, so passing `import.meta.url` resolves correctly.
46
+ *
37
47
  * @example
38
48
  * ```ts
39
49
  * import { discoverPackageJson } from '@kjanat/dreamcli';
@@ -44,7 +54,7 @@ type PackageJsonAdapter = Pick<RuntimeAdapter, 'readFile' | 'cwd'>;
44
54
  * }
45
55
  * ```
46
56
  */
47
- declare function discoverPackageJson(adapter: PackageJsonAdapter): Promise<PackageJsonData | null>;
57
+ declare function discoverPackageJson(adapter: PackageJsonAdapter, startDir?: string): Promise<PackageJsonData | null>;
48
58
  /**
49
59
  * Infer the CLI binary name from package.json data.
50
60
  *
@@ -1 +1 @@
1
- function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e){let r=e.cwd;for(;r!==void 0;){let a=null;try{a=await e.readFile(n(r,`package.json`))}catch{}if(a!==null){let e=i(a);if(e!==null)return e}r=t(r)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,o=typeof n.description==`string`?n.description:void 0,s=a(n.bin);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...o===void 0?{}:{description:o},...s===void 0?{}:{bin:s}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,o as inferCliName};
1
+ function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t(e){let t=e.lastIndexOf(`/`),n=e.lastIndexOf(`\\`),r=Math.max(t,n),i=n>t?`\\`:`/`;if(r<0)return;if(r===0)return e.length>1?i:void 0;let a=e.slice(0,r);if(a.length===2&&a[1]===`:`){let t=`${a}${i}`;return t===e?void 0:t}return a}function n(e,t){let n=e.includes(`\\`)?`\\`:`/`;return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}async function r(e,r){let a=r??e.cwd;for(;a!==void 0;){let r=null;try{r=await e.readFile(n(a,`package.json`))}catch{}if(r!==null){let e=i(r);if(e!==null)return e}a=t(a)}return null}function i(t){try{let n=JSON.parse(t);if(!e(n))return null;let r=typeof n.name==`string`?n.name:void 0,i=typeof n.version==`string`?n.version:void 0,o=typeof n.description==`string`?n.description:void 0,s=a(n.bin);return{...r===void 0?{}:{name:r},...i===void 0?{}:{version:i},...o===void 0?{}:{description:o},...s===void 0?{}:{bin:s}}}catch{return null}}function a(t){if(typeof t==`string`)return t;if(!e(t))return;let n={};for(let[e,r]of Object.entries(t)){if(typeof r!=`string`)return;n[e]=r}return n}function o(e){if(typeof e.bin==`object`){let t=Object.keys(e.bin);if(t.length>0&&t[0]!==void 0)return t[0]}if(e.name!==void 0){let t=e.name.indexOf(`/`);return t>=0?e.name.slice(t+1):e.name}}export{r as discoverPackageJson,o as inferCliName};
package/dist/version.mjs CHANGED
@@ -1 +1 @@
1
- const e=`2.1.0`,t=`763e386`;export{t as DREAMCLI_REVISION,e as DREAMCLI_VERSION};
1
+ const e=`2.2.0`,t=`2ca0220`;export{t as DREAMCLI_REVISION,e as DREAMCLI_VERSION};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kjanat/dreamcli",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Schema-first, fully typed TypeScript CLI framework",
5
5
  "keywords": [
6
6
  "cli",
@@ -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;
@@ -86,7 +86,8 @@ function joinPath(base: string, segment: string): string {
86
86
  // --- discoverPackageJson
87
87
 
88
88
  /**
89
- * Discover the nearest `package.json` by walking up from `adapter.cwd`.
89
+ * Discover the nearest `package.json` by walking up from `startDir` (or
90
+ * `adapter.cwd` when omitted).
90
91
  *
91
92
  * Convenience helper behind `CLIBuilder.packageJson()`. Most apps should let
92
93
  * the CLI runtime discover package metadata automatically; call this directly
@@ -96,6 +97,15 @@ function joinPath(base: string, segment: string): string {
96
97
  * is found (not an error). Malformed JSON and non-object roots also
97
98
  * return `null` — the feature is a convenience, not a hard requirement.
98
99
  *
100
+ * @param adapter - Adapter providing `readFile` + `cwd`.
101
+ * @param startDir - Optional explicit directory or file path to walk up from.
102
+ * Pass an absolute path inside your own package (e.g.
103
+ * `fileURLToPath(import.meta.url)`) when authoring an installable CLI whose
104
+ * version should reflect the CLI's own package, not the consumer's working
105
+ * directory. Defaults to `adapter.cwd` when `undefined`. A file path is
106
+ * probed as a directory first (yielding nothing) before the walk-up reaches
107
+ * its real parent directory, so passing `import.meta.url` resolves correctly.
108
+ *
99
109
  * @example
100
110
  * ```ts
101
111
  * import { discoverPackageJson } from '@kjanat/dreamcli';
@@ -106,8 +116,11 @@ function joinPath(base: string, segment: string): string {
106
116
  * }
107
117
  * ```
108
118
  */
109
- async function discoverPackageJson(adapter: PackageJsonAdapter): Promise<PackageJsonData | null> {
110
- let dir: string | undefined = adapter.cwd;
119
+ async function discoverPackageJson(
120
+ adapter: PackageJsonAdapter,
121
+ startDir?: string,
122
+ ): Promise<PackageJsonData | null> {
123
+ let dir: string | undefined = startDir ?? adapter.cwd;
111
124
 
112
125
  while (dir !== undefined) {
113
126
  let content: string | null = null;
@@ -21,3 +21,7 @@ declare module 'node:readline' {
21
21
  declare module 'node:fs/promises' {
22
22
  function readFile(path: string | URL, encoding: 'utf8'): Promise<string>;
23
23
  }
24
+
25
+ declare module 'node:url' {
26
+ function fileURLToPath(url: string | URL): string;
27
+ }