@larc-iu/plaid-client 0.2.0-alpha.2 → 0.2.0-alpha.20
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/index.d.ts +1638 -156
- package/package.json +1 -1
- package/src/batchRef.js +128 -0
- package/src/constraints.js +84 -0
- package/src/created.js +29 -0
- package/src/documentLock.js +342 -0
- package/src/events.js +266 -0
- package/src/http.js +719 -90
- package/src/ids.js +54 -0
- package/src/index.js +2781 -645
- package/src/metadataOps.js +117 -0
- package/src/pagination.js +19 -35
- package/src/provenance.js +268 -27
- package/src/replayed.js +27 -0
- package/src/requester.js +56 -0
- package/src/roles.js +26 -0
- package/src/serviceSchema.js +87 -33
- package/src/services.js +550 -54
- package/src/sse.js +60 -3
- package/src/textEdits.js +191 -0
- package/src/transforms.js +11 -1
package/src/http.js
CHANGED
|
@@ -1,33 +1,152 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { markReplayed } from "./replayed.js";
|
|
2
|
+
import { transformRequest, transformResponse } from "./transforms.js";
|
|
3
|
+
import { takeRefs } from "./batchRef.js";
|
|
4
|
+
import { uuidv7 } from "./ids.js";
|
|
5
|
+
|
|
6
|
+
// ---------------------------------------------------------------------------
|
|
7
|
+
// Batches: which calls a batch carries, and which go over the wire anyway.
|
|
8
|
+
//
|
|
9
|
+
// A batch is an OBJECT (`client.batch()`, or the argument `client.batched(fn)`
|
|
10
|
+
// hands `fn`), a view of the client with the same bundles. A write made on the
|
|
11
|
+
// batch queues; a call made on the client itself always goes over the wire,
|
|
12
|
+
// whatever batches happen to be open. So the editor, the importer and the
|
|
13
|
+
// app's chrome can share one client, and a write by code that knows nothing
|
|
14
|
+
// about a batch can never land inside it. Every call reaching this layer is
|
|
15
|
+
// one of three things, and the third column is what a new endpoint has to
|
|
16
|
+
// pick.
|
|
17
|
+
//
|
|
18
|
+
// 1. A WRITE of project data: an entity, its metadata, a layer, a membership,
|
|
19
|
+
// a comment. This is what a batch is for, so on a batch it QUEUES. It is
|
|
20
|
+
// the default and needs no flag.
|
|
21
|
+
//
|
|
22
|
+
// 2. A READ. Every GET is answered from the wire even when made on a batch:
|
|
23
|
+
// the caller gets data rather than `{ batched: true }`, it takes no slot in
|
|
24
|
+
// the batch's results, and server-side it runs against the pool rather than
|
|
25
|
+
// the batch's transaction connection. A read that travels as a POST
|
|
26
|
+
// (`query`) says so with `outOfBand`.
|
|
27
|
+
//
|
|
28
|
+
// 3. An OUT-OF-BAND SIGNAL: stopping a service request, reporting a service's
|
|
29
|
+
// progress or result, taking or dropping a document lock, forgetting a
|
|
30
|
+
// service, an admin action on the server itself. It is shaped like a write
|
|
31
|
+
// but carries no project data, and its whole value is that it happens NOW.
|
|
32
|
+
// Pass `outOfBand`: made on a batch it still goes over the wire, and it
|
|
33
|
+
// never joins an open logical operation. The audit group is a label for
|
|
34
|
+
// the writes, and a signal that is never audited would mark the group
|
|
35
|
+
// written and leave the relabel PATCH 404ing on a group nothing ever
|
|
36
|
+
// created.
|
|
37
|
+
//
|
|
38
|
+
// A broadcast message (`messages.sendMessage`) sits between a write and a
|
|
39
|
+
// signal: it stays batchable, so a message queued after the writes goes out
|
|
40
|
+
// after them, but it writes nothing to the audit log either. `noOperation`
|
|
41
|
+
// keeps it out of an open logical operation without making it out of band.
|
|
42
|
+
//
|
|
43
|
+
// Strict mode stamps the expected document-version onto every write, queued
|
|
44
|
+
// or not. The server checks the first write of a batch request that names the
|
|
45
|
+
// document and skips the rest of that document's, so the bump one op causes
|
|
46
|
+
// does not 409 the next. A batch split past MAX_BATCH_OPS restamps each later
|
|
47
|
+
// request with the version the one before it left (see submitBatch).
|
|
48
|
+
//
|
|
49
|
+
// `noBatch` is not part of that judgment. It marks the four calls the batch
|
|
50
|
+
// transport cannot carry at all (the multipart media and avatar uploads, the
|
|
51
|
+
// user-data store's put and delete) and raises so the caller finds out. A
|
|
52
|
+
// batch inside a batch is refused by the batch itself. Never put it on a read: it turns a swallowed read into a
|
|
53
|
+
// thrown one, which is what the chrome hit when an unrelated import was
|
|
54
|
+
// running. A blobless DELETE beside an upload is not one of them: it carries
|
|
55
|
+
// nothing the transport cannot express, so it takes its class from the three
|
|
56
|
+
// above like anything else.
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
2
58
|
|
|
3
59
|
// Default per-request timeout (ms). Applied to every request unless the client
|
|
4
60
|
// is constructed with a different `timeout` (0 / null disables it). Note: this
|
|
5
61
|
// also bounds media up/downloads — bump it (or disable) for very large files.
|
|
6
62
|
export const DEFAULT_TIMEOUT_MS = 30000;
|
|
7
63
|
|
|
64
|
+
// Batch submissions get their own, longer budget. A batch runs as ONE server
|
|
65
|
+
// transaction holding the single SQLite write lock for its whole duration, and
|
|
66
|
+
// aborting the HTTP request does not cancel it — so a short timeout buys
|
|
67
|
+
// nothing and costs a retry stacked on a write that is still running.
|
|
68
|
+
export const DEFAULT_BATCH_TIMEOUT_MS = 180000;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Note how far the server's clock is from this machine's, from a response's
|
|
72
|
+
* Date header, for `client.serverNow()`. A time the server stamped (an audit
|
|
73
|
+
* entry's `ts`) has to be judged against the server's clock: a browser clock
|
|
74
|
+
* minutes off would misjudge it. A response with no readable Date header
|
|
75
|
+
* leaves the last offset as it was.
|
|
76
|
+
*/
|
|
77
|
+
export function noteServerClock(client, headers) {
|
|
78
|
+
const at = Date.parse(headers?.get?.("date") ?? "");
|
|
79
|
+
if (!Number.isNaN(at)) client.serverClockOffsetMs = at - Date.now();
|
|
80
|
+
}
|
|
81
|
+
|
|
8
82
|
/**
|
|
9
83
|
* Extract and update document versions from response headers and body.
|
|
84
|
+
*
|
|
85
|
+
* `historical` marks a read made with `as-of`: its body carries the version
|
|
86
|
+
* the document HAD then, which is not what a strict-mode write must claim
|
|
87
|
+
* next, so the body is ignored and only the header (always the live
|
|
88
|
+
* version) is learned from. Without this, viewing an old state and then
|
|
89
|
+
* writing 409s on a version that stopped being current long ago.
|
|
10
90
|
*/
|
|
11
|
-
export function extractDocumentVersions(
|
|
12
|
-
|
|
91
|
+
export function extractDocumentVersions(
|
|
92
|
+
client,
|
|
93
|
+
responseHeaders,
|
|
94
|
+
responseBody = null,
|
|
95
|
+
{ historical = false } = {},
|
|
96
|
+
) {
|
|
97
|
+
// A replayed answer (see the Idempotency-Key note below) carries the
|
|
98
|
+
// versions right after the first send, and this page may have read newer
|
|
99
|
+
// ones since. Keep the higher of each.
|
|
100
|
+
const replayed = responseHeaders.get(REPLAYED_HEADER) === "true";
|
|
101
|
+
// Past fifty documents the server leaves the list out and says how many it
|
|
102
|
+
// left out. Any version held may be one of them, so all are forgotten, and
|
|
103
|
+
// makeRequest reads the strict-mode document's again (learnOmittedVersion).
|
|
104
|
+
if (responseHeaders.get("X-Document-Versions-Omitted")) {
|
|
105
|
+
client.documentVersions = {};
|
|
106
|
+
client.documentVersionsOmitted = true;
|
|
107
|
+
}
|
|
108
|
+
const docVersionsHeader = responseHeaders.get("X-Document-Versions");
|
|
13
109
|
if (docVersionsHeader) {
|
|
14
110
|
try {
|
|
15
111
|
const versionsMap = JSON.parse(docVersionsHeader);
|
|
16
|
-
if (typeof versionsMap ===
|
|
112
|
+
if (typeof versionsMap === "object" && versionsMap !== null) {
|
|
17
113
|
// Clone once, then assign — cloning inside the loop is O(n²) and pointless.
|
|
18
|
-
client.documentVersions =
|
|
114
|
+
client.documentVersions = mergeVersions(
|
|
115
|
+
client.documentVersions,
|
|
116
|
+
versionsMap,
|
|
117
|
+
replayed,
|
|
118
|
+
);
|
|
19
119
|
}
|
|
20
120
|
} catch (e) {
|
|
21
|
-
console.warn(
|
|
121
|
+
console.warn("Failed to parse document versions header:", e);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (!historical && responseBody && typeof responseBody === "object") {
|
|
126
|
+
if (responseBody["document/id"] && responseBody["document/version"]) {
|
|
127
|
+
client.documentVersions = mergeVersions(
|
|
128
|
+
client.documentVersions,
|
|
129
|
+
{ [responseBody["document/id"]]: responseBody["document/version"] },
|
|
130
|
+
replayed,
|
|
131
|
+
);
|
|
22
132
|
}
|
|
23
133
|
}
|
|
134
|
+
}
|
|
24
135
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
136
|
+
/**
|
|
137
|
+
* `held` with `learned` merged in. A replayed answer only raises a version:
|
|
138
|
+
* it is what the document was right after the first send.
|
|
139
|
+
*/
|
|
140
|
+
export function mergeVersions(held, learned, replayed = false) {
|
|
141
|
+
if (!replayed) return { ...held, ...learned };
|
|
142
|
+
const merged = { ...held };
|
|
143
|
+
for (const [docId, version] of Object.entries(learned)) {
|
|
144
|
+
const current = merged[docId];
|
|
145
|
+
if (!(typeof current === "number" && current >= version)) {
|
|
146
|
+
merged[docId] = version;
|
|
29
147
|
}
|
|
30
148
|
}
|
|
149
|
+
return merged;
|
|
31
150
|
}
|
|
32
151
|
|
|
33
152
|
/**
|
|
@@ -37,7 +156,11 @@ export async function parseErrorBody(response) {
|
|
|
37
156
|
try {
|
|
38
157
|
return await response.json();
|
|
39
158
|
} catch (_) {
|
|
40
|
-
return {
|
|
159
|
+
return {
|
|
160
|
+
message: await response
|
|
161
|
+
.text()
|
|
162
|
+
.catch(() => "Unable to read error response"),
|
|
163
|
+
};
|
|
41
164
|
}
|
|
42
165
|
}
|
|
43
166
|
|
|
@@ -45,7 +168,11 @@ export async function parseErrorBody(response) {
|
|
|
45
168
|
* Create an enriched error from a failed HTTP response.
|
|
46
169
|
*/
|
|
47
170
|
export function makeHttpError(response, errorData, url, method) {
|
|
48
|
-
const serverMessage =
|
|
171
|
+
const serverMessage =
|
|
172
|
+
errorData?.error ||
|
|
173
|
+
errorData?.message ||
|
|
174
|
+
response.statusText ||
|
|
175
|
+
"Unknown error";
|
|
49
176
|
const error = new Error(`HTTP ${response.status} ${serverMessage} at ${url}`);
|
|
50
177
|
error.status = response.status;
|
|
51
178
|
error.statusText = response.statusText;
|
|
@@ -59,7 +186,9 @@ export function makeHttpError(response, errorData, url, method) {
|
|
|
59
186
|
* Create a network error (status 0). Timeout aborts get a clearer message.
|
|
60
187
|
*/
|
|
61
188
|
export function makeNetworkError(originalError, url, method) {
|
|
62
|
-
const timedOut =
|
|
189
|
+
const timedOut =
|
|
190
|
+
originalError?.name === "TimeoutError" ||
|
|
191
|
+
originalError?.name === "AbortError";
|
|
63
192
|
const message = timedOut
|
|
64
193
|
? `Request timed out at ${url}`
|
|
65
194
|
: `Network error: ${originalError.message} at ${url}`;
|
|
@@ -68,50 +197,274 @@ export function makeNetworkError(originalError, url, method) {
|
|
|
68
197
|
error.url = url;
|
|
69
198
|
error.method = method;
|
|
70
199
|
error.originalError = originalError;
|
|
200
|
+
// The browser says it has no network, so the request most likely never
|
|
201
|
+
// left this machine. A timeout is not that: the request went, and may land.
|
|
202
|
+
if (!timedOut && globalThis.navigator?.onLine === false) error.offline = true;
|
|
71
203
|
return error;
|
|
72
204
|
}
|
|
73
205
|
|
|
206
|
+
// Retry budget for 503 "Database busy" responses. Plaid serializes writers on
|
|
207
|
+
// a single SQLite write lock; a writer that can't get it within the server's
|
|
208
|
+
// busy_timeout is refused with 503. That refusal is definitive — the
|
|
209
|
+
// transaction never opened, or was rolled back whole — so repeating the
|
|
210
|
+
// request is safe, including for a batch (which is all-or-nothing by
|
|
211
|
+
// construction). Retrying here is what lets a long import ride out someone
|
|
212
|
+
// else's slow write instead of dying partway through.
|
|
213
|
+
export const BUSY_RETRIES = 4;
|
|
214
|
+
export const BUSY_BACKOFF_MS = 250;
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Run `attempt`, retrying while it rejects with a 503. Exponential backoff
|
|
218
|
+
* with full jitter, so two clients that collide don't march in lockstep and
|
|
219
|
+
* collide again on every retry.
|
|
220
|
+
*
|
|
221
|
+
* `attempt` must perform the whole request, not just await a prepared one:
|
|
222
|
+
* a fetch body and an AbortSignal.timeout are both single-use.
|
|
223
|
+
*/
|
|
224
|
+
export async function retryWhileBusy(
|
|
225
|
+
attempt,
|
|
226
|
+
{ retries = BUSY_RETRIES, baseDelayMs = BUSY_BACKOFF_MS, onRetry } = {},
|
|
227
|
+
) {
|
|
228
|
+
for (let i = 0; ; i += 1) {
|
|
229
|
+
try {
|
|
230
|
+
return await attempt();
|
|
231
|
+
} catch (error) {
|
|
232
|
+
if (error?.status !== 503 || i >= retries) throw error;
|
|
233
|
+
const delay = Math.round(baseDelayMs * 2 ** i * (0.5 + Math.random()));
|
|
234
|
+
onRetry?.({ attempt: i + 1, retries, delay, error });
|
|
235
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// ---------------------------------------------------------------------------
|
|
241
|
+
// The Idempotency-Key.
|
|
242
|
+
//
|
|
243
|
+
// Every write that is not a signal (`outOfBand`), an upload (`noBatch`) or a
|
|
244
|
+
// call that mints a secret (`noIdempotency`) goes out with an
|
|
245
|
+
// `Idempotency-Key` header, and so does every batch request (a queued op has
|
|
246
|
+
// none: its batch request carries one). The server keeps the answer to a
|
|
247
|
+
// keyed write for a day, and the same key sent again for the same request is
|
|
248
|
+
// answered from it with `Idempotent-Replayed: true`, writing nothing. So a
|
|
249
|
+
// write whose answer was lost (no response, 502, 504) can be sent again
|
|
250
|
+
// safely: it lands once. `makeRequest` and `_postBatch` do that three times
|
|
251
|
+
// themselves (retryUnknown), and the error that escapes carries the key as
|
|
252
|
+
// `idempotencyKey`.
|
|
253
|
+
//
|
|
254
|
+
// Inside a logical operation opened with `keys` (client.keySeed()), the nth
|
|
255
|
+
// keyed request that joins it takes the key `<seed>.<n>` and, from its first
|
|
256
|
+
// run, a pinned strict-mode stamp, so running the operation again from the
|
|
257
|
+
// top sends byte for byte the requests the first run sent: those that landed
|
|
258
|
+
// are replayed and the rest run. A request that does not join the operation
|
|
259
|
+
// mints its own key.
|
|
260
|
+
// ---------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
export const IDEMPOTENCY_HEADER = "Idempotency-Key";
|
|
263
|
+
export const REPLAYED_HEADER = "Idempotent-Replayed";
|
|
264
|
+
|
|
265
|
+
// Delays before sending a keyed write again when its answer was lost.
|
|
266
|
+
export const UNKNOWN_RETRY_DELAYS_MS = [1000, 3000, 9000];
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Whether `error` leaves the outcome unknown: no response came (status 0),
|
|
270
|
+
* or a proxy answered for the server (502, 504). The write may have landed.
|
|
271
|
+
*/
|
|
272
|
+
export function isUnknownOutcome(error) {
|
|
273
|
+
const status = error?.status;
|
|
274
|
+
return status === 0 || status === 502 || status === 504;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Run `attempt`, sending it again after each delay in `delaysMs` while it
|
|
279
|
+
* fails with an unknown outcome. Only for a keyed write, whose resend is
|
|
280
|
+
* answered from the first send when that one landed. Not when the browser
|
|
281
|
+
* says it is offline: then the request never left, and the caller waits for
|
|
282
|
+
* the network instead. Full jitter, as retryWhileBusy.
|
|
283
|
+
*/
|
|
284
|
+
export async function retryUnknown(
|
|
285
|
+
attempt,
|
|
286
|
+
{ delaysMs = UNKNOWN_RETRY_DELAYS_MS, onRetry } = {},
|
|
287
|
+
) {
|
|
288
|
+
for (let i = 0; ; i += 1) {
|
|
289
|
+
try {
|
|
290
|
+
return await attempt();
|
|
291
|
+
} catch (error) {
|
|
292
|
+
if (!isUnknownOutcome(error) || error.offline || i >= delaysMs.length) {
|
|
293
|
+
throw error;
|
|
294
|
+
}
|
|
295
|
+
const delay = Math.round(delaysMs[i] * (0.5 + Math.random()));
|
|
296
|
+
onRetry?.({ attempt: i + 1, retries: delaysMs.length, delay, error });
|
|
297
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* The key for the next keyed request, and the strict-mode stamp it must
|
|
304
|
+
* claim when an earlier run of its operation already sent it. `joins` says
|
|
305
|
+
* whether the request joins the open logical operation.
|
|
306
|
+
* Returns `{ key, pin, record }`: `pin` is undefined when nothing is pinned,
|
|
307
|
+
* and `record(version)` pins what this request claimed, the first time.
|
|
308
|
+
*/
|
|
309
|
+
export function nextIdempotencyKey(client, joins) {
|
|
310
|
+
const frame = joins ? client.operationGroup?.frames.at(-1) : null;
|
|
311
|
+
const keys = frame?.keys;
|
|
312
|
+
if (!keys) return { key: uuidv7(), pin: undefined, record: () => {} };
|
|
313
|
+
const n = frame.count;
|
|
314
|
+
frame.count += 1;
|
|
315
|
+
const pinned = keys.stamps.has(n);
|
|
316
|
+
return {
|
|
317
|
+
key: `${keys.seed}.${n}`,
|
|
318
|
+
pin: pinned ? keys.stamps.get(n) : undefined,
|
|
319
|
+
record: (version) => {
|
|
320
|
+
if (!pinned) keys.stamps.set(n, version ?? null);
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
74
325
|
/**
|
|
75
326
|
* Build a fetch AbortSignal that fires after `timeout` ms, or undefined when
|
|
76
327
|
* timeouts are disabled / unsupported.
|
|
77
328
|
*/
|
|
78
329
|
export function timeoutSignal(timeout) {
|
|
79
|
-
if (
|
|
330
|
+
if (
|
|
331
|
+
timeout &&
|
|
332
|
+
timeout > 0 &&
|
|
333
|
+
typeof AbortSignal !== "undefined" &&
|
|
334
|
+
AbortSignal.timeout
|
|
335
|
+
) {
|
|
80
336
|
return AbortSignal.timeout(timeout);
|
|
81
337
|
}
|
|
82
338
|
return undefined;
|
|
83
339
|
}
|
|
84
340
|
|
|
85
341
|
/**
|
|
86
|
-
*
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
* noBatch - If true, throw when in batch mode
|
|
94
|
-
* skipResponseTransform - Return raw parsed JSON (no transformResponse)
|
|
95
|
-
* noAuth - Skip Authorization header
|
|
96
|
-
* binaryResponse - Return arrayBuffer instead of JSON/text
|
|
97
|
-
* timeout - Per-request timeout in ms overriding client.timeout
|
|
98
|
-
* for this call (0/null disables). Used for known-long
|
|
99
|
-
* ops like project delete.
|
|
342
|
+
* Send a request through XMLHttpRequest so the caller can watch the bytes go
|
|
343
|
+
* up: fetch cannot report upload progress. Resolves to a Response, so the rest
|
|
344
|
+
* of the pipeline is the same either way. The timeout is a STALL timeout,
|
|
345
|
+
* re-armed by every progress event, so a large file on a slow link is never
|
|
346
|
+
* cut off while it is still moving, only once nothing has moved for `timeout`
|
|
347
|
+
* ms. Rejects the way fetch does: a TypeError for a network failure, an error
|
|
348
|
+
* named TimeoutError for a stall.
|
|
100
349
|
*/
|
|
101
|
-
export
|
|
350
|
+
export function xhrSend(
|
|
351
|
+
url,
|
|
352
|
+
{ method, headers, body },
|
|
353
|
+
{ onUploadProgress, timeout } = {},
|
|
354
|
+
) {
|
|
355
|
+
return new Promise((resolve, reject) => {
|
|
356
|
+
const xhr = new XMLHttpRequest();
|
|
357
|
+
xhr.open(method, url);
|
|
358
|
+
xhr.responseType = "arraybuffer";
|
|
359
|
+
for (const [name, value] of Object.entries(headers || {}))
|
|
360
|
+
xhr.setRequestHeader(name, value);
|
|
361
|
+
|
|
362
|
+
let timer = null;
|
|
363
|
+
const disarm = () => clearTimeout(timer);
|
|
364
|
+
const arm = () => {
|
|
365
|
+
if (!timeout || timeout <= 0) return;
|
|
366
|
+
disarm();
|
|
367
|
+
timer = setTimeout(() => {
|
|
368
|
+
xhr.abort();
|
|
369
|
+
reject(
|
|
370
|
+
Object.assign(new Error(`Request timed out at ${url}`), {
|
|
371
|
+
name: "TimeoutError",
|
|
372
|
+
}),
|
|
373
|
+
);
|
|
374
|
+
}, timeout);
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
xhr.upload.onprogress = (e) => {
|
|
378
|
+
arm();
|
|
379
|
+
if (onUploadProgress) {
|
|
380
|
+
onUploadProgress({
|
|
381
|
+
loaded: e.loaded,
|
|
382
|
+
total: e.lengthComputable ? e.total : null,
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
xhr.onprogress = arm;
|
|
387
|
+
xhr.onload = () => {
|
|
388
|
+
disarm();
|
|
389
|
+
if (xhr.status === 0) {
|
|
390
|
+
reject(new TypeError(`Failed to fetch ${url}`));
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const responseHeaders = new Headers();
|
|
394
|
+
for (const line of (xhr.getAllResponseHeaders() || "")
|
|
395
|
+
.trim()
|
|
396
|
+
.split(/\r?\n/)) {
|
|
397
|
+
const i = line.indexOf(":");
|
|
398
|
+
if (i > 0)
|
|
399
|
+
responseHeaders.append(
|
|
400
|
+
line.slice(0, i).trim(),
|
|
401
|
+
line.slice(i + 1).trim(),
|
|
402
|
+
);
|
|
403
|
+
}
|
|
404
|
+
// A Response refuses a body for these statuses.
|
|
405
|
+
const responseBody = [204, 205, 304].includes(xhr.status)
|
|
406
|
+
? null
|
|
407
|
+
: xhr.response;
|
|
408
|
+
resolve(
|
|
409
|
+
new Response(responseBody, {
|
|
410
|
+
status: xhr.status,
|
|
411
|
+
statusText: xhr.statusText,
|
|
412
|
+
headers: responseHeaders,
|
|
413
|
+
}),
|
|
414
|
+
);
|
|
415
|
+
};
|
|
416
|
+
xhr.onerror = () => {
|
|
417
|
+
disarm();
|
|
418
|
+
reject(new TypeError(`Failed to fetch ${url}`));
|
|
419
|
+
};
|
|
420
|
+
xhr.onabort = () => {
|
|
421
|
+
disarm();
|
|
422
|
+
reject(
|
|
423
|
+
Object.assign(new Error(`Request aborted at ${url}`), {
|
|
424
|
+
name: "AbortError",
|
|
425
|
+
}),
|
|
426
|
+
);
|
|
427
|
+
};
|
|
428
|
+
|
|
429
|
+
arm();
|
|
430
|
+
xhr.send(body);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Everything a request is before it goes anywhere: the URL with its query
|
|
436
|
+
* params and the stamps strict mode, a per-call audit message and an open
|
|
437
|
+
* logical operation add, plus the transformed body. Shared by the wire path
|
|
438
|
+
* (`makeRequest`) and the batch path (`queueRequest`), so a queued op is
|
|
439
|
+
* exactly the request that would have gone out. Strict mode stamps every
|
|
440
|
+
* write, queued or not, and `stampedDocument` names the document it stamped
|
|
441
|
+
* for (null when it stamped nothing). `stampedGroup` is the open logical
|
|
442
|
+
* operation it joined, if any, for `makeRequest` to mark written once the
|
|
443
|
+
* server has taken the request.
|
|
444
|
+
*/
|
|
445
|
+
export function prepareRequest(client, method, path, options = {}) {
|
|
102
446
|
const {
|
|
103
447
|
body,
|
|
104
448
|
rawBody,
|
|
105
449
|
formData,
|
|
106
450
|
queryParams,
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
noAuth,
|
|
110
|
-
binaryResponse,
|
|
451
|
+
outOfBand,
|
|
452
|
+
noOperation,
|
|
111
453
|
auditMessage,
|
|
112
|
-
|
|
454
|
+
pinnedVersion,
|
|
455
|
+
versioned,
|
|
113
456
|
} = options;
|
|
114
457
|
|
|
458
|
+
// A write must not go out on a lock that lapsed. `documents.locked()`
|
|
459
|
+
// records the loss here when its keep-alive cannot renew, and from that
|
|
460
|
+
// moment the block is holding nothing: an edit by somebody else can already
|
|
461
|
+
// have landed between the read the work was planned from and the write about
|
|
462
|
+
// to go out. Reads pass, and so do the lock routes themselves, which is how
|
|
463
|
+
// the block still releases on its way out.
|
|
464
|
+
if (client.documentLockLost && method !== "GET" && !path.endsWith("/lock")) {
|
|
465
|
+
throw client.documentLockLost;
|
|
466
|
+
}
|
|
467
|
+
|
|
115
468
|
// Build URL
|
|
116
469
|
let url = `${client.baseUrl}${path}`;
|
|
117
470
|
|
|
@@ -140,114 +493,390 @@ export async function makeRequest(client, method, path, options = {}) {
|
|
|
140
493
|
requestBody = transformRequest(body);
|
|
141
494
|
}
|
|
142
495
|
|
|
143
|
-
// Strict mode: append document-version for non-GET requests
|
|
144
|
-
//
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
|
|
496
|
+
// Strict mode: append document-version for non-GET requests, on EVERY
|
|
497
|
+
// queued write of a batch. The server validates the first write it can
|
|
498
|
+
// (one whose route resolves a document) and skips the rest of that
|
|
499
|
+
// document's, so the version bump a sub-op causes does not 409 the next
|
|
500
|
+
// one. Stamping only the first write was silently no check at all
|
|
501
|
+
// whenever that write was one the route ignores, such as a vocabulary
|
|
502
|
+
// entry's metadata, which is exactly what the igt editor queues first.
|
|
503
|
+
// `stampedDocument` names the document the stamp is for, so a batch split
|
|
504
|
+
// into several requests can restamp its later ones (see submitBatch). An
|
|
505
|
+
// out-of-band signal (a lock, a service's progress, a query) is no write of
|
|
506
|
+
// the document and carries none.
|
|
507
|
+
// A resend of an operation's request claims what its first run claimed
|
|
508
|
+
// (`pinnedVersion`, null for no claim), so the two are the same request.
|
|
509
|
+
let stampedDocument = null;
|
|
510
|
+
let stampedVersion = null;
|
|
511
|
+
// A write with its own precondition (`versioned: false`, a text edit sent
|
|
512
|
+
// with the digest of the body it was made on) goes without the stamp.
|
|
513
|
+
if (
|
|
514
|
+
client.strictModeDocumentId &&
|
|
515
|
+
method !== "GET" &&
|
|
516
|
+
!outOfBand &&
|
|
517
|
+
versioned !== false
|
|
518
|
+
) {
|
|
151
519
|
const docId = client.strictModeDocumentId;
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
520
|
+
const docVersion =
|
|
521
|
+
pinnedVersion !== undefined
|
|
522
|
+
? pinnedVersion
|
|
523
|
+
: client.documentVersions[docId];
|
|
524
|
+
if (docVersion) {
|
|
525
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
155
526
|
url += `${separator}document-version=${encodeURIComponent(docVersion)}`;
|
|
156
|
-
|
|
527
|
+
stampedDocument = docId;
|
|
528
|
+
stampedVersion = docVersion;
|
|
157
529
|
}
|
|
158
530
|
}
|
|
159
531
|
|
|
160
532
|
// Per-call custom audit-log message (overrides the auto-generated
|
|
161
|
-
// description of THIS write)
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const separator = url.includes('?') ? '&' : '?';
|
|
533
|
+
// description of THIS write), stamped on the one write it was given to. The
|
|
534
|
+
// server templates `{param}` placeholders against the endpoint's own
|
|
535
|
+
// path/query/body params.
|
|
536
|
+
if (auditMessage && method !== "GET") {
|
|
537
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
167
538
|
url += `${separator}audit-message=${encodeURIComponent(auditMessage)}`;
|
|
168
539
|
}
|
|
169
540
|
|
|
170
541
|
// Logical-operation group (see client.beginOperation): stamp every write
|
|
171
542
|
// with the group id; the message rides along too so the server can label
|
|
172
|
-
// the group lazily on whichever tagged write lands first.
|
|
173
|
-
|
|
543
|
+
// the group lazily on whichever tagged write lands first. The group counts
|
|
544
|
+
// as written only once such a write has been taken (`makeRequest`): a group
|
|
545
|
+
// whose only write was refused was never made, and relabelling it 404s.
|
|
546
|
+
//
|
|
547
|
+
// An out-of-band signal is not one of those writes (see the note at the top
|
|
548
|
+
// of this file): it never lands in the audit log, so a stamp does nothing
|
|
549
|
+
// server-side while `written` promises a group that will never exist, and
|
|
550
|
+
// the relabel PATCH then 404s. A broadcast message (`noOperation`) is
|
|
551
|
+
// never audited either.
|
|
552
|
+
let stampedGroup = null;
|
|
553
|
+
if (
|
|
554
|
+
client.operationGroup &&
|
|
555
|
+
method !== "GET" &&
|
|
556
|
+
!outOfBand &&
|
|
557
|
+
!noOperation
|
|
558
|
+
) {
|
|
174
559
|
const group = client.operationGroup;
|
|
175
|
-
const separator = url.includes(
|
|
560
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
176
561
|
url += `${separator}group-id=${encodeURIComponent(group.id)}`;
|
|
177
|
-
if (group.message)
|
|
178
|
-
|
|
562
|
+
if (group.message)
|
|
563
|
+
url += `&group-message=${encodeURIComponent(group.message)}`;
|
|
564
|
+
if (group.kind) url += `&group-kind=${encodeURIComponent(group.kind)}`;
|
|
565
|
+
if (group.ref) url += `&group-ref=${encodeURIComponent(group.ref)}`;
|
|
566
|
+
stampedGroup = group;
|
|
179
567
|
}
|
|
180
568
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
569
|
+
return { url, requestBody, stampedDocument, stampedVersion, stampedGroup };
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Whether a write joins the open logical operation (see prepareRequest).
|
|
574
|
+
*/
|
|
575
|
+
export function joinsOperation(client, method, options = {}) {
|
|
576
|
+
return Boolean(
|
|
577
|
+
client.operationGroup &&
|
|
578
|
+
method !== "GET" &&
|
|
579
|
+
!options.outOfBand &&
|
|
580
|
+
!options.noOperation,
|
|
581
|
+
);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/**
|
|
585
|
+
* Whether a call made on the client goes out with an Idempotency-Key.
|
|
586
|
+
*/
|
|
587
|
+
export function takesIdempotencyKey(method, options = {}) {
|
|
588
|
+
return (
|
|
589
|
+
method !== "GET" &&
|
|
590
|
+
!options.outOfBand &&
|
|
591
|
+
!options.noBatch &&
|
|
592
|
+
!options.noIdempotency
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* `path` with its strict-mode `document-version` claim replaced by `version`,
|
|
598
|
+
* or dropped when `version` is unknown. For the later requests of a batch
|
|
599
|
+
* split past MAX_BATCH_OPS: each op was stamped with the version the document
|
|
600
|
+
* had when it was queued, and every request before it has since moved the
|
|
601
|
+
* document on.
|
|
602
|
+
*/
|
|
603
|
+
export function restampDocumentVersion(path, version) {
|
|
604
|
+
const [base, query = ""] = path.split(/\?(.*)/s);
|
|
605
|
+
const params = query
|
|
606
|
+
.split("&")
|
|
607
|
+
.filter((p) => p && !p.startsWith("document-version="));
|
|
608
|
+
if (version !== undefined && version !== null) {
|
|
609
|
+
params.push(`document-version=${encodeURIComponent(version)}`);
|
|
610
|
+
}
|
|
611
|
+
return params.length ? `${base}?${params.join("&")}` : base;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* The strict-mode document whose version a response left out
|
|
616
|
+
* (X-Document-Versions-Omitted) and the client has not learned since, or
|
|
617
|
+
* null. Such a write would go out unstamped, which is no check at all.
|
|
618
|
+
*/
|
|
619
|
+
function omittedStrictDocument(client) {
|
|
620
|
+
const docId = client.strictModeDocumentId;
|
|
621
|
+
return docId &&
|
|
622
|
+
client.documentVersionsOmitted &&
|
|
623
|
+
client.documentVersions[docId] === undefined
|
|
624
|
+
? docId
|
|
625
|
+
: null;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Read the strict-mode document once to learn the version a response left
|
|
630
|
+
* out. Done right after that response, so the client's own large write is
|
|
631
|
+
* not mistaken for somebody else's edit at the next save, and again before a
|
|
632
|
+
* strict write when that read failed.
|
|
633
|
+
*/
|
|
634
|
+
async function learnOmittedVersion(client) {
|
|
635
|
+
const docId = omittedStrictDocument(client);
|
|
636
|
+
if (!docId) return;
|
|
637
|
+
// One read at a time: a write made while it is in flight waits for it
|
|
638
|
+
// rather than going out unstamped.
|
|
639
|
+
if (!client._learningOmittedVersion) {
|
|
640
|
+
client._learningOmittedVersion = makeRequest(
|
|
641
|
+
client,
|
|
642
|
+
"GET",
|
|
643
|
+
`/api/v1/documents/${docId}`,
|
|
644
|
+
{ learningOmittedVersion: true },
|
|
645
|
+
).finally(() => {
|
|
646
|
+
client._learningOmittedVersion = null;
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
await client._learningOmittedVersion;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
async function learnOmittedVersionQuietly(client) {
|
|
653
|
+
try {
|
|
654
|
+
await learnOmittedVersion(client);
|
|
655
|
+
} catch (_) {
|
|
656
|
+
/* the write went through; the next strict write asks again */
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* A call made on a batch (see `PlaidClient#batch`). A write of project data is
|
|
662
|
+
* queued as one operation of the batch and answers `{ batched: true }`; its
|
|
663
|
+
* result is the matching entry of what `submit()` resolves to. A read, and a
|
|
664
|
+
* signal marked `outOfBand`, is the client's to make and goes over the wire
|
|
665
|
+
* now, exactly as if it had been made on the client.
|
|
666
|
+
*/
|
|
667
|
+
export async function queueRequest(batch, method, path, options = {}) {
|
|
668
|
+
if (method === "GET" || options.outOfBand) {
|
|
669
|
+
return batch.client._request(method, path, options);
|
|
670
|
+
}
|
|
671
|
+
if (!batch.open) {
|
|
672
|
+
throw new Error(`This batch was already submitted or aborted: ${path}`);
|
|
673
|
+
}
|
|
674
|
+
if (options.noBatch) {
|
|
675
|
+
throw new Error(`This endpoint cannot be used in a batch: ${path}`);
|
|
676
|
+
}
|
|
677
|
+
const { url, requestBody, stampedDocument, stampedGroup } = prepareRequest(
|
|
678
|
+
batch.client,
|
|
679
|
+
method,
|
|
680
|
+
path,
|
|
681
|
+
options,
|
|
682
|
+
);
|
|
683
|
+
const operation = {
|
|
684
|
+
path: url.replace(batch.client.baseUrl, ""),
|
|
685
|
+
method: method.toUpperCase(),
|
|
686
|
+
};
|
|
687
|
+
if (requestBody !== undefined) {
|
|
688
|
+
// Each b.ref() in the body goes beside it, as the path to a null the
|
|
689
|
+
// server fills with the id (batchRef.js).
|
|
690
|
+
const { body, refs } = takeRefs(batch, requestBody);
|
|
691
|
+
operation.body = body;
|
|
692
|
+
if (refs) operation.refs = refs;
|
|
693
|
+
}
|
|
694
|
+
batch.operations.push(operation);
|
|
695
|
+
batch.stampedDocuments.push(stampedDocument);
|
|
696
|
+
batch.stampedGroups.push(stampedGroup);
|
|
697
|
+
return { batched: true };
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Generic request method handling all fetch logic.
|
|
702
|
+
*
|
|
703
|
+
* Options:
|
|
704
|
+
* body - Object body, run through transformRequest
|
|
705
|
+
* rawBody - Body value passed directly (no transform). Mutually exclusive with body.
|
|
706
|
+
* formData - If true, body is FormData; skip Content-Type header
|
|
707
|
+
* queryParams - Object of query param key/values to append
|
|
708
|
+
* noBatch - If true, throw when made on a batch. Only for calls the
|
|
709
|
+
* batch transport cannot carry at all (see the note at the
|
|
710
|
+
* top of this file); never for a read.
|
|
711
|
+
* outOfBand - If true, the call is a signal rather than a write of
|
|
712
|
+
* project data: made on a batch it still goes over the
|
|
713
|
+
* wire, and it never joins an open logical operation (see
|
|
714
|
+
* the note at the top of this file).
|
|
715
|
+
* noOperation - If true, the call never joins an open logical operation
|
|
716
|
+
* but still queues on a batch like a write. For a
|
|
717
|
+
* broadcast message, which is never audited.
|
|
718
|
+
* versioned - If false, strict mode does not stamp the call with the
|
|
719
|
+
* document version. For a write that carries its own
|
|
720
|
+
* precondition (a text edit with `base`).
|
|
721
|
+
* skipResponseTransform - Return raw parsed JSON (no transformResponse)
|
|
722
|
+
* noAuth - Skip Authorization header
|
|
723
|
+
* binaryResponse - Return arrayBuffer instead of JSON/text
|
|
724
|
+
* timeout - Per-request timeout in ms overriding client.timeout
|
|
725
|
+
* for this call (0/null disables). Used for known-long
|
|
726
|
+
* ops like project delete.
|
|
727
|
+
* onUploadProgress - Called with `{ loaded, total }` (bytes; total null when
|
|
728
|
+
* unknown) as the request body goes up. In a browser the
|
|
729
|
+
* request then travels by XMLHttpRequest (see xhrSend),
|
|
730
|
+
* where the timeout only fires when the upload stalls;
|
|
731
|
+
* elsewhere the callback is ignored and fetch is used.
|
|
732
|
+
*/
|
|
733
|
+
export async function makeRequest(client, method, path, options = {}) {
|
|
734
|
+
const {
|
|
735
|
+
formData,
|
|
736
|
+
skipResponseTransform,
|
|
737
|
+
noAuth,
|
|
738
|
+
binaryResponse,
|
|
739
|
+
timeout,
|
|
740
|
+
onUploadProgress,
|
|
741
|
+
learningOmittedVersion,
|
|
742
|
+
} = options;
|
|
743
|
+
if (method !== "GET" && omittedStrictDocument(client)) {
|
|
744
|
+
await learnOmittedVersion(client);
|
|
195
745
|
}
|
|
746
|
+
const keyed = takesIdempotencyKey(method, options);
|
|
747
|
+
const joins = joinsOperation(client, method, options);
|
|
748
|
+
// The ids the joined operation minted for what it creates (withOperation's
|
|
749
|
+
// `minted`): a create refused 409 id-taken for one of them was made by an
|
|
750
|
+
// earlier send of this operation, and answers as made.
|
|
751
|
+
const minted = joins ? client.operationGroup?.frames.at(-1)?.minted : null;
|
|
752
|
+
const { key, pin, record } = keyed ? nextIdempotencyKey(client, joins) : {};
|
|
753
|
+
const { url, requestBody, stampedGroup, stampedVersion } = prepareRequest(
|
|
754
|
+
client,
|
|
755
|
+
method,
|
|
756
|
+
path,
|
|
757
|
+
keyed ? { ...options, pinnedVersion: pin } : options,
|
|
758
|
+
);
|
|
759
|
+
if (keyed) record(stampedVersion);
|
|
196
760
|
|
|
197
761
|
// Build fetch options
|
|
198
762
|
const headers = {};
|
|
199
763
|
if (!noAuth) {
|
|
200
|
-
headers[
|
|
764
|
+
headers["Authorization"] = `Bearer ${client.token}`;
|
|
201
765
|
}
|
|
202
766
|
if (!formData) {
|
|
203
|
-
headers[
|
|
767
|
+
headers["Content-Type"] = "application/json";
|
|
204
768
|
}
|
|
769
|
+
if (keyed) headers[IDEMPOTENCY_HEADER] = key;
|
|
205
770
|
|
|
206
771
|
const fetchOptions = { method, headers };
|
|
207
772
|
if (requestBody !== undefined) {
|
|
208
773
|
fetchOptions.body = formData ? requestBody : JSON.stringify(requestBody);
|
|
209
774
|
}
|
|
210
|
-
|
|
211
|
-
|
|
775
|
+
|
|
776
|
+
// A fresh AbortSignal.timeout per attempt: the signal fires once and stays
|
|
777
|
+
// aborted, so reusing it would make every retry fail instantly.
|
|
778
|
+
const timeoutMs = timeout !== undefined ? timeout : client.timeout;
|
|
779
|
+
const send = () => {
|
|
780
|
+
if (onUploadProgress && typeof XMLHttpRequest !== "undefined") {
|
|
781
|
+
return xhrSend(url, fetchOptions, {
|
|
782
|
+
onUploadProgress,
|
|
783
|
+
timeout: timeoutMs,
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
const signal = timeoutSignal(timeoutMs);
|
|
787
|
+
return fetch(url, signal ? { ...fetchOptions, signal } : fetchOptions);
|
|
788
|
+
};
|
|
789
|
+
|
|
790
|
+
// One attempt: a 503, and for a keyed write a 502 or 504, surfaces as a
|
|
791
|
+
// throw so the retries below can see it. Other failures are thrown from
|
|
792
|
+
// the checks after it.
|
|
793
|
+
const attempt = async () => {
|
|
794
|
+
let res;
|
|
795
|
+
try {
|
|
796
|
+
res = await send();
|
|
797
|
+
} catch (e) {
|
|
798
|
+
throw makeNetworkError(e, url, method);
|
|
799
|
+
}
|
|
800
|
+
if (
|
|
801
|
+
res.status === 503 ||
|
|
802
|
+
(keyed && (res.status === 502 || res.status === 504))
|
|
803
|
+
) {
|
|
804
|
+
throw makeHttpError(res, await parseErrorBody(res), url, method);
|
|
805
|
+
}
|
|
806
|
+
return res;
|
|
807
|
+
};
|
|
212
808
|
|
|
213
809
|
try {
|
|
214
|
-
const response =
|
|
810
|
+
const response = keyed
|
|
811
|
+
? await retryUnknown(() => retryWhileBusy(attempt), {
|
|
812
|
+
delaysMs: client.retryDelaysMs,
|
|
813
|
+
})
|
|
814
|
+
: await retryWhileBusy(attempt);
|
|
815
|
+
noteServerClock(client, response.headers);
|
|
215
816
|
|
|
216
817
|
if (!response.ok) {
|
|
217
|
-
const
|
|
818
|
+
const errorData = await parseErrorBody(response);
|
|
819
|
+
// Only a single create: a bulk refused whole made none of its rows.
|
|
820
|
+
// Never a deleted row: there is nothing to open.
|
|
821
|
+
if (
|
|
822
|
+
response.status === 409 &&
|
|
823
|
+
errorData?.error === "id-taken" &&
|
|
824
|
+
!errorData.deleted &&
|
|
825
|
+
minted?.has(errorData.id) &&
|
|
826
|
+
requestBody?.id === errorData.id
|
|
827
|
+
) {
|
|
828
|
+
if (stampedGroup) stampedGroup.written = true;
|
|
829
|
+
return transformResponse({ id: errorData.id });
|
|
830
|
+
}
|
|
831
|
+
const error = makeHttpError(response, errorData, url, method);
|
|
218
832
|
// 401 means the token is missing/expired/invalid. Fire the app's auth-error
|
|
219
833
|
// handler once (it discards the token and routes back to login). 403
|
|
220
834
|
// (forbidden — authenticated but not permitted) deliberately does NOT.
|
|
221
|
-
if (
|
|
835
|
+
if (
|
|
836
|
+
response.status === 401 &&
|
|
837
|
+
typeof client.onAuthError === "function" &&
|
|
838
|
+
!client._authErrorFired
|
|
839
|
+
) {
|
|
222
840
|
client._authErrorFired = true;
|
|
223
|
-
try {
|
|
841
|
+
try {
|
|
842
|
+
client.onAuthError(error);
|
|
843
|
+
} catch (_) {
|
|
844
|
+
/* handler must not mask the original error */
|
|
845
|
+
}
|
|
224
846
|
}
|
|
225
847
|
throw error;
|
|
226
848
|
}
|
|
849
|
+
// The server took it, so the operation's group exists.
|
|
850
|
+
if (stampedGroup) stampedGroup.written = true;
|
|
227
851
|
|
|
228
852
|
// Binary response (getMedia)
|
|
229
853
|
if (binaryResponse) {
|
|
230
854
|
extractDocumentVersions(client, response.headers);
|
|
855
|
+
if (!learningOmittedVersion) await learnOmittedVersionQuietly(client);
|
|
231
856
|
return await response.arrayBuffer();
|
|
232
857
|
}
|
|
233
858
|
|
|
234
859
|
// JSON or text response
|
|
235
|
-
const contentType = response.headers.get(
|
|
236
|
-
if (contentType && contentType.includes(
|
|
860
|
+
const contentType = response.headers.get("content-type");
|
|
861
|
+
if (contentType && contentType.includes("application/json")) {
|
|
237
862
|
const data = await response.json();
|
|
238
|
-
extractDocumentVersions(client, response.headers, data
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
863
|
+
extractDocumentVersions(client, response.headers, data, {
|
|
864
|
+
historical: /[?&]as-of=/.test(url),
|
|
865
|
+
});
|
|
866
|
+
if (!learningOmittedVersion) await learnOmittedVersionQuietly(client);
|
|
867
|
+
const answer = skipResponseTransform ? data : transformResponse(data);
|
|
868
|
+
return response.headers.get(REPLAYED_HEADER) === "true"
|
|
869
|
+
? markReplayed(answer)
|
|
870
|
+
: answer;
|
|
243
871
|
} else {
|
|
244
872
|
extractDocumentVersions(client, response.headers);
|
|
873
|
+
if (!learningOmittedVersion) await learnOmittedVersionQuietly(client);
|
|
245
874
|
return await response.text();
|
|
246
875
|
}
|
|
247
876
|
} catch (error) {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
throw
|
|
877
|
+
const escaped =
|
|
878
|
+
error.status !== undefined ? error : makeNetworkError(error, url, method);
|
|
879
|
+
if (keyed) escaped.idempotencyKey = key;
|
|
880
|
+
throw escaped;
|
|
252
881
|
}
|
|
253
882
|
}
|