@antasphere/cli-core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Antasphere
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,154 @@
1
+ # @antasphere/cli-core
2
+
3
+ The shared foundation every Antasphere tool CLI builds on. One config home for
4
+ the whole ecosystem, per-tool profile namespaces, the flag → env → profile →
5
+ default URL resolution order, the instance email-OTP auth client, and the
6
+ `CliIo` prompt seam. Tool commands, wire types, and API surfaces live in the
7
+ tools — this package carries only config/login plumbing, never secrets.
8
+
9
+ Consumers today: the `antasphere` account CLI (the hub's `packages/cli`) and
10
+ the `slideless` CLI. The design decisions live in the hub architecture brief
11
+ (`hub-architecture.md` §8, CLI family; §4c, the CLI token flow).
12
+
13
+ ## The config home
14
+
15
+ `$XDG_CONFIG_HOME/antasphere/` (default `~/.config/antasphere/`), directories
16
+ `0700`, files `0600`. One file per tool namespace — tools never collide, and a
17
+ new tool is a new file, never a schema change:
18
+
19
+ ```
20
+ antasphere/ 0700
21
+ ├── config.json 0600 the `hub` tool — the `antasphere`
22
+ │ account CLI (its pre-extraction
23
+ │ location, kept for compatibility)
24
+ └── tools/ 0700
25
+ └── <tool>.json 0600 every other tool, e.g. tools/slideless.json
26
+ ```
27
+
28
+ Each file holds one tool's profiles:
29
+
30
+ ```json
31
+ {
32
+ "activeProfile": "default",
33
+ "profiles": {
34
+ "default": {
35
+ "apiKey": "ant_…",
36
+ "baseUrl": "https://account.antasphere.com",
37
+ "email": "you@example.com",
38
+ "workspaceId": "…"
39
+ }
40
+ }
41
+ }
42
+ ```
43
+
44
+ `email` and `workspaceId` (the org the credential is bound to) are hub-profile
45
+ fields; instance tools typically store `apiKey` + `baseUrl` only. All config
46
+ I/O is env-injected (no `process.env` reads) — tests point the whole config
47
+ world at a temp dir via `XDG_CONFIG_HOME`.
48
+
49
+ ## Surface
50
+
51
+ - `configPath / loadConfig / saveConfig / clearConfig (env, tool)` — the
52
+ tool-namespaced store. `HUB_TOOL` names the hub namespace. `redactKey`
53
+ renders keys safely for terminals.
54
+ - `resolveProfile(config, requested, { unknownHint })` — the named (or
55
+ active) profile; an explicitly named missing profile throws `CliUsageError`.
56
+ - `resolveBaseUrl({ flag, env, envVar, profile, defaultUrl, missingMessage })`
57
+ — flag → tool env var → profile → optional default, origin-normalized;
58
+ throws the tool's message when nothing resolves (tools without a default
59
+ URL, i.e. the self-hosted ones, error deliberately).
60
+ - `resolveApiKey({ flag, env, envVar, profile })` — flag → env → profile.
61
+ - `CliAuthClient(baseUrl)` — the browserless email-OTP flow every instance
62
+ speaks: `request({ email })`, `complete({ email, otp, keyName?,
63
+ expiresInDays?, workspaceId? })` (the full key appears exactly once),
64
+ `revoke(apiKey)` (self-revocation = logout). Errors are `CliAuthError`
65
+ with `status`/`code`/`message`.
66
+ - `CliIo` + `ask` + `printJson` — the injectable I/O seam (env, streams,
67
+ fetch, interactive prompt) so tool CLIs run in-process under test.
68
+ - `migrateLegacyConfig(env, { tool, legacyDir })` — one-shot, non-destructive
69
+ import of a tool's pre-cli-core `$XDG_CONFIG_HOME/<legacyDir>/config.json`
70
+ into the shared home. Imports only when the tool has no profiles in the
71
+ shared home yet and the legacy file holds at least one; the legacy file is
72
+ left in place.
73
+
74
+ ## Consuming it
75
+
76
+ Until the package is on npm, pin the git tag (pnpm resolves the `github:`
77
+ shorthand over SSH — the repo is private):
78
+
79
+ ```json
80
+ "dependencies": {
81
+ "@antasphere/cli-core": "github:antasphere/cli-core#v0.1.0"
82
+ }
83
+ ```
84
+
85
+ The `prepare` script builds `dist/` on install, so git installs work from a
86
+ scratch clone — but pnpm ≥10 blocks dependency build scripts by default, and
87
+ for a git dependency it honors the allowlist **only as the exact resolved
88
+ spec** (no glob patterns, no bare package name — proven against an empty
89
+ store: a bare-name or missing entry fails with
90
+ `ERR_PNPM_GIT_DEP_PREPARE_NOT_ALLOWED`). We standardize the entry in
91
+ `pnpm-workspace.yaml`. Each consumer therefore carries:
92
+
93
+ ```yaml
94
+ # pnpm-workspace.yaml
95
+ onlyBuiltDependencies:
96
+ - esbuild
97
+ - '@antasphere/cli-core@git+ssh://git@github.com/antasphere/cli-core.git#<commit-sha-of-the-tag>'
98
+ ```
99
+
100
+ Bumping the pinned tag: update the dependency, run `pnpm install`, and paste
101
+ the new allowlist line pnpm prints in its error. At npm-publish time the
102
+ switch is one line in each consumer:
103
+
104
+ ```json
105
+ "@antasphere/cli-core": "^0.1.0"
106
+ ```
107
+
108
+ plus dropping the consumer's allowlist entry (registry tarballs ship a
109
+ prebuilt `dist/`, no build script runs).
110
+
111
+ ## Release
112
+
113
+ Releases are tokenless via npm **trusted publishing** (OIDC):
114
+ `.github/workflows/publish.yml` fires on a `vX.Y.Z` tag, verifies the tag
115
+ matches `package.json#version`, runs lint/typecheck/test/build, and publishes
116
+ with no npm token — npm authenticates the workflow's OIDC identity directly.
117
+
118
+ ```bash
119
+ # bump package.json#version, commit, then:
120
+ git tag v0.2.0 && git push origin v0.2.0
121
+ ```
122
+
123
+ **First publish is manual.** Trusted publishing can only be configured on a
124
+ package that already exists on npm, so the very first publish of the name is
125
+ done by hand from a clean checkout while logged in to an account that owns
126
+ the npm `antasphere` org:
127
+
128
+ ```bash
129
+ pnpm install # runs prepare → builds dist/
130
+ npm publish # publishConfig.access = public
131
+ ```
132
+
133
+ After that, configure the trusted publisher on npmjs.com
134
+ (package → Settings → Trusted Publisher → GitHub Actions) with exactly:
135
+
136
+ | Field | Value |
137
+ | -------------------- | ------------- |
138
+ | Organization or user | `antasphere` |
139
+ | Repository | `cli-core` |
140
+ | Workflow filename | `publish.yml` |
141
+ | Environment | *(leave empty)* |
142
+
143
+ and every further release is just the tag.
144
+
145
+ ## Development
146
+
147
+ ```bash
148
+ pnpm install
149
+ pnpm lint && pnpm typecheck && pnpm test && pnpm build
150
+ ```
151
+
152
+ Branches per the workspace rule: `prod` (default, releases/tags) + `dev`
153
+ (day-to-day work). License: MIT (permissive on purpose — this is plumbing
154
+ consumed by public CLIs; confirm before the first npm publish).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The browserless instance-OTP sign-in client (hub-architecture §4c):
3
+ *
4
+ * POST /api/v1/cli/auth/request — email a 6-digit sign-in code
5
+ * POST /api/v1/cli/auth/complete — verify the code, mint an API key
6
+ * (the full key appears exactly once)
7
+ * DELETE /api/v1/cli/auth/key — self-revoke the PRESENTING key (logout)
8
+ *
9
+ * The wire contract is the platform template's — the hub and every
10
+ * Antasphere tool instance speak it, so one client serves the whole family.
11
+ * Self-hosted instances authenticate against themselves with this same flow.
12
+ */
13
+ export declare class CliAuthError extends Error {
14
+ readonly status: number;
15
+ readonly code: string;
16
+ readonly details?: unknown | undefined;
17
+ constructor(status: number, code: string, message: string, details?: unknown | undefined);
18
+ }
19
+ export interface CliAuthRequestBody {
20
+ email: string;
21
+ }
22
+ /** Always `sent: true` on 2xx — deliberately silent about account existence. */
23
+ export interface CliAuthRequested {
24
+ sent: true;
25
+ }
26
+ export interface CliAuthCompleteBody {
27
+ email: string;
28
+ otp: string;
29
+ /** Display name for the minted key (server defaults to a CLI-login label). */
30
+ keyName?: string;
31
+ /** TTL in days at mint. Omit = never expires. */
32
+ expiresInDays?: number;
33
+ /** Hub only: the org the minted key binds to (default: oldest membership). */
34
+ workspaceId?: string;
35
+ }
36
+ /** The minted key's metadata row (template api-key wire shape). */
37
+ export interface CliAuthMintedKey {
38
+ id: string;
39
+ name: string;
40
+ keyId: string;
41
+ scopes: string[];
42
+ createdBy: string;
43
+ createdAt: string;
44
+ lastUsedAt: string | null;
45
+ revokedAt: string | null;
46
+ expiresAt: string | null;
47
+ }
48
+ export interface CliAuthCompleted {
49
+ /** Full key `<prefix>_<keyid>_<secret>` — shown once, never retrievable. */
50
+ key: string;
51
+ apiKey: CliAuthMintedKey;
52
+ user: {
53
+ id: string;
54
+ email: string;
55
+ name: string;
56
+ };
57
+ workspaceId: string;
58
+ }
59
+ export interface CliAuthRevoked {
60
+ revoked: true;
61
+ id: string;
62
+ }
63
+ export interface CliAuthClientOptions {
64
+ /** Instance origin, e.g. https://account.antasphere.com */
65
+ baseUrl: string;
66
+ fetch?: typeof globalThis.fetch;
67
+ }
68
+ export declare class CliAuthClient {
69
+ private readonly baseUrl;
70
+ private readonly fetchImpl;
71
+ constructor(options: CliAuthClientOptions);
72
+ /** Public: request a sign-in code by email. Generic success — no enumeration. */
73
+ request(body: CliAuthRequestBody): Promise<CliAuthRequested>;
74
+ /** Public: verify the code and mint an API key (returned once, like every mint). */
75
+ complete(body: CliAuthCompleteBody): Promise<CliAuthCompleted>;
76
+ /** CLI logout: revoke the PRESENTING API key (self-revocation). */
77
+ revoke(apiKey: string): Promise<CliAuthRevoked>;
78
+ /** Mirrors the platform SDK's parse: `{ error: { code, message, details } }` envelopes. */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zB,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAClD,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,IAAI,CAAC;IACd,EAAE,EAAE,MAAM,CAAC;CACZ;AAED,MAAM,WAAW,oBAAoB;IACnC,2DAA2D;IAC3D,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0B;gBAExC,OAAO,EAAE,oBAAoB;IAKzC,iFAAiF;IACjF,OAAO,CAAC,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAI5D,oFAAoF;IACpF,QAAQ,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAI9D,mEAAmE;IACnE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;IAI/C,2FAA2F;YAC7E,IAAI;CAuBnB"}
package/dist/auth.js ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The browserless instance-OTP sign-in client (hub-architecture §4c):
3
+ *
4
+ * POST /api/v1/cli/auth/request — email a 6-digit sign-in code
5
+ * POST /api/v1/cli/auth/complete — verify the code, mint an API key
6
+ * (the full key appears exactly once)
7
+ * DELETE /api/v1/cli/auth/key — self-revoke the PRESENTING key (logout)
8
+ *
9
+ * The wire contract is the platform template's — the hub and every
10
+ * Antasphere tool instance speak it, so one client serves the whole family.
11
+ * Self-hosted instances authenticate against themselves with this same flow.
12
+ */
13
+ export class CliAuthError extends Error {
14
+ status;
15
+ code;
16
+ details;
17
+ constructor(status, code, message, details) {
18
+ super(message);
19
+ this.status = status;
20
+ this.code = code;
21
+ this.details = details;
22
+ this.name = 'CliAuthError';
23
+ }
24
+ }
25
+ export class CliAuthClient {
26
+ baseUrl;
27
+ fetchImpl;
28
+ constructor(options) {
29
+ this.baseUrl = options.baseUrl.replace(/\/+$/, '');
30
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
31
+ }
32
+ /** Public: request a sign-in code by email. Generic success — no enumeration. */
33
+ request(body) {
34
+ return this.call('POST', '/cli/auth/request', body);
35
+ }
36
+ /** Public: verify the code and mint an API key (returned once, like every mint). */
37
+ complete(body) {
38
+ return this.call('POST', '/cli/auth/complete', body);
39
+ }
40
+ /** CLI logout: revoke the PRESENTING API key (self-revocation). */
41
+ revoke(apiKey) {
42
+ return this.call('DELETE', '/cli/auth/key', undefined, apiKey);
43
+ }
44
+ /** Mirrors the platform SDK's parse: `{ error: { code, message, details } }` envelopes. */
45
+ async call(method, path, body, apiKey) {
46
+ const headers = {};
47
+ if (apiKey)
48
+ headers['authorization'] = `Bearer ${apiKey}`;
49
+ if (body !== undefined)
50
+ headers['content-type'] = 'application/json';
51
+ const res = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
52
+ method,
53
+ headers,
54
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {})
55
+ });
56
+ if (res.status === 204)
57
+ return undefined;
58
+ const json = (await res.json().catch(() => null));
59
+ if (!res.ok) {
60
+ const errBody = (json ?? {});
61
+ throw new CliAuthError(res.status, errBody.error?.code ?? 'unknown_error', errBody.error?.message ?? `Request failed with ${res.status}`, errBody.error?.details);
62
+ }
63
+ return json;
64
+ }
65
+ }
66
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,OAAO,YAAa,SAAQ,KAAK;IAEnB;IACA;IAEA;IAJlB,YACkB,MAAc,EACd,IAAY,EA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IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,OAAO,UAAU,IAAI,EAAE,EAAE;YAChE,MAAM;YACN,OAAO;YACP,GAAG,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC9D,CAAC,CAAC;QACH,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG;YAAE,OAAO,SAAc,CAAC;QAC9C,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAC+B,CAAC;QAChF,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;YACZ,MAAM,OAAO,GAAG,CAAC,IAAI,IAAI,EAAE,CAAuE,CAAC;YACnG,MAAM,IAAI,YAAY,CACpB,GAAG,CAAC,MAAM,EACV,OAAO,CAAC,KAAK,EAAE,IAAI,IAAI,eAAe,EACtC,OAAO,CAAC,KAAK,EAAE,OAAO,IAAI,uBAAuB,GAAG,CAAC,MAAM,EAAE,EAC7D,OAAO,CAAC,KAAK,EAAE,OAAO,CACvB,CAAC;QACJ,CAAC;QACD,OAAO,IAAS,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * The shared Antasphere CLI config home: `$XDG_CONFIG_HOME/antasphere/`
3
+ * (default `~/.config/antasphere/`) — ONE home for the whole tool family
4
+ * (hub-architecture §8: per-tool CLIs share one core owning the config home).
5
+ *
6
+ * Layout — one file per tool namespace, so tools never collide and a new
7
+ * tool is a new file, never a schema change:
8
+ *
9
+ * antasphere/ 0700
10
+ * ├── config.json 0600 the `hub` tool (the `antasphere` account
11
+ * │ CLI — its pre-extraction location, kept)
12
+ * └── tools/ 0700
13
+ * └── <tool>.json 0600 every other tool's profiles
14
+ * (e.g. tools/slideless.json)
15
+ *
16
+ * Each file holds one tool's `{ activeProfile?, profiles }`: multiple named
17
+ * profiles per tool, one active profile per tool. Hub profiles additionally
18
+ * carry the active org (`workspaceId`) their credential is bound to.
19
+ *
20
+ * Files store API keys, so directories are created 0700 and files kept 0600
21
+ * on every write. All I/O is synchronous and env-injected (no process.env
22
+ * reads) so tests can point the whole config world at a temp dir via
23
+ * XDG_CONFIG_HOME.
24
+ */
25
+ export type CliEnv = Record<string, string | undefined>;
26
+ export interface CliProfile {
27
+ /** `<prefix>_...` API key for this profile. */
28
+ apiKey?: string;
29
+ /** Instance origin; absent = the tool's default instance, when it has one. */
30
+ baseUrl?: string;
31
+ /** The signed-in account's email (informational, set by login). */
32
+ email?: string;
33
+ /** The org/workspace the key is bound to (one workspace per credential). */
34
+ workspaceId?: string;
35
+ }
36
+ export interface CliConfig {
37
+ activeProfile?: string;
38
+ profiles: Record<string, CliProfile>;
39
+ }
40
+ /** The hub/account tool — its file is the config home's root `config.json`. */
41
+ export declare const HUB_TOOL = "hub";
42
+ /** Tool namespaces are lowercase slugs — they become file names. */
43
+ export declare function assertToolNamespace(tool: string): void;
44
+ /** Where a tool's config lives for this environment; null when no home is known. */
45
+ export declare function configPath(env: CliEnv, tool: string): string | null;
46
+ /** Tolerant parse (shared with the migrator): corrupt or foreign shapes → empty. */
47
+ export declare function parseConfig(raw: string): CliConfig;
48
+ /** Load a tool's config; a missing/unreadable/corrupt file is an empty config. */
49
+ export declare function loadConfig(env: CliEnv, tool: string): CliConfig;
50
+ /** Persist a tool's config (0700 dirs / 0600 file). Throws when no home is known. */
51
+ export declare function saveConfig(env: CliEnv, tool: string, config: CliConfig): string;
52
+ /** Delete a tool's config file (config clear). No-op when absent. */
53
+ export declare function clearConfig(env: CliEnv, tool: string): void;
54
+ /** `ant_abcd1234_…` → `ant_abcd1234_…c3f9` — safe for terminals and logs. */
55
+ export declare function redactKey(key: string): string;
56
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sour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M,GAAG,MAAM,CAG7C"}
package/dist/config.js ADDED
@@ -0,0 +1,78 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ /** The hub/account tool — its file is the config home's root `config.json`. */
4
+ export const HUB_TOOL = 'hub';
5
+ const TOOL_RE = /^[a-z][a-z0-9-]*$/;
6
+ /** Tool namespaces are lowercase slugs — they become file names. */
7
+ export function assertToolNamespace(tool) {
8
+ if (!TOOL_RE.test(tool)) {
9
+ throw new Error(`Invalid tool namespace "${tool}" — lowercase slugs only ([a-z][a-z0-9-]*).`);
10
+ }
11
+ }
12
+ /** Where a tool's config lives for this environment; null when no home is known. */
13
+ export function configPath(env, tool) {
14
+ assertToolNamespace(tool);
15
+ const base = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, '.config') : null);
16
+ if (!base)
17
+ return null;
18
+ const home = join(base, 'antasphere');
19
+ return tool === HUB_TOOL ? join(home, 'config.json') : join(home, 'tools', `${tool}.json`);
20
+ }
21
+ const EMPTY = { profiles: {} };
22
+ /** Tolerant parse (shared with the migrator): corrupt or foreign shapes → empty. */
23
+ export function parseConfig(raw) {
24
+ try {
25
+ const parsed = JSON.parse(raw);
26
+ const profiles = parsed.profiles && typeof parsed.profiles === 'object' ? parsed.profiles : {};
27
+ return {
28
+ ...(typeof parsed.activeProfile === 'string' ? { activeProfile: parsed.activeProfile } : {}),
29
+ profiles
30
+ };
31
+ }
32
+ catch {
33
+ return { ...EMPTY, profiles: {} };
34
+ }
35
+ }
36
+ /** Load a tool's config; a missing/unreadable/corrupt file is an empty config. */
37
+ export function loadConfig(env, tool) {
38
+ const path = configPath(env, tool);
39
+ if (!path || !existsSync(path))
40
+ return { ...EMPTY, profiles: {} };
41
+ try {
42
+ return parseConfig(readFileSync(path, 'utf8'));
43
+ }
44
+ catch {
45
+ return { ...EMPTY, profiles: {} };
46
+ }
47
+ }
48
+ /** Persist a tool's config (0700 dirs / 0600 file). Throws when no home is known. */
49
+ export function saveConfig(env, tool, config) {
50
+ const path = configPath(env, tool);
51
+ if (!path) {
52
+ throw new Error('Cannot locate a config directory — set HOME or XDG_CONFIG_HOME, or pass --api-key/--api-url explicitly.');
53
+ }
54
+ const dir = dirname(path);
55
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
56
+ // mkdir's mode only applies on creation — re-assert on every write, on
57
+ // every directory level we own (tools/ AND the antasphere home itself).
58
+ chmodSync(dir, 0o700);
59
+ const home = dirname(configPath(env, HUB_TOOL));
60
+ if (dir !== home)
61
+ chmodSync(home, 0o700);
62
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
63
+ chmodSync(path, 0o600);
64
+ return path;
65
+ }
66
+ /** Delete a tool's config file (config clear). No-op when absent. */
67
+ export function clearConfig(env, tool) {
68
+ const path = configPath(env, tool);
69
+ if (path && existsSync(path))
70
+ rmSync(path);
71
+ }
72
+ /** `ant_abcd1234_…` → `ant_abcd1234_…c3f9` — safe for terminals and logs. */
73
+ export function redactKey(key) {
74
+ if (key.length <= 16)
75
+ return '****';
76
+ return `${key.slice(0, 13)}…${key.slice(-4)}`;
77
+ }
78
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAChG,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AA6C1C,+EAA+E;AAC/E,MAAM,CAAC,MAAM,QAAQ,GAAG,KAAK,CAAC;AAE9B,MAAM,OAAO,GAAG,mBAAmB,CAAC;AAEpC,oEAAoE;AACpE,MAAM,UAAU,mBAAmB,CAAC,IAAY;IAC9C,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,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AAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAC7E,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACvB,OAAO,IAAI,CAAC;AACd,CAAC;AAED,qEAAqE;AACrE,MAAM,UAAU,WAAW,CAAC,GAAW,EAAE,IAAY;IACnD,MAAM,IAAI,GAAG,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACnC,IAAI,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC;QAAE,MAAM,CAAC,IAAI,CAAC,CAAC;AAC7C,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,SAAS,CAAC,GAAW;IACnC,IAAI,GAAG,CAAC,MAAM,IAAI,EAAE;QAAE,OAAO,MAAM,CAAC;IACpC,OAAO,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAChD,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @antasphere/cli-core — the shared foundation every Antasphere tool CLI
3
+ * builds on (hub-architecture §8): the `~/.config/antasphere/` config home
4
+ * with tool-namespaced profiles, the flag → env → profile → default URL
5
+ * resolution order, the instance email-OTP auth client, and the CliIo
6
+ * prompt seam. Tool commands, wire types, and API surfaces live in the
7
+ * tools; this package carries only config/login plumbing, never secrets.
8
+ */
9
+ export { assertToolNamespace, clearConfig, configPath, HUB_TOOL, loadConfig, parseConfig, redactKey, saveConfig } from './config.js';
10
+ export type { CliConfig, CliEnv, CliProfile } from './config.js';
11
+ export { ask, printJson } from './io.js';
12
+ export type { CliIo } from './io.js';
13
+ export { CliUsageError, DEFAULT_PROFILE, resolveApiKey, resolveBaseUrl, resolveProfile } from './resolve.js';
14
+ export type { ResolveApiKeyOptions, ResolveBaseUrlOptions, ResolvedProfile } from './resolve.js';
15
+ export { CliAuthClient, CliAuthError } from './auth.js';
16
+ export type { CliAuthClientOptions, CliAuthCompleteBody, CliAuthCompleted, CliAuthMintedKey, CliAuthRequestBody, CliAuthRequested, CliAuthRevoked } from './auth.js';
17
+ export { migrateLegacyConfig } from './migrate.js';
18
+ export type { LegacyMigrationSpec, MigrationResult } from './migrate.js';
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,UAAU,EACV,QAAQ,EACR,UAAU,EACV,WAAW,EACX,SAAS,EACT,UAAU,EACX,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEjE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACzC,YAAY,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC7G,YAAY,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAEjG,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACxD,YAAY,EACV,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACf,MAAM,WAAW,CAAC;AAEnB,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,YAAY,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @antasphere/cli-core — the shared foundation every Antasphere tool CLI
3
+ * builds on (hub-architecture §8): the `~/.config/antasphere/` config home
4
+ * with tool-namespaced profiles, the flag → env → profile → default URL
5
+ * resolution order, the instance email-OTP auth client, and the CliIo
6
+ * prompt seam. Tool commands, wire types, and API surfaces live in the
7
+ * tools; this package carries only config/login plumbing, never secrets.
8
+ */
9
+ export { assertToolNamespace, clearConfig, configPath, HUB_TOOL, loadConfig, parseConfig, redactKey, saveConfig } from './config.js';
10
+ export { ask, printJson } from './io.js';
11
+ export { CliUsageError, DEFAULT_PROFILE, resolveApiKey, resolveBaseUrl, resolveProfile } from './resolve.js';
12
+ export { CliAuthClient, CliAuthError } from './auth.js';
13
+ export { migrateLegacyConfig } from './migrate.js';
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,mBAAmB,EACnB,WAAW,EACX,UAAU,EACV,QAAQ,EACR,UAAU,EACV,WAAW,EACX,SAAS,EACT,UAAU,EACX,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAG7G,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAWxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC"}
package/dist/io.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { CliEnv } from './config.js';
2
+ /**
3
+ * Injectable I/O so a tool CLI is testable in-process: environment, output
4
+ * streams, fetch, and the interactive prompt seam. Bins wire real process
5
+ * streams + readline; tests wire recorders and scripted prompts.
6
+ */
7
+ export interface CliIo {
8
+ env: CliEnv;
9
+ out: {
10
+ write(s: string): void;
11
+ };
12
+ err: {
13
+ write(s: string): void;
14
+ };
15
+ fetch?: typeof globalThis.fetch;
16
+ /** Interactive line prompt (login email/code). The bin wires readline. */
17
+ prompt?: (question: string) => Promise<string>;
18
+ }
19
+ /** Interactive prompt; refuses cleanly when the runner has no prompt wired. */
20
+ export declare function ask(io: CliIo, question: string): Promise<string>;
21
+ export declare function printJson(io: CliIo, value: unknown): void;
22
+ //# sourceMappingURL=io.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io.d.ts","sourceRoot":"","sources":["../src/io.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE1C;;;;GAIG;AACH,MAAM,WAAW,KAAK;IACpB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE;QAAE,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;IAChC,GAAG,EAAE;QAAE,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;KAAE,CAAC;IAChC,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;IAChC,0EAA0E;IAC1E,MAAM,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;CAChD;AAED,+EAA+E;AAC/E,wBAAsB,GAAG,CAAC,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAOtE;AAED,wBAAgB,SAAS,CAAC,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEzD"}
package/dist/io.js ADDED
@@ -0,0 +1,14 @@
1
+ /** Interactive prompt; refuses cleanly when the runner has no prompt wired. */
2
+ export async function ask(io, question) {
3
+ if (!io.prompt) {
4
+ throw new Error('This command is interactive — no prompt available (pass the value as a flag).');
5
+ }
6
+ const answer = (await io.prompt(question)).trim();
7
+ if (!answer)
8
+ throw new Error('Aborted (empty input).');
9
+ return answer;
10
+ }
11
+ export function printJson(io, value) {
12
+ io.out.write(`${JSON.stringify(value, null, 2)}\n`);
13
+ }
14
+ //# sourceMappingURL=io.js.map
package/dist/io.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io.js","sourceRoot":"","sources":["../src/io.ts"],"names":[],"mappings":"AAgBA,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,GAAG,CAAC,EAAS,EAAE,QAAgB;IACnD,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,+EAA+E,CAAC,CAAC;IACnG,CAAC;IACD,MAAM,MAAM,GAAG,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAClD,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;IACvD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,EAAS,EAAE,KAAc;IACjD,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;AACtD,CAAC"}
@@ -0,0 +1,28 @@
1
+ import { type CliEnv } from './config.js';
2
+ /**
3
+ * One-shot, non-destructive import of a tool's pre-cli-core config file
4
+ * (`$XDG_CONFIG_HOME/<legacyDir>/config.json`) into the shared antasphere
5
+ * home. The legacy file is left in place — older CLI versions keep working;
6
+ * it simply stops being read by cli-core consumers.
7
+ */
8
+ export interface LegacyMigrationSpec {
9
+ /** Target tool namespace in the shared home (e.g. 'slideless'). */
10
+ tool: string;
11
+ /** Legacy app dir under the config base (e.g. 'slideless'). */
12
+ legacyDir: string;
13
+ }
14
+ export interface MigrationResult {
15
+ migrated: boolean;
16
+ /** The legacy file imported from (set when migrated). */
17
+ from?: string;
18
+ /** The shared-home file written (set when migrated). */
19
+ to?: string;
20
+ }
21
+ /**
22
+ * Imports iff (a) the tool has NO profiles in the shared home yet, and
23
+ * (b) the legacy file exists and holds at least one profile. Anything else —
24
+ * no home, no legacy file, empty/corrupt legacy content, or a shared-home
25
+ * config already carrying profiles — is a no-op.
26
+ */
27
+ export declare function migrateLegacyConfig(env: CliEnv, spec: LegacyMigrationSpec): MigrationResult;
28
+ //# sourceMappingURL=migrate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate.d.ts","sourceRoot":"","sources":["../src/migrate.ts"],"names":[],"mappings":"AAEA,OAAO,EAML,KAAK,MAAM,EACZ,MAAM,aAAa,CAAC;AAErB;;;;;GAKG;AAEH,MAAM,WAAW,mBAAmB;IAClC,mEAAmE;IACnE,IAAI,EAAE,MAAM,CAAC;IACb,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,eAAe;IAC9B,QAAQ,EAAE,OAAO,CAAC;IAClB,yDAAyD;IACzD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,wDAAwD;IACxD,EAAE,CAAC,EAAE,MAAM,CAAC;CACb;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,mBAAmB,GAAG,eAAe,CAqB3F"}
@@ -0,0 +1,38 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { assertToolNamespace, configPath, loadConfig, parseConfig, saveConfig } from './config.js';
4
+ /**
5
+ * Imports iff (a) the tool has NO profiles in the shared home yet, and
6
+ * (b) the legacy file exists and holds at least one profile. Anything else —
7
+ * no home, no legacy file, empty/corrupt legacy content, or a shared-home
8
+ * config already carrying profiles — is a no-op.
9
+ */
10
+ export function migrateLegacyConfig(env, spec) {
11
+ assertToolNamespace(spec.tool);
12
+ assertToolNamespace(spec.legacyDir);
13
+ const to = configPath(env, spec.tool);
14
+ if (!to)
15
+ return { migrated: false };
16
+ const current = loadConfig(env, spec.tool);
17
+ if (Object.keys(current.profiles).length > 0)
18
+ return { migrated: false };
19
+ const base = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, '.config') : null);
20
+ if (!base)
21
+ return { migrated: false };
22
+ const from = join(base, spec.legacyDir, 'config.json');
23
+ if (!existsSync(from))
24
+ return { migrated: false };
25
+ let raw;
26
+ try {
27
+ raw = readFileSync(from, 'utf8');
28
+ }
29
+ catch {
30
+ return { migrated: false };
31
+ }
32
+ const legacy = parseConfig(raw);
33
+ if (Object.keys(legacy.profiles).length === 0)
34
+ return { migrated: false };
35
+ saveConfig(env, spec.tool, legacy);
36
+ return { migrated: true, from, to };
37
+ }
38
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrate.js","sourceRoot":"","sources":["../src/migrate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EACL,mBAAmB,EACnB,UAAU,EACV,UAAU,EACV,WAAW,EACX,UAAU,EAEX,MAAM,aAAa,CAAC;AAwBrB;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAW,EAAE,IAAyB;IACxE,mBAAmB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC/B,mBAAmB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,CAAC,EAAE;QAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IACpC,MAAM,OAAO,GAAG,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;IAC3C,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,MAAM,GAAG,CAAC;QAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IACzE,MAAM,IAAI,GAAG,GAAG,CAAC,eAAe,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAClF,IAAI,CAAC,IAAI;QAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IACtC,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IACvD,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IAClD,IAAI,GAAW,CAAC;IAChB,IAAI,CAAC;QACH,GAAG,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IAC7B,CAAC;IACD,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;IAChC,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;IAC1E,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACnC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;AACtC,CAAC"}
@@ -0,0 +1,48 @@
1
+ import type { CliConfig, CliEnv, CliProfile } from './config.js';
2
+ /** A usage-level error: runners print `Error: <message>` and exit 1. */
3
+ export declare class CliUsageError extends Error {
4
+ }
5
+ /** The profile name tools fall back to when none is named or active. */
6
+ export declare const DEFAULT_PROFILE = "default";
7
+ export interface ResolvedProfile {
8
+ /** The resolved profile name (undefined = flags/env only, nothing stored). */
9
+ name: string | undefined;
10
+ profile: CliProfile | undefined;
11
+ }
12
+ /**
13
+ * The named (or active) profile of a tool's config, erroring on an
14
+ * explicitly named missing one. `unknownHint` lets the tool append its own
15
+ * remedy (e.g. 'run `slideless profiles` to list them.').
16
+ */
17
+ export declare function resolveProfile(config: CliConfig, requested: string | undefined, opts?: {
18
+ unknownHint?: string;
19
+ }): ResolvedProfile;
20
+ export interface ResolveBaseUrlOptions {
21
+ /** Value of --api-url (or an alias) when given. */
22
+ flag?: string | undefined;
23
+ env: CliEnv;
24
+ /** The tool's URL env var, e.g. 'ANTASPHERE_URL' / 'SLIDELESS_URL'. */
25
+ envVar: string;
26
+ profile?: CliProfile | undefined;
27
+ /** Optional tool default (the hub has one; self-hosted tools error instead). */
28
+ defaultUrl?: string;
29
+ /** Error text when nothing resolves and there is no default. */
30
+ missingMessage?: string;
31
+ }
32
+ /**
33
+ * Base-URL resolution in the ecosystem-wide order:
34
+ * flag → tool env var → profile → optional default → CliUsageError.
35
+ * The result is origin-normalized (trailing slashes stripped).
36
+ */
37
+ export declare function resolveBaseUrl(opts: ResolveBaseUrlOptions): string;
38
+ export interface ResolveApiKeyOptions {
39
+ /** Value of --api-key when given. */
40
+ flag?: string | undefined;
41
+ env: CliEnv;
42
+ /** The tool's key env var, e.g. 'ANTASPHERE_API_KEY' / 'SLIDELESS_API_KEY'. */
43
+ envVar: string;
44
+ profile?: CliProfile | undefined;
45
+ }
46
+ /** API-key resolution: flag → tool env var → profile (undefined = public only). */
47
+ export declare function resolveApiKey(opts: ResolveApiKeyOptions): string | undefined;
48
+ //# sourceMappingURL=resolve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEjE,wEAAwE;AACxE,qBAAa,aAAc,SAAQ,KAAK;CAAG;AAE3C,wEAAwE;AACxE,eAAO,MAAM,eAAe,YAAY,CAAC;AAEzC,MAAM,WAAW,eAAe;IAC9B,8EAA8E;IAC9E,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,OAAO,EAAE,UAAU,GAAG,SAAS,CAAC;CACjC;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,SAAS,EACjB,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAO,GAClC,eAAe,CAajB;AAED,MAAM,WAAW,qBAAqB;IACpC,mDAAmD;IACnD,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,uEAAuE;IACvE,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;IACjC,gFAAgF;IAChF,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,qBAAqB,GAAG,MAAM,CAQlE;AAED,MAAM,WAAW,oBAAoB;IACnC,qCAAqC;IACrC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,GAAG,EAAE,MAAM,CAAC;IACZ,+EAA+E;IAC/E,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;CAClC;AAED,mFAAmF;AACnF,wBAAgB,aAAa,CAAC,IAAI,EAAE,oBAAoB,GAAG,MAAM,GAAG,SAAS,CAE5E"}
@@ -0,0 +1,39 @@
1
+ /** A usage-level error: runners print `Error: <message>` and exit 1. */
2
+ export class CliUsageError extends Error {
3
+ }
4
+ /** The profile name tools fall back to when none is named or active. */
5
+ export const DEFAULT_PROFILE = 'default';
6
+ /**
7
+ * The named (or active) profile of a tool's config, erroring on an
8
+ * explicitly named missing one. `unknownHint` lets the tool append its own
9
+ * remedy (e.g. 'run `slideless profiles` to list them.').
10
+ */
11
+ export function resolveProfile(config, requested, opts = {}) {
12
+ if (requested) {
13
+ const profile = config.profiles[requested];
14
+ if (!profile) {
15
+ throw new CliUsageError(`Unknown profile "${requested}"${opts.unknownHint ? ` — ${opts.unknownHint}` : ''}`);
16
+ }
17
+ return { name: requested, profile };
18
+ }
19
+ const name = config.activeProfile;
20
+ const profile = name ? config.profiles[name] : undefined;
21
+ return { name: profile ? name : undefined, profile };
22
+ }
23
+ /**
24
+ * Base-URL resolution in the ecosystem-wide order:
25
+ * flag → tool env var → profile → optional default → CliUsageError.
26
+ * The result is origin-normalized (trailing slashes stripped).
27
+ */
28
+ export function resolveBaseUrl(opts) {
29
+ const raw = opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.baseUrl ?? opts.defaultUrl;
30
+ if (!raw) {
31
+ throw new CliUsageError(opts.missingMessage ?? `No instance configured — pass --api-url <url> or set ${opts.envVar}.`);
32
+ }
33
+ return raw.replace(/\/+$/, '');
34
+ }
35
+ /** API-key resolution: flag → tool env var → profile (undefined = public only). */
36
+ export function resolveApiKey(opts) {
37
+ return opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.apiKey;
38
+ }
39
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve.js","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAEA,wEAAwE;AACxE,MAAM,OAAO,aAAc,SAAQ,KAAK;CAAG;AAE3C,wEAAwE;AACxE,MAAM,CAAC,MAAM,eAAe,GAAG,SAAS,CAAC;AAQzC;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAC5B,MAAiB,EACjB,SAA6B,EAC7B,OAAiC,EAAE;IAEnC,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;QAC3C,IA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antasphere/cli-core",
3
+ "version": "0.1.0",
4
+ "description": "Shared CLI foundation for Antasphere tool CLIs: the ~/.config/antasphere config home, tool-namespaced profiles, URL resolution, the instance email-OTP auth client, and the CliIo prompt seam",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/antasphere/cli-core.git"
9
+ },
10
+ "type": "module",
11
+ "packageManager": "pnpm@10.34.4",
12
+ "engines": {
13
+ "node": ">=22"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "src"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsc -p tsconfig.build.json",
32
+ "typecheck": "tsc -p tsconfig.json --noEmit",
33
+ "lint": "eslint .",
34
+ "test": "vitest run",
35
+ "format": "prettier --write .",
36
+ "format:check": "prettier --check .",
37
+ "prepack": "tsc -p tsconfig.build.json",
38
+ "prepare": "tsc -p tsconfig.build.json"
39
+ },
40
+ "devDependencies": {
41
+ "@eslint/js": "^9.30.0",
42
+ "@types/node": "^22.15.0",
43
+ "eslint": "^9.30.0",
44
+ "eslint-config-prettier": "^10.1.0",
45
+ "prettier": "^3.6.0",
46
+ "typescript": "^5.8.0",
47
+ "typescript-eslint": "^8.35.0",
48
+ "vitest": "^3.2.0"
49
+ }
50
+ }
package/src/auth.ts ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The browserless instance-OTP sign-in client (hub-architecture §4c):
3
+ *
4
+ * POST /api/v1/cli/auth/request — email a 6-digit sign-in code
5
+ * POST /api/v1/cli/auth/complete — verify the code, mint an API key
6
+ * (the full key appears exactly once)
7
+ * DELETE /api/v1/cli/auth/key — self-revoke the PRESENTING key (logout)
8
+ *
9
+ * The wire contract is the platform template's — the hub and every
10
+ * Antasphere tool instance speak it, so one client serves the whole family.
11
+ * Self-hosted instances authenticate against themselves with this same flow.
12
+ */
13
+
14
+ export class CliAuthError extends Error {
15
+ constructor(
16
+ public readonly status: number,
17
+ public readonly code: string,
18
+ message: string,
19
+ public readonly details?: unknown
20
+ ) {
21
+ super(message);
22
+ this.name = 'CliAuthError';
23
+ }
24
+ }
25
+
26
+ export interface CliAuthRequestBody {
27
+ email: string;
28
+ }
29
+
30
+ /** Always `sent: true` on 2xx — deliberately silent about account existence. */
31
+ export interface CliAuthRequested {
32
+ sent: true;
33
+ }
34
+
35
+ export interface CliAuthCompleteBody {
36
+ email: string;
37
+ otp: string;
38
+ /** Display name for the minted key (server defaults to a CLI-login label). */
39
+ keyName?: string;
40
+ /** TTL in days at mint. Omit = never expires. */
41
+ expiresInDays?: number;
42
+ /** Hub only: the org the minted key binds to (default: oldest membership). */
43
+ workspaceId?: string;
44
+ }
45
+
46
+ /** The minted key's metadata row (template api-key wire shape). */
47
+ export interface CliAuthMintedKey {
48
+ id: string;
49
+ name: string;
50
+ keyId: string;
51
+ scopes: string[];
52
+ createdBy: string;
53
+ createdAt: string;
54
+ lastUsedAt: string | null;
55
+ revokedAt: string | null;
56
+ expiresAt: string | null;
57
+ }
58
+
59
+ export interface CliAuthCompleted {
60
+ /** Full key `<prefix>_<keyid>_<secret>` — shown once, never retrievable. */
61
+ key: string;
62
+ apiKey: CliAuthMintedKey;
63
+ user: { id: string; email: string; name: string };
64
+ workspaceId: string;
65
+ }
66
+
67
+ export interface CliAuthRevoked {
68
+ revoked: true;
69
+ id: string;
70
+ }
71
+
72
+ export interface CliAuthClientOptions {
73
+ /** Instance origin, e.g. https://account.antasphere.com */
74
+ baseUrl: string;
75
+ fetch?: typeof globalThis.fetch;
76
+ }
77
+
78
+ export class CliAuthClient {
79
+ private readonly baseUrl: string;
80
+ private readonly fetchImpl: typeof globalThis.fetch;
81
+
82
+ constructor(options: CliAuthClientOptions) {
83
+ this.baseUrl = options.baseUrl.replace(/\/+$/, '');
84
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
85
+ }
86
+
87
+ /** Public: request a sign-in code by email. Generic success — no enumeration. */
88
+ request(body: CliAuthRequestBody): Promise<CliAuthRequested> {
89
+ return this.call('POST', '/cli/auth/request', body);
90
+ }
91
+
92
+ /** Public: verify the code and mint an API key (returned once, like every mint). */
93
+ complete(body: CliAuthCompleteBody): Promise<CliAuthCompleted> {
94
+ return this.call('POST', '/cli/auth/complete', body);
95
+ }
96
+
97
+ /** CLI logout: revoke the PRESENTING API key (self-revocation). */
98
+ revoke(apiKey: string): Promise<CliAuthRevoked> {
99
+ return this.call('DELETE', '/cli/auth/key', undefined, apiKey);
100
+ }
101
+
102
+ /** Mirrors the platform SDK's parse: `{ error: { code, message, details } }` envelopes. */
103
+ private async call<T>(method: string, path: string, body?: unknown, apiKey?: string): Promise<T> {
104
+ const headers: Record<string, string> = {};
105
+ if (apiKey) headers['authorization'] = `Bearer ${apiKey}`;
106
+ if (body !== undefined) headers['content-type'] = 'application/json';
107
+ const res = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
108
+ method,
109
+ headers,
110
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {})
111
+ });
112
+ if (res.status === 204) return undefined as T;
113
+ const json = (await res.json().catch(() => null)) as
114
+ { error?: { code?: string; message?: string; details?: unknown } } | T | null;
115
+ if (!res.ok) {
116
+ const errBody = (json ?? {}) as { error?: { code?: string; message?: string; details?: unknown } };
117
+ throw new CliAuthError(
118
+ res.status,
119
+ errBody.error?.code ?? 'unknown_error',
120
+ errBody.error?.message ?? `Request failed with ${res.status}`,
121
+ errBody.error?.details
122
+ );
123
+ }
124
+ return json as T;
125
+ }
126
+ }
package/src/config.ts ADDED
@@ -0,0 +1,125 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+
4
+ /**
5
+ * The shared Antasphere CLI config home: `$XDG_CONFIG_HOME/antasphere/`
6
+ * (default `~/.config/antasphere/`) — ONE home for the whole tool family
7
+ * (hub-architecture §8: per-tool CLIs share one core owning the config home).
8
+ *
9
+ * Layout — one file per tool namespace, so tools never collide and a new
10
+ * tool is a new file, never a schema change:
11
+ *
12
+ * antasphere/ 0700
13
+ * ├── config.json 0600 the `hub` tool (the `antasphere` account
14
+ * │ CLI — its pre-extraction location, kept)
15
+ * └── tools/ 0700
16
+ * └── <tool>.json 0600 every other tool's profiles
17
+ * (e.g. tools/slideless.json)
18
+ *
19
+ * Each file holds one tool's `{ activeProfile?, profiles }`: multiple named
20
+ * profiles per tool, one active profile per tool. Hub profiles additionally
21
+ * carry the active org (`workspaceId`) their credential is bound to.
22
+ *
23
+ * Files store API keys, so directories are created 0700 and files kept 0600
24
+ * on every write. All I/O is synchronous and env-injected (no process.env
25
+ * reads) so tests can point the whole config world at a temp dir via
26
+ * XDG_CONFIG_HOME.
27
+ */
28
+
29
+ export type CliEnv = Record<string, string | undefined>;
30
+
31
+ export interface CliProfile {
32
+ /** `<prefix>_...` API key for this profile. */
33
+ apiKey?: string;
34
+ /** Instance origin; absent = the tool's default instance, when it has one. */
35
+ baseUrl?: string;
36
+ /** The signed-in account's email (informational, set by login). */
37
+ email?: string;
38
+ /** The org/workspace the key is bound to (one workspace per credential). */
39
+ workspaceId?: string;
40
+ }
41
+
42
+ export interface CliConfig {
43
+ activeProfile?: string;
44
+ profiles: Record<string, CliProfile>;
45
+ }
46
+
47
+ /** The hub/account tool — its file is the config home's root `config.json`. */
48
+ export const HUB_TOOL = 'hub';
49
+
50
+ const TOOL_RE = /^[a-z][a-z0-9-]*$/;
51
+
52
+ /** Tool namespaces are lowercase slugs — they become file names. */
53
+ export function assertToolNamespace(tool: string): void {
54
+ if (!TOOL_RE.test(tool)) {
55
+ throw new Error(`Invalid tool namespace "${tool}" — lowercase slugs only ([a-z][a-z0-9-]*).`);
56
+ }
57
+ }
58
+
59
+ /** Where a tool's config lives for this environment; null when no home is known. */
60
+ export function configPath(env: CliEnv, tool: string): string | null {
61
+ assertToolNamespace(tool);
62
+ const base = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, '.config') : null);
63
+ if (!base) return null;
64
+ const home = join(base, 'antasphere');
65
+ return tool === HUB_TOOL ? join(home, 'config.json') : join(home, 'tools', `${tool}.json`);
66
+ }
67
+
68
+ const EMPTY: CliConfig = { profiles: {} };
69
+
70
+ /** Tolerant parse (shared with the migrator): corrupt or foreign shapes → empty. */
71
+ export function parseConfig(raw: string): CliConfig {
72
+ try {
73
+ const parsed = JSON.parse(raw) as Partial<CliConfig>;
74
+ const profiles = parsed.profiles && typeof parsed.profiles === 'object' ? parsed.profiles : {};
75
+ return {
76
+ ...(typeof parsed.activeProfile === 'string' ? { activeProfile: parsed.activeProfile } : {}),
77
+ profiles
78
+ };
79
+ } catch {
80
+ return { ...EMPTY, profiles: {} };
81
+ }
82
+ }
83
+
84
+ /** Load a tool's config; a missing/unreadable/corrupt file is an empty config. */
85
+ export function loadConfig(env: CliEnv, tool: string): CliConfig {
86
+ const path = configPath(env, tool);
87
+ if (!path || !existsSync(path)) return { ...EMPTY, profiles: {} };
88
+ try {
89
+ return parseConfig(readFileSync(path, 'utf8'));
90
+ } catch {
91
+ return { ...EMPTY, profiles: {} };
92
+ }
93
+ }
94
+
95
+ /** Persist a tool's config (0700 dirs / 0600 file). Throws when no home is known. */
96
+ export function saveConfig(env: CliEnv, tool: string, config: CliConfig): string {
97
+ const path = configPath(env, tool);
98
+ if (!path) {
99
+ throw new Error(
100
+ 'Cannot locate a config directory — set HOME or XDG_CONFIG_HOME, or pass --api-key/--api-url explicitly.'
101
+ );
102
+ }
103
+ const dir = dirname(path);
104
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
105
+ // mkdir's mode only applies on creation — re-assert on every write, on
106
+ // every directory level we own (tools/ AND the antasphere home itself).
107
+ chmodSync(dir, 0o700);
108
+ const home = dirname(configPath(env, HUB_TOOL) as string);
109
+ if (dir !== home) chmodSync(home, 0o700);
110
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
111
+ chmodSync(path, 0o600);
112
+ return path;
113
+ }
114
+
115
+ /** Delete a tool's config file (config clear). No-op when absent. */
116
+ export function clearConfig(env: CliEnv, tool: string): void {
117
+ const path = configPath(env, tool);
118
+ if (path && existsSync(path)) rmSync(path);
119
+ }
120
+
121
+ /** `ant_abcd1234_…` → `ant_abcd1234_…c3f9` — safe for terminals and logs. */
122
+ export function redactKey(key: string): string {
123
+ if (key.length <= 16) return '****';
124
+ return `${key.slice(0, 13)}…${key.slice(-4)}`;
125
+ }
package/src/index.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @antasphere/cli-core — the shared foundation every Antasphere tool CLI
3
+ * builds on (hub-architecture §8): the `~/.config/antasphere/` config home
4
+ * with tool-namespaced profiles, the flag → env → profile → default URL
5
+ * resolution order, the instance email-OTP auth client, and the CliIo
6
+ * prompt seam. Tool commands, wire types, and API surfaces live in the
7
+ * tools; this package carries only config/login plumbing, never secrets.
8
+ */
9
+
10
+ export {
11
+ assertToolNamespace,
12
+ clearConfig,
13
+ configPath,
14
+ HUB_TOOL,
15
+ loadConfig,
16
+ parseConfig,
17
+ redactKey,
18
+ saveConfig
19
+ } from './config.js';
20
+ export type { CliConfig, CliEnv, CliProfile } from './config.js';
21
+
22
+ export { ask, printJson } from './io.js';
23
+ export type { CliIo } from './io.js';
24
+
25
+ export { CliUsageError, DEFAULT_PROFILE, resolveApiKey, resolveBaseUrl, resolveProfile } from './resolve.js';
26
+ export type { ResolveApiKeyOptions, ResolveBaseUrlOptions, ResolvedProfile } from './resolve.js';
27
+
28
+ export { CliAuthClient, CliAuthError } from './auth.js';
29
+ export type {
30
+ CliAuthClientOptions,
31
+ CliAuthCompleteBody,
32
+ CliAuthCompleted,
33
+ CliAuthMintedKey,
34
+ CliAuthRequestBody,
35
+ CliAuthRequested,
36
+ CliAuthRevoked
37
+ } from './auth.js';
38
+
39
+ export { migrateLegacyConfig } from './migrate.js';
40
+ export type { LegacyMigrationSpec, MigrationResult } from './migrate.js';
package/src/io.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { CliEnv } from './config.js';
2
+
3
+ /**
4
+ * Injectable I/O so a tool CLI is testable in-process: environment, output
5
+ * streams, fetch, and the interactive prompt seam. Bins wire real process
6
+ * streams + readline; tests wire recorders and scripted prompts.
7
+ */
8
+ export interface CliIo {
9
+ env: CliEnv;
10
+ out: { write(s: string): void };
11
+ err: { write(s: string): void };
12
+ fetch?: typeof globalThis.fetch;
13
+ /** Interactive line prompt (login email/code). The bin wires readline. */
14
+ prompt?: (question: string) => Promise<string>;
15
+ }
16
+
17
+ /** Interactive prompt; refuses cleanly when the runner has no prompt wired. */
18
+ export async function ask(io: CliIo, question: string): Promise<string> {
19
+ if (!io.prompt) {
20
+ throw new Error('This command is interactive — no prompt available (pass the value as a flag).');
21
+ }
22
+ const answer = (await io.prompt(question)).trim();
23
+ if (!answer) throw new Error('Aborted (empty input).');
24
+ return answer;
25
+ }
26
+
27
+ export function printJson(io: CliIo, value: unknown): void {
28
+ io.out.write(`${JSON.stringify(value, null, 2)}\n`);
29
+ }
package/src/migrate.ts ADDED
@@ -0,0 +1,61 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import {
4
+ assertToolNamespace,
5
+ configPath,
6
+ loadConfig,
7
+ parseConfig,
8
+ saveConfig,
9
+ type CliEnv
10
+ } from './config.js';
11
+
12
+ /**
13
+ * One-shot, non-destructive import of a tool's pre-cli-core config file
14
+ * (`$XDG_CONFIG_HOME/<legacyDir>/config.json`) into the shared antasphere
15
+ * home. The legacy file is left in place — older CLI versions keep working;
16
+ * it simply stops being read by cli-core consumers.
17
+ */
18
+
19
+ export interface LegacyMigrationSpec {
20
+ /** Target tool namespace in the shared home (e.g. 'slideless'). */
21
+ tool: string;
22
+ /** Legacy app dir under the config base (e.g. 'slideless'). */
23
+ legacyDir: string;
24
+ }
25
+
26
+ export interface MigrationResult {
27
+ migrated: boolean;
28
+ /** The legacy file imported from (set when migrated). */
29
+ from?: string;
30
+ /** The shared-home file written (set when migrated). */
31
+ to?: string;
32
+ }
33
+
34
+ /**
35
+ * Imports iff (a) the tool has NO profiles in the shared home yet, and
36
+ * (b) the legacy file exists and holds at least one profile. Anything else —
37
+ * no home, no legacy file, empty/corrupt legacy content, or a shared-home
38
+ * config already carrying profiles — is a no-op.
39
+ */
40
+ export function migrateLegacyConfig(env: CliEnv, spec: LegacyMigrationSpec): MigrationResult {
41
+ assertToolNamespace(spec.tool);
42
+ assertToolNamespace(spec.legacyDir);
43
+ const to = configPath(env, spec.tool);
44
+ if (!to) return { migrated: false };
45
+ const current = loadConfig(env, spec.tool);
46
+ if (Object.keys(current.profiles).length > 0) return { migrated: false };
47
+ const base = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, '.config') : null);
48
+ if (!base) return { migrated: false };
49
+ const from = join(base, spec.legacyDir, 'config.json');
50
+ if (!existsSync(from)) return { migrated: false };
51
+ let raw: string;
52
+ try {
53
+ raw = readFileSync(from, 'utf8');
54
+ } catch {
55
+ return { migrated: false };
56
+ }
57
+ const legacy = parseConfig(raw);
58
+ if (Object.keys(legacy.profiles).length === 0) return { migrated: false };
59
+ saveConfig(env, spec.tool, legacy);
60
+ return { migrated: true, from, to };
61
+ }
package/src/resolve.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { CliConfig, CliEnv, CliProfile } from './config.js';
2
+
3
+ /** A usage-level error: runners print `Error: <message>` and exit 1. */
4
+ export class CliUsageError extends Error {}
5
+
6
+ /** The profile name tools fall back to when none is named or active. */
7
+ export const DEFAULT_PROFILE = 'default';
8
+
9
+ export interface ResolvedProfile {
10
+ /** The resolved profile name (undefined = flags/env only, nothing stored). */
11
+ name: string | undefined;
12
+ profile: CliProfile | undefined;
13
+ }
14
+
15
+ /**
16
+ * The named (or active) profile of a tool's config, erroring on an
17
+ * explicitly named missing one. `unknownHint` lets the tool append its own
18
+ * remedy (e.g. 'run `slideless profiles` to list them.').
19
+ */
20
+ export function resolveProfile(
21
+ config: CliConfig,
22
+ requested: string | undefined,
23
+ opts: { unknownHint?: string } = {}
24
+ ): ResolvedProfile {
25
+ if (requested) {
26
+ const profile = config.profiles[requested];
27
+ if (!profile) {
28
+ throw new CliUsageError(
29
+ `Unknown profile "${requested}"${opts.unknownHint ? ` — ${opts.unknownHint}` : ''}`
30
+ );
31
+ }
32
+ return { name: requested, profile };
33
+ }
34
+ const name = config.activeProfile;
35
+ const profile = name ? config.profiles[name] : undefined;
36
+ return { name: profile ? name : undefined, profile };
37
+ }
38
+
39
+ export interface ResolveBaseUrlOptions {
40
+ /** Value of --api-url (or an alias) when given. */
41
+ flag?: string | undefined;
42
+ env: CliEnv;
43
+ /** The tool's URL env var, e.g. 'ANTASPHERE_URL' / 'SLIDELESS_URL'. */
44
+ envVar: string;
45
+ profile?: CliProfile | undefined;
46
+ /** Optional tool default (the hub has one; self-hosted tools error instead). */
47
+ defaultUrl?: string;
48
+ /** Error text when nothing resolves and there is no default. */
49
+ missingMessage?: string;
50
+ }
51
+
52
+ /**
53
+ * Base-URL resolution in the ecosystem-wide order:
54
+ * flag → tool env var → profile → optional default → CliUsageError.
55
+ * The result is origin-normalized (trailing slashes stripped).
56
+ */
57
+ export function resolveBaseUrl(opts: ResolveBaseUrlOptions): string {
58
+ const raw = opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.baseUrl ?? opts.defaultUrl;
59
+ if (!raw) {
60
+ throw new CliUsageError(
61
+ opts.missingMessage ?? `No instance configured — pass --api-url <url> or set ${opts.envVar}.`
62
+ );
63
+ }
64
+ return raw.replace(/\/+$/, '');
65
+ }
66
+
67
+ export interface ResolveApiKeyOptions {
68
+ /** Value of --api-key when given. */
69
+ flag?: string | undefined;
70
+ env: CliEnv;
71
+ /** The tool's key env var, e.g. 'ANTASPHERE_API_KEY' / 'SLIDELESS_API_KEY'. */
72
+ envVar: string;
73
+ profile?: CliProfile | undefined;
74
+ }
75
+
76
+ /** API-key resolution: flag → tool env var → profile (undefined = public only). */
77
+ export function resolveApiKey(opts: ResolveApiKeyOptions): string | undefined {
78
+ return opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.apiKey;
79
+ }