abysshub 0.0.1-dev.6 → 0.0.1-dev.8
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 +104 -5
- package/dist/client.d.ts +51 -2
- package/dist/client.js +228 -74
- package/dist/error.d.ts +2 -0
- package/dist/error.js +1 -1
- package/dist/http.d.ts +2 -1
- package/dist/http.js +18 -7
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/types.d.ts +44 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -20,11 +20,62 @@ try {
|
|
|
20
20
|
|
|
21
21
|
`run()` presses the Widget and waits for the run to end, however long it takes, then returns the succeeded run. A refusal or a failed run raises `AbyssError`.
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
It runs on Node 20+, Bun and Deno, with no dependencies. An API key is a server-side secret, so in a browser `new Abyss()` throws.
|
|
24
|
+
|
|
25
|
+
## The client
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
const abyss = new Abyss({ apiKey, baseURL, maxRetries, timeout });
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- **`apiKey`:** defaults to `ABYSS_API_KEY`. Without a key, `new Abyss()` raises `AbyssError` with `code: "invalid_api_key"`.
|
|
32
|
+
- **`baseURL`:** defaults to `ABYSS_BASE_URL`, else `https://api.abysshub.com`. A key starting `abyss_sk_dev_` goes to `https://api.dev.abysshub.com`.
|
|
33
|
+
- **`maxRetries`:** how many times a request is sent again (see [Retries](#retries)). Defaults to 2.
|
|
34
|
+
- **`timeout`:** the seconds every call waits at most, unless it sets its own (see [Timeouts](#timeouts)). None by default.
|
|
35
|
+
|
|
36
|
+
Every request sends `Authorization: Bearer <key>` and `User-Agent: abysshub-js/<version> (<runtime> <version>)`.
|
|
37
|
+
|
|
38
|
+
## Running a Widget
|
|
39
|
+
|
|
40
|
+
```js
|
|
41
|
+
const run = await abyss.run(widget, input, { maxPrice, idempotencyKey, timeout, signal });
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
- **`widget`** is `widget_<id>`, or an unlisted Widget's private token.
|
|
45
|
+
- **`input`** is the Widget's Fields by name (`GET /v1/widgets/{widget}` lists them as `input_schema`). A file Field takes a file (see [Files](#files)).
|
|
46
|
+
- **`maxPrice`:** the most the run may cost, in Byssium. A higher price is refused with `price_above_max`, and nothing is charged.
|
|
47
|
+
- **`idempotencyKey`:** each call presses with a fresh UUID `Idempotency-Key` unless you give one. Retries send the same one, so a run is never made or charged twice.
|
|
48
|
+
|
|
49
|
+
The press holds until the run ends. When the hold ends early (a deploy cuts it, the API's holds are all taken, or an hour passes), `run()` re-attaches with `GET <Location>?wait=true` until the run ends. Re-attaching has no limit and is not a retry. Connecting has 10 s, and 30 s of silence counts as a cut.
|
|
50
|
+
|
|
51
|
+
A **run** has `/v1`'s fields: `id`, `widget`, `status` (`queued`, `running`, `succeeded` or `failed`), `price`, `result`, `output_files`, `error`, `created_at`, `started_at` and `ended_at`.
|
|
52
|
+
|
|
53
|
+
## The routes
|
|
54
|
+
|
|
55
|
+
Under `run()` there is one method per route. Each takes `timeout` and `signal` in its last argument.
|
|
56
|
+
|
|
57
|
+
| Method | Route | Answers |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| `abyss.runs.create(widget, input, { maxPrice?, idempotencyKey? })` | `POST /v1/widgets/{widget}/runs` with `"wait": false` | the run, `queued`, at once |
|
|
60
|
+
| `abyss.runs.get(id, { wait? })` | `GET /v1/runs/{id}`, with `?wait=true` when `wait` | the run |
|
|
61
|
+
| `abyss.runs.list({ limit?, startingAfter? })` | `GET /v1/runs?limit=&starting_after=` | `{ data, has_more }`, newest first |
|
|
62
|
+
| `abyss.widgets.get(widget)` | `GET /v1/widgets/{widget}` | `{ id, name, description, url, price, free_runs, input_schema }` |
|
|
63
|
+
| `abyss.uploads.create(widget, { field, filename, size? })` | `POST /v1/widgets/{widget}/uploads` | `{ id, upload: { url, fields } }` |
|
|
64
|
+
| `abyss.key()` | `GET /v1/key` | `{ name, key, user, spend_cap, spent_this_month, created_at }` |
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
const queued = await abyss.runs.create("widget_131", { amount: 250000 });
|
|
68
|
+
// … later, or in another process:
|
|
69
|
+
const run = await abyss.runs.get(queued.id, { wait: true });
|
|
70
|
+
|
|
71
|
+
let page = await abyss.runs.list({ limit: 100 });
|
|
72
|
+
while (page.has_more) page = await abyss.runs.list({ limit: 100, startingAfter: page.data.at(-1).id });
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- **`runs.create()`** uploads the input's files like `run()`, then answers without waiting.
|
|
76
|
+
- **`runs.get()`** answers the run as it is, failed or not: only `run()` raises a failed run. With `wait`, it holds until the run ends, reading again when the hold is cut. A hold answers after an hour, or at once when the API's holds are all taken, so read again while `status` is `queued` or `running`.
|
|
77
|
+
- **`runs.list()`** answers each of `data` as a run, with `save()` and `output_files`.
|
|
78
|
+
- **`uploads.create()`** only asks for the grant. To upload by hand, POST every `fields` entry, then the file as `file`, to `url`, and put `id` in the input.
|
|
28
79
|
|
|
29
80
|
## Files
|
|
30
81
|
|
|
@@ -43,3 +94,51 @@ const paths = await run.save("output"); // ["output/charts/a.png", "output/outpu
|
|
|
43
94
|
- **Before the press,** each file is uploaded with `POST /v1/widgets/{widget}/uploads`, then sent to storage, in parallel, and its id goes in the input. An upload refusal (`held_input_*`) raises before any press. A retried press reuses the ids; it never uploads again.
|
|
44
95
|
- **`await run.save(dir)`** writes every output file under `dir` at its `path`, making folders, and answers the paths it wrote.
|
|
45
96
|
- **Each of `run.output_files`** has `await f.save(path)` and `await f.read()`, which answers a `Uint8Array`. An expired URL is refreshed once, by reading the run again with `GET /v1/runs/{id}`.
|
|
97
|
+
|
|
98
|
+
## Errors
|
|
99
|
+
|
|
100
|
+
A refusal, a failed run, a timeout and a lost connection all raise one class, `AbyssError`. There is no class per status: branch on `code`.
|
|
101
|
+
|
|
102
|
+
| Field | |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `code` | `/v1`'s error code, a failed run's `error.code`, or a library-only code below |
|
|
105
|
+
| `message` | what to do, for a person |
|
|
106
|
+
| `status` | the HTTP status of a refusal, else `null` |
|
|
107
|
+
| `param` | the Field, body key, query key or header at fault, else `null` |
|
|
108
|
+
| `doc_url` | the code on the API access page, else `null` |
|
|
109
|
+
| `request_id` | quote it to support, else `null` |
|
|
110
|
+
| `run` | the run, for a failed run or a timeout, else `null` |
|
|
111
|
+
|
|
112
|
+
- **Refusals:** `invalid_api_key` (401), `not_found` (404), `invalid_request`, `invalid_input`, `held_input_*`, `input_unreachable` and `idempotency_key_reused` (422), `insufficient_funds` (402), `spend_cap_reached` and `price_above_max` (400), `idempotency_key_in_use` (409), `rate_limited` (429), `server_error` (500).
|
|
113
|
+
- **A failed run:** `widget_fault`, `platform_fault` or `budget_exceeded`, with the run as `run`.
|
|
114
|
+
- **Library-only codes:** `timeout` (see [Timeouts](#timeouts)); `connection_error`, when the connection still drops before any answer after the retries, with the cause as `cause`; and `unexpected_response`, when an answer is not what the route sends.
|
|
115
|
+
|
|
116
|
+
## Retries
|
|
117
|
+
|
|
118
|
+
A request is sent again, at most `maxRetries` times (2 by default), only after:
|
|
119
|
+
|
|
120
|
+
- **a drop before any headers arrived:** a short backoff, then the same request, with the same `Idempotency-Key` for a press;
|
|
121
|
+
- **`429 rate_limited` and `409 idempotency_key_in_use`:** after the `Retry-After` seconds;
|
|
122
|
+
- **a `5xx`:** a short backoff (0.5 s, then 1 s).
|
|
123
|
+
|
|
124
|
+
When the last try fails too, it raises. Every other refusal raises at once, and re-attaching never counts as a retry.
|
|
125
|
+
|
|
126
|
+
## Timeouts
|
|
127
|
+
|
|
128
|
+
There is no timeout by default: `run()` waits as long as the run takes. `timeout` (seconds) and `signal` (an `AbortSignal`) stop the waiting, never the run.
|
|
129
|
+
|
|
130
|
+
```js
|
|
131
|
+
try {
|
|
132
|
+
const run = await abyss.run("widget_131", input, { timeout: 60, signal: AbortSignal.timeout(90_000) });
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error instanceof AbyssError && error.code === "timeout") {
|
|
135
|
+
// The run goes on. error.run is the run as last seen, or null when none was seen yet.
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Either one raises `AbyssError` with `code: "timeout"` and `run`, the run as last seen. During the press's first hold the run has not been seen yet, so `run` is `null`; to keep its `id` whatever happens, press with `runs.create()` and wait with `runs.get(id, { wait: true, timeout })`.
|
|
141
|
+
|
|
142
|
+
## Names
|
|
143
|
+
|
|
144
|
+
Returned data keeps `/v1`'s names: `output_files`, `has_more`, `request_id`. The library's own options are camelCase: `maxPrice`, `startingAfter`. A Field's name is never converted: `input` is sent as you write it.
|
package/dist/client.d.ts
CHANGED
|
@@ -1,22 +1,69 @@
|
|
|
1
1
|
import { Run } from "./run.js";
|
|
2
|
-
import type { Input } from "./types.js";
|
|
2
|
+
import type { Input, Key, RunList, Upload, Widget } from "./types.js";
|
|
3
3
|
export interface AbyssOptions {
|
|
4
4
|
/** Defaults to `ABYSS_API_KEY`. */
|
|
5
5
|
apiKey?: string;
|
|
6
6
|
/** Defaults to `ABYSS_BASE_URL`, else the address the key belongs to. */
|
|
7
7
|
baseURL?: string;
|
|
8
|
+
/** How many times a request is sent again after a drop before any headers, a `429`, a `409` or a `5xx`. Defaults to 2. */
|
|
8
9
|
maxRetries?: number;
|
|
10
|
+
/** The seconds every call waits at most, unless it sets its own. None by default. */
|
|
11
|
+
timeout?: number;
|
|
9
12
|
}
|
|
10
|
-
|
|
13
|
+
/** What every call takes. Stopping the waiting never stops the run. */
|
|
14
|
+
export interface CallOptions {
|
|
15
|
+
/** The seconds to wait at most, then raise `AbyssError` with `code: "timeout"`. */
|
|
16
|
+
timeout?: number;
|
|
17
|
+
/** Aborting it stops the waiting, as `timeout` does. */
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
export interface RunOptions extends CallOptions {
|
|
11
21
|
/** The most this run may cost, in Byssium. */
|
|
12
22
|
maxPrice?: number;
|
|
13
23
|
/** Defaults to a fresh UUID for each call. */
|
|
14
24
|
idempotencyKey?: string;
|
|
15
25
|
}
|
|
26
|
+
export interface GetRunOptions extends CallOptions {
|
|
27
|
+
/** Holds until the run ends, as the press holds. */
|
|
28
|
+
wait?: boolean;
|
|
29
|
+
}
|
|
30
|
+
export interface ListRunsOptions extends CallOptions {
|
|
31
|
+
/** How many runs to answer, 1 to 100; the API's default is 20. */
|
|
32
|
+
limit?: number;
|
|
33
|
+
/** The `id` of the last run on the page you have. */
|
|
34
|
+
startingAfter?: string;
|
|
35
|
+
}
|
|
36
|
+
/** What `uploads.create` asks for: the file Field, the file's name and its size in bytes. */
|
|
37
|
+
export interface UploadRequest {
|
|
38
|
+
field: string;
|
|
39
|
+
filename: string;
|
|
40
|
+
size?: number;
|
|
41
|
+
}
|
|
42
|
+
/** `/v1`'s run routes, one method each. */
|
|
43
|
+
export interface Runs {
|
|
44
|
+
/** Uploads the input's files and presses with `"wait": false`: answers the run at once, `queued`. */
|
|
45
|
+
create(widget: string, input: Input, options?: RunOptions): Promise<Run>;
|
|
46
|
+
/** Reads a run as it is, or with `wait` holds until it ends. A failed run is answered, not raised. */
|
|
47
|
+
get(id: string, options?: GetRunOptions): Promise<Run>;
|
|
48
|
+
/** Answers a page of runs, newest first. */
|
|
49
|
+
list(options?: ListRunsOptions): Promise<RunList<Run>>;
|
|
50
|
+
}
|
|
51
|
+
export interface Widgets {
|
|
52
|
+
/** Reads a Widget: its price, Free Runs and `input_schema`. */
|
|
53
|
+
get(widget: string, options?: CallOptions): Promise<Widget>;
|
|
54
|
+
}
|
|
55
|
+
export interface Uploads {
|
|
56
|
+
/** Asks for an upload's grant. `run()` and `runs.create()` upload files by themselves. */
|
|
57
|
+
create(widget: string, upload: UploadRequest, options?: CallOptions): Promise<Upload>;
|
|
58
|
+
}
|
|
16
59
|
export declare class Abyss {
|
|
17
60
|
#private;
|
|
18
61
|
readonly baseURL: string;
|
|
19
62
|
readonly maxRetries: number;
|
|
63
|
+
readonly timeout: number | null;
|
|
64
|
+
readonly runs: Runs;
|
|
65
|
+
readonly widgets: Widgets;
|
|
66
|
+
readonly uploads: Uploads;
|
|
20
67
|
constructor(options?: AbyssOptions);
|
|
21
68
|
/**
|
|
22
69
|
* Uploads the input's files, presses a Widget and waits for the run's ending,
|
|
@@ -24,4 +71,6 @@ export declare class Abyss {
|
|
|
24
71
|
* run; raises `AbyssError` on a refusal or a failed run.
|
|
25
72
|
*/
|
|
26
73
|
run(widget: string, input: Input, options?: RunOptions): Promise<Run>;
|
|
74
|
+
/** Answers the API Key making the call, with `GET /v1/key`. */
|
|
75
|
+
key(options?: CallOptions): Promise<Key>;
|
|
27
76
|
}
|
package/dist/client.js
CHANGED
|
@@ -2,18 +2,27 @@ import { AbyssError } from "./error.js";
|
|
|
2
2
|
import { uploadFiles } from "./files.js";
|
|
3
3
|
import { request } from "./http.js";
|
|
4
4
|
import { Run } from "./run.js";
|
|
5
|
+
import { VERSION } from "./version.js";
|
|
5
6
|
const API = "https://api.abysshub.com";
|
|
6
7
|
const DEV_API = "https://api.dev.abysshub.com";
|
|
7
8
|
const DEV_KEY_PREFIX = "abyss_sk_dev_";
|
|
8
9
|
/** The pause between two re-attaches that both ended without the run's ending. */
|
|
9
10
|
const REATTACH_PAUSE_MS = 1_000;
|
|
10
|
-
/** The pause before
|
|
11
|
+
/** The first pause before a retry after a drop or a 5xx; it doubles with each retry. */
|
|
11
12
|
const RETRY_PAUSE_MS = 500;
|
|
13
|
+
const BROWSER_REFUSAL = "An Abyss API key is a server-side secret. Call the API from your server.";
|
|
14
|
+
const USER_AGENT = `abysshub-js/${VERSION} (${runtime()})`;
|
|
12
15
|
export class Abyss {
|
|
13
16
|
baseURL;
|
|
14
17
|
maxRetries;
|
|
18
|
+
timeout;
|
|
19
|
+
runs;
|
|
20
|
+
widgets;
|
|
21
|
+
uploads;
|
|
15
22
|
#apiKey;
|
|
16
23
|
constructor(options = {}) {
|
|
24
|
+
if (inBrowser())
|
|
25
|
+
throw new Error(BROWSER_REFUSAL);
|
|
17
26
|
const apiKey = options.apiKey ?? env("ABYSS_API_KEY");
|
|
18
27
|
if (!apiKey) {
|
|
19
28
|
throw new AbyssError({
|
|
@@ -25,66 +34,111 @@ export class Abyss {
|
|
|
25
34
|
const baseURL = options.baseURL ?? env("ABYSS_BASE_URL") ?? (apiKey.startsWith(DEV_KEY_PREFIX) ? DEV_API : API);
|
|
26
35
|
this.baseURL = baseURL.replace(/\/+$/, "");
|
|
27
36
|
this.maxRetries = options.maxRetries ?? 2;
|
|
37
|
+
this.timeout = options.timeout ?? null;
|
|
38
|
+
this.runs = {
|
|
39
|
+
create: (widget, input, options = {}) => this.#call(options, async (call) => {
|
|
40
|
+
const press = await this.#press(call, widget, input, options, false);
|
|
41
|
+
return this.#run(expect(press, isRun, "The press answered without a run."));
|
|
42
|
+
}),
|
|
43
|
+
get: (id, options = {}) => this.#call(options, async (call) => this.#run(await this.#getRun(call, id, options.wait ?? false))),
|
|
44
|
+
list: (options = {}) => this.#call(options, (call) => this.#listRuns(call, options)),
|
|
45
|
+
};
|
|
46
|
+
this.widgets = {
|
|
47
|
+
get: (widget, options = {}) => this.#call(options, (call) => this.#get(call, this.#widgetURL(widget), isWidget, "The Widget answered without an id.")),
|
|
48
|
+
};
|
|
49
|
+
this.uploads = {
|
|
50
|
+
create: (widget, upload, options = {}) => this.#call(options, (call) => this.#grant(call, this.#widgetURL(widget), upload)),
|
|
51
|
+
};
|
|
28
52
|
}
|
|
29
53
|
/**
|
|
30
54
|
* Uploads the input's files, presses a Widget and waits for the run's ending,
|
|
31
55
|
* re-attaching through `Location` whenever the hold ends early. Returns the succeeded
|
|
32
56
|
* run; raises `AbyssError` on a refusal or a failed run.
|
|
33
57
|
*/
|
|
34
|
-
|
|
35
|
-
|
|
58
|
+
run(widget, input, options = {}) {
|
|
59
|
+
return this.#call(options, async (call) => {
|
|
60
|
+
const press = await this.#press(call, widget, input, options, true);
|
|
61
|
+
const reply = hasEnded(press) ? press : await this.#hold(call, this.#waitURL(press), hasEnded);
|
|
62
|
+
const run = this.#run(reply.run);
|
|
63
|
+
if (run.status === "failed") {
|
|
64
|
+
throw new AbyssError({
|
|
65
|
+
code: run.error?.code ?? "platform_fault",
|
|
66
|
+
message: run.error?.message ?? "The run failed.",
|
|
67
|
+
request_id: reply.requestId,
|
|
68
|
+
run,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return run;
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
/** Answers the API Key making the call, with `GET /v1/key`. */
|
|
75
|
+
key(options = {}) {
|
|
76
|
+
return this.#call(options, (call) => this.#get(call, `${this.baseURL}/v1/key`, isKey, "The key answered without a key."));
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Runs one call under its `timeout` and `signal`. When either stops the waiting, the
|
|
80
|
+
* call raises `AbyssError` with `code: "timeout"` and the run as last seen.
|
|
81
|
+
*/
|
|
82
|
+
async #call(options, work) {
|
|
83
|
+
const timeout = options.timeout ?? this.timeout;
|
|
84
|
+
const stop = new AbortController();
|
|
85
|
+
let message = "The signal stopped the waiting. The run goes on.";
|
|
86
|
+
const abort = () => stop.abort();
|
|
87
|
+
const timer = timeout === null
|
|
88
|
+
? undefined
|
|
89
|
+
: setTimeout(() => {
|
|
90
|
+
message = `Stopped waiting after ${timeout} s. The run goes on.`;
|
|
91
|
+
abort();
|
|
92
|
+
}, timeout * 1_000);
|
|
93
|
+
if (options.signal?.aborted)
|
|
94
|
+
abort();
|
|
95
|
+
options.signal?.addEventListener("abort", abort, { once: true });
|
|
96
|
+
const call = { signal: stop.signal, seen: null };
|
|
97
|
+
try {
|
|
98
|
+
return await work(call);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
if (!stop.signal.aborted)
|
|
102
|
+
throw error;
|
|
103
|
+
throw new AbyssError({ code: "timeout", message, run: call.seen && this.#run(call.seen) });
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
clearTimeout(timer);
|
|
107
|
+
options.signal?.removeEventListener("abort", abort);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Uploads the input's files and sends the press, with `"wait": false` unless it holds.
|
|
112
|
+
* Its retries send the same body and `Idempotency-Key`, so the uploads are never redone.
|
|
113
|
+
*/
|
|
114
|
+
async #press(call, widget, input, options, hold) {
|
|
115
|
+
const widgetURL = this.#widgetURL(widget);
|
|
36
116
|
const body = {
|
|
37
|
-
input: await uploadFiles(input, (field, filename, data) => this.#upload(widgetURL, field, filename, data)),
|
|
117
|
+
input: await uploadFiles(input, (field, filename, data) => this.#upload(call, widgetURL, field, filename, data)),
|
|
38
118
|
};
|
|
39
119
|
if (options.maxPrice !== undefined)
|
|
40
120
|
body.max_price = options.maxPrice;
|
|
41
|
-
|
|
121
|
+
if (!hold)
|
|
122
|
+
body.wait = false;
|
|
123
|
+
return this.#send(call, "POST", `${widgetURL}/runs`, {
|
|
42
124
|
"Content-Type": "application/json",
|
|
43
125
|
"Idempotency-Key": options.idempotencyKey ?? crypto.randomUUID(),
|
|
44
126
|
}, JSON.stringify(body));
|
|
45
|
-
const reply = hasEnded(press) ? press : await this.#reattach(press);
|
|
46
|
-
const run = new Run(reply.run, () => this.#read(reply.run.id));
|
|
47
|
-
if (run.status === "failed") {
|
|
48
|
-
throw new AbyssError({
|
|
49
|
-
code: run.error?.code ?? "platform_fault",
|
|
50
|
-
message: run.error?.message ?? "The run failed.",
|
|
51
|
-
request_id: reply.requestId,
|
|
52
|
-
run,
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
return run;
|
|
56
127
|
}
|
|
57
|
-
/**
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
for (let attempt = 0;; attempt++) {
|
|
63
|
-
try {
|
|
64
|
-
return await this.#send("POST", url, headers, body);
|
|
65
|
-
}
|
|
66
|
-
catch (error) {
|
|
67
|
-
if (error instanceof AbyssError || attempt >= this.maxRetries)
|
|
68
|
-
throw error;
|
|
69
|
-
await sleep(RETRY_PAUSE_MS);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
128
|
+
/** Asks for an upload with `POST /v1/widgets/{widget}/uploads`. */
|
|
129
|
+
async #grant(call, widgetURL, { field, filename, size }) {
|
|
130
|
+
// JSON.stringify leaves `size` out when it is undefined.
|
|
131
|
+
const grant = await this.#send(call, "POST", `${widgetURL}/uploads`, { "Content-Type": "application/json" }, JSON.stringify({ field, filename, size }));
|
|
132
|
+
return expect(grant, isUpload, "The upload answered without an id and a form.");
|
|
72
133
|
}
|
|
73
|
-
/** Asks for an upload
|
|
74
|
-
async #upload(widgetURL, field, filename, data) {
|
|
75
|
-
const grant = await this.#
|
|
76
|
-
if (!isUpload(grant.body)) {
|
|
77
|
-
throw new AbyssError({
|
|
78
|
-
code: "unexpected_response",
|
|
79
|
-
message: "The upload answered without an id and a form.",
|
|
80
|
-
request_id: grant.requestId,
|
|
81
|
-
});
|
|
82
|
-
}
|
|
134
|
+
/** Asks for an upload, sends the file to storage and answers its id. */
|
|
135
|
+
async #upload(call, widgetURL, field, filename, data) {
|
|
136
|
+
const grant = await this.#grant(call, widgetURL, { field, filename, size: data.size });
|
|
83
137
|
const form = new FormData();
|
|
84
|
-
for (const [name, value] of Object.entries(grant.
|
|
138
|
+
for (const [name, value] of Object.entries(grant.upload.fields))
|
|
85
139
|
form.append(name, value);
|
|
86
140
|
form.append("file", data, filename);
|
|
87
|
-
const stored = await fetch(grant.
|
|
141
|
+
const stored = await fetch(grant.upload.url, { method: "POST", body: form, signal: call.signal });
|
|
88
142
|
await stored.body?.cancel();
|
|
89
143
|
if (!stored.ok) {
|
|
90
144
|
throw new AbyssError({
|
|
@@ -94,30 +148,44 @@ export class Abyss {
|
|
|
94
148
|
param: field,
|
|
95
149
|
});
|
|
96
150
|
}
|
|
97
|
-
return grant.
|
|
151
|
+
return grant.id;
|
|
98
152
|
}
|
|
99
|
-
/** Reads a run
|
|
100
|
-
async #
|
|
101
|
-
const
|
|
102
|
-
if (
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
153
|
+
/** Reads a run with `GET /v1/runs/{id}`, holding with `?wait=true`. A cut hold is read again. */
|
|
154
|
+
async #getRun(call, id, wait) {
|
|
155
|
+
const url = new URL(`${this.baseURL}/v1/runs/${encodeURIComponent(id)}`);
|
|
156
|
+
if (wait)
|
|
157
|
+
url.searchParams.set("wait", "true");
|
|
158
|
+
const reply = await this.#hold(call, url.href, (reply) => !reply.cut);
|
|
159
|
+
return expect(reply, isRun, "The read answered without a run.");
|
|
160
|
+
}
|
|
161
|
+
async #listRuns(call, options) {
|
|
162
|
+
const url = new URL(`${this.baseURL}/v1/runs`);
|
|
163
|
+
if (options.limit !== undefined)
|
|
164
|
+
url.searchParams.set("limit", String(options.limit));
|
|
165
|
+
if (options.startingAfter !== undefined)
|
|
166
|
+
url.searchParams.set("starting_after", options.startingAfter);
|
|
167
|
+
const page = await this.#get(call, url.href, isRunList, "The run list answered without data.");
|
|
168
|
+
return { data: page.data.map((data) => this.#run(data)), has_more: page.has_more };
|
|
169
|
+
}
|
|
170
|
+
/** Reads `url` once and answers its body, when it is what the route answers. */
|
|
171
|
+
async #get(call, url, is, message) {
|
|
172
|
+
return expect(await this.#send(call, "GET", url), is, message);
|
|
173
|
+
}
|
|
174
|
+
/** Reads `url` until `done`. Re-attaching has no limit and is not a retry. */
|
|
175
|
+
async #hold(call, url, done) {
|
|
176
|
+
let reply = await this.#send(call, "GET", url);
|
|
177
|
+
while (!done(reply)) {
|
|
178
|
+
await sleep(REATTACH_PAUSE_MS, call.signal);
|
|
179
|
+
reply = await this.#send(call, "GET", url);
|
|
118
180
|
}
|
|
119
181
|
return reply;
|
|
120
182
|
}
|
|
183
|
+
#run(data) {
|
|
184
|
+
return new Run(data, () => this.#getRun({ signal: null, seen: null }, data.id, false));
|
|
185
|
+
}
|
|
186
|
+
#widgetURL(widget) {
|
|
187
|
+
return `${this.baseURL}/v1/widgets/${encodeURIComponent(widget)}`;
|
|
188
|
+
}
|
|
121
189
|
#waitURL(reply) {
|
|
122
190
|
const location = reply.location ?? (reply.run ? `/v1/runs/${reply.run.id}` : null);
|
|
123
191
|
if (!location) {
|
|
@@ -131,20 +199,68 @@ export class Abyss {
|
|
|
131
199
|
url.searchParams.set("wait", "true");
|
|
132
200
|
return url.href;
|
|
133
201
|
}
|
|
134
|
-
|
|
135
|
-
|
|
202
|
+
/**
|
|
203
|
+
* Sends one request to `/v1`. A drop before any headers, a `429`, a `409` and a `5xx`
|
|
204
|
+
* are sent again, at most `maxRetries` times; every other refusal raises at once.
|
|
205
|
+
*/
|
|
206
|
+
async #send(call, method, url, headers = {}, body) {
|
|
207
|
+
const init = {
|
|
136
208
|
method,
|
|
137
|
-
headers: { Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", ...headers },
|
|
209
|
+
headers: { Authorization: `Bearer ${this.#apiKey}`, Accept: "application/json", "User-Agent": USER_AGENT, ...headers },
|
|
210
|
+
signal: call.signal,
|
|
138
211
|
...(body === undefined ? {} : { body }),
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
212
|
+
};
|
|
213
|
+
for (let attempt = 0;; attempt++) {
|
|
214
|
+
let answer;
|
|
215
|
+
try {
|
|
216
|
+
answer = await request(url, init);
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
if (call.signal?.aborted)
|
|
220
|
+
throw error;
|
|
221
|
+
if (attempt >= this.maxRetries) {
|
|
222
|
+
throw new AbyssError({
|
|
223
|
+
code: "connection_error",
|
|
224
|
+
message: "The connection dropped, or timed out, before the API answered.",
|
|
225
|
+
cause: error,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
await sleep(backoff(attempt), call.signal);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
const requestId = answer.headers.get("request-id");
|
|
232
|
+
const parsed = parse(answer.text);
|
|
233
|
+
if (answer.status === 200 || answer.status === 202) {
|
|
234
|
+
const run = isRun(parsed) ? parsed : null;
|
|
235
|
+
if (run)
|
|
236
|
+
call.seen = run;
|
|
237
|
+
return { body: parsed, run, cut: answer.text === null, location: answer.headers.get("location"), requestId };
|
|
238
|
+
}
|
|
239
|
+
const pause = retryPause(answer, attempt);
|
|
240
|
+
if (pause === null || attempt >= this.maxRetries)
|
|
241
|
+
throw refusal(answer.status, parsed, requestId);
|
|
242
|
+
await sleep(pause, call.signal);
|
|
144
243
|
}
|
|
145
|
-
throw refusal(answer.status, parsed, requestId);
|
|
146
244
|
}
|
|
147
245
|
}
|
|
246
|
+
/** How long to wait before sending a refused request again, or null when it is not retried. */
|
|
247
|
+
function retryPause(answer, attempt) {
|
|
248
|
+
if (answer.status === 429 || answer.status === 409) {
|
|
249
|
+
const after = answer.headers.get("retry-after");
|
|
250
|
+
const seconds = after === null ? Number.NaN : Number(after);
|
|
251
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1_000 : backoff(attempt);
|
|
252
|
+
}
|
|
253
|
+
return answer.status >= 500 ? backoff(attempt) : null;
|
|
254
|
+
}
|
|
255
|
+
function backoff(attempt) {
|
|
256
|
+
return RETRY_PAUSE_MS * 2 ** attempt;
|
|
257
|
+
}
|
|
258
|
+
/** The reply's body when it is what the route answers, else `unexpected_response`. */
|
|
259
|
+
function expect(reply, is, message) {
|
|
260
|
+
if (is(reply.body))
|
|
261
|
+
return reply.body;
|
|
262
|
+
throw new AbyssError({ code: "unexpected_response", message, request_id: reply.requestId });
|
|
263
|
+
}
|
|
148
264
|
function refusal(status, body, requestId) {
|
|
149
265
|
const error = isObject(body) && isObject(body.error) ? body.error : null;
|
|
150
266
|
if (!error || typeof error.code !== "string") {
|
|
@@ -180,6 +296,15 @@ function isObject(value) {
|
|
|
180
296
|
function isRun(value) {
|
|
181
297
|
return isObject(value) && typeof value.id === "string" && typeof value.status === "string";
|
|
182
298
|
}
|
|
299
|
+
function isRunList(value) {
|
|
300
|
+
return isObject(value) && Array.isArray(value.data) && value.data.every(isRun) && typeof value.has_more === "boolean";
|
|
301
|
+
}
|
|
302
|
+
function isWidget(value) {
|
|
303
|
+
return isObject(value) && typeof value.id === "string";
|
|
304
|
+
}
|
|
305
|
+
function isKey(value) {
|
|
306
|
+
return isObject(value) && typeof value.key === "string";
|
|
307
|
+
}
|
|
183
308
|
function isUpload(value) {
|
|
184
309
|
return (isObject(value) &&
|
|
185
310
|
typeof value.id === "string" &&
|
|
@@ -200,6 +325,35 @@ function env(name) {
|
|
|
200
325
|
return undefined;
|
|
201
326
|
}
|
|
202
327
|
}
|
|
203
|
-
|
|
204
|
-
|
|
328
|
+
/** Whether this runs in a browser, where an API key would be exposed. */
|
|
329
|
+
function inBrowser() {
|
|
330
|
+
const scope = globalThis;
|
|
331
|
+
return scope.window !== undefined && scope.document !== undefined;
|
|
332
|
+
}
|
|
333
|
+
/** The runtime and its version, for the User-Agent. Bun and Deno also serve `process`, so they are asked first. */
|
|
334
|
+
function runtime() {
|
|
335
|
+
const scope = globalThis;
|
|
336
|
+
if (scope.Bun?.version)
|
|
337
|
+
return `bun ${scope.Bun.version}`;
|
|
338
|
+
if (scope.Deno?.version?.deno)
|
|
339
|
+
return `deno ${scope.Deno.version.deno}`;
|
|
340
|
+
if (scope.process?.versions?.node)
|
|
341
|
+
return `node ${scope.process.versions.node}`;
|
|
342
|
+
return "unknown";
|
|
343
|
+
}
|
|
344
|
+
/** Waits `ms`, or rejects as soon as `signal` aborts. */
|
|
345
|
+
function sleep(ms, signal) {
|
|
346
|
+
return new Promise((resolve, reject) => {
|
|
347
|
+
if (signal?.aborted)
|
|
348
|
+
return reject(signal.reason);
|
|
349
|
+
const stop = () => {
|
|
350
|
+
clearTimeout(timer);
|
|
351
|
+
reject(signal?.reason);
|
|
352
|
+
};
|
|
353
|
+
const timer = setTimeout(() => {
|
|
354
|
+
signal?.removeEventListener("abort", stop);
|
|
355
|
+
resolve();
|
|
356
|
+
}, ms);
|
|
357
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
358
|
+
});
|
|
205
359
|
}
|
package/dist/error.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ export interface AbyssErrorFields {
|
|
|
7
7
|
doc_url?: string | null;
|
|
8
8
|
request_id?: string | null;
|
|
9
9
|
run?: Run | null;
|
|
10
|
+
/** What a `connection_error` was caused by. */
|
|
11
|
+
cause?: unknown;
|
|
10
12
|
}
|
|
11
13
|
/**
|
|
12
14
|
* The one error the library raises: a refusal from `/v1`, or a run that failed.
|
package/dist/error.js
CHANGED
|
@@ -11,7 +11,7 @@ export class AbyssError extends Error {
|
|
|
11
11
|
request_id;
|
|
12
12
|
run;
|
|
13
13
|
constructor(fields) {
|
|
14
|
-
super(fields.message);
|
|
14
|
+
super(fields.message, fields.cause === undefined ? undefined : { cause: fields.cause });
|
|
15
15
|
this.name = "AbyssError";
|
|
16
16
|
this.code = fields.code;
|
|
17
17
|
this.status = fields.status ?? null;
|
package/dist/http.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export interface Answer {
|
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
15
|
* Sends one request and reads its whole body. A failure before the headers rejects;
|
|
16
|
-
* a cut after them answers `text: null`, so the caller can re-attach.
|
|
16
|
+
* a cut after them answers `text: null`, so the caller can re-attach. `init.signal`
|
|
17
|
+
* stops the request at any point, and then it always rejects.
|
|
17
18
|
*/
|
|
18
19
|
export declare function request(url: string, init: RequestInit, limits?: Limits): Promise<Answer>;
|
package/dist/http.js
CHANGED
|
@@ -1,20 +1,31 @@
|
|
|
1
1
|
export const LIMITS = { connectMs: 10_000, silenceMs: 30_000 };
|
|
2
2
|
/**
|
|
3
3
|
* Sends one request and reads its whole body. A failure before the headers rejects;
|
|
4
|
-
* a cut after them answers `text: null`, so the caller can re-attach.
|
|
4
|
+
* a cut after them answers `text: null`, so the caller can re-attach. `init.signal`
|
|
5
|
+
* stops the request at any point, and then it always rejects.
|
|
5
6
|
*/
|
|
6
7
|
export async function request(url, init, limits = LIMITS) {
|
|
8
|
+
const stop = init.signal;
|
|
9
|
+
stop?.throwIfAborted();
|
|
7
10
|
const controller = new AbortController();
|
|
8
|
-
const
|
|
9
|
-
|
|
11
|
+
const abort = () => controller.abort();
|
|
12
|
+
stop?.addEventListener("abort", abort, { once: true });
|
|
13
|
+
const connect = setTimeout(abort, limits.connectMs);
|
|
10
14
|
try {
|
|
11
|
-
response
|
|
15
|
+
let response;
|
|
16
|
+
try {
|
|
17
|
+
response = await fetch(url, { ...init, signal: controller.signal });
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
clearTimeout(connect);
|
|
21
|
+
}
|
|
22
|
+
const text = await readBody(response, controller, limits.silenceMs);
|
|
23
|
+
stop?.throwIfAborted();
|
|
24
|
+
return { status: response.status, headers: response.headers, text };
|
|
12
25
|
}
|
|
13
26
|
finally {
|
|
14
|
-
|
|
27
|
+
stop?.removeEventListener("abort", abort);
|
|
15
28
|
}
|
|
16
|
-
const text = await readBody(response, controller, limits.silenceMs);
|
|
17
|
-
return { status: response.status, headers: response.headers, text };
|
|
18
29
|
}
|
|
19
30
|
async function readBody(response, controller, silenceMs) {
|
|
20
31
|
if (!response.body)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export { Abyss, type AbyssOptions, type RunOptions } from "./client.js";
|
|
1
|
+
export { Abyss, type AbyssOptions, type CallOptions, type GetRunOptions, type ListRunsOptions, type RunOptions, type Runs, type UploadRequest, type Uploads, type Widgets, } from "./client.js";
|
|
2
2
|
export { AbyssError, type AbyssErrorFields } from "./error.js";
|
|
3
3
|
export { file, type FileData, type FileOptions, type InputFile } from "./files.js";
|
|
4
4
|
export type { Run, RunFile } from "./run.js";
|
|
5
|
-
export type { Input, RunError, RunStatus } from "./types.js";
|
|
5
|
+
export type { Input, Key, RunError, RunList, RunStatus, Upload, Widget } from "./types.js";
|
package/dist/index.js
CHANGED
package/dist/types.d.ts
CHANGED
|
@@ -27,3 +27,47 @@ export interface RunData {
|
|
|
27
27
|
}
|
|
28
28
|
/** A Widget's input: its Fields by name, never converted. */
|
|
29
29
|
export type Input = Record<string, unknown>;
|
|
30
|
+
/** A page of runs, newest first, as `GET /v1/runs` sends it. */
|
|
31
|
+
export interface RunList<R = RunData> {
|
|
32
|
+
data: R[];
|
|
33
|
+
/** Whether a page `starting_after` the last run here would find more. */
|
|
34
|
+
has_more: boolean;
|
|
35
|
+
}
|
|
36
|
+
/** A Widget, as the caller about to press it sees it. */
|
|
37
|
+
export interface Widget {
|
|
38
|
+
id: string;
|
|
39
|
+
name: string | null;
|
|
40
|
+
description: string | null;
|
|
41
|
+
url: string;
|
|
42
|
+
/** The one price a run costs, Call Price included. */
|
|
43
|
+
price: number;
|
|
44
|
+
/** The caller's Free Runs on this Widget; null for their own Widget and for a free one. */
|
|
45
|
+
free_runs: {
|
|
46
|
+
limit: number;
|
|
47
|
+
remaining: number;
|
|
48
|
+
} | null;
|
|
49
|
+
/** The JSON Schema the input must match. */
|
|
50
|
+
input_schema: Record<string, unknown>;
|
|
51
|
+
}
|
|
52
|
+
/** An upload's grant: its `id` goes in the input once the file is in storage. */
|
|
53
|
+
export interface Upload {
|
|
54
|
+
id: string;
|
|
55
|
+
/** POST every `fields` entry, then the file as `file`, to `url`. */
|
|
56
|
+
upload: {
|
|
57
|
+
url: string;
|
|
58
|
+
fields: Record<string, string>;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** The API Key making the call, as `GET /v1/key` sends it. Never its secret. */
|
|
62
|
+
export interface Key {
|
|
63
|
+
name: string;
|
|
64
|
+
/** The key's display form: its prefix and last four characters. */
|
|
65
|
+
key: string;
|
|
66
|
+
user: {
|
|
67
|
+
id: number;
|
|
68
|
+
name: string;
|
|
69
|
+
};
|
|
70
|
+
spend_cap: number | null;
|
|
71
|
+
spent_this_month: number;
|
|
72
|
+
created_at: string;
|
|
73
|
+
}
|
package/dist/version.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "abysshub",
|
|
3
|
-
"version": "0.0.1-dev.
|
|
3
|
+
"version": "0.0.1-dev.8",
|
|
4
4
|
"description": "The official JavaScript library for the Abyss API.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://github.com/Abysshub/abysshub-sdk/tree/main/js#readme",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"node": ">=20"
|
|
28
28
|
},
|
|
29
29
|
"scripts": {
|
|
30
|
-
"build": "tsc",
|
|
30
|
+
"build": "node scripts/version.js && tsc",
|
|
31
31
|
"prepack": "npm run build",
|
|
32
32
|
"test": "npm run build && node --test test/*.test.js"
|
|
33
33
|
},
|