@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.
Files changed (96) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/LICENCE.fr.txt +280 -0
  3. package/LICENSE.txt +262 -0
  4. package/README.md +1260 -2
  5. package/dist/admin/index.cjs +3521 -0
  6. package/dist/admin/index.cjs.map +1 -0
  7. package/dist/admin/index.d.cts +1070 -0
  8. package/dist/admin/index.d.ts +1070 -0
  9. package/dist/admin/index.js +301 -0
  10. package/dist/admin/index.js.map +1 -0
  11. package/dist/browser.cjs +8073 -0
  12. package/dist/browser.cjs.map +1 -0
  13. package/dist/browser.d.cts +106 -0
  14. package/dist/browser.d.ts +106 -0
  15. package/dist/browser.js +53 -0
  16. package/dist/browser.js.map +1 -0
  17. package/dist/chunk-BM526BHG.js +342 -0
  18. package/dist/chunk-BM526BHG.js.map +1 -0
  19. package/dist/chunk-D2YEVTG7.js +327 -0
  20. package/dist/chunk-D2YEVTG7.js.map +1 -0
  21. package/dist/chunk-OHKVUREN.js +3500 -0
  22. package/dist/chunk-OHKVUREN.js.map +1 -0
  23. package/dist/chunk-TDTK2L5H.js +3842 -0
  24. package/dist/chunk-TDTK2L5H.js.map +1 -0
  25. package/dist/coreOperations.gen-BMYPoBbz.d.ts +1760 -0
  26. package/dist/coreOperations.gen-BxX5xRxw.d.cts +1760 -0
  27. package/dist/errors-B-GqAtQv.d.cts +75960 -0
  28. package/dist/errors-B-GqAtQv.d.ts +75960 -0
  29. package/dist/events/index.cjs +1972 -0
  30. package/dist/events/index.cjs.map +1 -0
  31. package/dist/events/index.d.cts +781 -0
  32. package/dist/events/index.d.ts +781 -0
  33. package/dist/events/index.js +826 -0
  34. package/dist/events/index.js.map +1 -0
  35. package/dist/index.cjs +8072 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.d.cts +76 -0
  38. package/dist/index.d.ts +76 -0
  39. package/dist/index.js +52 -0
  40. package/dist/index.js.map +1 -0
  41. package/dist/operations.gen-CvTyzKNF.d.cts +3993 -0
  42. package/dist/operations.gen-DUD406TV.d.ts +3993 -0
  43. package/package.json +127 -4
  44. package/src/admin/index.ts +47 -0
  45. package/src/admin/rules/mountayaAdmin.ts +102 -0
  46. package/src/browser.ts +232 -0
  47. package/src/core/engines/sessionToken.ts +870 -0
  48. package/src/core/rules/auth.ts +1017 -0
  49. package/src/core/rules/clientHeader.ts +28 -0
  50. package/src/core/rules/dates.ts +200 -0
  51. package/src/core/rules/decode.ts +154 -0
  52. package/src/core/rules/envelope.ts +41 -0
  53. package/src/core/rules/errors.ts +1486 -0
  54. package/src/core/rules/graphql.ts +576 -0
  55. package/src/core/rules/headerValue.ts +42 -0
  56. package/src/core/rules/idempotencyKey.ts +64 -0
  57. package/src/core/rules/nullMask.ts +127 -0
  58. package/src/core/rules/nullMasks.gen.ts +416 -0
  59. package/src/core/rules/paginate.ts +316 -0
  60. package/src/core/rules/rateLimit.ts +507 -0
  61. package/src/core/rules/redaction.ts +219 -0
  62. package/src/core/rules/resourceRef.ts +110 -0
  63. package/src/core/rules/responseBody.ts +492 -0
  64. package/src/core/rules/retry.ts +386 -0
  65. package/src/core/rules/selection.ts +416 -0
  66. package/src/core/rules/sessionAnswer.ts +90 -0
  67. package/src/core/rules/sessionSchedule.ts +131 -0
  68. package/src/core/rules/sessionWait.ts +112 -0
  69. package/src/core/rules/transport.ts +2386 -0
  70. package/src/core/rules/version.gen.ts +16 -0
  71. package/src/core/rules/webAddress.ts +165 -0
  72. package/src/core/rules/webAddresses.gen.ts +30 -0
  73. package/src/data/operations.gen.ts +603 -0
  74. package/src/data/schema.gen.ts +8078 -0
  75. package/src/data/selection.gen.ts +472 -0
  76. package/src/events/index.ts +67 -0
  77. package/src/events/rules/agent.ts +439 -0
  78. package/src/events/rules/collab.ts +554 -0
  79. package/src/events/rules/collabNulls.gen.ts +17 -0
  80. package/src/events/rules/eventStream.ts +94 -0
  81. package/src/events/rules/openSseStream.ts +594 -0
  82. package/src/events/rules/sse.ts +349 -0
  83. package/src/index.ts +231 -0
  84. package/src/rest/adminOperations.gen.ts +70 -0
  85. package/src/rest/adminResources.gen.ts +136 -0
  86. package/src/rest/coreOperations.gen.ts +74 -0
  87. package/src/rest/coreResources.gen.ts +244 -0
  88. package/src/rest/dates.gen.ts +217 -0
  89. package/src/rest/operations.gen.ts +4341 -0
  90. package/src/rest/resources.gen.ts +369 -0
  91. package/src/rest/schema.gen.ts +56840 -0
  92. package/src/tiles/operations.gen.ts +206 -0
  93. package/src/tiles/schema.gen.ts +8408 -0
  94. package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
  95. package/src/webhooks/rules/webhookEvent.ts +38 -0
  96. package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
@@ -0,0 +1,1017 @@
1
+ /**
2
+ * The Mountaya credential model.
3
+ *
4
+ * There are four credentials, not three, and they compose differently from one another
5
+ * in ways that are easy to get wrong:
6
+ *
7
+ * | Credential | Header | Composes with |
8
+ * |--------------|-------------------|------------------------|
9
+ * | `pk_` key | `X-API-Key` | optionally a session |
10
+ * | `sess_` | `X-Session-Token` | ACCOMPANIES the key |
11
+ * | `sk_` secret | `X-API-Key` | mints sessions only |
12
+ * | `share_` | `X-Share-Token` | REPLACES the key |
13
+ *
14
+ * A session token does not replace the publishable key: both headers ride together, and
15
+ * sending the session alone is a 401. A share token is the opposite: it replaces the key
16
+ * entirely, reaches exactly the one resource it was minted for, and is refused on every
17
+ * operation whose `security` does not name a share token on its own, every write among them.
18
+ * (A share credential that also asked for cookies reads those operations through the visitor's
19
+ * own session instead; see {@link ShareCredential.cookie}.)
20
+ *
21
+ * The session token names the user an operation acts as. `postSession` mints it for the `user_id`
22
+ * its caller names, or for no user, and every request made with it acts as that user: no header
23
+ * names one. An operation that acts as a member (every `studio-embedded` operation, every
24
+ * `management` write, every read under `/v1/me`) declares `x-acting-user: required`, and the API
25
+ * answers it under a token minted without `user_id` with a 401. A token minted without `user_id`
26
+ * therefore reads and never writes. The token is opaque, so the client knows whom it names only
27
+ * where a {@link SessionTokenSource} reports it, as a `SessionTokenEngine` does from its mint's
28
+ * `user_id`, and refuses such an operation locally there.
29
+ *
30
+ * A token is minted for a surface as well, `postSession`'s `surface`: `api` by default, or
31
+ * `studio-embedded`, the only surface a `studio-embedded` operation accepts, which the API
32
+ * answers under a token minted for another with a 401. The client sends whatever token it is
33
+ * given and lets the API decide: a studio host is the one reader of the surface a token names.
34
+ *
35
+ * A session token lives minutes, so the credential may hold it as a function or as a
36
+ * {@link SessionTokenSource} rather than a string: {@link sessionTokenOf} reads it on every read,
37
+ * and one client follows the token for the page's life. A source also says when a mint is out,
38
+ * and a request made while it holds no token waits for that mint (see `sessionWait.ts`).
39
+ *
40
+ * What an operation takes is read off what it DECLARES, never off its method: whether a secret
41
+ * key authenticates it, whether it takes any credential at all, whether it accepts a share token,
42
+ * whether every way to call it carries a session token, and whether it acts as the user that token
43
+ * names. A generated operation states each from the contract, and a credential that cannot meet them is
44
+ * refused here, before anything is sent: the server would answer the same request with a 401 or
45
+ * a 400 that names none of the rules.
46
+ */
47
+
48
+ import type { SessionTokenSnapshot } from "../engines/sessionToken.js";
49
+ import { describeType, MountayaConfigurationError } from "./errors.js";
50
+ import { isEmptyHeaderValue, isHeaderValue } from "./headerValue.js";
51
+
52
+ /**
53
+ * SessionTokenSource is a session token that changes over time and says when one is on its way:
54
+ * what a `SessionTokenEngine` is, and what `credential.sessionToken` takes beside a string and a
55
+ * function.
56
+ *
57
+ * A request made while the source holds no token and reports `isLoading` subscribes to it for the
58
+ * span of its wait, so an engine nobody holds yet starts its mint, and the request waits for the
59
+ * token, bounded by its `signal` and its `timeoutMs`. Once the wait ends with no token, the
60
+ * request goes out under the key alone, and an operation that requires a session is refused
61
+ * with the mint's `error` as its cause.
62
+ *
63
+ * `isLoading` reports a token on its way, not only a mint out: a source that mints on its next
64
+ * subscriber, as an engine nobody holds yet does, reports it, and a source that reports neither a
65
+ * token nor one on its way is never subscribed by a request. The client's `credentialScope` reads
66
+ * the snapshot by the same rule, so the scope a read is keyed under agrees with what it carries.
67
+ *
68
+ * Whoever holds the source subscribed keeps it fresh: an engine refreshes its token only while it
69
+ * has a listener, and one parked holding a token keeps that token past its expiry. A long-lived
70
+ * client subscribes once for the life of the page or the process.
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * import { Mountaya, SessionTokenEngine } from "@mountaya/client";
75
+ *
76
+ * declare const mintFromMyServer: () => Promise<{
77
+ * expires_at: Date;
78
+ * token: string;
79
+ * user_id: string | null;
80
+ * }>;
81
+ *
82
+ * const session = new SessionTokenEngine({ mint: mintFromMyServer });
83
+ * // The engine refreshes while something subscribes to it: hold it for the process's life.
84
+ * session.subscribe(() => undefined);
85
+ *
86
+ * const mountaya = new Mountaya({
87
+ * credential: { publishableKey: "pk_…", sessionToken: session },
88
+ * });
89
+ * ```
90
+ */
91
+ export interface SessionTokenSource {
92
+ /**
93
+ * The token held now, whether one is on its way, and what the last mint failed with; and, where
94
+ * the source knows them, when the token expires and the user it was minted for.
95
+ */
96
+ getSnapshot(): Pick<SessionTokenSnapshot, "error" | "isLoading" | "token"> & {
97
+ /**
98
+ * When the token held now expires. An event stream opened with it that closes at or after
99
+ * this instant is opened again at once with the next token, as the API ends a stream with
100
+ * its credential.
101
+ */
102
+ readonly expiresAt?: Date | undefined;
103
+ /**
104
+ * The user the token held now was minted for, `null` for none. A call that acts as a member is
105
+ * refused locally while it reads `null`; left out, the call is sent for the API to decide.
106
+ */
107
+ readonly userId?: string | null | undefined;
108
+ };
109
+ /**
110
+ * Registers a listener told of every change of the snapshot, and returns its release. A source
111
+ * may start minting on its first listener, as a `SessionTokenEngine` does.
112
+ */
113
+ subscribe(listener: () => void): () => void;
114
+ }
115
+
116
+ /**
117
+ * PublishableCredential authenticates browser and embedding access with a `pk_` key,
118
+ * optionally scoped up by a session token minted from a secret key.
119
+ *
120
+ * The session token is also who the client acts as: your server mints it with `postSession`'s
121
+ * `user_id` set to the person signed in, and every call that acts as a member acts as that
122
+ * person. A client following a person through sign-in, an account switch and sign-out follows a
123
+ * {@link SessionTokenSource} that mints for whoever is signed in.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * import { Mountaya } from "@mountaya/client";
128
+ *
129
+ * declare const session: { readonly token: string };
130
+ *
131
+ * // Your server minted `session` with postSession's `user_id` set to the person signed in.
132
+ * const mountaya = new Mountaya({
133
+ * credential: { publishableKey: "pk_…", sessionToken: session.token },
134
+ * });
135
+ * ```
136
+ */
137
+ export interface PublishableCredential {
138
+ /** The `pk_` key, sent as `X-API-Key`. An empty or blank one is refused as a missing credential. */
139
+ readonly publishableKey: string;
140
+ /**
141
+ * The session token that accompanies the key: a `sess_` string, a function the client calls
142
+ * whenever it reads the token, or a {@link SessionTokenSource} such as a `SessionTokenEngine`.
143
+ * The token is read for each request, each event-stream open and each read of
144
+ * `MountayaTransport.mapCredential`, so every map built on the client too.
145
+ *
146
+ * A source is how one client follows a token that rotates and waits for the first one: a
147
+ * request made while the source holds no token and reports one on its way waits for it, so a
148
+ * page's first reads carry the session rather than going out under the key alone. A function may
149
+ * answer `undefined` before the first token is minted, and the key then goes out alone, so an
150
+ * operation that requires a session is refused until it answers one.
151
+ *
152
+ * A string is checked for its `sess_` prefix at construction; what a function or a source
153
+ * answers is checked at every read, where a call made with an answer that fails the check is
154
+ * refused before anything is sent.
155
+ *
156
+ * A token names the user it was minted for: `postSession` mints one for the `user_id` your
157
+ * server gives it, and every request made with it acts as that user. The reads take a token
158
+ * minted without `user_id`, and every operation that acts as a member answers one with a 401. A
159
+ * source that reports the user each token names, as a `SessionTokenEngine` does, has such an
160
+ * operation refused locally while its token is minted without `user_id`.
161
+ */
162
+ readonly sessionToken?: string | (() => string | undefined) | SessionTokenSource | undefined;
163
+ /**
164
+ * Never set: a key credential sends no cookie, and one written beside a key is refused at
165
+ * construction. The browser's own session is {@link CookieCredential}, a credential of its
166
+ * own.
167
+ */
168
+ readonly cookie?: undefined;
169
+ }
170
+
171
+ /**
172
+ * SecretCredential authenticates server-to-server session minting with an `sk_` key.
173
+ *
174
+ * It is the only credential that can call `postSession` (`POST /v1/sessions`), and
175
+ * `postSession` is the only operation it authenticates: sent to any other operation that takes a
176
+ * credential, it is refused with a `MountayaConfigurationError` before the request, where the
177
+ * API would answer a 401 as if no credential had been sent. An operation that takes none, such
178
+ * as `postOrganizationLookup`, goes out with nothing the credential holds. It is sent alone: a
179
+ * secret key beside a publishable key, a session token or a share token is refused with a
180
+ * `MountayaConfigurationError` before any request. It must never reach a browser.
181
+ */
182
+ export interface SecretCredential {
183
+ /** The `sk_` key, sent as `X-API-Key` to `postSession` alone. Never quoted in a refusal. */
184
+ readonly secretKey: string;
185
+ /** Never set: see {@link PublishableCredential.cookie}. */
186
+ readonly cookie?: undefined;
187
+ }
188
+
189
+ /**
190
+ * ShareCredential authenticates a link visitor with a `share_` token. It reaches exactly
191
+ * the itinerary or collection the token was minted for, read-only.
192
+ */
193
+ export interface ShareCredential {
194
+ /** The `share_` token, sent as `X-Share-Token` in place of a key. */
195
+ readonly shareToken: string;
196
+ /**
197
+ * Also send ambient cookies, on every operation that takes a credential.
198
+ *
199
+ * A share link is often opened by someone who is *also* signed in, and the server answers a
200
+ * signed-in visitor a richer projection than an anonymous one. Sending both lets it, and costs
201
+ * nothing when the visitor is anonymous.
202
+ *
203
+ * It also decides what happens on a read that takes a credential but no share token. Without
204
+ * it the read is refused locally, as the server would refuse the token. With it the token is
205
+ * left off and the read rides the session alone, so a signed-in visitor gets their answer and
206
+ * an anonymous one gets the server's 401. A write is refused either way.
207
+ *
208
+ * @default false
209
+ */
210
+ readonly cookie?: boolean | undefined;
211
+ }
212
+
213
+ /**
214
+ * CookieCredential defers authentication to the browser's ambient credentials.
215
+ *
216
+ * No credential header is sent; the request carries `credentials: "include"` and whatever
217
+ * cookies the browser already holds for the target origin. An operation that takes no
218
+ * credential, such as `postOrganizationLookup`, is the exception: it is sent no cookie. Use it when the caller has already authenticated by other means: a session
219
+ * cookie from your own sign-in, or a backend-for-frontend that fronts the Mountaya API on your
220
+ * origin and attaches the real credential server-side.
221
+ *
222
+ * It is the one credential that carries no secret of its own, which is exactly why it
223
+ * exists: a browser that cannot read its own httpOnly session cookie cannot build a
224
+ * header from it either.
225
+ *
226
+ * **It is outside the published contract, and the local refusals do not apply to it.** The
227
+ * contract's four credentials are the keys and tokens its `security` names; a cookie is
228
+ * Mountaya's own web application's session, or whatever a proxy in front of the API decides it
229
+ * means. So no operation's declaration refuses it: it is not refused where an operation
230
+ * accepts no share token, requires a session token or acts as a member, because the session it
231
+ * rides on already names its user. What the server makes of it is the server's answer.
232
+ *
233
+ * It carries no key and no token. A client given `cookie` beside a key throws
234
+ * `MountayaConfigurationError` at construction, since which of the two was meant is not the
235
+ * client's to guess: `{ cookie: true }` alone rides the browser's session, and a key credential
236
+ * without `cookie` sends its key. Beside a share token, `cookie` is the share credential's own
237
+ * (see {@link ShareCredential.cookie}).
238
+ */
239
+ export interface CookieCredential {
240
+ /** Rides the browser's own session: `credentials: "include"` and no credential header. */
241
+ readonly cookie: true;
242
+ /** Never set: the cookie credential carries no key. */
243
+ readonly publishableKey?: undefined;
244
+ /** Never set: the cookie credential carries no key. */
245
+ readonly secretKey?: undefined;
246
+ /** Never set: a session token accompanies a publishable key, which this credential has not. */
247
+ readonly sessionToken?: undefined;
248
+ /** Never set: a share visitor asking for cookies is a {@link ShareCredential} with `cookie`. */
249
+ readonly shareToken?: undefined;
250
+ }
251
+
252
+ /**
253
+ * Credential is any of the ways to authenticate, told apart by which key is present.
254
+ *
255
+ * The union does not stop a caller supplying two: `{ publishableKey, shareToken }` satisfies
256
+ * it, because a union of object types accepts the members of every alternative. So the pair
257
+ * is resolved at runtime, the way the contract says: a share token REPLACES a key beside it.
258
+ * The server, sent both, reads the key and ignores the token, so this client sends the share
259
+ * token alone where the operation accepts one and refuses the call where it does not.
260
+ *
261
+ * A member written as `undefined` is an omitted one, as it is for every client option, so a
262
+ * caller forwarding an optional token keeps the credential the other members make.
263
+ */
264
+ export type Credential =
265
+ | PublishableCredential
266
+ | SecretCredential
267
+ | ShareCredential
268
+ | CookieCredential;
269
+
270
+ const PUBLISHABLE_PREFIX = "pk_";
271
+ const SECRET_PREFIX = "sk_";
272
+ const SESSION_PREFIX = "sess_";
273
+ const SHARE_PREFIX = "share_";
274
+
275
+ /** The members a credential spells a key or a token with, each of them a string. */
276
+ const KEY_MEMBERS = ["publishableKey", "secretKey", "sessionToken", "shareToken"] as const;
277
+
278
+ /**
279
+ * assertHeaderValue refuses a credential member no request header carries: one holding a
280
+ * character outside printable ASCII, a line break, a tab or another control character at either
281
+ * end or inside it, or a character past ASCII, which a placeholder left in place holds.
282
+ * {@link isHeaderValue} is the rule. A member that is empty or whitespace alone holds no key at
283
+ * all, and is refused as a missing one rather than here.
284
+ *
285
+ * Sent as it is, the runtime's `fetch` refuses the request, or sends the value as bytes the API
286
+ * reads as other letters, and a refused request is reported after its retries as a connection
287
+ * failure that tells the reader to check the network. The refusal names the member and never its
288
+ * value, which may be a key.
289
+ */
290
+ const assertHeaderValue = (member: string, value: string): void => {
291
+ if (isHeaderValue(value) || isEmptyHeaderValue(value)) {
292
+ return;
293
+ }
294
+
295
+ throw new MountayaConfigurationError(
296
+ `credential.${member} holds a character no request header carries, since a header carries printable ASCII alone: a line break, a tab or another control character, at either end or inside it, or a character past ASCII, a letter of Latin-1 such as \u00e9 among them. ` +
297
+ (value.includes("\u2026")
298
+ ? "It reads as a placeholder: replace it with the value your organization was issued."
299
+ : "Pass it as it was issued, with no line break around it."),
300
+ );
301
+ };
302
+
303
+ /**
304
+ * startOf spells the first characters of a value in the publishable key's slot, which is how a
305
+ * reader tells which value landed there. It is never called for the secret key's slot: a value
306
+ * there is a secret until the server says otherwise, and none of it reaches a message.
307
+ */
308
+ const startOf = (value: string): string => `Received a value starting with "${value.slice(0, 3)}".`;
309
+
310
+ /**
311
+ * assertPrefix refuses a key or a token that does not start with the prefix its member takes,
312
+ * naming the member by the path a caller writes it at. `detail` is the sentence that follows the
313
+ * refusal, where the caller has one to add.
314
+ *
315
+ * The prefix is the whole of the check. What follows it is not read, its length least of all:
316
+ * the server alone knows what it issued.
317
+ */
318
+ const assertPrefix = (member: string, prefix: string, value: string, detail?: string): void => {
319
+ if (value.startsWith(prefix)) {
320
+ return;
321
+ }
322
+
323
+ const refusal = `credential.${member} must start with "${prefix}".`;
324
+
325
+ throw new MountayaConfigurationError(detail === undefined ? refusal : `${refusal} ${detail}`);
326
+ };
327
+
328
+ /** The shapes a credential takes, as a refusal spells them for a caller to pick from. */
329
+ const CREDENTIAL_SHAPES =
330
+ "{ publishableKey } (with a sessionToken where a call needs one), " +
331
+ "{ shareToken } for a share link, { cookie: true } for the browser's own session, " +
332
+ "or { secretKey } on a server";
333
+
334
+ /**
335
+ * memberOf reads one member of a credential as the value it holds, `undefined` where it is
336
+ * absent or written as `undefined`.
337
+ */
338
+ const memberOf = (credential: Credential, member: string): unknown =>
339
+ Reflect.get(credential, member);
340
+
341
+ /**
342
+ * holdsKey reports whether a credential carries a key or a token in `member`. A string that is
343
+ * empty or whitespace alone carries none, since that is how an unset environment variable
344
+ * arrives: the credential is then read as one without it, and refused as a missing one is.
345
+ */
346
+ const holdsKey = (credential: Credential, member: (typeof KEY_MEMBERS)[number]): boolean => {
347
+ const value = memberOf(credential, member);
348
+
349
+ return value !== undefined && !(typeof value === "string" && isEmptyHeaderValue(value));
350
+ };
351
+
352
+ /**
353
+ * isSecretCredential reports whether a credential carries a secret key, which then decides its
354
+ * kind whatever else it carries.
355
+ */
356
+ export const isSecretCredential = (credential: Credential): credential is SecretCredential =>
357
+ holdsKey(credential, "secretKey");
358
+
359
+ /**
360
+ * isShareCredential reports whether a credential carries a share token, which then replaces a
361
+ * publishable key beside it.
362
+ */
363
+ export const isShareCredential = (credential: Credential): credential is ShareCredential =>
364
+ holdsKey(credential, "shareToken");
365
+
366
+ /** isPublishableCredential reports whether a credential carries a publishable key. */
367
+ export const isPublishableCredential = (
368
+ credential: Credential,
369
+ ): credential is PublishableCredential => holdsKey(credential, "publishableKey");
370
+
371
+ /**
372
+ * isCookie reports whether a credential is the browser's own session: `cookie: true` with no key
373
+ * or token beside it. `cookie` beside a key makes no cookie credential, and
374
+ * {@link assertCredential} refuses it.
375
+ */
376
+ const isCookie = (credential: Credential): credential is CookieCredential =>
377
+ memberOf(credential, "cookie") === true &&
378
+ KEY_MEMBERS.every((member) => !holdsKey(credential, member));
379
+
380
+ /**
381
+ * isSessionTokenSource reports whether a session token member is a {@link SessionTokenSource}: an
382
+ * object whose `getSnapshot` and `subscribe` are functions.
383
+ */
384
+ const isSessionTokenSource = (value: unknown): value is SessionTokenSource =>
385
+ typeof value === "object" &&
386
+ value !== null &&
387
+ typeof Reflect.get(value, "getSnapshot") === "function" &&
388
+ typeof Reflect.get(value, "subscribe") === "function";
389
+
390
+ /**
391
+ * assertSourceMembers refuses a session token object that states `getSnapshot` or `subscribe`
392
+ * and is still no {@link SessionTokenSource}, naming the member that is no function by its type
393
+ * and never its value. An object that states neither is left to the refusal of its type.
394
+ */
395
+ const assertSourceMembers = (value: unknown): void => {
396
+ if (typeof value !== "object" || value === null) {
397
+ return;
398
+ }
399
+
400
+ if (!("getSnapshot" in value) && !("subscribe" in value)) {
401
+ return;
402
+ }
403
+
404
+ for (const name of ["getSnapshot", "subscribe"]) {
405
+ const found: unknown = Reflect.get(value, name);
406
+
407
+ if (typeof found !== "function") {
408
+ throw new MountayaConfigurationError(
409
+ `credential.sessionToken.${name} is ${describeType(found)}; a session token source ` +
410
+ "states getSnapshot and subscribe as functions, as a SessionTokenEngine does.",
411
+ );
412
+ }
413
+ }
414
+ };
415
+
416
+ /**
417
+ * assertMemberTypes refuses a credential member of a type no credential takes: a key or a token
418
+ * that is not a string, a session token that is neither a string, a function nor a
419
+ * {@link SessionTokenSource}, or a `cookie` that is not a boolean. A member that is a string is
420
+ * held to what a request header carries, by {@link assertHeaderValue}.
421
+ *
422
+ * The refusal names the member and its type and never its value, since a key is a secret
423
+ * whatever type it arrived as. A session token's function is not called here: what it answers
424
+ * is checked where it is read, by {@link sessionTokenOf}.
425
+ */
426
+ const assertMemberTypes = (credential: Credential): void => {
427
+ for (const member of KEY_MEMBERS) {
428
+ const value = memberOf(credential, member);
429
+ const readPerRequest =
430
+ member === "sessionToken" && (typeof value === "function" || isSessionTokenSource(value));
431
+
432
+ if (member === "sessionToken" && !readPerRequest) {
433
+ assertSourceMembers(value);
434
+ }
435
+
436
+ if (value !== undefined && typeof value !== "string" && !readPerRequest) {
437
+ throw new MountayaConfigurationError(
438
+ `credential.${member} is ${describeType(value)}; pass it as a string, ` +
439
+ (member === "sessionToken" ? "a function answering one, or a SessionTokenEngine, " : "") +
440
+ "or leave it out.",
441
+ );
442
+ }
443
+
444
+ if (typeof value === "string") {
445
+ if (member === "sessionToken" && isEmptyHeaderValue(value)) {
446
+ throw new MountayaConfigurationError(
447
+ `credential.sessionToken is ${value === "" ? "an empty string" : "whitespace alone"}; pass the token your server minted, or leave it out.`,
448
+ );
449
+ }
450
+
451
+ assertHeaderValue(member, value);
452
+ }
453
+ }
454
+
455
+ const cookie = memberOf(credential, "cookie");
456
+ if (cookie !== undefined && typeof cookie !== "boolean") {
457
+ throw new MountayaConfigurationError(
458
+ `credential.cookie is ${describeType(cookie)}; pass true to send the browser's own cookies, or leave it out.`,
459
+ );
460
+ }
461
+ };
462
+
463
+ /**
464
+ * refuseCookieBesideKey builds the refusal for `cookie` written beside a key: which of the two
465
+ * the caller meant is not the client's to guess, and either reading is wrong for the caller who
466
+ * meant the other.
467
+ */
468
+ const refuseCookieBesideKey = (key: "publishableKey" | "secretKey"): MountayaConfigurationError =>
469
+ new MountayaConfigurationError(
470
+ `credential carries ${key} and cookie together, which no credential does: a cookie ` +
471
+ "credential carries no key, and a key credential sends no cookie. Drop cookie to " +
472
+ "authenticate with the key, or pass { cookie: true } alone to ride the browser's own " +
473
+ "session.",
474
+ );
475
+
476
+ /**
477
+ * wantsCookies reports whether a credential asks for ambient browser credentials.
478
+ *
479
+ * Only the cookie and share credentials ever do. A publishable key deliberately does NOT:
480
+ * sending a cookie alongside a scoped key lets the cookie's broader session outrank the
481
+ * key, so an embed would silently see more than the key permits. A request made under a
482
+ * credential this answers false for carries `credentials: "omit"`, so no cookie travels with it
483
+ * even where the API is reached through the page's own origin.
484
+ */
485
+ export const wantsCookies = (credential: Credential): boolean =>
486
+ isCookie(credential) || (isShareCredential(credential) && credential.cookie === true);
487
+
488
+ /**
489
+ * inShippedRuntime reports whether the current runtime is one whose code ships to the people who
490
+ * use it: a page, whose global object holds both a DOM `window` and a `document`, or a React
491
+ * Native application, whose `navigator.product` reads `ReactNative`. Anyone holding the
492
+ * application reads every value bundled into it, a secret key among them.
493
+ *
494
+ * This is the one place the package looks at `window`, `document` or `navigator`, and it looks
495
+ * at them to refuse work rather than to do any. `globalThis` is used rather than a bare `window`
496
+ * reference so the check stays a runtime question in every bundler, and so it never throws under
497
+ * Node where the identifier is simply absent.
498
+ *
499
+ * It reads those members and nothing else of the runtime. A browser's worker (dedicated, shared
500
+ * or service) holds neither a `window` nor a `document`, and its `navigator.product` reads
501
+ * `Gecko`, so it answers false there and the guard does not reach a worker's bundle: what keeps a
502
+ * secret key out of one is the browser entry point, which takes no secret key at all. Node's own
503
+ * `navigator` names no product.
504
+ */
505
+ const inShippedRuntime = (): boolean => {
506
+ if (typeof globalThis !== "object") {
507
+ return false;
508
+ }
509
+
510
+ if ("window" in globalThis && "document" in globalThis) {
511
+ return true;
512
+ }
513
+
514
+ // Read against a widened type: `lib.dom` declares a `navigator` on every runtime, and a runtime
515
+ // may hold none, or one whose `product` is no string.
516
+ const runtime: { readonly navigator?: { readonly product?: unknown } | undefined } = globalThis;
517
+
518
+ return runtime.navigator?.product === "ReactNative";
519
+ };
520
+
521
+ /**
522
+ * assertSessionToken refuses a session token no request header carries and one that does not
523
+ * start with `sess_`: the checks a string gets at construction and a function's answer gets at
524
+ * every read.
525
+ *
526
+ * The refusal never quotes the value, which may be a key pasted into the wrong slot.
527
+ */
528
+ const assertSessionToken = (token: string): void => {
529
+ assertHeaderValue("sessionToken", token);
530
+ // The value's own first characters stay out of this one: a key pasted here is the likely slip.
531
+ assertPrefix("sessionToken", SESSION_PREFIX, token);
532
+ };
533
+
534
+ /**
535
+ * sessionTokenOf reads the session token a publishable credential carries at this moment: the
536
+ * string it holds, what its function answers now, or the token its source's snapshot holds, with
537
+ * `undefined` for none.
538
+ *
539
+ * Every reader of the token goes through it (the headers of a request, an event-stream open, the
540
+ * projection a map reads), so a function or a source is read once per read and its answer is
541
+ * never kept. A string was checked at construction and is returned as it is.
542
+ *
543
+ * @throws `MountayaConfigurationError` where the function or the source answers neither a string
544
+ * nor `undefined`, naming the type and never the value, or a string without the `sess_`
545
+ * prefix, or one no request header carries.
546
+ */
547
+ export const sessionTokenOf = (credential: PublishableCredential): string | undefined => {
548
+ const member = credential.sessionToken;
549
+ if (member === undefined || typeof member === "string") {
550
+ return member;
551
+ }
552
+
553
+ // Typed as the credential says, and still whatever the caller's function or source answered:
554
+ // read as unknown until it is shown to be a string.
555
+ const answer: unknown = typeof member === "function" ? member() : member.getSnapshot().token;
556
+ if (answer === undefined) {
557
+ return undefined;
558
+ }
559
+
560
+ if (typeof answer !== "string") {
561
+ throw new MountayaConfigurationError(
562
+ `credential.sessionToken answered ${describeType(answer)}; answer the current token as a ` +
563
+ "string, or undefined while there is none.",
564
+ );
565
+ }
566
+
567
+ assertSessionToken(answer);
568
+
569
+ return answer;
570
+ };
571
+
572
+ /**
573
+ * sessionSourceOf answers the {@link SessionTokenSource} a credential holds as its session token,
574
+ * or `undefined` where it holds a string, a function or none.
575
+ */
576
+ export const sessionSourceOf = (credential: Credential): SessionTokenSource | undefined => {
577
+ const member = memberOf(credential, "sessionToken");
578
+
579
+ return isPublishableCredential(credential) && isSessionTokenSource(member) ? member : undefined;
580
+ };
581
+
582
+ /**
583
+ * sessionUserOf reads the user the session token a credential holds now was minted for, as its
584
+ * source reports it: a string names one, `null` names none, and undefined is a source that does
585
+ * not say, or a token held as a string or a function, whose user the client is not told.
586
+ */
587
+ export const sessionUserOf = (credential: Credential): string | null | undefined => {
588
+ const source = sessionSourceOf(credential);
589
+ if (source === undefined) {
590
+ return undefined;
591
+ }
592
+
593
+ // Read as unknown: a source of the caller's own may answer anything there.
594
+ const user: unknown = source.getSnapshot().userId;
595
+
596
+ return typeof user === "string" || user === null ? user : undefined;
597
+ };
598
+
599
+ /**
600
+ * sessionExpiryOf reads when the session token a credential holds now expires, as its source
601
+ * reports it, or undefined where it reports no instant.
602
+ */
603
+ export const sessionExpiryOf = (credential: Credential): Date | undefined => {
604
+ const expiry: unknown = sessionSourceOf(credential)?.getSnapshot().expiresAt;
605
+
606
+ return expiry instanceof Date && !Number.isNaN(expiry.getTime()) ? expiry : undefined;
607
+ };
608
+
609
+ /**
610
+ * holdsSession reports whether a request made now under a publishable credential carries a
611
+ * session token or waits for one: a string, a function answering a string now, or a source that
612
+ * holds a token or reports one on its way, which is the rule a request's wait reads too. It
613
+ * never quotes the token, and an answer that is not a token is refused where a request reads it,
614
+ * not here.
615
+ *
616
+ * @throws what a session token held as a function throws, since the function is called here.
617
+ */
618
+ export const holdsSession = (credential: PublishableCredential): boolean => {
619
+ const member = credential.sessionToken;
620
+ if (member === undefined || typeof member === "string") {
621
+ return member !== undefined;
622
+ }
623
+
624
+ if (typeof member === "function") {
625
+ return typeof member() === "string";
626
+ }
627
+
628
+ const snapshot = member.getSnapshot();
629
+
630
+ return snapshot.token !== undefined || snapshot.isLoading;
631
+ };
632
+
633
+ /**
634
+ * assertCredential rejects a credential that cannot work, before any request is made.
635
+ *
636
+ * Prefix checking is not pedantry. Every one of these values is an opaque string, so a
637
+ * publishable key pasted into the secret slot produces a 401 from the server with no hint
638
+ * about which of the two was wrong, and the mistake is common, because the two are
639
+ * copied from adjacent rows of the same settings page.
640
+ *
641
+ * The browser guard is the second of two defences against leaking a secret key into a
642
+ * client bundle. The first is that `@mountaya/client/browser` never exports the secret
643
+ * constructor at all, so a correctly-resolved browser build cannot reach it. This one
644
+ * catches the case that entry point cannot: a bundler resolving the Node condition into
645
+ * code that ships to a browser anyway, or a React Native application, which resolves no
646
+ * browser entry point at all.
647
+ *
648
+ * The shape is checked before any prefix, because a caller outside the compiler (a JavaScript
649
+ * caller, or a value past a cast) can hand over anything: no credential at all, a member of the
650
+ * wrong type, `cookie` beside a key, or an object that is none of the shapes a credential takes.
651
+ * Each is refused here, named, rather than read as the nearest shape or thrown as a `TypeError`
652
+ * from inside the check.
653
+ *
654
+ * @throws `MountayaConfigurationError` for every credential that cannot work.
655
+ */
656
+ export const assertCredential = (credential: Credential): void => {
657
+ // Typed as the union, and still whatever the caller passed: read as unknown until it is shown
658
+ // to be an object.
659
+ const value: unknown = credential;
660
+ if (typeof value !== "object" || value === null) {
661
+ throw new MountayaConfigurationError(
662
+ `credential is ${describeType(value)}; pass ${CREDENTIAL_SHAPES}.`,
663
+ );
664
+ }
665
+
666
+ assertMemberTypes(credential);
667
+
668
+ if (isSecretCredential(credential)) {
669
+ if (memberOf(credential, "cookie") !== undefined) {
670
+ throw refuseCookieBesideKey("secretKey");
671
+ }
672
+
673
+ // A secret key is sent alone, so a part beside it is one the caller expects sent and it never
674
+ // is, or a credential of another kind the secret would ride with. A part left blank is none.
675
+ const beside = KEY_MEMBERS.find(
676
+ (member) => member !== "secretKey" && holdsKey(credential, member),
677
+ );
678
+ if (beside !== undefined) {
679
+ throw new MountayaConfigurationError(
680
+ `credential carries secretKey beside ${beside}, which no credential does: a secret key is sent alone, to postSession. Drop ${beside} to mint sessions with the secret key, or drop secretKey ${
681
+ beside === "sessionToken"
682
+ ? "and pass { publishableKey, sessionToken }, since a session token accompanies a publishable key."
683
+ : `to authenticate with the ${beside}.`
684
+ }`,
685
+ );
686
+ }
687
+
688
+ assertPrefix(
689
+ "secretKey",
690
+ SECRET_PREFIX,
691
+ credential.secretKey,
692
+ credential.secretKey.startsWith(PUBLISHABLE_PREFIX)
693
+ ? "This looks like a publishable key: pass it as { publishableKey }."
694
+ : // Nothing of the value is quoted: a key pasted without its prefix is still a secret.
695
+ "Pass the secret key as it was issued: nothing of the value is quoted here.",
696
+ );
697
+
698
+ if (inShippedRuntime()) {
699
+ throw new MountayaConfigurationError(
700
+ "A secret key must never reach a browser or a mobile application: anyone can read it out of the bundle. " +
701
+ "Mint a session token on your server with POST /v1/sessions and send that to the client instead.",
702
+ );
703
+ }
704
+
705
+ return;
706
+ }
707
+
708
+ // A share token REPLACES a key beside it, so the pair is a share credential, and `cookie`
709
+ // beside the token is how a signed-in visitor asks for their own session too.
710
+ if (isShareCredential(credential)) {
711
+ // Nothing of the value is quoted: a share token opens a resource to whoever holds it.
712
+ assertPrefix("shareToken", SHARE_PREFIX, credential.shareToken);
713
+
714
+ return;
715
+ }
716
+
717
+ if (isPublishableCredential(credential)) {
718
+ if (memberOf(credential, "cookie") !== undefined) {
719
+ throw refuseCookieBesideKey("publishableKey");
720
+ }
721
+
722
+ assertPrefix(
723
+ "publishableKey",
724
+ PUBLISHABLE_PREFIX,
725
+ credential.publishableKey,
726
+ credential.publishableKey.startsWith(SECRET_PREFIX)
727
+ ? "This looks like a secret key: pass it as { secretKey }, and only from a server."
728
+ : startOf(credential.publishableKey),
729
+ );
730
+
731
+ // A string is checked now; a function or a source has nothing to answer before its first
732
+ // mint, so its answer is checked at every read instead.
733
+ if (typeof credential.sessionToken === "string") {
734
+ assertSessionToken(credential.sessionToken);
735
+ }
736
+
737
+ return;
738
+ }
739
+
740
+ if (memberOf(credential, "cookie") !== undefined) {
741
+ // A key an unset environment variable left blank still says a key was meant: read as the
742
+ // browser's own session, the credential would send the visitor's cookies in its place.
743
+ const blank = KEY_MEMBERS.find(
744
+ (member) => member !== "sessionToken" && memberOf(credential, member) !== undefined,
745
+ );
746
+ if (blank !== undefined) {
747
+ throw new MountayaConfigurationError(
748
+ `credential carries cookie beside an empty ${blank}, which is how an unset environment ` +
749
+ `variable arrives: set ${blank}, or pass { cookie: true } alone to ride the browser's ` +
750
+ "own session.",
751
+ );
752
+ }
753
+ }
754
+
755
+ if (isCookie(credential)) {
756
+ return;
757
+ }
758
+
759
+ // None of the shapes a credential takes. A key member still written here is blank, since a key
760
+ // that holds text makes a shape above, and is named so the unset variable behind it is found.
761
+ const blanks = KEY_MEMBERS.filter(
762
+ (member) => member !== "sessionToken" && memberOf(credential, member) !== undefined,
763
+ ).map((member) => `credential.${member}`);
764
+ const blankNote =
765
+ blanks.length === 0
766
+ ? ""
767
+ : ` (${blanks.join(" and ")} ${blanks.length === 1 ? "is" : "are"} empty or blank, which ` +
768
+ "is how an unset environment variable arrives, and counts as none)";
769
+
770
+ // A session token alone is the likeliest slip, and the one whose fix can be spelled out exactly.
771
+ throw new MountayaConfigurationError(
772
+ memberOf(credential, "sessionToken") === undefined
773
+ ? `credential carries no publishableKey, secretKey, shareToken or cookie: true${blankNote}, so it authenticates nothing; pass ${CREDENTIAL_SHAPES}.`
774
+ : "credential carries a sessionToken and no publishableKey, which the session token accompanies rather than replaces; pass { publishableKey, sessionToken }.",
775
+ );
776
+ };
777
+
778
+ /**
779
+ * OperationCredentials is what one operation declares about the credentials it takes, plus the
780
+ * method it is sent with: everything the local refusals below read.
781
+ *
782
+ * A generated operation states each flag from the contract, and `RequestArgs` carries the same
783
+ * members, so a request descriptor IS one of these. Every credential flag is read as declared
784
+ * and none is inferred from the method: an absent flag is an operation that does not declare the
785
+ * thing it names, so a share token is refused, a session token is not required, and a secret key
786
+ * is refused unless the operation takes no credential.
787
+ */
788
+ export interface OperationCredentials {
789
+ /**
790
+ * Whether one of the operation's security requirements is a share token on its own. Where it
791
+ * is not, a share token is refused locally, which is how every write refuses one, and how a
792
+ * read no share link reaches refuses one before the 401 the server would answer.
793
+ */
794
+ readonly acceptsShareToken?: boolean | undefined;
795
+ /**
796
+ * Whether the operation acts as the user its session token was minted for: its `x-acting-user` is
797
+ * `required`. Where it does, a credential whose session source reports a token minted without
798
+ * `user_id` is refused locally, since the API would answer the call with a 401.
799
+ */
800
+ readonly actsAsMember?: boolean | undefined;
801
+ /** The HTTP method, which a refusal names where the call names no operation. */
802
+ readonly method: string;
803
+ /** Names the operation in a refusal, so the message says which call was refused. */
804
+ readonly operationId?: string | undefined;
805
+ /**
806
+ * Whether the operation only reads, for a read the method would call a write: a share token
807
+ * refused on a write is told it writes.
808
+ */
809
+ readonly read?: boolean | undefined;
810
+ /**
811
+ * Whether the operation is authenticated by a secret key, which `postSession` alone is. Where
812
+ * it is, every credential but a secret key is refused locally; where it is not, a secret key
813
+ * is refused, unless the operation takes no credential.
814
+ */
815
+ readonly requiresSecretKey?: boolean | undefined;
816
+ /**
817
+ * Whether every one of the operation's security requirements names a session token. Where it
818
+ * does, a credential carrying none is refused locally rather than sent to be answered with a
819
+ * 401.
820
+ */
821
+ readonly requiresSession?: boolean | undefined;
822
+ /**
823
+ * Whether the operation takes no credential at all, as `postOrganizationLookup` does. Where it
824
+ * does, nothing the credential holds is sent and nothing is refused.
825
+ */
826
+ readonly takesNoCredential?: boolean | undefined;
827
+ }
828
+
829
+ /** The operation a refusal names, or its method where the call names no operation. */
830
+ const subjectOf = (operation: Pick<OperationCredentials, "method" | "operationId">): string =>
831
+ operation.operationId ?? `A ${operation.method.toUpperCase()}`;
832
+
833
+ /**
834
+ * Reports whether an operation writes: sent with any method but a read's, and not declared a
835
+ * read, which every Data API query is over its POST.
836
+ */
837
+ const isWrite = (operation: Pick<OperationCredentials, "method" | "read">): boolean => {
838
+ const upper = operation.method.toUpperCase();
839
+
840
+ return operation.read !== true && upper !== "GET" && upper !== "HEAD" && upper !== "OPTIONS";
841
+ };
842
+
843
+ /**
844
+ * credentialHeaders projects a credential onto the headers for one operation, refusing locally
845
+ * a credential that operation cannot take.
846
+ *
847
+ * The refusals, each read off the operation's DECLARATION and never off its method, and each
848
+ * one a request the server would answer with a status that names no rule:
849
+ *
850
+ * - **Any credential but a secret key where a secret key authenticates the operation**, which
851
+ * `postSession` alone declares. The server answers a publishable key there with a 401 that
852
+ * says only that the credential is not accepted.
853
+ * - **A secret key on any other operation that takes a credential.** The server does not read
854
+ * it there at all, and answers with a 401 as if nothing had been sent.
855
+ * - **A share token where the operation accepts none.** The server answers a share-token write
856
+ * with a 401, as if no credential had been sent, or a 400 when the body fails validation
857
+ * first; neither says the token cannot write. It REPLACES a key beside it, so a client
858
+ * configured with both sends the share token alone, and is refused where it cannot be sent.
859
+ * - **No session token where every requirement names one.** A share token carries none; a
860
+ * publishable key carries one only when it was given one, or while its function answers one.
861
+ * - **A session token minted without `user_id` where the operation acts as a member.** Read off a
862
+ * {@link SessionTokenSource} that reports the user, as a `SessionTokenEngine` does; a token held
863
+ * as a string or a function is sent, since the client is not told whom it names.
864
+ *
865
+ * An operation that takes no credential, as `postOrganizationLookup` does, is read against none
866
+ * of them and sent nothing the credential holds.
867
+ *
868
+ * A {@link CookieCredential} is read against none of them either: it is outside the published
869
+ * contract, and its session already names its user. It sends no header of its own.
870
+ *
871
+ * A {@link ShareCredential} that asked for cookies is that credential on a read that takes no
872
+ * share token: nothing is refused and no header is sent, so the visitor's own session carries
873
+ * the read if they have one and the server answers a 401 if they do not. This is how a visitor
874
+ * who is also signed in reads beyond the link, their own itineraries for one. A write is refused
875
+ * all the same, since the credential is a read-only link whatever rides with it.
876
+ */
877
+ export const credentialHeaders = (
878
+ credential: Credential,
879
+ operation: OperationCredentials,
880
+ ): Record<string, string> => {
881
+ if (operation.takesNoCredential === true) {
882
+ return {};
883
+ }
884
+
885
+ if (isCookie(credential)) {
886
+ // No header by design. The browser attaches the cookie; a header built from one it
887
+ // cannot read is the thing this credential exists to avoid.
888
+ return {};
889
+ }
890
+
891
+ if (operation.requiresSecretKey === true) {
892
+ if (isSecretCredential(credential)) {
893
+ return { "X-API-Key": credential.secretKey };
894
+ }
895
+
896
+ throw new MountayaConfigurationError(
897
+ `${subjectOf(operation)} is authenticated by a secret key alone, which must never reach a ` +
898
+ "browser. Call it on your server with { secretKey }, and give the caller the session " +
899
+ "token it mints as { publishableKey, sessionToken }.",
900
+ );
901
+ }
902
+
903
+ if (isSecretCredential(credential)) {
904
+ throw new MountayaConfigurationError(
905
+ `${subjectOf(operation)} does not take a secret key: a secret key authenticates ` +
906
+ "postSession alone, and the API answers one here with a 401 as if nothing had been " +
907
+ "sent. " +
908
+ (operation.requiresSession !== true
909
+ ? "Call this one with a publishable key, and keep the secret key on the server that " +
910
+ "mints sessions."
911
+ : operation.actsAsMember === true
912
+ ? "Mint a session token with it on your server, giving postSession's user_id the " +
913
+ "member this call acts as, and call this one with { publishableKey, sessionToken }."
914
+ : "Mint a session token with it on your server, and call this one with " +
915
+ "{ publishableKey, sessionToken }."),
916
+ );
917
+ }
918
+
919
+ if (isShareCredential(credential)) {
920
+ if (operation.acceptsShareToken === true) {
921
+ return { "X-Share-Token": credential.shareToken };
922
+ }
923
+
924
+ if (credential.cookie === true && !isWrite(operation)) {
925
+ // The visitor's own session carries this read, as the cookie the browser attaches, so
926
+ // no header is sent: the token stays off an operation that does not declare it, and
927
+ // whether a session is there to answer is the server's to say.
928
+ return {};
929
+ }
930
+
931
+ throw new MountayaConfigurationError(
932
+ `${subjectOf(operation)} does not accept a share token. A share token is read-only and ` +
933
+ "reaches the one itinerary, collection or zone it was minted for, through the " +
934
+ "operations that declare it. " +
935
+ (isWrite(operation)
936
+ ? "Minting, rotating and disabling a share link take a publishable key with the " +
937
+ "`studio-embedded` scope and a session token minted for `studio-embedded` naming a " +
938
+ "member with a write role."
939
+ : "Call this one with a publishable key."),
940
+ );
941
+ }
942
+
943
+ // Read once for this request: a function is called here, and its answer is what both the
944
+ // session requirement and the header below read.
945
+ const sessionToken = sessionTokenOf(credential);
946
+
947
+ if (operation.requiresSession === true && sessionToken === undefined) {
948
+ // A call that acts as a member is told which token it needs as well as that it needs one:
949
+ // the API reads the member off the token, so a token minted without `user_id` is refused
950
+ // there as surely as none.
951
+ const forMember =
952
+ operation.actsAsMember === true
953
+ ? " This call acts as a member, so mint the token with postSession's user_id set to the " +
954
+ "user it acts as."
955
+ : "";
956
+ const source = sessionSourceOf(credential);
957
+ if (source !== undefined) {
958
+ const { error } = source.getSnapshot();
959
+
960
+ throw new MountayaConfigurationError(
961
+ `${subjectOf(operation)} requires a session token beside the publishable key, and ` +
962
+ "credential.sessionToken holds none: " +
963
+ (error === undefined
964
+ ? "no token has been minted, or minting is disabled. "
965
+ : "its last mint failed, which this error carries as its cause. ") +
966
+ `Make the call once it holds the token your server minted.${forMember}`,
967
+ error === undefined ? undefined : { cause: error },
968
+ );
969
+ }
970
+
971
+ if (typeof credential.sessionToken === "function") {
972
+ throw new MountayaConfigurationError(
973
+ `${subjectOf(operation)} requires a session token beside the publishable key, and ` +
974
+ "credential.sessionToken answered none: no token has been minted yet, or the " +
975
+ `session has ended. Make the call once it answers the token your server minted.${forMember}`,
976
+ );
977
+ }
978
+
979
+ throw new MountayaConfigurationError(
980
+ operation.actsAsMember === true
981
+ ? `${subjectOf(operation)} acts as a member, so it requires a session token minted for ` +
982
+ "that member beside the publishable key. Mint one on your server with POST " +
983
+ "/v1/sessions, giving user_id the user it acts as, and pass " +
984
+ "{ publishableKey, sessionToken } when constructing the client."
985
+ : `${subjectOf(operation)} requires a session token beside the publishable key. Mint ` +
986
+ "one on your server with POST /v1/sessions and pass { publishableKey, sessionToken } " +
987
+ "when constructing the client.",
988
+ );
989
+ }
990
+
991
+ // The token names the user the call acts as, and a source that reports whom says so: one
992
+ // minted without `user_id` reads and never writes, and the API answers this call under it with
993
+ // a 401 that names no rule. A token held as a string or a function names a user the client is
994
+ // not told, and the call goes out for the API to decide.
995
+ if (
996
+ operation.actsAsMember === true &&
997
+ sessionToken !== undefined &&
998
+ sessionUserOf(credential) === null
999
+ ) {
1000
+ throw new MountayaConfigurationError(
1001
+ `${subjectOf(operation)} acts as the user its session token was minted for, and ` +
1002
+ "credential.sessionToken holds a token minted without user_id, which reads and never " +
1003
+ "acts as a member. Mint the token on your server with postSession's user_id set to the " +
1004
+ "user signed in.",
1005
+ );
1006
+ }
1007
+
1008
+ const headers: Record<string, string> = { "X-API-Key": credential.publishableKey };
1009
+
1010
+ // The session token accompanies the key rather than replacing it. Sending it alone is
1011
+ // a 401, which is why this is an addition and never an else-branch.
1012
+ if (sessionToken !== undefined) {
1013
+ headers["X-Session-Token"] = sessionToken;
1014
+ }
1015
+
1016
+ return headers;
1017
+ };