@mountaya/client 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +104 -0
- package/LICENCE.fr.txt +280 -0
- package/LICENSE.txt +262 -0
- package/README.md +1260 -2
- package/dist/admin/index.cjs +3521 -0
- package/dist/admin/index.cjs.map +1 -0
- package/dist/admin/index.d.cts +1070 -0
- package/dist/admin/index.d.ts +1070 -0
- package/dist/admin/index.js +301 -0
- package/dist/admin/index.js.map +1 -0
- package/dist/browser.cjs +8073 -0
- package/dist/browser.cjs.map +1 -0
- package/dist/browser.d.cts +106 -0
- package/dist/browser.d.ts +106 -0
- package/dist/browser.js +53 -0
- package/dist/browser.js.map +1 -0
- package/dist/chunk-BM526BHG.js +342 -0
- package/dist/chunk-BM526BHG.js.map +1 -0
- package/dist/chunk-D2YEVTG7.js +327 -0
- package/dist/chunk-D2YEVTG7.js.map +1 -0
- package/dist/chunk-OHKVUREN.js +3500 -0
- package/dist/chunk-OHKVUREN.js.map +1 -0
- package/dist/chunk-TDTK2L5H.js +3842 -0
- package/dist/chunk-TDTK2L5H.js.map +1 -0
- package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
- package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
- package/dist/errors-B-GqAtQv.d.cts +75960 -0
- package/dist/errors-B-GqAtQv.d.ts +75960 -0
- package/dist/events/index.cjs +1972 -0
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.d.cts +781 -0
- package/dist/events/index.d.ts +781 -0
- package/dist/events/index.js +826 -0
- package/dist/events/index.js.map +1 -0
- package/dist/index.cjs +8072 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +76 -0
- package/dist/index.d.ts +76 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +1 -0
- package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
- package/dist/operations.gen-DUD406TV.d.ts +3993 -0
- package/package.json +127 -4
- package/src/admin/index.ts +47 -0
- package/src/admin/rules/mountayaAdmin.ts +102 -0
- package/src/browser.ts +232 -0
- package/src/core/engines/sessionToken.ts +870 -0
- package/src/core/rules/auth.ts +1017 -0
- package/src/core/rules/clientHeader.ts +28 -0
- package/src/core/rules/dates.ts +200 -0
- package/src/core/rules/decode.ts +154 -0
- package/src/core/rules/envelope.ts +41 -0
- package/src/core/rules/errors.ts +1486 -0
- package/src/core/rules/graphql.ts +576 -0
- package/src/core/rules/headerValue.ts +42 -0
- package/src/core/rules/idempotencyKey.ts +64 -0
- package/src/core/rules/nullMask.ts +127 -0
- package/src/core/rules/nullMasks.gen.ts +416 -0
- package/src/core/rules/paginate.ts +316 -0
- package/src/core/rules/rateLimit.ts +507 -0
- package/src/core/rules/redaction.ts +219 -0
- package/src/core/rules/resourceRef.ts +110 -0
- package/src/core/rules/responseBody.ts +492 -0
- package/src/core/rules/retry.ts +386 -0
- package/src/core/rules/selection.ts +416 -0
- package/src/core/rules/sessionAnswer.ts +90 -0
- package/src/core/rules/sessionSchedule.ts +131 -0
- package/src/core/rules/sessionWait.ts +112 -0
- package/src/core/rules/transport.ts +2386 -0
- package/src/core/rules/version.gen.ts +16 -0
- package/src/core/rules/webAddress.ts +165 -0
- package/src/core/rules/webAddresses.gen.ts +30 -0
- package/src/data/operations.gen.ts +603 -0
- package/src/data/schema.gen.ts +8078 -0
- package/src/data/selection.gen.ts +472 -0
- package/src/events/index.ts +67 -0
- package/src/events/rules/agent.ts +439 -0
- package/src/events/rules/collab.ts +554 -0
- package/src/events/rules/collabNulls.gen.ts +17 -0
- package/src/events/rules/eventStream.ts +94 -0
- package/src/events/rules/openSseStream.ts +594 -0
- package/src/events/rules/sse.ts +349 -0
- package/src/index.ts +231 -0
- package/src/rest/adminOperations.gen.ts +70 -0
- package/src/rest/adminResources.gen.ts +136 -0
- package/src/rest/coreOperations.gen.ts +74 -0
- package/src/rest/coreResources.gen.ts +244 -0
- package/src/rest/dates.gen.ts +217 -0
- package/src/rest/operations.gen.ts +4341 -0
- package/src/rest/resources.gen.ts +369 -0
- package/src/rest/schema.gen.ts +56840 -0
- package/src/tiles/operations.gen.ts +206 -0
- package/src/tiles/schema.gen.ts +8408 -0
- package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
- package/src/webhooks/rules/webhookEvent.ts +38 -0
- package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
|
@@ -0,0 +1,2386 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The transport.
|
|
3
|
+
*
|
|
4
|
+
* This is the one place in the package where `fetch` is called. Everything above it (the REST
|
|
5
|
+
* operations, the tile helpers, the Data API wrappers) composes this function, and
|
|
6
|
+
* `@mountaya/elements` never reaches it at all, which is where the boundary falls.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
assertCredential,
|
|
11
|
+
type Credential,
|
|
12
|
+
credentialHeaders,
|
|
13
|
+
holdsSession,
|
|
14
|
+
isPublishableCredential,
|
|
15
|
+
isSecretCredential,
|
|
16
|
+
isShareCredential,
|
|
17
|
+
type OperationCredentials,
|
|
18
|
+
sessionExpiryOf,
|
|
19
|
+
sessionSourceOf,
|
|
20
|
+
sessionTokenOf,
|
|
21
|
+
sessionUserOf,
|
|
22
|
+
wantsCookies,
|
|
23
|
+
} from "./auth.js";
|
|
24
|
+
import { CLIENT_HEADER_VALUE } from "./clientHeader.js";
|
|
25
|
+
import type { DateMask } from "./dates.js";
|
|
26
|
+
import {
|
|
27
|
+
answerDetailsOf,
|
|
28
|
+
describeType,
|
|
29
|
+
entriesOf,
|
|
30
|
+
MountayaConfigurationError,
|
|
31
|
+
MountayaConnectionError,
|
|
32
|
+
parseRetryAfter,
|
|
33
|
+
refuseOption,
|
|
34
|
+
replayedOf,
|
|
35
|
+
} from "./errors.js";
|
|
36
|
+
import { isEmptyHeaderValue, isHeaderValue } from "./headerValue.js";
|
|
37
|
+
import { mintIdempotencyKey } from "./idempotencyKey.js";
|
|
38
|
+
import { type NullableMask, withAbsentNulls } from "./nullMask.js";
|
|
39
|
+
import { responseNulls } from "./nullMasks.gen.js";
|
|
40
|
+
import type { RateLimitInfo } from "./rateLimit.js";
|
|
41
|
+
import { printableCredential, printableProjection, secretDigest } from "./redaction.js";
|
|
42
|
+
import {
|
|
43
|
+
decodeSuccessDates,
|
|
44
|
+
isAborted,
|
|
45
|
+
parseSuccessBody,
|
|
46
|
+
readBytes,
|
|
47
|
+
readFailure,
|
|
48
|
+
readFailureText,
|
|
49
|
+
readText,
|
|
50
|
+
} from "./responseBody.js";
|
|
51
|
+
import {
|
|
52
|
+
abortReasonOf,
|
|
53
|
+
backoffDelay,
|
|
54
|
+
defaultRetry,
|
|
55
|
+
isKeyInUse,
|
|
56
|
+
jitteredDelay,
|
|
57
|
+
KEY_IN_USE_MIN_WAIT_MS,
|
|
58
|
+
MAX_TIMER_DELAY_MS,
|
|
59
|
+
namedError,
|
|
60
|
+
type RetryOptions,
|
|
61
|
+
resolveRetry,
|
|
62
|
+
type Surface,
|
|
63
|
+
shouldRetry,
|
|
64
|
+
sleep,
|
|
65
|
+
} from "./retry.js";
|
|
66
|
+
import { waitForSessionToken } from "./sessionWait.js";
|
|
67
|
+
import { assertWebAddresses, bareHostPattern } from "./webAddress.js";
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Default base URLs, one per surface.
|
|
71
|
+
*
|
|
72
|
+
* `tiles` and `rest` are each the `servers` entry of their own public bundle, so each moves
|
|
73
|
+
* only when the contract does. `data` has no published server URL to read (the Data API is
|
|
74
|
+
* reached through a URL set per environment), so it is stated here.
|
|
75
|
+
*
|
|
76
|
+
* `scripts/contract-checkout.test.mjs` compares every entry against the contract checkout beside
|
|
77
|
+
* the repository, which is what keeps this object derived rather than hand-kept: a default that
|
|
78
|
+
* drifts from the published server URL is a first call that reaches the wrong host, and nothing
|
|
79
|
+
* else in the toolchain would notice.
|
|
80
|
+
*/
|
|
81
|
+
export const defaultBaseUrls: Readonly<Record<Surface, string>> = {
|
|
82
|
+
/** The Data API, stated here since the Data API publishes no server URL to read. */
|
|
83
|
+
data: "https://data.mountaya.com",
|
|
84
|
+
/** The Map Studio REST API, where the event streams are opened too. */
|
|
85
|
+
rest: "https://api.mountaya.com",
|
|
86
|
+
/** The Tile API. */
|
|
87
|
+
tiles: "https://tiles.mountaya.com",
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* DEFAULT_TIMEOUT_MS is how long one attempt waits for a response's headers when a client names
|
|
92
|
+
* no `timeoutMs`.
|
|
93
|
+
*/
|
|
94
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* SERVER_BUDGET_MARGIN_MS is how much longer than an operation's own `x-timeout-ms` an attempt
|
|
98
|
+
* waits by default, in milliseconds: the API answers a 504 itself once it has spent that long, and
|
|
99
|
+
* the margin lets that answer arrive before the client gives up on it, so a write the API is
|
|
100
|
+
* still running is not abandoned for a repeat that would meet it in flight.
|
|
101
|
+
*/
|
|
102
|
+
const SERVER_BUDGET_MARGIN_MS = 5000;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* responseNullMask answers the members the answer an operation succeeds with reads null where it
|
|
106
|
+
* leaves them out, or undefined for an operation whose answer holds none.
|
|
107
|
+
*
|
|
108
|
+
* @param operationId - The operation the answer is to.
|
|
109
|
+
*/
|
|
110
|
+
const responseNullMask = (operationId: string): NullableMask | undefined =>
|
|
111
|
+
// Read as the table's own member alone: an operation id that names a member every object
|
|
112
|
+
// inherits, `toString` among them, names no answer.
|
|
113
|
+
Object.hasOwn(responseNulls, operationId) ? responseNulls[operationId] : undefined;
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* ResponseReport is what {@link ClientOptions.onResponse} is told of each attempt an answer came
|
|
117
|
+
* back to: which call, on which surface, which attempt, the answer's status, whether the API gave
|
|
118
|
+
* it again for a key it had seen, the id the API recorded it under and the rate-limit state it
|
|
119
|
+
* describes.
|
|
120
|
+
*/
|
|
121
|
+
export interface ResponseReport {
|
|
122
|
+
/** Which attempt of the call the answer is to, 0 for the first. */
|
|
123
|
+
readonly attempt: number;
|
|
124
|
+
/** The contract's name for the call's operation. */
|
|
125
|
+
readonly operationId: string;
|
|
126
|
+
/**
|
|
127
|
+
* The rate-limit state the answer's `RateLimit-Policy` and `RateLimit` describe, where they
|
|
128
|
+
* describe one: the Data API and the Tile API do on every answer made under a key.
|
|
129
|
+
*/
|
|
130
|
+
readonly rateLimit?: RateLimitInfo | undefined;
|
|
131
|
+
/**
|
|
132
|
+
* Whether the answer carries `Idempotent-Replayed: true`: the API kept it for the call's
|
|
133
|
+
* `Idempotency-Key`, which an earlier request carried, and gave it again rather than run the
|
|
134
|
+
* write a second time.
|
|
135
|
+
*/
|
|
136
|
+
readonly replayed: boolean;
|
|
137
|
+
/** The answer's `X-Request-Id`, exactly as sent, where it sent one. */
|
|
138
|
+
readonly requestId?: string | undefined;
|
|
139
|
+
/** The answer's HTTP status. */
|
|
140
|
+
readonly status: number;
|
|
141
|
+
/** The API the call went to. */
|
|
142
|
+
readonly surface: Surface;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* BaseUrlOverrides names the base URL a client reaches each surface at, one surface at a time:
|
|
147
|
+
* what {@link ClientOptions.baseUrls} takes.
|
|
148
|
+
*
|
|
149
|
+
* A surface left out keeps its default, and so does one written as `undefined`, which a caller
|
|
150
|
+
* forwarding a URL it may not hold writes. Each member states that `undefined`, so the same
|
|
151
|
+
* forward compiles for a consumer under `exactOptionalPropertyTypes`.
|
|
152
|
+
*/
|
|
153
|
+
export interface BaseUrlOverrides {
|
|
154
|
+
/**
|
|
155
|
+
* The Data API's base URL.
|
|
156
|
+
*
|
|
157
|
+
* @default "https://data.mountaya.com"
|
|
158
|
+
*/
|
|
159
|
+
readonly data?: string | undefined;
|
|
160
|
+
/**
|
|
161
|
+
* The Map Studio REST API's base URL, which the event streams are opened on too.
|
|
162
|
+
*
|
|
163
|
+
* @default "https://api.mountaya.com"
|
|
164
|
+
*/
|
|
165
|
+
readonly rest?: string | undefined;
|
|
166
|
+
/**
|
|
167
|
+
* The Tile API's base URL.
|
|
168
|
+
*
|
|
169
|
+
* @default "https://tiles.mountaya.com"
|
|
170
|
+
*/
|
|
171
|
+
readonly tiles?: string | undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* ClientOptions configures a client. Only the credential is required: a first call should not
|
|
176
|
+
* need a base URL, a timeout policy or a retry policy to be chosen.
|
|
177
|
+
*
|
|
178
|
+
* `timeoutMs`, each `retry` member, each `baseUrls` entry, `language` and `fetch` are checked at
|
|
179
|
+
* construction, and one that cannot work throws a `MountayaConfigurationError` naming the option
|
|
180
|
+
* and the value. A credential that cannot work throws one naming what is wrong with it: an empty
|
|
181
|
+
* or blank key reads as a missing credential, nothing of a share token, a session token or a
|
|
182
|
+
* value in the secret key's slot is quoted, and of a value in the publishable key's slot under
|
|
183
|
+
* the wrong prefix its first three characters alone, which tell which value landed there. A
|
|
184
|
+
* refused `baseUrls` entry that holds an `@` is named without its value, since a password may
|
|
185
|
+
* stand before the `@`, and options that are not an object at all are named by their type. A
|
|
186
|
+
* member written as `undefined` is an omitted one, so a caller forwarding an optional value
|
|
187
|
+
* keeps the default.
|
|
188
|
+
*/
|
|
189
|
+
export interface ClientOptions {
|
|
190
|
+
/** How the client authenticates: see {@link Credential} for the shapes it takes. */
|
|
191
|
+
readonly credential: Credential;
|
|
192
|
+
/**
|
|
193
|
+
* Overrides the default base URL per surface, one surface at a time. Useful against a local
|
|
194
|
+
* stack or behind a gateway.
|
|
195
|
+
*
|
|
196
|
+
* Each entry is an absolute `http:` or `https:` URL with no query and no fragment
|
|
197
|
+
* (`http://localhost:8080`), a path starting with one `/` for a gateway on the page's own
|
|
198
|
+
* origin (`/api`), or `""` for the page's own origin itself. A bare host such as
|
|
199
|
+
* `api.example.com` is refused rather than joined as a path, and so is a path whose dot
|
|
200
|
+
* segments or backslashes resolve it to `//host`, which `fetch` reads as another origin, and an
|
|
201
|
+
* entry with whitespace at either end. An absolute URL names no username and no password
|
|
202
|
+
* (`https://user:pass@host`), which `fetch` refuses in a request's URL.
|
|
203
|
+
*
|
|
204
|
+
* The page's own origin is the origin of the page's address, `location`, which a `<base>`
|
|
205
|
+
* element does not move: a request under a path or `""` leaves as an absolute URL at that
|
|
206
|
+
* origin, never as a relative one the document's base URL could send to another host. Where
|
|
207
|
+
* no page names an `http` or `https` origin (Node, a native application, `about:blank`, a
|
|
208
|
+
* `file:` document), a path or `""` names no place to send a request, and the client is
|
|
209
|
+
* refused with a `MountayaConfigurationError` as it is built.
|
|
210
|
+
*
|
|
211
|
+
* @default {@link defaultBaseUrls}, entry by entry: a surface left out keeps its own.
|
|
212
|
+
*/
|
|
213
|
+
readonly baseUrls?: BaseUrlOverrides | undefined;
|
|
214
|
+
/**
|
|
215
|
+
* How long one attempt waits for a response to arrive, in whole milliseconds from 1 to
|
|
216
|
+
* 2,147,483,647.
|
|
217
|
+
*
|
|
218
|
+
* It bounds each attempt rather than the retry sequence, so a retried call is not left with
|
|
219
|
+
* nothing by the attempt before it. An operation that states the most the API spends on it
|
|
220
|
+
* (`x-timeout-ms`) waits that plus five seconds where that is longer, so an import is not
|
|
221
|
+
* abandoned while the API is still running it; a call's own `timeoutMs` stands over both. It stops once the response's headers are in: a large body
|
|
222
|
+
* still arriving is not cut off, and only the caller's `signal` ends it. An attempt that
|
|
223
|
+
* reaches it fails as a `MountayaConnectionError` saying so, and is retried as a network
|
|
224
|
+
* failure is.
|
|
225
|
+
*
|
|
226
|
+
* A refusal's body is the one read with a bound of its own, whatever this is set to: an error
|
|
227
|
+
* envelope is read from at most 64 KiB arriving within 5 seconds, and past either the status
|
|
228
|
+
* alone classifies the failure.
|
|
229
|
+
*
|
|
230
|
+
* @default 30000
|
|
231
|
+
*/
|
|
232
|
+
readonly timeoutMs?: number | undefined;
|
|
233
|
+
/** The retry policy, laid over the defaults member by member: see {@link RetryOptions}. */
|
|
234
|
+
readonly retry?: RetryOptions | undefined;
|
|
235
|
+
/**
|
|
236
|
+
* Told of every attempt an answer came back to, once each, in order: a success, a refusal and
|
|
237
|
+
* an answer the client repeats alike, the open of an event stream included. An attempt that
|
|
238
|
+
* never arrived has no answer to report. See {@link ResponseReport} for what it is told.
|
|
239
|
+
*
|
|
240
|
+
* For observing, never for steering: the client delays no request on the rate-limit state it
|
|
241
|
+
* reports, and a fault the hook throws changes nothing the call answers. It reaches the
|
|
242
|
+
* runtime as the program's own uncaught error, on a microtask. A value that is not a function
|
|
243
|
+
* is refused at construction.
|
|
244
|
+
*/
|
|
245
|
+
readonly onResponse?: ((report: ResponseReport) => void) | undefined;
|
|
246
|
+
/**
|
|
247
|
+
* BCP 47 tag sent as `Accept-Language` (`"fr"`, `"pt-BR"`) on every request and every event
|
|
248
|
+
* stream's open. A value that is not a string, one no request header carries (a character
|
|
249
|
+
* outside printable ASCII: a line break, a tab, a letter of Latin-1 such as `é`) and one that is
|
|
250
|
+
* empty or whitespace alone are each refused at construction.
|
|
251
|
+
*
|
|
252
|
+
* Worth setting. The API localizes its validation sentences, and applications
|
|
253
|
+
* splice those into copy they have already translated: leaving it unset asks for no language
|
|
254
|
+
* in particular, and a user reads one message written half in each.
|
|
255
|
+
*
|
|
256
|
+
* @default `"*"`, which asks for no language in particular, so the language an answer is
|
|
257
|
+
* written in is never one the runtime's `fetch` writes for a request that names none.
|
|
258
|
+
*/
|
|
259
|
+
readonly language?: string | undefined;
|
|
260
|
+
/**
|
|
261
|
+
* Replaces the global fetch. For tests, proxies and instrumentation. A value that is not a
|
|
262
|
+
* function is refused at construction.
|
|
263
|
+
*
|
|
264
|
+
* A function that reads the response it answers reads a clone of it. A body already read, or
|
|
265
|
+
* one a reader is still held on, cannot be read a second time: a success is then reported as a
|
|
266
|
+
* body that broke off, a `MountayaConnectionError`, and a failure is classified by its status
|
|
267
|
+
* alone, with no entry.
|
|
268
|
+
*
|
|
269
|
+
* @default the global `fetch`, read at each call.
|
|
270
|
+
*/
|
|
271
|
+
readonly fetch?: typeof fetch | undefined;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* RequestOptions are the per-call knobs a CALLER sets, as the last parameter of every generated
|
|
276
|
+
* operation and of every bound method.
|
|
277
|
+
*
|
|
278
|
+
* The distinction from {@link RequestArgs} is who builds it: an operation builds those from the
|
|
279
|
+
* contract (a path, a method, an idempotence flag), and a caller has no business stating any of
|
|
280
|
+
* them. This is the other half, and it is deliberately narrow: everything a request needs that a
|
|
281
|
+
* generated signature cannot know.
|
|
282
|
+
*
|
|
283
|
+
* The Data API's options bag extends this one, so a knob added here reaches all three surfaces.
|
|
284
|
+
*/
|
|
285
|
+
export interface RequestOptions {
|
|
286
|
+
/**
|
|
287
|
+
* Overrides the client's retry policy for this call alone.
|
|
288
|
+
*
|
|
289
|
+
* Merged over the client's own, member by member, so a call that sets only `maxRetries` keeps
|
|
290
|
+
* the client's delays. The policy is the contract's to state per client AND per call: a
|
|
291
|
+
* search box that re-queries on every keystroke wants no retries at all, and a background
|
|
292
|
+
* sync on the same client wants the defaults, and neither should need a second client to say
|
|
293
|
+
* so. Which statuses are repeated is not a knob: that is the contract's rule, not the
|
|
294
|
+
* caller's. Checked before the first attempt, as a client's is at construction.
|
|
295
|
+
*/
|
|
296
|
+
readonly retry?: RetryOptions | undefined;
|
|
297
|
+
/**
|
|
298
|
+
* How long each attempt of this call waits for a response, in whole milliseconds from 1 to
|
|
299
|
+
* 2,147,483,647, in place of the client's {@link ClientOptions.timeoutMs} and of the budget
|
|
300
|
+
* the operation states, longer or shorter than either. It bounds a wait for the first session
|
|
301
|
+
* token as well. A value outside the range is refused before the first attempt, naming the
|
|
302
|
+
* call.
|
|
303
|
+
*
|
|
304
|
+
* @default the larger of the client's own `timeoutMs` and the operation's `x-timeout-ms` plus
|
|
305
|
+
* five seconds, where it states one.
|
|
306
|
+
*/
|
|
307
|
+
readonly timeoutMs?: number | undefined;
|
|
308
|
+
/**
|
|
309
|
+
* Aborts the request, any retry of it, and the reading of its body.
|
|
310
|
+
*
|
|
311
|
+
* Joined to each attempt's own timeout, so a caller's abort and a timeout are both honoured
|
|
312
|
+
* rather than the last one set winning, and it settles a call at once wherever the call is:
|
|
313
|
+
* waiting for headers, waiting out a backoff, or reading a body, a failure's as well as a
|
|
314
|
+
* success's. The call rejects with the signal's own reason, never rewrapped, or with an
|
|
315
|
+
* `AbortError` where the signal carries none. A body still arriving is cancelled, which lets
|
|
316
|
+
* go of its connection, on every runtime that streams a response's body. Where the runtime
|
|
317
|
+
* buffers bodies whole and exposes no stream (React Native), the read is abandoned instead.
|
|
318
|
+
*/
|
|
319
|
+
readonly signal?: AbortSignal | undefined;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* RequestArgs describes one call: what a generated operation builds, and what a consumer builds
|
|
324
|
+
* for an operation this client does not bind, stating what that operation declares (`dates`,
|
|
325
|
+
* `requiresSecretKey`, `takesNoCredential`, `acceptsShareToken`, `requiresSession`,
|
|
326
|
+
* `actsAsMember`, `serverBudgetMs`, `takesIdempotencyKey`).
|
|
327
|
+
*
|
|
328
|
+
* A declaration left out is one the operation does not make, so a hand-built call states each
|
|
329
|
+
* one its operation makes: without `dates` its body decodes no `Date`, and without
|
|
330
|
+
* `requiresSecretKey` or `takesNoCredential` a secret key is refused on it. No declaration
|
|
331
|
+
* refuses a cookie credential, which is outside the published contract.
|
|
332
|
+
*
|
|
333
|
+
* The headers a call names are `accept`, `idempotencyKey` and `ifMatch`, and no other: the rest a
|
|
334
|
+
* request carries are the client's to write, `X-Mountaya-Client` among them, which names the SDK
|
|
335
|
+
* on every request.
|
|
336
|
+
*/
|
|
337
|
+
export interface RequestArgs {
|
|
338
|
+
/** The API the call goes to, whose base URL the path is joined onto. */
|
|
339
|
+
readonly surface: Surface;
|
|
340
|
+
/** The HTTP method, as the contract states it (`"GET"`, `"POST"`). */
|
|
341
|
+
readonly method: string;
|
|
342
|
+
/**
|
|
343
|
+
* The path under the surface's base URL, starting with `/`, each parameter already
|
|
344
|
+
* percent-encoded. A path that leaves the base URL, or holds an empty or a dot segment, is
|
|
345
|
+
* refused before the first attempt.
|
|
346
|
+
*/
|
|
347
|
+
readonly path: string;
|
|
348
|
+
/** The contract's name for the operation, which every refusal and failure message names. */
|
|
349
|
+
readonly operationId: string;
|
|
350
|
+
/**
|
|
351
|
+
* The instants in the success body, as a {@link DateMask}: each string the mask names decodes
|
|
352
|
+
* to a `Date` where it is a full ISO 8601 timestamp carrying a zone and naming a real instant,
|
|
353
|
+
* and every other string stays a string. A generated operation states the mask its contract
|
|
354
|
+
* declares, and nothing where the contract declares no instant. Omitted, the body decodes no
|
|
355
|
+
* `Date` at all.
|
|
356
|
+
*/
|
|
357
|
+
readonly dates?: DateMask | undefined;
|
|
358
|
+
/**
|
|
359
|
+
* Whether the operation is authenticated by a secret key: the contract declares
|
|
360
|
+
* `x-pkey-scope: none` beside a security requirement, which `postSession` alone does. A
|
|
361
|
+
* generated operation states `true` there and nothing elsewhere. Where it is stated, every
|
|
362
|
+
* credential but a secret key is refused locally. Where it is not, a secret key is refused,
|
|
363
|
+
* unless the operation takes no credential: the API answers a secret key on an operation it
|
|
364
|
+
* does not authenticate with a 401, as if nothing had been sent.
|
|
365
|
+
*/
|
|
366
|
+
readonly requiresSecretKey?: boolean | undefined;
|
|
367
|
+
/**
|
|
368
|
+
* Whether the operation takes no credential at all: its `security` is an empty list, which
|
|
369
|
+
* `postOrganizationLookup`'s is. A generated operation states `true` there and nothing
|
|
370
|
+
* elsewhere. Where it is stated, the request carries nothing the client's credential holds,
|
|
371
|
+
* no header and no cookie, whatever origin the API is reached at, and no credential is
|
|
372
|
+
* refused.
|
|
373
|
+
*/
|
|
374
|
+
readonly takesNoCredential?: boolean | undefined;
|
|
375
|
+
/**
|
|
376
|
+
* Whether one of the operation's security requirements is a share token on its own. A
|
|
377
|
+
* generated operation states `true` where the contract does and nothing elsewhere, and
|
|
378
|
+
* nothing means no: a share token is refused locally, before the first attempt, on every
|
|
379
|
+
* operation that does not state it. That is how a share-token write is refused, and how a read
|
|
380
|
+
* no share link reaches is refused before the 401 the server would answer.
|
|
381
|
+
*
|
|
382
|
+
* A client holding a share token beside a key sends the share token alone where this is
|
|
383
|
+
* `true`, since a share token REPLACES the key: the server, sent both, would read the key.
|
|
384
|
+
*/
|
|
385
|
+
readonly acceptsShareToken?: boolean | undefined;
|
|
386
|
+
/**
|
|
387
|
+
* Whether every one of the operation's security requirements names a session token. A
|
|
388
|
+
* generated operation states `true` where the contract does, and a credential carrying none (a
|
|
389
|
+
* bare publishable key, a secret key, a share token) is then refused locally rather than sent
|
|
390
|
+
* to be answered with a 401. A credential whose {@link SessionTokenSource} has a token on its
|
|
391
|
+
* way waits for it first, and is refused only once that wait ends with none. The contract
|
|
392
|
+
* states it on every `management` and every `studio-embedded` operation, and the Data API on
|
|
393
|
+
* every operation.
|
|
394
|
+
*/
|
|
395
|
+
readonly requiresSession?: boolean | undefined;
|
|
396
|
+
/**
|
|
397
|
+
* The caller's per-call override of the client's retry policy, from
|
|
398
|
+
* {@link RequestOptions.retry}. Merged over the client's policy member by member.
|
|
399
|
+
*/
|
|
400
|
+
readonly retry?: RetryOptions | undefined;
|
|
401
|
+
/**
|
|
402
|
+
* How long each attempt of this call waits for a response, from {@link RequestOptions.timeoutMs}:
|
|
403
|
+
* a whole number of milliseconds from 1 to 2,147,483,647, which stands over the client's own
|
|
404
|
+
* and over {@link RequestArgs.serverBudgetMs}. A value outside the range is refused before the
|
|
405
|
+
* first attempt, naming the call.
|
|
406
|
+
*
|
|
407
|
+
* @default the larger of the client's own `timeoutMs` and `serverBudgetMs` plus five seconds.
|
|
408
|
+
*/
|
|
409
|
+
readonly timeoutMs?: number | undefined;
|
|
410
|
+
/**
|
|
411
|
+
* The most the API spends on the operation before it answers a 504 itself, its `x-timeout-ms`,
|
|
412
|
+
* in whole milliseconds. A generated operation states it wherever the contract does, which is
|
|
413
|
+
* every operation but an event stream. Each attempt then waits the larger of the client's own
|
|
414
|
+
* `timeoutMs` and this plus five seconds, unless the call names its own.
|
|
415
|
+
*/
|
|
416
|
+
readonly serverBudgetMs?: number | undefined;
|
|
417
|
+
/**
|
|
418
|
+
* Whether repeating this request is safe. Declared rather than inferred: the Data API
|
|
419
|
+
* is GraphQL over POST and every one of its operations is a read.
|
|
420
|
+
*/
|
|
421
|
+
readonly idempotent: boolean;
|
|
422
|
+
/**
|
|
423
|
+
* Whether the operation declares `Idempotency-Key`, which every POST, PATCH and DELETE of the
|
|
424
|
+
* Map Studio API does but `postSession`, `postOrganizationLookup` and the two collaboration
|
|
425
|
+
* signals, `postItineraryCollab` and `postZoneCollab`; the Tile API has no write, and no read
|
|
426
|
+
* declares it. Where it does, each attempt of the call sends one key:
|
|
427
|
+
* {@link RequestArgs.idempotencyKey} where the caller passes one, and otherwise one drawn from
|
|
428
|
+
* the runtime's cryptographic random source before the first attempt, or none where the runtime
|
|
429
|
+
* has no such source. Where it does not, no key is sent, the caller's included.
|
|
430
|
+
*/
|
|
431
|
+
readonly takesIdempotencyKey?: boolean | undefined;
|
|
432
|
+
/**
|
|
433
|
+
* The `Idempotency-Key` every attempt of this call sends, as given, on an operation that states
|
|
434
|
+
* {@link RequestArgs.takesIdempotencyKey}; on any other it is neither sent nor read. A request
|
|
435
|
+
* that carries a key is repeated after a 502, a 503, a 504, a dropped connection and a 409
|
|
436
|
+
* saying the key is still in use, whatever the operation declares, since the API answers a key
|
|
437
|
+
* it has seen with the answer it stored, and every error the call raises carries the key it
|
|
438
|
+
* sent. One that is empty, whitespace alone, or holds a character no request header carries (a
|
|
439
|
+
* character outside printable ASCII) is refused before the first attempt.
|
|
440
|
+
*/
|
|
441
|
+
readonly idempotencyKey?: string | undefined;
|
|
442
|
+
/**
|
|
443
|
+
* The tag a conditional write names, sent as `If-Match` on every attempt exactly as given: the
|
|
444
|
+
* `etag` of the resource as the API wrote it, or `*` for a resource that exists at all. The
|
|
445
|
+
* client never writes one the caller did not name. A stale one is answered with a 412, a
|
|
446
|
+
* `MountayaPreconditionFailedError`, which is never repeated. One that is empty, whitespace
|
|
447
|
+
* alone, or holds a character no request header carries (a character outside printable ASCII)
|
|
448
|
+
* is refused before the first attempt.
|
|
449
|
+
*/
|
|
450
|
+
readonly ifMatch?: string | undefined;
|
|
451
|
+
/**
|
|
452
|
+
* Whether the operation acts as the user its session token was minted for: its
|
|
453
|
+
* `x-acting-user` is `required`. A generated operation states `true` there and nothing
|
|
454
|
+
* elsewhere. Where it is stated, a credential whose {@link SessionTokenSource} reports a token
|
|
455
|
+
* minted without `user_id` is refused locally, since the API would answer the call with a 401.
|
|
456
|
+
*/
|
|
457
|
+
readonly actsAsMember?: boolean | undefined;
|
|
458
|
+
/**
|
|
459
|
+
* Whether this operation only READS where its method would say it writes. Omitted means
|
|
460
|
+
* "whatever the method implies", which is right for every REST and tile operation. A share
|
|
461
|
+
* token refused on an operation that does not accept one is told it cannot write where the
|
|
462
|
+
* operation writes.
|
|
463
|
+
*
|
|
464
|
+
* `idempotent` answers a different question and cannot stand in for this one: `PATCH` and
|
|
465
|
+
* `DELETE` are idempotent writes. It belongs on any operation whose verb is the transport rather
|
|
466
|
+
* than the intent: `core/rules/graphql.ts` sets it for the whole Data API, which is GraphQL
|
|
467
|
+
* over POST.
|
|
468
|
+
*/
|
|
469
|
+
readonly read?: boolean | undefined;
|
|
470
|
+
/**
|
|
471
|
+
* The query string, one parameter per member. A member that is `undefined` is left out, and
|
|
472
|
+
* that is the only omission: `""` is sent as `key=`, and `false` and `0` as written.
|
|
473
|
+
*/
|
|
474
|
+
readonly query?: Record<string, string | number | boolean | undefined> | undefined;
|
|
475
|
+
/**
|
|
476
|
+
* The request body: sent as JSON, or as it is where it is a `FormData`, whose multipart
|
|
477
|
+
* boundary `fetch` writes. A body that cannot be sent as JSON is refused before the first
|
|
478
|
+
* attempt, and so is one holding a web address with no scheme in a member the contract types
|
|
479
|
+
* `format: uri` for the call's `operationId` on the Map Studio API, judged as the JSON sent.
|
|
480
|
+
*/
|
|
481
|
+
readonly body?: unknown;
|
|
482
|
+
/**
|
|
483
|
+
* The `Accept` header, `application/json` where it is left out. `text/event-stream` is refused
|
|
484
|
+
* before the first attempt: a stream is opened from `@mountaya/client/events`. So is one that
|
|
485
|
+
* is empty, whitespace alone, or holds a character no request header carries (a character
|
|
486
|
+
* outside printable ASCII).
|
|
487
|
+
*/
|
|
488
|
+
readonly accept?: string | undefined;
|
|
489
|
+
/** Aborts the call wherever it is, as {@link RequestOptions.signal} does. */
|
|
490
|
+
readonly signal?: AbortSignal | undefined;
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* isFormData recognises a multipart body the transport must hand to fetch untouched.
|
|
495
|
+
*
|
|
496
|
+
* One public operation takes an uploaded file: `postItineraryPreview`, whose file
|
|
497
|
+
* providers (gpx, geojson, kml, kmz, fit, tcx) are declared `multipart/form-data` while
|
|
498
|
+
* its online providers are declared `application/json`. Both branches are the same
|
|
499
|
+
* operation, so the discriminator has to be the body's own runtime type.
|
|
500
|
+
*
|
|
501
|
+
* The `typeof` guard is not ceremony: `FormData` is global from Node 18 on, but this
|
|
502
|
+
* package supports embedding in runtimes that provide `fetch` through a polyfill, and a
|
|
503
|
+
* bare `instanceof` against a missing global throws a ReferenceError rather than
|
|
504
|
+
* answering false.
|
|
505
|
+
*/
|
|
506
|
+
const isFormData = (body: unknown): body is FormData =>
|
|
507
|
+
typeof FormData !== "undefined" && body instanceof FormData;
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* encodeBody turns an operation's body into something fetch can send.
|
|
511
|
+
*
|
|
512
|
+
* A FormData rides through as itself. Serializing it would produce the string
|
|
513
|
+
* "[object FormData]" and upload nothing: a failure that reaches the server as a valid
|
|
514
|
+
* request with a nonsense body, so it surfaces as a parse error naming the file format
|
|
515
|
+
* rather than anything pointing back here.
|
|
516
|
+
*
|
|
517
|
+
* @throws `MountayaConfigurationError` naming the operation for a body `JSON.stringify` refuses
|
|
518
|
+
* (a cycle, a `BigInt`, a `toJSON` that throws), carrying what it threw as its `cause`.
|
|
519
|
+
*/
|
|
520
|
+
const encodeBody = (body: unknown, operationId: string): BodyInit | undefined => {
|
|
521
|
+
if (body === undefined) {
|
|
522
|
+
return undefined;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (isFormData(body)) {
|
|
526
|
+
return body;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
try {
|
|
530
|
+
return JSON.stringify(body);
|
|
531
|
+
} catch (cause) {
|
|
532
|
+
// The first line of what it threw: a runtime spells a cycle's path over several, and the
|
|
533
|
+
// `cause` carries them all.
|
|
534
|
+
const reason =
|
|
535
|
+
cause instanceof Error ? cause.message.split("\n", 1)[0] : `threw ${describeType(cause)}`;
|
|
536
|
+
|
|
537
|
+
throw new MountayaConfigurationError(
|
|
538
|
+
`${operationId}: the body cannot be sent as JSON (${reason}). Pass a body JSON.stringify accepts, with no cycle and no BigInt.`,
|
|
539
|
+
{ cause },
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* BinaryBody is what a non-JSON operation resolves to: the bytes, plus the two headers
|
|
546
|
+
* that say what they are and what to call them.
|
|
547
|
+
*
|
|
548
|
+
* The bytes alone would be under-described. A tile's media type decides whether it is
|
|
549
|
+
* decoded as protobuf or handed to an image decoder, and an export's `filename` is the
|
|
550
|
+
* name the API chose for the file: a `.gpx` named after the itinerary, in the viewer's
|
|
551
|
+
* language. Reconstructing either from the request would mean re-deriving something the
|
|
552
|
+
* response already answered.
|
|
553
|
+
*/
|
|
554
|
+
export interface BinaryBody {
|
|
555
|
+
/** The body, whole, as it arrived. */
|
|
556
|
+
readonly bytes: ArrayBuffer;
|
|
557
|
+
/** The response's Content-Type, verbatim, when the response carried one. */
|
|
558
|
+
readonly contentType?: string | undefined;
|
|
559
|
+
/** The download filename from Content-Disposition, when the response carried one. */
|
|
560
|
+
readonly filename?: string | undefined;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/**
|
|
564
|
+
* StreamDeclaration is what a call made outside this transport declares about the credentials
|
|
565
|
+
* it takes: the flags {@link RequestArgs} carries for a request this client makes itself, and
|
|
566
|
+
* the operation id a refusal names.
|
|
567
|
+
*/
|
|
568
|
+
type StreamDeclaration = Partial<
|
|
569
|
+
Pick<RequestArgs, "acceptsShareToken" | "actsAsMember" | "operationId" | "requiresSession">
|
|
570
|
+
>;
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* StreamSeam is what {@link MountayaTransport.streamSeam} hands a `text/event-stream` opener: the
|
|
574
|
+
* credential ladder, the resolved fetch, the bound on the wait for a response, and a URL resolver
|
|
575
|
+
* over the REST origin.
|
|
576
|
+
*
|
|
577
|
+
* Every stream on the contract is on the REST surface, so the resolver is bound to that one
|
|
578
|
+
* rather than taking a surface. A tile or a GraphQL stream would need it to grow an argument,
|
|
579
|
+
* and neither exists.
|
|
580
|
+
*/
|
|
581
|
+
export interface StreamSeam {
|
|
582
|
+
/**
|
|
583
|
+
* applyAuth folds this transport's credential into the request's RequestInit.
|
|
584
|
+
*
|
|
585
|
+
* `declaration` is what the stream's operation declares, as {@link RequestArgs} carries it
|
|
586
|
+
* for a request. Every stream on the contract requires a session token and acts as the member
|
|
587
|
+
* it names, so an opener states `{ actsAsMember: true, requiresSession: true }`, and a
|
|
588
|
+
* credential that cannot meet either is refused here, before the stream opens, with the error a
|
|
589
|
+
* request would raise. No stream accepts a share token, and none takes a secret key.
|
|
590
|
+
*/
|
|
591
|
+
readonly applyAuth: (
|
|
592
|
+
init: RequestInit,
|
|
593
|
+
method: string,
|
|
594
|
+
declaration?: StreamDeclaration,
|
|
595
|
+
) => RequestInit;
|
|
596
|
+
/** doFetch is the fetch this transport resolved: the real one, or the caller's double. */
|
|
597
|
+
readonly doFetch: typeof fetch;
|
|
598
|
+
/**
|
|
599
|
+
* report tells the client's {@link ClientOptions.onResponse} of an open's answer, as a request
|
|
600
|
+
* tells it of each attempt's. An open is one attempt, reported as attempt 0: a reader's reopen
|
|
601
|
+
* is an open of its own.
|
|
602
|
+
*/
|
|
603
|
+
readonly report: (response: Response, operationId: string) => void;
|
|
604
|
+
/**
|
|
605
|
+
* sessionExpiresAt answers when the session token an open made now carries expires, where the
|
|
606
|
+
* credential's source reports it. The API ends a stream with the credential it was opened
|
|
607
|
+
* with, so a stream that closes at or after this instant is opened again at once.
|
|
608
|
+
*/
|
|
609
|
+
readonly sessionExpiresAt: () => Date | undefined;
|
|
610
|
+
/**
|
|
611
|
+
* sessionUserId answers the user the session token an open made now names, as the credential's
|
|
612
|
+
* source reports it: a string names one, `null` names none, and undefined is a source that does
|
|
613
|
+
* not say, or a token held as a string or a function, whose user the client is not told. A
|
|
614
|
+
* collaboration stream reads it as the member the stream is read as.
|
|
615
|
+
*/
|
|
616
|
+
readonly sessionUserId: () => string | null | undefined;
|
|
617
|
+
/**
|
|
618
|
+
* waitForSession waits, before an open, for a session token the credential's source reports on
|
|
619
|
+
* its way, as a request waits for one, bounded by {@link StreamSeam.timeoutMs} and `signal`. It
|
|
620
|
+
* answers undefined where there is nothing to wait for, so the open is made at once.
|
|
621
|
+
*
|
|
622
|
+
* @throws (as a rejection) the abort reason once `signal` aborts, and a
|
|
623
|
+
* `MountayaConnectionError` naming the operation once the wait outlasts the bound.
|
|
624
|
+
*/
|
|
625
|
+
readonly waitForSession: (operationId: string, signal: AbortSignal) => Promise<void> | undefined;
|
|
626
|
+
/**
|
|
627
|
+
* timeoutMs is how long an open waits for the stream's response, in milliseconds: the client's
|
|
628
|
+
* own {@link ClientOptions.timeoutMs}, as construction resolved it, so the default where the
|
|
629
|
+
* client named none. An opener bounds the wait for the response with it, as one attempt of a
|
|
630
|
+
* request is bounded. It says nothing of the stream once it is open: a stream's silence has a
|
|
631
|
+
* bound of its own, which the opener holds.
|
|
632
|
+
*/
|
|
633
|
+
readonly timeoutMs: number;
|
|
634
|
+
/**
|
|
635
|
+
* url resolves one REST path against the origin this transport is pointed at.
|
|
636
|
+
*
|
|
637
|
+
* A resolver rather than the origin itself, because joining the two is not concatenation:
|
|
638
|
+
* a base with a trailing slash, a base carrying a path prefix, and the empty base a
|
|
639
|
+
* same-origin proxy uses all produce a different join, and every generated operation
|
|
640
|
+
* already goes through this one. A stream opener spelling it itself would be the one
|
|
641
|
+
* request that resolves differently from the rest.
|
|
642
|
+
*
|
|
643
|
+
* `operationId` names the stream's operation in a refusal.
|
|
644
|
+
*
|
|
645
|
+
* @throws `MountayaConfigurationError` for a path that resolves outside the base URL, or that
|
|
646
|
+
* holds an empty segment or a dot segment, as a request's path is refused.
|
|
647
|
+
*/
|
|
648
|
+
readonly url: (path: string, operationId?: string) => string;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** The `filename*` parameter's raw value, up to the next parameter. */
|
|
652
|
+
const extendedFilenamePattern = /(?:^|;)[ \t]*filename\*[ \t]*=[ \t]*([^;]*)/i;
|
|
653
|
+
|
|
654
|
+
/** The plain `filename` parameter's raw value: a quoted string with its escapes, or a token. */
|
|
655
|
+
const plainFilenamePattern = /(?:^|;)[ \t]*filename[ \t]*=[ \t]*("(?:[^"\\]|\\.)*"|[^;]*)/i;
|
|
656
|
+
|
|
657
|
+
/** A value of percent-escapes and plain characters only, with no `%` standing alone. */
|
|
658
|
+
const percentEncodedPattern = /^(?:%[0-9a-f]{2}|[^%])*$/i;
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* decodeExtendedValue decodes an RFC 8187 extended value, `charset'language'value`, or answers
|
|
662
|
+
* undefined where it cannot.
|
|
663
|
+
*
|
|
664
|
+
* The language tag is skipped: it says what language the name is in, and is no part of the name.
|
|
665
|
+
* UTF-8 is what RFC 8187 asks a sender to write; ISO-8859-1, which RFC 5987 allows as well, is
|
|
666
|
+
* decoded too, a byte to a character. Any other charset, or an escape that does not decode (a
|
|
667
|
+
* stray `%`, bytes that are not UTF-8), answers undefined, and the plain `filename` beside it
|
|
668
|
+
* stands in. A value with no charset at all, which neither grammar allows and some senders
|
|
669
|
+
* write, is read as UTF-8.
|
|
670
|
+
*/
|
|
671
|
+
const decodeExtendedValue = (raw: string): string | undefined => {
|
|
672
|
+
// Senders quote it now and then though the grammar does not.
|
|
673
|
+
const value = raw.trim().replace(/^"(.*)"$/, "$1");
|
|
674
|
+
const charsetEnd = value.indexOf("'");
|
|
675
|
+
const languageEnd = charsetEnd < 0 ? -1 : value.indexOf("'", charsetEnd + 1);
|
|
676
|
+
const charset = languageEnd < 0 ? "utf-8" : value.slice(0, charsetEnd).toLowerCase();
|
|
677
|
+
const encoded = languageEnd < 0 ? value : value.slice(languageEnd + 1);
|
|
678
|
+
|
|
679
|
+
if (!percentEncodedPattern.test(encoded)) {
|
|
680
|
+
return undefined;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
if (charset === "iso-8859-1") {
|
|
684
|
+
return encoded.replace(/%([0-9a-f]{2})/gi, (_escape, byte: string) =>
|
|
685
|
+
String.fromCharCode(Number.parseInt(byte, 16)),
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
if (charset !== "utf-8") {
|
|
690
|
+
return undefined;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
try {
|
|
694
|
+
return decodeURIComponent(encoded);
|
|
695
|
+
} catch {
|
|
696
|
+
// Escapes spelling bytes that are not UTF-8.
|
|
697
|
+
return undefined;
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* filenameFromContentDisposition reads the download filename out of the header, or answers
|
|
703
|
+
* undefined where it names none. It never throws: a name it cannot read costs the caller the
|
|
704
|
+
* name, never the download.
|
|
705
|
+
*
|
|
706
|
+
* RFC 8187's `filename*` form comes first because it is the one that survives a non-ASCII name:
|
|
707
|
+
* an itinerary called "Traversée des Écrins" is exported with its accents intact there and
|
|
708
|
+
* mangled in the plain `filename` fallback beside it. The plain form stands in when the extended
|
|
709
|
+
* one is absent or cannot be decoded; see {@link decodeExtendedValue}.
|
|
710
|
+
*
|
|
711
|
+
* Parsing this belongs in the SDK. Every application downloading an export needs the name, the
|
|
712
|
+
* header's grammar is not obvious, and the two forms have to be tried in this order, which is
|
|
713
|
+
* three chances to get it subtly wrong, once per integration.
|
|
714
|
+
*/
|
|
715
|
+
export const filenameFromContentDisposition = (header: string | null): string | undefined => {
|
|
716
|
+
if (header === null || header === "") {
|
|
717
|
+
return undefined;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
const extended = extendedFilenamePattern.exec(header)?.[1];
|
|
721
|
+
const decoded = extended === undefined ? undefined : decodeExtendedValue(extended);
|
|
722
|
+
if (decoded !== undefined && decoded !== "") {
|
|
723
|
+
return decoded;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const plain = plainFilenamePattern.exec(header)?.[1]?.trim() ?? "";
|
|
727
|
+
const quoted = /^"((?:[^"\\]|\\.)*)"$/.exec(plain)?.[1];
|
|
728
|
+
// A quoted string loses its quotes and its escapes; a token, or a quote left unclosed, is read
|
|
729
|
+
// as written, less any quote at either end.
|
|
730
|
+
const name = quoted === undefined ? plain.replace(/^"|"$/g, "") : quoted.replace(/\\(.)/g, "$1");
|
|
731
|
+
|
|
732
|
+
return name === "" ? undefined : name;
|
|
733
|
+
};
|
|
734
|
+
|
|
735
|
+
/** Matches a base URL that carries its own scheme and authority. */
|
|
736
|
+
const absoluteUrlPattern = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* SAME_ORIGIN_BASE stands in for the current origin while a relative base URL is joined.
|
|
740
|
+
*
|
|
741
|
+
* A relative base (`""` for same-origin, or `/api` behind a reverse proxy) is a real
|
|
742
|
+
* configuration: an application served from the same host as the API, or fronting it
|
|
743
|
+
* with its own gateway, has no absolute URL to name. `new URL` cannot join against one, so
|
|
744
|
+
* the join happens against this placeholder and the placeholder is then removed, which
|
|
745
|
+
* keeps path resolution and query encoding in URL's hands for both shapes.
|
|
746
|
+
*
|
|
747
|
+
* The `.invalid` TLD is reserved by RFC 2606 and can never resolve, so a slip that let one
|
|
748
|
+
* of these escape would fail immediately rather than reaching some real host.
|
|
749
|
+
*/
|
|
750
|
+
const SAME_ORIGIN_BASE = "http://same-origin.invalid";
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* pageOrigin answers the origin of the page's own address, or undefined where there is none to
|
|
754
|
+
* read a path against: no page at all, as in Node, or an address that names no `http` or `https`
|
|
755
|
+
* origin (`about:blank`, a `file:` document, a worker started from a `blob:`).
|
|
756
|
+
*
|
|
757
|
+
* Read off `location`, which a `<base>` element does not move, and never off the document's base
|
|
758
|
+
* URL, which one does. A relative URL handed to `fetch` is resolved against that base, so on a
|
|
759
|
+
* page whose `<base>` names another host a path in `baseUrls` would send the request there with
|
|
760
|
+
* the client's credential. In a worker `location` is the worker's own address, which is what
|
|
761
|
+
* its `fetch` resolves against.
|
|
762
|
+
*/
|
|
763
|
+
const pageOrigin = (): string | undefined => {
|
|
764
|
+
// Read against a widened type: `lib.dom` declares a `location` on every runtime, and Node
|
|
765
|
+
// holds none.
|
|
766
|
+
const runtime: { readonly location?: { readonly href?: unknown } | undefined } = globalThis;
|
|
767
|
+
const href = runtime.location?.href;
|
|
768
|
+
if (typeof href !== "string") {
|
|
769
|
+
return undefined;
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
let address: URL;
|
|
773
|
+
try {
|
|
774
|
+
address = new URL(href);
|
|
775
|
+
} catch {
|
|
776
|
+
// An address the parser does not read names no origin.
|
|
777
|
+
return undefined;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
return address.protocol === "http:" || address.protocol === "https:" ? address.origin : undefined;
|
|
781
|
+
};
|
|
782
|
+
|
|
783
|
+
/** Matches a path segment the URL parser reads as a dot segment, written or percent-encoded. */
|
|
784
|
+
const dotSegmentPattern = /^(?:\.|%2e){1,2}$/i;
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* Matches what the URL parser drops from either end of a reference before it reads it: spaces
|
|
788
|
+
* and the control characters below them.
|
|
789
|
+
*/
|
|
790
|
+
const edgeControlPattern = /^[\0-\x20]+|[\0-\x20]+$/g;
|
|
791
|
+
|
|
792
|
+
/**
|
|
793
|
+
* refusePath builds the refusal of a path the join would not send where it is written to.
|
|
794
|
+
* `context` names the operation where the caller has one.
|
|
795
|
+
*/
|
|
796
|
+
const refusePath = (
|
|
797
|
+
path: string,
|
|
798
|
+
why: string,
|
|
799
|
+
context: string | undefined,
|
|
800
|
+
): MountayaConfigurationError =>
|
|
801
|
+
new MountayaConfigurationError(
|
|
802
|
+
`${context === undefined ? "" : `${context}: `}the path ${JSON.stringify(path)} ${why}`,
|
|
803
|
+
);
|
|
804
|
+
|
|
805
|
+
/**
|
|
806
|
+
* joinUrl joins an operation's path and query onto a base URL and answers the join in the form
|
|
807
|
+
* the base is written in: an absolute URL for an absolute base, a path for a relative one. It
|
|
808
|
+
* reads nothing of the runtime, so the same base and path join to the same value on a page and
|
|
809
|
+
* off one, which is what lets {@link isJoinableBase} judge a base by it.
|
|
810
|
+
*
|
|
811
|
+
* The path is held to the base it is joined onto. The join resolves it as a URL reference, so a
|
|
812
|
+
* path that is an absolute URL, or one that opens with more than one slash, names another origin,
|
|
813
|
+
* and a dot segment or an empty one (which an identifier of `..`, `.` or `""` makes, the first two
|
|
814
|
+
* surviving percent-encoding) addresses another route than the one written. Each is refused: the
|
|
815
|
+
* request would carry the client's credential there. `context` names the operation in the
|
|
816
|
+
* refusal. The segments are read as the join reads them, without the whitespace it removes: a
|
|
817
|
+
* tab or a line break anywhere in the path, and spaces and control characters at its ends.
|
|
818
|
+
*
|
|
819
|
+
* @throws `MountayaConfigurationError` for a path that leaves the base or holds an empty or a dot
|
|
820
|
+
* segment; `TypeError` where the base does not parse, which {@link isJoinableBase} refuses at
|
|
821
|
+
* construction so that no request reaches it.
|
|
822
|
+
*/
|
|
823
|
+
const joinUrl = (
|
|
824
|
+
baseUrl: string,
|
|
825
|
+
path: string,
|
|
826
|
+
query: RequestArgs["query"],
|
|
827
|
+
context?: string,
|
|
828
|
+
): string => {
|
|
829
|
+
const absolute = absoluteUrlPattern.test(baseUrl);
|
|
830
|
+
const base = absolute
|
|
831
|
+
? baseUrl
|
|
832
|
+
: `${SAME_ORIGIN_BASE}${baseUrl.startsWith("/") ? "" : "/"}${baseUrl}`;
|
|
833
|
+
const root = new URL(base.endsWith("/") ? base : `${base}/`);
|
|
834
|
+
|
|
835
|
+
// Read as the parser reads it, in the parser's order. It first drops the spaces and control
|
|
836
|
+
// characters at either end and every tab, line feed and carriage return wherever they stand,
|
|
837
|
+
// so a segment written `.`, a tab, `.` is the dot segment `..` by the time it is resolved: the
|
|
838
|
+
// segments are read off the path with those gone, and the join is made from it. Then a
|
|
839
|
+
// backslash is a slash, and the path ends where a query or a fragment begins. One leading
|
|
840
|
+
// slash is the path's own, written either way, and a path of nothing is the base.
|
|
841
|
+
const relative = path
|
|
842
|
+
.replace(edgeControlPattern, "")
|
|
843
|
+
.replace(/[\t\n\r]/g, "")
|
|
844
|
+
.replace(/^[/\\]/, "");
|
|
845
|
+
const written = relative.replace(/[?#].*$/s, "").replaceAll("\\", "/");
|
|
846
|
+
if (
|
|
847
|
+
written !== "" &&
|
|
848
|
+
written.split("/").some((part) => part === "" || dotSegmentPattern.test(part))
|
|
849
|
+
) {
|
|
850
|
+
throw refusePath(
|
|
851
|
+
path,
|
|
852
|
+
'holds an empty segment or a dot segment ("." or ".."), which addresses another route than the one written. Pass each identifier as the platform issued it.',
|
|
853
|
+
context,
|
|
854
|
+
);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// Joined behind `./`, so the parser reads what is left as segments under the base and as
|
|
858
|
+
// nothing else: without it a first segment holding a colon reads as a scheme, and one that
|
|
859
|
+
// opens with a space loses it to the parser's second look at the ends. Every path the check
|
|
860
|
+
// above takes stays under the base, and the comparison below holds the join to that.
|
|
861
|
+
const url = new URL(`./${relative}`, root);
|
|
862
|
+
if (!url.href.startsWith(root.href)) {
|
|
863
|
+
throw refusePath(
|
|
864
|
+
path,
|
|
865
|
+
'resolves outside the base URL it is joined onto, so the request would leave the API with the client\'s credential. Pass a path of the API, starting with one "/".',
|
|
866
|
+
context,
|
|
867
|
+
);
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
if (query !== undefined) {
|
|
871
|
+
// `undefined` is the omission, and it is the ONLY omission. An empty string is sent as
|
|
872
|
+
// `?key=`, which several endpoints read as a filter matching nothing where the omitted
|
|
873
|
+
// param means unfiltered, so a caller forwarding a cleared form field straight through
|
|
874
|
+
// must fold `""` back to `undefined` itself rather than relying on this loop to.
|
|
875
|
+
// Narrowing it here instead would make an intentional empty value unsendable.
|
|
876
|
+
for (const [key, value] of Object.entries(query)) {
|
|
877
|
+
if (value !== undefined) {
|
|
878
|
+
url.searchParams.set(key, String(value));
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// What is left of a relative join opens with the slash the root ends on.
|
|
884
|
+
return absolute ? url.toString() : url.toString().slice(SAME_ORIGIN_BASE.length);
|
|
885
|
+
};
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* buildUrl answers the URL a request is sent to: what {@link joinUrl} answers for an absolute
|
|
889
|
+
* base, and for a relative one that path on the page's own origin, as {@link pageOrigin} reads
|
|
890
|
+
* it. A client is built with a relative base only where a page names one; the path alone is what
|
|
891
|
+
* is left where the page is gone since.
|
|
892
|
+
*
|
|
893
|
+
* The origin goes on here, after the join and never inside it: a base is judged at construction
|
|
894
|
+
* by the path it joins to, and a path that resolves to `//host` opens with `//` only while no
|
|
895
|
+
* origin stands before it.
|
|
896
|
+
*
|
|
897
|
+
* @throws `MountayaConfigurationError` for a path {@link joinUrl} refuses; `TypeError` where the
|
|
898
|
+
* base does not parse.
|
|
899
|
+
*/
|
|
900
|
+
const buildUrl = (
|
|
901
|
+
baseUrl: string,
|
|
902
|
+
path: string,
|
|
903
|
+
query: RequestArgs["query"],
|
|
904
|
+
context?: string,
|
|
905
|
+
): string => {
|
|
906
|
+
const joined = joinUrl(baseUrl, path, query, context);
|
|
907
|
+
|
|
908
|
+
return absoluteUrlPattern.test(baseUrl) ? joined : `${pageOrigin() ?? ""}${joined}`;
|
|
909
|
+
};
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* isJoinableBase reports whether a base URL is one {@link joinUrl} can join a path onto: `""`,
|
|
913
|
+
* a path, or an absolute URL. It answers the same for one base on a page and off one.
|
|
914
|
+
*
|
|
915
|
+
* The test runs the join itself, so a value this accepts is one the join reads the way its
|
|
916
|
+
* caller meant. An absolute URL must be `http:` or `https:`, because that is what `fetch` sends;
|
|
917
|
+
* `ftp:` parses as a URL and fails at the first call. A relative one must start with exactly one
|
|
918
|
+
* `/`, and must still start with exactly one once joined: the join resolves dot segments and
|
|
919
|
+
* reads a backslash as a slash, so `/.//host` and `/\host` come out as `//host`, which `fetch`
|
|
920
|
+
* reads as another origin. Neither may carry a query or a fragment, which the join would put in
|
|
921
|
+
* the middle of every URL it builds, nor whitespace at either end, which the join drops from an
|
|
922
|
+
* absolute URL and sends as `%20` on a path. A base the join cannot parse at all is refused here
|
|
923
|
+
* rather than at the first call.
|
|
924
|
+
*/
|
|
925
|
+
const isJoinableBase = (base: string): boolean => {
|
|
926
|
+
if (base === "") {
|
|
927
|
+
return true;
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
if (base.trim() !== base || base.includes("?") || base.includes("#")) {
|
|
931
|
+
return false;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
const absolute = absoluteUrlPattern.test(base);
|
|
935
|
+
if (!absolute && (!base.startsWith("/") || base.startsWith("//"))) {
|
|
936
|
+
return false;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
let joined: string;
|
|
940
|
+
try {
|
|
941
|
+
joined = joinUrl(base, "/", undefined);
|
|
942
|
+
} catch {
|
|
943
|
+
return false;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
if (!absolute) {
|
|
947
|
+
return !joined.startsWith("//");
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
const { host, protocol } = new URL(joined);
|
|
951
|
+
|
|
952
|
+
return (protocol === "http:" || protocol === "https:") && host !== "";
|
|
953
|
+
};
|
|
954
|
+
|
|
955
|
+
/**
|
|
956
|
+
* carriesUserinfo reports whether an absolute base URL names a username or a password before its
|
|
957
|
+
* host (`https://user:pass@host`). Such a URL parses, and `fetch` refuses every request built
|
|
958
|
+
* from it. A base the parser refuses carries none here: {@link isJoinableBase} is what refuses it.
|
|
959
|
+
*/
|
|
960
|
+
const carriesUserinfo = (base: string): boolean => {
|
|
961
|
+
if (!absoluteUrlPattern.test(base)) {
|
|
962
|
+
return false;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
try {
|
|
966
|
+
const { password, username } = new URL(base);
|
|
967
|
+
|
|
968
|
+
return username !== "" || password !== "";
|
|
969
|
+
} catch {
|
|
970
|
+
return false;
|
|
971
|
+
}
|
|
972
|
+
};
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* resolveBaseUrls lays a client's `baseUrls` over the defaults, entry by entry, refusing an
|
|
976
|
+
* entry {@link isJoinableBase} rejects, one that {@link carriesUserinfo}, and a path or `""` where
|
|
977
|
+
* no page names an origin to read it against ({@link pageOrigin}). A refused entry that holds an
|
|
978
|
+
* `@` is named and never quoted, whichever rule refuses it.
|
|
979
|
+
*
|
|
980
|
+
* Read entry by entry rather than spread, because a spread copies an entry written as
|
|
981
|
+
* `undefined` over the default it was meant to leave alone, and the first call then throws a
|
|
982
|
+
* `TypeError` while joining its URL.
|
|
983
|
+
*
|
|
984
|
+
* @throws `MountayaConfigurationError` for an entry that is not a joinable base, one that names a
|
|
985
|
+
* username or a password, a path or `""` where no page names an origin, or a `baseUrls` that is
|
|
986
|
+
* not an object.
|
|
987
|
+
*/
|
|
988
|
+
const resolveBaseUrls = (baseUrls: BaseUrlOverrides | undefined): Record<Surface, string> => {
|
|
989
|
+
if (baseUrls === undefined) {
|
|
990
|
+
return { ...defaultBaseUrls };
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
if (typeof baseUrls !== "object" || baseUrls === null) {
|
|
994
|
+
throw refuseOption(
|
|
995
|
+
"baseUrls",
|
|
996
|
+
baseUrls,
|
|
997
|
+
'pass an object naming a base URL per surface, such as { rest: "http://localhost:8080" }.',
|
|
998
|
+
);
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
const entry = (surface: Surface): string => {
|
|
1002
|
+
const value: unknown = baseUrls[surface];
|
|
1003
|
+
if (value === undefined) {
|
|
1004
|
+
return defaultBaseUrls[surface];
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Named without its value, which holds a password.
|
|
1008
|
+
if (typeof value === "string" && carriesUserinfo(value)) {
|
|
1009
|
+
throw new MountayaConfigurationError(
|
|
1010
|
+
`baseUrls.${surface} carries a username or a password before its host, which fetch refuses in a request's URL; pass the URL without them, and authenticate through the client's credential.`,
|
|
1011
|
+
);
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
if (typeof value === "string" && isJoinableBase(value)) {
|
|
1015
|
+
// A path names a place only against a page's own origin. Where no page names one, as in
|
|
1016
|
+
// Node, a native application or a page at a `file:` address, it names none, and handed to
|
|
1017
|
+
// fetch as written it would fail at the first call, far from the option that wrote it.
|
|
1018
|
+
if (!absoluteUrlPattern.test(value) && pageOrigin() === undefined) {
|
|
1019
|
+
throw new MountayaConfigurationError(
|
|
1020
|
+
`baseUrls.${surface} is ${value.includes("@") ? "a path" : JSON.stringify(value)}, a path read against the page's own origin, and no page here names an http or https origin to read it against; pass an http or https URL, such as "https://maps.example.com${value.includes("@") ? "" : value}".`,
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
return value;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// What stands before an "@" may be a password in a spelling the URL parser reads as no
|
|
1028
|
+
// userinfo, or refuses to read at all, so a refused entry that holds one is not quoted.
|
|
1029
|
+
if (typeof value === "string" && value.includes("@")) {
|
|
1030
|
+
throw new MountayaConfigurationError(
|
|
1031
|
+
`baseUrls.${surface} holds an "@" and is no base URL this client can join a path onto, so its value is not quoted: a username or a password may stand before the "@". Pass an http or https URL with no username, password, query or fragment, a path starting with one "/" that does not resolve to "//", or "" for the page's own origin, with no whitespace at either end.`,
|
|
1032
|
+
);
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// A bare host is the likeliest slip, and the one whose fix can be spelled out exactly.
|
|
1036
|
+
const scheme =
|
|
1037
|
+
typeof value === "string" && bareHostPattern.test(value)
|
|
1038
|
+
? ` For a host, add its scheme: "https://${value}".`
|
|
1039
|
+
: "";
|
|
1040
|
+
|
|
1041
|
+
throw refuseOption(
|
|
1042
|
+
`baseUrls.${surface}`,
|
|
1043
|
+
value,
|
|
1044
|
+
`pass an http or https URL with no query or fragment, a path starting with one "/" that does not resolve to "//", or "" for the page's own origin, with no whitespace at either end.${scheme}`,
|
|
1045
|
+
);
|
|
1046
|
+
};
|
|
1047
|
+
|
|
1048
|
+
return { data: entry("data"), rest: entry("rest"), tiles: entry("tiles") };
|
|
1049
|
+
};
|
|
1050
|
+
|
|
1051
|
+
/**
|
|
1052
|
+
* resolveTimeout reads a client's `timeoutMs`, refusing one that is not a whole number of
|
|
1053
|
+
* milliseconds a timer can honour.
|
|
1054
|
+
*
|
|
1055
|
+
* `0` is refused rather than read as "no timeout": it would abort every attempt, and a caller
|
|
1056
|
+
* wanting no bound on a long call has the call's own `signal` for that.
|
|
1057
|
+
*
|
|
1058
|
+
* @throws `MountayaConfigurationError` for a value outside 1 to 2,147,483,647 or a fraction.
|
|
1059
|
+
*/
|
|
1060
|
+
const resolveTimeout = (timeoutMs: number | undefined, context?: string): number => {
|
|
1061
|
+
if (timeoutMs === undefined) {
|
|
1062
|
+
return DEFAULT_TIMEOUT_MS;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
if (Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= MAX_TIMER_DELAY_MS) {
|
|
1066
|
+
return timeoutMs;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
throw refuseOption(
|
|
1070
|
+
"timeoutMs",
|
|
1071
|
+
timeoutMs,
|
|
1072
|
+
context === undefined
|
|
1073
|
+
? `pass a whole number of milliseconds from 1 to ${MAX_TIMER_DELAY_MS}, or leave it out for the default of ${DEFAULT_TIMEOUT_MS}.`
|
|
1074
|
+
: `pass a whole number of milliseconds from 1 to ${MAX_TIMER_DELAY_MS}, or leave it out for the client's own.`,
|
|
1075
|
+
context,
|
|
1076
|
+
);
|
|
1077
|
+
};
|
|
1078
|
+
|
|
1079
|
+
/**
|
|
1080
|
+
* NO_LANGUAGE is the `Accept-Language` a client given no `language` sends: the wildcard, which
|
|
1081
|
+
* asks for no language in particular. Sent rather than left out, so the language an answer is
|
|
1082
|
+
* written in is the client's configuration and never one the runtime's `fetch` writes for a
|
|
1083
|
+
* request that names none, as a browser's does from its own preferences.
|
|
1084
|
+
*/
|
|
1085
|
+
const NO_LANGUAGE = "*";
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* resolveLanguage reads a client's `language`, refusing one that is not a string, one no
|
|
1089
|
+
* request header carries (a character outside printable ASCII: a line break, a tab or another
|
|
1090
|
+
* control character, at either end or inside it, or a letter past ASCII) and one a request
|
|
1091
|
+
* carries as nothing: an empty string, or whitespace alone. {@link isHeaderValue} and
|
|
1092
|
+
* {@link isEmptyHeaderValue} are the rules.
|
|
1093
|
+
*
|
|
1094
|
+
* Sent as it is, the runtime's `fetch` refuses the first kind of request, or writes it as bytes
|
|
1095
|
+
* the API reads as other letters, and a refused call is reported after its retries as a
|
|
1096
|
+
* connection failure that tells the reader to check the network. The second kind is sent as an
|
|
1097
|
+
* `Accept-Language` with nothing in it, which states no language while the client reports one
|
|
1098
|
+
* from `requestLanguage`. A tag's own grammar is not checked: the API reads the header, and falls
|
|
1099
|
+
* back where it knows no such language.
|
|
1100
|
+
*
|
|
1101
|
+
* @throws `MountayaConfigurationError` for a language that is no string, one no request header
|
|
1102
|
+
* carries, or one that is empty or whitespace alone.
|
|
1103
|
+
*/
|
|
1104
|
+
const resolveLanguage = (language: string | undefined): string | undefined => {
|
|
1105
|
+
// Typed as a string, and still whatever a caller outside the compiler passed.
|
|
1106
|
+
const given: unknown = language;
|
|
1107
|
+
if (given === undefined) {
|
|
1108
|
+
return undefined;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
if (typeof given === "string" && isHeaderValue(given) && !isEmptyHeaderValue(given)) {
|
|
1112
|
+
return given;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
throw refuseOption(
|
|
1116
|
+
"language",
|
|
1117
|
+
given,
|
|
1118
|
+
`pass a BCP 47 tag such as "fr" or "pt-BR", in printable ASCII with no line break around it, or leave it out to send "${NO_LANGUAGE}", which asks for no language in particular.`,
|
|
1119
|
+
);
|
|
1120
|
+
};
|
|
1121
|
+
|
|
1122
|
+
/**
|
|
1123
|
+
* resolveFetch reads a client's `fetch`, refusing one that is not a function, and answers the
|
|
1124
|
+
* fetch the client calls: the caller's own, or the global one through {@link boundFetch}.
|
|
1125
|
+
*
|
|
1126
|
+
* A value that cannot be called surfaces otherwise from the first call, as a connection failure
|
|
1127
|
+
* retried and reported with a next step about the network.
|
|
1128
|
+
*
|
|
1129
|
+
* @throws `MountayaConfigurationError` for a `fetch` that is neither a function nor `undefined`.
|
|
1130
|
+
*/
|
|
1131
|
+
const resolveFetch = (fetchImpl: typeof fetch | undefined): typeof fetch => {
|
|
1132
|
+
const given: unknown = fetchImpl;
|
|
1133
|
+
if (given !== undefined && typeof given !== "function") {
|
|
1134
|
+
throw refuseOption(
|
|
1135
|
+
"fetch",
|
|
1136
|
+
given,
|
|
1137
|
+
"pass a function that takes what the global fetch takes, or leave it out to call the global one.",
|
|
1138
|
+
);
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
return boundFetch(fetchImpl);
|
|
1142
|
+
};
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* boundFetch resolves the fetch implementation a caller issues requests through, keeping the
|
|
1146
|
+
* global one callable through a local binding.
|
|
1147
|
+
*
|
|
1148
|
+
* `fetch` is bound to the global object, and invoking it through a local or parameter binding
|
|
1149
|
+
* (which is exactly how this transport holds it, and how a stream opener is handed one) throws
|
|
1150
|
+
* "Illegal invocation" in browsers, with a message naming nothing useful. Wrapping the default
|
|
1151
|
+
* in a call preserves the binding. An implementation the caller supplied is already a standalone
|
|
1152
|
+
* function and is returned untouched, which is what makes a test double, MSW, or request
|
|
1153
|
+
* instrumentation work without the wrapper getting in the way.
|
|
1154
|
+
*
|
|
1155
|
+
* It is exported because a stream is a fetch the caller owns (see {@link MountayaTransport.applyAuth})
|
|
1156
|
+
* and needs the same resolution this transport does. It lives in THIS module rather than beside
|
|
1157
|
+
* the stream opener so the package keeps naming the global in exactly one file: the property
|
|
1158
|
+
* `boundary.test.ts` pins, and the reason the resolution is written once rather than twice.
|
|
1159
|
+
*
|
|
1160
|
+
* @param fetchImpl - The caller's own fetch, or `undefined` for the global one.
|
|
1161
|
+
* @returns `fetchImpl` as given, or a function that calls the global fetch at each call.
|
|
1162
|
+
*/
|
|
1163
|
+
export const boundFetch = (fetchImpl?: typeof fetch): typeof fetch =>
|
|
1164
|
+
fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
|
|
1165
|
+
|
|
1166
|
+
/**
|
|
1167
|
+
* AttemptSignal is the signal one attempt is sent under: the caller's own, joined to the
|
|
1168
|
+
* attempt's timeout.
|
|
1169
|
+
*/
|
|
1170
|
+
interface AttemptSignal {
|
|
1171
|
+
/** The signal the attempt's fetch is handed. */
|
|
1172
|
+
readonly signal: AbortSignal;
|
|
1173
|
+
/** Whether the timeout, rather than the caller, ended the attempt. */
|
|
1174
|
+
readonly timedOut: () => boolean;
|
|
1175
|
+
/**
|
|
1176
|
+
* Ends the attempt's own hold on the request once it has an answer or has failed: the timeout
|
|
1177
|
+
* stops, and a caller's signal that was joined by hand is let go.
|
|
1178
|
+
*/
|
|
1179
|
+
readonly release: () => void;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/**
|
|
1183
|
+
* attemptSignal joins a caller's signal to one attempt's timeout, on any runtime this package
|
|
1184
|
+
* supports.
|
|
1185
|
+
*
|
|
1186
|
+
* The timeout is a plain timer rather than `AbortSignal.timeout`, for two reasons. The attempt
|
|
1187
|
+
* has to be able to stop it: it bounds the wait for a response, and a timer that stayed armed
|
|
1188
|
+
* through the body read would cut a large export off mid-download, which is a response that
|
|
1189
|
+
* arrived. And a transport relying on either static throws a `TypeError` at its first request
|
|
1190
|
+
* where the runtime lacks it: `AbortSignal.timeout` is missing on Safari before 16 and
|
|
1191
|
+
* `AbortSignal.any` on Safari before 17.4, and React Native before 0.87 lacks both.
|
|
1192
|
+
*
|
|
1193
|
+
* The caller's signal is joined with `AbortSignal.any` where the runtime has it, which keeps it
|
|
1194
|
+
* joined for as long as the response's body is read, with nothing to release. Elsewhere a
|
|
1195
|
+
* listener forwards it, and {@link AttemptSignal.release} removes the listener, so a long-lived
|
|
1196
|
+
* caller signal does not keep one closure per request. A body read on such a runtime is ended
|
|
1197
|
+
* by the read itself, which watches the caller's signal and cancels the body: see
|
|
1198
|
+
* {@link readBytes}.
|
|
1199
|
+
*/
|
|
1200
|
+
const attemptSignal = (timeoutMs: number, caller: AbortSignal | undefined): AttemptSignal => {
|
|
1201
|
+
const controller = new AbortController();
|
|
1202
|
+
let timedOut = false;
|
|
1203
|
+
|
|
1204
|
+
const timer = setTimeout(() => {
|
|
1205
|
+
timedOut = true;
|
|
1206
|
+
controller.abort(namedError("TimeoutError", `no response within ${timeoutMs} ms`));
|
|
1207
|
+
}, timeoutMs);
|
|
1208
|
+
|
|
1209
|
+
const stopTimer = () => {
|
|
1210
|
+
clearTimeout(timer);
|
|
1211
|
+
};
|
|
1212
|
+
|
|
1213
|
+
if (caller === undefined) {
|
|
1214
|
+
return { release: stopTimer, signal: controller.signal, timedOut: () => timedOut };
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
// Read off the constructor rather than trusted from the type: `lib.dom` declares `any` on every
|
|
1218
|
+
// runtime, and the runtimes this fallback is for do not have it.
|
|
1219
|
+
const any: unknown = Reflect.get(AbortSignal, "any");
|
|
1220
|
+
if (typeof any === "function") {
|
|
1221
|
+
return {
|
|
1222
|
+
release: stopTimer,
|
|
1223
|
+
signal: AbortSignal.any([caller, controller.signal]),
|
|
1224
|
+
timedOut: () => timedOut,
|
|
1225
|
+
};
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
const forward = () => {
|
|
1229
|
+
controller.abort(abortReasonOf(caller));
|
|
1230
|
+
};
|
|
1231
|
+
|
|
1232
|
+
if (caller.aborted) {
|
|
1233
|
+
forward();
|
|
1234
|
+
} else {
|
|
1235
|
+
caller.addEventListener("abort", forward, { once: true });
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
return {
|
|
1239
|
+
release: () => {
|
|
1240
|
+
stopTimer();
|
|
1241
|
+
caller.removeEventListener("abort", forward);
|
|
1242
|
+
},
|
|
1243
|
+
signal: controller.signal,
|
|
1244
|
+
timedOut: () => timedOut,
|
|
1245
|
+
};
|
|
1246
|
+
};
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* refuseEventStream refuses a call that asks for `text/event-stream`, before the first attempt.
|
|
1250
|
+
*
|
|
1251
|
+
* A feed has no end: the API writes a heartbeat into it for as long as it is open, so a request
|
|
1252
|
+
* that reads its body to the end never settles and holds every chunk it has read. The openers of
|
|
1253
|
+
* `@mountaya/client/events` read a feed frame by frame, resume it and report how it closed.
|
|
1254
|
+
*
|
|
1255
|
+
* @throws `MountayaConfigurationError` naming the operation and the opener that reads it.
|
|
1256
|
+
*/
|
|
1257
|
+
const refuseEventStream = (args: Pick<RequestArgs, "accept" | "operationId">): void => {
|
|
1258
|
+
const asksForStream = (args.accept ?? "")
|
|
1259
|
+
.split(",")
|
|
1260
|
+
.some((range) => range.split(";")[0]?.trim().toLowerCase() === "text/event-stream");
|
|
1261
|
+
if (!asksForStream) {
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
const opener =
|
|
1266
|
+
args.operationId === "getAgentRunEvents"
|
|
1267
|
+
? "createAgentTransport"
|
|
1268
|
+
: args.operationId === "getItineraryEvents" ||
|
|
1269
|
+
args.operationId === "getOrganizationEvents" ||
|
|
1270
|
+
args.operationId === "getZoneEvents"
|
|
1271
|
+
? "createCollabTransport"
|
|
1272
|
+
: "openSseStream";
|
|
1273
|
+
|
|
1274
|
+
throw new MountayaConfigurationError(
|
|
1275
|
+
`${args.operationId} answers an event stream, which has no end for a request to read to. ` +
|
|
1276
|
+
`Open it with ${opener} from @mountaya/client/events, which reads it frame by frame.`,
|
|
1277
|
+
);
|
|
1278
|
+
};
|
|
1279
|
+
|
|
1280
|
+
/**
|
|
1281
|
+
* discardBody cancels the body of a response nobody is going to read, releasing its connection.
|
|
1282
|
+
*
|
|
1283
|
+
* Not awaited: the cancellation is the runtime's to finish, and a request waiting on it would be
|
|
1284
|
+
* waiting on nothing it needs. A body that is already errored, or absent where the runtime does
|
|
1285
|
+
* not stream (React Native), has nothing to release, and its refusal is dropped for that reason.
|
|
1286
|
+
*
|
|
1287
|
+
* Read against a widened type, since `lib.dom` declares a web stream on every `Response`: a
|
|
1288
|
+
* `fetch` option built on another stream family answers a body with no `cancel` to call, a Node
|
|
1289
|
+
* `Readable` for one, or one whose `cancel` answers no promise. Such a body is left to the
|
|
1290
|
+
* `fetch` that answered it, and never fails the call the next attempt answers.
|
|
1291
|
+
*/
|
|
1292
|
+
const discardBody = (response: Response): void => {
|
|
1293
|
+
const body: { readonly cancel?: (() => unknown) | undefined } | null | undefined = response.body;
|
|
1294
|
+
if (typeof body?.cancel !== "function") {
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
try {
|
|
1299
|
+
// Resolved first, so a `cancel` that answers nothing, or a thenable, is chained on alike.
|
|
1300
|
+
Promise.resolve(body.cancel()).catch(() => undefined);
|
|
1301
|
+
} catch {
|
|
1302
|
+
// A `cancel` that throws where the web's rejects has released nothing this client can.
|
|
1303
|
+
}
|
|
1304
|
+
};
|
|
1305
|
+
|
|
1306
|
+
/**
|
|
1307
|
+
* resolveServerBudget reads an operation's own budget, refusing one that is not a whole number of
|
|
1308
|
+
* milliseconds a timer can honour once the margin is added to it.
|
|
1309
|
+
*
|
|
1310
|
+
* @throws `MountayaConfigurationError` naming the call.
|
|
1311
|
+
*/
|
|
1312
|
+
const resolveServerBudget = (budget: number | undefined, context: string): number | undefined => {
|
|
1313
|
+
if (budget === undefined) {
|
|
1314
|
+
return undefined;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
if (Number.isInteger(budget) && budget >= 1 && budget <= MAX_TIMER_DELAY_MS) {
|
|
1318
|
+
return budget;
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
throw refuseOption(
|
|
1322
|
+
"serverBudgetMs",
|
|
1323
|
+
budget,
|
|
1324
|
+
`pass the operation's x-timeout-ms, a whole number of milliseconds from 1 to ${MAX_TIMER_DELAY_MS}, or leave it out where it declares none.`,
|
|
1325
|
+
context,
|
|
1326
|
+
);
|
|
1327
|
+
};
|
|
1328
|
+
|
|
1329
|
+
/**
|
|
1330
|
+
* attemptBudget answers how long each attempt of a call waits for its response: the call's own
|
|
1331
|
+
* `timeoutMs` where it names one, and otherwise the larger of the client's and the operation's
|
|
1332
|
+
* `x-timeout-ms` plus {@link SERVER_BUDGET_MARGIN_MS}, held to what a timer honours.
|
|
1333
|
+
*
|
|
1334
|
+
* @throws `MountayaConfigurationError` for a call budget or an operation budget out of range.
|
|
1335
|
+
*/
|
|
1336
|
+
const attemptBudget = (
|
|
1337
|
+
clientMs: number,
|
|
1338
|
+
args: Pick<RequestArgs, "operationId" | "serverBudgetMs" | "timeoutMs">,
|
|
1339
|
+
): number => {
|
|
1340
|
+
if (args.timeoutMs !== undefined) {
|
|
1341
|
+
return resolveTimeout(args.timeoutMs, args.operationId);
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
const server = resolveServerBudget(args.serverBudgetMs, args.operationId);
|
|
1345
|
+
|
|
1346
|
+
return server === undefined
|
|
1347
|
+
? clientMs
|
|
1348
|
+
: Math.min(MAX_TIMER_DELAY_MS, Math.max(clientMs, server + SERVER_BUDGET_MARGIN_MS));
|
|
1349
|
+
};
|
|
1350
|
+
|
|
1351
|
+
/**
|
|
1352
|
+
* What a caller passes in place of a header a call names, by the member it passes it as.
|
|
1353
|
+
*/
|
|
1354
|
+
const callerHeaderRemedies = {
|
|
1355
|
+
accept:
|
|
1356
|
+
"pass the media type the call answers in, such as application/json, or leave it out for application/json.",
|
|
1357
|
+
idempotencyKey:
|
|
1358
|
+
"pass a key of printable ASCII, such as a UUID, or leave it out for the client to draw one.",
|
|
1359
|
+
ifMatch:
|
|
1360
|
+
"pass the etag the resource was read under, as the API wrote it, or leave it out for an unconditional write.",
|
|
1361
|
+
} as const;
|
|
1362
|
+
|
|
1363
|
+
/**
|
|
1364
|
+
* assertCallerHeader refuses a value the caller passes for a request header that no request can
|
|
1365
|
+
* carry: one that is empty or whitespace alone, or holds a character outside printable ASCII, a
|
|
1366
|
+
* line break, a tab or another control character at either end or inside it, or a letter past
|
|
1367
|
+
* ASCII. Anything else is the API's to judge.
|
|
1368
|
+
*
|
|
1369
|
+
* Sent as it is, the runtime's `fetch` refuses the request, which the call's loop would read as a
|
|
1370
|
+
* request that never arrived and repeat, or writes the value as bytes the API reads as other
|
|
1371
|
+
* letters, so a write's key would no longer be the one its caller holds.
|
|
1372
|
+
*
|
|
1373
|
+
* @throws `MountayaConfigurationError` naming the call and the member, never the value.
|
|
1374
|
+
*/
|
|
1375
|
+
const assertCallerHeader = (
|
|
1376
|
+
member: keyof typeof callerHeaderRemedies,
|
|
1377
|
+
value: unknown,
|
|
1378
|
+
context: string,
|
|
1379
|
+
): void => {
|
|
1380
|
+
if (value === undefined) {
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
if (typeof value === "string" && isHeaderValue(value) && !isEmptyHeaderValue(value)) {
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
throw new MountayaConfigurationError(
|
|
1389
|
+
`${context}: ${member} is ${typeof value === "string" ? "a string no request header carries" : describeType(value)}; ${callerHeaderRemedies[member]}`,
|
|
1390
|
+
);
|
|
1391
|
+
};
|
|
1392
|
+
|
|
1393
|
+
/**
|
|
1394
|
+
* surfaceFault hands a hook's own fault to the runtime as an uncaught error, on a microtask: a
|
|
1395
|
+
* hook that throws is a defect of the program that passed it, and must neither fail the call
|
|
1396
|
+
* nor disappear.
|
|
1397
|
+
*/
|
|
1398
|
+
const surfaceFault = (fault: unknown): void => {
|
|
1399
|
+
queueMicrotask(() => {
|
|
1400
|
+
throw fault;
|
|
1401
|
+
});
|
|
1402
|
+
};
|
|
1403
|
+
|
|
1404
|
+
/**
|
|
1405
|
+
* resolveHook reads a client's `onResponse`, refusing one that is not a function.
|
|
1406
|
+
*
|
|
1407
|
+
* @throws `MountayaConfigurationError` for a hook that is neither a function nor `undefined`.
|
|
1408
|
+
*/
|
|
1409
|
+
const resolveHook = (
|
|
1410
|
+
hook: ClientOptions["onResponse"],
|
|
1411
|
+
): ((report: ResponseReport) => void) | undefined => {
|
|
1412
|
+
const given: unknown = hook;
|
|
1413
|
+
if (given === undefined || typeof given === "function") {
|
|
1414
|
+
return hook;
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
throw refuseOption("onResponse", given, "pass a function told of each answer, or leave it out.");
|
|
1418
|
+
};
|
|
1419
|
+
|
|
1420
|
+
/**
|
|
1421
|
+
* firstCodeOf reads the classifying code of a refusal's body, the first entry's, or undefined
|
|
1422
|
+
* where the body is no envelope.
|
|
1423
|
+
*/
|
|
1424
|
+
const firstCodeOf = (text: string): string | undefined => {
|
|
1425
|
+
let body: unknown;
|
|
1426
|
+
try {
|
|
1427
|
+
body = JSON.parse(text);
|
|
1428
|
+
} catch {
|
|
1429
|
+
return undefined;
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
return entriesOf(body)[0]?.extensions?.code;
|
|
1433
|
+
};
|
|
1434
|
+
|
|
1435
|
+
/**
|
|
1436
|
+
* rereadable answers a refusal whose body is already read as a response that can be read again,
|
|
1437
|
+
* with the same status and headers, so the error it maps to is built from the same answer.
|
|
1438
|
+
*/
|
|
1439
|
+
const rereadable = (response: Response, text: string): Response =>
|
|
1440
|
+
new Response(text === "" ? null : text, {
|
|
1441
|
+
headers: response.headers,
|
|
1442
|
+
status: response.status,
|
|
1443
|
+
statusText: response.statusText,
|
|
1444
|
+
});
|
|
1445
|
+
|
|
1446
|
+
/** SentCall is what one call's retry loop answers: the last response, and the key it sent. */
|
|
1447
|
+
interface SentCall {
|
|
1448
|
+
/** The `Idempotency-Key` every attempt of the call sent, or undefined where it sent none. */
|
|
1449
|
+
readonly idempotencyKey: string | undefined;
|
|
1450
|
+
/** The response of the call's last attempt, as it arrived, its body unread. */
|
|
1451
|
+
readonly response: Response;
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
/**
|
|
1455
|
+
* carryingKey answers a failure raised by a call that fixed a key, before its first attempt or
|
|
1456
|
+
* between two attempts, as the same failure carrying that key: a configuration error or a
|
|
1457
|
+
* connection error the client raised once the key was fixed, a credential the first attempt
|
|
1458
|
+
* refused and a first token's wait its budget ended among them. The caller sends the same call
|
|
1459
|
+
* again with that key, and the write is made once. Anything else, a caller's abort reason among
|
|
1460
|
+
* it, is answered as it is.
|
|
1461
|
+
*/
|
|
1462
|
+
const carryingKey = (failure: unknown, idempotencyKey: string | undefined): unknown => {
|
|
1463
|
+
if (idempotencyKey === undefined) {
|
|
1464
|
+
return failure;
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
if (failure instanceof MountayaConfigurationError) {
|
|
1468
|
+
return new MountayaConfigurationError(failure.message, {
|
|
1469
|
+
cause: failure.cause,
|
|
1470
|
+
idempotencyKey,
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
if (failure instanceof MountayaConnectionError) {
|
|
1475
|
+
return new MountayaConnectionError(failure.message, failure.cause, idempotencyKey);
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
return failure;
|
|
1479
|
+
};
|
|
1480
|
+
|
|
1481
|
+
/**
|
|
1482
|
+
* MountayaTransport performs authenticated, retrying requests against the three surfaces.
|
|
1483
|
+
*
|
|
1484
|
+
* Prefixed, like every class this package publishes. `Transport` is one of the most reusable
|
|
1485
|
+
* nouns in the language (a consumer's own HTTP layer, a test double, a second vendor's SDK),
|
|
1486
|
+
* and an unprefixed published class is a name a consumer has to alias on import the first
|
|
1487
|
+
* time two of them meet. It is also the name a stack trace and a `instanceof` failure print,
|
|
1488
|
+
* where "Transport" says nothing about whose.
|
|
1489
|
+
*/
|
|
1490
|
+
export class MountayaTransport {
|
|
1491
|
+
private readonly credential: Credential;
|
|
1492
|
+
private readonly baseUrls: Record<Surface, string>;
|
|
1493
|
+
private readonly timeoutMs: number;
|
|
1494
|
+
private readonly retry: Required<RetryOptions>;
|
|
1495
|
+
private readonly language?: string | undefined;
|
|
1496
|
+
private readonly doFetch: typeof fetch;
|
|
1497
|
+
private readonly credentialsMode: RequestCredentials;
|
|
1498
|
+
private readonly onResponse: ((report: ResponseReport) => void) | undefined;
|
|
1499
|
+
|
|
1500
|
+
/**
|
|
1501
|
+
* Builds a transport over one credential and its options, checking both before anything is
|
|
1502
|
+
* sent.
|
|
1503
|
+
*
|
|
1504
|
+
* @throws `MountayaConfigurationError` for options that are not an object, a credential that
|
|
1505
|
+
* cannot work, or an option outside its range: see {@link ClientOptions}.
|
|
1506
|
+
*/
|
|
1507
|
+
constructor(options: ClientOptions) {
|
|
1508
|
+
// Typed as the options, and still whatever a caller outside the compiler passed: a
|
|
1509
|
+
// JavaScript `new Mountaya()`, or a configuration read that came back empty. Read as unknown
|
|
1510
|
+
// until it is shown to be an object, so the refusal names the options and the fix rather
|
|
1511
|
+
// than a `TypeError` naming `credential`. It names their type and never their value, which
|
|
1512
|
+
// may be a key.
|
|
1513
|
+
const given: unknown = options;
|
|
1514
|
+
if (typeof given !== "object" || given === null) {
|
|
1515
|
+
throw new MountayaConfigurationError(
|
|
1516
|
+
`options is ${describeType(given)}; pass { credential }, with any other option beside it, such as { credential: { publishableKey } }.`,
|
|
1517
|
+
);
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
assertCredential(options.credential);
|
|
1521
|
+
|
|
1522
|
+
// Kept as a view that reads the caller's own credential and prints each secret it holds by
|
|
1523
|
+
// its prefix alone, so a client logged whole prints none of them.
|
|
1524
|
+
this.credential = printableCredential(options.credential);
|
|
1525
|
+
// Resolved once: whether this credential asks the browser to attach its own cookies. The
|
|
1526
|
+
// cookie credential does, and a share credential that states `cookie`. Every other
|
|
1527
|
+
// credential sends `omit` and never `same-origin`: a base URL may be the page's own origin
|
|
1528
|
+
// ("" or "/api"), where `same-origin` attaches the page's cookies beside a key, and
|
|
1529
|
+
// wantsCookies says why a key never rides with one.
|
|
1530
|
+
this.credentialsMode = wantsCookies(options.credential) ? "include" : "omit";
|
|
1531
|
+
this.baseUrls = resolveBaseUrls(options.baseUrls);
|
|
1532
|
+
this.timeoutMs = resolveTimeout(options.timeoutMs);
|
|
1533
|
+
this.retry = resolveRetry(defaultRetry, options.retry);
|
|
1534
|
+
this.language = resolveLanguage(options.language);
|
|
1535
|
+
this.onResponse = resolveHook(options.onResponse);
|
|
1536
|
+
|
|
1537
|
+
// Resolved at CALL time, not here. Capturing globalThis.fetch in the constructor
|
|
1538
|
+
// freezes whatever was installed at that moment, so a client built during module
|
|
1539
|
+
// evaluation never sees a fetch patched afterwards, which is how MSW, request
|
|
1540
|
+
// instrumentation and test stubs all work. A long-lived client would silently keep
|
|
1541
|
+
// calling the original.
|
|
1542
|
+
//
|
|
1543
|
+
// It is invoked as `globalThis.fetch(...)` rather than through a bare reference: an
|
|
1544
|
+
// unbound fetch throws "Illegal invocation" in browsers, with a message naming
|
|
1545
|
+
// nothing useful.
|
|
1546
|
+
this.doFetch = resolveFetch(options.fetch);
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
/**
|
|
1550
|
+
* mapCredential projects the browser-safe half of this transport's credential, for a
|
|
1551
|
+
* renderer that has to authenticate requests it makes for itself.
|
|
1552
|
+
*
|
|
1553
|
+
* `@mountaya/elements` exists because MapLibre fetches tiles, sprites and glyphs on its own
|
|
1554
|
+
* schedule, and a credential belongs in a header: the Tile API reads one from the query too,
|
|
1555
|
+
* for a request that cannot set a header, and a key in a URL lands in every log, cache and
|
|
1556
|
+
* `Referer` that URL reaches. MapLibre's `transformRequest` is the one place to attach a
|
|
1557
|
+
* header to a request MapLibre makes. Without this projection a consumer would have to pass
|
|
1558
|
+
* their key twice (once to the client, once to the map), and the second copy would drift from
|
|
1559
|
+
* the first the moment a session token rotated.
|
|
1560
|
+
*
|
|
1561
|
+
* **A secret key is never projected**, and that is the whole point of it being a
|
|
1562
|
+
* projection rather than a getter for `this.credential`. A secret key mints session
|
|
1563
|
+
* tokens and must never reach a browser; a transport built with one yields an empty
|
|
1564
|
+
* credential here, so the mistake produces an unauthenticated map rather than a leak.
|
|
1565
|
+
*
|
|
1566
|
+
* **The cookie flag rides along, and it is not redundant with the browser's own
|
|
1567
|
+
* behaviour.** A browser attaches cookies unasked only to a SAME-ORIGIN request; the Tile
|
|
1568
|
+
* API is a separate host (`tiles.mountaya.com` by default), so the flag is what becomes
|
|
1569
|
+
* `credentials: "include"` on the far side. Dropping it costs a signed-in share-link visitor
|
|
1570
|
+
* what their own account reads: the token still authorizes the shared resource, but the
|
|
1571
|
+
* API cannot see who is asking, so a signed-in visitor is served the anonymous projection
|
|
1572
|
+
* with nothing failing.
|
|
1573
|
+
*
|
|
1574
|
+
* Which credentials ask for it is `wantsCookies`, the same predicate `credentialsMode`
|
|
1575
|
+
* uses above, so a map and a REST call made by one client cannot disagree about it. A
|
|
1576
|
+
* publishable key deliberately never carries one: the cookie's broader session would
|
|
1577
|
+
* outrank the scoped key.
|
|
1578
|
+
*
|
|
1579
|
+
* **Every read answers the session token current at that read.** A token held as a function
|
|
1580
|
+
* is called here each time, so a renderer that reads the projection per request sends the
|
|
1581
|
+
* token current at that request, as a REST call from the same client does. The projection never
|
|
1582
|
+
* waits: while a source has its first token on its way, a read answers the key alone, so a
|
|
1583
|
+
* tile a map asks for in that window is the anonymous one, and the tiles it asks for once the
|
|
1584
|
+
* token lands carry it.
|
|
1585
|
+
*
|
|
1586
|
+
* **It prints no secret.** A log of the projection, `JSON.stringify` of it and `String` of it show
|
|
1587
|
+
* a session token and a share token by their prefix alone (`sess_…`), as the credential the
|
|
1588
|
+
* client keeps prints them, and each member still reads whole.
|
|
1589
|
+
*
|
|
1590
|
+
* @throws `MountayaConfigurationError` where a session token held as a function or a source
|
|
1591
|
+
* answers neither a string nor `undefined`, or a string without the `sess_` prefix.
|
|
1592
|
+
*/
|
|
1593
|
+
get mapCredential(): {
|
|
1594
|
+
/** `true` where the renderer's requests ride the browser's cookies, as the client's do. */
|
|
1595
|
+
readonly cookie?: boolean | undefined;
|
|
1596
|
+
/** The publishable key, where the credential holds one. */
|
|
1597
|
+
readonly publishableKey?: string | undefined;
|
|
1598
|
+
/** The session token current at this read, where the credential holds one. */
|
|
1599
|
+
readonly sessionToken?: string | undefined;
|
|
1600
|
+
/** The share token, where the credential holds one. */
|
|
1601
|
+
readonly shareToken?: string | undefined;
|
|
1602
|
+
} {
|
|
1603
|
+
const credential = this.credential;
|
|
1604
|
+
const cookie = wantsCookies(credential) ? { cookie: true } : {};
|
|
1605
|
+
|
|
1606
|
+
// Read by value, as every other reader of the credential reads it, so a member written as
|
|
1607
|
+
// `undefined` is as absent here as it is from the request's headers.
|
|
1608
|
+
if (isShareCredential(credential)) {
|
|
1609
|
+
return printableProjection({ ...cookie, shareToken: credential.shareToken });
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
if (isPublishableCredential(credential)) {
|
|
1613
|
+
const sessionToken = sessionTokenOf(credential);
|
|
1614
|
+
|
|
1615
|
+
return printableProjection(
|
|
1616
|
+
sessionToken === undefined
|
|
1617
|
+
? { publishableKey: credential.publishableKey }
|
|
1618
|
+
: { publishableKey: credential.publishableKey, sessionToken },
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
// A secret or cookie credential. The secret cannot go to a browser at all, and
|
|
1623
|
+
// `wantsCookies` is false for it, so it projects nothing; the cookie credential has no
|
|
1624
|
+
// header to forward and projects the flag alone.
|
|
1625
|
+
return printableProjection(cookie);
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* applyAuth folds this transport's credential into a `RequestInit`, for a call this
|
|
1630
|
+
* client does not make itself.
|
|
1631
|
+
*
|
|
1632
|
+
* Server-sent events are the case it exists for. A stream is a `fetch` the caller owns (it
|
|
1633
|
+
* reads the body rather than awaiting it, reconnects on its own terms, and lives far longer
|
|
1634
|
+
* than a request), so it cannot go through {@link request}. What it must not own is the
|
|
1635
|
+
* credential contract: which header a share token rides in, that a session token
|
|
1636
|
+
* accompanies a publishable key rather than replacing it, that a cookie credential sends
|
|
1637
|
+
* no header and asks for the cookie instead. A host that rebuilds that ladder gets a
|
|
1638
|
+
* ladder that agrees with this one until one of them learns something.
|
|
1639
|
+
*
|
|
1640
|
+
* It stays narrower than a streaming method although two stream vocabularies ARE on the
|
|
1641
|
+
* contract. {@link streamSeam} is what a stream takes from this transport, and the
|
|
1642
|
+
* openers over it live on `@mountaya/client/events` rather than here, so a caller reading
|
|
1643
|
+
* REST and GraphQL never pays for a reader they do not open.
|
|
1644
|
+
*
|
|
1645
|
+
* Caller-supplied headers and init survive: this merges into what it is given, so an
|
|
1646
|
+
* `Accept: text/event-stream` or a `signal` set by the caller is not replaced. `credentials`
|
|
1647
|
+
* is the one member it always writes: `include` for a cookie credential and for a share
|
|
1648
|
+
* credential that states `cookie`, and `omit` for every other, so a key or a bare share token
|
|
1649
|
+
* never travels beside the page's cookies, whatever origin the API is reached at. The client's
|
|
1650
|
+
* `language` rides as `Accept-Language`, `*` where it was given none, as on every request it
|
|
1651
|
+
* makes, so a stream's refusals and the names its events carry come in the language the rest of
|
|
1652
|
+
* the client reads. So does `X-Mountaya-Client`, which names the SDK on every request. Both are
|
|
1653
|
+
* the client's to write: a value the caller's init states for either is replaced.
|
|
1654
|
+
*
|
|
1655
|
+
* The credential is read at each call, a session token held as a function or a source
|
|
1656
|
+
* included, so a stream reopened after the token rotated opens with the current one. It reads
|
|
1657
|
+
* the token held at the call and never waits for one on its way, where a request does.
|
|
1658
|
+
*
|
|
1659
|
+
* `declaration` carries what the call's operation declares, as {@link RequestArgs} does for a
|
|
1660
|
+
* request this client makes, and the same refusals read it: a secret key, which authenticates no
|
|
1661
|
+
* stream, a share token where it does not state `acceptsShareToken`, a credential with no session
|
|
1662
|
+
* token where it states `requiresSession`, and a session source reporting a token minted without
|
|
1663
|
+
* `user_id` where it states `actsAsMember`. Each is a configuration error thrown here, before
|
|
1664
|
+
* anything is opened. The server would answer a share-token write with a 401, or a 400 when
|
|
1665
|
+
* validation fails first, and neither names the rule.
|
|
1666
|
+
*/
|
|
1667
|
+
applyAuth(
|
|
1668
|
+
init: RequestInit = {},
|
|
1669
|
+
method = "GET",
|
|
1670
|
+
declaration: StreamDeclaration = {},
|
|
1671
|
+
): RequestInit {
|
|
1672
|
+
const projected = credentialHeaders(this.credential, { ...declaration, method });
|
|
1673
|
+
|
|
1674
|
+
const headers = new Headers(init.headers);
|
|
1675
|
+
for (const [name, value] of Object.entries(projected)) {
|
|
1676
|
+
headers.set(name, value);
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
headers.set("Accept-Language", this.language ?? NO_LANGUAGE);
|
|
1680
|
+
headers.set("X-Mountaya-Client", CLIENT_HEADER_VALUE);
|
|
1681
|
+
|
|
1682
|
+
return { ...init, credentials: this.credentialsMode, headers };
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
/**
|
|
1686
|
+
* streamSeam projects what one `text/event-stream` open needs from this transport: the
|
|
1687
|
+
* credential ladder, the fetch this client resolved, the bound one attempt waits for a
|
|
1688
|
+
* response, and the origin the REST surface is being reached at.
|
|
1689
|
+
*
|
|
1690
|
+
* It exists because a stream cannot go through {@link requestRaw} and the reasons are
|
|
1691
|
+
* structural rather than stylistic. `requestRaw` retries a non-ok status, which for a stream
|
|
1692
|
+
* means silently reopening a feed the caller believes it holds one handle to, and it accepts
|
|
1693
|
+
* no per-call headers, so there is nowhere to put the `Last-Event-ID` a resume rides on.
|
|
1694
|
+
* `requestBinary` is further still: it buffers the whole body, which for a feed with no end
|
|
1695
|
+
* never resolves.
|
|
1696
|
+
*
|
|
1697
|
+
* Handing the seam out rather than opening the stream here is what keeps the reader off
|
|
1698
|
+
* the root barrel's graph. The openers live on `@mountaya/client/events`, so a consumer
|
|
1699
|
+
* reading REST and GraphQL pays nothing for a frame parser they never use, which is the
|
|
1700
|
+
* split the entry point itself exists for.
|
|
1701
|
+
*
|
|
1702
|
+
* `doFetch` is projected rather than kept private because the alternative is worse: the
|
|
1703
|
+
* caller resolving its own, which is precisely the bypass `boundary.test.ts` guards
|
|
1704
|
+
* against. What comes back here is the fetch this transport already uses, so a test
|
|
1705
|
+
* double, an instrumented fetch or a polyfill installed on the client reaches the stream
|
|
1706
|
+
* too. Retry is deliberately NOT part of it: reconnection is a stream's own policy, and
|
|
1707
|
+
* a transport-level retry would reopen a feed behind the caller's back.
|
|
1708
|
+
*/
|
|
1709
|
+
get streamSeam(): StreamSeam {
|
|
1710
|
+
return {
|
|
1711
|
+
applyAuth: (init, method, declaration) => this.applyAuth(init, method, declaration),
|
|
1712
|
+
doFetch: this.doFetch,
|
|
1713
|
+
report: (response, operationId) => {
|
|
1714
|
+
this.report(response, { operationId, surface: "rest" }, 0);
|
|
1715
|
+
},
|
|
1716
|
+
sessionExpiresAt: () => sessionExpiryOf(this.credential),
|
|
1717
|
+
sessionUserId: () => sessionUserOf(this.credential),
|
|
1718
|
+
timeoutMs: this.timeoutMs,
|
|
1719
|
+
url: (path, operationId) => buildUrl(this.baseUrls.rest, path, undefined, operationId),
|
|
1720
|
+
waitForSession: (operationId, signal) => {
|
|
1721
|
+
const source = sessionSourceOf(this.credential);
|
|
1722
|
+
|
|
1723
|
+
return source === undefined
|
|
1724
|
+
? undefined
|
|
1725
|
+
: waitForSessionToken(source, { operationId, signal, timeoutMs: this.timeoutMs });
|
|
1726
|
+
},
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
/**
|
|
1731
|
+
* credentialScope identifies WHICH credential this transport holds and WHO it acts as, for a
|
|
1732
|
+
* cache key.
|
|
1733
|
+
*
|
|
1734
|
+
* One query cache usually serves a whole application, so a resource read under one
|
|
1735
|
+
* credential and the same resource read under another land on one entry unless something
|
|
1736
|
+
* separates them. That is wrong twice over, and the second way is a security property
|
|
1737
|
+
* rather than a correctness one: a share link uses its first read as the token's
|
|
1738
|
+
* AUTHORIZATION PROBE, so an entry seeded by a different credential would let a rotated
|
|
1739
|
+
* or foreign token resolve out of cache without ever reaching the API.
|
|
1740
|
+
*
|
|
1741
|
+
* The share token is part of the value for exactly that reason, by a digest of it: two
|
|
1742
|
+
* successive tokens for one resource are the case the probe exists to separate, and keying on
|
|
1743
|
+
* the kind alone would collapse them. A digest names a token without holding it, so a query key
|
|
1744
|
+
* that devtools show, a cache persisted to storage or a key written to a log carries no secret,
|
|
1745
|
+
* and the same token is named alike on a server and in the page it renders.
|
|
1746
|
+
*
|
|
1747
|
+
* Under a publishable key, the session is part of the value, since the session token names the
|
|
1748
|
+
* user a request acts as and what a member reads is theirs:
|
|
1749
|
+
*
|
|
1750
|
+
* - a token held by a source that reports the user it was minted for, as a
|
|
1751
|
+
* `SessionTokenEngine` does, is keyed by that user, `user:<id>`, or as one minted without
|
|
1752
|
+
* `user_id`, so a page whose person signs out or switches account serves nobody what the
|
|
1753
|
+
* person before them read, and a token the source rotates for the same person keeps the
|
|
1754
|
+
* entries;
|
|
1755
|
+
* - a token held as a string is keyed by a digest of the token, since the client is not told
|
|
1756
|
+
* whom it names and it never rotates, and a key never holds the token itself;
|
|
1757
|
+
* - a token held as a function, or by a source that reports no user, is keyed by its presence
|
|
1758
|
+
* alone, since its value rotates and folding it in would evict the whole cache every refresh
|
|
1759
|
+
* to distinguish a credential from itself. Present means a request made now carries a token
|
|
1760
|
+
* or waits for one, which a source reports from construction until its mint answers.
|
|
1761
|
+
*
|
|
1762
|
+
* An answer read under the key alone (a server prefetch, a failed mint, a sign-out) is the
|
|
1763
|
+
* anonymous projection, keyed apart from every session. A secret key is named by its kind
|
|
1764
|
+
* alone, and the browser's own session as `cookie`. {@link subscribeCredentialScope} tells a
|
|
1765
|
+
* listener each time the value moves.
|
|
1766
|
+
*
|
|
1767
|
+
* Before a source's first token lands, the value names the session's presence and not yet its
|
|
1768
|
+
* user, and {@link credentialScopePending} is true: a cache holds its reads until it turns
|
|
1769
|
+
* false, so each one is keyed once, under the user the token names.
|
|
1770
|
+
*
|
|
1771
|
+
* Every member is written so that no space stands inside it, a key and a user escaped and a
|
|
1772
|
+
* secret digested, so the space between two members cannot come from inside one. Opaque by
|
|
1773
|
+
* contract. Compare it, do not parse it.
|
|
1774
|
+
*
|
|
1775
|
+
* @throws what a session token held as a function throws, since the function is called here.
|
|
1776
|
+
*/
|
|
1777
|
+
get credentialScope(): string {
|
|
1778
|
+
const credential = this.credential;
|
|
1779
|
+
|
|
1780
|
+
if (isShareCredential(credential)) {
|
|
1781
|
+
return `share:${secretDigest(credential.shareToken)}`;
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
if (isSecretCredential(credential)) {
|
|
1785
|
+
// A secret key never reaches a browser, so a transport holding one is server-side and
|
|
1786
|
+
// there is one per process. Naming the key would put a secret in a cache key.
|
|
1787
|
+
return "secret";
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
if (!isPublishableCredential(credential)) {
|
|
1791
|
+
return "cookie";
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
const key = `key:${encodeURIComponent(credential.publishableKey)}`;
|
|
1795
|
+
if (!holdsSession(credential)) {
|
|
1796
|
+
return key;
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
const member = credential.sessionToken;
|
|
1800
|
+
if (typeof member === "string") {
|
|
1801
|
+
return `${key} session:${secretDigest(member)}`;
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
const user = sessionUserOf(credential);
|
|
1805
|
+
if (user === null) {
|
|
1806
|
+
return `${key} session nobody`;
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
return user === undefined
|
|
1810
|
+
? `${key} session`
|
|
1811
|
+
: `${key} session user:${encodeURIComponent(user)}`;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
/**
|
|
1815
|
+
* credentialScopePending reports whether {@link credentialScope} is still to be told who the
|
|
1816
|
+
* session acts as: the credential's {@link SessionTokenSource} holds no token and reports one
|
|
1817
|
+
* on its way, which it does from its construction until its first mint answers, and again
|
|
1818
|
+
* after a sign-out while the next person's mint is out.
|
|
1819
|
+
*
|
|
1820
|
+
* While it is true, the scope names a session and no user yet, and the token that lands names
|
|
1821
|
+
* the user a request made now acts as. That landing refines the scope of the same credential
|
|
1822
|
+
* rather than replacing it, so a query cache holds every read keyed by the scope until this
|
|
1823
|
+
* turns false, and keys each read once, under the scope the token settles. Holding them costs
|
|
1824
|
+
* no time: a request made now waits for that token anyway.
|
|
1825
|
+
*
|
|
1826
|
+
* False for every other credential and state: a token held as a string or a function, a source
|
|
1827
|
+
* that holds a token (a refresh in flight included), a source whose mint failed or that is
|
|
1828
|
+
* disabled, a key alone, a secret key, a share token and the browser's own session.
|
|
1829
|
+
* {@link subscribeCredentialScope} tells a listener each time it moves.
|
|
1830
|
+
*/
|
|
1831
|
+
get credentialScopePending(): boolean {
|
|
1832
|
+
const source = sessionSourceOf(this.credential);
|
|
1833
|
+
if (source === undefined) {
|
|
1834
|
+
return false;
|
|
1835
|
+
}
|
|
1836
|
+
|
|
1837
|
+
const snapshot = source.getSnapshot();
|
|
1838
|
+
|
|
1839
|
+
return snapshot.token === undefined && snapshot.isLoading;
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
/**
|
|
1843
|
+
* subscribeCredentialScope registers a listener told each time {@link credentialScope} or
|
|
1844
|
+
* {@link credentialScopePending} moves, and returns its release.
|
|
1845
|
+
*
|
|
1846
|
+
* Both move where the credential's {@link SessionTokenSource} does: a first mint that lands, a
|
|
1847
|
+
* sign-out that clears the token, a mint for another person. A refresh for the same person
|
|
1848
|
+
* moves neither. The listener reads them both, and {@link actsAsMember}, which moves with them.
|
|
1849
|
+
* A credential with no source never moves, and its release does nothing. Subscribing holds the
|
|
1850
|
+
* source as any subscriber does, so an engine nobody held yet starts its mint. A fault the
|
|
1851
|
+
* listener throws reaches the runtime as the program's own uncaught error, on a microtask, and
|
|
1852
|
+
* every later move is still told.
|
|
1853
|
+
*
|
|
1854
|
+
* @param listener - Called with no argument after each move of the scope or of its pending flag.
|
|
1855
|
+
* @returns The function that removes the listener.
|
|
1856
|
+
*/
|
|
1857
|
+
subscribeCredentialScope(listener: () => void): () => void {
|
|
1858
|
+
const source = sessionSourceOf(this.credential);
|
|
1859
|
+
if (source === undefined) {
|
|
1860
|
+
return () => undefined;
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
let lastScope = this.credentialScope;
|
|
1864
|
+
let lastPending = this.credentialScopePending;
|
|
1865
|
+
|
|
1866
|
+
return source.subscribe(() => {
|
|
1867
|
+
const scope = this.credentialScope;
|
|
1868
|
+
const pending = this.credentialScopePending;
|
|
1869
|
+
if (scope === lastScope && pending === lastPending) {
|
|
1870
|
+
return;
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
lastScope = scope;
|
|
1874
|
+
lastPending = pending;
|
|
1875
|
+
try {
|
|
1876
|
+
listener();
|
|
1877
|
+
} catch (fault) {
|
|
1878
|
+
surfaceFault(fault);
|
|
1879
|
+
}
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
/**
|
|
1884
|
+
* actsAsMember reports whether a call that acts as a member can be made under this transport's
|
|
1885
|
+
* credential now, as far as the client is told: `true` where its session source reports a token
|
|
1886
|
+
* minted for a user, `false` where it reports one minted without `user_id`, and where the
|
|
1887
|
+
* credential carries no session token at all (a bare publishable key, a secret key, a share token), and
|
|
1888
|
+
* undefined where the client is not told, as under a token held as a string or a function, a
|
|
1889
|
+
* source that reports no user, or the browser's own session.
|
|
1890
|
+
*
|
|
1891
|
+
* It is the question a surface that writes asks to decide whether to offer its writes: `false`
|
|
1892
|
+
* means every call that acts as a member is refused before it is sent. Read it again when
|
|
1893
|
+
* {@link subscribeCredentialScope} reports a move.
|
|
1894
|
+
*/
|
|
1895
|
+
get actsAsMember(): boolean | undefined {
|
|
1896
|
+
const credential = this.credential;
|
|
1897
|
+
|
|
1898
|
+
if (isSecretCredential(credential) || isShareCredential(credential)) {
|
|
1899
|
+
return false;
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
if (!isPublishableCredential(credential)) {
|
|
1903
|
+
return undefined;
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
if (credential.sessionToken === undefined) {
|
|
1907
|
+
return false;
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
const user = sessionUserOf(credential);
|
|
1911
|
+
|
|
1912
|
+
return user === undefined ? undefined : user !== null;
|
|
1913
|
+
}
|
|
1914
|
+
|
|
1915
|
+
/**
|
|
1916
|
+
* reachesSessionOperations reports whether this transport can make the operations that require
|
|
1917
|
+
* a session token: every Data API request, and every `management` and `studio-embedded`
|
|
1918
|
+
* operation of the Map Studio API, the writes and the collaboration and agent streams among them.
|
|
1919
|
+
*
|
|
1920
|
+
* It answers for the credential's shape and never for a token: true under a publishable key
|
|
1921
|
+
* given a `sessionToken` in any form (a string, a function or a source, whether or not it holds
|
|
1922
|
+
* a token at this moment), and under the browser's own session, which those refusals do not
|
|
1923
|
+
* read; false under a publishable key given no session token, a secret key and a share token,
|
|
1924
|
+
* each of which is refused such an operation before anything is sent. A function is not called
|
|
1925
|
+
* and a source is not read, so a session whose first mint is still out, or whose last mint
|
|
1926
|
+
* failed, reaches them here, and the request itself waits for its token or is refused for want
|
|
1927
|
+
* of one.
|
|
1928
|
+
*
|
|
1929
|
+
* It is the question a surface that writes asks at configuration time, where the answer false
|
|
1930
|
+
* means none of its writes can ever leave the process.
|
|
1931
|
+
*/
|
|
1932
|
+
get reachesSessionOperations(): boolean {
|
|
1933
|
+
const credential = this.credential;
|
|
1934
|
+
|
|
1935
|
+
if (isSecretCredential(credential) || isShareCredential(credential)) {
|
|
1936
|
+
return false;
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
// Read by value, as every reader of the credential reads it: a member written as `undefined`
|
|
1940
|
+
// is an omitted one.
|
|
1941
|
+
return isPublishableCredential(credential) ? credential.sessionToken !== undefined : true;
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
/**
|
|
1945
|
+
* tilesBaseUrl is the origin the Tile API is being reached at.
|
|
1946
|
+
*
|
|
1947
|
+
* A renderer needs it to decide which of MapLibre's many requests get the credential
|
|
1948
|
+
* attached: `transformRequest` is called for every request including third-party
|
|
1949
|
+
* basemaps and fonts, so the allowlist is the security boundary, not a nicety. Reading it
|
|
1950
|
+
* from here rather than defaulting to the public host is what keeps a map pointed at a
|
|
1951
|
+
* local stack or a proxy authenticating correctly.
|
|
1952
|
+
*/
|
|
1953
|
+
get tilesBaseUrl(): string {
|
|
1954
|
+
return this.baseUrls.tiles;
|
|
1955
|
+
}
|
|
1956
|
+
|
|
1957
|
+
/**
|
|
1958
|
+
* restBaseUrl is the address the Map Studio API is being reached at, as the client was given it
|
|
1959
|
+
* or its default.
|
|
1960
|
+
*
|
|
1961
|
+
* A read shared across clients is shared only between clients that send to the same API: a
|
|
1962
|
+
* client pointed at a staging stack and another at production may hold the same publishable
|
|
1963
|
+
* key, and an answer one of them read is no answer for the other.
|
|
1964
|
+
*/
|
|
1965
|
+
get restBaseUrl(): string {
|
|
1966
|
+
return this.baseUrls.rest;
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
/**
|
|
1970
|
+
* requestLanguage is the language this transport was given, which it sends as
|
|
1971
|
+
* `Accept-Language`, or undefined where it was given none and sends `*`, which asks for no
|
|
1972
|
+
* language in particular.
|
|
1973
|
+
*
|
|
1974
|
+
* The third member of the projection `mapCredential` and `tilesBaseUrl` belong to, and it
|
|
1975
|
+
* exists for the same reason they do: tile labels and legends are localized server-side,
|
|
1976
|
+
* so a renderer that does not state a language is labelled in whatever the browser
|
|
1977
|
+
* happens to prefer while every REST message beside it comes back in the client's. One
|
|
1978
|
+
* itinerary, two languages, and nothing failing.
|
|
1979
|
+
*
|
|
1980
|
+
* A getter rather than a second `language` option on the map, because the two could then
|
|
1981
|
+
* disagree, and the one a reader would blame is not the one that would be wrong.
|
|
1982
|
+
*/
|
|
1983
|
+
get requestLanguage(): string | undefined {
|
|
1984
|
+
return this.language;
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
/**
|
|
1988
|
+
* requestRaw performs one call, retrying per the policy, and returns the Response as it
|
|
1989
|
+
* arrived, including a non-ok one, with its body unread.
|
|
1990
|
+
*
|
|
1991
|
+
* It is the single retry loop every other method composes. The Data API needs the raw
|
|
1992
|
+
* response because a GraphQL failure arrives as an envelope under the failure's own HTTP
|
|
1993
|
+
* status, so classifying by status alone would discard the API's message.
|
|
1994
|
+
*
|
|
1995
|
+
* Each attempt waits for the response's headers for the call's own `timeoutMs`, or else the
|
|
1996
|
+
* larger of the client's and the operation's `serverBudgetMs` plus five seconds. A write that
|
|
1997
|
+
* declares `Idempotency-Key` sends one key on every attempt, the caller's or one drawn before
|
|
1998
|
+
* the first, and an operation that declares none sends none. Each attempt reads the credential
|
|
1999
|
+
* again, so a repeat carries the session token the credential holds when it is sent. A response
|
|
2000
|
+
* it repeats has its body cancelled. Every wait between attempts comes out of the call's
|
|
2001
|
+
* `retry.maxWaitMs`, and a wait that does not fit is not taken: the response that asked for it
|
|
2002
|
+
* comes back as it is. A 409 whose key is still in use is repeated within that budget alone,
|
|
2003
|
+
* after at least a second, and not counted against `retry.maxRetries`. Where the runtime has
|
|
2004
|
+
* `AbortSignal.any`, the caller's signal reaches the returned body as well; elsewhere a caller
|
|
2005
|
+
* reading the body itself cancels it through `response.body`. The client's `onResponse` is told
|
|
2006
|
+
* of every attempt an answer came back to.
|
|
2007
|
+
*
|
|
2008
|
+
* @throws `MountayaConfigurationError` before the first attempt, when the call asks for
|
|
2009
|
+
* `text/event-stream`, the credential cannot make it, its `retry`, `timeoutMs` or
|
|
2010
|
+
* `serverBudgetMs` is out of range, its `accept`, `idempotencyKey` or `ifMatch` is one no
|
|
2011
|
+
* request header carries, its body cannot be sent as JSON or holds a web address with no
|
|
2012
|
+
* scheme where the operation's contract types one, or its path leaves the base URL or holds an
|
|
2013
|
+
* empty or a dot segment, and once a wait for a session token ends with none on a call that
|
|
2014
|
+
* requires a session, before a repeat as before the first attempt;
|
|
2015
|
+
* `MountayaConnectionError` when no response was obtained at all, saying whether the attempt
|
|
2016
|
+
* timed out, or when a session token the credential's source reports on its way has not
|
|
2017
|
+
* landed within the call's `timeoutMs`, else the client's; {@link abortReasonOf} the caller's
|
|
2018
|
+
* signal once it aborts, whatever `fetch` rejected with. Every error raised once the call's
|
|
2019
|
+
* own arguments are accepted carries the `idempotencyKey` the call fixed, where it fixed one:
|
|
2020
|
+
* a credential its first attempt refuses and a first token's wait its budget ends included.
|
|
2021
|
+
*/
|
|
2022
|
+
async requestRaw(args: RequestArgs): Promise<Response> {
|
|
2023
|
+
return (await this.send(args)).response;
|
|
2024
|
+
}
|
|
2025
|
+
|
|
2026
|
+
/**
|
|
2027
|
+
* send is {@link requestRaw}, answering the `Idempotency-Key` the call sent beside the response,
|
|
2028
|
+
* where it sent one, so the error its answer is read into carries the key a caller sends the
|
|
2029
|
+
* call again with.
|
|
2030
|
+
*/
|
|
2031
|
+
private async send(args: RequestArgs): Promise<SentCall> {
|
|
2032
|
+
// Every local refusal runs HERE, once, before the loop, never inside it. A refusal is a
|
|
2033
|
+
// configuration error: nothing was sent, nothing can be learned by sending it, and the
|
|
2034
|
+
// configuration will not have changed by the next attempt. Raised inside the loop's `try`
|
|
2035
|
+
// it would read as a request that failed before a response arrived, which is a connection
|
|
2036
|
+
// error the loop RETRIES, so a share-token write would surface as a network fault, after a
|
|
2037
|
+
// backoff, naming nothing. The first attempt's headers are built here for that reason, and
|
|
2038
|
+
// each repeat's again before it is sent.
|
|
2039
|
+
assertCallerHeader("accept", args.accept, args.operationId);
|
|
2040
|
+
refuseEventStream(args);
|
|
2041
|
+
const timeoutMs = attemptBudget(this.timeoutMs, args);
|
|
2042
|
+
// A key rides an operation that declares the header and no other, so one a caller passes to
|
|
2043
|
+
// an operation that declares none is neither sent nor read.
|
|
2044
|
+
const takesKey = args.takesIdempotencyKey === true;
|
|
2045
|
+
if (takesKey) {
|
|
2046
|
+
assertCallerHeader("idempotencyKey", args.idempotencyKey, args.operationId);
|
|
2047
|
+
}
|
|
2048
|
+
assertCallerHeader("ifMatch", args.ifMatch, args.operationId);
|
|
2049
|
+
|
|
2050
|
+
const url = buildUrl(this.baseUrls[args.surface], args.path, args.query, args.operationId);
|
|
2051
|
+
const retry = resolveRetry(this.retry, args.retry, args.operationId);
|
|
2052
|
+
// The body is the call's and the same for every attempt, so it is serialized once, and one
|
|
2053
|
+
// that cannot be serialized is refused with the other local refusals, as is one holding a web
|
|
2054
|
+
// address with no scheme where the operation's contract types one, judged as the wire carries
|
|
2055
|
+
// it.
|
|
2056
|
+
const body = encodeBody(args.body, args.operationId);
|
|
2057
|
+
if (args.surface === "rest" && typeof body === "string") {
|
|
2058
|
+
assertWebAddresses(args.operationId, body);
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
// A request made while the credential's source holds no token and reports one on its way
|
|
2062
|
+
// waits for it, so it carries the session rather than going out under the key alone. Only
|
|
2063
|
+
// the operations a session token can ride on wait, and every refusal that does not read the
|
|
2064
|
+
// token runs ahead of the wait, so a mint that never answers hides none of them. A repeat
|
|
2065
|
+
// waits the same way, for a source that lost its token between two attempts.
|
|
2066
|
+
const source =
|
|
2067
|
+
args.takesNoCredential === true || args.requiresSecretKey === true
|
|
2068
|
+
? undefined
|
|
2069
|
+
: sessionSourceOf(this.credential);
|
|
2070
|
+
// Undefined where there is nothing to wait for, so an attempt with no wait is sent in the
|
|
2071
|
+
// same turn it is made.
|
|
2072
|
+
const waitForSession = (): Promise<void> | undefined =>
|
|
2073
|
+
source === undefined
|
|
2074
|
+
? undefined
|
|
2075
|
+
: // Bounded by the call's own budget, else the client's: the operation's own is the most
|
|
2076
|
+
// the API spends on it, and the mint is the application's endpoint, not the API.
|
|
2077
|
+
waitForSessionToken(source, {
|
|
2078
|
+
operationId: args.operationId,
|
|
2079
|
+
signal: args.signal,
|
|
2080
|
+
timeoutMs: args.timeoutMs === undefined ? this.timeoutMs : timeoutMs,
|
|
2081
|
+
});
|
|
2082
|
+
|
|
2083
|
+
// One key for the whole call, fixed once its own arguments are accepted and before its first
|
|
2084
|
+
// attempt reads the credential: a call whose arguments are refused fixes none, and every error
|
|
2085
|
+
// raised from here on carries the key, a credential the first attempt refuses and a first
|
|
2086
|
+
// token's wait its budget ends included, since its caller sends the same call again with it.
|
|
2087
|
+
// A runtime with no cryptographic source draws none, and the call then carries none.
|
|
2088
|
+
const idempotencyKey = takesKey ? (args.idempotencyKey ?? mintIdempotencyKey()) : undefined;
|
|
2089
|
+
const keyed = idempotencyKey !== undefined;
|
|
2090
|
+
let headers: Record<string, string>;
|
|
2091
|
+
try {
|
|
2092
|
+
const firstWait = waitForSession();
|
|
2093
|
+
if (firstWait !== undefined) {
|
|
2094
|
+
await firstWait;
|
|
2095
|
+
}
|
|
2096
|
+
headers = this.headers(args, idempotencyKey);
|
|
2097
|
+
} catch (error) {
|
|
2098
|
+
throw carryingKey(error, idempotencyKey);
|
|
2099
|
+
}
|
|
2100
|
+
// An operation that takes no credential is sent no cookie either, whatever the credential
|
|
2101
|
+
// asks for, since a cookie is how the cookie credential and a signed-in share visitor
|
|
2102
|
+
// authenticate.
|
|
2103
|
+
const credentials: RequestCredentials =
|
|
2104
|
+
args.takesNoCredential === true ? "omit" : this.credentialsMode;
|
|
2105
|
+
|
|
2106
|
+
// Every wait of the call comes out of one budget, so a run of refusals cannot hold a call
|
|
2107
|
+
// for longer than its caller agreed to.
|
|
2108
|
+
let waitedMs = 0;
|
|
2109
|
+
// The repeats `retry.maxRetries` counts: every one but the repeat of a key still in use,
|
|
2110
|
+
// which asks whether the first attempt has finished and is bounded by the budget alone.
|
|
2111
|
+
let retries = 0;
|
|
2112
|
+
|
|
2113
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
2114
|
+
if (attempt > 0) {
|
|
2115
|
+
// A repeat reads the credential again, so it carries the session token the credential
|
|
2116
|
+
// holds as it leaves rather than the one the first attempt carried, which may have
|
|
2117
|
+
// expired during the waits between them.
|
|
2118
|
+
try {
|
|
2119
|
+
const waiting = waitForSession();
|
|
2120
|
+
if (waiting !== undefined) {
|
|
2121
|
+
await waiting;
|
|
2122
|
+
}
|
|
2123
|
+
headers = this.headers(args, idempotencyKey);
|
|
2124
|
+
} catch (error) {
|
|
2125
|
+
throw carryingKey(error, idempotencyKey);
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
// A fresh timeout per attempt: the budget is per request, not for the whole
|
|
2130
|
+
// retry sequence, so a first attempt that times out does not leave its successors
|
|
2131
|
+
// with nothing left.
|
|
2132
|
+
const deadline = attemptSignal(timeoutMs, args.signal);
|
|
2133
|
+
|
|
2134
|
+
let response: Response;
|
|
2135
|
+
try {
|
|
2136
|
+
response = await this.doFetch(url, {
|
|
2137
|
+
body,
|
|
2138
|
+
credentials,
|
|
2139
|
+
headers,
|
|
2140
|
+
method: args.method,
|
|
2141
|
+
signal: deadline.signal,
|
|
2142
|
+
});
|
|
2143
|
+
} catch (cause) {
|
|
2144
|
+
deadline.release();
|
|
2145
|
+
|
|
2146
|
+
// A caller's own abort is theirs and is never retried or rewrapped. It is read off the
|
|
2147
|
+
// signal rather than off what fetch rejected with, because a fetch polyfill may reject an
|
|
2148
|
+
// abort with an error of its own (React Native's does), which would lose the reason.
|
|
2149
|
+
if (args.signal !== undefined && isAborted(args.signal)) {
|
|
2150
|
+
throw abortReasonOf(args.signal);
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
// A timeout says so, with the budget and the option that sets it: read as a generic
|
|
2154
|
+
// connection failure it sends a reader to the network when the budget may be too short.
|
|
2155
|
+
const failure = new MountayaConnectionError(
|
|
2156
|
+
deadline.timedOut()
|
|
2157
|
+
? `${args.operationId}: no response within ${timeoutMs} ms. Raise timeoutMs for a call that is slow to answer, or check the network path to the API.`
|
|
2158
|
+
: `${args.operationId}: the request failed before a response arrived. Check the network, and that baseUrls.${args.surface} names a host that answers.`,
|
|
2159
|
+
cause,
|
|
2160
|
+
idempotencyKey,
|
|
2161
|
+
);
|
|
2162
|
+
|
|
2163
|
+
if (
|
|
2164
|
+
!shouldRetry({
|
|
2165
|
+
idempotent: args.idempotent,
|
|
2166
|
+
keyed,
|
|
2167
|
+
maxRetries: retry.maxRetries,
|
|
2168
|
+
retries,
|
|
2169
|
+
})
|
|
2170
|
+
) {
|
|
2171
|
+
throw failure;
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
const delay = jitteredDelay({
|
|
2175
|
+
attempt,
|
|
2176
|
+
baseDelayMs: retry.baseDelayMs,
|
|
2177
|
+
maxDelayMs: retry.maxDelayMs,
|
|
2178
|
+
});
|
|
2179
|
+
if (waitedMs + delay > retry.maxWaitMs) {
|
|
2180
|
+
throw failure;
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
waitedMs += delay;
|
|
2184
|
+
retries += 1;
|
|
2185
|
+
await sleep(delay, args.signal);
|
|
2186
|
+
|
|
2187
|
+
continue;
|
|
2188
|
+
}
|
|
2189
|
+
|
|
2190
|
+
// The headers are in, so the timeout has done its work: from here a success's body is
|
|
2191
|
+
// read for as long as it takes, and only the caller's signal ends it. A refusal's is read
|
|
2192
|
+
// under bounds of its own, see `readFailure`.
|
|
2193
|
+
deadline.release();
|
|
2194
|
+
this.report(response, args, attempt);
|
|
2195
|
+
|
|
2196
|
+
if (response.ok) {
|
|
2197
|
+
return { idempotencyKey, response };
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
// A 409 is repeated only where its entry says the key is still in use, and a 429 only where
|
|
2201
|
+
// its entry does not say it refuses a ceiling, so a keyed 409 and every 429 are read here,
|
|
2202
|
+
// once, under the bounds a refusal's body is read under, and handed on rebuilt from what
|
|
2203
|
+
// was read where they are not repeated.
|
|
2204
|
+
let code: string | undefined;
|
|
2205
|
+
if ((response.status === 409 && keyed) || response.status === 429) {
|
|
2206
|
+
const text = await readFailureText(response, args.signal);
|
|
2207
|
+
code = firstCodeOf(text);
|
|
2208
|
+
response = rereadable(response, text);
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
const answered = { code, idempotent: args.idempotent, keyed, status: response.status };
|
|
2212
|
+
if (!shouldRetry({ ...answered, maxRetries: retry.maxRetries, retries })) {
|
|
2213
|
+
return { idempotencyKey, response };
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
// Retry-After is read here rather than left to the caller, because the decision to
|
|
2217
|
+
// wait belongs to the loop that is about to wait. Only the headers are read. A key in use
|
|
2218
|
+
// waits at least a second, so the budget, its one bound, is spent by every repeat of it.
|
|
2219
|
+
const inUse = isKeyInUse(answered);
|
|
2220
|
+
const scheduled = backoffDelay({
|
|
2221
|
+
attempt,
|
|
2222
|
+
baseDelayMs: retry.baseDelayMs,
|
|
2223
|
+
maxDelayMs: retry.maxDelayMs,
|
|
2224
|
+
retryAfterSeconds: parseRetryAfter(response.headers.get("Retry-After")),
|
|
2225
|
+
});
|
|
2226
|
+
const delay = inUse ? Math.max(KEY_IN_USE_MIN_WAIT_MS, scheduled) : scheduled;
|
|
2227
|
+
|
|
2228
|
+
// A wait the budget has no room for is not taken: the response goes back as it is, and
|
|
2229
|
+
// a 429's error carries the wait for the caller to schedule a retry from.
|
|
2230
|
+
if (waitedMs + delay > retry.maxWaitMs) {
|
|
2231
|
+
return { idempotencyKey, response };
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
// The response being retried is never read, and a body nobody reads holds its connection
|
|
2235
|
+
// until the runtime collects it, so under a burst of retries the pool runs dry. Cancelled
|
|
2236
|
+
// rather than drained: a drain would download a body only to throw it away.
|
|
2237
|
+
discardBody(response);
|
|
2238
|
+
|
|
2239
|
+
waitedMs += delay;
|
|
2240
|
+
if (!inUse) {
|
|
2241
|
+
retries += 1;
|
|
2242
|
+
}
|
|
2243
|
+
await sleep(delay, args.signal);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
|
|
2247
|
+
/**
|
|
2248
|
+
* request performs one call and returns the parsed body, with each instant `args.dates` names
|
|
2249
|
+
* decoded to a `Date` and every other string left a string.
|
|
2250
|
+
*
|
|
2251
|
+
* `T` is asserted rather than validated. The generated operation types come from the
|
|
2252
|
+
* same spec the API serves, so a runtime re-validation would spend time proving
|
|
2253
|
+
* something the contract already guarantees, and would reject a response the moment
|
|
2254
|
+
* the API added a field, which is a compatible change.
|
|
2255
|
+
*
|
|
2256
|
+
* @throws what {@link requestRaw} throws; the `MountayaApiError` class a non-2xx status maps
|
|
2257
|
+
* to; the base `MountayaApiError` for a success whose body is not JSON, carrying the answer's
|
|
2258
|
+
* status and request id with the parser's failure as its `cause`;
|
|
2259
|
+
* `MountayaConnectionError` for a body that broke off before it was complete; the caller's
|
|
2260
|
+
* own abort reason while a body, a success's or a failure's, is still arriving. Each error but
|
|
2261
|
+
* the abort reason carries the `idempotencyKey` the call sent, where it sent one.
|
|
2262
|
+
*/
|
|
2263
|
+
async request<T>(args: RequestArgs): Promise<T> {
|
|
2264
|
+
const { idempotencyKey, response } = await this.send(args);
|
|
2265
|
+
// The key the call sent, rather than the one the caller passed: an operation that declares
|
|
2266
|
+
// none sent none, and a write the caller passed none to sent the one the client drew.
|
|
2267
|
+
const call = { ...args, idempotencyKey };
|
|
2268
|
+
|
|
2269
|
+
if (!response.ok) {
|
|
2270
|
+
throw await readFailure(response, call);
|
|
2271
|
+
}
|
|
2272
|
+
|
|
2273
|
+
const text = await readText(response, call);
|
|
2274
|
+
|
|
2275
|
+
// The wire's boundary: the body is typed by the operation that asked for it, as the
|
|
2276
|
+
// contract generates it, and is not validated against that type here. A member that type
|
|
2277
|
+
// marks required and nullable, left out, reads null, as the type says it may be.
|
|
2278
|
+
const decoded = decodeSuccessDates(
|
|
2279
|
+
parseSuccessBody(text, response, call),
|
|
2280
|
+
args.dates,
|
|
2281
|
+
response,
|
|
2282
|
+
call,
|
|
2283
|
+
);
|
|
2284
|
+
|
|
2285
|
+
return withAbsentNulls(
|
|
2286
|
+
decoded,
|
|
2287
|
+
args.surface === "rest" ? responseNullMask(args.operationId) : undefined,
|
|
2288
|
+
) as T;
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
/**
|
|
2292
|
+
* requestBinary performs one call and returns the bytes with the two headers that
|
|
2293
|
+
* describe them, for tile and export responses that are protobuf, PNG, WebP or an
|
|
2294
|
+
* octet stream rather than JSON.
|
|
2295
|
+
*
|
|
2296
|
+
* It goes through the same retry loop as every other call, so tile fetches, the surface most
|
|
2297
|
+
* likely to hit a quota at 600 requests per minute across a whole organization, back off like
|
|
2298
|
+
* the rest.
|
|
2299
|
+
*
|
|
2300
|
+
* @throws as {@link request} does, except for a success whose body is not JSON: the bytes are
|
|
2301
|
+
* handed back as they arrived, with the `Content-Type` that says what they are.
|
|
2302
|
+
*/
|
|
2303
|
+
async requestBinary(args: RequestArgs): Promise<BinaryBody> {
|
|
2304
|
+
const { idempotencyKey, response } = await this.send(args);
|
|
2305
|
+
const call = { ...args, idempotencyKey };
|
|
2306
|
+
|
|
2307
|
+
if (!response.ok) {
|
|
2308
|
+
throw await readFailure(response, call);
|
|
2309
|
+
}
|
|
2310
|
+
|
|
2311
|
+
return {
|
|
2312
|
+
bytes: await readBytes(response, call),
|
|
2313
|
+
contentType: response.headers.get("Content-Type") ?? undefined,
|
|
2314
|
+
filename: filenameFromContentDisposition(response.headers.get("Content-Disposition")),
|
|
2315
|
+
};
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
/**
|
|
2319
|
+
* headers builds the headers of one attempt, and is where every local credential refusal is
|
|
2320
|
+
* raised: {@link credentialHeaders} reads what the operation declares off `args`, which
|
|
2321
|
+
* carries the same members.
|
|
2322
|
+
*
|
|
2323
|
+
* Built for the first attempt before the retry loop, where a refusal leaves nothing sent, and
|
|
2324
|
+
* again for each repeat, so a session token held as a function or a source is read for every
|
|
2325
|
+
* attempt: a repeat carries the token the credential holds as it leaves, never one that expired
|
|
2326
|
+
* during the waits before it. The call's key and its tag ride every attempt alike, and so does
|
|
2327
|
+
* `X-Mountaya-Client`, whatever the credential and whatever the operation declares.
|
|
2328
|
+
*/
|
|
2329
|
+
private headers(args: RequestArgs, idempotencyKey: string | undefined): Record<string, string> {
|
|
2330
|
+
const operation: OperationCredentials = args;
|
|
2331
|
+
const headers: Record<string, string> = {
|
|
2332
|
+
Accept: args.accept ?? "application/json",
|
|
2333
|
+
...credentialHeaders(this.credential, operation),
|
|
2334
|
+
};
|
|
2335
|
+
|
|
2336
|
+
// A multipart body sets no Content-Type here on purpose. fetch derives it from the
|
|
2337
|
+
// FormData, including the generated boundary, and any value written here replaces
|
|
2338
|
+
// that one, leaving the server a multipart document it cannot split.
|
|
2339
|
+
if (args.body !== undefined && !isFormData(args.body)) {
|
|
2340
|
+
headers["Content-Type"] = "application/json";
|
|
2341
|
+
}
|
|
2342
|
+
|
|
2343
|
+
// The client's language rides every request whatever the credential, an operation that
|
|
2344
|
+
// takes no credential included, and so does the SDK that made it: both are the client's and
|
|
2345
|
+
// no part of the credential.
|
|
2346
|
+
headers["Accept-Language"] = this.language ?? NO_LANGUAGE;
|
|
2347
|
+
headers["X-Mountaya-Client"] = CLIENT_HEADER_VALUE;
|
|
2348
|
+
|
|
2349
|
+
if (idempotencyKey !== undefined) {
|
|
2350
|
+
headers["Idempotency-Key"] = idempotencyKey;
|
|
2351
|
+
}
|
|
2352
|
+
|
|
2353
|
+
if (args.ifMatch !== undefined) {
|
|
2354
|
+
headers["If-Match"] = args.ifMatch;
|
|
2355
|
+
}
|
|
2356
|
+
|
|
2357
|
+
return headers;
|
|
2358
|
+
}
|
|
2359
|
+
|
|
2360
|
+
/**
|
|
2361
|
+
* report tells the client's `onResponse` of one answer. A fault the hook throws leaves the call
|
|
2362
|
+
* as it was and reaches the runtime on a microtask.
|
|
2363
|
+
*/
|
|
2364
|
+
private report(
|
|
2365
|
+
response: Response,
|
|
2366
|
+
call: Pick<RequestArgs, "operationId" | "surface">,
|
|
2367
|
+
attempt: number,
|
|
2368
|
+
): void {
|
|
2369
|
+
if (this.onResponse === undefined) {
|
|
2370
|
+
return;
|
|
2371
|
+
}
|
|
2372
|
+
|
|
2373
|
+
try {
|
|
2374
|
+
this.onResponse({
|
|
2375
|
+
attempt,
|
|
2376
|
+
operationId: call.operationId,
|
|
2377
|
+
replayed: replayedOf(response.headers),
|
|
2378
|
+
status: response.status,
|
|
2379
|
+
surface: call.surface,
|
|
2380
|
+
...answerDetailsOf(response.headers),
|
|
2381
|
+
});
|
|
2382
|
+
} catch (fault) {
|
|
2383
|
+
surfaceFault(fault);
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
}
|