@kjanat/dreamcli 2.4.0 → 2.5.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.
@@ -101,28 +101,147 @@ function joinPath(base: string, segment: string): string {
101
101
  return base.endsWith(sep) ? `${base}${segment}` : `${base}${sep}${segment}`;
102
102
  }
103
103
 
104
+ // --- discoverManifest
105
+
106
+ /** Default manifest filenames probed when none are supplied. @internal */
107
+ const DEFAULT_MANIFEST_FILES: readonly string[] = ['package.json'];
108
+
109
+ /** Options for {@link discoverManifest}. */
110
+ interface ManifestDiscoveryOptions {
111
+ /**
112
+ * Explicit directory or file path to walk up from. Defaults to
113
+ * `adapter.cwd` when omitted. Pass an absolute path inside your own package
114
+ * (e.g. `fileURLToPath(import.meta.url)`) for installable CLIs whose version
115
+ * should reflect the CLI's own package, not the consumer's working directory.
116
+ *
117
+ * This low-level helper takes a resolved path **string** only. The builder
118
+ * sugar `CLIBuilder.manifest({ from })` exposes the same anchor under the name
119
+ * `from` and additionally accepts a `file:` URL string or `URL` instance,
120
+ * normalizing it to a path first.
121
+ */
122
+ readonly startDir?: string;
123
+ /**
124
+ * Candidate manifest filenames, in per-directory priority order
125
+ * (e.g. `['deno.json', 'jsr.json']`). At each directory the first existing
126
+ * file that carries CLI metadata wins, so the nearest manifest directory
127
+ * always takes precedence over file order. A file that parses but holds no
128
+ * recognised metadata (e.g. a config-only `deno.json` with just
129
+ * `tasks`/`imports`) is skipped, so a sibling `jsr.json` — or a manifest
130
+ * higher up — can still be found. Defaults to `['package.json']`.
131
+ *
132
+ * An empty list is a deliberate no-op: with no candidates to probe, the
133
+ * walk-up reads nothing and resolves to `null` (consistent with the
134
+ * "returns `null` when no manifest is found" contract).
135
+ */
136
+ readonly files?: readonly string[];
137
+ }
138
+
139
+ /**
140
+ * Whether parsed manifest data carries any CLI-relevant metadata.
141
+ *
142
+ * {@link parsePackageJson} returns an empty object for a config-only manifest
143
+ * (e.g. a `deno.json` holding only `tasks` / `imports` / `compilerOptions`).
144
+ * Treating that empty result as a discovery hit would shadow a sibling
145
+ * `jsr.json` and halt the walk-up, silently dropping real metadata. Discovery
146
+ * therefore only accepts a manifest that actually carries at least one
147
+ * recognised field.
148
+ *
149
+ * @internal
150
+ */
151
+ function manifestHasMetadata(data: PackageJsonData): boolean {
152
+ return (
153
+ data.name !== undefined ||
154
+ data.version !== undefined ||
155
+ data.description !== undefined ||
156
+ data.bin !== undefined ||
157
+ data.homepage !== undefined ||
158
+ data.repository !== undefined
159
+ );
160
+ }
161
+
162
+ /**
163
+ * Discover the nearest manifest (`package.json`, `deno.json`, `jsr.json`, …)
164
+ * by walking up from `startDir` (or `adapter.cwd` when omitted).
165
+ *
166
+ * Convenience helper behind `CLIBuilder.manifest()`. Most apps should let the
167
+ * CLI runtime discover metadata automatically; call this directly when testing
168
+ * metadata inference or embedding the behavior in custom tooling.
169
+ *
170
+ * Candidate files are parsed as JSON with a JSONC fallback — `package.json`,
171
+ * `deno.json`, `jsr.json`, and `deno.jsonc` all qualify, including files that
172
+ * carry `//` / block comments or trailing commas (common in `deno.json`). A
173
+ * file that fails both parses is skipped, so discovery keeps probing.
174
+ *
175
+ * Returns the parsed metadata on success, `null` when no manifest is found
176
+ * (not an error). Malformed JSON, non-object roots, and config-only manifests
177
+ * that carry no recognised metadata (e.g. a `deno.json` with only `tasks` /
178
+ * `imports`) are all skipped, so discovery keeps probing the remaining
179
+ * candidate files and parent directories — the feature is a convenience, not a
180
+ * hard requirement.
181
+ *
182
+ * @param adapter - Adapter providing `readFile` + `cwd`.
183
+ * @param options - Optional anchor (`startDir`) and candidate filenames (`files`).
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * import { discoverManifest } from '@kjanat/dreamcli';
188
+ *
189
+ * const meta = await discoverManifest(adapter, { files: ['deno.json', 'jsr.json'] });
190
+ * if (meta !== null) {
191
+ * console.log(meta.version); // '1.2.3'
192
+ * }
193
+ * ```
194
+ */
195
+ async function discoverManifest(
196
+ adapter: PackageJsonAdapter,
197
+ options: ManifestDiscoveryOptions = {},
198
+ ): Promise<PackageJsonData | null> {
199
+ const files = options.files ?? DEFAULT_MANIFEST_FILES;
200
+ let dir: string | undefined = options.startDir ?? adapter.cwd;
201
+
202
+ while (dir !== undefined) {
203
+ for (const file of files) {
204
+ let content: string | null = null;
205
+ try {
206
+ content = await adapter.readFile(joinPath(dir, file));
207
+ } catch {
208
+ // Adapter may throw on permission errors, is-directory, or other
209
+ // syscall failures — skip this file and keep probing.
210
+ }
211
+ if (content !== null) {
212
+ const parsed = parsePackageJson(content);
213
+ if (parsed !== null && manifestHasMetadata(parsed)) {
214
+ return parsed;
215
+ }
216
+ }
217
+ }
218
+ dir = parentDir(dir);
219
+ }
220
+
221
+ return null;
222
+ }
223
+
104
224
  // --- discoverPackageJson
105
225
 
106
226
  /**
107
227
  * Discover the nearest `package.json` by walking up from `startDir` (or
108
228
  * `adapter.cwd` when omitted).
109
229
  *
110
- * Convenience helper behind `CLIBuilder.packageJson()`. Most apps should let
111
- * the CLI runtime discover package metadata automatically; call this directly
112
- * when testing metadata inference or embedding the behavior in custom tooling.
230
+ * @deprecated Use {@link discoverManifest} with `{ files: ['package.json'] }`
231
+ * (the default), which also supports `deno.json` / `jsr.json`.
113
232
  *
114
- * Returns the parsed metadata on success, `null` when no `package.json`
115
- * is found (not an error). Malformed JSON and non-object roots also
116
- * return `null` — the feature is a convenience, not a hard requirement.
233
+ * Behavior note (changed by the manifest generalization): a parseable but
234
+ * metadata-less `package.json` — `{}`, or one carrying only non-metadata fields
235
+ * such as `dependencies` / `scripts` / `type` — is no longer treated as a
236
+ * discovery hit. Previously such a file halted the walk-up and resolved to `{}`;
237
+ * now it is skipped and the walk-up CONTINUES to parent directories. In a
238
+ * monorepo this means a metadata-less leaf `package.json` no longer shadows an
239
+ * ancestor manifest, so an ancestor's `version` can surface where the old
240
+ * behavior returned `{}`. Pass pre-loaded `data` (or use {@link discoverManifest}
241
+ * with an explicit `startDir`) when you need to pin discovery to one directory.
117
242
  *
118
243
  * @param adapter - Adapter providing `readFile` + `cwd`.
119
244
  * @param startDir - Optional explicit directory or file path to walk up from.
120
- * Pass an absolute path inside your own package (e.g.
121
- * `fileURLToPath(import.meta.url)`) when authoring an installable CLI whose
122
- * version should reflect the CLI's own package, not the consumer's working
123
- * directory. Defaults to `adapter.cwd` when `undefined`. A file path is
124
- * probed as a directory first (yielding nothing) before the walk-up reaches
125
- * its real parent directory, so passing `import.meta.url` resolves correctly.
126
245
  *
127
246
  * @example
128
247
  * ```ts
@@ -138,40 +257,117 @@ async function discoverPackageJson(
138
257
  adapter: PackageJsonAdapter,
139
258
  startDir?: string,
140
259
  ): Promise<PackageJsonData | null> {
141
- let dir: string | undefined = startDir ?? adapter.cwd;
260
+ return discoverManifest(adapter, startDir !== undefined ? { startDir } : {});
261
+ }
142
262
 
143
- while (dir !== undefined) {
144
- let content: string | null = null;
145
- try {
146
- content = await adapter.readFile(joinPath(dir, 'package.json'));
147
- } catch {
148
- // Adapter may throw on permission errors, is-directory, or other
149
- // syscall failures — skip this directory and keep walking up.
263
+ // --- stripJsonc
264
+
265
+ /** Whitespace characters JSON treats as insignificant. @internal */
266
+ function isJsonWhitespace(ch: string): boolean {
267
+ return ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r';
268
+ }
269
+
270
+ /**
271
+ * Strip JSONC extensions (line/block comments and trailing commas) so the result
272
+ * is plain JSON. String-aware: comment markers and commas inside string literals
273
+ * are preserved verbatim, so a `"https://…"` URL or a `"/* …"` value survives
274
+ * untouched. Runtime-agnostic — no dependencies, plain string scanning.
275
+ *
276
+ * Only invoked as a fallback when strict `JSON.parse` fails, so valid JSON never
277
+ * passes through here.
278
+ *
279
+ * @internal
280
+ */
281
+ function stripJsonc(input: string): string {
282
+ // Pass 1 — drop comments outside of strings.
283
+ let decommented = '';
284
+ let inString = false;
285
+ let escaped = false;
286
+ for (let i = 0; i < input.length; i += 1) {
287
+ const ch = input[i] ?? '';
288
+ if (inString) {
289
+ decommented += ch;
290
+ if (escaped) escaped = false;
291
+ else if (ch === '\\') escaped = true;
292
+ else if (ch === '"') inString = false;
293
+ continue;
150
294
  }
151
- if (content !== null) {
152
- const parsed = parsePackageJson(content);
153
- if (parsed !== null) {
154
- return parsed;
155
- }
295
+ if (ch === '"') {
296
+ inString = true;
297
+ decommented += ch;
298
+ continue;
156
299
  }
157
- dir = parentDir(dir);
300
+ if (ch === '/' && input[i + 1] === '/') {
301
+ i += 2;
302
+ while (i < input.length && input[i] !== '\n') i += 1;
303
+ i -= 1; // let the loop's increment land on (and re-emit) the newline
304
+ continue;
305
+ }
306
+ if (ch === '/' && input[i + 1] === '*') {
307
+ i += 2;
308
+ while (i < input.length && !(input[i] === '*' && input[i + 1] === '/')) i += 1;
309
+ i += 1; // skip the '*'; the loop increment skips the closing '/'
310
+ continue;
311
+ }
312
+ decommented += ch;
158
313
  }
159
314
 
160
- return null;
315
+ // Pass 2 — drop commas immediately before a closing `}` or `]`.
316
+ let result = '';
317
+ inString = false;
318
+ escaped = false;
319
+ for (let i = 0; i < decommented.length; i += 1) {
320
+ const ch = decommented[i] ?? '';
321
+ if (inString) {
322
+ result += ch;
323
+ if (escaped) escaped = false;
324
+ else if (ch === '\\') escaped = true;
325
+ else if (ch === '"') inString = false;
326
+ continue;
327
+ }
328
+ if (ch === '"') {
329
+ inString = true;
330
+ result += ch;
331
+ continue;
332
+ }
333
+ if (ch === ',') {
334
+ let j = i + 1;
335
+ while (j < decommented.length && isJsonWhitespace(decommented[j] ?? '')) j += 1;
336
+ const next = decommented[j];
337
+ if (next === '}' || next === ']') {
338
+ continue; // trailing comma — omit it
339
+ }
340
+ }
341
+ result += ch;
342
+ }
343
+ return result;
161
344
  }
162
345
 
163
346
  // --- parsePackageJson
164
347
 
165
348
  /**
166
- * Parse a package.json content string into {@link PackageJsonData}.
349
+ * Parse a manifest content string into {@link PackageJsonData}.
167
350
  *
168
- * Returns `null` for malformed JSON or non-object roots.
351
+ * Strict JSON is parsed directly; on failure, a JSONC fallback strips comments
352
+ * and trailing commas (common in `deno.json`) and retries. Returns `null` for
353
+ * content that is neither valid JSON nor JSONC, or whose root is not an object.
169
354
  *
170
355
  * @internal
171
356
  */
172
357
  function parsePackageJson(content: string): PackageJsonData | null {
358
+ let parsed: unknown;
359
+ try {
360
+ parsed = JSON.parse(content);
361
+ } catch {
362
+ // Tolerate JSONC: deno.json is parsed as JSONC by Deno and real files
363
+ // routinely carry comments / trailing commas. Retry after stripping them.
364
+ try {
365
+ parsed = JSON.parse(stripJsonc(content));
366
+ } catch {
367
+ return null;
368
+ }
369
+ }
173
370
  try {
174
- const parsed: unknown = JSON.parse(content);
175
371
  if (!isPlainObject(parsed)) {
176
372
  return null;
177
373
  }
@@ -314,31 +510,44 @@ function packageRepositoryUrl(pkg: PackageJsonData): string | undefined {
314
510
  // --- inferCliName
315
511
 
316
512
  /**
317
- * Infer the CLI binary name from package.json data.
513
+ * Infer the CLI binary name from manifest data.
318
514
  *
319
515
  * Resolution order:
320
516
  * 1. First key of `bin` object (e.g. `{"mycli": "./dist/cli.js"}` → `"mycli"`)
321
- * 2. Package `name` with scope stripped (e.g. `"@scope/mycli"` → `"mycli"`)
517
+ * 2. Package `name`, scope stripped by default (e.g. `"@scope/mycli"` → `"mycli"`);
518
+ * pass `{ stripScope: false }` to keep the full scoped name
322
519
  * 3. `undefined` if neither exists
323
520
  *
521
+ * Note: `bin` keys are never scoped, so `stripScope` only affects the `name`
522
+ * fallback (relevant for `deno.json` / `jsr.json`, which have no `bin` field).
523
+ *
524
+ * @param pkg - Parsed manifest metadata.
525
+ * @param options - `stripScope` (default `true`): strip a leading `@scope/`
526
+ * from the `name` fallback.
527
+ *
324
528
  * @example
325
529
  * ```ts
326
530
  * import { inferCliName } from '@kjanat/dreamcli';
327
531
  *
328
- * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
329
- * inferCliName({ name: '@scope/mycli' }); // 'mycli'
330
- * inferCliName({ name: 'mycli' }); // 'mycli'
331
- * inferCliName({}); // undefined
532
+ * inferCliName({ bin: { mycli: './dist/cli.js' } }); // 'mycli'
533
+ * inferCliName({ name: '@scope/mycli' }); // 'mycli'
534
+ * inferCliName({ name: '@scope/mycli' }, { stripScope: false }); // '@scope/mycli'
535
+ * inferCliName({ name: 'mycli' }); // 'mycli'
536
+ * inferCliName({}); // undefined
332
537
  * ```
333
538
  */
334
- function inferCliName(pkg: PackageJsonData): string | undefined {
335
- // Prefer bin key name
539
+ function inferCliName(
540
+ pkg: PackageJsonData,
541
+ options: { readonly stripScope?: boolean } = {},
542
+ ): string | undefined {
543
+ // Prefer bin key name (never scoped).
336
544
  if (typeof pkg.bin === 'object') {
337
545
  const keys = Object.keys(pkg.bin);
338
546
  if (keys.length > 0 && keys[0] !== undefined) return keys[0];
339
547
  }
340
- // Fall back to package name, stripped of scope
548
+ // Fall back to package name, optionally stripped of scope.
341
549
  if (pkg.name !== undefined) {
550
+ if (options.stripScope === false) return pkg.name;
342
551
  const slashIdx = pkg.name.indexOf('/');
343
552
  return slashIdx >= 0 ? pkg.name.slice(slashIdx + 1) : pkg.name;
344
553
  }
@@ -347,5 +556,5 @@ function inferCliName(pkg: PackageJsonData): string | undefined {
347
556
 
348
557
  // --- Exports
349
558
 
350
- export type { PackageJsonAdapter, PackageJsonData, PackageRepository };
351
- export { discoverPackageJson, inferCliName, packageRepositoryUrl };
559
+ export type { ManifestDiscoveryOptions, PackageJsonAdapter, PackageJsonData, PackageRepository };
560
+ export { discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl };
@@ -21,6 +21,7 @@ import type {
21
21
  ProgressOptions,
22
22
  SpinnerHandle,
23
23
  } from '#internals/core/schema/activity.ts';
24
+ import { bindMethods } from './bind.ts';
24
25
  import type { WriteFn } from './writer.ts';
25
26
  import { writeLine } from './writer.ts';
26
27
 
@@ -90,6 +91,7 @@ class StaticSpinnerHandle implements SpinnerHandle {
90
91
  private readonly write: WriteFn,
91
92
  ) {
92
93
  writeLine(write, text);
94
+ bindMethods(this);
93
95
  }
94
96
 
95
97
  update(_text: string): void {
@@ -153,6 +155,7 @@ class StaticProgressHandle implements ProgressHandle {
153
155
  if (label !== undefined) {
154
156
  writeLine(write, label);
155
157
  }
158
+ bindMethods(this);
156
159
  }
157
160
 
158
161
  increment(_n?: number): void {
@@ -263,6 +266,7 @@ class TTYSpinnerHandle implements SpinnerHandle {
263
266
  this.frameIndex = (this.frameIndex + 1) % SPINNER_FRAMES.length;
264
267
  this.render();
265
268
  }, SPINNER_INTERVAL_MS);
269
+ bindMethods(this);
266
270
  }
267
271
 
268
272
  /** Render the current frame + text, overwriting the current line. */
@@ -372,6 +376,7 @@ class TTYProgressHandle implements ProgressHandle {
372
376
  this.render();
373
377
  }, PULSE_INTERVAL_MS);
374
378
  }
379
+ bindMethods(this);
375
380
  }
376
381
 
377
382
  /** Advance the indeterminate pulse position with bounce logic. */
@@ -472,6 +477,7 @@ class CaptureSpinnerHandle implements SpinnerHandle {
472
477
  private readonly events: ActivityEvent[],
473
478
  ) {
474
479
  events.push({ type: 'spinner:start', text });
480
+ bindMethods(this);
475
481
  }
476
482
 
477
483
  update(text: string): void {
@@ -529,6 +535,7 @@ class CaptureProgressHandle implements ProgressHandle {
529
535
  private readonly events: ActivityEvent[],
530
536
  ) {
531
537
  events.push({ type: 'progress:start', label: opts.label ?? '', total: opts.total });
538
+ bindMethods(this);
532
539
  }
533
540
 
534
541
  increment(n?: number): void {
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Method-binding helper for value objects handed to consumers.
3
+ *
4
+ * Output value objects — the `Out` channel and the spinner/progress handles
5
+ * — expose methods that read instance state via `this`. Consumers naturally
6
+ * detach those methods, either by destructuring
7
+ * (`const { log } = out` / `const { succeed, fail } = spinner`) or by passing
8
+ * them as callbacks (`promise.finally(spinner.stop)`). Detached, an unbound
9
+ * prototype method loses its `this` and crashes on the first field access.
10
+ *
11
+ * {@linkcode bindMethods} eliminates that footgun by installing instance-bound
12
+ * copies of every method, so the ergonomic usage is also the correct one.
13
+ *
14
+ * @module dreamcli/core/output/bind
15
+ * @internal
16
+ */
17
+
18
+ /**
19
+ * Bind every method on an instance's prototype chain to the instance.
20
+ *
21
+ * Walks the prototype chain up to (but excluding) `Object.prototype`, binding
22
+ * each method name exactly once — the most-derived definition wins, so subclass
23
+ * overrides (e.g. `CaptureOutputChannel.spinner`) are preserved rather than
24
+ * clobbered by a base-class version. Bound methods are installed as
25
+ * non-enumerable own properties, mirroring the enumerability of the prototype
26
+ * methods they shadow. Getters and non-function members are left untouched.
27
+ *
28
+ * Call this once, last, in a class constructor. Because it reads the live
29
+ * prototype rather than a hand-maintained name list, methods added later are
30
+ * bound automatically — the binding can't silently fall out of date.
31
+ *
32
+ * @param instance - The object whose methods should be bound to it.
33
+ * @internal
34
+ */
35
+ function bindMethods(instance: object): void {
36
+ const bound = instance as Record<PropertyKey, unknown>;
37
+ const seen = new Set<string>();
38
+ let proto: object | null = Object.getPrototypeOf(instance);
39
+
40
+ while (proto !== null && proto !== Object.prototype) {
41
+ for (const name of Object.getOwnPropertyNames(proto)) {
42
+ if (name === 'constructor' || seen.has(name)) continue;
43
+ seen.add(name);
44
+
45
+ const descriptor = Object.getOwnPropertyDescriptor(proto, name);
46
+ if (descriptor === undefined || typeof descriptor.value !== 'function') continue;
47
+
48
+ Object.defineProperty(bound, name, {
49
+ value: descriptor.value.bind(instance),
50
+ writable: true,
51
+ enumerable: false,
52
+ configurable: true,
53
+ });
54
+ }
55
+ proto = Object.getPrototypeOf(proto);
56
+ }
57
+ }
58
+
59
+ export { bindMethods };
@@ -31,6 +31,7 @@ import {
31
31
  TTYProgressHandle,
32
32
  TTYSpinnerHandle,
33
33
  } from './activity.ts';
34
+ import { bindMethods } from './bind.ts';
34
35
  import type { OutputPolicy, Verbosity } from './contracts.ts';
35
36
  import {
36
37
  resolveOutputPolicy,
@@ -185,6 +186,11 @@ class OutputChannel implements Out {
185
186
  this.policy = resolveOutputPolicy(options);
186
187
  this.jsonMode = options.jsonMode;
187
188
  this.isTTY = options.isTTY;
189
+
190
+ // Bind methods to the instance so they keep working when destructured
191
+ // off `out` (e.g. `const { log } = out`). Resolves subclass overrides
192
+ // (spinner/progress in CaptureOutputChannel) automatically.
193
+ bindMethods(this);
188
194
  }
189
195
 
190
196
  /**
package/src/index.ts CHANGED
@@ -27,9 +27,13 @@ export type {
27
27
  CLISchema,
28
28
  ConfigSettings,
29
29
  HelpLinks,
30
+ InferNameOption,
31
+ ManifestPresetSettings,
32
+ ManifestSettings,
30
33
  PackageJsonSettings,
31
34
  PluginCommandContext,
32
35
  ResolvedCommandParams,
36
+ ResolvedManifestSettings,
33
37
  } from './core/cli/index.ts';
34
38
  export { CLIBuilder, cli, plugin } from './core/cli/index.ts';
35
39
  export type { CompletionOptions, Shell } from './core/completion/index.ts';
@@ -48,6 +52,7 @@ export type {
48
52
  ConfigFound,
49
53
  ConfigNotFound,
50
54
  FormatLoader,
55
+ ManifestDiscoveryOptions,
51
56
  PackageJsonAdapter,
52
57
  PackageJsonData,
53
58
  PackageRepository,
@@ -56,6 +61,7 @@ export {
56
61
  buildConfigSearchPaths,
57
62
  configFormat,
58
63
  discoverConfig,
64
+ discoverManifest,
59
65
  discoverPackageJson,
60
66
  inferCliName,
61
67
  packageRepositoryUrl,