@theholocron/cli 5.0.0-alpha.25 → 5.0.0-alpha.250

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/dist/index.mjs CHANGED
@@ -1,14 +1,18 @@
1
- import { CARDINALITY, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
1
+ import { CARDINALITY, ElevationRequiredError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, isMulti } from "./plugin/capabilities.mjs";
2
+ import { a as resolvePluginPackage, i as resolveEntry, n as ConfigError, r as resolveConfig, t as compose } from "./compose-DFW8ftHT.mjs";
2
3
  import { AuthError, createResolveToken as createResolveToken$1, createRestClient } from "@theholocron/http-client";
3
- import { createEnvLookup } from "@theholocron/env-utils";
4
+ import { createEnvLookup, withEnvPrefix } from "@theholocron/env-utils";
4
5
  import { Entry, findCredentials } from "@napi-rs/keyring";
5
- import { readFile } from "node:fs/promises";
6
6
  import { basename, dirname, join } from "node:path";
7
- import { execFile } from "node:child_process";
8
- import { promisify } from "node:util";
7
+ import { readPackageJson } from "@theholocron/pkg-utils";
9
8
  import { loadTasksConfig } from "@theholocron/astromech/config";
10
9
  import { ConfigFileError, ConfigFileError as ConfigFileError$1, loadConfigFile } from "@theholocron/datapad";
11
- createEnvLookup();
10
+ import { readGitRemote } from "@theholocron/git-utils";
11
+ import { lookup } from "node:dns/promises";
12
+ // src/env/env.ts
13
+ /** Singleton env for simple global lookups throughout the CLI. */
14
+ const env = createEnvLookup();
15
+ withEnvPrefix(env, "HOLOCRON");
12
16
  /**
13
17
  * Create an injectable env for commands that accept a fake env in tests.
14
18
  * Pass `input.env` when available, falls back to `process.env`.
@@ -16,8 +20,7 @@ createEnvLookup();
16
20
  function makeEnv(source) {
17
21
  return createEnvLookup(source);
18
22
  }
19
- //#endregion
20
- //#region src/auth/keyring.ts
23
+ // src/auth/keyring/keyring.ts
21
24
  /**
22
25
  * Keyring-backed bootstrap credential store.
23
26
  *
@@ -86,8 +89,7 @@ function listStoredProviders() {
86
89
  return [];
87
90
  }
88
91
  }
89
- //#endregion
90
- //#region src/auth/auth-resolver.ts
92
+ // src/auth/auth-resolver/auth-resolver.ts
91
93
  /** Wraps `createResolveToken` from `@theholocron/http` and injects the
92
94
  * system keyring so plugins stay at a one-liner call site. */
93
95
  function createResolveToken(config) {
@@ -108,12 +110,11 @@ function createFeatureResolver(config) {
108
110
  const env = makeEnv(input.env);
109
111
  const keyring = input.keyring ?? getToken;
110
112
  const token = input.cliToken || env.get(config.envName) || keyring(config.keyringKey);
111
- if (!token) throw new AuthError(`no GitHub token found for this operation. Pass --token <PAT>, set ${config.envName}, or run: holocron auth set ${config.keyringKey} <PAT>`);
113
+ if (!token) throw new AuthError(`no ${config.vendor ?? "GitHub"} token found for this operation. Pass --token <token>, set ${config.envName}, or run: holocron auth set ${config.keyringKey} <token>`);
112
114
  return token;
113
115
  };
114
116
  }
115
- //#endregion
116
- //#region src/commands/setup/derived-properties.ts
117
+ // src/commands/setup/derived-properties/derived-properties.ts
117
118
  /**
118
119
  * Repo archetype, in priority order:
119
120
  * 1. `*-template` repo name → `template` (independent of package shape).
@@ -184,7 +185,7 @@ function deriveCapabilities(providers) {
184
185
  return Object.keys(providers ?? {}).sort();
185
186
  }
186
187
  /**
187
- * `source` + `ci` are the minimal baseline every repo `holocron setup`
188
+ * `source` + `ci` are the minimal baseline every repo `holocron repo setup`
188
189
  * touches wires — every `holocron.config.ts` in this org already satisfies
189
190
  * this, so `non-compliant` here means drift (a provider manually removed
190
191
  * after setup), not an unmet aspirational policy. Deliberately not a richer
@@ -213,215 +214,17 @@ function missingCapabilities(capabilities) {
213
214
  */
214
215
  async function readWorkspacePackageJsons(repoRoot, workspacePackages) {
215
216
  const results = [];
216
- for (const { slug, dir = "packages" } of workspacePackages) try {
217
- const raw = await readFile(join(repoRoot, dir, slug, "package.json"), "utf8");
218
- results.push(JSON.parse(raw));
219
- } catch {}
220
- return results;
221
- }
222
- //#endregion
223
- //#region src/config/config.ts
224
- var ConfigError = class extends Error {
225
- name = "ConfigError";
226
- };
227
- const PLUGIN_PREFIX = "@theholocron/holocron-plugin-";
228
- const COMMUNITY_PREFIX = "holocron-plugin-";
229
- /**
230
- * Resolve `"github"` → `"@theholocron/holocron-plugin-github"`.
231
- * Fully-qualified names (scoped or not) are honored verbatim, which
232
- * is how third-party plugins published outside the org work.
233
- */
234
- function resolvePluginPackage(provider) {
235
- if (!provider) throw new ConfigError("provider name is empty");
236
- if (provider.startsWith("@")) return provider;
237
- if (provider.startsWith(COMMUNITY_PREFIX)) return provider;
238
- if (provider.includes("/")) return provider;
239
- return PLUGIN_PREFIX + provider;
240
- }
241
- /** A bare `[provider, options]` tuple, with both elements present? */
242
- function isOptionsTuple(value) {
243
- if (!Array.isArray(value)) return false;
244
- if (value.length !== 2) return false;
245
- if (typeof value[0] !== "string") return false;
246
- const opt = value[1];
247
- return typeof opt === "object" && opt !== null && !Array.isArray(opt);
248
- }
249
- function normalizeEntry(entry) {
250
- if (typeof entry === "string") return {
251
- provider: entry,
252
- packageName: resolvePluginPackage(entry),
253
- options: {}
254
- };
255
- const [provider, options] = entry;
256
- return {
257
- provider,
258
- packageName: resolvePluginPackage(provider),
259
- options
260
- };
261
- }
262
- function resolveEntry(key, raw) {
263
- const cardinality = CARDINALITY[key];
264
- if (typeof raw === "string") {
265
- if (cardinality === "many") throw new ConfigError(`\`${key}\` accepts multiple providers; wrap a single one in an array: ["${raw}"]`);
266
- return {
267
- cardinality: "single",
268
- tuple: normalizeEntry(raw)
269
- };
270
- }
271
- if (!Array.isArray(raw)) throw new ConfigError(`\`${key}\` entry must be a string or array, got ${typeof raw}`);
272
- if (isOptionsTuple(raw)) {
273
- if (cardinality === "many") return {
274
- cardinality: "many",
275
- tuples: [normalizeEntry(raw)]
276
- };
277
- return {
278
- cardinality: "single",
279
- tuple: normalizeEntry(raw)
280
- };
217
+ for (const { slug, dir = "packages", path } of workspacePackages) {
218
+ const pkg = await readPackageJson(join(repoRoot, path ?? join(dir, slug)));
219
+ if (pkg) results.push(pkg);
281
220
  }
282
- if (cardinality === "single") throw new ConfigError(`\`${key}\` accepts exactly one provider; got a multi-provider list with ${raw.length} entries`);
283
- return {
284
- cardinality: "many",
285
- tuples: raw.map((entry, idx) => {
286
- if (typeof entry === "string") return normalizeEntry(entry);
287
- if (isOptionsTuple(entry)) return normalizeEntry(entry);
288
- throw new ConfigError(`\`${key}[${idx}]\` must be a provider string or [provider, options] tuple`);
289
- })
290
- };
291
- }
292
- function resolveConfig(raw) {
293
- if (!raw.name) throw new ConfigError("`name` is required");
294
- if (!raw.providers || typeof raw.providers !== "object") throw new ConfigError("`providers` block is required");
295
- const providers = {};
296
- for (const [key, entry] of Object.entries(raw.providers)) {
297
- if (entry === void 0) continue;
298
- providers[key] = resolveEntry(key, entry);
299
- }
300
- for (const required of REQUIRED_CAPABILITIES) if (!providers[required]) throw new ConfigError(`required capability \`${required}\` is missing from providers`);
301
- let docs;
302
- if (raw.docs !== void 0) {
303
- if (!raw.docs.build) throw new ConfigError("`docs.build` is required when `docs` is set");
304
- docs = raw.docs;
305
- }
306
- const homepage = raw.homepage ?? (docs?.domain ? `https://${docs.domain}/` : void 0);
307
- return {
308
- name: raw.name,
309
- description: raw.description,
310
- homepage,
311
- org: raw.org,
312
- domain: raw.domain,
313
- repo: raw.repo,
314
- tasks: raw.tasks,
315
- syncScripts: raw.syncScripts,
316
- holocronScript: raw.holocronScript,
317
- extraRequiredChecks: raw.extraRequiredChecks,
318
- hooks: raw.hooks,
319
- providers,
320
- apps: raw.apps ?? [],
321
- doctor: raw.doctor ?? {},
322
- agent: raw.agent,
323
- skills: raw.skills,
324
- docs,
325
- env: raw.env,
326
- log: raw.log,
327
- telemetry: raw.telemetry
328
- };
329
- }
330
- //#endregion
331
- //#region src/config/compose.ts
332
- function taskName(e) {
333
- return typeof e === "string" ? e : e.name;
334
- }
335
- /**
336
- * Merge any number of capability fragments into a single preset object that
337
- * spreads directly into `defineConfig()`.
338
- *
339
- * - Accepts individual capabilities or nested arrays (for bundle presets).
340
- * - Deduplicates by `id` — when the same ID appears more than once, the last
341
- * occurrence wins. This lets callers override bundle defaults by listing an
342
- * explicit capability after the bundle.
343
- * - Validates all `requires` at call time and throws `ConfigError` if any are
344
- * unmet, listing every missing dependency in a single message.
345
- *
346
- * @example
347
- * // docs-only site — no typecheck
348
- * const preset = compose(node(), docs());
349
- *
350
- * // library with docs
351
- * const preset = compose(node(), typecheck(), docs());
352
- *
353
- * // nextjs() is a bundle that returns Capability[]
354
- * const preset = compose(node(), nextjs());
355
- */
356
- function compose(...args) {
357
- const flat = args.flat();
358
- const byId = /* @__PURE__ */ new Map();
359
- for (const cap of flat) byId.set(cap.id, cap);
360
- const caps = [...byId.values()];
361
- const available = new Set(caps.map((c) => c.id));
362
- const errors = [];
363
- for (const cap of caps) for (const req of cap.requires ?? []) if (!available.has(req)) errors.push(`"${cap.id}" requires "${req}"`);
364
- if (errors.length > 0) throw new ConfigError(`compose(): unmet dependencies — ${errors.join(", ")}`);
365
- const taskMap = /* @__PURE__ */ new Map();
366
- for (const cap of caps) for (const entry of cap.tasks ?? []) taskMap.set(taskName(entry), entry);
367
- let providers = {};
368
- for (const cap of caps) if (cap.providers) providers = {
369
- ...providers,
370
- ...cap.providers
371
- };
372
- const checksSeen = /* @__PURE__ */ new Set();
373
- const extraRequiredChecks = [];
374
- for (const cap of caps) for (const check of cap.extraRequiredChecks ?? []) if (!checksSeen.has(check)) {
375
- checksSeen.add(check);
376
- extraRequiredChecks.push(check);
377
- }
378
- let repo = {};
379
- for (const cap of caps) {
380
- if (!cap.repo) continue;
381
- const { properties, topics, teams, ...scalars } = cap.repo;
382
- repo = {
383
- ...repo,
384
- ...scalars
385
- };
386
- if (properties) repo.properties = {
387
- ...repo.properties,
388
- ...properties
389
- };
390
- if (topics) {
391
- const merged = /* @__PURE__ */ new Set([...repo.topics ?? [], ...topics]);
392
- repo.topics = [...merged];
393
- }
394
- if (teams) {
395
- const teamMap = new Map((repo.teams ?? []).map((t) => [typeof t === "string" ? t : t.slug, t]));
396
- for (const t of teams) teamMap.set(typeof t === "string" ? t : t.slug, t);
397
- repo.teams = [...teamMap.values()];
398
- }
399
- }
400
- let org;
401
- let domain;
402
- let docs;
403
- for (const cap of caps) {
404
- if (cap.org !== void 0) org = cap.org;
405
- if (cap.domain !== void 0) domain = cap.domain;
406
- if (cap.docs !== void 0) docs = cap.docs;
407
- }
408
- return {
409
- tasks: [...taskMap.values()],
410
- providers,
411
- repo,
412
- extraRequiredChecks,
413
- ...org !== void 0 ? { org } : {},
414
- ...domain !== void 0 ? { domain } : {},
415
- ...docs !== void 0 ? { docs } : {}
416
- };
221
+ return results;
417
222
  }
418
- //#endregion
419
- //#region src/config/define-config.ts
223
+ // src/config/define-config/define-config.ts
420
224
  function defineConfig(config) {
421
225
  return config;
422
226
  }
423
- //#endregion
424
- //#region src/config/load-config.ts
227
+ // src/config/load-config/load-config.ts
425
228
  /**
426
229
  * `holocron.config.{ts,js,mjs,cjs,json}` loader.
427
230
  *
@@ -433,34 +236,40 @@ function defineConfig(config) {
433
236
  * Probe order is TS-first (`.ts` → `.js` → `.mjs` → `.cjs` → `.json`) —
434
237
  * see ADR-0010 / issue #75 / #81.
435
238
  */
436
- const execFileAsync = promisify(execFile);
437
239
  /**
438
- * Read + parse + resolve `holocron.config.*` from the given directory.
240
+ * Read + parse + resolve `holocron.config.*` starting from the given
241
+ * directory, walking up through ancestors to the nearest `.git` boundary
242
+ * when `cwd` itself has no match — every command is usable from any
243
+ * subdirectory of a repo, not only its exact root (see
244
+ * `@theholocron/datapad`'s own doc comment for the stop conditions).
439
245
  * Throws {@link ConfigFileError} when nothing is found or a file cannot
440
- * be loaded, or `ConfigError` when the config is invalid.
246
+ * be loaded, or `ConfigError` when the config fails schema checks.
441
247
  */
442
248
  async function loadConfig(cwd) {
443
249
  const found = await loadConfigFile({
444
250
  cwd,
445
- name: "holocron"
251
+ name: "holocron",
252
+ walkUp: true
446
253
  });
447
254
  if (!found) throw new ConfigFileError$1(`no holocron.config.{ts,js,mjs,cjs,json} found in ${cwd}. Create one — see the README for the schema.`);
255
+ const withDefaults = await deriveDefaults(found);
448
256
  return {
449
- resolved: resolveConfig(await deriveDefaults(dirname(found.filepath), found.config)),
257
+ resolved: resolveConfig(withDefaults),
450
258
  filepath: found.filepath
451
259
  };
452
260
  }
453
- async function deriveDefaults(configDir, raw) {
454
- const result = { ...raw };
261
+ async function deriveDefaults(found) {
262
+ const configDir = dirname(found.filepath);
263
+ const result = { ...found.config };
455
264
  if (!result.name) result.name = await readPackageJsonName(configDir) ?? basename(configDir);
456
265
  if (result.repo && !result.repo.name) {
457
- const repoName = await readGitRemote(configDir);
458
- if (repoName) result.repo = {
266
+ const remote = await readGitRemote(configDir);
267
+ if (remote?.host === "github.com") result.repo = {
459
268
  ...result.repo,
460
- name: repoName
269
+ name: remote.slug
461
270
  };
462
271
  }
463
- const manifest = await loadTasksConfig(configDir);
272
+ const manifest = await loadTasksConfig(configDir, { holocron: found });
464
273
  if (manifest.tasks) result.tasks = manifest.tasks;
465
274
  if (manifest.syncScripts !== void 0) result.syncScripts = manifest.syncScripts;
466
275
  if (manifest.holocronScript !== void 0) result.holocronScript = manifest.holocronScript;
@@ -469,31 +278,144 @@ async function deriveDefaults(configDir, raw) {
469
278
  return result;
470
279
  }
471
280
  async function readPackageJsonName(dir) {
472
- try {
473
- const content = await readFile(join(dir, "package.json"), "utf8");
474
- const pkg = JSON.parse(content);
475
- return typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : void 0;
476
- } catch {
477
- return;
281
+ const name = (await readPackageJson(dir))?.name;
282
+ return name === void 0 ? void 0 : name.replace(/^@[^/]+\//, "");
283
+ }
284
+ // src/plugin/connection-probe/connection-probe.ts
285
+ const TLS_CODES = /* @__PURE__ */ new Set([
286
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
287
+ "SELF_SIGNED_CERT_IN_CHAIN",
288
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
289
+ "CERT_HAS_EXPIRED",
290
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
291
+ "ERR_TLS_CERT_ALTNAME_INVALID"
292
+ ]);
293
+ /** The code Node attaches to a network failure, with that error's message: on the error itself, or on its `cause` (where `fetch` puts it). */
294
+ function codeOf(err) {
295
+ for (let e = err, depth = 0; e && depth < 4; depth++) {
296
+ if (typeof e.code === "string") return {
297
+ code: e.code,
298
+ message: String(e.message ?? "")
299
+ };
300
+ e = e.cause;
478
301
  }
479
302
  }
480
- async function readGitRemote(dir) {
481
- try {
482
- const { stdout } = await execFileAsync("git", [
483
- "remote",
484
- "get-url",
485
- "origin"
486
- ], { cwd: dir });
487
- return parseGitRemoteUrl(stdout.trim());
488
- } catch {
489
- return;
303
+ /** A network failure in plain words, with what usually causes it. Never includes anything from a request. */
304
+ function describeNetworkError(err, timeoutMs) {
305
+ const found = codeOf(err);
306
+ const code = found?.code;
307
+ const name = err?.name;
308
+ if (name === "TimeoutError" || name === "AbortError" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "ETIMEDOUT") return `no answer within ${timeoutMs / 1e3}s (${code ?? name}): a firewall, VPN or proxy may be dropping it`;
309
+ switch (code) {
310
+ case "ENOTFOUND":
311
+ case "EAI_AGAIN": return `${code}: the name did not resolve; check your network and DNS`;
312
+ case "ECONNREFUSED": return "ECONNREFUSED: the host refused the connection";
313
+ case "ECONNRESET":
314
+ case "UND_ERR_SOCKET": return `${code}: the connection was cut off; a proxy or firewall may be interfering`;
315
+ case "ENETUNREACH":
316
+ case "EHOSTUNREACH": return `${code}: no route to the host; check that you are online`;
317
+ default:
318
+ if (code && TLS_CODES.has(code)) return `${code}: the TLS certificate was not trusted; a corporate proxy that re-signs traffic needs NODE_EXTRA_CA_CERTS`;
319
+ return found ? `${found.code}: ${found.message}` : String(err?.message ?? err);
490
320
  }
491
321
  }
492
- function parseGitRemoteUrl(url) {
493
- const httpsMatch = url.match(/github\.com\/([^/]+\/[^/]+?)(?:\.git)?$/);
494
- if (httpsMatch) return httpsMatch[1];
495
- const sshMatch = url.match(/github\.com:([^/]+\/[^/]+?)(?:\.git)?$/);
496
- if (sshMatch) return sshMatch[1];
322
+ /**
323
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem: does the name
324
+ * resolve, does the host answer, is there a token, and does the provider accept it. A step that cannot work because an
325
+ * earlier one failed is reported as not tried rather than failing a second time for the same reason.
326
+ */
327
+ function connectionProbe(input) {
328
+ const timeoutMs = input.timeoutMs ?? 1e4;
329
+ return {
330
+ summary: `Check the network path to ${input.provider} and that it accepts your token.`,
331
+ writes: false,
332
+ async run(probe) {
333
+ let reachable = true;
334
+ if (input.url) {
335
+ const host = new URL(input.url).hostname;
336
+ const lookup$1 = input.lookup ?? (input.fetch ? void 0 : (h) => lookup(h));
337
+ if (lookup$1) try {
338
+ const { address } = await lookup$1(host);
339
+ probe.say({
340
+ status: "ok",
341
+ label: `DNS ${host}`,
342
+ detail: address
343
+ });
344
+ } catch (err) {
345
+ reachable = false;
346
+ probe.say({
347
+ status: "fail",
348
+ label: `DNS ${host}`,
349
+ detail: describeNetworkError(err, timeoutMs)
350
+ });
351
+ }
352
+ if (reachable) {
353
+ const started = Date.now();
354
+ try {
355
+ const res = await (input.fetch ?? fetch)(input.url, {
356
+ method: "GET",
357
+ signal: AbortSignal.timeout(timeoutMs)
358
+ });
359
+ probe.say({
360
+ status: "ok",
361
+ label: `reach ${host}`,
362
+ detail: `HTTP ${res.status} in ${Date.now() - started} ms`
363
+ });
364
+ } catch (err) {
365
+ reachable = false;
366
+ probe.say({
367
+ status: "fail",
368
+ label: `reach ${host}`,
369
+ detail: describeNetworkError(err, timeoutMs)
370
+ });
371
+ }
372
+ } else probe.say({
373
+ status: "info",
374
+ label: `reach ${host}`,
375
+ detail: "not tried: the name did not resolve"
376
+ });
377
+ }
378
+ let token;
379
+ try {
380
+ token = await input.token();
381
+ } catch (err) {
382
+ probe.say({
383
+ status: "fail",
384
+ label: "token",
385
+ detail: err.message
386
+ });
387
+ probe.say({
388
+ status: "info",
389
+ label: "accepted",
390
+ detail: "not tried: there is no token"
391
+ });
392
+ return;
393
+ }
394
+ probe.secret(token);
395
+ probe.say({
396
+ status: "ok",
397
+ label: "token",
398
+ detail: "found"
399
+ });
400
+ if (!reachable) {
401
+ probe.say({
402
+ status: "info",
403
+ label: "accepted",
404
+ detail: "not tried: the host could not be reached"
405
+ });
406
+ return;
407
+ }
408
+ const result = await input.verify(token);
409
+ probe.say(result.ok ? {
410
+ status: "ok",
411
+ label: "accepted",
412
+ detail: result.subject
413
+ } : {
414
+ status: "fail",
415
+ label: "accepted",
416
+ detail: result.message
417
+ });
418
+ }
419
+ };
497
420
  }
498
- //#endregion
499
- export { AuthError, CARDINALITY, ConfigError, ConfigFileError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, compose, createFeatureResolver, createResolveToken, createRestClient, defineConfig, deleteToken, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, getToken, isMulti, listStoredProviders, loadConfig, missingCapabilities, readWorkspacePackageJsons, resolveConfig, resolveEntry, resolvePluginPackage, setToken };
421
+ export { AuthError, CARDINALITY, ConfigError, ConfigFileError, ElevationRequiredError, ProviderApiError, REQUIRED_CAPABILITIES, WebhookVerificationError, compose, connectionProbe, createFeatureResolver, createResolveToken, createRestClient, defineConfig, deleteToken, deriveCapabilities, deriveCompliance, deriveProfile, deriveStack, describeNetworkError, getToken, isMulti, listStoredProviders, loadConfig, missingCapabilities, readWorkspacePackageJsons, resolveConfig, resolveEntry, resolvePluginPackage, setToken };