@clifn/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/README.md +383 -0
- package/dist/client.d.ts +46 -0
- package/dist/client.js +198 -0
- package/dist/config-loader.d.ts +18 -0
- package/dist/config-loader.js +125 -0
- package/dist/config.d.ts +13 -0
- package/dist/config.js +57 -0
- package/dist/credentials.d.ts +19 -0
- package/dist/credentials.js +79 -0
- package/dist/diagnostics.d.ts +19 -0
- package/dist/diagnostics.js +152 -0
- package/dist/env.d.ts +20 -0
- package/dist/env.js +74 -0
- package/dist/exec.d.ts +29 -0
- package/dist/exec.js +143 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +13 -0
- package/dist/output.d.ts +37 -0
- package/dist/output.js +217 -0
- package/dist/prompt.d.ts +18 -0
- package/dist/prompt.js +83 -0
- package/dist/runner.d.ts +36 -0
- package/dist/runner.js +94 -0
- package/dist/scaffold.d.ts +26 -0
- package/dist/scaffold.js +94 -0
- package/dist/stdio.d.ts +7 -0
- package/dist/stdio.js +33 -0
- package/dist/ui.d.ts +10 -0
- package/dist/ui.js +25 -0
- package/package.json +120 -0
package/README.md
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
# clifn
|
|
2
|
+
|
|
3
|
+
Reusable CLI primitives for Superfunctions packages and downstream CLIs.
|
|
4
|
+
|
|
5
|
+
`clifn` remains a single package at `clifn/core`, published as `@clifn/core`. It is the shared parser-agnostic CLI toolkit for generic concerns that repeat across Superfunctions CLIs, while each owning CLI keeps its product-specific command graph and behavior.
|
|
6
|
+
|
|
7
|
+
Current public subpaths:
|
|
8
|
+
|
|
9
|
+
- `@clifn/core/credentials`
|
|
10
|
+
- `@clifn/core/config`
|
|
11
|
+
- `@clifn/core/client`
|
|
12
|
+
- `@clifn/core/ui`
|
|
13
|
+
- `@clifn/core/stdio`
|
|
14
|
+
- `@clifn/core/prompt`
|
|
15
|
+
|
|
16
|
+
New additive subpaths are exported for the generic CLI-builder surface:
|
|
17
|
+
|
|
18
|
+
- `@clifn/core/output`
|
|
19
|
+
- `@clifn/core/runner`
|
|
20
|
+
- `@clifn/core/config-loader`
|
|
21
|
+
- `@clifn/core/env`
|
|
22
|
+
- `@clifn/core/diagnostics`
|
|
23
|
+
- `@clifn/core/exec`
|
|
24
|
+
- `@clifn/core/scaffold`
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install @clifn/core
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Conduct CLI-style usage
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
import { createCredentialStore } from "@clifn/core/credentials";
|
|
36
|
+
import { createProjectConfig } from "@clifn/core/config";
|
|
37
|
+
import { createApiClient } from "@clifn/core/client";
|
|
38
|
+
import { readJsonStdin, writeJsonStdout } from "@clifn/core/stdio";
|
|
39
|
+
import { ui } from "@clifn/core/ui";
|
|
40
|
+
|
|
41
|
+
const credentials = createCredentialStore();
|
|
42
|
+
const config = createProjectConfig();
|
|
43
|
+
const profile = String(config.get("profile") ?? "default");
|
|
44
|
+
|
|
45
|
+
const api = createApiClient({
|
|
46
|
+
credentials,
|
|
47
|
+
profile,
|
|
48
|
+
projectId: String(config.get("projectId") ?? ""),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const input = await readJsonStdin<{ command: string }>();
|
|
52
|
+
ui.info(`running command: ${input.command}`);
|
|
53
|
+
const result = await api.post("/runs", input);
|
|
54
|
+
writeJsonStdout(result.data);
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Generic CLI usage
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { prompt } from "@clifn/core/prompt";
|
|
61
|
+
import { ui } from "@clifn/core/ui";
|
|
62
|
+
|
|
63
|
+
const target = await prompt.select("Target environment", [
|
|
64
|
+
"local",
|
|
65
|
+
"staging",
|
|
66
|
+
"production",
|
|
67
|
+
]);
|
|
68
|
+
const confirmed = await prompt.confirm(`Deploy to ${target}?`);
|
|
69
|
+
|
|
70
|
+
if (!confirmed) {
|
|
71
|
+
ui.warn("deployment cancelled");
|
|
72
|
+
} else {
|
|
73
|
+
ui.success(`deployment started for ${target}`);
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Shared CLI-builder quick start
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { runAction } from "@clifn/core/runner";
|
|
81
|
+
|
|
82
|
+
const exitCode = await runAction(
|
|
83
|
+
async ({ name }, ctx) => {
|
|
84
|
+
ctx.output.info(`hello ${name}`);
|
|
85
|
+
},
|
|
86
|
+
{ name: "world" },
|
|
87
|
+
{
|
|
88
|
+
verbose: false,
|
|
89
|
+
}
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
process.exitCode = exitCode;
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Parser compatibility patterns
|
|
96
|
+
|
|
97
|
+
`clifn` stays parser-agnostic. The owning CLI keeps parser choice and parser dependencies, while `clifn` supplies the reusable execution and output primitives underneath.
|
|
98
|
+
|
|
99
|
+
The current repository already uses all three parser styles:
|
|
100
|
+
|
|
101
|
+
- `contentfn/cli` and `hostfn/cli` use `commander`
|
|
102
|
+
- `apifn/cli` and `docsfn/cli` use `cac`
|
|
103
|
+
- `datafn/cli` uses raw `node:util.parseArgs`
|
|
104
|
+
|
|
105
|
+
The parser canaries under `clifn/core/tests/fixtures/*` prove that `runAction()` and the shared output service work in each style without adding parser libraries to `clifn` runtime dependencies.
|
|
106
|
+
|
|
107
|
+
### `commander`
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { Command } from "commander";
|
|
111
|
+
import { runAction } from "@clifn/core/runner";
|
|
112
|
+
|
|
113
|
+
const program = new Command();
|
|
114
|
+
|
|
115
|
+
program.option("--json", "Emit machine-readable output");
|
|
116
|
+
program
|
|
117
|
+
.command("greet")
|
|
118
|
+
.option("--name <name>", "Name to greet", "world")
|
|
119
|
+
.action(async (options, command) => {
|
|
120
|
+
const globals = command.parent?.opts() ?? {};
|
|
121
|
+
|
|
122
|
+
return runAction(
|
|
123
|
+
async ({ name }, ctx) => {
|
|
124
|
+
ctx.output.info(`hello ${name}`);
|
|
125
|
+
},
|
|
126
|
+
{ name: options.name },
|
|
127
|
+
{
|
|
128
|
+
mode: globals.json ? "json" : "text",
|
|
129
|
+
}
|
|
130
|
+
);
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### `cac`
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
import { cac } from "cac";
|
|
138
|
+
import { runAction } from "@clifn/core/runner";
|
|
139
|
+
|
|
140
|
+
const cli = cac("demo");
|
|
141
|
+
|
|
142
|
+
cli.option("--json", "Emit machine-readable output");
|
|
143
|
+
cli
|
|
144
|
+
.command("greet")
|
|
145
|
+
.option("--name <name>", "Name to greet")
|
|
146
|
+
.action((options) =>
|
|
147
|
+
runAction(
|
|
148
|
+
async ({ name }, ctx) => {
|
|
149
|
+
return {
|
|
150
|
+
data: {
|
|
151
|
+
ok: true,
|
|
152
|
+
name,
|
|
153
|
+
},
|
|
154
|
+
};
|
|
155
|
+
},
|
|
156
|
+
{ name: options.name ?? "world" },
|
|
157
|
+
{
|
|
158
|
+
mode: options.json ? "json" : "text",
|
|
159
|
+
}
|
|
160
|
+
)
|
|
161
|
+
);
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
### `node:util.parseArgs`
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import { parseArgs } from "node:util";
|
|
168
|
+
import { runAction } from "@clifn/core/runner";
|
|
169
|
+
|
|
170
|
+
const { values, positionals } = parseArgs({
|
|
171
|
+
allowPositionals: true,
|
|
172
|
+
options: {
|
|
173
|
+
name: { type: "string" },
|
|
174
|
+
json: { type: "boolean" },
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
if (positionals[0] === "greet") {
|
|
179
|
+
await runAction(
|
|
180
|
+
async ({ name }, ctx) => {
|
|
181
|
+
ctx.output.info(`hello ${name}`);
|
|
182
|
+
},
|
|
183
|
+
{ name: values.name ?? "world" },
|
|
184
|
+
{
|
|
185
|
+
mode: values.json ? "json" : "text",
|
|
186
|
+
}
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Consumer ownership stays explicit:
|
|
192
|
+
|
|
193
|
+
- `clifn` owns the parser-agnostic runner/output/diagnostics/config/env/exec/scaffold helpers
|
|
194
|
+
- the consuming CLI owns command registration, parser wiring, and parser package installation
|
|
195
|
+
- parser libraries such as `commander` and `cac` remain consumer dependencies or test-only canary dependencies, not `clifn` runtime dependencies
|
|
196
|
+
|
|
197
|
+
## API Overview
|
|
198
|
+
|
|
199
|
+
### Compatibility promise
|
|
200
|
+
|
|
201
|
+
- Existing imports for `@clifn/core/credentials`, `@clifn/core/config`, `@clifn/core/client`, `@clifn/core/ui`, `@clifn/core/stdio`, and `@clifn/core/prompt` remain valid.
|
|
202
|
+
- The new subpaths are additive and do not replace any existing import path.
|
|
203
|
+
- `@clifn/core/ui` remains the compatibility-facing terminal helper path even as newer shared output primitives land in `@clifn/core/output`.
|
|
204
|
+
|
|
205
|
+
### `@clifn/core/credentials`
|
|
206
|
+
|
|
207
|
+
- `createCredentialStore(path?)` -> INI profile store.
|
|
208
|
+
- `MissingProfileError` -> typed error when profile is not found.
|
|
209
|
+
|
|
210
|
+
### `@clifn/core/config`
|
|
211
|
+
|
|
212
|
+
- `createProjectConfig(path?)` -> JSON project config store.
|
|
213
|
+
- `InvalidConfigError` -> typed error for invalid JSON/object shapes.
|
|
214
|
+
|
|
215
|
+
### `@clifn/core/client`
|
|
216
|
+
|
|
217
|
+
- `createApiClient(config)` -> authenticated HTTP client with retries.
|
|
218
|
+
- `HttpFailureError` -> typed error for non-2xx responses.
|
|
219
|
+
- `HttpRequestError` -> typed error for network/transport failures.
|
|
220
|
+
|
|
221
|
+
### `@clifn/core/ui`
|
|
222
|
+
|
|
223
|
+
- `ui.success`, `ui.error`, `ui.warn`, `ui.info`
|
|
224
|
+
- `ui.spinner(message)` -> start/stop/succeed/fail
|
|
225
|
+
- `ui.table(rows)` -> deterministic table output
|
|
226
|
+
|
|
227
|
+
### `@clifn/core/stdio`
|
|
228
|
+
|
|
229
|
+
- `readJsonStdin<T>()` -> parse one JSON document from stdin.
|
|
230
|
+
- `writeJsonStdout(value)` -> serialize one JSON document + trailing newline.
|
|
231
|
+
- `InvalidJsonStdinError` -> typed deterministic parse failure.
|
|
232
|
+
|
|
233
|
+
### `@clifn/core/prompt`
|
|
234
|
+
|
|
235
|
+
- `prompt.select`
|
|
236
|
+
- `prompt.multiSelect`
|
|
237
|
+
- `prompt.text`
|
|
238
|
+
- `prompt.confirm`
|
|
239
|
+
|
|
240
|
+
### New shared CLI-builder modules
|
|
241
|
+
|
|
242
|
+
These module entrypoints are the generic surface that repository CLIs can share:
|
|
243
|
+
|
|
244
|
+
- `@clifn/core/output`
|
|
245
|
+
- generic text/JSON output service contract
|
|
246
|
+
- quiet/verbose behavior
|
|
247
|
+
- deterministic table rendering
|
|
248
|
+
- spinner surface
|
|
249
|
+
- `@clifn/core/runner`
|
|
250
|
+
- parser-agnostic action runner contract
|
|
251
|
+
- normalized action context with output, diagnostics, exec, scaffold, cwd, env, and non-interactive state
|
|
252
|
+
- `@clifn/core/config-loader`
|
|
253
|
+
- shared config discovery and typed loading contract for TS/JS/MJS/CJS/JSON configs
|
|
254
|
+
- uses the same Jiti-informed `.ts` loading path already established in `packages/cli` and `apifn/cli`
|
|
255
|
+
- `@clifn/core/env`
|
|
256
|
+
- generic environment readers for strings, integers, and booleans
|
|
257
|
+
- explicit missing, invalid, and out-of-range error codes for shared CLI callers
|
|
258
|
+
- `@clifn/core/diagnostics`
|
|
259
|
+
- shared diagnostic model plus deterministic sort/redaction/formatting surface
|
|
260
|
+
- `@clifn/core/exec`
|
|
261
|
+
- subprocess execution contract for buffered capture, streaming, and timeout reporting
|
|
262
|
+
- `@clifn/core/scaffold`
|
|
263
|
+
- deterministic file and directory scaffolding contract with explicit overwrite policy
|
|
264
|
+
|
|
265
|
+
## Adoption boundary
|
|
266
|
+
|
|
267
|
+
`clifn` is the shared home for generic CLI-builder concerns that appear across existing repository CLIs such as:
|
|
268
|
+
|
|
269
|
+
- `packages/cli` and `apifn/cli` for config loading patterns
|
|
270
|
+
- `hostfn/cli`, `recfn/cli`, and `apifn/cli` for output and command-runner patterns
|
|
271
|
+
- `docsfn/cli` and `plugfn/cli` for structured diagnostics and test/reporting surfaces
|
|
272
|
+
|
|
273
|
+
Responsibilities that belong in `clifn`:
|
|
274
|
+
|
|
275
|
+
- generic action execution
|
|
276
|
+
- generic output formatting and machine-readable output
|
|
277
|
+
- config discovery/loading contracts
|
|
278
|
+
- generic env readers
|
|
279
|
+
- generic diagnostics formatting
|
|
280
|
+
- generic subprocess helpers
|
|
281
|
+
- generic scaffolding helpers
|
|
282
|
+
|
|
283
|
+
Responsibilities that stay in the owning CLI:
|
|
284
|
+
|
|
285
|
+
- product-specific command graphs
|
|
286
|
+
- business/domain validation
|
|
287
|
+
- domain-specific scan rules
|
|
288
|
+
- deployment or packaging rules tied to one product
|
|
289
|
+
- browser-extension orchestration and manifest-aware behavior
|
|
290
|
+
|
|
291
|
+
## Representative adoption notes
|
|
292
|
+
|
|
293
|
+
### `packages/cli`
|
|
294
|
+
|
|
295
|
+
- Repeated pattern today:
|
|
296
|
+
- config discovery and loading in `packages/cli/src/utils/load-library-config.ts`
|
|
297
|
+
- config-path fallback logic in `packages/cli/src/utils/config.ts`
|
|
298
|
+
- `clifn` adoption target:
|
|
299
|
+
- `@clifn/core/config-loader` for deterministic TS/JS/MJS/CJS/JSON loading
|
|
300
|
+
- Product-owned concerns that stay local:
|
|
301
|
+
- schema and library semantics specific to `@superfunctions/cli`
|
|
302
|
+
|
|
303
|
+
### `apifn/cli`
|
|
304
|
+
|
|
305
|
+
- Repeated pattern today:
|
|
306
|
+
- `cac` command registration in `apifn/cli/src/index.ts`
|
|
307
|
+
- config loading in `apifn/cli/src/config.ts`
|
|
308
|
+
- output helpers in `apifn/cli/src/utils/output.ts`
|
|
309
|
+
- `clifn` adoption target:
|
|
310
|
+
- keep `cac`, but move generic concerns onto `@clifn/core/runner`, `@clifn/core/output`, and `@clifn/core/config-loader`
|
|
311
|
+
- Product-owned concerns that stay local:
|
|
312
|
+
- OpenAPI generation, diff semantics, mock/serve behavior, and collection rules
|
|
313
|
+
|
|
314
|
+
### `hostfn/cli`
|
|
315
|
+
|
|
316
|
+
- Repeated pattern today:
|
|
317
|
+
- `commander` command registration and repeated async `try/catch` wrappers in `hostfn/cli/src/index.ts`
|
|
318
|
+
- logger formatting in `hostfn/cli/src/utils/logger.ts`
|
|
319
|
+
- `clifn` adoption target:
|
|
320
|
+
- keep `commander`, but move shared action execution and output concerns onto `@clifn/core/runner`, `@clifn/core/output`, and `@clifn/core/exec`
|
|
321
|
+
- Product-owned concerns that stay local:
|
|
322
|
+
- deployment workflows, SSH/server orchestration, runtime adapters, and host-specific validation
|
|
323
|
+
|
|
324
|
+
### `recfn/cli`
|
|
325
|
+
|
|
326
|
+
- Repeated pattern today:
|
|
327
|
+
- text/json rendering and table-like formatting in `recfn/cli/src/output.ts`
|
|
328
|
+
- `clifn` adoption target:
|
|
329
|
+
- `@clifn/core/output` for generic mode switching and transport
|
|
330
|
+
- keep domain-specific formatters local where they encode recording/bot semantics
|
|
331
|
+
- Product-owned concerns that stay local:
|
|
332
|
+
- recording analytics formatting, transcript search semantics, and recorder-specific data shapes
|
|
333
|
+
|
|
334
|
+
### extfn adoption contract
|
|
335
|
+
|
|
336
|
+
`extfn/cli` is an explicit future adopter of the generic `clifn` surface, but only for generic CLI concerns.
|
|
337
|
+
|
|
338
|
+
`extfn/cli` SHOULD use:
|
|
339
|
+
|
|
340
|
+
- `@clifn/core/runner` for normalized action execution and exit handling
|
|
341
|
+
- `@clifn/core/output` for text/json output, quiet/verbose behavior, and spinner usage
|
|
342
|
+
- `@clifn/core/diagnostics` for stable formatting and redaction of generic diagnostics
|
|
343
|
+
- `@clifn/core/config-loader` for extension config discovery and loading
|
|
344
|
+
- `@clifn/core/env` for generic env parsing
|
|
345
|
+
- `@clifn/core/exec` for subprocess orchestration during builds and packaging
|
|
346
|
+
- `@clifn/core/scaffold` for template-free deterministic file creation
|
|
347
|
+
|
|
348
|
+
`extfn/cli` MAY keep:
|
|
349
|
+
|
|
350
|
+
- its preferred parser (`commander`, `cac`, or raw `parseArgs`)
|
|
351
|
+
- product-specific formatter helpers that encode extension semantics
|
|
352
|
+
|
|
353
|
+
`extfn/cli` MUST stay extfn-owned for:
|
|
354
|
+
|
|
355
|
+
- Vite-based extension orchestration
|
|
356
|
+
- browser launching behavior
|
|
357
|
+
- extension packaging rules and archive layout
|
|
358
|
+
- manifest-aware scan rules
|
|
359
|
+
- plugin-specific contracts such as extension plugin wiring
|
|
360
|
+
- target-specific extension validation
|
|
361
|
+
|
|
362
|
+
If `extfn/cli` needs a generic capability that is not yet exported by `clifn`, that capability should be added to `clifn` first instead of being reimplemented as extfn-local CLI infrastructure.
|
|
363
|
+
|
|
364
|
+
## Notes
|
|
365
|
+
|
|
366
|
+
- Package path follows repo convention: `clifn/core` workspace, package name `@clifn/core`.
|
|
367
|
+
- `clifn` is designed for public imports only; no private/internal path imports are required.
|
|
368
|
+
- The generic modules prefer repository-shared mechanisms, including the existing `packages/cli` loader pattern, before introducing new runtime dependencies.
|
|
369
|
+
- `@clifn/core/config-loader` rejects remote config URLs and unsupported extensions with explicit error codes.
|
|
370
|
+
- `@clifn/core/env` uses explicit `CLIFN_ENV_*` error codes for missing, invalid, and out-of-range values.
|
|
371
|
+
|
|
372
|
+
## Conduct v0.3 compatibility note
|
|
373
|
+
|
|
374
|
+
`clifn` intentionally exposes stable subpath imports for Conduct and other CLIs:
|
|
375
|
+
|
|
376
|
+
- `@clifn/core/credentials`
|
|
377
|
+
- `@clifn/core/config`
|
|
378
|
+
- `@clifn/core/client`
|
|
379
|
+
- `@clifn/core/ui`
|
|
380
|
+
- `@clifn/core/stdio`
|
|
381
|
+
- `@clifn/core/prompt`
|
|
382
|
+
|
|
383
|
+
Use these public subpaths directly; do not import from internal `dist/*` paths.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type CredentialStore } from "./credentials.js";
|
|
2
|
+
export interface ApiRequestOptions {
|
|
3
|
+
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
4
|
+
path: string;
|
|
5
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
6
|
+
body?: unknown;
|
|
7
|
+
headers?: Record<string, string>;
|
|
8
|
+
}
|
|
9
|
+
export interface ApiResponse<T = unknown> {
|
|
10
|
+
status: number;
|
|
11
|
+
data: T | null;
|
|
12
|
+
headers: Headers;
|
|
13
|
+
}
|
|
14
|
+
export interface ApiClient {
|
|
15
|
+
request<T = unknown>(options: ApiRequestOptions): Promise<ApiResponse<T>>;
|
|
16
|
+
get<T = unknown>(path: string, query?: ApiRequestOptions["query"]): Promise<ApiResponse<T>>;
|
|
17
|
+
post<T = unknown>(path: string, body?: unknown): Promise<ApiResponse<T>>;
|
|
18
|
+
put<T = unknown>(path: string, body?: unknown): Promise<ApiResponse<T>>;
|
|
19
|
+
patch<T = unknown>(path: string, body?: unknown): Promise<ApiResponse<T>>;
|
|
20
|
+
delete<T = unknown>(path: string): Promise<ApiResponse<T>>;
|
|
21
|
+
}
|
|
22
|
+
export interface ApiClientConfig {
|
|
23
|
+
baseUrl?: string;
|
|
24
|
+
credentials?: CredentialStore;
|
|
25
|
+
profile?: string;
|
|
26
|
+
apiKey?: string;
|
|
27
|
+
projectId?: string;
|
|
28
|
+
retries?: number;
|
|
29
|
+
retryDelayMs?: number;
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
defaultHeaders?: Record<string, string>;
|
|
32
|
+
fetchImpl?: typeof fetch;
|
|
33
|
+
}
|
|
34
|
+
export declare class HttpFailureError extends Error {
|
|
35
|
+
readonly code = "CLIFN_HTTP_FAILURE";
|
|
36
|
+
readonly status: number;
|
|
37
|
+
readonly url: string;
|
|
38
|
+
readonly responseBody: unknown;
|
|
39
|
+
constructor(status: number, url: string, responseBody: unknown);
|
|
40
|
+
}
|
|
41
|
+
export declare class HttpRequestError extends Error {
|
|
42
|
+
readonly code = "CLIFN_HTTP_REQUEST_ERROR";
|
|
43
|
+
readonly url: string;
|
|
44
|
+
constructor(url: string, message: string, cause?: unknown);
|
|
45
|
+
}
|
|
46
|
+
export declare function createApiClient(config: ApiClientConfig): ApiClient;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { MissingProfileError } from "./credentials.js";
|
|
2
|
+
export class HttpFailureError extends Error {
|
|
3
|
+
code = "CLIFN_HTTP_FAILURE";
|
|
4
|
+
status;
|
|
5
|
+
url;
|
|
6
|
+
responseBody;
|
|
7
|
+
constructor(status, url, responseBody) {
|
|
8
|
+
super(`HTTP request failed (${status}) for ${url}`);
|
|
9
|
+
this.name = "HttpFailureError";
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.url = url;
|
|
12
|
+
this.responseBody = responseBody;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export class HttpRequestError extends Error {
|
|
16
|
+
code = "CLIFN_HTTP_REQUEST_ERROR";
|
|
17
|
+
url;
|
|
18
|
+
constructor(url, message, cause) {
|
|
19
|
+
super(`HTTP request error for ${url}: ${message}`);
|
|
20
|
+
this.name = "HttpRequestError";
|
|
21
|
+
this.url = url;
|
|
22
|
+
this.cause = cause;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function resolveAuth(config) {
|
|
26
|
+
if (config.baseUrl && config.apiKey) {
|
|
27
|
+
return { baseUrl: config.baseUrl, apiKey: config.apiKey };
|
|
28
|
+
}
|
|
29
|
+
if (!config.credentials) {
|
|
30
|
+
throw new HttpRequestError("unknown", "api client requires either {baseUrl, apiKey} or a credentials store");
|
|
31
|
+
}
|
|
32
|
+
const profileName = config.profile ?? "default";
|
|
33
|
+
const profile = config.credentials.getProfile(profileName);
|
|
34
|
+
return {
|
|
35
|
+
baseUrl: profile.backend,
|
|
36
|
+
apiKey: profile.key,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function buildUrl(baseUrl, path, query) {
|
|
40
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path) || path.startsWith("//")) {
|
|
41
|
+
throw new HttpRequestError(baseUrl, "request path must be relative");
|
|
42
|
+
}
|
|
43
|
+
const url = new URL(`${baseUrl.replace(/\/$/, "")}/${path.replace(/^\//, "")}`);
|
|
44
|
+
if (query) {
|
|
45
|
+
for (const [key, value] of Object.entries(query)) {
|
|
46
|
+
if (value === undefined) {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
url.searchParams.set(key, String(value));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return url.toString();
|
|
53
|
+
}
|
|
54
|
+
async function readResponseBody(response) {
|
|
55
|
+
const raw = await response.text();
|
|
56
|
+
if (raw.length === 0) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
60
|
+
if (contentType.includes("application/json")) {
|
|
61
|
+
try {
|
|
62
|
+
return JSON.parse(raw);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return raw;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return raw;
|
|
69
|
+
}
|
|
70
|
+
function shouldRetry(status) {
|
|
71
|
+
return status === 429 || status >= 500;
|
|
72
|
+
}
|
|
73
|
+
function sleep(ms) {
|
|
74
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
75
|
+
}
|
|
76
|
+
function isOneShotBody(value) {
|
|
77
|
+
return typeof ReadableStream !== "undefined" && value instanceof ReadableStream;
|
|
78
|
+
}
|
|
79
|
+
function isBodyInitLike(value) {
|
|
80
|
+
return (typeof value === "string" ||
|
|
81
|
+
value instanceof URLSearchParams ||
|
|
82
|
+
value instanceof ArrayBuffer ||
|
|
83
|
+
ArrayBuffer.isView(value) ||
|
|
84
|
+
(typeof FormData !== "undefined" && value instanceof FormData) ||
|
|
85
|
+
(typeof Blob !== "undefined" && value instanceof Blob) ||
|
|
86
|
+
(typeof ReadableStream !== "undefined" && value instanceof ReadableStream));
|
|
87
|
+
}
|
|
88
|
+
function serializeRequestBody(body) {
|
|
89
|
+
if (body === undefined) {
|
|
90
|
+
return { body: undefined };
|
|
91
|
+
}
|
|
92
|
+
if (isBodyInitLike(body)) {
|
|
93
|
+
return { body };
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
body: JSON.stringify(body),
|
|
97
|
+
defaultContentType: "application/json",
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
export function createApiClient(config) {
|
|
101
|
+
const auth = resolveAuth(config);
|
|
102
|
+
const fetchImpl = config.fetchImpl ?? globalThis.fetch;
|
|
103
|
+
const retries = config.retries ?? 1;
|
|
104
|
+
const retryDelayMs = config.retryDelayMs ?? 150;
|
|
105
|
+
const timeoutMs = config.timeoutMs ?? 8_000;
|
|
106
|
+
if (!fetchImpl) {
|
|
107
|
+
throw new HttpRequestError(auth.baseUrl, "global fetch is not available");
|
|
108
|
+
}
|
|
109
|
+
async function doRequest(options) {
|
|
110
|
+
const method = options.method ?? "GET";
|
|
111
|
+
let url;
|
|
112
|
+
try {
|
|
113
|
+
url = buildUrl(auth.baseUrl, options.path, options.query);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
if (error instanceof HttpRequestError) {
|
|
117
|
+
throw error;
|
|
118
|
+
}
|
|
119
|
+
const message = error instanceof Error ? error.message : "invalid request url";
|
|
120
|
+
throw new HttpRequestError(auth.baseUrl, message, error);
|
|
121
|
+
}
|
|
122
|
+
const maxRetries = isOneShotBody(options.body) ? 0 : retries;
|
|
123
|
+
for (let attempt = 0;; attempt += 1) {
|
|
124
|
+
const controller = new AbortController();
|
|
125
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
126
|
+
try {
|
|
127
|
+
const serializedBody = serializeRequestBody(options.body);
|
|
128
|
+
const headers = new Headers();
|
|
129
|
+
for (const [key, value] of Object.entries(config.defaultHeaders ?? {})) {
|
|
130
|
+
headers.set(key, value);
|
|
131
|
+
}
|
|
132
|
+
for (const [key, value] of Object.entries(options.headers ?? {})) {
|
|
133
|
+
headers.set(key, value);
|
|
134
|
+
}
|
|
135
|
+
if (!headers.has("authorization")) {
|
|
136
|
+
headers.set("Authorization", `Bearer ${auth.apiKey}`);
|
|
137
|
+
}
|
|
138
|
+
if (config.projectId) {
|
|
139
|
+
headers.set("X-Project-ID", config.projectId);
|
|
140
|
+
}
|
|
141
|
+
if (serializedBody.defaultContentType && !headers.has("content-type")) {
|
|
142
|
+
headers.set("Content-Type", serializedBody.defaultContentType);
|
|
143
|
+
}
|
|
144
|
+
const response = await fetchImpl(url, {
|
|
145
|
+
method,
|
|
146
|
+
headers,
|
|
147
|
+
body: serializedBody.body,
|
|
148
|
+
signal: controller.signal,
|
|
149
|
+
});
|
|
150
|
+
const data = await readResponseBody(response);
|
|
151
|
+
if (!response.ok) {
|
|
152
|
+
if (attempt < maxRetries && shouldRetry(response.status)) {
|
|
153
|
+
await sleep(retryDelayMs * (attempt + 1));
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
throw new HttpFailureError(response.status, url, data);
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
status: response.status,
|
|
160
|
+
data: data,
|
|
161
|
+
headers: response.headers,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
if (error instanceof MissingProfileError || error instanceof HttpFailureError) {
|
|
166
|
+
throw error;
|
|
167
|
+
}
|
|
168
|
+
if (attempt < maxRetries) {
|
|
169
|
+
await sleep(retryDelayMs * (attempt + 1));
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
const message = error instanceof Error ? error.message : "unknown error";
|
|
173
|
+
throw new HttpRequestError(url, message, error);
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
clearTimeout(timeout);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
request: doRequest,
|
|
182
|
+
get(path, query) {
|
|
183
|
+
return doRequest({ method: "GET", path, query });
|
|
184
|
+
},
|
|
185
|
+
post(path, body) {
|
|
186
|
+
return doRequest({ method: "POST", path, body });
|
|
187
|
+
},
|
|
188
|
+
put(path, body) {
|
|
189
|
+
return doRequest({ method: "PUT", path, body });
|
|
190
|
+
},
|
|
191
|
+
patch(path, body) {
|
|
192
|
+
return doRequest({ method: "PATCH", path, body });
|
|
193
|
+
},
|
|
194
|
+
delete(path) {
|
|
195
|
+
return doRequest({ method: "DELETE", path });
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type ConfigLoaderErrorCode = "CLIFN_CONFIG_INVALID" | "CLIFN_CONFIG_NOT_FOUND" | "CLIFN_CONFIG_UNSUPPORTED";
|
|
2
|
+
export declare class ConfigLoaderError extends Error {
|
|
3
|
+
readonly code: ConfigLoaderErrorCode;
|
|
4
|
+
constructor(code: ConfigLoaderErrorCode, message: string);
|
|
5
|
+
}
|
|
6
|
+
export interface ConfigLoaderOptions<T> {
|
|
7
|
+
cwd?: string;
|
|
8
|
+
configPath?: string;
|
|
9
|
+
candidates?: readonly string[];
|
|
10
|
+
exportNames?: readonly string[];
|
|
11
|
+
validate?: (value: unknown, path: string) => T;
|
|
12
|
+
}
|
|
13
|
+
export interface LoadedConfig<T> {
|
|
14
|
+
config: T;
|
|
15
|
+
path: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function defineConfig<T>(config: T): T;
|
|
18
|
+
export declare function loadConfig<T>(options?: ConfigLoaderOptions<T>): Promise<LoadedConfig<T>>;
|