@zerosumstudio/conduit 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +785 -2
- package/dist/core-DXSbz15-.d.ts +142 -0
- package/dist/dev-CNYwEGcY.js +14 -0
- package/dist/devtools.d.ts +61 -0
- package/dist/devtools.js +152 -0
- package/dist/errors-DT0d6Qhy.js +85 -0
- package/dist/index.d.ts +177 -0
- package/dist/index.js +2412 -0
- package/dist/observable-LsEew2iL.d.ts +30 -0
- package/dist/query-state-BlmK3fBM.js +37 -0
- package/dist/react.d.ts +75 -0
- package/dist/react.js +331 -0
- package/dist/shared-2HssxK9p.d.ts +53 -0
- package/dist/shared-BsSjKC7q.js +118 -0
- package/dist/stores-DGXWZXXg.js +195 -0
- package/dist/testing.d.ts +88 -0
- package/dist/testing.js +224 -0
- package/dist/types-B9nuOKel.d.ts +689 -0
- package/dist/upload.d.ts +27 -0
- package/dist/upload.js +94 -0
- package/docs/migration-1.0.md +423 -0
- package/docs/threat-model.md +69 -0
- package/package.json +151 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,2412 @@
|
|
|
1
|
+
import { i as toConduitError, n as isConduitError, r as isErrorCode, t as ConduitError } from "./errors-DT0d6Qhy.js";
|
|
2
|
+
import { a as resolveEndpointTags, i as defineEndpoint, n as isBodyless, r as isCacheable, t as IDLE_QUERY_STATE } from "./query-state-BlmK3fBM.js";
|
|
3
|
+
import { a as consoleLogger, i as sharedClient, n as getSharedClient, o as reportError, r as releaseSharedClient } from "./shared-BsSjKC7q.js";
|
|
4
|
+
import { a as formatErrorUrl, c as redactResponse, d as stripQuery, i as createUrlRedactor, l as resolveCredentialHeaders, n as DEFAULT_REDACT, o as formatKey, r as createRequestError, s as redactRequest, t as createStore, u as resolveRedact } from "./stores-DGXWZXXg.js";
|
|
5
|
+
import { t as IS_DEVELOPMENT } from "./dev-CNYwEGcY.js";
|
|
6
|
+
|
|
7
|
+
// src/http/body.ts
|
|
8
|
+
const EMPTY = {
|
|
9
|
+
body: null,
|
|
10
|
+
contentType: void 0
|
|
11
|
+
};
|
|
12
|
+
/** Kinds that were never going to survive JSON, so trying only produces a confusing engine error. */
|
|
13
|
+
const UNENCODABLE = /* @__PURE__ */ new Set([
|
|
14
|
+
"function",
|
|
15
|
+
"symbol",
|
|
16
|
+
"bigint"
|
|
17
|
+
]);
|
|
18
|
+
function isBodyInit(value) {
|
|
19
|
+
return value instanceof Blob || value instanceof FormData || value instanceof URLSearchParams || value instanceof ArrayBuffer || value instanceof ReadableStream || ArrayBuffer.isView(value);
|
|
20
|
+
}
|
|
21
|
+
/** Anything the platform already accepts passes through untouched. Everything else is JSON. */
|
|
22
|
+
function encodeBody(value) {
|
|
23
|
+
if (value === void 0 || value === null) return EMPTY;
|
|
24
|
+
if (typeof value === "string") return {
|
|
25
|
+
body: value,
|
|
26
|
+
contentType: void 0
|
|
27
|
+
};
|
|
28
|
+
if (typeof value === "object" && isBodyInit(value)) return {
|
|
29
|
+
body: value,
|
|
30
|
+
contentType: void 0
|
|
31
|
+
};
|
|
32
|
+
if (UNENCODABLE.has(typeof value)) throw new ConduitError({
|
|
33
|
+
code: "INVALID_ARGUMENT",
|
|
34
|
+
message: `A ${typeof value} cannot be a request body. Pass a plain value or a BodyInit.`
|
|
35
|
+
});
|
|
36
|
+
try {
|
|
37
|
+
return {
|
|
38
|
+
body: JSON.stringify(value),
|
|
39
|
+
contentType: "application/json"
|
|
40
|
+
};
|
|
41
|
+
} catch (cause) {
|
|
42
|
+
throw new ConduitError({
|
|
43
|
+
code: "INVALID_ARGUMENT",
|
|
44
|
+
message: "The request body is not JSON-encodable. Remove the circular reference.",
|
|
45
|
+
cause
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/primitives/events.ts
|
|
51
|
+
function createEventBus(logger = consoleLogger) {
|
|
52
|
+
const typed = /* @__PURE__ */ new Map();
|
|
53
|
+
const all = /* @__PURE__ */ new Map();
|
|
54
|
+
let nextId = 0;
|
|
55
|
+
let count = 0;
|
|
56
|
+
const dispatch = (listener, event) => {
|
|
57
|
+
try {
|
|
58
|
+
listener(event);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
reportError(logger, "An event listener threw. The request is unaffected.", error);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const subscribe = (bucket, listener) => {
|
|
64
|
+
const id = nextId++;
|
|
65
|
+
bucket.set(id, listener);
|
|
66
|
+
count++;
|
|
67
|
+
let isRemoved = false;
|
|
68
|
+
return () => {
|
|
69
|
+
if (isRemoved || !bucket.delete(id)) return;
|
|
70
|
+
isRemoved = true;
|
|
71
|
+
count--;
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
return {
|
|
75
|
+
get active() {
|
|
76
|
+
return count > 0;
|
|
77
|
+
},
|
|
78
|
+
on(type, listener) {
|
|
79
|
+
let listeners = typed.get(type);
|
|
80
|
+
if (listeners === void 0) {
|
|
81
|
+
listeners = /* @__PURE__ */ new Map();
|
|
82
|
+
typed.set(type, listeners);
|
|
83
|
+
}
|
|
84
|
+
return subscribe(listeners, listener);
|
|
85
|
+
},
|
|
86
|
+
onAny(listener) {
|
|
87
|
+
return subscribe(all, listener);
|
|
88
|
+
},
|
|
89
|
+
emit(type, event) {
|
|
90
|
+
const listeners = typed.get(type);
|
|
91
|
+
if (listeners !== void 0) {
|
|
92
|
+
for (const [id, listener] of [...listeners]) if (listeners.has(id)) dispatch(listener, event);
|
|
93
|
+
}
|
|
94
|
+
for (const [id, listener] of [...all]) if (all.has(id)) dispatch(listener, event);
|
|
95
|
+
},
|
|
96
|
+
clear() {
|
|
97
|
+
for (const bucket of typed.values()) bucket.clear();
|
|
98
|
+
typed.clear();
|
|
99
|
+
all.clear();
|
|
100
|
+
count = 0;
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/** Monotonic milliseconds, for durations. */
|
|
105
|
+
function getMonotonicTime() {
|
|
106
|
+
return performance.now();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/http/keys.ts
|
|
110
|
+
/** FNV-1a, 32-bit. Cheap enough to run on every request, and not cryptographic. */
|
|
111
|
+
function hashText(input) {
|
|
112
|
+
let hash = 0x811c9dc5;
|
|
113
|
+
for (let index = 0; index < input.length; index++) {
|
|
114
|
+
hash ^= input.charCodeAt(index);
|
|
115
|
+
hash = Math.imul(hash, 16777619);
|
|
116
|
+
}
|
|
117
|
+
return (hash >>> 0).toString(36);
|
|
118
|
+
}
|
|
119
|
+
function getParamName(pair) {
|
|
120
|
+
const split = pair.indexOf("=");
|
|
121
|
+
return split === -1 ? pair : pair.slice(0, split);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Sorts the query string so `?a=1&b=2` and `?b=2&a=1` share an entry. Sorted by
|
|
125
|
+
* name only and stably, so `?sort=name&sort=age` keeps its order and stays
|
|
126
|
+
* distinct from the reverse.
|
|
127
|
+
*/
|
|
128
|
+
function toCanonicalUrl(url) {
|
|
129
|
+
const mark = url.indexOf("?");
|
|
130
|
+
if (mark === -1) return url;
|
|
131
|
+
const path = url.slice(0, mark);
|
|
132
|
+
const pairs = url.slice(mark + 1).split("&").filter((pair) => pair !== "").sort((first, second) => {
|
|
133
|
+
const a = getParamName(first);
|
|
134
|
+
const b = getParamName(second);
|
|
135
|
+
return Number(a > b) - Number(a < b);
|
|
136
|
+
});
|
|
137
|
+
return pairs.length === 0 ? path : `${path}?${pairs.join("&")}`;
|
|
138
|
+
}
|
|
139
|
+
const bodyIds = /* @__PURE__ */ new WeakMap();
|
|
140
|
+
let nextBodyId = 0;
|
|
141
|
+
/**
|
|
142
|
+
* Text-like bodies hash by value, so identical payloads share a key. A stream
|
|
143
|
+
* or `Blob` cannot be read without consuming it, so it gets a per-instance id
|
|
144
|
+
* and never matches anything else.
|
|
145
|
+
*/
|
|
146
|
+
function fingerprintBody(body) {
|
|
147
|
+
if (body === null) return "";
|
|
148
|
+
if (typeof body === "string") return hashText(body);
|
|
149
|
+
if (body instanceof URLSearchParams) return hashText(body.toString());
|
|
150
|
+
const existing = bodyIds.get(body);
|
|
151
|
+
if (existing !== void 0) return existing;
|
|
152
|
+
const id = `#${(nextBodyId++).toString(36)}`;
|
|
153
|
+
bodyIds.set(body, id);
|
|
154
|
+
return id;
|
|
155
|
+
}
|
|
156
|
+
/** A repeated name within one init comma-joins, the way `Headers` does. */
|
|
157
|
+
function joinPairs(pairs) {
|
|
158
|
+
const joined = /* @__PURE__ */ new Map();
|
|
159
|
+
for (const pair of pairs) {
|
|
160
|
+
const [name, value] = pair;
|
|
161
|
+
if (name === void 0 || value === void 0) continue;
|
|
162
|
+
const lower = name.toLowerCase();
|
|
163
|
+
const existing = joined.get(lower);
|
|
164
|
+
joined.set(lower, existing === void 0 ? value : `${existing}, ${value}`);
|
|
165
|
+
}
|
|
166
|
+
return joined;
|
|
167
|
+
}
|
|
168
|
+
/** A header init as lowercase `[name, value]` pairs. Plain and array inits are read directly, so a cache hit never builds a `Headers`. */
|
|
169
|
+
function toEntries(init) {
|
|
170
|
+
if (init instanceof Headers) return [...init];
|
|
171
|
+
if (Array.isArray(init)) return [...joinPairs(init)];
|
|
172
|
+
return Object.entries(init).map(([name, value]) => [name.toLowerCase(), value]);
|
|
173
|
+
}
|
|
174
|
+
function collect(init, into) {
|
|
175
|
+
for (const [name, value] of init === void 0 ? [] : toEntries(init)) into.set(name, value);
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Hashes the headers that make two requests to the same url different requests.
|
|
179
|
+
*
|
|
180
|
+
* Merging matches how the client builds them: a repeated name within one init
|
|
181
|
+
* comma-joins, and the option headers replace the config ones.
|
|
182
|
+
*/
|
|
183
|
+
function fingerprintHeaders(configHeaders, optionHeaders, vary) {
|
|
184
|
+
if (vary !== "*" && vary.length === 0) return "";
|
|
185
|
+
const merged = /* @__PURE__ */ new Map();
|
|
186
|
+
collect(configHeaders, merged);
|
|
187
|
+
collect(optionHeaders, merged);
|
|
188
|
+
if (merged.size === 0) return "";
|
|
189
|
+
const wanted = vary === "*" ? void 0 : new Set(vary.map((name) => name.toLowerCase()));
|
|
190
|
+
const parts = [];
|
|
191
|
+
for (const [name, value] of merged) if (wanted === void 0 || wanted.has(name)) parts.push(`${name}:${value}`);
|
|
192
|
+
if (parts.length === 0) return "";
|
|
193
|
+
parts.sort();
|
|
194
|
+
return hashText(parts.join("\n"));
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Everything beyond method, url and body that makes a request distinct,
|
|
198
|
+
* pre-hashed so `withRequest` can recompute a key without the headers.
|
|
199
|
+
*/
|
|
200
|
+
function deriveVariance(configHeaders, optionHeaders, vary, credentials) {
|
|
201
|
+
const headers = fingerprintHeaders(configHeaders, optionHeaders, vary);
|
|
202
|
+
const parts = [];
|
|
203
|
+
if (headers !== "") parts.push(`h:${headers}`);
|
|
204
|
+
if (credentials !== void 0) parts.push(`c:${credentials}`);
|
|
205
|
+
return parts.join(" ");
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* The identity a request is cached, deduped and superseded by, left readable
|
|
209
|
+
* for devtools. Credentials and decode mode are part of it: colliding on either
|
|
210
|
+
* serves a caller someone else's data, or the same bytes as the wrong type.
|
|
211
|
+
*/
|
|
212
|
+
function deriveKey(inputs) {
|
|
213
|
+
let key = `${inputs.method} ${toCanonicalUrl(inputs.url)}`;
|
|
214
|
+
if (inputs.body !== null) key += ` ${fingerprintBody(inputs.body)}`;
|
|
215
|
+
if (inputs.variance !== "") key += ` ${inputs.variance}`;
|
|
216
|
+
if (inputs.parse !== void 0 && inputs.parse !== "auto") key += ` p:${inputs.parse}`;
|
|
217
|
+
return key;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// src/client/methods.ts
|
|
221
|
+
/** Folds a positional body argument into options without ever setting `body: undefined`. */
|
|
222
|
+
function bodyOptions(method, body, options) {
|
|
223
|
+
return body === void 0 ? {
|
|
224
|
+
...options,
|
|
225
|
+
method
|
|
226
|
+
} : {
|
|
227
|
+
...options,
|
|
228
|
+
method,
|
|
229
|
+
body
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Builds the shared verb surface, so a scope offers exactly what the client does.
|
|
234
|
+
* The loose signatures here are what the typed `RequestMethods` compiles down to.
|
|
235
|
+
*/
|
|
236
|
+
function createMethods(execute) {
|
|
237
|
+
return {
|
|
238
|
+
request: (path, options) => execute(path, options ?? {}),
|
|
239
|
+
get: (path, options) => execute(path, {
|
|
240
|
+
...options,
|
|
241
|
+
method: "GET"
|
|
242
|
+
}),
|
|
243
|
+
head: (path, options) => execute(path, {
|
|
244
|
+
...options,
|
|
245
|
+
method: "HEAD"
|
|
246
|
+
}),
|
|
247
|
+
delete: (path, options) => execute(path, {
|
|
248
|
+
...options,
|
|
249
|
+
method: "DELETE"
|
|
250
|
+
}),
|
|
251
|
+
post: (path, body, options) => execute(path, bodyOptions("POST", body, options)),
|
|
252
|
+
put: (path, body, options) => execute(path, bodyOptions("PUT", body, options)),
|
|
253
|
+
patch: (path, body, options) => execute(path, bodyOptions("PATCH", body, options))
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// src/http/pipeline.ts
|
|
258
|
+
/** Folds middleware into a single function, outermost first. Run once per `.with()`. */
|
|
259
|
+
function compose(middlewares, terminal) {
|
|
260
|
+
if (middlewares.length === 0) return terminal;
|
|
261
|
+
return middlewares.reduceRight((downstream, middleware) => (request) => middleware(request, downstream), terminal);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// src/http/promise.ts
|
|
265
|
+
const swallow = () => {};
|
|
266
|
+
/**
|
|
267
|
+
* `view` shapes the record `.response()` hands out, so work like redaction is
|
|
268
|
+
* only done for callers that ask for it.
|
|
269
|
+
*/
|
|
270
|
+
function createConduitPromise(run, view = (response) => response) {
|
|
271
|
+
const promise = run.then((response) => response.data);
|
|
272
|
+
promise.response = () => {
|
|
273
|
+
promise.catch(swallow);
|
|
274
|
+
return run.then(view);
|
|
275
|
+
};
|
|
276
|
+
promise.safe = () => {
|
|
277
|
+
promise.catch(swallow);
|
|
278
|
+
return run.then((response) => ({
|
|
279
|
+
data: response.data,
|
|
280
|
+
error: null
|
|
281
|
+
}), (error) => ({
|
|
282
|
+
data: null,
|
|
283
|
+
error: toConduitError(error)
|
|
284
|
+
}));
|
|
285
|
+
};
|
|
286
|
+
return promise;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// src/http/request.ts
|
|
290
|
+
const keepUrl = (url) => url;
|
|
291
|
+
/**
|
|
292
|
+
* Materialises the request record every middleware sees. `headers` is a
|
|
293
|
+
* memoised getter, since cache and dedupe answer from `key` alone.
|
|
294
|
+
*/
|
|
295
|
+
function createRequest(init) {
|
|
296
|
+
const { buildHeaders, redactUrl, ...fields } = init;
|
|
297
|
+
let headers;
|
|
298
|
+
return {
|
|
299
|
+
...fields,
|
|
300
|
+
redactUrl: redactUrl ?? keepUrl,
|
|
301
|
+
get headers() {
|
|
302
|
+
headers ??= buildHeaders();
|
|
303
|
+
return headers;
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* A copy with the given fields replaced. Rewriting what a request is re-derives
|
|
309
|
+
* what it is identified by, unless the patch names a key itself.
|
|
310
|
+
*/
|
|
311
|
+
function withRequest(request, patch) {
|
|
312
|
+
const next = {
|
|
313
|
+
...request,
|
|
314
|
+
...patch
|
|
315
|
+
};
|
|
316
|
+
if (patch.key === void 0 && (patch.url !== void 0 || patch.method !== void 0 || patch.body !== void 0 || patch.variance !== void 0 || patch.parse !== void 0)) return {
|
|
317
|
+
...next,
|
|
318
|
+
key: deriveKey(next)
|
|
319
|
+
};
|
|
320
|
+
return next;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// src/http/origin.ts
|
|
324
|
+
const WEB_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
|
|
325
|
+
/** Reduces `https://host:8443/` to its origin, or fails when the entry is not an http(s) origin. */
|
|
326
|
+
function parseOrigin(entry) {
|
|
327
|
+
const parsed = URL.canParse(entry) ? new URL(entry) : void 0;
|
|
328
|
+
if (parsed === void 0 || !WEB_PROTOCOLS.has(parsed.protocol) || parsed.username !== "" || parsed.password !== "" || parsed.search !== "" || parsed.hash !== "" || parsed.pathname !== "/" && parsed.pathname !== "") throw new ConduitError({
|
|
329
|
+
code: "INVALID_ARGUMENT",
|
|
330
|
+
message: `"${stripQuery(entry)}" is not an origin. Use scheme, host and port, like "https://api.example.com".`
|
|
331
|
+
});
|
|
332
|
+
return parsed.origin;
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* What a relative url resolves against. `fetch` resolves against the document's
|
|
336
|
+
* base, which a `<base href>` can move away from `location`, so this reads it.
|
|
337
|
+
*/
|
|
338
|
+
function getDocumentBase() {
|
|
339
|
+
const candidates = [typeof document === "object" ? document.baseURI : void 0, typeof location === "object" ? location.href : void 0];
|
|
340
|
+
for (const candidate of candidates) if (typeof candidate === "string" && URL.canParse(candidate) && WEB_PROTOCOLS.has(new URL(candidate).protocol)) return candidate;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* One place that decides where a request may go. Every url is resolved with
|
|
344
|
+
* `new URL` and compared as an origin, and what gets sent is the checked href,
|
|
345
|
+
* never the string it came from.
|
|
346
|
+
*/
|
|
347
|
+
function createOriginPolicy(baseUrl, origins) {
|
|
348
|
+
const allowed = new Set(origins);
|
|
349
|
+
const isAbsoluteBase = URL.canParse(baseUrl);
|
|
350
|
+
const absoluteBase = isAbsoluteBase ? new URL(baseUrl) : void 0;
|
|
351
|
+
const trimmed = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
|
|
352
|
+
const joinBase = isAbsoluteBase || trimmed === "" || trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
|
|
353
|
+
if (absoluteBase !== void 0 && !WEB_PROTOCOLS.has(absoluteBase.protocol)) throw new ConduitError({
|
|
354
|
+
code: "INVALID_ARGUMENT",
|
|
355
|
+
message: `baseUrl "${stripQuery(baseUrl)}" is not an http(s) url.`
|
|
356
|
+
});
|
|
357
|
+
const basePath = absoluteBase === void 0 ? joinBase : absoluteBase.pathname.replace(/\/$/, "");
|
|
358
|
+
const reject = (url, why) => {
|
|
359
|
+
throw new ConduitError({
|
|
360
|
+
code: "ORIGIN_REJECTED",
|
|
361
|
+
message: `"${stripQuery(url)}" ${why}`
|
|
362
|
+
});
|
|
363
|
+
};
|
|
364
|
+
const getRelativeBase = () => {
|
|
365
|
+
const documentBase = getDocumentBase();
|
|
366
|
+
if (documentBase === void 0) throw new ConduitError({
|
|
367
|
+
code: "INVALID_ARGUMENT",
|
|
368
|
+
message: `A relative baseUrl ("${baseUrl}") needs a page. Pass an absolute baseUrl on a server.`
|
|
369
|
+
});
|
|
370
|
+
return documentBase;
|
|
371
|
+
};
|
|
372
|
+
const getApiOrigin = () => absoluteBase === void 0 ? new URL(getRelativeBase()).origin : absoluteBase.origin;
|
|
373
|
+
const parse = (url, base) => {
|
|
374
|
+
if (!URL.canParse(url, base)) return reject(url, "is not a url conduit can send.");
|
|
375
|
+
return new URL(url, base);
|
|
376
|
+
};
|
|
377
|
+
const assertWeb = (parsed, original) => {
|
|
378
|
+
if (!WEB_PROTOCOLS.has(parsed.protocol)) reject(original, `uses ${parsed.protocol}, and only http and https are sent. If this is a path, start it with a slash.`);
|
|
379
|
+
if (parsed.username !== "" || parsed.password !== "") reject(original, "carries credentials in the url, which fetch refuses.");
|
|
380
|
+
};
|
|
381
|
+
const assertOrigin = (parsed, original) => {
|
|
382
|
+
assertWeb(parsed, original);
|
|
383
|
+
if (parsed.origin !== getApiOrigin() && !allowed.has(parsed.origin)) reject(original, "leaves the origins this client is allowed to call. Add it to config.origins if this is intentional.");
|
|
384
|
+
};
|
|
385
|
+
return {
|
|
386
|
+
resolve(path) {
|
|
387
|
+
if (URL.canParse(path)) {
|
|
388
|
+
const absolute = new URL(path);
|
|
389
|
+
assertOrigin(absolute, path);
|
|
390
|
+
return absolute;
|
|
391
|
+
}
|
|
392
|
+
const joined = joinBase + (path.startsWith("/") ? path : `/${path}`);
|
|
393
|
+
const parsed = parse(joined, absoluteBase === void 0 ? getRelativeBase() : void 0);
|
|
394
|
+
assertOrigin(parsed, path);
|
|
395
|
+
if (!(basePath === "" || parsed.pathname === basePath || parsed.pathname.startsWith(`${basePath}/`))) reject(path, `resolves outside baseUrl's path "${basePath}".`);
|
|
396
|
+
return parsed;
|
|
397
|
+
},
|
|
398
|
+
assertAllowed(url) {
|
|
399
|
+
const parsed = parse(url, void 0);
|
|
400
|
+
assertOrigin(parsed, url);
|
|
401
|
+
return parsed;
|
|
402
|
+
},
|
|
403
|
+
isApiOrigin(url) {
|
|
404
|
+
try {
|
|
405
|
+
return URL.canParse(url) && new URL(url).origin === getApiOrigin();
|
|
406
|
+
} catch {
|
|
407
|
+
return false;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// src/client/scopes.ts
|
|
414
|
+
function createScope(init) {
|
|
415
|
+
let controller = new AbortController();
|
|
416
|
+
let isDisposed = false;
|
|
417
|
+
const cancel = (reason) => {
|
|
418
|
+
controller.abort(new ConduitError({
|
|
419
|
+
code: "ABORTED",
|
|
420
|
+
message: reason,
|
|
421
|
+
owner: init.name
|
|
422
|
+
}));
|
|
423
|
+
};
|
|
424
|
+
const scope = {
|
|
425
|
+
...createMethods(init.createExecutor(() => controller.signal, init.name)),
|
|
426
|
+
name: init.name,
|
|
427
|
+
get signal() {
|
|
428
|
+
return controller.signal;
|
|
429
|
+
},
|
|
430
|
+
abort(reason) {
|
|
431
|
+
if (isDisposed) return;
|
|
432
|
+
cancel(reason ?? `Scope "${init.name}" was aborted.`);
|
|
433
|
+
controller = new AbortController();
|
|
434
|
+
},
|
|
435
|
+
dispose() {
|
|
436
|
+
if (isDisposed) return;
|
|
437
|
+
isDisposed = true;
|
|
438
|
+
cancel(`Scope "${init.name}" was disposed.`);
|
|
439
|
+
init.onDispose(scope);
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
return scope;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// src/http/signals.ts
|
|
446
|
+
/**
|
|
447
|
+
* Merges caller, scope and timeout signals into the one the transport listens
|
|
448
|
+
* to. First to abort wins and its `reason` carries through, so the failure says
|
|
449
|
+
* which one it was.
|
|
450
|
+
*/
|
|
451
|
+
function composeSignals(signals) {
|
|
452
|
+
const present = [];
|
|
453
|
+
for (const signal of signals) if (signal !== void 0) present.push(signal);
|
|
454
|
+
const only = present[0];
|
|
455
|
+
if (present.length === 0) return new AbortController().signal;
|
|
456
|
+
return present.length === 1 && only !== void 0 ? only : AbortSignal.any(present);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// src/http/abort.ts
|
|
460
|
+
function toAbortError(request, cause) {
|
|
461
|
+
const reason = request.signal.reason;
|
|
462
|
+
if (isConduitError(reason)) return new ConduitError({
|
|
463
|
+
code: reason.code,
|
|
464
|
+
message: reason.message,
|
|
465
|
+
method: request.method,
|
|
466
|
+
url: formatErrorUrl(request),
|
|
467
|
+
status: reason.status,
|
|
468
|
+
owner: request.owner,
|
|
469
|
+
cause: cause ?? reason
|
|
470
|
+
});
|
|
471
|
+
return createRequestError(request, "ABORTED", "was aborted.", { cause: cause ?? reason });
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// src/http/transport.ts
|
|
475
|
+
const EMPTY_STATUSES = /* @__PURE__ */ new Set([
|
|
476
|
+
204,
|
|
477
|
+
205,
|
|
478
|
+
304
|
|
479
|
+
]);
|
|
480
|
+
function resolveMode(response, mode) {
|
|
481
|
+
if (mode !== "auto") return mode;
|
|
482
|
+
if (EMPTY_STATUSES.has(response.status)) return "none";
|
|
483
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
484
|
+
if (contentType.includes("json")) return "json";
|
|
485
|
+
if (contentType.startsWith("text/") || contentType.includes("xml")) return "text";
|
|
486
|
+
return contentType === "" ? "text" : "blob";
|
|
487
|
+
}
|
|
488
|
+
async function readAs(response, mode) {
|
|
489
|
+
switch (mode) {
|
|
490
|
+
case "json": {
|
|
491
|
+
const text = await response.text();
|
|
492
|
+
return text === "" ? null : JSON.parse(text);
|
|
493
|
+
}
|
|
494
|
+
case "text": return response.text();
|
|
495
|
+
case "blob": return response.blob();
|
|
496
|
+
case "arrayBuffer": return response.arrayBuffer();
|
|
497
|
+
case "formData": return response.formData();
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
async function decodeBody(response, request) {
|
|
501
|
+
const mode = resolveMode(response, request.parse);
|
|
502
|
+
if (mode === "none") return null;
|
|
503
|
+
try {
|
|
504
|
+
return await readAs(response, mode);
|
|
505
|
+
} catch (cause) {
|
|
506
|
+
if (request.signal.aborted) throw toAbortError(request, cause);
|
|
507
|
+
throw createRequestError(request, "PARSE_FAILED", `returned a body that is not ${mode}. Set parse to match it.`, {
|
|
508
|
+
status: response.status,
|
|
509
|
+
cause
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Reads an error response, where a 503 carrying an HTML page under a JSON content
|
|
515
|
+
* type must not become a parse failure and lose the status.
|
|
516
|
+
*/
|
|
517
|
+
async function decodeErrorBody(response, request) {
|
|
518
|
+
const mode = resolveMode(response, request.parse);
|
|
519
|
+
if (mode === "none") return null;
|
|
520
|
+
try {
|
|
521
|
+
if (mode !== "json") return await readAs(response, mode);
|
|
522
|
+
const text = await response.text();
|
|
523
|
+
if (text === "") return null;
|
|
524
|
+
try {
|
|
525
|
+
return JSON.parse(text);
|
|
526
|
+
} catch {
|
|
527
|
+
return text;
|
|
528
|
+
}
|
|
529
|
+
} catch {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
function toTransportError(cause, request) {
|
|
534
|
+
if (isConduitError(cause)) return cause;
|
|
535
|
+
const name = cause instanceof Error ? cause.name : "";
|
|
536
|
+
if (name === "TimeoutError") return createRequestError(request, "TIMEOUT", "timed out.", { cause });
|
|
537
|
+
if (name === "AbortError" || request.signal.aborted) return toAbortError(request, cause);
|
|
538
|
+
return createRequestError(request, "NETWORK", "never reached a server. Check the network, DNS, CORS and TLS.", { cause });
|
|
539
|
+
}
|
|
540
|
+
/** Credentials a platform strips itself when a redirect crosses origins. */
|
|
541
|
+
const STRIPPED_HEADERS = /* @__PURE__ */ new Set([
|
|
542
|
+
"authorization",
|
|
543
|
+
"cookie",
|
|
544
|
+
"proxy-authorization"
|
|
545
|
+
]);
|
|
546
|
+
const REDIRECT_STATUSES = /* @__PURE__ */ new Set([
|
|
547
|
+
301,
|
|
548
|
+
302,
|
|
549
|
+
303,
|
|
550
|
+
307,
|
|
551
|
+
308
|
|
552
|
+
]);
|
|
553
|
+
/** Whether the request holds a credential that a redirect would carry to another origin. */
|
|
554
|
+
function carriesLooseCredential(request, config) {
|
|
555
|
+
return [...config.credentialHeaders, ...request.meta.credentialHeaders ?? []].some((name) => !STRIPPED_HEADERS.has(name) && request.headers.has(name));
|
|
556
|
+
}
|
|
557
|
+
function isBlockedRedirect(response) {
|
|
558
|
+
return response.type === "opaqueredirect" || REDIRECT_STATUSES.has(response.status);
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Decides how a request treats redirects. A custom credential means `manual`,
|
|
562
|
+
* unless the caller chose, and XHR cannot do `manual` at all, so it fails closed.
|
|
563
|
+
*/
|
|
564
|
+
function planRedirect(request, config) {
|
|
565
|
+
const isCredentialed = carriesLooseCredential(request, config);
|
|
566
|
+
const canBlock = request.meta.fetch === void 0;
|
|
567
|
+
if (!canBlock && request.credentials === "omit") throw createRequestError(request, "INVALID_ARGUMENT", "asks for credentials: 'omit', which XMLHttpRequest cannot honour. Drop onProgress or the option.");
|
|
568
|
+
if (!canBlock && isCredentialed && request.redirect !== "follow") throw createRequestError(request, "INVALID_ARGUMENT", "sends a credential through XMLHttpRequest, which cannot refuse a redirect. Set redirect: 'follow', or drop onProgress.");
|
|
569
|
+
const isGuarded = canBlock && isCredentialed && request.redirect === void 0;
|
|
570
|
+
return {
|
|
571
|
+
redirect: isGuarded ? "manual" : request.redirect,
|
|
572
|
+
isGuarded
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** Request fields that go to fetch under their own names, when the request sets them. */
|
|
576
|
+
const PASSTHROUGH_FIELDS = [
|
|
577
|
+
"credentials",
|
|
578
|
+
"mode",
|
|
579
|
+
"cache",
|
|
580
|
+
"keepalive",
|
|
581
|
+
"priority",
|
|
582
|
+
"referrerPolicy",
|
|
583
|
+
"integrity"
|
|
584
|
+
];
|
|
585
|
+
function buildInit(request) {
|
|
586
|
+
const init = {
|
|
587
|
+
method: request.method,
|
|
588
|
+
headers: request.headers,
|
|
589
|
+
signal: request.signal
|
|
590
|
+
};
|
|
591
|
+
if (request.body !== null) {
|
|
592
|
+
init.body = request.body;
|
|
593
|
+
if (request.body instanceof ReadableStream) init.duplex = "half";
|
|
594
|
+
}
|
|
595
|
+
for (const field of PASSTHROUGH_FIELDS) if (request[field] !== void 0) Object.assign(init, { [field]: request[field] });
|
|
596
|
+
return init;
|
|
597
|
+
}
|
|
598
|
+
/** The terminal handler: everything inside the onion ends here, at the network. */
|
|
599
|
+
function createFetchTransport(config, policy) {
|
|
600
|
+
return async (request) => {
|
|
601
|
+
const target = policy.assertAllowed(request.url);
|
|
602
|
+
const init = buildInit(request);
|
|
603
|
+
const send = request.meta.fetch ?? config.fetch;
|
|
604
|
+
const { redirect, isGuarded } = planRedirect(request, config);
|
|
605
|
+
if (redirect !== void 0) init.redirect = redirect;
|
|
606
|
+
let response;
|
|
607
|
+
try {
|
|
608
|
+
response = await send(target.href, init);
|
|
609
|
+
} catch (cause) {
|
|
610
|
+
throw toTransportError(cause, request);
|
|
611
|
+
}
|
|
612
|
+
if (isGuarded && isBlockedRedirect(response)) throw createRequestError(request, "REDIRECT_BLOCKED", "was answered with a redirect while carrying a credential. Set redirect: 'follow' on the request if that is intended.", {
|
|
613
|
+
status: response.status,
|
|
614
|
+
headers: response.headers
|
|
615
|
+
});
|
|
616
|
+
if (!response.ok) throw createRequestError(request, "HTTP_STATUS", `failed with ${response.status} ${response.statusText}`.trimEnd(), {
|
|
617
|
+
status: response.status,
|
|
618
|
+
headers: response.headers,
|
|
619
|
+
body: await decodeErrorBody(response, request)
|
|
620
|
+
});
|
|
621
|
+
return {
|
|
622
|
+
status: response.status,
|
|
623
|
+
headers: response.headers,
|
|
624
|
+
data: await decodeBody(response, request),
|
|
625
|
+
raw: response,
|
|
626
|
+
from: "network",
|
|
627
|
+
attempt: request.meta.attempt ?? 1,
|
|
628
|
+
request
|
|
629
|
+
};
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// src/http/url.ts
|
|
634
|
+
/**
|
|
635
|
+
* A placeholder starts a segment. A colon anywhere else is literal, which keeps
|
|
636
|
+
* `/v1/models/gemini-pro:generateContent` and `//user:pass@host` working. Write
|
|
637
|
+
* `::name` for a literal segment that has to begin with one.
|
|
638
|
+
*/
|
|
639
|
+
const PARAM_PATTERN = /(^|\/)(::?)([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
640
|
+
const DOT_SEGMENTS = /* @__PURE__ */ new Set([".", ".."]);
|
|
641
|
+
/** Whether a path has a `:name` placeholder, which a literal `::name` does not count as. */
|
|
642
|
+
function hasPlaceholders(path) {
|
|
643
|
+
return [...stripQuery(path).matchAll(PARAM_PATTERN)].some((match) => match[2] === ":");
|
|
644
|
+
}
|
|
645
|
+
/** Turns one param value into a path segment, or says which rule it broke. */
|
|
646
|
+
function formatParam(label, name, value) {
|
|
647
|
+
const fail = (detail) => new ConduitError({
|
|
648
|
+
code: "INVALID_ARGUMENT",
|
|
649
|
+
message: `Path "${label}" ${detail}`
|
|
650
|
+
});
|
|
651
|
+
if (value === void 0) throw fail(`needs params: { ${name}: … }.`);
|
|
652
|
+
if (typeof value !== "string" && typeof value !== "number") throw fail(`was given ${value === null ? "null" : typeof value} for ":${name}". Pass a string or a number.`);
|
|
653
|
+
const text = String(value).trim();
|
|
654
|
+
if (text === "") throw fail(`was given an empty ":${name}". Pass a value.`);
|
|
655
|
+
if (DOT_SEGMENTS.has(text)) throw fail(`was given "${text}" for ":${name}". A dot segment climbs out of the path.`);
|
|
656
|
+
return encodeURIComponent(String(value));
|
|
657
|
+
}
|
|
658
|
+
/** Substitutes `:name` placeholders. A missing value is an `INVALID_ARGUMENT`, not a 404. */
|
|
659
|
+
function applyPathParams(path, params, logger = consoleLogger) {
|
|
660
|
+
const label = stripQuery(path);
|
|
661
|
+
const mark = path.indexOf("?");
|
|
662
|
+
const head = mark === -1 ? path : path.slice(0, mark);
|
|
663
|
+
const tail = mark === -1 ? "" : path.slice(mark);
|
|
664
|
+
if (head.search(PARAM_PATTERN) === -1) {
|
|
665
|
+
if (IS_DEVELOPMENT && params !== void 0 && Object.keys(params).length > 0) logger.warn(`[conduit] "${label}" was given params ${JSON.stringify(Object.keys(params))} but has no ":name" placeholders. Did you mean query?`);
|
|
666
|
+
return path;
|
|
667
|
+
}
|
|
668
|
+
return head.replace(PARAM_PATTERN, (_match, prefix, colons, name) => {
|
|
669
|
+
if (colons === "::") return `${prefix}:${name}`;
|
|
670
|
+
const value = params !== void 0 && Object.hasOwn(params, name) ? params[name] : void 0;
|
|
671
|
+
return `${prefix}${formatParam(label, name, value)}`;
|
|
672
|
+
}) + tail;
|
|
673
|
+
}
|
|
674
|
+
function serialiseQuery(query) {
|
|
675
|
+
const search = new URLSearchParams();
|
|
676
|
+
for (const key of Object.keys(query)) {
|
|
677
|
+
const value = query[key];
|
|
678
|
+
if (value === void 0 || value === null) continue;
|
|
679
|
+
for (const entry of Array.isArray(value) ? value : [value]) search.append(key, String(entry));
|
|
680
|
+
}
|
|
681
|
+
return search.toString();
|
|
682
|
+
}
|
|
683
|
+
function appendQuery(url, query) {
|
|
684
|
+
const serialised = query === void 0 ? "" : serialiseQuery(query);
|
|
685
|
+
if (serialised === "") return url;
|
|
686
|
+
const hashMark = url.indexOf("#");
|
|
687
|
+
const head = hashMark === -1 ? url : url.slice(0, hashMark);
|
|
688
|
+
const hash = hashMark === -1 ? "" : url.slice(hashMark);
|
|
689
|
+
return head + (head.includes("?") ? "&" : "?") + serialised + hash;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// src/client/core.ts
|
|
693
|
+
const EMPTY_TAGS = Object.freeze([]);
|
|
694
|
+
function getDefaultFetch() {
|
|
695
|
+
if (typeof globalThis.fetch !== "function") throw new ConduitError({
|
|
696
|
+
code: "INVALID_ARGUMENT",
|
|
697
|
+
message: "No global fetch was found. Pass one as config.fetch."
|
|
698
|
+
});
|
|
699
|
+
return (input, init) => globalThis.fetch(input, init);
|
|
700
|
+
}
|
|
701
|
+
function resolveHeaders(headers) {
|
|
702
|
+
if (headers === void 0 || typeof headers === "function") return headers;
|
|
703
|
+
return () => headers;
|
|
704
|
+
}
|
|
705
|
+
function resolveConfig(config) {
|
|
706
|
+
const vary = config.vary ?? "*";
|
|
707
|
+
return {
|
|
708
|
+
baseUrl: config.baseUrl ?? "",
|
|
709
|
+
headers: resolveHeaders(config.headers),
|
|
710
|
+
credentials: config.credentials,
|
|
711
|
+
vary: vary === "*" ? vary : vary.map((name) => name.toLowerCase()),
|
|
712
|
+
owner: config.owner,
|
|
713
|
+
lane: config.lane ?? "default",
|
|
714
|
+
parse: config.parse ?? "auto",
|
|
715
|
+
fetch: config.fetch ?? getDefaultFetch(),
|
|
716
|
+
mode: config.mode,
|
|
717
|
+
redirect: config.redirect,
|
|
718
|
+
cache: config.cache,
|
|
719
|
+
keepalive: config.keepalive,
|
|
720
|
+
priority: config.priority,
|
|
721
|
+
referrerPolicy: config.referrerPolicy,
|
|
722
|
+
integrity: config.integrity,
|
|
723
|
+
origins: (config.origins ?? []).map(parseOrigin),
|
|
724
|
+
redact: resolveRedact(config.redact),
|
|
725
|
+
credentialHeaders: resolveCredentialHeaders(config.redact),
|
|
726
|
+
logger: config.logger ?? consoleLogger
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
function buildHeaders(configHeaders, optionHeaders, contentType) {
|
|
730
|
+
const headers = new Headers(configHeaders);
|
|
731
|
+
if (optionHeaders !== void 0) new Headers(optionHeaders).forEach((value, name) => {
|
|
732
|
+
headers.set(name, value);
|
|
733
|
+
});
|
|
734
|
+
if (contentType !== void 0 && !headers.has("content-type")) headers.set("content-type", contentType);
|
|
735
|
+
return headers;
|
|
736
|
+
}
|
|
737
|
+
/** A request's own `RequestInit` fields, with the client's as the default for each. */
|
|
738
|
+
function mergePassthrough(options, config) {
|
|
739
|
+
return {
|
|
740
|
+
mode: options.mode ?? config.mode,
|
|
741
|
+
redirect: options.redirect ?? config.redirect,
|
|
742
|
+
cache: options.cache ?? config.cache,
|
|
743
|
+
keepalive: options.keepalive ?? config.keepalive,
|
|
744
|
+
priority: options.priority ?? config.priority,
|
|
745
|
+
referrerPolicy: options.referrerPolicy ?? config.referrerPolicy,
|
|
746
|
+
integrity: options.integrity ?? config.integrity
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
/** Folds an endpoint's `query`/`body`/`tags` and its own `vars` into ordinary request options. */
|
|
750
|
+
function resolveEndpointOptions(endpoint, vars, options) {
|
|
751
|
+
const tags = resolveEndpointTags(endpoint.tags, vars);
|
|
752
|
+
const query = endpoint.query?.(vars);
|
|
753
|
+
const body = endpoint.body?.(vars);
|
|
754
|
+
return {
|
|
755
|
+
...endpoint.options,
|
|
756
|
+
method: endpoint.method,
|
|
757
|
+
...vars === void 0 || !hasPlaceholders(endpoint.path) ? {} : { params: vars },
|
|
758
|
+
...query === void 0 ? {} : { query },
|
|
759
|
+
...body === void 0 ? {} : { body },
|
|
760
|
+
...tags === void 0 ? {} : { tags },
|
|
761
|
+
...endpoint.cacheable === void 0 ? {} : { cacheable: endpoint.cacheable },
|
|
762
|
+
...options
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
/** Runs an endpoint's `response` schema, or plain function, against a decoded body. */
|
|
766
|
+
async function decodeEndpointResponse(schema, response) {
|
|
767
|
+
const { request } = response;
|
|
768
|
+
const failure = (detail, extra) => createRequestError(request, "VALIDATION_FAILED", detail, {
|
|
769
|
+
status: response.status,
|
|
770
|
+
...extra
|
|
771
|
+
});
|
|
772
|
+
if (typeof schema === "function") try {
|
|
773
|
+
return schema(response.data);
|
|
774
|
+
} catch (cause) {
|
|
775
|
+
throw failure("failed its response function.", { cause });
|
|
776
|
+
}
|
|
777
|
+
const outcome = await schema["~standard"].validate(response.data);
|
|
778
|
+
if ("issues" in outcome) throw failure("failed its response schema.", { body: outcome.issues });
|
|
779
|
+
return outcome.value;
|
|
780
|
+
}
|
|
781
|
+
var Client = class {
|
|
782
|
+
#config;
|
|
783
|
+
#policy;
|
|
784
|
+
#transport;
|
|
785
|
+
#context;
|
|
786
|
+
#events;
|
|
787
|
+
#redactUrl;
|
|
788
|
+
#plugins = [];
|
|
789
|
+
#middlewares = [];
|
|
790
|
+
#scopes = /* @__PURE__ */ new Set();
|
|
791
|
+
#resetListeners = /* @__PURE__ */ new Set();
|
|
792
|
+
#changeListeners = /* @__PURE__ */ new Set();
|
|
793
|
+
#dispatch;
|
|
794
|
+
#root = new AbortController();
|
|
795
|
+
#isDestroyed = false;
|
|
796
|
+
constructor(config = {}) {
|
|
797
|
+
this.#config = resolveConfig(config);
|
|
798
|
+
this.#policy = createOriginPolicy(this.#config.baseUrl, this.#config.origins);
|
|
799
|
+
this.#redactUrl = createUrlRedactor(this.#config.redact.query);
|
|
800
|
+
this.#events = createEventBus(this.#config.logger);
|
|
801
|
+
this.#transport = createFetchTransport(this.#config, this.#policy);
|
|
802
|
+
this.#dispatch = this.#transport;
|
|
803
|
+
this.#context = {
|
|
804
|
+
config: this.#config,
|
|
805
|
+
events: this.#events,
|
|
806
|
+
request: (path, options) => this.#execute(path, options ?? {}),
|
|
807
|
+
dispatch: (request) => this.#dispatch(request),
|
|
808
|
+
isApiOrigin: (url) => this.#policy.isApiOrigin(url),
|
|
809
|
+
resetIdentity: () => {
|
|
810
|
+
this.#resetIdentity();
|
|
811
|
+
},
|
|
812
|
+
onResetIdentity: (listener) => this.#subscribe(this.#resetListeners, listener),
|
|
813
|
+
notifyCacheChange: (change) => {
|
|
814
|
+
this.#notify(this.#changeListeners, (listener) => {
|
|
815
|
+
listener(change);
|
|
816
|
+
});
|
|
817
|
+
},
|
|
818
|
+
onCacheChange: (listener) => this.#subscribe(this.#changeListeners, listener)
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
get config() {
|
|
822
|
+
return this.#config;
|
|
823
|
+
}
|
|
824
|
+
/** Whether {@link Client.destroy} has run. */
|
|
825
|
+
isDestroyed() {
|
|
826
|
+
return this.#isDestroyed;
|
|
827
|
+
}
|
|
828
|
+
/** Every request start, settle and failure, plus whatever plugins publish. */
|
|
829
|
+
get events() {
|
|
830
|
+
return this.#events;
|
|
831
|
+
}
|
|
832
|
+
getKey(pathOrEndpoint, second) {
|
|
833
|
+
if (typeof pathOrEndpoint === "string") return this.#prepare(pathOrEndpoint, second ?? {}).key;
|
|
834
|
+
const options = resolveEndpointOptions(pathOrEndpoint, second, void 0);
|
|
835
|
+
return this.#prepare(pathOrEndpoint.path, options).key;
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Installs a plugin and merges what it returns onto the client, so the
|
|
839
|
+
* extension shows up in the type. `client.invalidate()` does not compile
|
|
840
|
+
* until `cache()` is installed.
|
|
841
|
+
*/
|
|
842
|
+
with(plugin) {
|
|
843
|
+
this.#assertAlive();
|
|
844
|
+
if (this.#plugins.some((installed) => installed.name === plugin.name)) throw new ConduitError({
|
|
845
|
+
code: "DUPLICATE_PLUGIN",
|
|
846
|
+
message: `Plugin "${plugin.name}" is already installed.`
|
|
847
|
+
});
|
|
848
|
+
this.#plugins.push(plugin);
|
|
849
|
+
if (plugin.middleware !== void 0) {
|
|
850
|
+
this.#middlewares.push(plugin.middleware);
|
|
851
|
+
this.#dispatch = compose(this.#middlewares, this.#transport);
|
|
852
|
+
}
|
|
853
|
+
const extension = plugin.onInit?.(this.#context);
|
|
854
|
+
if (extension) {
|
|
855
|
+
for (const key of Object.keys(extension)) if (key in this) throw new ConduitError({
|
|
856
|
+
code: "EXTENSION_COLLISION",
|
|
857
|
+
message: `Plugin "${plugin.name}" adds "${key}", which the client already has. Rename it.`
|
|
858
|
+
});
|
|
859
|
+
Object.assign(this, extension);
|
|
860
|
+
}
|
|
861
|
+
return this;
|
|
862
|
+
}
|
|
863
|
+
request(path, ...args) {
|
|
864
|
+
return this.#execute(path, args[0] ?? {});
|
|
865
|
+
}
|
|
866
|
+
get(path, ...args) {
|
|
867
|
+
return this.#execute(path, {
|
|
868
|
+
...args[0],
|
|
869
|
+
method: "GET"
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
head(path, ...args) {
|
|
873
|
+
return this.#execute(path, {
|
|
874
|
+
...args[0],
|
|
875
|
+
method: "HEAD"
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
delete(path, ...args) {
|
|
879
|
+
return this.#execute(path, {
|
|
880
|
+
...args[0],
|
|
881
|
+
method: "DELETE"
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
post(path, body, ...args) {
|
|
885
|
+
return this.#execute(path, bodyOptions("POST", body, args[0]));
|
|
886
|
+
}
|
|
887
|
+
put(path, body, ...args) {
|
|
888
|
+
return this.#execute(path, bodyOptions("PUT", body, args[0]));
|
|
889
|
+
}
|
|
890
|
+
patch(path, body, ...args) {
|
|
891
|
+
return this.#execute(path, bodyOptions("PATCH", body, args[0]));
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Runs a {@link defineEndpoint | typed endpoint}: `vars` fill its path
|
|
895
|
+
* params, build its query and body, and its `response` schema, if it has
|
|
896
|
+
* one, validates the decoded body before this resolves. A failing schema
|
|
897
|
+
* rejects with code `VALIDATION_FAILED`, carrying the issues as `body`.
|
|
898
|
+
*
|
|
899
|
+
* ```ts
|
|
900
|
+
* const user = await api.call(getUser, { id: '7' })
|
|
901
|
+
* ```
|
|
902
|
+
*/
|
|
903
|
+
call(endpoint, vars, options) {
|
|
904
|
+
const requestOptions = resolveEndpointOptions(endpoint, vars, options);
|
|
905
|
+
const schema = endpoint.response;
|
|
906
|
+
const run = async () => {
|
|
907
|
+
const response = await this.#run(endpoint.path, requestOptions);
|
|
908
|
+
if (schema === void 0) return response;
|
|
909
|
+
return {
|
|
910
|
+
...response,
|
|
911
|
+
data: await decodeEndpointResponse(schema, response)
|
|
912
|
+
};
|
|
913
|
+
};
|
|
914
|
+
return createConduitPromise(run(), (response) => redactResponse(response, this.#config.redact));
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Posts a `FormData` or `Blob`, with no default timeout, since a slow
|
|
918
|
+
* connection is not a hung one. It is a `post` that defaults its method and
|
|
919
|
+
* skips the timeout, and it runs through the same middleware stack as
|
|
920
|
+
* everything else. For progress events use `uploadWithProgress` from the
|
|
921
|
+
* `/upload` entry.
|
|
922
|
+
*/
|
|
923
|
+
upload(path, body, options = {}) {
|
|
924
|
+
const { meta, ...rest } = options;
|
|
925
|
+
return this.#execute(path, {
|
|
926
|
+
...rest,
|
|
927
|
+
method: "POST",
|
|
928
|
+
body,
|
|
929
|
+
meta: {
|
|
930
|
+
timeoutMs: 0,
|
|
931
|
+
...meta
|
|
932
|
+
}
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
/** Opens a cancellation boundary. Requests made through it carry `name` as their owner. */
|
|
936
|
+
scope(name) {
|
|
937
|
+
this.#assertAlive();
|
|
938
|
+
const scope = createScope({
|
|
939
|
+
name,
|
|
940
|
+
createExecutor: (getSignal, owner) => (path, options) => this.#execute(path, options, getSignal(), owner),
|
|
941
|
+
onDispose: (released) => {
|
|
942
|
+
this.#scopes.delete(released);
|
|
943
|
+
}
|
|
944
|
+
});
|
|
945
|
+
this.#scopes.add(scope);
|
|
946
|
+
return scope;
|
|
947
|
+
}
|
|
948
|
+
/** Cancels everything in flight, across every scope. The client and its scopes stay usable. */
|
|
949
|
+
abortAll(reason) {
|
|
950
|
+
const message = reason ?? "Every in-flight request was aborted.";
|
|
951
|
+
this.#root.abort(new ConduitError({
|
|
952
|
+
code: "ABORTED",
|
|
953
|
+
message
|
|
954
|
+
}));
|
|
955
|
+
this.#root = new AbortController();
|
|
956
|
+
for (const scope of this.#scopes) scope.abort(message);
|
|
957
|
+
}
|
|
958
|
+
destroy() {
|
|
959
|
+
if (this.#isDestroyed) return;
|
|
960
|
+
this.#isDestroyed = true;
|
|
961
|
+
this.#root.abort(new ConduitError({
|
|
962
|
+
code: "ABORTED",
|
|
963
|
+
message: "The client was destroyed."
|
|
964
|
+
}));
|
|
965
|
+
for (const scope of [...this.#scopes]) scope.dispose();
|
|
966
|
+
for (let index = this.#plugins.length - 1; index >= 0; index--) this.#plugins[index]?.onDestroy?.();
|
|
967
|
+
this.#plugins.length = 0;
|
|
968
|
+
this.#middlewares.length = 0;
|
|
969
|
+
this.#resetListeners.clear();
|
|
970
|
+
this.#changeListeners.clear();
|
|
971
|
+
this.#dispatch = this.#transport;
|
|
972
|
+
if (this.#events.active) this.#events.emit("client:destroy", {
|
|
973
|
+
type: "client:destroy",
|
|
974
|
+
at: Date.now()
|
|
975
|
+
});
|
|
976
|
+
this.#events.clear();
|
|
977
|
+
}
|
|
978
|
+
#subscribe(listeners, listener) {
|
|
979
|
+
listeners.add(listener);
|
|
980
|
+
return () => {
|
|
981
|
+
listeners.delete(listener);
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
/** Separate from `abortAll`: a sign-out has to forget what the client already holds. */
|
|
985
|
+
#resetIdentity() {
|
|
986
|
+
this.#notify(this.#resetListeners, (listener) => {
|
|
987
|
+
listener();
|
|
988
|
+
});
|
|
989
|
+
}
|
|
990
|
+
/** Runs every listener, and reports one that throws without stopping the rest. */
|
|
991
|
+
#notify(listeners, run) {
|
|
992
|
+
for (const listener of [...listeners]) try {
|
|
993
|
+
run(listener);
|
|
994
|
+
} catch (error) {
|
|
995
|
+
reportError(this.#config.logger, "A plugin listener threw.", error);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
#assertAlive() {
|
|
999
|
+
if (this.#isDestroyed) throw new ConduitError({
|
|
1000
|
+
code: "DESTROYED",
|
|
1001
|
+
message: "This client was destroyed. Create a new one."
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
/** Everything a request's identity depends on, derived once and shared with `getKey`. */
|
|
1005
|
+
#prepare(path, options) {
|
|
1006
|
+
const config = this.#config;
|
|
1007
|
+
const method = options.method ?? "GET";
|
|
1008
|
+
const resolved = this.#policy.resolve(applyPathParams(path, options.params, config.logger));
|
|
1009
|
+
const url = appendQuery(resolved.href, options.query);
|
|
1010
|
+
const encoded = encodeBody(options.body);
|
|
1011
|
+
const credentials = options.credentials ?? config.credentials;
|
|
1012
|
+
const parse = options.parse ?? config.parse;
|
|
1013
|
+
if (encoded.body !== null && isBodyless(method)) throw new ConduitError({
|
|
1014
|
+
code: "INVALID_ARGUMENT",
|
|
1015
|
+
message: `${method} ${resolved.origin}${resolved.pathname} cannot carry a body. Drop it or use another method.`
|
|
1016
|
+
});
|
|
1017
|
+
const configHeaders = config.headers?.();
|
|
1018
|
+
const variance = deriveVariance(configHeaders, options.headers, config.vary, credentials);
|
|
1019
|
+
return {
|
|
1020
|
+
method,
|
|
1021
|
+
url,
|
|
1022
|
+
encoded,
|
|
1023
|
+
variance,
|
|
1024
|
+
credentials,
|
|
1025
|
+
parse,
|
|
1026
|
+
configHeaders,
|
|
1027
|
+
isCacheable: isCacheable(method, options.cacheable),
|
|
1028
|
+
key: options.key ?? deriveKey({
|
|
1029
|
+
method,
|
|
1030
|
+
url,
|
|
1031
|
+
body: encoded.body,
|
|
1032
|
+
variance,
|
|
1033
|
+
parse
|
|
1034
|
+
})
|
|
1035
|
+
};
|
|
1036
|
+
}
|
|
1037
|
+
#execute(path, options, scopeSignal, scopeOwner) {
|
|
1038
|
+
const run = this.#run(path, options, scopeSignal, scopeOwner);
|
|
1039
|
+
return createConduitPromise(run, (response) => redactResponse(response, this.#config.redact));
|
|
1040
|
+
}
|
|
1041
|
+
#buildRequest(path, options, scopeSignal, scopeOwner) {
|
|
1042
|
+
const config = this.#config;
|
|
1043
|
+
const prepared = this.#prepare(path, options);
|
|
1044
|
+
const signal = composeSignals([
|
|
1045
|
+
this.#root.signal,
|
|
1046
|
+
scopeSignal,
|
|
1047
|
+
options.signal
|
|
1048
|
+
]);
|
|
1049
|
+
return createRequest({
|
|
1050
|
+
url: prepared.url,
|
|
1051
|
+
method: prepared.method,
|
|
1052
|
+
body: prepared.encoded.body,
|
|
1053
|
+
signal,
|
|
1054
|
+
key: prepared.key,
|
|
1055
|
+
variance: prepared.variance,
|
|
1056
|
+
lane: options.lane ?? config.lane,
|
|
1057
|
+
owner: options.owner ?? scopeOwner ?? config.owner,
|
|
1058
|
+
tags: options.tags ?? EMPTY_TAGS,
|
|
1059
|
+
cacheable: prepared.isCacheable,
|
|
1060
|
+
parse: prepared.parse,
|
|
1061
|
+
credentials: prepared.credentials,
|
|
1062
|
+
...mergePassthrough(options, config),
|
|
1063
|
+
meta: options.meta === void 0 ? {} : { ...options.meta },
|
|
1064
|
+
redactUrl: this.#redactUrl,
|
|
1065
|
+
buildHeaders: () => buildHeaders(prepared.configHeaders, options.headers, prepared.encoded.contentType)
|
|
1066
|
+
});
|
|
1067
|
+
}
|
|
1068
|
+
async #run(path, options, scopeSignal, scopeOwner) {
|
|
1069
|
+
this.#assertAlive();
|
|
1070
|
+
const config = this.#config;
|
|
1071
|
+
const request = this.#buildRequest(path, options, scopeSignal, scopeOwner);
|
|
1072
|
+
const isWatched = this.#events.active;
|
|
1073
|
+
const started = isWatched ? getMonotonicTime() : 0;
|
|
1074
|
+
const exposed = isWatched ? redactRequest(request, config.redact) : request;
|
|
1075
|
+
if (isWatched) this.#events.emit("request:start", {
|
|
1076
|
+
type: "request:start",
|
|
1077
|
+
request: exposed,
|
|
1078
|
+
at: Date.now()
|
|
1079
|
+
});
|
|
1080
|
+
try {
|
|
1081
|
+
const response = await this.#dispatch(request);
|
|
1082
|
+
if (isWatched) this.#events.emit("request:settle", {
|
|
1083
|
+
type: "request:settle",
|
|
1084
|
+
request: exposed,
|
|
1085
|
+
response: redactResponse(response, config.redact),
|
|
1086
|
+
durationMs: getMonotonicTime() - started,
|
|
1087
|
+
at: Date.now()
|
|
1088
|
+
});
|
|
1089
|
+
return response;
|
|
1090
|
+
} catch (cause) {
|
|
1091
|
+
const error = toConduitError(cause);
|
|
1092
|
+
error.requestId ??= request.meta.requestId;
|
|
1093
|
+
if (isWatched) this.#events.emit("request:error", {
|
|
1094
|
+
type: "request:error",
|
|
1095
|
+
request: exposed,
|
|
1096
|
+
error,
|
|
1097
|
+
durationMs: getMonotonicTime() - started,
|
|
1098
|
+
at: Date.now()
|
|
1099
|
+
});
|
|
1100
|
+
throw error;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
function createClient(config) {
|
|
1105
|
+
return new Client(config);
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// src/primitives/freeze.ts
|
|
1109
|
+
function deepFreeze(value, seen) {
|
|
1110
|
+
if (typeof value !== "object" || value === null || seen.has(value)) return;
|
|
1111
|
+
seen.add(value);
|
|
1112
|
+
Object.freeze(value);
|
|
1113
|
+
if (Array.isArray(value)) {
|
|
1114
|
+
for (const entry of value) deepFreeze(entry, seen);
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
if (Object.getPrototypeOf(value) === Object.prototype) for (const entry of Object.values(value)) deepFreeze(entry, seen);
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Marks a body that more than one caller holds. Deep in development, where
|
|
1121
|
+
* catching the mutation matters, shallow in production, where the cost does.
|
|
1122
|
+
*/
|
|
1123
|
+
function protect(data) {
|
|
1124
|
+
if (typeof data !== "object" || data === null) return;
|
|
1125
|
+
if (IS_DEVELOPMENT) {
|
|
1126
|
+
deepFreeze(data, /* @__PURE__ */ new WeakSet());
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
Object.freeze(data);
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// src/plugins/cache.ts
|
|
1133
|
+
const DEFAULT_TTL_MS = 3e4;
|
|
1134
|
+
const DEFAULT_MAX_ENTRIES$1 = 200;
|
|
1135
|
+
/** What `setData` builds on when nothing is stored under the key yet. */
|
|
1136
|
+
const EMPTY_ENTRY = {
|
|
1137
|
+
status: 200,
|
|
1138
|
+
headers: new Headers(),
|
|
1139
|
+
tags: []
|
|
1140
|
+
};
|
|
1141
|
+
/**
|
|
1142
|
+
* Tags accumulate rather than being replaced. Several callers populate one key
|
|
1143
|
+
* and only some know its tags, so last-write-wins would unhook the entry from
|
|
1144
|
+
* `invalidateTag` without saying so.
|
|
1145
|
+
*/
|
|
1146
|
+
function mergeTags(previous, next) {
|
|
1147
|
+
if (previous === void 0 || previous.length === 0) return next;
|
|
1148
|
+
if (next.length === 0) return previous;
|
|
1149
|
+
const merged = new Set(previous);
|
|
1150
|
+
for (const tag of next) merged.add(tag);
|
|
1151
|
+
return merged.size === previous.length ? previous : [...merged];
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* A response cache shared by every bundle, so a remote that mounts second reads
|
|
1155
|
+
* what the first already fetched. A hit costs a map lookup and nothing else.
|
|
1156
|
+
*
|
|
1157
|
+
* It stores what `request.cacheable` allows, which is `GET` and `HEAD` unless a
|
|
1158
|
+
* request or endpoint says otherwise. Tags only label entries for `invalidateTag`.
|
|
1159
|
+
*/
|
|
1160
|
+
function cache(config = {}) {
|
|
1161
|
+
const ttlMs = config.ttlMs ?? DEFAULT_TTL_MS;
|
|
1162
|
+
const max = config.max ?? DEFAULT_MAX_ENTRIES$1;
|
|
1163
|
+
const staleMs = config.staleMs ?? 0;
|
|
1164
|
+
const entries = /* @__PURE__ */ new Map();
|
|
1165
|
+
const revalidating = /* @__PURE__ */ new Set();
|
|
1166
|
+
/**
|
|
1167
|
+
* A read that started before an invalidation must not store what it fetched.
|
|
1168
|
+
* Tracked per read rather than by a shared counter, which would also discard
|
|
1169
|
+
* every unrelated response in flight at the time.
|
|
1170
|
+
*/
|
|
1171
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
1172
|
+
const lifetime = new AbortController();
|
|
1173
|
+
let events;
|
|
1174
|
+
let context;
|
|
1175
|
+
const begin = (request) => {
|
|
1176
|
+
const pending = {
|
|
1177
|
+
key: request.key,
|
|
1178
|
+
tags: request.tags,
|
|
1179
|
+
isSuppressed: false
|
|
1180
|
+
};
|
|
1181
|
+
inFlight.add(pending);
|
|
1182
|
+
return pending;
|
|
1183
|
+
};
|
|
1184
|
+
const suppress = (matches) => {
|
|
1185
|
+
for (const pending of inFlight) if (matches(pending)) pending.isSuppressed = true;
|
|
1186
|
+
};
|
|
1187
|
+
const announce = (target, removed) => {
|
|
1188
|
+
if (removed === 0) return removed;
|
|
1189
|
+
context?.notifyCacheChange({
|
|
1190
|
+
type: "invalidate",
|
|
1191
|
+
target
|
|
1192
|
+
});
|
|
1193
|
+
if (events?.active === true) events.emit("cache:invalidate", {
|
|
1194
|
+
type: "cache:invalidate",
|
|
1195
|
+
target,
|
|
1196
|
+
removed,
|
|
1197
|
+
at: Date.now()
|
|
1198
|
+
});
|
|
1199
|
+
return removed;
|
|
1200
|
+
};
|
|
1201
|
+
const read = (key) => {
|
|
1202
|
+
const entry = entries.get(key);
|
|
1203
|
+
if (entry === void 0) return;
|
|
1204
|
+
entries.delete(key);
|
|
1205
|
+
entries.set(key, entry);
|
|
1206
|
+
return entry;
|
|
1207
|
+
};
|
|
1208
|
+
const enforceCap = () => {
|
|
1209
|
+
if (entries.size > max) {
|
|
1210
|
+
const oldest = entries.keys().next().value;
|
|
1211
|
+
if (oldest !== void 0) entries.delete(oldest);
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
const write = (request, response, pending) => {
|
|
1215
|
+
if (pending.isSuppressed) return;
|
|
1216
|
+
const now = Date.now();
|
|
1217
|
+
protect(response.data);
|
|
1218
|
+
entries.set(request.key, {
|
|
1219
|
+
status: response.status,
|
|
1220
|
+
headers: response.headers,
|
|
1221
|
+
data: response.data,
|
|
1222
|
+
tags: mergeTags(entries.get(request.key)?.tags, request.tags),
|
|
1223
|
+
freshUntil: now + ttlMs,
|
|
1224
|
+
staleUntil: now + ttlMs + staleMs
|
|
1225
|
+
});
|
|
1226
|
+
enforceCap();
|
|
1227
|
+
};
|
|
1228
|
+
const serve = (entry, request, from) => ({
|
|
1229
|
+
status: entry.status,
|
|
1230
|
+
headers: entry.headers,
|
|
1231
|
+
data: entry.data,
|
|
1232
|
+
raw: void 0,
|
|
1233
|
+
from,
|
|
1234
|
+
attempt: 1,
|
|
1235
|
+
request
|
|
1236
|
+
});
|
|
1237
|
+
const isStorable = (response) => {
|
|
1238
|
+
const control = response.headers.get("cache-control");
|
|
1239
|
+
return control === null || !/no-store|no-cache/i.test(control);
|
|
1240
|
+
};
|
|
1241
|
+
const refresh = (request, next) => {
|
|
1242
|
+
if (revalidating.has(request.key)) return false;
|
|
1243
|
+
revalidating.add(request.key);
|
|
1244
|
+
const detached = withRequest(request, {
|
|
1245
|
+
signal: lifetime.signal,
|
|
1246
|
+
meta: {
|
|
1247
|
+
...request.meta,
|
|
1248
|
+
cache: "bypass"
|
|
1249
|
+
}
|
|
1250
|
+
});
|
|
1251
|
+
const pending = begin(detached);
|
|
1252
|
+
(context?.dispatch ?? next)(detached).then((response) => {
|
|
1253
|
+
if (isStorable(response)) write(detached, response, pending);
|
|
1254
|
+
}).catch((error) => {
|
|
1255
|
+
reportError(context?.config.logger ?? consoleLogger, "A background refresh failed.", error);
|
|
1256
|
+
}).finally(() => {
|
|
1257
|
+
inFlight.delete(pending);
|
|
1258
|
+
revalidating.delete(request.key);
|
|
1259
|
+
});
|
|
1260
|
+
return true;
|
|
1261
|
+
};
|
|
1262
|
+
const fetchAndStore = async (request, next) => {
|
|
1263
|
+
const pending = begin(request);
|
|
1264
|
+
try {
|
|
1265
|
+
const response = await next(request);
|
|
1266
|
+
if (isStorable(response)) write(request, response, pending);
|
|
1267
|
+
return response;
|
|
1268
|
+
} finally {
|
|
1269
|
+
inFlight.delete(pending);
|
|
1270
|
+
}
|
|
1271
|
+
};
|
|
1272
|
+
/** The stored answer for a request, while it is fresh or may still be served stale. */
|
|
1273
|
+
const serveStored = (entry, request, next, now) => {
|
|
1274
|
+
if (now < entry.freshUntil) {
|
|
1275
|
+
if (events?.active === true) events.emit("cache:hit", {
|
|
1276
|
+
type: "cache:hit",
|
|
1277
|
+
key: formatKey(request),
|
|
1278
|
+
owner: request.owner,
|
|
1279
|
+
at: now
|
|
1280
|
+
});
|
|
1281
|
+
return serve(entry, request, "cache");
|
|
1282
|
+
}
|
|
1283
|
+
if (now >= entry.staleUntil) return;
|
|
1284
|
+
const hasStarted = refresh(request, next);
|
|
1285
|
+
if (events?.active === true) events.emit("cache:stale", {
|
|
1286
|
+
type: "cache:stale",
|
|
1287
|
+
key: formatKey(request),
|
|
1288
|
+
owner: request.owner,
|
|
1289
|
+
isRevalidating: hasStarted,
|
|
1290
|
+
at: now
|
|
1291
|
+
});
|
|
1292
|
+
return serve(entry, request, "stale");
|
|
1293
|
+
};
|
|
1294
|
+
const middleware = async (request, next) => {
|
|
1295
|
+
const mode = request.meta.cache;
|
|
1296
|
+
if (mode === "bypass" || !request.cacheable) return next(request);
|
|
1297
|
+
if (mode === "refresh") return fetchAndStore(request, next);
|
|
1298
|
+
const now = Date.now();
|
|
1299
|
+
const entry = read(request.key);
|
|
1300
|
+
const stored = entry === void 0 ? void 0 : serveStored(entry, request, next, now);
|
|
1301
|
+
if (stored !== void 0) return stored;
|
|
1302
|
+
if (events?.active === true) events.emit("cache:miss", {
|
|
1303
|
+
type: "cache:miss",
|
|
1304
|
+
key: formatKey(request),
|
|
1305
|
+
owner: request.owner,
|
|
1306
|
+
at: now
|
|
1307
|
+
});
|
|
1308
|
+
return fetchAndStore(request, next);
|
|
1309
|
+
};
|
|
1310
|
+
const clearCache = () => {
|
|
1311
|
+
const removed = entries.size;
|
|
1312
|
+
entries.clear();
|
|
1313
|
+
suppress(() => true);
|
|
1314
|
+
announce("*", removed);
|
|
1315
|
+
};
|
|
1316
|
+
let release;
|
|
1317
|
+
return {
|
|
1318
|
+
name: "cache",
|
|
1319
|
+
middleware,
|
|
1320
|
+
onInit: (ctx) => {
|
|
1321
|
+
events = ctx.events;
|
|
1322
|
+
context = ctx;
|
|
1323
|
+
release = ctx.onResetIdentity(clearCache);
|
|
1324
|
+
return {
|
|
1325
|
+
invalidate: (key) => {
|
|
1326
|
+
suppress((pending) => pending.key === key);
|
|
1327
|
+
return announce(key, entries.delete(key) ? 1 : 0) > 0;
|
|
1328
|
+
},
|
|
1329
|
+
invalidateTag: (tag) => {
|
|
1330
|
+
let removed = 0;
|
|
1331
|
+
for (const [key, entry] of entries) if (entry.tags.includes(tag)) {
|
|
1332
|
+
entries.delete(key);
|
|
1333
|
+
removed++;
|
|
1334
|
+
}
|
|
1335
|
+
suppress((pending) => pending.tags.includes(tag));
|
|
1336
|
+
return announce(`tag:${tag}`, removed);
|
|
1337
|
+
},
|
|
1338
|
+
clearCache,
|
|
1339
|
+
getCacheSize: () => entries.size,
|
|
1340
|
+
setData: (key, data) => {
|
|
1341
|
+
const existing = entries.get(key);
|
|
1342
|
+
const { status, headers, tags } = existing ?? EMPTY_ENTRY;
|
|
1343
|
+
const previous = existing?.data;
|
|
1344
|
+
const next = typeof data === "function" ? data(previous) : data;
|
|
1345
|
+
const now = Date.now();
|
|
1346
|
+
protect(next);
|
|
1347
|
+
entries.set(key, {
|
|
1348
|
+
status,
|
|
1349
|
+
headers,
|
|
1350
|
+
data: next,
|
|
1351
|
+
tags,
|
|
1352
|
+
freshUntil: now + ttlMs,
|
|
1353
|
+
staleUntil: now + ttlMs + staleMs
|
|
1354
|
+
});
|
|
1355
|
+
enforceCap();
|
|
1356
|
+
context?.notifyCacheChange({
|
|
1357
|
+
type: "set",
|
|
1358
|
+
key,
|
|
1359
|
+
data: next,
|
|
1360
|
+
at: now
|
|
1361
|
+
});
|
|
1362
|
+
if (events?.active === true) events.emit("cache:set", {
|
|
1363
|
+
type: "cache:set",
|
|
1364
|
+
key,
|
|
1365
|
+
data: next,
|
|
1366
|
+
at: now
|
|
1367
|
+
});
|
|
1368
|
+
return previous;
|
|
1369
|
+
}
|
|
1370
|
+
};
|
|
1371
|
+
},
|
|
1372
|
+
onDestroy: () => {
|
|
1373
|
+
release?.();
|
|
1374
|
+
release = void 0;
|
|
1375
|
+
lifetime.abort();
|
|
1376
|
+
entries.clear();
|
|
1377
|
+
revalidating.clear();
|
|
1378
|
+
inFlight.clear();
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
// src/plugins/dedupe.ts
|
|
1384
|
+
/**
|
|
1385
|
+
* One request per key, however many callers ask for it. It shares a flight for
|
|
1386
|
+
* every request that is `cacheable`.
|
|
1387
|
+
*
|
|
1388
|
+
* Cancellation is reference-counted. The flight runs on its own controller and
|
|
1389
|
+
* aborts when the last participant leaves, so one remote unmounting cancels its
|
|
1390
|
+
* own wait and nobody else's.
|
|
1391
|
+
*/
|
|
1392
|
+
function dedupe() {
|
|
1393
|
+
const flights = /* @__PURE__ */ new Map();
|
|
1394
|
+
let events;
|
|
1395
|
+
const join = async (flight, request, isJoined) => {
|
|
1396
|
+
flight.participants++;
|
|
1397
|
+
let hasLeft = false;
|
|
1398
|
+
let rejectOnAbort = () => {};
|
|
1399
|
+
const leave = (isAborted) => {
|
|
1400
|
+
if (hasLeft) return;
|
|
1401
|
+
hasLeft = true;
|
|
1402
|
+
request.signal.removeEventListener("abort", onAbort);
|
|
1403
|
+
flight.participants--;
|
|
1404
|
+
if (isAborted && flight.participants === 0) {
|
|
1405
|
+
if (flights.get(request.key) === flight) flights.delete(request.key);
|
|
1406
|
+
flight.controller.abort(request.signal.reason);
|
|
1407
|
+
}
|
|
1408
|
+
};
|
|
1409
|
+
function onAbort() {
|
|
1410
|
+
const error = toAbortError(request);
|
|
1411
|
+
leave(true);
|
|
1412
|
+
rejectOnAbort(error);
|
|
1413
|
+
}
|
|
1414
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
1415
|
+
const abandoned = new Promise((_resolve, reject) => {
|
|
1416
|
+
rejectOnAbort = reject;
|
|
1417
|
+
});
|
|
1418
|
+
try {
|
|
1419
|
+
const response = await Promise.race([flight.promise, abandoned]);
|
|
1420
|
+
protect(response.data);
|
|
1421
|
+
return isJoined ? {
|
|
1422
|
+
...response,
|
|
1423
|
+
from: "dedupe",
|
|
1424
|
+
request
|
|
1425
|
+
} : response;
|
|
1426
|
+
} finally {
|
|
1427
|
+
leave(false);
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
const middleware = async (request, next) => {
|
|
1431
|
+
if (request.meta.dedupe === "bypass" || !request.cacheable) return next(request);
|
|
1432
|
+
if (request.signal.aborted) throw toAbortError(request);
|
|
1433
|
+
const existing = flights.get(request.key);
|
|
1434
|
+
if (existing !== void 0 && !existing.controller.signal.aborted) {
|
|
1435
|
+
if (events?.active === true) events.emit("dedupe:join", {
|
|
1436
|
+
type: "dedupe:join",
|
|
1437
|
+
key: formatKey(request),
|
|
1438
|
+
owner: request.owner,
|
|
1439
|
+
at: Date.now()
|
|
1440
|
+
});
|
|
1441
|
+
return join(existing, request, true);
|
|
1442
|
+
}
|
|
1443
|
+
const controller = new AbortController();
|
|
1444
|
+
const flight = {
|
|
1445
|
+
controller,
|
|
1446
|
+
participants: 0,
|
|
1447
|
+
promise: next(withRequest(request, { signal: controller.signal }))
|
|
1448
|
+
};
|
|
1449
|
+
flights.set(request.key, flight);
|
|
1450
|
+
const forget = () => {
|
|
1451
|
+
if (flights.get(request.key) === flight) flights.delete(request.key);
|
|
1452
|
+
};
|
|
1453
|
+
flight.promise.then(forget, forget);
|
|
1454
|
+
return join(flight, request, false);
|
|
1455
|
+
};
|
|
1456
|
+
let release;
|
|
1457
|
+
return {
|
|
1458
|
+
name: "dedupe",
|
|
1459
|
+
middleware,
|
|
1460
|
+
onInit: (ctx) => {
|
|
1461
|
+
events = ctx.events;
|
|
1462
|
+
release = ctx.onResetIdentity(() => {
|
|
1463
|
+
flights.clear();
|
|
1464
|
+
});
|
|
1465
|
+
return { getInFlightCount: () => flights.size };
|
|
1466
|
+
},
|
|
1467
|
+
onDestroy: () => {
|
|
1468
|
+
release?.();
|
|
1469
|
+
release = void 0;
|
|
1470
|
+
flights.clear();
|
|
1471
|
+
}
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
// src/plugins/observable.ts
|
|
1476
|
+
const DEFAULT_MAX_ENTRIES = 200;
|
|
1477
|
+
/**
|
|
1478
|
+
* Turns request traffic into per-key state for framework bindings to read. It
|
|
1479
|
+
* lives on the client, so two remotes rendering the same query watch one store.
|
|
1480
|
+
*/
|
|
1481
|
+
function observable(config = {}) {
|
|
1482
|
+
const max = config.max ?? DEFAULT_MAX_ENTRIES;
|
|
1483
|
+
const stores = /* @__PURE__ */ new Map();
|
|
1484
|
+
/** Tags seen on requests for a key, so a `cache:invalidate` tag target can be matched here too. */
|
|
1485
|
+
const tagsByKey = /* @__PURE__ */ new Map();
|
|
1486
|
+
let generation = 0;
|
|
1487
|
+
/** Counts identity resets, so a read that started before one never writes after it. */
|
|
1488
|
+
let epoch = 0;
|
|
1489
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1490
|
+
const enter = (key) => {
|
|
1491
|
+
pending.set(key, (pending.get(key) ?? 0) + 1);
|
|
1492
|
+
};
|
|
1493
|
+
/** Drops one participant and reports how many are left. */
|
|
1494
|
+
const leave = (key) => {
|
|
1495
|
+
const left = (pending.get(key) ?? 1) - 1;
|
|
1496
|
+
if (left <= 0) {
|
|
1497
|
+
pending.delete(key);
|
|
1498
|
+
return 0;
|
|
1499
|
+
}
|
|
1500
|
+
pending.set(key, left);
|
|
1501
|
+
return left;
|
|
1502
|
+
};
|
|
1503
|
+
const trackTags = (request) => {
|
|
1504
|
+
if (request.tags.length === 0) return;
|
|
1505
|
+
let known = tagsByKey.get(request.key);
|
|
1506
|
+
if (known === void 0) {
|
|
1507
|
+
known = /* @__PURE__ */ new Set();
|
|
1508
|
+
tagsByKey.set(request.key, known);
|
|
1509
|
+
}
|
|
1510
|
+
for (const tag of request.tags) known.add(tag);
|
|
1511
|
+
};
|
|
1512
|
+
const wrappers = /* @__PURE__ */ new Map();
|
|
1513
|
+
const forget = (key) => {
|
|
1514
|
+
stores.delete(key);
|
|
1515
|
+
tagsByKey.delete(key);
|
|
1516
|
+
wrappers.delete(key);
|
|
1517
|
+
};
|
|
1518
|
+
let sweepTimer;
|
|
1519
|
+
const sweep = () => {
|
|
1520
|
+
if (stores.size <= max) return;
|
|
1521
|
+
for (const [key, store] of stores) {
|
|
1522
|
+
if (stores.size <= max) break;
|
|
1523
|
+
if (store.listeners === 0) forget(key);
|
|
1524
|
+
}
|
|
1525
|
+
};
|
|
1526
|
+
const requestSweep = () => {
|
|
1527
|
+
if (sweepTimer !== void 0) return;
|
|
1528
|
+
sweepTimer = setTimeout(() => {
|
|
1529
|
+
sweepTimer = void 0;
|
|
1530
|
+
sweep();
|
|
1531
|
+
}, 0);
|
|
1532
|
+
};
|
|
1533
|
+
const getStore = (key) => {
|
|
1534
|
+
const existing = stores.get(key);
|
|
1535
|
+
if (existing !== void 0) {
|
|
1536
|
+
stores.delete(key);
|
|
1537
|
+
stores.set(key, existing);
|
|
1538
|
+
return existing;
|
|
1539
|
+
}
|
|
1540
|
+
const created = createStore(IDLE_QUERY_STATE);
|
|
1541
|
+
stores.set(key, created);
|
|
1542
|
+
if (stores.size > max) requestSweep();
|
|
1543
|
+
return created;
|
|
1544
|
+
};
|
|
1545
|
+
const bumpOne = (key) => {
|
|
1546
|
+
const store = stores.get(key);
|
|
1547
|
+
if (store === void 0) return;
|
|
1548
|
+
generation++;
|
|
1549
|
+
store.update((current) => ({
|
|
1550
|
+
...current,
|
|
1551
|
+
invalidatedAt: generation
|
|
1552
|
+
}));
|
|
1553
|
+
};
|
|
1554
|
+
const bumpAll = () => {
|
|
1555
|
+
generation++;
|
|
1556
|
+
for (const store of stores.values()) store.update((current) => ({
|
|
1557
|
+
...current,
|
|
1558
|
+
invalidatedAt: generation
|
|
1559
|
+
}));
|
|
1560
|
+
};
|
|
1561
|
+
const applySet = (key, data, at) => {
|
|
1562
|
+
const store = stores.get(key);
|
|
1563
|
+
if (store === void 0) return;
|
|
1564
|
+
store.set({
|
|
1565
|
+
status: "success",
|
|
1566
|
+
data,
|
|
1567
|
+
error: void 0,
|
|
1568
|
+
from: "cache",
|
|
1569
|
+
isFetching: false,
|
|
1570
|
+
updatedAt: at,
|
|
1571
|
+
invalidatedAt: store.getState().invalidatedAt
|
|
1572
|
+
});
|
|
1573
|
+
};
|
|
1574
|
+
const bumpTag = (tag) => {
|
|
1575
|
+
for (const [key, tags] of tagsByKey) if (tags.has(tag)) bumpOne(key);
|
|
1576
|
+
};
|
|
1577
|
+
const middleware = async (request, next) => {
|
|
1578
|
+
const store = getStore(request.key);
|
|
1579
|
+
const startedAtEpoch = epoch;
|
|
1580
|
+
trackTags(request);
|
|
1581
|
+
enter(request.key);
|
|
1582
|
+
store.update((current) => ({
|
|
1583
|
+
...current,
|
|
1584
|
+
status: current.data === void 0 ? "loading" : current.status,
|
|
1585
|
+
isFetching: true
|
|
1586
|
+
}));
|
|
1587
|
+
try {
|
|
1588
|
+
const response = await next(request);
|
|
1589
|
+
const others = leave(request.key);
|
|
1590
|
+
if (epoch !== startedAtEpoch) return response;
|
|
1591
|
+
store.set({
|
|
1592
|
+
status: "success",
|
|
1593
|
+
data: response.data,
|
|
1594
|
+
error: void 0,
|
|
1595
|
+
from: response.from,
|
|
1596
|
+
isFetching: others > 0,
|
|
1597
|
+
updatedAt: Date.now(),
|
|
1598
|
+
invalidatedAt: store.getState().invalidatedAt
|
|
1599
|
+
});
|
|
1600
|
+
return response;
|
|
1601
|
+
} catch (cause) {
|
|
1602
|
+
const error = toConduitError(cause);
|
|
1603
|
+
const others = leave(request.key);
|
|
1604
|
+
if (epoch !== startedAtEpoch) throw error;
|
|
1605
|
+
if (error.code === "ABORTED") {
|
|
1606
|
+
if (others === 0) store.update((current) => ({
|
|
1607
|
+
...current,
|
|
1608
|
+
status: current.data === void 0 ? "idle" : current.status,
|
|
1609
|
+
isFetching: false
|
|
1610
|
+
}));
|
|
1611
|
+
throw error;
|
|
1612
|
+
}
|
|
1613
|
+
store.update((current) => ({
|
|
1614
|
+
...current,
|
|
1615
|
+
status: "error",
|
|
1616
|
+
error,
|
|
1617
|
+
isFetching: others > 0,
|
|
1618
|
+
updatedAt: Date.now()
|
|
1619
|
+
}));
|
|
1620
|
+
throw error;
|
|
1621
|
+
}
|
|
1622
|
+
};
|
|
1623
|
+
let releaseReset;
|
|
1624
|
+
let releaseChange;
|
|
1625
|
+
return {
|
|
1626
|
+
name: "observable",
|
|
1627
|
+
middleware,
|
|
1628
|
+
onInit: (ctx) => {
|
|
1629
|
+
releaseReset = ctx.onResetIdentity(() => {
|
|
1630
|
+
epoch++;
|
|
1631
|
+
generation++;
|
|
1632
|
+
for (const store of stores.values()) store.set({
|
|
1633
|
+
...IDLE_QUERY_STATE,
|
|
1634
|
+
invalidatedAt: generation
|
|
1635
|
+
});
|
|
1636
|
+
tagsByKey.clear();
|
|
1637
|
+
});
|
|
1638
|
+
releaseChange = ctx.onCacheChange((change) => {
|
|
1639
|
+
if (change.type === "set") {
|
|
1640
|
+
applySet(change.key, change.data, change.at);
|
|
1641
|
+
return;
|
|
1642
|
+
}
|
|
1643
|
+
if (change.target === "*") bumpAll();
|
|
1644
|
+
else if (change.target.startsWith("tag:")) bumpTag(change.target.slice(4));
|
|
1645
|
+
else bumpOne(change.target);
|
|
1646
|
+
});
|
|
1647
|
+
return {
|
|
1648
|
+
observe: (key) => {
|
|
1649
|
+
const store = getStore(key);
|
|
1650
|
+
const existing = wrappers.get(key);
|
|
1651
|
+
if (existing !== void 0) return existing;
|
|
1652
|
+
const wrapped = {
|
|
1653
|
+
getState: () => store.getState(),
|
|
1654
|
+
subscribe: (listener) => {
|
|
1655
|
+
const off = store.subscribe(listener);
|
|
1656
|
+
let isReleased = false;
|
|
1657
|
+
const unsubscribe = () => {
|
|
1658
|
+
if (isReleased) return;
|
|
1659
|
+
isReleased = true;
|
|
1660
|
+
off();
|
|
1661
|
+
requestSweep();
|
|
1662
|
+
};
|
|
1663
|
+
return unsubscribe;
|
|
1664
|
+
}
|
|
1665
|
+
};
|
|
1666
|
+
wrappers.set(key, wrapped);
|
|
1667
|
+
return wrapped;
|
|
1668
|
+
},
|
|
1669
|
+
getObservedCount: () => stores.size
|
|
1670
|
+
};
|
|
1671
|
+
},
|
|
1672
|
+
onDestroy: () => {
|
|
1673
|
+
releaseReset?.();
|
|
1674
|
+
releaseReset = void 0;
|
|
1675
|
+
releaseChange?.();
|
|
1676
|
+
releaseChange = void 0;
|
|
1677
|
+
wrappers.clear();
|
|
1678
|
+
clearTimeout(sweepTimer);
|
|
1679
|
+
sweepTimer = void 0;
|
|
1680
|
+
stores.clear();
|
|
1681
|
+
tagsByKey.clear();
|
|
1682
|
+
pending.clear();
|
|
1683
|
+
}
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
// src/plugins/queue.ts
|
|
1688
|
+
const DEFAULT_CONCURRENCY = 6;
|
|
1689
|
+
const DEFAULT_LANES = [
|
|
1690
|
+
"critical",
|
|
1691
|
+
"default",
|
|
1692
|
+
"prefetch"
|
|
1693
|
+
];
|
|
1694
|
+
function assertPositive(what, value) {
|
|
1695
|
+
if (Number.isInteger(value) && value >= 1) return;
|
|
1696
|
+
throw new ConduitError({
|
|
1697
|
+
code: "INVALID_ARGUMENT",
|
|
1698
|
+
message: `queue({ ${what}: ${String(value)} }) must be a whole number of at least 1.`
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Bounded concurrency with priority lanes, so a remote's speculative
|
|
1703
|
+
* prefetching cannot queue ahead of the host's boot path down in the browser's
|
|
1704
|
+
* connection pool.
|
|
1705
|
+
*/
|
|
1706
|
+
function queue(config = {}) {
|
|
1707
|
+
const concurrency = config.concurrency ?? DEFAULT_CONCURRENCY;
|
|
1708
|
+
const lanes = config.lanes ?? DEFAULT_LANES;
|
|
1709
|
+
const limits = config.limits ?? {};
|
|
1710
|
+
const priorities = new Map(lanes.map((lane, index) => [lane, index]));
|
|
1711
|
+
assertPositive("concurrency", concurrency);
|
|
1712
|
+
for (const [lane, limit] of Object.entries(limits)) assertPositive(`limits.${lane}`, limit);
|
|
1713
|
+
const waiting = [];
|
|
1714
|
+
const laneActive = /* @__PURE__ */ new Map();
|
|
1715
|
+
let active = 0;
|
|
1716
|
+
let events;
|
|
1717
|
+
const getPriority = (lane) => priorities.get(lane) ?? lanes.length;
|
|
1718
|
+
const getLimit = (lane) => limits[lane] ?? concurrency;
|
|
1719
|
+
const countActive = (lane) => laneActive.get(lane) ?? 0;
|
|
1720
|
+
const canRun = (lane) => active < concurrency && countActive(lane) < getLimit(lane);
|
|
1721
|
+
const acquire = (lane) => {
|
|
1722
|
+
active++;
|
|
1723
|
+
laneActive.set(lane, countActive(lane) + 1);
|
|
1724
|
+
};
|
|
1725
|
+
const release = (lane) => {
|
|
1726
|
+
active--;
|
|
1727
|
+
laneActive.set(lane, countActive(lane) - 1);
|
|
1728
|
+
};
|
|
1729
|
+
const pump = () => {
|
|
1730
|
+
for (;;) {
|
|
1731
|
+
let chosen = -1;
|
|
1732
|
+
for (let index = 0; index < waiting.length; index++) {
|
|
1733
|
+
const waiter = waiting[index];
|
|
1734
|
+
const best = chosen === -1 ? void 0 : waiting[chosen];
|
|
1735
|
+
if (waiter === void 0 || !canRun(waiter.lane)) continue;
|
|
1736
|
+
if (best === void 0 || waiter.priority < best.priority) chosen = index;
|
|
1737
|
+
}
|
|
1738
|
+
if (chosen === -1) return;
|
|
1739
|
+
const [waiter] = waiting.splice(chosen, 1);
|
|
1740
|
+
if (waiter === void 0) return;
|
|
1741
|
+
waiter.detach();
|
|
1742
|
+
acquire(waiter.lane);
|
|
1743
|
+
waiter.resolve();
|
|
1744
|
+
}
|
|
1745
|
+
};
|
|
1746
|
+
const wait = (request) => new Promise((resolve, reject) => {
|
|
1747
|
+
const waiter = {
|
|
1748
|
+
lane: request.lane,
|
|
1749
|
+
priority: getPriority(request.lane),
|
|
1750
|
+
resolve,
|
|
1751
|
+
detach: () => {}
|
|
1752
|
+
};
|
|
1753
|
+
const onAbort = () => {
|
|
1754
|
+
const index = waiting.indexOf(waiter);
|
|
1755
|
+
if (index !== -1) waiting.splice(index, 1);
|
|
1756
|
+
waiter.detach();
|
|
1757
|
+
reject(toAbortError(request));
|
|
1758
|
+
};
|
|
1759
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
1760
|
+
waiter.detach = () => request.signal.removeEventListener("abort", onAbort);
|
|
1761
|
+
waiting.push(waiter);
|
|
1762
|
+
});
|
|
1763
|
+
const middleware = async (request, next) => {
|
|
1764
|
+
if (request.meta.queue === "bypass") return next(request);
|
|
1765
|
+
if (request.signal.aborted) throw toAbortError(request);
|
|
1766
|
+
if (canRun(request.lane)) acquire(request.lane);
|
|
1767
|
+
else {
|
|
1768
|
+
if (events?.active === true) events.emit("queue:enqueue", {
|
|
1769
|
+
type: "queue:enqueue",
|
|
1770
|
+
key: formatKey(request),
|
|
1771
|
+
owner: request.owner,
|
|
1772
|
+
lane: request.lane,
|
|
1773
|
+
depth: waiting.length,
|
|
1774
|
+
at: Date.now()
|
|
1775
|
+
});
|
|
1776
|
+
await wait(request);
|
|
1777
|
+
}
|
|
1778
|
+
try {
|
|
1779
|
+
return await next(request);
|
|
1780
|
+
} finally {
|
|
1781
|
+
release(request.lane);
|
|
1782
|
+
pump();
|
|
1783
|
+
}
|
|
1784
|
+
};
|
|
1785
|
+
return {
|
|
1786
|
+
name: "queue",
|
|
1787
|
+
middleware,
|
|
1788
|
+
onInit: (ctx) => {
|
|
1789
|
+
events = ctx.events;
|
|
1790
|
+
return {
|
|
1791
|
+
getQueueDepth: (lane) => lane === void 0 ? waiting.length : waiting.reduce((count, waiter) => count + (waiter.lane === lane ? 1 : 0), 0),
|
|
1792
|
+
getActiveCount: () => active
|
|
1793
|
+
};
|
|
1794
|
+
},
|
|
1795
|
+
onDestroy: () => {
|
|
1796
|
+
waiting.length = 0;
|
|
1797
|
+
laneActive.clear();
|
|
1798
|
+
active = 0;
|
|
1799
|
+
}
|
|
1800
|
+
};
|
|
1801
|
+
}
|
|
1802
|
+
|
|
1803
|
+
// src/plugins/retry.ts
|
|
1804
|
+
/** Methods conduit may replay after a failure. `POST` and `PATCH` are absent deliberately. */
|
|
1805
|
+
const IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
|
|
1806
|
+
"GET",
|
|
1807
|
+
"HEAD",
|
|
1808
|
+
"PUT",
|
|
1809
|
+
"DELETE",
|
|
1810
|
+
"OPTIONS"
|
|
1811
|
+
]);
|
|
1812
|
+
const RETRYABLE_STATUSES = [
|
|
1813
|
+
408,
|
|
1814
|
+
425,
|
|
1815
|
+
429,
|
|
1816
|
+
500,
|
|
1817
|
+
502,
|
|
1818
|
+
503,
|
|
1819
|
+
504
|
|
1820
|
+
];
|
|
1821
|
+
const DEFAULT_ATTEMPTS = 3;
|
|
1822
|
+
const DEFAULT_BASE_DELAY_MS = 300;
|
|
1823
|
+
const DEFAULT_MAX_DELAY_MS = 5e3;
|
|
1824
|
+
const DEFAULT_MAX_RETRY_AFTER_MS = 3e4;
|
|
1825
|
+
function parseRetryAfter(error) {
|
|
1826
|
+
const header = error.headers?.get("retry-after");
|
|
1827
|
+
if (header === void 0 || header === null || header.trim() === "") return;
|
|
1828
|
+
const seconds = Number(header);
|
|
1829
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
|
|
1830
|
+
const date = Date.parse(header);
|
|
1831
|
+
return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
|
|
1832
|
+
}
|
|
1833
|
+
function isBodyConsumed(request) {
|
|
1834
|
+
return request.body instanceof ReadableStream && request.body.locked;
|
|
1835
|
+
}
|
|
1836
|
+
/** Waits, unless the request is cancelled first. A backoff must not outlive its request. */
|
|
1837
|
+
function sleep(ms, request) {
|
|
1838
|
+
if (request.signal.aborted) return Promise.reject(toAbortError(request));
|
|
1839
|
+
return new Promise((resolve, reject) => {
|
|
1840
|
+
const timer = setTimeout(() => {
|
|
1841
|
+
request.signal.removeEventListener("abort", onAbort);
|
|
1842
|
+
resolve();
|
|
1843
|
+
}, ms);
|
|
1844
|
+
function onAbort() {
|
|
1845
|
+
clearTimeout(timer);
|
|
1846
|
+
reject(toAbortError(request));
|
|
1847
|
+
}
|
|
1848
|
+
request.signal.addEventListener("abort", onAbort, { once: true });
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* Replays a failed request with exponential backoff. Install it outside the
|
|
1853
|
+
* queue so a replay waits its turn instead of amplifying a failing endpoint.
|
|
1854
|
+
*/
|
|
1855
|
+
function retry(config = {}) {
|
|
1856
|
+
const attempts = config.attempts ?? DEFAULT_ATTEMPTS;
|
|
1857
|
+
const baseDelayMs = config.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
|
|
1858
|
+
const maxDelayMs = config.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
|
|
1859
|
+
const maxRetryAfterMs = config.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
|
|
1860
|
+
const jitter = config.jitter ?? true;
|
|
1861
|
+
const idempotentOnly = config.idempotentOnly ?? true;
|
|
1862
|
+
const statuses = new Set(config.statuses ?? RETRYABLE_STATUSES);
|
|
1863
|
+
let events;
|
|
1864
|
+
const isRetryable = (error, request, attempt) => {
|
|
1865
|
+
if (isBodyConsumed(request)) return false;
|
|
1866
|
+
if (config.shouldRetry !== void 0) return config.shouldRetry(error, request, attempt);
|
|
1867
|
+
if (idempotentOnly && !IDEMPOTENT_METHODS.has(request.method) && !request.cacheable) return false;
|
|
1868
|
+
if (error.code === "NETWORK" || error.code === "TIMEOUT") return true;
|
|
1869
|
+
return error.code === "HTTP_STATUS" && error.status !== void 0 && statuses.has(error.status);
|
|
1870
|
+
};
|
|
1871
|
+
/**
|
|
1872
|
+
* How long to wait before the next attempt, or `undefined` to give up. A
|
|
1873
|
+
* `Retry-After` beyond `maxRetryAfterMs` gives up rather than being clamped,
|
|
1874
|
+
* which would ignore what the server just asked for.
|
|
1875
|
+
*/
|
|
1876
|
+
const getBackoffMs = (attempt, retryAfterMs) => {
|
|
1877
|
+
if (retryAfterMs !== void 0) return retryAfterMs > maxRetryAfterMs ? void 0 : retryAfterMs;
|
|
1878
|
+
const window = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
|
|
1879
|
+
return jitter ? Math.random() * window : window;
|
|
1880
|
+
};
|
|
1881
|
+
const middleware = async (request, next) => {
|
|
1882
|
+
let attempt = 1;
|
|
1883
|
+
for (;;) {
|
|
1884
|
+
request.meta.attempt = attempt;
|
|
1885
|
+
try {
|
|
1886
|
+
return await next(request);
|
|
1887
|
+
} catch (cause) {
|
|
1888
|
+
const error = toConduitError(cause);
|
|
1889
|
+
const retryAfterMs = parseRetryAfter(error);
|
|
1890
|
+
if (retryAfterMs !== void 0) error.retryAfterMs = retryAfterMs;
|
|
1891
|
+
if (attempt >= attempts || !isRetryable(error, request, attempt)) throw error;
|
|
1892
|
+
const delay = getBackoffMs(attempt, retryAfterMs);
|
|
1893
|
+
if (delay === void 0) throw error;
|
|
1894
|
+
if (events?.active === true) events.emit("retry:attempt", {
|
|
1895
|
+
type: "retry:attempt",
|
|
1896
|
+
key: formatKey(request),
|
|
1897
|
+
owner: request.owner,
|
|
1898
|
+
attempt,
|
|
1899
|
+
delayMs: delay,
|
|
1900
|
+
code: error.code,
|
|
1901
|
+
at: Date.now()
|
|
1902
|
+
});
|
|
1903
|
+
config.onRetry?.({
|
|
1904
|
+
request,
|
|
1905
|
+
error,
|
|
1906
|
+
attempt,
|
|
1907
|
+
delayMs: delay
|
|
1908
|
+
});
|
|
1909
|
+
await sleep(delay, request);
|
|
1910
|
+
attempt++;
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
};
|
|
1914
|
+
return {
|
|
1915
|
+
name: "retry",
|
|
1916
|
+
middleware,
|
|
1917
|
+
onInit: (ctx) => {
|
|
1918
|
+
events = ctx.events;
|
|
1919
|
+
}
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
// src/primitives/timers.ts
|
|
1924
|
+
/** The largest delay `setTimeout` can hold without overflowing its 32-bit signed field. */
|
|
1925
|
+
const MAX_TIMER_DELAY_MS = 0x7fffffff;
|
|
1926
|
+
|
|
1927
|
+
// src/plugins/session.ts
|
|
1928
|
+
const UNAUTHORISED = 401;
|
|
1929
|
+
const DEFAULT_REFRESH_LEEWAY_MS = 6e4;
|
|
1930
|
+
/** Names of the headers a request holds, and what they hold, to see what `authorize` added. */
|
|
1931
|
+
function snapshotHeaders(headers) {
|
|
1932
|
+
const snapshot = /* @__PURE__ */ new Map();
|
|
1933
|
+
headers.forEach((value, name) => {
|
|
1934
|
+
snapshot.set(name, value);
|
|
1935
|
+
});
|
|
1936
|
+
return snapshot;
|
|
1937
|
+
}
|
|
1938
|
+
/**
|
|
1939
|
+
* One session for every bundle on the page. Reads and recovery are
|
|
1940
|
+
* single-flight, and losing the session runs once however many requests failed
|
|
1941
|
+
* at the same moment.
|
|
1942
|
+
*
|
|
1943
|
+
* Nothing about the session is sticky. A lost session is `anonymous`, and every
|
|
1944
|
+
* later request goes out without credentials until a read finds one again.
|
|
1945
|
+
*/
|
|
1946
|
+
function session(config) {
|
|
1947
|
+
const adapter = config.adapter;
|
|
1948
|
+
if (typeof adapter.identify !== "function") throw new ConduitError({
|
|
1949
|
+
code: "INVALID_ARGUMENT",
|
|
1950
|
+
message: "session({ adapter }) needs identify(session)."
|
|
1951
|
+
});
|
|
1952
|
+
const leewayMs = config.refreshLeewayMs ?? DEFAULT_REFRESH_LEEWAY_MS;
|
|
1953
|
+
const extraOrigins = new Set((config.origins ?? []).map(parseOrigin));
|
|
1954
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1955
|
+
const lifetime = new AbortController();
|
|
1956
|
+
/** One controller per in-flight credentialed request, so losing the session cancels only those. */
|
|
1957
|
+
const flights = /* @__PURE__ */ new Set();
|
|
1958
|
+
let state = {
|
|
1959
|
+
status: "unknown",
|
|
1960
|
+
session: null,
|
|
1961
|
+
error: null,
|
|
1962
|
+
updatedAt: 0
|
|
1963
|
+
};
|
|
1964
|
+
let reading;
|
|
1965
|
+
let readToken = 0;
|
|
1966
|
+
let renewing;
|
|
1967
|
+
let timer;
|
|
1968
|
+
/** Goes up on every successful read, so a request can tell the session it was sent under from today's. */
|
|
1969
|
+
let generation = 0;
|
|
1970
|
+
let lostGeneration = -1;
|
|
1971
|
+
let lostError;
|
|
1972
|
+
let lastIdentity;
|
|
1973
|
+
/** Whether a real identity has ever been observed, so the very first read never resets by itself. */
|
|
1974
|
+
let isIdentityKnown = false;
|
|
1975
|
+
let context;
|
|
1976
|
+
let events;
|
|
1977
|
+
let channel;
|
|
1978
|
+
const isLost = (next) => next.status === "anonymous" && next.error?.code === "UNAUTHENTICATED";
|
|
1979
|
+
const publish = (next) => {
|
|
1980
|
+
state = next;
|
|
1981
|
+
if (events?.active === true) events.emit("session:change", {
|
|
1982
|
+
type: "session:change",
|
|
1983
|
+
status: next.status,
|
|
1984
|
+
isLost: isLost(next),
|
|
1985
|
+
at: next.updatedAt
|
|
1986
|
+
});
|
|
1987
|
+
for (const listener of [...listeners]) try {
|
|
1988
|
+
listener(next);
|
|
1989
|
+
} catch (error) {
|
|
1990
|
+
context?.config.logger.error(`[conduit] A session listener threw. The session is unaffected. ${String(error)}`);
|
|
1991
|
+
}
|
|
1992
|
+
};
|
|
1993
|
+
const broadcast = () => {
|
|
1994
|
+
if (!lifetime.signal.aborted) channel?.postMessage({ type: "session:change" });
|
|
1995
|
+
};
|
|
1996
|
+
/** Arms a timer for a delay of any size, in chunks the platform can hold. */
|
|
1997
|
+
const stopRefreshTimer = () => {
|
|
1998
|
+
clearTimeout(timer);
|
|
1999
|
+
timer = void 0;
|
|
2000
|
+
};
|
|
2001
|
+
/** Reports a background read that failed. The state already says so, and nobody awaits it. */
|
|
2002
|
+
const reportInBackground = (promise) => {
|
|
2003
|
+
promise.catch((error) => {
|
|
2004
|
+
reportError(context?.config.logger ?? consoleLogger, "The session read failed.", error);
|
|
2005
|
+
});
|
|
2006
|
+
};
|
|
2007
|
+
const arm = (delayMs, run) => {
|
|
2008
|
+
if (delayMs > 0x7fffffff) {
|
|
2009
|
+
timer = setTimeout(() => {
|
|
2010
|
+
arm(delayMs - MAX_TIMER_DELAY_MS, run);
|
|
2011
|
+
}, MAX_TIMER_DELAY_MS);
|
|
2012
|
+
return;
|
|
2013
|
+
}
|
|
2014
|
+
timer = setTimeout(run, Math.max(0, delayMs));
|
|
2015
|
+
};
|
|
2016
|
+
const scheduleRefresh = (value) => {
|
|
2017
|
+
stopRefreshTimer();
|
|
2018
|
+
if (value === null || adapter.expiresAt === void 0) return;
|
|
2019
|
+
const expires = adapter.expiresAt(value);
|
|
2020
|
+
if (expires === void 0 || !Number.isFinite(expires)) return;
|
|
2021
|
+
const now = Date.now();
|
|
2022
|
+
const beforeLeeway = expires - now - leewayMs;
|
|
2023
|
+
if (beforeLeeway > 0) {
|
|
2024
|
+
arm(beforeLeeway, handleRefreshDue);
|
|
2025
|
+
return;
|
|
2026
|
+
}
|
|
2027
|
+
const untilExpiry = expires - now;
|
|
2028
|
+
if (untilExpiry > 0) arm(untilExpiry, handleRefreshDue);
|
|
2029
|
+
};
|
|
2030
|
+
const adapterContext = {
|
|
2031
|
+
request: (path, options) => {
|
|
2032
|
+
if (context === void 0) throw new ConduitError({
|
|
2033
|
+
code: "INVALID_ARGUMENT",
|
|
2034
|
+
message: "The session plugin was used before it was installed."
|
|
2035
|
+
});
|
|
2036
|
+
return context.request(path, {
|
|
2037
|
+
...options,
|
|
2038
|
+
lane: options?.lane ?? "critical",
|
|
2039
|
+
meta: {
|
|
2040
|
+
...options?.meta,
|
|
2041
|
+
session: "bypass",
|
|
2042
|
+
cache: "bypass",
|
|
2043
|
+
dedupe: "bypass"
|
|
2044
|
+
}
|
|
2045
|
+
});
|
|
2046
|
+
},
|
|
2047
|
+
signal: lifetime.signal
|
|
2048
|
+
};
|
|
2049
|
+
/** Cancels what is in flight under the current credentials, so none of it lands under the next ones. */
|
|
2050
|
+
const cancelFlights = (reason) => {
|
|
2051
|
+
for (const flight of [...flights]) flight.abort(reason);
|
|
2052
|
+
};
|
|
2053
|
+
/** Takes what a read found: the new generation, a reset if the user changed, and the new state. */
|
|
2054
|
+
const acceptRead = (value, isFromPeer) => {
|
|
2055
|
+
const identity = value === null ? void 0 : adapter.identify(value);
|
|
2056
|
+
const hasChangedIdentity = isIdentityKnown && identity !== lastIdentity;
|
|
2057
|
+
generation++;
|
|
2058
|
+
if (hasChangedIdentity) {
|
|
2059
|
+
cancelFlights(new ConduitError({
|
|
2060
|
+
code: "ABORTED",
|
|
2061
|
+
message: "The signed-in user changed."
|
|
2062
|
+
}));
|
|
2063
|
+
context?.resetIdentity();
|
|
2064
|
+
}
|
|
2065
|
+
lastIdentity = identity;
|
|
2066
|
+
isIdentityKnown = true;
|
|
2067
|
+
publish(value === null ? {
|
|
2068
|
+
status: "anonymous",
|
|
2069
|
+
session: null,
|
|
2070
|
+
error: null,
|
|
2071
|
+
updatedAt: Date.now()
|
|
2072
|
+
} : {
|
|
2073
|
+
status: "authenticated",
|
|
2074
|
+
session: value,
|
|
2075
|
+
error: null,
|
|
2076
|
+
updatedAt: Date.now()
|
|
2077
|
+
});
|
|
2078
|
+
scheduleRefresh(value);
|
|
2079
|
+
if (hasChangedIdentity && !isFromPeer) broadcast();
|
|
2080
|
+
return value;
|
|
2081
|
+
};
|
|
2082
|
+
const runRead = async (token, isFromPeer) => {
|
|
2083
|
+
publish({
|
|
2084
|
+
status: "loading",
|
|
2085
|
+
session: state.session,
|
|
2086
|
+
error: state.error,
|
|
2087
|
+
updatedAt: Date.now()
|
|
2088
|
+
});
|
|
2089
|
+
try {
|
|
2090
|
+
const value = await adapter.load(adapterContext);
|
|
2091
|
+
if (token !== readToken) return await (reading ?? Promise.resolve(state.session));
|
|
2092
|
+
return acceptRead(value, isFromPeer);
|
|
2093
|
+
} catch (cause) {
|
|
2094
|
+
if (token !== readToken) return await (reading ?? Promise.resolve(state.session));
|
|
2095
|
+
const error = isConduitError(cause) ? cause : toConduitError(cause, "UNKNOWN", `The session could not be read: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
2096
|
+
publish({
|
|
2097
|
+
status: "error",
|
|
2098
|
+
session: state.session,
|
|
2099
|
+
error,
|
|
2100
|
+
updatedAt: Date.now()
|
|
2101
|
+
});
|
|
2102
|
+
throw error;
|
|
2103
|
+
} finally {
|
|
2104
|
+
if (token === readToken) reading = void 0;
|
|
2105
|
+
}
|
|
2106
|
+
};
|
|
2107
|
+
const read = (isFromPeer = false) => {
|
|
2108
|
+
readToken++;
|
|
2109
|
+
reading = runRead(readToken, isFromPeer);
|
|
2110
|
+
return reading;
|
|
2111
|
+
};
|
|
2112
|
+
const load = () => {
|
|
2113
|
+
if (state.status === "authenticated" || state.status === "anonymous") return Promise.resolve(state.session);
|
|
2114
|
+
return reading ?? read();
|
|
2115
|
+
};
|
|
2116
|
+
const reload = () => read();
|
|
2117
|
+
const handleRefreshDue = () => {
|
|
2118
|
+
if (renewing === void 0) reportInBackground(reload());
|
|
2119
|
+
};
|
|
2120
|
+
const lose = (cause) => {
|
|
2121
|
+
if (lostGeneration === generation && lostError !== void 0) return lostError;
|
|
2122
|
+
const error = toConduitError(cause, "UNAUTHENTICATED");
|
|
2123
|
+
lostGeneration = generation;
|
|
2124
|
+
lostError = error;
|
|
2125
|
+
lastIdentity = void 0;
|
|
2126
|
+
isIdentityKnown = false;
|
|
2127
|
+
stopRefreshTimer();
|
|
2128
|
+
cancelFlights(error);
|
|
2129
|
+
publish({
|
|
2130
|
+
status: "anonymous",
|
|
2131
|
+
session: null,
|
|
2132
|
+
error,
|
|
2133
|
+
updatedAt: Date.now()
|
|
2134
|
+
});
|
|
2135
|
+
context?.resetIdentity();
|
|
2136
|
+
adapter.onClear?.();
|
|
2137
|
+
config.onUnauthenticated?.(error);
|
|
2138
|
+
broadcast();
|
|
2139
|
+
return error;
|
|
2140
|
+
};
|
|
2141
|
+
const isUnauthenticated = (error, request) => adapter.isUnauthenticated === void 0 ? error.code === "HTTP_STATUS" && error.status === UNAUTHORISED : adapter.isUnauthenticated(error, request);
|
|
2142
|
+
const renew = async () => {
|
|
2143
|
+
if (reading !== void 0) return reading.then((value) => value !== null, () => false);
|
|
2144
|
+
if (adapter.renew === void 0) return false;
|
|
2145
|
+
renewing ??= adapter.renew(adapterContext).then(async (recovered) => {
|
|
2146
|
+
if (recovered) await reload().catch((error) => {
|
|
2147
|
+
reportError(context?.config.logger ?? consoleLogger, "The read after renewal failed.", error);
|
|
2148
|
+
});
|
|
2149
|
+
return recovered && state.status === "authenticated";
|
|
2150
|
+
}).catch((error) => {
|
|
2151
|
+
reportError(context?.config.logger ?? consoleLogger, "The adapter could not renew the session.", error);
|
|
2152
|
+
return false;
|
|
2153
|
+
}).finally(() => {
|
|
2154
|
+
renewing = void 0;
|
|
2155
|
+
});
|
|
2156
|
+
return renewing;
|
|
2157
|
+
};
|
|
2158
|
+
const authorize = (request) => {
|
|
2159
|
+
if (adapter.authorize === void 0 || state.session === null) return request;
|
|
2160
|
+
const before = snapshotHeaders(request.headers);
|
|
2161
|
+
const authorized = adapter.authorize(request, state.session);
|
|
2162
|
+
const changed = [];
|
|
2163
|
+
authorized.headers.forEach((value, name) => {
|
|
2164
|
+
if (before.get(name) !== value) changed.push(name);
|
|
2165
|
+
});
|
|
2166
|
+
if (changed.length > 0) authorized.meta.credentialHeaders = [.../* @__PURE__ */ new Set([...authorized.meta.credentialHeaders ?? [], ...changed])];
|
|
2167
|
+
return authorized;
|
|
2168
|
+
};
|
|
2169
|
+
/** Sends one request with whatever credentials the session holds now. */
|
|
2170
|
+
const send = async (request, next) => {
|
|
2171
|
+
if (state.session === null) return next(request);
|
|
2172
|
+
const flight = new AbortController();
|
|
2173
|
+
const authorized = authorize(request);
|
|
2174
|
+
flights.add(flight);
|
|
2175
|
+
try {
|
|
2176
|
+
const signal = composeSignals([authorized.signal, flight.signal]);
|
|
2177
|
+
return await next(withRequest(authorized, { signal }));
|
|
2178
|
+
} finally {
|
|
2179
|
+
flights.delete(flight);
|
|
2180
|
+
}
|
|
2181
|
+
};
|
|
2182
|
+
/** A token adapter has nothing to send until it knows who is signed in. */
|
|
2183
|
+
const prepare = async () => {
|
|
2184
|
+
const isSettled = state.status === "authenticated" || state.status === "anonymous" || state.status === "error" && state.session !== null;
|
|
2185
|
+
if (adapter.authorize === void 0 || isSettled) return;
|
|
2186
|
+
try {
|
|
2187
|
+
await load();
|
|
2188
|
+
} catch (cause) {
|
|
2189
|
+
if (state.session === null) throw toConduitError(cause);
|
|
2190
|
+
}
|
|
2191
|
+
};
|
|
2192
|
+
const isInScope = (request) => {
|
|
2193
|
+
if (!URL.canParse(request.url)) return false;
|
|
2194
|
+
return context?.isApiOrigin(request.url) === true || extraOrigins.has(new URL(request.url).origin);
|
|
2195
|
+
};
|
|
2196
|
+
/**
|
|
2197
|
+
* What follows a rejected credentialed request: a replay with today's
|
|
2198
|
+
* session, after one try at renewal when it was sent under the current one.
|
|
2199
|
+
*/
|
|
2200
|
+
const recover = async (request, next, error, sentGeneration, sentIdentity) => {
|
|
2201
|
+
if (lostGeneration === generation && lostError !== void 0) throw lostError;
|
|
2202
|
+
if (sentGeneration === generation && !await renew()) throw lose(error);
|
|
2203
|
+
if (lastIdentity !== sentIdentity) throw toConduitError(error, "UNAUTHENTICATED", `${error.message} The user changed, so it was not replayed.`);
|
|
2204
|
+
try {
|
|
2205
|
+
return await send(request, next);
|
|
2206
|
+
} catch (replayCause) {
|
|
2207
|
+
const replayed = toConduitError(replayCause);
|
|
2208
|
+
throw isUnauthenticated(replayed, request) && state.session !== null ? lose(replayed) : replayed;
|
|
2209
|
+
}
|
|
2210
|
+
};
|
|
2211
|
+
const middleware = async (request, next) => {
|
|
2212
|
+
if (request.meta.session === "bypass" || !isInScope(request)) return next(request);
|
|
2213
|
+
await prepare();
|
|
2214
|
+
const sentGeneration = generation;
|
|
2215
|
+
const sentIdentity = lastIdentity;
|
|
2216
|
+
const hasCredentials = state.session !== null;
|
|
2217
|
+
try {
|
|
2218
|
+
return await send(request, next);
|
|
2219
|
+
} catch (cause) {
|
|
2220
|
+
const error = toConduitError(cause);
|
|
2221
|
+
if (!hasCredentials || !isUnauthenticated(error, request)) throw error;
|
|
2222
|
+
return recover(request, next, error, sentGeneration, sentIdentity);
|
|
2223
|
+
}
|
|
2224
|
+
};
|
|
2225
|
+
const handle = {
|
|
2226
|
+
getState: () => state,
|
|
2227
|
+
subscribe: (listener) => {
|
|
2228
|
+
listeners.add(listener);
|
|
2229
|
+
return () => {
|
|
2230
|
+
listeners.delete(listener);
|
|
2231
|
+
};
|
|
2232
|
+
},
|
|
2233
|
+
load,
|
|
2234
|
+
reload,
|
|
2235
|
+
clear: () => {
|
|
2236
|
+
stopRefreshTimer();
|
|
2237
|
+
readToken++;
|
|
2238
|
+
reading = void 0;
|
|
2239
|
+
lastIdentity = void 0;
|
|
2240
|
+
isIdentityKnown = false;
|
|
2241
|
+
cancelFlights(new ConduitError({
|
|
2242
|
+
code: "ABORTED",
|
|
2243
|
+
message: "The session was cleared."
|
|
2244
|
+
}));
|
|
2245
|
+
context?.resetIdentity();
|
|
2246
|
+
adapter.onClear?.();
|
|
2247
|
+
publish({
|
|
2248
|
+
status: "unknown",
|
|
2249
|
+
session: null,
|
|
2250
|
+
error: null,
|
|
2251
|
+
updatedAt: Date.now()
|
|
2252
|
+
});
|
|
2253
|
+
broadcast();
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
return {
|
|
2257
|
+
name: "session",
|
|
2258
|
+
middleware,
|
|
2259
|
+
onInit: (ctx) => {
|
|
2260
|
+
context = ctx;
|
|
2261
|
+
events = ctx.events;
|
|
2262
|
+
for (const origin of extraOrigins) if (!ctx.config.origins.includes(origin) && !ctx.isApiOrigin(origin)) ctx.config.logger.warn(`[conduit] session({ origins }) lists ${origin}, which is not in the client's origins, so every request to it is rejected. Add it to createClient({ origins }).`);
|
|
2263
|
+
if (config.channel !== void 0 && typeof BroadcastChannel === "function") {
|
|
2264
|
+
channel = new BroadcastChannel(config.channel);
|
|
2265
|
+
channel.onmessage = (message) => {
|
|
2266
|
+
if (message.data?.type === "session:change") reportInBackground(reading ?? read(true));
|
|
2267
|
+
};
|
|
2268
|
+
}
|
|
2269
|
+
if (config.autoLoad === true) reportInBackground(load());
|
|
2270
|
+
return { session: handle };
|
|
2271
|
+
},
|
|
2272
|
+
onDestroy: () => {
|
|
2273
|
+
stopRefreshTimer();
|
|
2274
|
+
lifetime.abort();
|
|
2275
|
+
channel?.close();
|
|
2276
|
+
channel = void 0;
|
|
2277
|
+
listeners.clear();
|
|
2278
|
+
}
|
|
2279
|
+
};
|
|
2280
|
+
}
|
|
2281
|
+
|
|
2282
|
+
// src/plugins/timeout.ts
|
|
2283
|
+
const DEFAULT_TIMEOUT_MS = 15e3;
|
|
2284
|
+
/**
|
|
2285
|
+
* Cancels a request that has taken too long, with code `TIMEOUT` rather than a
|
|
2286
|
+
* generic abort. Install it innermost so the clock covers one network attempt
|
|
2287
|
+
* rather than a whole retry sequence.
|
|
2288
|
+
*/
|
|
2289
|
+
function timeout(config = {}) {
|
|
2290
|
+
const defaultMs = config.ms ?? DEFAULT_TIMEOUT_MS;
|
|
2291
|
+
const middleware = async (request, next) => {
|
|
2292
|
+
const ms = request.meta.timeoutMs ?? defaultMs;
|
|
2293
|
+
if (!Number.isFinite(ms) || ms <= 0) return next(request);
|
|
2294
|
+
const controller = new AbortController();
|
|
2295
|
+
const timer = setTimeout(() => {
|
|
2296
|
+
controller.abort(createRequestError(request, "TIMEOUT", `exceeded its ${ms}ms timeout.`));
|
|
2297
|
+
}, Math.min(ms, MAX_TIMER_DELAY_MS));
|
|
2298
|
+
try {
|
|
2299
|
+
const signal = composeSignals([request.signal, controller.signal]);
|
|
2300
|
+
return await next(withRequest(request, { signal }));
|
|
2301
|
+
} finally {
|
|
2302
|
+
clearTimeout(timer);
|
|
2303
|
+
}
|
|
2304
|
+
};
|
|
2305
|
+
return {
|
|
2306
|
+
name: "timeout",
|
|
2307
|
+
middleware
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
// src/client/defaults.ts
|
|
2312
|
+
function defaults(client, config = {}) {
|
|
2313
|
+
let stack = client.with(observable(config.observable)).with(cache(config.cache)).with(dedupe());
|
|
2314
|
+
if (config.session !== void 0) stack = stack.with(session(config.session));
|
|
2315
|
+
if (config.retry !== false) stack = stack.with(retry(config.retry));
|
|
2316
|
+
stack = stack.with(queue(config.queue));
|
|
2317
|
+
if (config.timeout !== false) stack = stack.with(timeout(config.timeout));
|
|
2318
|
+
return stack;
|
|
2319
|
+
}
|
|
2320
|
+
|
|
2321
|
+
// src/plugins/api-version.ts
|
|
2322
|
+
const DEFAULT_HEADER$1 = "x-api-version";
|
|
2323
|
+
/**
|
|
2324
|
+
* Notices when a bundle is talking to an API it was not built against, and says
|
|
2325
|
+
* so once per server version rather than once per request. Error responses
|
|
2326
|
+
* count too, since a deployment that moved on often fails first.
|
|
2327
|
+
*/
|
|
2328
|
+
function apiVersion(config) {
|
|
2329
|
+
const header = config.header ?? DEFAULT_HEADER$1;
|
|
2330
|
+
const expected = String(config.expected);
|
|
2331
|
+
const reported = /* @__PURE__ */ new Set();
|
|
2332
|
+
let events;
|
|
2333
|
+
let logger;
|
|
2334
|
+
if (expected === "") throw new ConduitError({
|
|
2335
|
+
code: "INVALID_ARGUMENT",
|
|
2336
|
+
message: "apiVersion({ expected }) needs a version."
|
|
2337
|
+
});
|
|
2338
|
+
const check = (headers, url, method) => {
|
|
2339
|
+
const actual = headers?.get(header) ?? null;
|
|
2340
|
+
if (actual === null || actual === expected || reported.has(actual)) return;
|
|
2341
|
+
reported.add(actual);
|
|
2342
|
+
const report = {
|
|
2343
|
+
expected,
|
|
2344
|
+
actual,
|
|
2345
|
+
url
|
|
2346
|
+
};
|
|
2347
|
+
if (events?.active === true) events.emit("api-version:mismatch", {
|
|
2348
|
+
type: "api-version:mismatch",
|
|
2349
|
+
...report,
|
|
2350
|
+
at: Date.now()
|
|
2351
|
+
});
|
|
2352
|
+
if (config.onMismatch !== void 0) {
|
|
2353
|
+
config.onMismatch(report);
|
|
2354
|
+
return;
|
|
2355
|
+
}
|
|
2356
|
+
(logger ?? consoleLogger).warn(`[conduit] Built against API ${expected}, but ${method} ${url} answered as ${actual}. Deploy the two together.`);
|
|
2357
|
+
};
|
|
2358
|
+
const middleware = async (request, next) => {
|
|
2359
|
+
try {
|
|
2360
|
+
const response = await next(request);
|
|
2361
|
+
check(response.headers, stripQuery(request.url), request.method);
|
|
2362
|
+
return response;
|
|
2363
|
+
} catch (cause) {
|
|
2364
|
+
const error = toConduitError(cause);
|
|
2365
|
+
check(error.headers, stripQuery(request.url), request.method);
|
|
2366
|
+
throw error;
|
|
2367
|
+
}
|
|
2368
|
+
};
|
|
2369
|
+
return {
|
|
2370
|
+
name: "apiVersion",
|
|
2371
|
+
middleware,
|
|
2372
|
+
onInit: (ctx) => {
|
|
2373
|
+
events = ctx.events;
|
|
2374
|
+
logger = ctx.config.logger;
|
|
2375
|
+
}
|
|
2376
|
+
};
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
// src/plugins/request-id.ts
|
|
2380
|
+
const DEFAULT_HEADER = "x-request-id";
|
|
2381
|
+
/**
|
|
2382
|
+
* Sends an id with every attempt, and records it on `ConduitError.requestId`,
|
|
2383
|
+
* on `response.request.meta.requestId` and on devtools entries, so a failure in
|
|
2384
|
+
* the UI leads straight to the server's log line.
|
|
2385
|
+
*
|
|
2386
|
+
* Install it last, inside cache and dedupe. The id then never reaches a key,
|
|
2387
|
+
* and each retry goes out with an id of its own. A header the caller already
|
|
2388
|
+
* set is kept and reported as it is.
|
|
2389
|
+
*/
|
|
2390
|
+
function requestId(config = {}) {
|
|
2391
|
+
const header = config.header ?? DEFAULT_HEADER;
|
|
2392
|
+
const generate = config.generate ?? (() => crypto.randomUUID());
|
|
2393
|
+
const middleware = async (request, next) => {
|
|
2394
|
+
const headers = new Headers(request.headers);
|
|
2395
|
+
const id = headers.get(header) ?? generate();
|
|
2396
|
+
headers.set(header, id);
|
|
2397
|
+
request.meta.requestId = id;
|
|
2398
|
+
try {
|
|
2399
|
+
return await next(withRequest(request, { headers }));
|
|
2400
|
+
} catch (cause) {
|
|
2401
|
+
const error = toConduitError(cause);
|
|
2402
|
+
error.requestId = id;
|
|
2403
|
+
throw error;
|
|
2404
|
+
}
|
|
2405
|
+
};
|
|
2406
|
+
return {
|
|
2407
|
+
name: "requestId",
|
|
2408
|
+
middleware
|
|
2409
|
+
};
|
|
2410
|
+
}
|
|
2411
|
+
|
|
2412
|
+
export { ConduitError, DEFAULT_REDACT, apiVersion, cache, createClient, dedupe, defaults, defineEndpoint, getSharedClient, isConduitError, isErrorCode, observable, queue, releaseSharedClient, requestId, retry, session, sharedClient, timeout, toConduitError, withRequest };
|