@b3os/sdk 0.0.0-stage → 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 +202 -0
- package/README.md +233 -2
- package/dist/cjs/core/client.d.ts +165 -0
- package/dist/cjs/core/client.js +825 -0
- package/dist/cjs/core/client.js.map +1 -0
- package/dist/cjs/core/errors.d.ts +101 -0
- package/dist/cjs/core/errors.js +249 -0
- package/dist/cjs/core/errors.js.map +1 -0
- package/dist/cjs/core/index.d.ts +12 -0
- package/dist/cjs/core/index.js +42 -0
- package/dist/cjs/core/index.js.map +1 -0
- package/dist/cjs/core/jobs.d.ts +31 -0
- package/dist/cjs/core/jobs.js +72 -0
- package/dist/cjs/core/jobs.js.map +1 -0
- package/dist/cjs/core/namespace.d.ts +7 -0
- package/dist/cjs/core/namespace.js +13 -0
- package/dist/cjs/core/namespace.js.map +1 -0
- package/dist/cjs/core/op.d.ts +47 -0
- package/dist/cjs/core/op.js +5 -0
- package/dist/cjs/core/op.js.map +1 -0
- package/dist/cjs/core/promise.d.ts +106 -0
- package/dist/cjs/core/promise.js +200 -0
- package/dist/cjs/core/promise.js.map +1 -0
- package/dist/cjs/core/response.d.ts +54 -0
- package/dist/cjs/core/response.js +92 -0
- package/dist/cjs/core/response.js.map +1 -0
- package/dist/cjs/core/sse.d.ts +79 -0
- package/dist/cjs/core/sse.js +291 -0
- package/dist/cjs/core/sse.js.map +1 -0
- package/dist/cjs/core/timing.d.ts +20 -0
- package/dist/cjs/core/timing.js +96 -0
- package/dist/cjs/core/timing.js.map +1 -0
- package/dist/cjs/core/transport.d.ts +80 -0
- package/dist/cjs/core/transport.js +472 -0
- package/dist/cjs/core/transport.js.map +1 -0
- package/dist/cjs/core/util.d.ts +25 -0
- package/dist/cjs/core/util.js +142 -0
- package/dist/cjs/core/util.js.map +1 -0
- package/dist/cjs/core/ws.d.ts +52 -0
- package/dist/cjs/core/ws.js +181 -0
- package/dist/cjs/core/ws.js.map +1 -0
- package/dist/cjs/generated/client.d.ts +62 -0
- package/dist/cjs/generated/client.js +130 -0
- package/dist/cjs/generated/client.js.map +1 -0
- package/dist/cjs/generated/errors.d.ts +4 -0
- package/dist/cjs/generated/errors.js +160 -0
- package/dist/cjs/generated/errors.js.map +1 -0
- package/dist/cjs/generated/ids.d.ts +114 -0
- package/dist/cjs/generated/ids.js +47 -0
- package/dist/cjs/generated/ids.js.map +1 -0
- package/dist/cjs/generated/jobs.d.ts +10 -0
- package/dist/cjs/generated/jobs.js +24 -0
- package/dist/cjs/generated/jobs.js.map +1 -0
- package/dist/cjs/generated/ns/actions.d.ts +161 -0
- package/dist/cjs/generated/ns/actions.js +304 -0
- package/dist/cjs/generated/ns/actions.js.map +1 -0
- package/dist/cjs/generated/ns/infer.d.ts +190 -0
- package/dist/cjs/generated/ns/infer.js +253 -0
- package/dist/cjs/generated/ns/infer.js.map +1 -0
- package/dist/cjs/generated/ns/keys.d.ts +76 -0
- package/dist/cjs/generated/ns/keys.js +144 -0
- package/dist/cjs/generated/ns/keys.js.map +1 -0
- package/dist/cjs/generated/ns/limits.d.ts +22 -0
- package/dist/cjs/generated/ns/limits.js +32 -0
- package/dist/cjs/generated/ns/limits.js.map +1 -0
- package/dist/cjs/generated/ns/orgs.d.ts +38 -0
- package/dist/cjs/generated/ns/orgs.js +68 -0
- package/dist/cjs/generated/ns/orgs.js.map +1 -0
- package/dist/cjs/generated/ns/projects.d.ts +57 -0
- package/dist/cjs/generated/ns/projects.js +115 -0
- package/dist/cjs/generated/ns/projects.js.map +1 -0
- package/dist/cjs/generated/ns/render.d.ts +159 -0
- package/dist/cjs/generated/ns/render.js +299 -0
- package/dist/cjs/generated/ns/render.js.map +1 -0
- package/dist/cjs/generated/ns/requests.d.ts +36 -0
- package/dist/cjs/generated/ns/requests.js +54 -0
- package/dist/cjs/generated/ns/requests.js.map +1 -0
- package/dist/cjs/generated/ns/routines.d.ts +212 -0
- package/dist/cjs/generated/ns/routines.js +419 -0
- package/dist/cjs/generated/ns/routines.js.map +1 -0
- package/dist/cjs/generated/ns/sandboxes.d.ts +318 -0
- package/dist/cjs/generated/ns/sandboxes.js +549 -0
- package/dist/cjs/generated/ns/sandboxes.js.map +1 -0
- package/dist/cjs/generated/ns/usage.d.ts +30 -0
- package/dist/cjs/generated/ns/usage.js +49 -0
- package/dist/cjs/generated/ns/usage.js.map +1 -0
- package/dist/cjs/generated/ns/vault.d.ts +69 -0
- package/dist/cjs/generated/ns/vault.js +122 -0
- package/dist/cjs/generated/ns/vault.js.map +1 -0
- package/dist/cjs/generated/ns/vision.d.ts +376 -0
- package/dist/cjs/generated/ns/vision.js +736 -0
- package/dist/cjs/generated/ns/vision.js.map +1 -0
- package/dist/cjs/generated/ns/webhooks.d.ts +50 -0
- package/dist/cjs/generated/ns/webhooks.js +91 -0
- package/dist/cjs/generated/ns/webhooks.js.map +1 -0
- package/dist/cjs/generated/types.d.ts +4613 -0
- package/dist/cjs/generated/types.js +4 -0
- package/dist/cjs/generated/types.js.map +1 -0
- package/dist/cjs/index.d.ts +22 -0
- package/dist/cjs/index.js +81 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/webhooks.d.ts +19 -0
- package/dist/cjs/webhooks.js +85 -0
- package/dist/cjs/webhooks.js.map +1 -0
- package/dist/esm/core/client.d.ts +165 -0
- package/dist/esm/core/client.js +821 -0
- package/dist/esm/core/client.js.map +1 -0
- package/dist/esm/core/errors.d.ts +101 -0
- package/dist/esm/core/errors.js +239 -0
- package/dist/esm/core/errors.js.map +1 -0
- package/dist/esm/core/index.d.ts +12 -0
- package/dist/esm/core/index.js +15 -0
- package/dist/esm/core/index.js.map +1 -0
- package/dist/esm/core/jobs.d.ts +31 -0
- package/dist/esm/core/jobs.js +66 -0
- package/dist/esm/core/jobs.js.map +1 -0
- package/dist/esm/core/namespace.d.ts +7 -0
- package/dist/esm/core/namespace.js +9 -0
- package/dist/esm/core/namespace.js.map +1 -0
- package/dist/esm/core/op.d.ts +47 -0
- package/dist/esm/core/op.js +4 -0
- package/dist/esm/core/op.js.map +1 -0
- package/dist/esm/core/promise.d.ts +106 -0
- package/dist/esm/core/promise.js +193 -0
- package/dist/esm/core/promise.js.map +1 -0
- package/dist/esm/core/response.d.ts +54 -0
- package/dist/esm/core/response.js +86 -0
- package/dist/esm/core/response.js.map +1 -0
- package/dist/esm/core/sse.d.ts +79 -0
- package/dist/esm/core/sse.js +286 -0
- package/dist/esm/core/sse.js.map +1 -0
- package/dist/esm/core/timing.d.ts +20 -0
- package/dist/esm/core/timing.js +92 -0
- package/dist/esm/core/timing.js.map +1 -0
- package/dist/esm/core/transport.d.ts +80 -0
- package/dist/esm/core/transport.js +465 -0
- package/dist/esm/core/transport.js.map +1 -0
- package/dist/esm/core/util.d.ts +25 -0
- package/dist/esm/core/util.js +128 -0
- package/dist/esm/core/util.js.map +1 -0
- package/dist/esm/core/ws.d.ts +52 -0
- package/dist/esm/core/ws.js +175 -0
- package/dist/esm/core/ws.js.map +1 -0
- package/dist/esm/generated/client.d.ts +62 -0
- package/dist/esm/generated/client.js +126 -0
- package/dist/esm/generated/client.js.map +1 -0
- package/dist/esm/generated/errors.d.ts +4 -0
- package/dist/esm/generated/errors.js +157 -0
- package/dist/esm/generated/errors.js.map +1 -0
- package/dist/esm/generated/ids.d.ts +114 -0
- package/dist/esm/generated/ids.js +42 -0
- package/dist/esm/generated/ids.js.map +1 -0
- package/dist/esm/generated/jobs.d.ts +10 -0
- package/dist/esm/generated/jobs.js +21 -0
- package/dist/esm/generated/jobs.js.map +1 -0
- package/dist/esm/generated/ns/actions.d.ts +161 -0
- package/dist/esm/generated/ns/actions.js +300 -0
- package/dist/esm/generated/ns/actions.js.map +1 -0
- package/dist/esm/generated/ns/infer.d.ts +190 -0
- package/dist/esm/generated/ns/infer.js +249 -0
- package/dist/esm/generated/ns/infer.js.map +1 -0
- package/dist/esm/generated/ns/keys.d.ts +76 -0
- package/dist/esm/generated/ns/keys.js +140 -0
- package/dist/esm/generated/ns/keys.js.map +1 -0
- package/dist/esm/generated/ns/limits.d.ts +22 -0
- package/dist/esm/generated/ns/limits.js +28 -0
- package/dist/esm/generated/ns/limits.js.map +1 -0
- package/dist/esm/generated/ns/orgs.d.ts +38 -0
- package/dist/esm/generated/ns/orgs.js +64 -0
- package/dist/esm/generated/ns/orgs.js.map +1 -0
- package/dist/esm/generated/ns/projects.d.ts +57 -0
- package/dist/esm/generated/ns/projects.js +111 -0
- package/dist/esm/generated/ns/projects.js.map +1 -0
- package/dist/esm/generated/ns/render.d.ts +159 -0
- package/dist/esm/generated/ns/render.js +295 -0
- package/dist/esm/generated/ns/render.js.map +1 -0
- package/dist/esm/generated/ns/requests.d.ts +36 -0
- package/dist/esm/generated/ns/requests.js +50 -0
- package/dist/esm/generated/ns/requests.js.map +1 -0
- package/dist/esm/generated/ns/routines.d.ts +212 -0
- package/dist/esm/generated/ns/routines.js +415 -0
- package/dist/esm/generated/ns/routines.js.map +1 -0
- package/dist/esm/generated/ns/sandboxes.d.ts +318 -0
- package/dist/esm/generated/ns/sandboxes.js +545 -0
- package/dist/esm/generated/ns/sandboxes.js.map +1 -0
- package/dist/esm/generated/ns/usage.d.ts +30 -0
- package/dist/esm/generated/ns/usage.js +45 -0
- package/dist/esm/generated/ns/usage.js.map +1 -0
- package/dist/esm/generated/ns/vault.d.ts +69 -0
- package/dist/esm/generated/ns/vault.js +118 -0
- package/dist/esm/generated/ns/vault.js.map +1 -0
- package/dist/esm/generated/ns/vision.d.ts +376 -0
- package/dist/esm/generated/ns/vision.js +732 -0
- package/dist/esm/generated/ns/vision.js.map +1 -0
- package/dist/esm/generated/ns/webhooks.d.ts +50 -0
- package/dist/esm/generated/ns/webhooks.js +87 -0
- package/dist/esm/generated/ns/webhooks.js.map +1 -0
- package/dist/esm/generated/types.d.ts +4613 -0
- package/dist/esm/generated/types.js +3 -0
- package/dist/esm/generated/types.js.map +1 -0
- package/dist/esm/index.d.ts +22 -0
- package/dist/esm/index.js +28 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/webhooks.d.ts +19 -0
- package/dist/esm/webhooks.js +79 -0
- package/dist/esm/webhooks.js.map +1 -0
- package/package.json +97 -3
- package/src/core/client.ts +1022 -0
- package/src/core/errors.ts +296 -0
- package/src/core/index.ts +45 -0
- package/src/core/jobs.ts +94 -0
- package/src/core/namespace.ts +10 -0
- package/src/core/op.ts +53 -0
- package/src/core/promise.ts +268 -0
- package/src/core/response.ts +115 -0
- package/src/core/sse.ts +305 -0
- package/src/core/timing.ts +106 -0
- package/src/core/transport.ts +489 -0
- package/src/core/util.ts +138 -0
- package/src/core/ws.ts +215 -0
- package/src/generated/client.ts +143 -0
- package/src/generated/errors.ts +313 -0
- package/src/generated/ids.ts +47 -0
- package/src/generated/jobs.ts +25 -0
- package/src/generated/ns/actions.ts +353 -0
- package/src/generated/ns/infer.ts +332 -0
- package/src/generated/ns/keys.ts +152 -0
- package/src/generated/ns/limits.ts +35 -0
- package/src/generated/ns/orgs.ts +77 -0
- package/src/generated/ns/projects.ts +122 -0
- package/src/generated/ns/render.ts +348 -0
- package/src/generated/ns/requests.ts +61 -0
- package/src/generated/ns/routines.ts +474 -0
- package/src/generated/ns/sandboxes.ts +671 -0
- package/src/generated/ns/usage.ts +56 -0
- package/src/generated/ns/vault.ts +136 -0
- package/src/generated/ns/vision.ts +836 -0
- package/src/generated/ns/webhooks.ts +100 -0
- package/src/generated/types.ts +5131 -0
- package/src/index.ts +30 -0
- package/src/webhooks.ts +100 -0
|
@@ -0,0 +1,825 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// The core client: configuration, routing between beta-api.b3os.org and the same-host fast paths, the request
|
|
3
|
+
// pipeline (idempotency keys, retries with jittered backoff, timeouts, typed errors, Server-Timing), and the job
|
|
4
|
+
// and stream plumbing the generated namespaces call. It knows no product; src/generated/ns/* do.
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.B3OSCore = exports.DEFAULT_SOCKET_PATH = exports.DEFAULT_BASE_URL = void 0;
|
|
7
|
+
const errors_ts_1 = require("./errors.js");
|
|
8
|
+
const promise_ts_1 = require("./promise.js");
|
|
9
|
+
const response_ts_1 = require("./response.js");
|
|
10
|
+
const sse_ts_1 = require("./sse.js");
|
|
11
|
+
const transport_ts_1 = require("./transport.js");
|
|
12
|
+
const util_ts_1 = require("./util.js");
|
|
13
|
+
exports.DEFAULT_BASE_URL = "https://beta-api.b3os.org";
|
|
14
|
+
/** b3osd's Unix socket on a B3OS node (ARCHITECTURE §1). */
|
|
15
|
+
exports.DEFAULT_SOCKET_PATH = "/run/b3os/b3osd/b3osd.sock";
|
|
16
|
+
const JSON_CT = /^application\/(?:[\w.+-]+\+)?json\b/i;
|
|
17
|
+
const NO_RETRY_TIMEOUT_CODES = new Set(["request_timeout", "upstream_timeout", "scrape_timeout", "job_timed_out"]);
|
|
18
|
+
/**
|
|
19
|
+
* Codes that reject a request before any work, so even non-idempotent calls may be retried. They count only when
|
|
20
|
+
* B3OS said so in the error body, or when the status alone proves the request never got in (NEVER_REACHED_STATUSES):
|
|
21
|
+
* an intermediary's 502 or 503 page may come after the origin already ran the request.
|
|
22
|
+
*/
|
|
23
|
+
const REJECTED_BEFORE_WORK = new Set([
|
|
24
|
+
"rate_limited",
|
|
25
|
+
"concurrency_limited",
|
|
26
|
+
"ticket_limit",
|
|
27
|
+
"node_unavailable",
|
|
28
|
+
"product_unavailable",
|
|
29
|
+
"capacity_unavailable",
|
|
30
|
+
"auth_unavailable",
|
|
31
|
+
"idempotency_request_in_progress",
|
|
32
|
+
]);
|
|
33
|
+
function trimSlash(s) {
|
|
34
|
+
return s.endsWith("/") ? s.replace(/\/+$/, "") : s;
|
|
35
|
+
}
|
|
36
|
+
/** Percent-encodes what a request target cannot carry, leaving URL syntax (and existing escapes) alone. */
|
|
37
|
+
function encodeWildcard(v) {
|
|
38
|
+
const hash = v.indexOf("#");
|
|
39
|
+
const s = hash >= 0 ? v.slice(0, hash) : v;
|
|
40
|
+
return s.replace(/[^A-Za-z0-9\-._~:/?\[\]@!$&'()*+,;=%]/g, (c) => Array.from(new TextEncoder().encode(c), (b) => `%${b.toString(16).toUpperCase().padStart(2, "0")}`).join(""));
|
|
41
|
+
}
|
|
42
|
+
/** `.` or `..`, also percent-encoded (`%2e`, `.%2E`): URL parsers (WHATWG, httpx) resolve these segments. */
|
|
43
|
+
const DOT_SEGMENT = /^(?:\.|%2e){1,2}$/i;
|
|
44
|
+
/** `scheme://authority` + path + query of an absolute URL given as a wildcard value (vision.readUrl). */
|
|
45
|
+
const ABSOLUTE_URL = /^([A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#]*)([^?#]*)(.*)$/s;
|
|
46
|
+
function hasDotSegment(path) {
|
|
47
|
+
return path.split("/").some((seg) => DOT_SEGMENT.test(seg));
|
|
48
|
+
}
|
|
49
|
+
/** RFC 3986 §5.2.4 remove_dot_segments on an absolute path, treating `%2e` as `.` as WHATWG URL parsing does. */
|
|
50
|
+
function removeDotSegments(path) {
|
|
51
|
+
const segs = path.split("/");
|
|
52
|
+
const out = [];
|
|
53
|
+
for (let i = 0; i < segs.length; i++) {
|
|
54
|
+
const seg = segs[i];
|
|
55
|
+
const last = i === segs.length - 1;
|
|
56
|
+
if (i > 0 && DOT_SEGMENT.test(seg)) {
|
|
57
|
+
if (seg.replace(/%2e/gi, ".") === ".." && out.length > 1)
|
|
58
|
+
out.pop();
|
|
59
|
+
if (last)
|
|
60
|
+
out.push("");
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
out.push(seg);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return out.join("/");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A wildcard path value (a target URL, a model id that contains `/`) with dot segments resolved inside it, so
|
|
70
|
+
* they can never climb out of the operation's own path: `/v1/vision/r/https://x/../../../v1/keys` would
|
|
71
|
+
* otherwise reach `GET /v1/keys` with the API key. An absolute URL is normalized the way the target server
|
|
72
|
+
* would see it anyway; any other value with a dot segment is refused.
|
|
73
|
+
*/
|
|
74
|
+
function safeWildcard(op, name, v) {
|
|
75
|
+
const hash = v.indexOf("#");
|
|
76
|
+
let s = hash >= 0 ? v.slice(0, hash) : v;
|
|
77
|
+
const q = s.indexOf("?");
|
|
78
|
+
if (hasDotSegment(q >= 0 ? s.slice(0, q) : s)) {
|
|
79
|
+
const m = ABSOLUTE_URL.exec(s);
|
|
80
|
+
if (m)
|
|
81
|
+
s = `${m[1]}${removeDotSegments(m[2])}${m[3]}`;
|
|
82
|
+
const q2 = s.indexOf("?");
|
|
83
|
+
if (hasDotSegment(q2 >= 0 ? s.slice(0, q2) : s)) {
|
|
84
|
+
throw new TypeError(`@b3os/sdk: ${op.id}: the path parameter ${name} must not contain "." or ".." segments`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return encodeWildcard(s);
|
|
88
|
+
}
|
|
89
|
+
/** Account paths `request()` sends to the API host unless told otherwise. */
|
|
90
|
+
const EDGE_PATHS = /^\/v1\/(keys|usage|limits|orgs|projects|auth|actions\/registry)(\/|$)/;
|
|
91
|
+
function buildPath(op, values) {
|
|
92
|
+
if (!op.path.includes("{"))
|
|
93
|
+
return op.path;
|
|
94
|
+
const names = op.params ?? [];
|
|
95
|
+
let i = 0;
|
|
96
|
+
return op.path.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
97
|
+
const idx = names.indexOf(name);
|
|
98
|
+
const v = values?.[idx >= 0 ? idx : i];
|
|
99
|
+
i++;
|
|
100
|
+
if (v === undefined || v === null || v === "") {
|
|
101
|
+
throw new TypeError(`@b3os/sdk: ${op.id} needs the path parameter ${name}`);
|
|
102
|
+
}
|
|
103
|
+
const s = String(v);
|
|
104
|
+
if (name === op.wildcard)
|
|
105
|
+
return safeWildcard(op, name, s);
|
|
106
|
+
if (s === "." || s === "..") {
|
|
107
|
+
// encodeURIComponent keeps dots, and a lone ".." segment would move the request to the parent path.
|
|
108
|
+
throw new TypeError(`@b3os/sdk: ${op.id}: the path parameter ${name} cannot be "${s}"`);
|
|
109
|
+
}
|
|
110
|
+
return encodeURIComponent(s);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
function buildQuery(query, extra) {
|
|
114
|
+
let sp;
|
|
115
|
+
if (query) {
|
|
116
|
+
for (const [k, v] of Object.entries(query)) {
|
|
117
|
+
if (v === undefined || v === null)
|
|
118
|
+
continue;
|
|
119
|
+
sp ??= new URLSearchParams();
|
|
120
|
+
if (Array.isArray(v))
|
|
121
|
+
for (const x of v)
|
|
122
|
+
sp.append(k, String(x));
|
|
123
|
+
else if (v instanceof Date)
|
|
124
|
+
sp.append(k, v.toISOString());
|
|
125
|
+
else
|
|
126
|
+
sp.append(k, String(v));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (extra) {
|
|
130
|
+
sp ??= new URLSearchParams();
|
|
131
|
+
for (const [k, v] of Object.entries(extra))
|
|
132
|
+
sp.set(k, v);
|
|
133
|
+
}
|
|
134
|
+
const s = sp ? sp.toString() : "";
|
|
135
|
+
return s ? `?${s}` : "";
|
|
136
|
+
}
|
|
137
|
+
function isTerminalJob(j) {
|
|
138
|
+
return (0, util_ts_1.isObject)(j) && typeof j.status === "string" && promise_ts_1.TERMINAL_JOB_STATUSES.has(j.status);
|
|
139
|
+
}
|
|
140
|
+
function jobIdOf(j) {
|
|
141
|
+
if (typeof j === "string")
|
|
142
|
+
return j;
|
|
143
|
+
if ((0, util_ts_1.isObject)(j) && typeof j.id === "string")
|
|
144
|
+
return j.id;
|
|
145
|
+
throw new TypeError("@b3os/sdk: expected a job object or a job id");
|
|
146
|
+
}
|
|
147
|
+
function eventType(ev) {
|
|
148
|
+
return (0, util_ts_1.isObject)(ev) && typeof ev.type === "string" ? ev.type : undefined;
|
|
149
|
+
}
|
|
150
|
+
function connectRefused(err) {
|
|
151
|
+
const code = err?.code;
|
|
152
|
+
return code === "ENOENT" || code === "ECONNREFUSED" || code === "EACCES" || code === "EPERM";
|
|
153
|
+
}
|
|
154
|
+
function describeErr(err) {
|
|
155
|
+
if (err instanceof Error) {
|
|
156
|
+
const cause = err.cause;
|
|
157
|
+
const code = err.code ?? cause?.code;
|
|
158
|
+
const msg = cause?.message && cause.message !== err.message ? `${err.message} (${cause.message})` : err.message;
|
|
159
|
+
return code && !msg.includes(code) ? `${code}: ${msg}` : msg;
|
|
160
|
+
}
|
|
161
|
+
return String(err);
|
|
162
|
+
}
|
|
163
|
+
class B3OSCore {
|
|
164
|
+
apiKey;
|
|
165
|
+
baseUrl;
|
|
166
|
+
maxRetries;
|
|
167
|
+
maxRetryDelayMs;
|
|
168
|
+
timeoutMs;
|
|
169
|
+
edge;
|
|
170
|
+
node;
|
|
171
|
+
headers;
|
|
172
|
+
onResponse;
|
|
173
|
+
constructor(options = {}) {
|
|
174
|
+
this.apiKey = options.apiKey !== undefined ? options.apiKey : ((0, util_ts_1.env)("B3OS_API_KEY") ?? null);
|
|
175
|
+
const explicitBase = options.baseUrl ?? (0, util_ts_1.env)("B3OS_BASE_URL");
|
|
176
|
+
this.baseUrl = trimSlash(explicitBase ?? exports.DEFAULT_BASE_URL);
|
|
177
|
+
this.maxRetries = options.maxRetries ?? 2;
|
|
178
|
+
this.maxRetryDelayMs = options.maxRetryDelayMs ?? 60_000;
|
|
179
|
+
this.timeoutMs = options.timeoutMs;
|
|
180
|
+
this.onResponse = options.onResponse;
|
|
181
|
+
const headers = {};
|
|
182
|
+
const rt = (0, util_ts_1.runtime)();
|
|
183
|
+
if (rt === "node" || rt === "bun" || rt === "deno" || rt === "workerd") {
|
|
184
|
+
headers["user-agent"] = `b3os-sdk-ts/${util_ts_1.SDK_VERSION} ${(0, util_ts_1.runtimeLabel)()}`;
|
|
185
|
+
}
|
|
186
|
+
for (const [k, v] of Object.entries(options.headers ?? {}))
|
|
187
|
+
headers[k.toLowerCase()] = v;
|
|
188
|
+
this.headers = headers;
|
|
189
|
+
const fetchT = new transport_ts_1.FetchTransport(this.baseUrl, options.fetch);
|
|
190
|
+
this.edge = { kind: "edge", transport: fetchT, base: this.baseUrl, auth: true, auto: false };
|
|
191
|
+
const pref = options.transport ?? (0, util_ts_1.env)("B3OS_TRANSPORT") ?? "auto";
|
|
192
|
+
const sockEnv = (0, util_ts_1.env)("B3OS_SOCKET");
|
|
193
|
+
const sockDisabled = options.socketPath === false || sockEnv === "0" || sockEnv === "off";
|
|
194
|
+
const nodeUrl = options.nodeUrl !== undefined ? options.nodeUrl : ((0, util_ts_1.env)("B3OS_API_URL") ?? null);
|
|
195
|
+
let node = this.edge;
|
|
196
|
+
if (pref !== "http") {
|
|
197
|
+
const explicitSock = typeof options.socketPath === "string" ? options.socketPath : sockDisabled ? undefined : sockEnv;
|
|
198
|
+
if (explicitSock) {
|
|
199
|
+
node = this.udsRoute(explicitSock, false, options.fetch);
|
|
200
|
+
}
|
|
201
|
+
else if (nodeUrl) {
|
|
202
|
+
const base = trimSlash(nodeUrl);
|
|
203
|
+
// Plain HTTP to the node (inside a sandbox) goes through node:http keep-alive on Node, unless the caller
|
|
204
|
+
// supplied its own fetch.
|
|
205
|
+
const useNodeHttp = !options.fetch && base.startsWith("http:") && transport_ts_1.NodeHttpTransport.available();
|
|
206
|
+
node = {
|
|
207
|
+
kind: "node-http",
|
|
208
|
+
transport: useNodeHttp ? new transport_ts_1.NodeHttpTransport({ baseUrl: base }) : new transport_ts_1.FetchTransport(base, options.fetch),
|
|
209
|
+
base,
|
|
210
|
+
auth: false,
|
|
211
|
+
auto: false,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
else if (!this.apiKey &&
|
|
215
|
+
!explicitBase &&
|
|
216
|
+
!sockDisabled &&
|
|
217
|
+
options.socketPath !== null &&
|
|
218
|
+
(0, transport_ts_1.socketExists)(exports.DEFAULT_SOCKET_PATH)) {
|
|
219
|
+
// Only without a key: the socket acts as the uid's principal, and silently mixing it with the key's
|
|
220
|
+
// principal (whoami says org A, listSandboxes shows org B) is worse than the network hop.
|
|
221
|
+
node = this.udsRoute(exports.DEFAULT_SOCKET_PATH, true, options.fetch);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
this.node = node;
|
|
225
|
+
}
|
|
226
|
+
udsRoute(path, auto, fetchFn) {
|
|
227
|
+
const rt = (0, util_ts_1.runtime)();
|
|
228
|
+
if (rt === "bun") {
|
|
229
|
+
return {
|
|
230
|
+
kind: "uds",
|
|
231
|
+
transport: new transport_ts_1.FetchTransport("http://b3osd", fetchFn, path),
|
|
232
|
+
base: "http://b3osd",
|
|
233
|
+
auth: false,
|
|
234
|
+
auto,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
if (!transport_ts_1.NodeHttpTransport.available()) {
|
|
238
|
+
throw new Error(`@b3os/sdk: the Unix socket ${path} needs Node or Bun; set B3OS_TRANSPORT=http on ${rt}`);
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
kind: "uds",
|
|
242
|
+
transport: new transport_ts_1.NodeHttpTransport({ socketPath: path }),
|
|
243
|
+
base: "http://b3osd",
|
|
244
|
+
auth: false,
|
|
245
|
+
auto,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/** Where node-served and edge-served operations go (`unix:/run/b3os/b3osd/b3osd.sock`, a URL). */
|
|
249
|
+
get routes() {
|
|
250
|
+
return { node: this.node.transport.label, edge: this.edge.transport.label, nodeKind: this.node.kind };
|
|
251
|
+
}
|
|
252
|
+
/** Closes pooled connections (the Unix socket agent). Optional; idle sockets do not keep the process alive. */
|
|
253
|
+
close() {
|
|
254
|
+
this.node.transport.close?.();
|
|
255
|
+
if (this.edge !== this.node)
|
|
256
|
+
this.edge.transport.close?.();
|
|
257
|
+
}
|
|
258
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
259
|
+
// The request pipeline
|
|
260
|
+
headersFor(route, op, o, accept) {
|
|
261
|
+
const h = { ...this.headers, accept };
|
|
262
|
+
if (route.auth && this.apiKey)
|
|
263
|
+
h.authorization = `Bearer ${this.apiKey}`;
|
|
264
|
+
if (o.traceparent)
|
|
265
|
+
h.traceparent = o.traceparent;
|
|
266
|
+
if (o.headers)
|
|
267
|
+
for (const [k, v] of Object.entries(o.headers))
|
|
268
|
+
h[k.toLowerCase()] = v;
|
|
269
|
+
void op;
|
|
270
|
+
return h;
|
|
271
|
+
}
|
|
272
|
+
encodeBody(op, args, h) {
|
|
273
|
+
const b = args.body;
|
|
274
|
+
if (b === undefined)
|
|
275
|
+
return undefined;
|
|
276
|
+
const kind = args.bodyType ?? op.body ?? "json";
|
|
277
|
+
if (kind === "json") {
|
|
278
|
+
h["content-type"] ??= "application/json";
|
|
279
|
+
return JSON.stringify(b);
|
|
280
|
+
}
|
|
281
|
+
if (kind === "yaml") {
|
|
282
|
+
h["content-type"] ??= "application/yaml";
|
|
283
|
+
return String(b);
|
|
284
|
+
}
|
|
285
|
+
if (kind === "form") {
|
|
286
|
+
h["content-type"] ??= "application/x-www-form-urlencoded";
|
|
287
|
+
return new URLSearchParams(b).toString();
|
|
288
|
+
}
|
|
289
|
+
if (h["content-type"] === undefined) {
|
|
290
|
+
h["content-type"] =
|
|
291
|
+
op.contentType ??
|
|
292
|
+
(typeof Blob !== "undefined" && b instanceof Blob && b.type ? b.type : "application/octet-stream");
|
|
293
|
+
}
|
|
294
|
+
if (typeof b === "string" || b instanceof Uint8Array || b instanceof ArrayBuffer)
|
|
295
|
+
return b;
|
|
296
|
+
if (typeof Blob !== "undefined" && b instanceof Blob)
|
|
297
|
+
return b;
|
|
298
|
+
if (typeof ReadableStream !== "undefined" && b instanceof ReadableStream)
|
|
299
|
+
return b;
|
|
300
|
+
if (ArrayBuffer.isView(b))
|
|
301
|
+
return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
|
|
302
|
+
throw new TypeError(`@b3os/sdk: ${op.id} takes a string, Uint8Array, ArrayBuffer, Blob or ReadableStream body`);
|
|
303
|
+
}
|
|
304
|
+
hint(route, op, err) {
|
|
305
|
+
if (err.code === "edge_only") {
|
|
306
|
+
return this.apiKey
|
|
307
|
+
? `${op.id} is served by ${this.baseUrl}`
|
|
308
|
+
: `${op.id} is served by ${this.baseUrl}; set B3OS_API_KEY (or pass apiKey) so the SDK can send it there`;
|
|
309
|
+
}
|
|
310
|
+
if (err.status === 401 && route.auth && !this.apiKey) {
|
|
311
|
+
return "No API key is configured: set B3OS_API_KEY or pass apiKey";
|
|
312
|
+
}
|
|
313
|
+
if (err.status === 403 && err.reason === "scope" && route.kind === "uds") {
|
|
314
|
+
return ("Over the node's Unix socket this process acts as the local principal its uid maps to in b3osd.toml " +
|
|
315
|
+
"([auth.local_peers], else the read-only [auth.local_default]); set B3OS_TRANSPORT=http to use your API key");
|
|
316
|
+
}
|
|
317
|
+
return undefined;
|
|
318
|
+
}
|
|
319
|
+
/** Sends one operation with retries. Resolves with a 2xx (or 101) response whose body is still unread. */
|
|
320
|
+
async send(op, args, o, x) {
|
|
321
|
+
const method = op.method;
|
|
322
|
+
const pathStr = buildPath(op, args.path);
|
|
323
|
+
const query = buildQuery(args.query, x.extraQuery);
|
|
324
|
+
let idemKey = o.idempotencyKey;
|
|
325
|
+
if (!idemKey && op.idem && method !== "GET")
|
|
326
|
+
idemKey = (0, util_ts_1.uuid)();
|
|
327
|
+
const streamBody = typeof ReadableStream !== "undefined" && args.body instanceof ReadableStream;
|
|
328
|
+
const retrySafe = !streamBody && (method === "GET" || method === "HEAD" || method === "PUT" || method === "DELETE" || !!idemKey);
|
|
329
|
+
const maxRetries = streamBody ? 0 : (o.maxRetries ?? this.maxRetries);
|
|
330
|
+
const perAttempt = o.timeoutMs ?? this.timeoutMs ?? (x.sse ? 30_000 : Math.min(op.timeoutMs, 65_000) + 5_000);
|
|
331
|
+
let route = op.edge ? this.edge : this.node;
|
|
332
|
+
let attempt = 0;
|
|
333
|
+
for (;;) {
|
|
334
|
+
const headers = this.headersFor(route, op, o, x.accept);
|
|
335
|
+
if (idemKey)
|
|
336
|
+
headers["idempotency-key"] = idemKey;
|
|
337
|
+
if (op.headerParams && args.headerParams) {
|
|
338
|
+
for (const [k, name] of Object.entries(op.headerParams)) {
|
|
339
|
+
const v = args.headerParams[k];
|
|
340
|
+
if (v !== undefined && v !== null)
|
|
341
|
+
headers[name.toLowerCase()] = String(v);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const body = this.encodeBody(op, args, headers);
|
|
345
|
+
const path = pathStr + query;
|
|
346
|
+
const url = route.base + path;
|
|
347
|
+
if (o.signal?.aborted)
|
|
348
|
+
throw new errors_ts_1.B3OSAbortError({ operationId: op.id, cause: o.signal.reason });
|
|
349
|
+
const t0 = performance.now();
|
|
350
|
+
let res;
|
|
351
|
+
try {
|
|
352
|
+
// The transport enforces the per-attempt timeout (for streams: until the response head) and the signal.
|
|
353
|
+
res = await route.transport.send({
|
|
354
|
+
method,
|
|
355
|
+
url,
|
|
356
|
+
path,
|
|
357
|
+
headers,
|
|
358
|
+
body,
|
|
359
|
+
signal: o.signal,
|
|
360
|
+
timeoutMs: perAttempt,
|
|
361
|
+
stream: !!x.sse,
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
catch (cause) {
|
|
365
|
+
if (o.signal?.aborted)
|
|
366
|
+
throw new errors_ts_1.B3OSAbortError({ operationId: op.id, cause });
|
|
367
|
+
const timedOut = cause instanceof transport_ts_1.TransportTimeout;
|
|
368
|
+
if (route.auto && connectRefused(cause) && !timedOut) {
|
|
369
|
+
// The node socket exists but refuses us (permissions, stale socket): use the API from now on.
|
|
370
|
+
this.node = this.edge;
|
|
371
|
+
route = this.edge;
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
const err = timedOut
|
|
375
|
+
? new errors_ts_1.B3OSTimeoutError({
|
|
376
|
+
detail: `${op.id} did not answer within ${perAttempt} ms (${route.transport.label})`,
|
|
377
|
+
operationId: op.id,
|
|
378
|
+
cause,
|
|
379
|
+
})
|
|
380
|
+
: new errors_ts_1.B3OSConnectionError({
|
|
381
|
+
detail: `Could not reach ${route.transport.label}: ${describeErr(cause)}`,
|
|
382
|
+
operationId: op.id,
|
|
383
|
+
cause,
|
|
384
|
+
});
|
|
385
|
+
// Timeouts are not retried: the budget is spent. A refused connection never reached the server.
|
|
386
|
+
if (!timedOut && attempt < maxRetries && (retrySafe || connectRefused(cause))) {
|
|
387
|
+
await (0, util_ts_1.sleep)((0, util_ts_1.backoffMs)(attempt), o.signal).catch(() => { });
|
|
388
|
+
attempt++;
|
|
389
|
+
continue;
|
|
390
|
+
}
|
|
391
|
+
throw err;
|
|
392
|
+
}
|
|
393
|
+
const elapsed = performance.now() - t0;
|
|
394
|
+
const info = new response_ts_1.ResponseInfo({
|
|
395
|
+
operationId: op.id,
|
|
396
|
+
method,
|
|
397
|
+
url: route.kind === "uds" ? `${route.transport.label}${path}` : url,
|
|
398
|
+
status: res.status,
|
|
399
|
+
headers: res.headers,
|
|
400
|
+
transport: route.transport.kind,
|
|
401
|
+
attempts: attempt + 1,
|
|
402
|
+
elapsedMs: elapsed,
|
|
403
|
+
idempotencyKey: idemKey,
|
|
404
|
+
});
|
|
405
|
+
try {
|
|
406
|
+
this.onResponse?.(info);
|
|
407
|
+
}
|
|
408
|
+
catch {
|
|
409
|
+
// A logging hook must never break the call.
|
|
410
|
+
}
|
|
411
|
+
if ((res.status >= 200 && res.status < 300) || res.status === 101) {
|
|
412
|
+
return { res, info };
|
|
413
|
+
}
|
|
414
|
+
// An error answer: read it, decide whether to retry.
|
|
415
|
+
let text = "";
|
|
416
|
+
try {
|
|
417
|
+
text = await res.text();
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
text = "";
|
|
421
|
+
}
|
|
422
|
+
const ct = res.headers.get("content-type");
|
|
423
|
+
const parsed = (0, errors_ts_1.parseErrorBody)(res.status, ct, text);
|
|
424
|
+
const retryAfterMs = (0, util_ts_1.parseRetryAfter)(res.headers.get("retry-after")) ??
|
|
425
|
+
(parsed.retryAfterS !== undefined ? parsed.retryAfterS * 1000 : null);
|
|
426
|
+
const err0 = new errors_ts_1.B3OSError({
|
|
427
|
+
code: parsed.code,
|
|
428
|
+
status: res.status,
|
|
429
|
+
title: parsed.title,
|
|
430
|
+
detail: parsed.detail,
|
|
431
|
+
type: parsed.type,
|
|
432
|
+
requestId: parsed.instance ?? res.headers.get("x-request-id"),
|
|
433
|
+
errors: parsed.errors,
|
|
434
|
+
problem: parsed.problem,
|
|
435
|
+
headers: res.headers,
|
|
436
|
+
timing: info.timing,
|
|
437
|
+
retryAfterMs,
|
|
438
|
+
operationId: op.id,
|
|
439
|
+
});
|
|
440
|
+
const hint = this.hint(route, op, err0);
|
|
441
|
+
const err = hint
|
|
442
|
+
? new errors_ts_1.B3OSError({
|
|
443
|
+
code: err0.code,
|
|
444
|
+
status: err0.status,
|
|
445
|
+
title: err0.title,
|
|
446
|
+
detail: err0.detail,
|
|
447
|
+
type: err0.type,
|
|
448
|
+
requestId: err0.requestId,
|
|
449
|
+
errors: err0.errors,
|
|
450
|
+
problem: err0.problem,
|
|
451
|
+
headers: err0.headers,
|
|
452
|
+
timing: err0.timing,
|
|
453
|
+
retryAfterMs,
|
|
454
|
+
operationId: op.id,
|
|
455
|
+
hint,
|
|
456
|
+
})
|
|
457
|
+
: err0;
|
|
458
|
+
const rejectedBeforeWork = REJECTED_BEFORE_WORK.has(err.code) && (!parsed.codeFromStatus || errors_ts_1.NEVER_REACHED_STATUSES.has(res.status));
|
|
459
|
+
const retryable = rejectedBeforeWork ||
|
|
460
|
+
(retrySafe && err.retryable && (err.status ?? 0) >= 500 && !NO_RETRY_TIMEOUT_CODES.has(err.code));
|
|
461
|
+
if (attempt < maxRetries && retryable) {
|
|
462
|
+
const delay = retryAfterMs ?? (0, util_ts_1.backoffMs)(attempt);
|
|
463
|
+
if (delay <= this.maxRetryDelayMs) {
|
|
464
|
+
await (0, util_ts_1.sleep)(delay + Math.random() * Math.min(250, delay * 0.1), o.signal).catch(() => { });
|
|
465
|
+
if (o.signal?.aborted)
|
|
466
|
+
throw new errors_ts_1.B3OSAbortError({ operationId: op.id });
|
|
467
|
+
attempt++;
|
|
468
|
+
continue;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
throw err;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
async readBody(sent, op, expect, signal) {
|
|
475
|
+
const { res } = sent;
|
|
476
|
+
try {
|
|
477
|
+
if (res.status === 204 || res.status === 101 || op.method === "HEAD") {
|
|
478
|
+
res.cancel();
|
|
479
|
+
return undefined;
|
|
480
|
+
}
|
|
481
|
+
const ct = res.headers.get("content-type") ?? "";
|
|
482
|
+
const isJson = JSON_CT.test(ct);
|
|
483
|
+
if (expect === "bytes" || (expect === "auto" && !isJson && !ct.startsWith("text/"))) {
|
|
484
|
+
return await res.bytes();
|
|
485
|
+
}
|
|
486
|
+
const text = await res.text();
|
|
487
|
+
if (expect === "text" || (expect === "auto" && !isJson))
|
|
488
|
+
return text;
|
|
489
|
+
if (text === "")
|
|
490
|
+
return undefined;
|
|
491
|
+
try {
|
|
492
|
+
return JSON.parse(text);
|
|
493
|
+
}
|
|
494
|
+
catch (cause) {
|
|
495
|
+
throw new errors_ts_1.B3OSError({
|
|
496
|
+
code: "invalid_response",
|
|
497
|
+
status: res.status,
|
|
498
|
+
detail: `${op.id} answered ${res.status} with a body that is not JSON (${ct || "no content type"})`,
|
|
499
|
+
requestId: res.headers.get("x-request-id"),
|
|
500
|
+
headers: res.headers,
|
|
501
|
+
operationId: op.id,
|
|
502
|
+
cause,
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
catch (e) {
|
|
507
|
+
if (e instanceof errors_ts_1.B3OSError)
|
|
508
|
+
throw e;
|
|
509
|
+
if (e instanceof transport_ts_1.TransportTimeout) {
|
|
510
|
+
throw new errors_ts_1.B3OSTimeoutError({
|
|
511
|
+
detail: `${op.id}: the response body did not arrive in time`,
|
|
512
|
+
operationId: op.id,
|
|
513
|
+
cause: e,
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
if (signal?.aborted)
|
|
517
|
+
throw new errors_ts_1.B3OSAbortError({ operationId: op.id, cause: e });
|
|
518
|
+
throw new errors_ts_1.B3OSConnectionError({
|
|
519
|
+
detail: `The response body of ${op.id} broke: ${describeErr(e)}`,
|
|
520
|
+
operationId: op.id,
|
|
521
|
+
cause: e,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
async exec(op, args, o, accept = "application/json", expect = "auto", extraQuery) {
|
|
526
|
+
const sent = await this.send(op, args, o, { accept, extraQuery });
|
|
527
|
+
const data = (await this.readBody(sent, op, expect, o.signal));
|
|
528
|
+
(0, response_ts_1.remember)(data, sent.info);
|
|
529
|
+
return { data, response: sent.info };
|
|
530
|
+
}
|
|
531
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
532
|
+
// What the generated namespaces call
|
|
533
|
+
/** @internal One request, parsed by content type. */
|
|
534
|
+
_call(op, args, options = {}, accept, expect = "auto") {
|
|
535
|
+
return new promise_ts_1.APIPromise(this.exec(op, args, options, accept ?? "application/json", expect));
|
|
536
|
+
}
|
|
537
|
+
/** @internal A list operation (cursor pagination). */
|
|
538
|
+
_list(op, args, options = {}) {
|
|
539
|
+
const next = (cursor) => this._call(op, { ...args, query: { ...(args.query ?? {}), cursor } }, options);
|
|
540
|
+
return new promise_ts_1.ListPromise(this.exec(op, args, options), next);
|
|
541
|
+
}
|
|
542
|
+
/** @internal A GET event stream (job events, logs), resumed with Last-Event-ID. */
|
|
543
|
+
_stream(op, args, options = {}, behavior = {}) {
|
|
544
|
+
return new sse_ts_1.EventStream(this.streamOptions(op, args, options, behavior));
|
|
545
|
+
}
|
|
546
|
+
streamOptions(op, args, options, behavior) {
|
|
547
|
+
return {
|
|
548
|
+
operationId: op.id,
|
|
549
|
+
resumable: true,
|
|
550
|
+
reconnectOnEnd: behavior.reconnectOnEnd ?? false,
|
|
551
|
+
idleTimeoutMs: options.idleTimeoutMs,
|
|
552
|
+
maxReconnects: options.maxReconnects,
|
|
553
|
+
signal: options.signal,
|
|
554
|
+
isTerminal: behavior.terminal ? (ev) => behavior.terminal?.(ev) ?? false : undefined,
|
|
555
|
+
open: async (ctx) => {
|
|
556
|
+
const lastId = ctx.lastEventId ?? (ctx.attempt === 0 ? options.lastEventId : undefined);
|
|
557
|
+
const headers = { ...(options.headers ?? {}) };
|
|
558
|
+
if (lastId !== undefined)
|
|
559
|
+
headers["last-event-id"] = lastId;
|
|
560
|
+
const sent = await this.send(op, args, { ...options, headers, signal: ctx.signal, maxRetries: ctx.attempt === 0 ? options.maxRetries : 0 }, { accept: "text/event-stream", sse: true });
|
|
561
|
+
return this.expectEventStream(sent, op);
|
|
562
|
+
},
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
expectEventStream(sent, op) {
|
|
566
|
+
const res = sent.res;
|
|
567
|
+
const ct = res.headers.get("content-type") ?? "";
|
|
568
|
+
if (!ct.startsWith("text/event-stream")) {
|
|
569
|
+
res.cancel();
|
|
570
|
+
throw new errors_ts_1.B3OSError({
|
|
571
|
+
code: "invalid_response",
|
|
572
|
+
status: res.status,
|
|
573
|
+
detail: `${op.id} answered ${res.status} with ${ct || "no content type"} instead of an event stream`,
|
|
574
|
+
requestId: sent.info.requestId,
|
|
575
|
+
operationId: op.id,
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
return res;
|
|
579
|
+
}
|
|
580
|
+
/** @internal An SSE response to a POST (exec output, chat chunks): not resumable. */
|
|
581
|
+
_postStream(op, args, options = {}, behavior = {}) {
|
|
582
|
+
return new sse_ts_1.EventStream({
|
|
583
|
+
operationId: op.id,
|
|
584
|
+
resumable: false,
|
|
585
|
+
doneSentinel: behavior.doneSentinel,
|
|
586
|
+
idleTimeoutMs: options.idleTimeoutMs,
|
|
587
|
+
signal: options.signal,
|
|
588
|
+
isTerminal: behavior.terminal ? (ev) => behavior.terminal?.(ev) ?? false : undefined,
|
|
589
|
+
open: async (ctx) => {
|
|
590
|
+
const sent = await this.send(op, args, { ...options, signal: ctx.signal }, { accept: "text/event-stream", sse: true, extraQuery: behavior.extraQuery });
|
|
591
|
+
return this.expectEventStream(sent, op);
|
|
592
|
+
},
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
/** @internal A job-creating operation (`x-b3os-job`). */
|
|
596
|
+
_job(op, args, options = {}) {
|
|
597
|
+
const ops = op.job;
|
|
598
|
+
if (!ops)
|
|
599
|
+
throw new Error(`@b3os/sdk: ${op.id} is not a job operation`);
|
|
600
|
+
// One idempotency key for every request that creates this job, whatever the mode.
|
|
601
|
+
const o = op.idem ? { ...options, idempotencyKey: options.idempotencyKey ?? (0, util_ts_1.uuid)() } : options;
|
|
602
|
+
const runner = {
|
|
603
|
+
create: () => this.exec(op, args, o),
|
|
604
|
+
createAndWait: async (w) => {
|
|
605
|
+
const deadline = Date.now() + (w.timeoutMs ?? ops.events.timeoutMs);
|
|
606
|
+
const waitS = Math.max(0, Math.min(60, Math.floor((deadline - Date.now()) / 1000)));
|
|
607
|
+
const first = await this.exec(op, args, { ...o, signal: w.signal ?? o.signal }, "application/json", "auto", {
|
|
608
|
+
wait: String(waitS),
|
|
609
|
+
});
|
|
610
|
+
const data = await this.waitJob(ops, first.data, { ...w, timeoutMs: deadline - Date.now() });
|
|
611
|
+
return { data, response: first.response };
|
|
612
|
+
},
|
|
613
|
+
createAndStream: (so) => this.createStream(op, args, o, so),
|
|
614
|
+
waitFor: (job, w) => this.waitJob(ops, job, w),
|
|
615
|
+
eventsFor: (created, so) => this.jobEventStream(ops, created, so),
|
|
616
|
+
};
|
|
617
|
+
return new promise_ts_1.JobPromise(runner);
|
|
618
|
+
}
|
|
619
|
+
createStream(op, args, o, so) {
|
|
620
|
+
const ops = op.job;
|
|
621
|
+
return new promise_ts_1.JobEventStream({
|
|
622
|
+
operationId: op.id,
|
|
623
|
+
resumable: true,
|
|
624
|
+
reconnectOnEnd: true,
|
|
625
|
+
idleTimeoutMs: so.idleTimeoutMs,
|
|
626
|
+
maxReconnects: so.maxReconnects,
|
|
627
|
+
signal: so.signal ?? o.signal,
|
|
628
|
+
isTerminal: (ev) => promise_ts_1.TERMINAL_JOB_EVENTS.has(eventType(ev) ?? ""),
|
|
629
|
+
open: async (ctx) => {
|
|
630
|
+
if (ctx.attempt === 0) {
|
|
631
|
+
const sent = await this.send(op, args, { ...o, headers: { ...o.headers, ...so.headers }, signal: ctx.signal }, {
|
|
632
|
+
accept: "text/event-stream",
|
|
633
|
+
sse: true,
|
|
634
|
+
});
|
|
635
|
+
return this.expectEventStream(sent, op);
|
|
636
|
+
}
|
|
637
|
+
const jobId = (0, util_ts_1.isObject)(ctx.lastEvent) && typeof ctx.lastEvent.job_id === "string" ? ctx.lastEvent.job_id : null;
|
|
638
|
+
if (!jobId) {
|
|
639
|
+
throw new errors_ts_1.B3OSError({
|
|
640
|
+
code: "stream_interrupted",
|
|
641
|
+
detail: `${op.id}: the stream broke before the first event, so the job id is unknown`,
|
|
642
|
+
operationId: op.id,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
const headers = { ...(so.headers ?? {}) };
|
|
646
|
+
if (ctx.lastEventId !== undefined)
|
|
647
|
+
headers["last-event-id"] = ctx.lastEventId;
|
|
648
|
+
const sent = await this.send(ops.events, { path: [jobId] }, { headers, signal: ctx.signal, maxRetries: 0 }, { accept: "text/event-stream", sse: true });
|
|
649
|
+
return this.expectEventStream(sent, ops.events);
|
|
650
|
+
},
|
|
651
|
+
}, (terminal) => this.finalJobFromEvent(ops, terminal));
|
|
652
|
+
}
|
|
653
|
+
async finalJobFromEvent(ops, ev) {
|
|
654
|
+
if ((0, util_ts_1.isObject)(ev) && (0, util_ts_1.isObject)(ev.job) && isTerminalJob(ev.job))
|
|
655
|
+
return ev.job;
|
|
656
|
+
const id = (0, util_ts_1.isObject)(ev) && typeof ev.job_id === "string" ? ev.job_id : undefined;
|
|
657
|
+
if (!id)
|
|
658
|
+
throw new Error("@b3os/sdk: terminal event without a job");
|
|
659
|
+
return (await this.exec(ops.get, { path: [id] }, {})).data;
|
|
660
|
+
}
|
|
661
|
+
jobEventStream(ops, jobOrId, so) {
|
|
662
|
+
return new promise_ts_1.JobEventStream({
|
|
663
|
+
operationId: ops.events.id,
|
|
664
|
+
resumable: true,
|
|
665
|
+
reconnectOnEnd: true,
|
|
666
|
+
idleTimeoutMs: so.idleTimeoutMs,
|
|
667
|
+
maxReconnects: so.maxReconnects,
|
|
668
|
+
signal: so.signal,
|
|
669
|
+
isTerminal: (ev) => promise_ts_1.TERMINAL_JOB_EVENTS.has(eventType(ev) ?? ""),
|
|
670
|
+
open: async (ctx) => {
|
|
671
|
+
const id = jobIdOf(await jobOrId);
|
|
672
|
+
const headers = { ...(so.headers ?? {}) };
|
|
673
|
+
const lastId = ctx.lastEventId ?? (ctx.attempt === 0 ? so.lastEventId : undefined);
|
|
674
|
+
if (lastId !== undefined)
|
|
675
|
+
headers["last-event-id"] = lastId;
|
|
676
|
+
const sent = await this.send(ops.events, { path: [id] }, { headers, signal: ctx.signal, maxRetries: ctx.attempt === 0 ? undefined : 0 }, { accept: "text/event-stream", sse: true });
|
|
677
|
+
return this.expectEventStream(sent, ops.events);
|
|
678
|
+
},
|
|
679
|
+
}, (terminal) => this.finalJobFromEvent(ops, terminal));
|
|
680
|
+
}
|
|
681
|
+
finishJob(job, w) {
|
|
682
|
+
const j = job;
|
|
683
|
+
if (j.status === "succeeded" || w.throwOnFailure === false)
|
|
684
|
+
return job;
|
|
685
|
+
const e = (0, util_ts_1.isObject)(j.error) ? j.error : {};
|
|
686
|
+
const code = typeof e.code === "string" ? e.code : j.status === "canceled" ? "job_canceled" : "internal";
|
|
687
|
+
throw new errors_ts_1.B3OSJobError(job, {
|
|
688
|
+
code,
|
|
689
|
+
status: typeof e.status === "number" ? e.status : null,
|
|
690
|
+
title: typeof e.title === "string" ? e.title : undefined,
|
|
691
|
+
detail: typeof e.detail === "string" ? e.detail : `${j.object} ${j.id} ${j.status}`,
|
|
692
|
+
requestId: typeof e.instance === "string" ? e.instance : null,
|
|
693
|
+
problem: (0, util_ts_1.isObject)(j.error) ? j.error : null,
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
/** @internal Waits until a job is terminal: its event stream first, polling as the fallback. */
|
|
697
|
+
async waitJob(ops, jobOrId, w = {}) {
|
|
698
|
+
if (typeof jobOrId !== "string" && isTerminalJob(jobOrId))
|
|
699
|
+
return this.finishJob(jobOrId, w);
|
|
700
|
+
const id = jobIdOf(jobOrId);
|
|
701
|
+
const deadline = Date.now() + (w.timeoutMs ?? ops.events.timeoutMs);
|
|
702
|
+
const ac = new AbortController();
|
|
703
|
+
const onAbort = () => ac.abort(w.signal?.reason);
|
|
704
|
+
w.signal?.addEventListener("abort", onAbort, { once: true });
|
|
705
|
+
const timer = setTimeout(() => ac.abort(new Error("deadline")), Math.max(0, deadline - Date.now()));
|
|
706
|
+
let polling = false;
|
|
707
|
+
let pollAttempt = 0;
|
|
708
|
+
try {
|
|
709
|
+
for (;;) {
|
|
710
|
+
if (w.signal?.aborted)
|
|
711
|
+
throw new errors_ts_1.B3OSAbortError({ operationId: ops.get.id });
|
|
712
|
+
if (Date.now() >= deadline)
|
|
713
|
+
break;
|
|
714
|
+
if (!polling) {
|
|
715
|
+
try {
|
|
716
|
+
const stream = this.jobEventStream(ops, id, { signal: ac.signal });
|
|
717
|
+
for await (const ev of stream) {
|
|
718
|
+
w.onEvent?.(ev);
|
|
719
|
+
if (promise_ts_1.TERMINAL_JOB_EVENTS.has(eventType(ev) ?? "")) {
|
|
720
|
+
return this.finishJob(await this.finalJobFromEvent(ops, ev), w);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
catch (e) {
|
|
725
|
+
if (w.signal?.aborted)
|
|
726
|
+
throw new errors_ts_1.B3OSAbortError({ operationId: ops.events.id, cause: e });
|
|
727
|
+
if (ac.signal.aborted)
|
|
728
|
+
break;
|
|
729
|
+
if (!(e instanceof errors_ts_1.B3OSError))
|
|
730
|
+
throw e;
|
|
731
|
+
if (e.code === "route_not_found" ||
|
|
732
|
+
e.code === "not_implemented" ||
|
|
733
|
+
e.code === "invalid_response" ||
|
|
734
|
+
e.status === 405 ||
|
|
735
|
+
e.status === 406) {
|
|
736
|
+
// No usable events operation on this deployment: poll the job instead.
|
|
737
|
+
polling = true;
|
|
738
|
+
}
|
|
739
|
+
else if (e.status === 401 || e.status === 403 || e.status === 404 || e.status === 410) {
|
|
740
|
+
throw e;
|
|
741
|
+
}
|
|
742
|
+
else if (!e.retryable && e.code !== "stream_interrupted") {
|
|
743
|
+
throw e;
|
|
744
|
+
}
|
|
745
|
+
// Otherwise transient: check the job, then reconnect.
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
const cur = await this.exec(ops.get, { path: [id] }, { signal: ac.signal }).catch((e) => {
|
|
749
|
+
if (ac.signal.aborted && !w.signal?.aborted)
|
|
750
|
+
return null;
|
|
751
|
+
throw e;
|
|
752
|
+
});
|
|
753
|
+
if (cur === null)
|
|
754
|
+
break;
|
|
755
|
+
if (isTerminalJob(cur.data))
|
|
756
|
+
return this.finishJob(cur.data, w);
|
|
757
|
+
const ra = (0, util_ts_1.parseRetryAfter)(cur.response.headers.get("retry-after"));
|
|
758
|
+
await (0, util_ts_1.sleep)(Math.min(Math.max(0, deadline - Date.now()), ra ?? (0, util_ts_1.backoffMs)(pollAttempt++, 1000, 5000)), ac.signal).catch(() => { });
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
finally {
|
|
762
|
+
clearTimeout(timer);
|
|
763
|
+
w.signal?.removeEventListener("abort", onAbort);
|
|
764
|
+
}
|
|
765
|
+
if (w.signal?.aborted)
|
|
766
|
+
throw new errors_ts_1.B3OSAbortError({ operationId: ops.get.id });
|
|
767
|
+
throw new errors_ts_1.B3OSTimeoutError({
|
|
768
|
+
detail: `${id} was not finished after ${w.timeoutMs ?? ops.events.timeoutMs} ms; it keeps running on the server`,
|
|
769
|
+
operationId: ops.get.id,
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
/** @internal Events of an existing job. */
|
|
773
|
+
_jobEvents(ops, job, so = {}) {
|
|
774
|
+
return this.jobEventStream(ops, job, so);
|
|
775
|
+
}
|
|
776
|
+
/** @internal Raw send for helpers that need the response (WebSocket tickets, downloads). */
|
|
777
|
+
_send(op, args, options, accept) {
|
|
778
|
+
return this.send(op, args, options, { accept });
|
|
779
|
+
}
|
|
780
|
+
/** @internal The route an operation would use (helpers that open WebSockets need the base URL). */
|
|
781
|
+
_routeFor(op) {
|
|
782
|
+
const r = op.edge ? this.edge : this.node;
|
|
783
|
+
return { base: r.base, kind: r.kind, auth: r.auth };
|
|
784
|
+
}
|
|
785
|
+
/** @internal Whether a WebSocket can take the operation's route (not over the Unix socket). */
|
|
786
|
+
_wsRoute(op) {
|
|
787
|
+
const r = op.edge ? this.edge : this.node;
|
|
788
|
+
if (r.kind !== "uds")
|
|
789
|
+
return { base: r.base, kind: r.kind };
|
|
790
|
+
if (this.apiKey)
|
|
791
|
+
return { base: this.edge.base, kind: "edge" };
|
|
792
|
+
throw new errors_ts_1.B3OSError({
|
|
793
|
+
code: "unsupported_transport",
|
|
794
|
+
detail: `${op.id} opens a WebSocket, which the SDK cannot carry over the Unix socket`,
|
|
795
|
+
hint: "Set B3OS_API_KEY so it goes through beta-api.b3os.org, or B3OS_API_URL to a node URL",
|
|
796
|
+
operationId: op.id,
|
|
797
|
+
});
|
|
798
|
+
}
|
|
799
|
+
// ------------------------------------------------------------------------------------------------------------
|
|
800
|
+
// Public escape hatch
|
|
801
|
+
/**
|
|
802
|
+
* Calls any operation by method and path, for endpoints the namespaces do not wrap (device login) or newer than
|
|
803
|
+
* this SDK. Account paths (`/v1/keys`, `/v1/auth`, …) go to the edge unless `edge` says otherwise.
|
|
804
|
+
*/
|
|
805
|
+
request(req, options = {}) {
|
|
806
|
+
const op = {
|
|
807
|
+
id: `${req.method} ${req.path}`,
|
|
808
|
+
method: req.method,
|
|
809
|
+
path: req.path.includes("{") ? req.path.replace(/[{}]/g, "") : req.path,
|
|
810
|
+
edge: req.edge ?? EDGE_PATHS.test(req.path),
|
|
811
|
+
timeoutMs: req.timeoutMs ?? 65_000,
|
|
812
|
+
errorFormat: req.errorFormat,
|
|
813
|
+
scope: "unknown",
|
|
814
|
+
};
|
|
815
|
+
const args = { query: req.query, body: req.body, bodyType: req.bodyType };
|
|
816
|
+
const o = req.headers ? { ...options, headers: { ...req.headers, ...options.headers } } : options;
|
|
817
|
+
return new promise_ts_1.APIPromise(this.exec(op, args, o));
|
|
818
|
+
}
|
|
819
|
+
/** @internal SSE parse helper for namespaces. */
|
|
820
|
+
static parseJsonEvent(msg) {
|
|
821
|
+
return JSON.parse(msg.data);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
exports.B3OSCore = B3OSCore;
|
|
825
|
+
//# sourceMappingURL=client.js.map
|