@theholocron/kyber 5.0.0-alpha.345 → 5.0.0-alpha.347

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/README.md CHANGED
@@ -20,7 +20,33 @@ Published, so a second CLI can import it. `@theholocron/cli` is its first consum
20
20
  | `/testing` | A test harness for a CLI: `createCliRunner` runs a built binary in a fresh directory with an environment built from nothing, `runCommand` runs one yargs command module through a real parse, `ensureBuilt` is a Vitest global setup that builds only when `dist` is missing or stale, and `hermeticCreateRequire` resolves modules only from one directory. |
21
21
  | `/observability` | The logging and telemetry wiring of a CLI: `createCliLogger({ envPrefix, resolveAxiom? })` returns a memoized root logger (`buildCliLogger`, `getLogger`, `reportError`, `getRunId`, `resolveLogLevel`) whose level comes from `--log` / `--verbose` / `--quiet`, then `<PREFIX>_LOG_LEVEL`, then the config file, and is quiet on a terminal unless asked; `createCliTelemetry({ envPrefix, dsn, posthogKey, posthogHost })` returns Sentry error reporting and PostHog analytics behind `<PREFIX>_TELEMETRY=false`. `@theholocron/observability` is an optional peer. |
22
22
  | `/config` | A `<name>.config.{ts,js,mjs,cjs,json}` for a new CLI: `createConfigSystem({ name, derive?, resolve, merge })` returns `defineConfig`, `loadConfig` (walks up to `.git`) and `compose()` (dedupe by `id`, all unmet `requires` in one `ConfigError`, per-key merge). Strategies: `lastWins`, `shallowMerge`, `union`, `mergeByKey`. `@theholocron/datapad` is an optional peer. |
23
+ | `/plugins` | A plugin system for a new CLI: `createPluginSystem({ packagePrefix, providers, communityPrefix?, configFile?, pluginOptions?, preload? })` returns a `PluginLoader` class and `resolvePackage`. `load()` imports each configured provider's package (from the working directory first, importer injectable), calls its `createPlugin(options)` and fills a registry typed by your capability map: `get(key)` is one implementation for a `single` capability and an array for a `many` one. A package may export a capability config (`{ provider, options? }`) whose preset options sit under the project's. A failing provider is recorded in `loadFailures()` and `get` rethrows its error; `load()` never throws for one. Also `assertPluginsResolvable`, `isModuleNotFound`, `resolvePluginPackage`, `defaultImporter` and `LoaderError`. |
23
24
  | `/flags` | The options every command of a tool takes: `addGlobalOptions(parser, { describe?, cwd? })` declares `--dry-run`, a repeatable `--token` and `--cwd` once on the root; `tokenContext(values, report)` parses the `--token` values and reports a bad one without a stack trace; `groupMenu(parent, open)` is the hidden default command that makes a bare group (`tool repo`) do something useful; `InferArgs` types a command's handler arguments from its builder. |
25
+ | `/checks` | `runCheckAgainstUrl(input, opts?)` runs an HTTP check with assertions (`status_code`, `response_time`, `body`, `header`) over `fetch` and returns `{ passed, failures, requestError? }`, with no monitoring vendor involved; `connectionProbe({ provider, url?, token, verify })` is a probe that tells a network problem from a credential problem (and `describeNetworkError` words a network failure). |
26
+ | `/git` | `moveMajorTag({ group, version?, dryRun?, remote? })` moves a version group's major tag (`ci-v1`) to its latest stable release and force-pushes it; `runGit(args, cwd)` runs `git` without a shell. |
27
+
28
+ ## Build a plugin system
29
+
30
+ ```ts
31
+ import { createPluginSystem } from "@theholocron/kyber/plugins";
32
+
33
+ type Capabilities = {
34
+ source: { cardinality: "single"; impl: Source };
35
+ notify: { cardinality: "many"; impl: Notifier };
36
+ };
37
+
38
+ const { PluginLoader } = createPluginSystem<Capabilities, Config, { repoRoot: string }>({
39
+ packagePrefix: "@acme/mytool-plugin-",
40
+ providers: (config) => config.providers,
41
+ });
42
+
43
+ const loader = new PluginLoader(config, { repoRoot: process.cwd() });
44
+ await loader.load();
45
+ loader.get("source"); // Source
46
+ loader.get("notify"); // Notifier[]
47
+ ```
48
+
49
+ A plugin package exports `createPlugin(options)` returning `{ name, capabilities: { source: () => impl } }`.
24
50
 
25
51
  ## Usage
26
52
 
@@ -0,0 +1,135 @@
1
+ /** The result of asking a provider who a token belongs to. */
2
+ type ConnectionVerifyResult = {
3
+ ok: true;
4
+ subject: string;
5
+ } | {
6
+ ok: false;
7
+ message: string;
8
+ };
9
+ /** One line a connection probe reports. */
10
+ interface ConnectionProbeRow {
11
+ /** `ok` or `fail` for a result, `info` for a fact. */
12
+ status: "ok" | "fail" | "info";
13
+ /** The row's short title. */
14
+ label: string;
15
+ /** Further detail, when there is some. */
16
+ detail?: string;
17
+ }
18
+ /** What a connection probe is handed: where to report, and which values must never be printed. Satisfied by a probe context. */
19
+ interface ConnectionProbeContext {
20
+ /** Reports one line. */
21
+ say(row: ConnectionProbeRow): void;
22
+ /** Marks a value (the token) as one that must never be printed. */
23
+ secret(value: string | undefined): void;
24
+ }
25
+ /** A probe that checks the network path to a provider and its token. Assignable to a plugin system's probe type. */
26
+ interface ConnectionProbe {
27
+ /** One sentence for a listing of probes. */
28
+ summary: string;
29
+ /** Always `false`: it creates and changes nothing. */
30
+ writes: false;
31
+ /** Runs the probe, reporting through `ctx`. */
32
+ run(ctx: ConnectionProbeContext): Promise<void>;
33
+ }
34
+ /** What a connection probe needs to check a provider's host and token. */
35
+ interface ConnectionProbeInput {
36
+ /** How the provider is named in output, e.g. `Axiom`. */
37
+ provider: string;
38
+ /** A URL on the provider's API host. Without one, only the token is checked (a provider that has no HTTP API of its own). */
39
+ url?: string;
40
+ /** Finds the token the plugin would use. Throws with a message that says where to put one when there is none. */
41
+ token: () => string | Promise<string>;
42
+ /** Asks the provider who the token belongs to. */
43
+ verify: (token: string) => Promise<ConnectionVerifyResult>;
44
+ /** Stands in for the network, so with one the name lookup (which cannot be stood in for) is not made. */
45
+ fetch?: typeof fetch;
46
+ /** Resolves a hostname. Defaults to the system resolver, unless `fetch` is given. */
47
+ lookup?: (host: string) => Promise<{
48
+ address: string;
49
+ }>;
50
+ /** Longest to wait for the host to answer. Defaults to 10 s. */
51
+ timeoutMs?: number;
52
+ }
53
+ /**
54
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem: does the name
55
+ * resolve, does the host answer, is there a token, and does the provider accept it. A step that cannot work because an
56
+ * earlier one failed is reported as not tried rather than failing a second time for the same reason.
57
+ *
58
+ * @param input - The provider, its API URL, how to find and verify its token, and test seams for the network.
59
+ * @returns A probe in the shape a plugin system expects: `summary`, `writes: false` and `run(ctx)`, which reports through `ctx.say`.
60
+ */
61
+ export declare function connectionProbe(input: ConnectionProbeInput): ConnectionProbe;
62
+ /**
63
+ * A network failure in plain words, with what usually causes it. Never includes anything from a request.
64
+ *
65
+ * @param err - The error `fetch` or a name lookup threw; Node's error code is read from it or from its `cause`.
66
+ * @param timeoutMs - The deadline that was set, for the "no answer within" message.
67
+ * @returns One line for a person: the code and what usually causes it.
68
+ */
69
+ export declare function describeNetworkError(err: unknown, timeoutMs: number): string;
70
+ /** What part of a response a {@link CheckAssertion} looks at. */
71
+ type CheckAssertionSource = "status_code" | "response_time" | "body" | "header";
72
+ /** How a {@link CheckAssertion} compares the part of the response with its target. */
73
+ type CheckAssertionComparison = "equals" | "not_equals" | "contains" | "not_contains" | "greater_than" | "less_than";
74
+ /** A condition a check's response must meet to pass. */
75
+ interface CheckAssertion {
76
+ /** The part of the response to look at. */
77
+ source: CheckAssertionSource;
78
+ /** How to compare it with `target`. */
79
+ comparison: CheckAssertionComparison;
80
+ /** The header name, required when `source` is `"header"`. */
81
+ property?: string;
82
+ /** The value to compare against. */
83
+ target?: string;
84
+ }
85
+ /** An HTTP check: the request to make and the conditions its response must meet. Structurally a monitoring check's definition. */
86
+ interface CheckInput {
87
+ /** The URL to request. */
88
+ url: string;
89
+ /** The HTTP method. Defaults to `GET`. A body is only sent for a method other than `GET` and `HEAD`. */
90
+ method?: string;
91
+ /** The request body. */
92
+ body?: string;
93
+ /** Conditions the response must meet; with none, only the status (below 400) is checked. */
94
+ assertions?: CheckAssertion[];
95
+ /** Inverts the implicit status check: set it when the healthy response is itself an error status (a 404, say). */
96
+ shouldFail?: boolean;
97
+ }
98
+ interface CheckRunResult {
99
+ passed: boolean;
100
+ status?: number;
101
+ responseTimeMs?: number;
102
+ /** Human-readable reasons, one per failed assertion (plus the implicit >=400 check, when it fires). Empty when `passed`. */
103
+ failures: string[];
104
+ /** Set only when the request itself failed (network error, timeout, etc.) — never passes, regardless of `shouldFail`. */
105
+ requestError?: string;
106
+ }
107
+ interface RunCheckOptions {
108
+ /**
109
+ * Overrides the origin of `input.url` — e.g. a PR's preview deployment
110
+ * origin instead of the check's own configured production one. Only
111
+ * the scheme+host+port are taken from this; `input.url`'s own
112
+ * path/query are preserved (a bare preview origin would otherwise
113
+ * silently drop e.g. `/api/webhook` and test `/` instead).
114
+ */
115
+ url?: string;
116
+ /** Injectable for testing. Defaults to the global `fetch`. */
117
+ fetch?: typeof fetch;
118
+ /** Request timeout in ms, covering the whole request including body read. Default 10s. */
119
+ timeoutMs?: number;
120
+ /** Max response body bytes read when an assertion needs the body. Default 1MB. */
121
+ maxBodyBytes?: number;
122
+ /** Extra headers merged into the request — e.g. a Deployment Protection bypass header. */
123
+ headers?: Record<string, string>;
124
+ }
125
+ /**
126
+ * Runs one HTTP check against a URL and says whether it passed: the request is made here, every assertion is evaluated
127
+ * here, and nothing is sent to a monitoring vendor. A response status of 400 or more fails the check before any assertion
128
+ * runs, unless `input.shouldFail` is set. A network error or a timeout never passes (`requestError`).
129
+ *
130
+ * @param input - The check: the URL, the method, the body and the assertions to evaluate.
131
+ * @param opts - Overrides for the origin, headers, timeout and body cap, and a `fetch` to stand in for the network.
132
+ * @returns The outcome: whether it passed, the status and timing, and one reason per failed assertion.
133
+ */
134
+ export declare function runCheckAgainstUrl(input: CheckInput, opts?: RunCheckOptions): Promise<CheckRunResult>;
135
+ export type { CheckAssertion, CheckAssertionComparison, CheckAssertionSource, CheckInput, CheckRunResult, ConnectionProbe, ConnectionProbeContext, ConnectionProbeInput, ConnectionProbeRow, ConnectionVerifyResult, RunCheckOptions };
@@ -0,0 +1,262 @@
1
+ import { lookup } from "node:dns/promises";
2
+ // src/checks/describe-network-error/describe-network-error.ts
3
+ const TLS_CODES = /* @__PURE__ */ new Set([
4
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
5
+ "SELF_SIGNED_CERT_IN_CHAIN",
6
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
7
+ "CERT_HAS_EXPIRED",
8
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
9
+ "ERR_TLS_CERT_ALTNAME_INVALID"
10
+ ]);
11
+ /** 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). */
12
+ function codeOf(err) {
13
+ for (let e = err, depth = 0; e && depth < 4; depth++) {
14
+ if (typeof e.code === "string") return {
15
+ code: e.code,
16
+ message: String(e.message ?? "")
17
+ };
18
+ e = e.cause;
19
+ }
20
+ }
21
+ /**
22
+ * A network failure in plain words, with what usually causes it. Never includes anything from a request.
23
+ *
24
+ * @param err - The error `fetch` or a name lookup threw; Node's error code is read from it or from its `cause`.
25
+ * @param timeoutMs - The deadline that was set, for the "no answer within" message.
26
+ * @returns One line for a person: the code and what usually causes it.
27
+ */
28
+ function describeNetworkError(err, timeoutMs) {
29
+ const found = codeOf(err);
30
+ const code = found?.code;
31
+ const name = err?.name;
32
+ 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`;
33
+ switch (code) {
34
+ case "ENOTFOUND":
35
+ case "EAI_AGAIN": return `${code}: the name did not resolve; check your network and DNS`;
36
+ case "ECONNREFUSED": return "ECONNREFUSED: the host refused the connection";
37
+ case "ECONNRESET":
38
+ case "UND_ERR_SOCKET": return `${code}: the connection was cut off; a proxy or firewall may be interfering`;
39
+ case "ENETUNREACH":
40
+ case "EHOSTUNREACH": return `${code}: no route to the host; check that you are online`;
41
+ default:
42
+ 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`;
43
+ return found ? `${found.code}: ${found.message}` : String(err?.message ?? err);
44
+ }
45
+ }
46
+ // src/checks/connection-probe/connection-probe.ts
47
+ /**
48
+ * The `connection` probe every provider offers, for telling a network problem from a credential problem: does the name
49
+ * resolve, does the host answer, is there a token, and does the provider accept it. A step that cannot work because an
50
+ * earlier one failed is reported as not tried rather than failing a second time for the same reason.
51
+ *
52
+ * @param input - The provider, its API URL, how to find and verify its token, and test seams for the network.
53
+ * @returns A probe in the shape a plugin system expects: `summary`, `writes: false` and `run(ctx)`, which reports through `ctx.say`.
54
+ */
55
+ function connectionProbe(input) {
56
+ const timeoutMs = input.timeoutMs ?? 1e4;
57
+ return {
58
+ summary: `Check the network path to ${input.provider} and that it accepts your token.`,
59
+ writes: false,
60
+ async run(probe) {
61
+ let reachable = true;
62
+ if (input.url) {
63
+ const host = new URL(input.url).hostname;
64
+ const lookup$1 = input.lookup ?? (input.fetch ? void 0 : (h) => lookup(h));
65
+ if (lookup$1) try {
66
+ const { address } = await lookup$1(host);
67
+ probe.say({
68
+ status: "ok",
69
+ label: `DNS ${host}`,
70
+ detail: address
71
+ });
72
+ } catch (err) {
73
+ reachable = false;
74
+ probe.say({
75
+ status: "fail",
76
+ label: `DNS ${host}`,
77
+ detail: describeNetworkError(err, timeoutMs)
78
+ });
79
+ }
80
+ if (reachable) {
81
+ const started = Date.now();
82
+ try {
83
+ const res = await (input.fetch ?? fetch)(input.url, {
84
+ method: "GET",
85
+ signal: AbortSignal.timeout(timeoutMs)
86
+ });
87
+ probe.say({
88
+ status: "ok",
89
+ label: `reach ${host}`,
90
+ detail: `HTTP ${res.status} in ${Date.now() - started} ms`
91
+ });
92
+ } catch (err) {
93
+ reachable = false;
94
+ probe.say({
95
+ status: "fail",
96
+ label: `reach ${host}`,
97
+ detail: describeNetworkError(err, timeoutMs)
98
+ });
99
+ }
100
+ } else probe.say({
101
+ status: "info",
102
+ label: `reach ${host}`,
103
+ detail: "not tried: the name did not resolve"
104
+ });
105
+ }
106
+ let token;
107
+ try {
108
+ token = await input.token();
109
+ } catch (err) {
110
+ probe.say({
111
+ status: "fail",
112
+ label: "token",
113
+ detail: err.message
114
+ });
115
+ probe.say({
116
+ status: "info",
117
+ label: "accepted",
118
+ detail: "not tried: there is no token"
119
+ });
120
+ return;
121
+ }
122
+ probe.secret(token);
123
+ probe.say({
124
+ status: "ok",
125
+ label: "token",
126
+ detail: "found"
127
+ });
128
+ if (!reachable) {
129
+ probe.say({
130
+ status: "info",
131
+ label: "accepted",
132
+ detail: "not tried: the host could not be reached"
133
+ });
134
+ return;
135
+ }
136
+ const result = await input.verify(token);
137
+ probe.say(result.ok ? {
138
+ status: "ok",
139
+ label: "accepted",
140
+ detail: result.subject
141
+ } : {
142
+ status: "fail",
143
+ label: "accepted",
144
+ detail: result.message
145
+ });
146
+ }
147
+ };
148
+ }
149
+ // src/checks/run-check-against-url/run-check-against-url.ts
150
+ /**
151
+ * Runs one HTTP check against a URL and says whether it passed: the request is made here, every assertion is evaluated
152
+ * here, and nothing is sent to a monitoring vendor. A response status of 400 or more fails the check before any assertion
153
+ * runs, unless `input.shouldFail` is set. A network error or a timeout never passes (`requestError`).
154
+ *
155
+ * @param input - The check: the URL, the method, the body and the assertions to evaluate.
156
+ * @param opts - Overrides for the origin, headers, timeout and body cap, and a `fetch` to stand in for the network.
157
+ * @returns The outcome: whether it passed, the status and timing, and one reason per failed assertion.
158
+ */
159
+ async function runCheckAgainstUrl(input, opts = {}) {
160
+ const doFetch = opts.fetch ?? fetch;
161
+ const url = resolveUrl(input.url, opts.url);
162
+ const method = input.method ?? "GET";
163
+ const hasBody = input.body !== void 0 && method !== "GET" && method !== "HEAD";
164
+ const needsBody = (input.assertions ?? []).some((a) => a.source === "body");
165
+ const start = Date.now();
166
+ let response;
167
+ let bodyText = "";
168
+ try {
169
+ response = await doFetch(url, {
170
+ method,
171
+ ...hasBody ? { body: input.body } : {},
172
+ ...opts.headers ? { headers: opts.headers } : {},
173
+ redirect: "manual",
174
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 1e4)
175
+ });
176
+ if (needsBody) bodyText = await readBodyCapped(response, opts.maxBodyBytes ?? 1e6);
177
+ } catch (err) {
178
+ return {
179
+ passed: false,
180
+ failures: [],
181
+ requestError: requestErrorMessage(err)
182
+ };
183
+ }
184
+ const responseTimeMs = Date.now() - start;
185
+ const failures = [];
186
+ if (!input.shouldFail && response.status >= 400) failures.push(`HTTP ${response.status} (>= 400 counts as a failure unless \`shouldFail\` is set)`);
187
+ for (const assertion of input.assertions ?? []) {
188
+ const actual = extractActual(assertion, {
189
+ response,
190
+ bodyText,
191
+ responseTimeMs
192
+ });
193
+ if (!evaluate(assertion.comparison, actual, assertion.target)) failures.push(`${assertion.source} ${assertion.comparison} "${assertion.target ?? ""}" — got "${truncate(actual)}"`);
194
+ }
195
+ return {
196
+ passed: failures.length === 0,
197
+ status: response.status,
198
+ responseTimeMs,
199
+ failures
200
+ };
201
+ }
202
+ /** Swaps in `overrideUrl`'s origin, keeping `originalUrl`'s own path + query. */
203
+ function resolveUrl(originalUrl, overrideUrl) {
204
+ if (!overrideUrl) return originalUrl;
205
+ const original = new URL(originalUrl);
206
+ const resolved = new URL(overrideUrl);
207
+ resolved.pathname = original.pathname;
208
+ resolved.search = original.search;
209
+ return resolved.toString();
210
+ }
211
+ function requestErrorMessage(err) {
212
+ if (err instanceof Error) return err.name === "TimeoutError" ? `request timed out: ${err.message}` : err.message;
213
+ return String(err);
214
+ }
215
+ /** Reads up to `maxBytes` of the response body, discarding the rest — a large/unending body can't exhaust memory. */
216
+ async function readBodyCapped(response, maxBytes) {
217
+ if (!response.body) return "";
218
+ const reader = response.body.getReader();
219
+ const chunks = [];
220
+ let total = 0;
221
+ try {
222
+ for (;;) {
223
+ const { done, value } = await reader.read();
224
+ if (done) break;
225
+ const remaining = maxBytes - total;
226
+ if (remaining <= 0) break;
227
+ const stored = value.length > remaining ? value.slice(0, remaining) : value;
228
+ chunks.push(stored);
229
+ total += stored.length;
230
+ }
231
+ } finally {
232
+ await reader.cancel().catch(() => {});
233
+ }
234
+ return Buffer.concat(chunks.map((c) => Buffer.from(c))).toString("utf8");
235
+ }
236
+ /** Keeps a failure message readable when `actual` is a full HTML/JSON response body. */
237
+ function truncate(value, max = 200) {
238
+ return value.length > max ? `${value.slice(0, max)}…` : value;
239
+ }
240
+ function extractActual(assertion, ctx) {
241
+ switch (assertion.source) {
242
+ case "status_code": return String(ctx.response.status);
243
+ case "response_time": return String(ctx.responseTimeMs);
244
+ case "body": return ctx.bodyText;
245
+ case "header": {
246
+ const name = assertion.property ?? "";
247
+ return name ? ctx.response.headers.get(name) ?? "" : "";
248
+ }
249
+ }
250
+ }
251
+ function evaluate(comparison, actual, target) {
252
+ const t = target ?? "";
253
+ switch (comparison) {
254
+ case "equals": return actual === t;
255
+ case "not_equals": return actual !== t;
256
+ case "contains": return actual.includes(t);
257
+ case "not_contains": return !actual.includes(t);
258
+ case "greater_than": return Number(actual) > Number(t);
259
+ case "less_than": return Number(actual) < Number(t);
260
+ }
261
+ }
262
+ export { connectionProbe, describeNetworkError, runCheckAgainstUrl };
@@ -1,4 +1,3 @@
1
- import { createInterface } from "node:readline";
2
1
  // src/ui/strip-control/strip-control.ts
3
2
  /**
4
3
  * Control characters (newlines and the C1 range included, whose 0x9b is an 8-bit CSI) turned into spaces and whitespace
@@ -35,26 +34,4 @@ function describeError(err) {
35
34
  }
36
35
  return base;
37
36
  }
38
- // src/ui/wait-for-enter/wait-for-enter.ts
39
- /**
40
- * Print `message` and wait until Enter is pressed, the input ends, or Ctrl-C is pressed, whichever comes first, and
41
- * return which: `enter`, or `closed` for the other two. It never hangs on a closed input. It reads from stdin and
42
- * writes to stderr, so a pipe on stdout is never touched; the caller checks there is a terminal to answer it. The
43
- * streams are parameters so a test can answer for the user.
44
- */
45
- function waitForEnter(message, input = process.stdin, output = process.stderr) {
46
- return new Promise((resolve) => {
47
- const rl = createInterface({
48
- input,
49
- output
50
- });
51
- let answered = false;
52
- rl.on("close", () => resolve(answered ? "enter" : "closed"));
53
- rl.on("SIGINT", () => rl.close());
54
- rl.question(message, () => {
55
- answered = true;
56
- rl.close();
57
- });
58
- });
59
- }
60
- export { stripControl as i, describeError as n, sanitizeDetail as r, waitForEnter as t };
37
+ export { sanitizeDetail as n, stripControl as r, describeError as t };
package/dist/git.d.mts ADDED
@@ -0,0 +1,57 @@
1
+ import { Logger } from "@theholocron/observability/core";
2
+ /** Runs `git` with `args` in `cwd` and returns its trimmed stdout; throws when git fails. */
3
+ type RunGit = (args: readonly string[], cwd: string) => string;
4
+ /** What `moveMajorTag` needs, and the seams that stand in for the terminal, logging and `git`. */
5
+ interface MoveMajorTagInput {
6
+ /** The version group whose major tag moves: its tags are `<group>-v<version>`. */
7
+ group: string;
8
+ /** The stable release the major tag should point at (`1.4.0`). Defaults to the group's latest stable tag. */
9
+ version?: string;
10
+ /** Working directory (the repo root). Defaults to process.cwd(). */
11
+ cwd?: string;
12
+ /** Print what would move without tagging or pushing. */
13
+ dryRun?: boolean;
14
+ /** The remote to push to. Defaults to `origin`. */
15
+ remote?: string;
16
+ /** Where progress lines go. Defaults to `console.log`. */
17
+ /** Where progress lines go. Defaults to `console.log`. */
18
+ print?: (line: string) => void;
19
+ /** Structured-logging sink, sibling of `print`. Nothing is logged without one. */
20
+ logger?: Logger;
21
+ /** Injectable for testing. Defaults to spawning `git`. */
22
+ git?: RunGit;
23
+ }
24
+ /** How a run ended. */
25
+ type MoveMajorTagStatus = "ok" | "fail" | "dry-run";
26
+ /** What `moveMajorTag` did. */
27
+ interface MoveMajorTagReport {
28
+ status: MoveMajorTagStatus;
29
+ /** The moving major tag (`ci-v1`), when one was worked out. */
30
+ tag?: string;
31
+ /** The release tag it points at (`ci-v1.4.0`). */
32
+ target?: string;
33
+ message?: string;
34
+ }
35
+ /**
36
+ * Moves a version group's major tag (`ci-v1`) to its latest stable release (`ci-v1.4.0`) and force-pushes it, so
37
+ * a caller that pins `ci-v1` follows the group without changing its workflow files. Immutable tags
38
+ * (`ci-v1.4.0`) are never touched. Run by the group's release (`publishCmd`) and by hand for a repair.
39
+ *
40
+ * A prerelease is refused: the major tag follows stable releases only.
41
+ *
42
+ * @param input - The group, and optionally the version, the working directory, the remote and `dryRun`; `print`, `logger`
43
+ * and `git` stand in for the terminal, structured logging and the `git` binary.
44
+ * @returns The outcome: `ok`, `dry-run` or `fail` (with `message`), and the tag names that were worked out.
45
+ */
46
+ export declare function moveMajorTag(input: MoveMajorTagInput): Promise<MoveMajorTagReport>;
47
+ /**
48
+ * Runs `git` with `args` in `cwd` and returns its trimmed stdout. Spawns `git` without a shell, so a version or group can
49
+ * never be read as anything but an argument. stderr is piped, not shown: git narrates a push, and a failure is in the
50
+ * thrown error's message.
51
+ *
52
+ * @param args - The arguments after `git`.
53
+ * @param cwd - The directory to run in (the repo root).
54
+ * @returns The command's trimmed standard output; throws when git fails.
55
+ */
56
+ export declare const runGit: RunGit;
57
+ export type { MoveMajorTagInput, MoveMajorTagReport, MoveMajorTagStatus, RunGit };
package/dist/git.mjs ADDED
@@ -0,0 +1,124 @@
1
+ import { t as describeError } from "./describe-error-y4wLzFzj.mjs";
2
+ import { execFileSync } from "node:child_process";
3
+ // src/git/run-git/run-git.ts
4
+ /**
5
+ * Runs `git` with `args` in `cwd` and returns its trimmed stdout. Spawns `git` without a shell, so a version or group can
6
+ * never be read as anything but an argument. stderr is piped, not shown: git narrates a push, and a failure is in the
7
+ * thrown error's message.
8
+ *
9
+ * @param args - The arguments after `git`.
10
+ * @param cwd - The directory to run in (the repo root).
11
+ * @returns The command's trimmed standard output; throws when git fails.
12
+ */
13
+ const runGit = (args, cwd) => execFileSync("git", [...args], {
14
+ cwd,
15
+ encoding: "utf8",
16
+ stdio: [
17
+ "ignore",
18
+ "pipe",
19
+ "pipe"
20
+ ]
21
+ }).trim();
22
+ // src/git/move-major-tag/move-major-tag.ts
23
+ const STABLE = /^(\d+)\.(\d+)\.(\d+)$/;
24
+ /** Orders stable versions, newest last. */
25
+ function compare(a, b) {
26
+ const [pa, pb] = [a, b].map((v) => STABLE.exec(v).slice(1).map(Number));
27
+ return pa.reduce((diff, n, i) => diff || n - pb[i], 0);
28
+ }
29
+ /**
30
+ * Moves a version group's major tag (`ci-v1`) to its latest stable release (`ci-v1.4.0`) and force-pushes it, so
31
+ * a caller that pins `ci-v1` follows the group without changing its workflow files. Immutable tags
32
+ * (`ci-v1.4.0`) are never touched. Run by the group's release (`publishCmd`) and by hand for a repair.
33
+ *
34
+ * A prerelease is refused: the major tag follows stable releases only.
35
+ *
36
+ * @param input - The group, and optionally the version, the working directory, the remote and `dryRun`; `print`, `logger`
37
+ * and `git` stand in for the terminal, structured logging and the `git` binary.
38
+ * @returns The outcome: `ok`, `dry-run` or `fail` (with `message`), and the tag names that were worked out.
39
+ */
40
+ async function moveMajorTag(input) {
41
+ const print = input.print ?? ((line) => console.log(line));
42
+ const logger = input.logger;
43
+ const cwd = input.cwd ?? process.cwd();
44
+ const git = input.git ?? runGit;
45
+ const { group, dryRun = false, remote = "origin" } = input;
46
+ const fail = (message) => {
47
+ print(` ✗ ${message}`);
48
+ logger?.info({
49
+ group,
50
+ status: "fail"
51
+ }, "move-major-tag: done");
52
+ return {
53
+ status: "fail",
54
+ message
55
+ };
56
+ };
57
+ let version = input.version;
58
+ try {
59
+ if (version === void 0) {
60
+ version = git([
61
+ "tag",
62
+ "--list",
63
+ `${group}-v*`
64
+ ], cwd).split("\n").map((tag) => tag.slice(`${group}-v`.length)).filter((v) => STABLE.test(v)).sort(compare).at(-1);
65
+ if (version === void 0) return fail(`no stable ${group}-v<version> tag to move ${group}-v<major> to`);
66
+ }
67
+ const parts = STABLE.exec(version);
68
+ if (!parts) return fail(`${version} is not a stable version (x.y.z); the major tag follows stable releases only`);
69
+ const target = `${group}-v${version}`;
70
+ const tag = `${group}-v${parts[1]}`;
71
+ print(`Moving ${tag} to ${target}${dryRun ? " (dry-run)" : ""}…`);
72
+ logger?.info({
73
+ group,
74
+ tag,
75
+ target,
76
+ dryRun: dryRun || void 0
77
+ }, "move-major-tag: start");
78
+ let commit;
79
+ try {
80
+ commit = git([
81
+ "rev-parse",
82
+ "--verify",
83
+ `refs/tags/${target}^{commit}`
84
+ ], cwd);
85
+ } catch {
86
+ return fail(`no tag ${target} in this clone; fetch the tags first (git fetch --tags)`);
87
+ }
88
+ if (dryRun) {
89
+ print(` ~ ${tag} → ${commit.slice(0, 9)} (${target}), then push --force ${remote}`);
90
+ return {
91
+ status: "dry-run",
92
+ tag,
93
+ target
94
+ };
95
+ }
96
+ git([
97
+ "tag",
98
+ "--force",
99
+ tag,
100
+ commit
101
+ ], cwd);
102
+ git([
103
+ "push",
104
+ "--force",
105
+ remote,
106
+ `refs/tags/${tag}`
107
+ ], cwd);
108
+ print(` ✓ ${tag} → ${commit.slice(0, 9)} (${target})`);
109
+ logger?.info({
110
+ group,
111
+ tag,
112
+ target,
113
+ status: "ok"
114
+ }, "move-major-tag: done");
115
+ return {
116
+ status: "ok",
117
+ tag,
118
+ target
119
+ };
120
+ } catch (error) {
121
+ return fail(describeError(error));
122
+ }
123
+ }
124
+ export { moveMajorTag, runGit };
package/dist/menu.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as NonInteractiveError } from "./non-interactive-error-Mm_Mn79M.mjs";
2
2
  import { pickMenuItem, promptForDeferredOptions, promptForOptions, promptForPositionals } from "./prompts.mjs";
3
- import { confirm } from "@inquirer/prompts";
4
3
  import { spawn } from "node:child_process";
4
+ import { confirm } from "@inquirer/prompts";
5
5
  // src/menu/forwarded-flags/forwarded-flags.ts
6
6
  /**
7
7
  * `--token` (repeatable), `--org`, `--cwd`, `--dry-run` — the global flags a
@@ -0,0 +1,221 @@
1
+ /** How many providers a capability resolves to: one (`"single"`) or several active at once (`"many"`). */
2
+ type Cardinality = "single" | "many";
3
+ /**
4
+ * The capabilities of a CLI as a type: each key maps to its cardinality and to the interface a provider implements.
5
+ * It exists only at the type level; it types `loader.get(key)` so a `single` key hands back one implementation and a
6
+ * `many` key an array.
7
+ * Declare it as a `type` alias, not an `interface` (an interface has no index signature).
8
+ *
9
+ * @example
10
+ * type MyCapabilities = {
11
+ * source: { cardinality: "single"; impl: Source };
12
+ * notifications: { cardinality: "many"; impl: Notifier };
13
+ * };
14
+ */
15
+ type CapabilityShape = Record<string, {
16
+ cardinality: Cardinality;
17
+ impl: unknown;
18
+ }>;
19
+ /** The capability keys of a {@link CapabilityShape}. */
20
+ type CapabilityKeyOf<Caps extends CapabilityShape> = Extract<keyof Caps, string>;
21
+ /** What `loader.get(key)` returns for `key`: one implementation for a `single` capability, an array for a `many`. */
22
+ type ResolvedCapability<Caps extends CapabilityShape, K extends CapabilityKeyOf<Caps>> = Caps[K]["cardinality"] extends "many" ? Caps[K]["impl"][] : Caps[K]["impl"];
23
+ /** A provider with its plugin package resolved. */
24
+ interface ProviderTuple {
25
+ /** The provider's short name, e.g. `github`. */
26
+ provider: string;
27
+ /** The package that implements it, e.g. `@acme/mycli-plugin-github`. */
28
+ packageName: string;
29
+ /** Options the config gives this provider. */
30
+ options: Record<string, unknown>;
31
+ }
32
+ /** What a capability is configured with: one provider, or a list of them. */
33
+ type ProviderEntry = {
34
+ cardinality: "single";
35
+ tuple: ProviderTuple;
36
+ } | {
37
+ cardinality: "many";
38
+ tuples: ProviderTuple[];
39
+ };
40
+ /** Imports a package by name. Injectable, so tests need no real packages installed. */
41
+ type PluginImporter = (packageName: string) => Promise<unknown>;
42
+ /**
43
+ * What a plugin's `createPlugin(options)` returns: a name, a factory per capability it implements, and whatever else
44
+ * the CLI lets a plugin carry (`Extra`, e.g. probes).
45
+ */
46
+ type LoadedPlugin<Caps extends CapabilityShape, Extra extends object = Record<never, never>> = {
47
+ /** The plugin's name. */
48
+ name: string;
49
+ /** A factory for each capability the plugin implements; the loader calls the one it needs. */
50
+ capabilities: Partial<{ [K in CapabilityKeyOf<Caps>]: () => unknown; }>;
51
+ } & Extra;
52
+ /** The shape a plugin package must export: `createPlugin(options)`. */
53
+ interface PluginModule<Caps extends CapabilityShape, Extra extends object = Record<never, never>> {
54
+ /** Builds the plugin from the merged options. */
55
+ createPlugin: (options: Record<string, unknown>) => LoadedPlugin<Caps, Extra>;
56
+ }
57
+ /** The default export of a capability config package: a provider and the preset options to start it with. */
58
+ interface CapabilityConfigPackage {
59
+ /** The provider's short name or package. */
60
+ provider: string;
61
+ /** Preset options; the project's own options for the provider win over them. */
62
+ options?: Record<string, unknown>;
63
+ }
64
+ /** A provider that could not be loaded: a missing package, a bad token, an unimplemented capability. */
65
+ interface PluginLoadFailure<Key extends string = string> {
66
+ /** The capability that was being loaded. */
67
+ key: Key;
68
+ /** The provider's short name. */
69
+ provider: string;
70
+ /** The package that failed. */
71
+ packageName: string;
72
+ /** What went wrong. */
73
+ error: Error;
74
+ }
75
+ /** The part of a loader {@link assertPluginsResolvable} reads. Every `PluginLoader` satisfies it. */
76
+ interface PluginLoadReport {
77
+ /** The capability keys that loaded. */
78
+ loadedKeys(): readonly string[];
79
+ /** The providers that failed to load. */
80
+ loadFailures(): readonly PluginLoadFailure[];
81
+ }
82
+ /** What a {@link PluginSystemOptions.preload} step can do to the loader while it runs. */
83
+ interface PreloadApi<Caps extends CapabilityShape> {
84
+ /** Load one provider (import, `createPlugin`, capability factory) and return its implementation. Throws on failure. */
85
+ loadOne(key: CapabilityKeyOf<Caps>, tuple: ProviderTuple): Promise<unknown>;
86
+ /** Record a provider as failed, so `get` and `loadFailures` report it, and carry on. */
87
+ fail(key: CapabilityKeyOf<Caps>, tuple: ProviderTuple, err: unknown): void;
88
+ /** Put the loaded implementations of a capability in the registry. */
89
+ register(key: CapabilityKeyOf<Caps>, impls: unknown): void;
90
+ }
91
+ /** A step that runs before the providers load, and that loads some capabilities itself. */
92
+ interface PreloadStep<Caps extends CapabilityShape, Config, Context, LoadOptions> {
93
+ /** The capabilities the step loads, so the normal loop skips them. */
94
+ keys: readonly CapabilityKeyOf<Caps>[];
95
+ /** Runs once at the start of `load()`. */
96
+ run(api: PreloadApi<Caps>, input: {
97
+ config: Config;
98
+ context: Context;
99
+ options: LoadOptions | undefined;
100
+ }): Promise<void> | void;
101
+ }
102
+ /** What {@link createPluginSystem} needs to build a CLI's plugin loader. */
103
+ interface PluginSystemOptions<Caps extends CapabilityShape, Config, Context extends object, LoadOptions = undefined> {
104
+ /** What a short provider name is prefixed with to get its package, e.g. `@acme/mycli-plugin-`. */
105
+ packagePrefix: string;
106
+ /** The prefix of an unscoped third-party plugin package, e.g. `mycli-plugin-`; such names are used as they are. */
107
+ communityPrefix?: string;
108
+ /** The name of the config file, for the message when a capability is asked for and was never configured. */
109
+ configFile?: string;
110
+ /** Reads the resolved provider entries, by capability, out of the CLI's config. */
111
+ providers: (config: Config) => Partial<{ [K in CapabilityKeyOf<Caps>]: ProviderEntry; }>;
112
+ /**
113
+ * The options handed to `createPlugin` for one provider. Defaults to the context spread first and the provider's own
114
+ * options over it. Return what you want, with the provider's `tuple.options` last so they win.
115
+ */
116
+ pluginOptions?: (input: {
117
+ config: Config;
118
+ context: Context;
119
+ tuple: ProviderTuple;
120
+ }) => Record<string, unknown>;
121
+ /** A step that loads some capabilities before the rest (for example credentials that other plugins read). */
122
+ preload?: PreloadStep<Caps, Config, Context, LoadOptions>;
123
+ }
124
+ /** The loader a CLI builds with {@link createPluginSystem}. */
125
+ interface PluginLoader<Caps extends CapabilityShape, Extra extends object = Record<never, never>> extends PluginLoadReport {
126
+ /**
127
+ * Imports every configured plugin and builds the capability registry. Never throws for one plugin's failure: it is
128
+ * recorded in {@link PluginLoader.loadFailures} and the load continues, so a command learns a capability is absent
129
+ * from `has()` / `get()`.
130
+ */
131
+ load(): Promise<void>;
132
+ /** The implementation of a capability: one for a `single` key, an array for a `many` key. Throws when it did not load. */
133
+ get<K extends CapabilityKeyOf<Caps>>(key: K): ResolvedCapability<Caps, K>;
134
+ /** Whether a capability has loaded. */
135
+ has(key: CapabilityKeyOf<Caps>): boolean;
136
+ /** Every capability key that has loaded. */
137
+ loadedKeys(): CapabilityKeyOf<Caps>[];
138
+ /** The providers that failed to load. Empty on a clean load. */
139
+ loadFailures(): readonly PluginLoadFailure<CapabilityKeyOf<Caps>>[];
140
+ /** The plugin object of each provider that was created, by provider name. */
141
+ plugins(): ReadonlyMap<string, LoadedPlugin<Caps, Extra>>;
142
+ }
143
+ /** The class {@link createPluginSystem} returns; extend it or construct it directly. */
144
+ interface PluginLoaderConstructor<Caps extends CapabilityShape, Config, Context extends object, Extra extends object = Record<never, never>, LoadOptions = undefined> {
145
+ /**
146
+ * @param config - The resolved config.
147
+ * @param context - Per-run context every plugin receives in its options.
148
+ * @param importer - Imports a package by name; defaults to resolving from the current directory first.
149
+ * @param options - Passed to the {@link PluginSystemOptions.preload} step.
150
+ */
151
+ new (config: Config, context: Context, importer?: PluginImporter, options?: LoadOptions): PluginLoader<Caps, Extra>;
152
+ }
153
+ /** What {@link createPluginSystem} returns. */
154
+ interface PluginSystem<Caps extends CapabilityShape, Config, Context extends object, Extra extends object = Record<never, never>, LoadOptions = undefined> {
155
+ /** The loader class, bound to this CLI's prefix, config shape and hooks. */
156
+ PluginLoader: PluginLoaderConstructor<Caps, Config, Context, Extra, LoadOptions>;
157
+ /** Turn a provider's short name into its package name with this CLI's prefixes. */
158
+ resolvePackage: (provider: string) => string;
159
+ }
160
+ /**
161
+ * Build the plugin system of a new CLI: a loader that reads the providers from your config, imports each one's package
162
+ * (resolving from the working directory first), calls its `createPlugin(options)` and keeps the capabilities it
163
+ * implements in a typed registry, `single` or `many` per capability.
164
+ *
165
+ * A package may also export a capability config (`export default { provider, options? }`); the loader follows it to the
166
+ * provider and merges the preset options under the project's own. A provider that fails to load is recorded and
167
+ * skipped, never thrown, so one missing token does not stop a command that does not need it.
168
+ *
169
+ * What is yours stays yours: the capability interfaces (the `Caps` type), the package prefix, how the config lists
170
+ * providers and what a plugin is handed. Nothing about credentials, tokens or `.env` files is built in; a CLI that
171
+ * wants them uses `pluginOptions` and the `preload` step.
172
+ *
173
+ * @example
174
+ * const { PluginLoader } = createPluginSystem<MyCapabilities, MyConfig, MyContext>({
175
+ * packagePrefix: "@acme/mycli-plugin-",
176
+ * providers: (config) => config.providers,
177
+ * });
178
+ * const loader = new PluginLoader(config, { repoRoot });
179
+ * await loader.load();
180
+ * const source = loader.get("source");
181
+ */
182
+ export declare function createPluginSystem<Caps extends CapabilityShape, Config, Context extends object, Extra extends object = Record<never, never>, LoadOptions = undefined>(options: PluginSystemOptions<Caps, Config, Context, LoadOptions>): PluginSystem<Caps, Config, Context, Extra, LoadOptions>;
183
+ /**
184
+ * Turn "every plugin failed because none is installed here" (a CLI run from a global install, outside the project that
185
+ * has the plugins) into one actionable error, instead of a stack of `Cannot find package` failures.
186
+ *
187
+ * Does nothing in every other case: some capability loaded, a failure that is not a missing package (a bad token, an
188
+ * unimplemented capability) or no plugins configured at all. Call it right after `await loader.load()`.
189
+ *
190
+ * @param loader - A loaded plugin loader.
191
+ * @param command - The command being run, for the message.
192
+ * @param createError - Builds the error to throw from the command and the unresolved package names.
193
+ */
194
+ export declare function assertPluginsResolvable(loader: PluginLoadReport, command: string, createError: (command: string, packages: readonly string[]) => Error): void;
195
+ /**
196
+ * The importer a plugin loader uses unless it is given another: resolves the package from the current working
197
+ * directory first, so a globally installed CLI finds the plugins of the project it runs in, and falls back to a plain
198
+ * `import()` when that fails.
199
+ */
200
+ export declare const defaultImporter: PluginImporter;
201
+ /**
202
+ * Whether an error is a raw "package isn't installed here" failure from `import()` or `require.resolve`:
203
+ * `ERR_MODULE_NOT_FOUND` / `MODULE_NOT_FOUND`, or the "Cannot find package/module" message Node prints for it.
204
+ */
205
+ export declare function isModuleNotFound(err: unknown): boolean;
206
+ /** Raised when a plugin cannot be imported, does not export what a plugin must, or a capability is asked for and absent. */
207
+ export declare class LoaderError extends Error {
208
+ name: string;
209
+ }
210
+ /**
211
+ * Turn a provider name into the package that implements it: `"github"` becomes `"<prefix>github"`. A scoped name
212
+ * (`@acme/x`), a name that already starts with `communityPrefix` and any name containing `/` are returned as they are,
213
+ * which is how plugins published outside your scope work.
214
+ *
215
+ * @param provider - The short name or the full package name.
216
+ * @param prefix - What a short name is prefixed with, e.g. `@acme/mycli-plugin-`.
217
+ * @param communityPrefix - The prefix an unscoped third-party package uses, e.g. `mycli-plugin-`.
218
+ * @throws `Error` when `provider` is empty.
219
+ */
220
+ export declare function resolvePluginPackage(provider: string, prefix: string, communityPrefix?: string): string;
221
+ export type { CapabilityConfigPackage, CapabilityKeyOf, CapabilityShape, Cardinality, LoadedPlugin, PluginImporter, PluginLoadFailure, PluginLoadReport, PluginLoader, PluginLoaderConstructor, PluginModule, PluginSystem, PluginSystemOptions, PreloadApi, PreloadStep, ProviderEntry, ProviderTuple, ResolvedCapability };
@@ -0,0 +1,216 @@
1
+ import { createRequire } from "node:module";
2
+ import { pathToFileURL } from "node:url";
3
+ // src/plugins/loader-error/loader-error.ts
4
+ /** Raised when a plugin cannot be imported, does not export what a plugin must, or a capability is asked for and absent. */
5
+ var LoaderError = class extends Error {
6
+ name = "LoaderError";
7
+ };
8
+ // src/plugins/assert-plugins-resolvable/assert-plugins-resolvable.ts
9
+ /**
10
+ * Turn "every plugin failed because none is installed here" (a CLI run from a global install, outside the project that
11
+ * has the plugins) into one actionable error, instead of a stack of `Cannot find package` failures.
12
+ *
13
+ * Does nothing in every other case: some capability loaded, a failure that is not a missing package (a bad token, an
14
+ * unimplemented capability) or no plugins configured at all. Call it right after `await loader.load()`.
15
+ *
16
+ * @param loader - A loaded plugin loader.
17
+ * @param command - The command being run, for the message.
18
+ * @param createError - Builds the error to throw from the command and the unresolved package names.
19
+ */
20
+ function assertPluginsResolvable(loader, command, createError) {
21
+ if (loader.loadedKeys().length > 0) return;
22
+ const failures = loader.loadFailures();
23
+ if (failures.length === 0) return;
24
+ const isImportFailure = (err) => err instanceof LoaderError && err.message.startsWith("failed to import");
25
+ if (!failures.every((f) => isImportFailure(f.error))) return;
26
+ throw createError(command, [...new Set(failures.map((f) => f.packageName))]);
27
+ }
28
+ // src/plugins/default-importer/default-importer.ts
29
+ /**
30
+ * The importer a plugin loader uses unless it is given another: resolves the package from the current working
31
+ * directory first, so a globally installed CLI finds the plugins of the project it runs in, and falls back to a plain
32
+ * `import()` when that fails.
33
+ */
34
+ const defaultImporter = async (packageName) => {
35
+ try {
36
+ const resolved = createRequire(process.cwd() + "/").resolve(packageName);
37
+ return import(pathToFileURL(resolved).href);
38
+ } catch {
39
+ return import(packageName);
40
+ }
41
+ };
42
+ // src/plugins/resolve-plugin-package/resolve-plugin-package.ts
43
+ /**
44
+ * Turn a provider name into the package that implements it: `"github"` becomes `"<prefix>github"`. A scoped name
45
+ * (`@acme/x`), a name that already starts with `communityPrefix` and any name containing `/` are returned as they are,
46
+ * which is how plugins published outside your scope work.
47
+ *
48
+ * @param provider - The short name or the full package name.
49
+ * @param prefix - What a short name is prefixed with, e.g. `@acme/mycli-plugin-`.
50
+ * @param communityPrefix - The prefix an unscoped third-party package uses, e.g. `mycli-plugin-`.
51
+ * @throws `Error` when `provider` is empty.
52
+ */
53
+ function resolvePluginPackage(provider, prefix, communityPrefix) {
54
+ if (!provider) throw new Error("provider name is empty");
55
+ if (provider.startsWith("@")) return provider;
56
+ if (communityPrefix && provider.startsWith(communityPrefix)) return provider;
57
+ if (provider.includes("/")) return provider;
58
+ return prefix + provider;
59
+ }
60
+ // src/plugins/create-plugin-system/create-plugin-system.ts
61
+ function messageOf(err) {
62
+ return err instanceof Error ? err.message : String(err);
63
+ }
64
+ function isPluginModule(mod) {
65
+ return typeof mod?.createPlugin === "function";
66
+ }
67
+ function isCapabilityConfigModule(mod) {
68
+ return typeof (mod?.default)?.provider === "string";
69
+ }
70
+ /**
71
+ * Build the plugin system of a new CLI: a loader that reads the providers from your config, imports each one's package
72
+ * (resolving from the working directory first), calls its `createPlugin(options)` and keeps the capabilities it
73
+ * implements in a typed registry, `single` or `many` per capability.
74
+ *
75
+ * A package may also export a capability config (`export default { provider, options? }`); the loader follows it to the
76
+ * provider and merges the preset options under the project's own. A provider that fails to load is recorded and
77
+ * skipped, never thrown, so one missing token does not stop a command that does not need it.
78
+ *
79
+ * What is yours stays yours: the capability interfaces (the `Caps` type), the package prefix, how the config lists
80
+ * providers and what a plugin is handed. Nothing about credentials, tokens or `.env` files is built in; a CLI that
81
+ * wants them uses `pluginOptions` and the `preload` step.
82
+ *
83
+ * @example
84
+ * const { PluginLoader } = createPluginSystem<MyCapabilities, MyConfig, MyContext>({
85
+ * packagePrefix: "@acme/mycli-plugin-",
86
+ * providers: (config) => config.providers,
87
+ * });
88
+ * const loader = new PluginLoader(config, { repoRoot });
89
+ * await loader.load();
90
+ * const source = loader.get("source");
91
+ */
92
+ function createPluginSystem(options) {
93
+ const { packagePrefix, communityPrefix, configFile = "the config", providers, pluginOptions, preload } = options;
94
+ const resolvePackage = (provider) => resolvePluginPackage(provider, packagePrefix, communityPrefix);
95
+ class Loader {
96
+ config;
97
+ context;
98
+ importer;
99
+ loadOptions;
100
+ registry = /* @__PURE__ */ new Map();
101
+ failures = [];
102
+ created = /* @__PURE__ */ new Map();
103
+ constructor(config, context, importer = defaultImporter, loadOptions) {
104
+ this.config = config;
105
+ this.context = context;
106
+ this.importer = importer;
107
+ this.loadOptions = loadOptions;
108
+ }
109
+ async load() {
110
+ const skip = new Set(preload?.keys ?? []);
111
+ if (preload) await preload.run({
112
+ loadOne: (key, tuple) => this.loadOne(key, tuple),
113
+ fail: (key, tuple, err) => this.recordFailure(key, tuple, err),
114
+ register: (key, impls) => void this.registry.set(key, impls)
115
+ }, {
116
+ config: this.config,
117
+ context: this.context,
118
+ options: this.loadOptions
119
+ });
120
+ const entries = Object.entries(providers(this.config));
121
+ for (const [key, entry] of entries) {
122
+ if (!entry || skip.has(key)) continue;
123
+ if (entry.cardinality === "single") try {
124
+ this.registry.set(key, await this.loadOne(key, entry.tuple));
125
+ } catch (err) {
126
+ this.recordFailure(key, entry.tuple, err);
127
+ }
128
+ else {
129
+ const impls = [];
130
+ for (const tuple of entry.tuples) try {
131
+ impls.push(await this.loadOne(key, tuple));
132
+ } catch (err) {
133
+ this.recordFailure(key, tuple, err);
134
+ }
135
+ if (impls.length > 0) this.registry.set(key, impls);
136
+ }
137
+ }
138
+ }
139
+ get(key) {
140
+ const impl = this.registry.get(key);
141
+ if (impl === void 0) {
142
+ const failure = this.failures.find((f) => f.key === key);
143
+ if (failure) throw failure.error;
144
+ throw new LoaderError(`capability \`${key}\` is not loaded — is it declared in ${configFile}?`);
145
+ }
146
+ return impl;
147
+ }
148
+ has(key) {
149
+ return this.registry.has(key);
150
+ }
151
+ loadedKeys() {
152
+ return Array.from(this.registry.keys());
153
+ }
154
+ loadFailures() {
155
+ return this.failures;
156
+ }
157
+ plugins() {
158
+ return this.created;
159
+ }
160
+ recordFailure(key, tuple, err) {
161
+ this.failures.push({
162
+ key,
163
+ provider: tuple.provider,
164
+ packageName: tuple.packageName,
165
+ error: err instanceof Error ? err : new Error(String(err))
166
+ });
167
+ }
168
+ async loadOne(key, tuple) {
169
+ const mod = await this.importer(tuple.packageName).catch((err) => {
170
+ throw new LoaderError(`failed to import \`${tuple.packageName}\` for capability \`${key}\`: ${messageOf(err)}`);
171
+ });
172
+ if (isPluginModule(mod)) {
173
+ const plugin = mod.createPlugin(pluginOptions ? pluginOptions({
174
+ config: this.config,
175
+ context: this.context,
176
+ tuple
177
+ }) : {
178
+ ...this.context,
179
+ ...tuple.options
180
+ });
181
+ this.created.set(tuple.provider, plugin);
182
+ const factory = plugin.capabilities[key];
183
+ if (typeof factory !== "function") throw new LoaderError(`\`${tuple.packageName}\` does not implement the \`${key}\` capability`);
184
+ return factory();
185
+ }
186
+ if (isCapabilityConfigModule(mod)) {
187
+ const cap = mod.default;
188
+ return this.loadOne(key, {
189
+ provider: cap.provider,
190
+ packageName: resolvePackage(cap.provider),
191
+ options: {
192
+ ...cap.options,
193
+ ...tuple.options
194
+ }
195
+ });
196
+ }
197
+ throw new LoaderError(`\`${tuple.packageName}\` does not export \`createPlugin(options)\` or a capability config ({ provider, options? })`);
198
+ }
199
+ }
200
+ return {
201
+ PluginLoader: Loader,
202
+ resolvePackage
203
+ };
204
+ }
205
+ // src/plugins/is-module-not-found/is-module-not-found.ts
206
+ /**
207
+ * Whether an error is a raw "package isn't installed here" failure from `import()` or `require.resolve`:
208
+ * `ERR_MODULE_NOT_FOUND` / `MODULE_NOT_FOUND`, or the "Cannot find package/module" message Node prints for it.
209
+ */
210
+ function isModuleNotFound(err) {
211
+ if (!(err instanceof Error)) return false;
212
+ const code = err.code;
213
+ if (code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND") return true;
214
+ return /Cannot find (?:package|module)|MODULE_NOT_FOUND/.test(err.message);
215
+ }
216
+ export { LoaderError, assertPluginsResolvable, createPluginSystem, defaultImporter, isModuleNotFound, resolvePluginPackage };
package/dist/secrets.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { n as parseTokenArgs, t as TokenParseError } from "./token-args-BgrCq_kK.mjs";
2
- import { n as describeError, t as waitForEnter } from "./wait-for-enter-Do0h9yET.mjs";
2
+ import { t as describeError } from "./describe-error-y4wLzFzj.mjs";
3
+ import { t as waitForEnter } from "./wait-for-enter-BeC-qTm3.mjs";
3
4
  import { createRequire } from "node:module";
4
5
  import { execFileSync } from "node:child_process";
5
6
  import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
package/dist/testing.mjs CHANGED
@@ -2,8 +2,8 @@ import { execFileSync, spawn } from "node:child_process";
2
2
  import { existsSync, readdirSync, realpathSync, statSync } from "node:fs";
3
3
  import { dirname, join, sep } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
- import { mkdtemp, rm, writeFile } from "node:fs/promises";
6
5
  import { fileURLToPath } from "node:url";
6
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
7
7
  import yargs from "yargs";
8
8
  // src/testing/cli-runner/cli-runner.ts
9
9
  /**
package/dist/ui.mjs CHANGED
@@ -1,7 +1,8 @@
1
+ import { n as sanitizeDetail, r as stripControl, t as describeError } from "./describe-error-y4wLzFzj.mjs";
1
2
  import { t as NonInteractiveError } from "./non-interactive-error-Mm_Mn79M.mjs";
2
- import { i as stripControl, n as describeError, r as sanitizeDetail, t as waitForEnter } from "./wait-for-enter-Do0h9yET.mjs";
3
- import chalk from "chalk";
3
+ import { t as waitForEnter } from "./wait-for-enter-BeC-qTm3.mjs";
4
4
  import { spawn } from "node:child_process";
5
+ import chalk from "chalk";
5
6
  import ora from "ora";
6
7
  // src/ui/command-failure/command-failure.ts
7
8
  /**
@@ -0,0 +1,24 @@
1
+ import { createInterface } from "node:readline";
2
+ // src/ui/wait-for-enter/wait-for-enter.ts
3
+ /**
4
+ * Print `message` and wait until Enter is pressed, the input ends, or Ctrl-C is pressed, whichever comes first, and
5
+ * return which: `enter`, or `closed` for the other two. It never hangs on a closed input. It reads from stdin and
6
+ * writes to stderr, so a pipe on stdout is never touched; the caller checks there is a terminal to answer it. The
7
+ * streams are parameters so a test can answer for the user.
8
+ */
9
+ function waitForEnter(message, input = process.stdin, output = process.stderr) {
10
+ return new Promise((resolve) => {
11
+ const rl = createInterface({
12
+ input,
13
+ output
14
+ });
15
+ let answered = false;
16
+ rl.on("close", () => resolve(answered ? "enter" : "closed"));
17
+ rl.on("SIGINT", () => rl.close());
18
+ rl.question(message, () => {
19
+ answered = true;
20
+ rl.close();
21
+ });
22
+ });
23
+ }
24
+ export { waitForEnter as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/kyber",
3
- "version": "5.0.0-alpha.345",
3
+ "version": "5.0.0-alpha.347",
4
4
  "description": "The reusable parts of a command-line tool: terminal output, prompts, the interactive menu, the update notifier, safe handling of tokens, a test harness and the global flags.",
5
5
  "keywords": [
6
6
  "cli",
@@ -20,6 +20,11 @@
20
20
  "sideEffects": false,
21
21
  "type": "module",
22
22
  "exports": {
23
+ "./checks": {
24
+ "types": "./dist/checks.d.mts",
25
+ "import": "./dist/checks.mjs",
26
+ "default": "./dist/checks.mjs"
27
+ },
23
28
  "./config": {
24
29
  "types": "./dist/config.d.mts",
25
30
  "import": "./dist/config.mjs",
@@ -30,6 +35,11 @@
30
35
  "import": "./dist/flags.mjs",
31
36
  "default": "./dist/flags.mjs"
32
37
  },
38
+ "./git": {
39
+ "types": "./dist/git.d.mts",
40
+ "import": "./dist/git.mjs",
41
+ "default": "./dist/git.mjs"
42
+ },
33
43
  "./menu": {
34
44
  "types": "./dist/menu.d.mts",
35
45
  "import": "./dist/menu.mjs",
@@ -45,6 +55,11 @@
45
55
  "import": "./dist/observability.mjs",
46
56
  "default": "./dist/observability.mjs"
47
57
  },
58
+ "./plugins": {
59
+ "types": "./dist/plugins.d.mts",
60
+ "import": "./dist/plugins.mjs",
61
+ "default": "./dist/plugins.mjs"
62
+ },
48
63
  "./prompts": {
49
64
  "types": "./dist/prompts.d.mts",
50
65
  "import": "./dist/prompts.mjs",
@@ -90,12 +105,12 @@
90
105
  "typescript": "^5.9.3",
91
106
  "vitest": "^5.0.5",
92
107
  "yargs": "^18.1.0",
93
- "@theholocron/datapad": "5.0.0-alpha.345",
108
+ "@theholocron/datapad": "5.0.0-alpha.347",
94
109
  "@theholocron/observability": "0.7.0-alpha.1",
95
110
  "@theholocron/tsdown-config": "^8.9.0-alpha.8",
96
- "@theholocron/eslint-config": "^8.9.0-alpha.8",
111
+ "@theholocron/tsconfig": "^8.9.0-alpha.8",
97
112
  "@theholocron/vitest-config": "^8.9.0-alpha.8",
98
- "@theholocron/tsconfig": "^8.9.0-alpha.8"
113
+ "@theholocron/eslint-config": "^8.9.0-alpha.8"
99
114
  },
100
115
  "peerDependencies": {
101
116
  "@inquirer/prompts": "^8.0.0",
@@ -106,8 +121,8 @@
106
121
  "dotenv": "^17.0.0",
107
122
  "ora": "^9.0.0",
108
123
  "yargs": "^18.0.0",
109
- "@theholocron/datapad": "^5.0.0-alpha.345",
110
- "@theholocron/observability": "^0.7.0-alpha.1"
124
+ "@theholocron/observability": "^0.7.0-alpha.1",
125
+ "@theholocron/datapad": "^5.0.0-alpha.347"
111
126
  },
112
127
  "peerDependenciesMeta": {
113
128
  "@inquirer/prompts": {