@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,1972 @@
1
+ 'use strict';
2
+
3
+ // src/core/rules/rateLimit.ts
4
+ var digitPattern = /[0-9]/;
5
+ var alphaPattern = /[A-Za-z]/;
6
+ var lowercaseAlphaPattern = /[a-z]/;
7
+ var keyCharPattern = /[a-z0-9_.*-]/;
8
+ var tokenCharPattern = /[!#$%&'*+\-.^_`|~0-9A-Za-z:/]/;
9
+ var base64CharPattern = /[A-Za-z0-9+/=]/;
10
+ var Cursor = class {
11
+ constructor(text) {
12
+ this.text = text;
13
+ }
14
+ text;
15
+ index = 0;
16
+ /** Whether every character is consumed. */
17
+ get done() {
18
+ return this.index >= this.text.length;
19
+ }
20
+ /**
21
+ * The next character, or "" at the end. A method rather than a getter, so a comparison with it
22
+ * is not taken to hold after the cursor moves.
23
+ */
24
+ peek() {
25
+ return this.text[this.index] ?? "";
26
+ }
27
+ /** Consumes one character and answers it. */
28
+ take() {
29
+ const char = this.peek();
30
+ this.index += 1;
31
+ return char;
32
+ }
33
+ /** Discards spaces. */
34
+ skipSpaces() {
35
+ while (this.peek() === " ") {
36
+ this.index += 1;
37
+ }
38
+ }
39
+ /** Discards optional whitespace: spaces and tabs. */
40
+ skipWhitespace() {
41
+ while (this.peek() === " " || this.peek() === " ") {
42
+ this.index += 1;
43
+ }
44
+ }
45
+ /** Consumes `char` and answers whether the next character was it. */
46
+ consume(char) {
47
+ return this.take() === char;
48
+ }
49
+ /** An item or an inner list, and its parameters. */
50
+ member() {
51
+ if (this.peek() === "(") {
52
+ if (!this.innerList()) {
53
+ return void 0;
54
+ }
55
+ const parameters2 = this.parameters();
56
+ return parameters2 === void 0 ? void 0 : { item: void 0, parameters: parameters2 };
57
+ }
58
+ const item = this.bareItem();
59
+ const parameters = item === void 0 ? void 0 : this.parameters();
60
+ return parameters === void 0 ? void 0 : { item, parameters };
61
+ }
62
+ /** An inner list, `(item item);params`, whose items are parsed and set aside. */
63
+ innerList() {
64
+ this.index += 1;
65
+ for (; ; ) {
66
+ this.skipSpaces();
67
+ if (this.peek() === ")") {
68
+ this.index += 1;
69
+ return true;
70
+ }
71
+ if (this.bareItem() === void 0 || this.parameters() === void 0) {
72
+ return false;
73
+ }
74
+ if (this.peek() !== " " && this.peek() !== ")") {
75
+ return false;
76
+ }
77
+ }
78
+ }
79
+ /** The parameters after an item: `;key=value`, a key alone being `true`. */
80
+ parameters() {
81
+ const parameters = /* @__PURE__ */ new Map();
82
+ while (this.peek() === ";") {
83
+ this.index += 1;
84
+ this.skipSpaces();
85
+ const key = this.key();
86
+ if (key === void 0) {
87
+ return void 0;
88
+ }
89
+ let value = { kind: "boolean", value: true };
90
+ if (this.peek() === "=") {
91
+ this.index += 1;
92
+ value = this.bareItem();
93
+ }
94
+ if (value === void 0) {
95
+ return void 0;
96
+ }
97
+ parameters.set(key, value);
98
+ }
99
+ return parameters;
100
+ }
101
+ /** A parameter's key: a lowercase letter or `*`, then lowercase letters, digits, `_-.*`. */
102
+ key() {
103
+ if (!lowercaseAlphaPattern.test(this.peek()) && this.peek() !== "*") {
104
+ return void 0;
105
+ }
106
+ let key = this.take();
107
+ while (keyCharPattern.test(this.peek())) {
108
+ key += this.take();
109
+ }
110
+ return key;
111
+ }
112
+ /** One bare item, its kind decided by its first character. */
113
+ bareItem() {
114
+ const first = this.peek();
115
+ if (first === "-" || digitPattern.test(first)) {
116
+ return this.number();
117
+ }
118
+ if (first === '"') {
119
+ const value = this.string();
120
+ return value === void 0 ? void 0 : { kind: "string", value };
121
+ }
122
+ if (first === "*" || alphaPattern.test(first)) {
123
+ return { kind: "token", value: this.token() };
124
+ }
125
+ if (first === ":") {
126
+ return this.bytes() ? { kind: "bytes" } : void 0;
127
+ }
128
+ if (first === "?") {
129
+ this.index += 1;
130
+ const value = this.take();
131
+ return value === "0" || value === "1" ? { kind: "boolean", value: value === "1" } : void 0;
132
+ }
133
+ if (first === "@") {
134
+ this.index += 1;
135
+ const date = this.number();
136
+ return date?.kind === "integer" ? { kind: "date", value: date.value } : void 0;
137
+ }
138
+ if (first === "%") {
139
+ this.index += 1;
140
+ const value = this.displayString();
141
+ return value === void 0 ? void 0 : { kind: "display", value };
142
+ }
143
+ return void 0;
144
+ }
145
+ /** An integer of at most 15 digits, or a decimal of at most 12 before its point and 3 after. */
146
+ number() {
147
+ let sign = 1;
148
+ if (this.peek() === "-") {
149
+ sign = -1;
150
+ this.index += 1;
151
+ }
152
+ let digits = "";
153
+ let decimal = false;
154
+ while (digitPattern.test(this.peek()) || this.peek() === "." && !decimal) {
155
+ if (this.peek() === ".") {
156
+ if (digits.length > 12) {
157
+ return void 0;
158
+ }
159
+ decimal = true;
160
+ }
161
+ digits += this.take();
162
+ if (!decimal && digits.length > 15 || decimal && digits.length > 16) {
163
+ return void 0;
164
+ }
165
+ }
166
+ if (digits === "" || digits.startsWith(".")) {
167
+ return void 0;
168
+ }
169
+ if (!decimal) {
170
+ return { kind: "integer", value: sign * Number(digits) };
171
+ }
172
+ const fraction = digits.slice(digits.indexOf(".") + 1);
173
+ if (fraction.length === 0 || fraction.length > 3) {
174
+ return void 0;
175
+ }
176
+ return { kind: "decimal", value: sign * Number(digits) };
177
+ }
178
+ /** A quoted string of printable ASCII, whose only escapes are `\"` and `\\`. */
179
+ string() {
180
+ this.index += 1;
181
+ let value = "";
182
+ for (; ; ) {
183
+ if (this.done) {
184
+ return void 0;
185
+ }
186
+ const char = this.take();
187
+ if (char === '"') {
188
+ return value;
189
+ }
190
+ if (char === "\\") {
191
+ const escaped = this.take();
192
+ if (escaped !== '"' && escaped !== "\\") {
193
+ return void 0;
194
+ }
195
+ value += escaped;
196
+ continue;
197
+ }
198
+ const code = char.charCodeAt(0);
199
+ if (code < 32 || code > 126) {
200
+ return void 0;
201
+ }
202
+ value += char;
203
+ }
204
+ }
205
+ /** A token: a letter or `*`, then tchar, `:` and `/`. */
206
+ token() {
207
+ let value = this.take();
208
+ while (tokenCharPattern.test(this.peek())) {
209
+ value += this.take();
210
+ }
211
+ return value;
212
+ }
213
+ /** A byte sequence, `:base64:`, read for its shape alone. */
214
+ bytes() {
215
+ this.index += 1;
216
+ while (base64CharPattern.test(this.peek())) {
217
+ this.index += 1;
218
+ }
219
+ return this.consume(":");
220
+ }
221
+ /** A display string, `"…"` with each byte past ASCII percent-encoded as lowercase hex. */
222
+ displayString() {
223
+ if (!this.consume('"')) {
224
+ return void 0;
225
+ }
226
+ const bytes = [];
227
+ for (; ; ) {
228
+ if (this.done) {
229
+ return void 0;
230
+ }
231
+ const char = this.take();
232
+ const code = char.charCodeAt(0);
233
+ if (code < 32 || code > 126) {
234
+ return void 0;
235
+ }
236
+ if (char === '"') {
237
+ try {
238
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes));
239
+ } catch {
240
+ return void 0;
241
+ }
242
+ }
243
+ if (char === "%") {
244
+ const hex = this.take() + this.take();
245
+ if (!/^[0-9a-f]{2}$/.test(hex)) {
246
+ return void 0;
247
+ }
248
+ bytes.push(Number.parseInt(hex, 16));
249
+ continue;
250
+ }
251
+ bytes.push(code);
252
+ }
253
+ }
254
+ };
255
+ var parseList = (text) => {
256
+ const cursor = new Cursor(text);
257
+ const members = [];
258
+ cursor.skipSpaces();
259
+ while (!cursor.done) {
260
+ const member = cursor.member();
261
+ if (member === void 0) {
262
+ return void 0;
263
+ }
264
+ members.push(member);
265
+ cursor.skipWhitespace();
266
+ if (cursor.done) {
267
+ break;
268
+ }
269
+ if (!cursor.consume(",")) {
270
+ return void 0;
271
+ }
272
+ cursor.skipWhitespace();
273
+ if (cursor.done) {
274
+ return void 0;
275
+ }
276
+ }
277
+ return members;
278
+ };
279
+ var wholeNumber = (item) => item?.kind === "integer" && item.value >= 0 ? item.value : void 0;
280
+ var policyName = (member) => member.item?.kind === "string" ? member.item.value : void 0;
281
+ var parseRateLimit = (headers) => {
282
+ const policyField = headers.get("RateLimit-Policy");
283
+ const declared = policyField === null ? void 0 : parseList(policyField);
284
+ if (declared === void 0) {
285
+ return void 0;
286
+ }
287
+ const stateField = headers.get("RateLimit");
288
+ const states = /* @__PURE__ */ new Map();
289
+ for (const member of (stateField === null ? void 0 : parseList(stateField)) ?? []) {
290
+ const name = policyName(member);
291
+ if (name !== void 0 && !states.has(name)) {
292
+ states.set(name, member);
293
+ }
294
+ }
295
+ const policies = [];
296
+ for (const member of declared) {
297
+ const name = policyName(member);
298
+ const quota = wholeNumber(member.parameters.get("q"));
299
+ if (name === void 0 || quota === void 0) {
300
+ continue;
301
+ }
302
+ const state = states.get(name)?.parameters;
303
+ policies.push({
304
+ name,
305
+ quota,
306
+ remaining: wholeNumber(state?.get("r")),
307
+ resetSeconds: wholeNumber(state?.get("t")),
308
+ windowSeconds: wholeNumber(member.parameters.get("w"))
309
+ });
310
+ }
311
+ return policies.length === 0 ? void 0 : { policies };
312
+ };
313
+
314
+ // src/core/rules/errors.ts
315
+ var MountayaError = class extends Error {
316
+ name = "MountayaError";
317
+ /**
318
+ * The `Idempotency-Key` the call that raised this error fixed for its attempts, the caller's own
319
+ * or the one the client drew for it, and undefined where it fixed none: a read, an operation
320
+ * that declares no key, a call whose own arguments were refused, and a runtime with no
321
+ * cryptographic random source. The key is fixed before the first attempt, so a call whose
322
+ * credential its first attempt refused, or whose wait for a first session token ran out,
323
+ * carries it too.
324
+ *
325
+ * A write that carried one may have been made whatever the error says: an answer that never
326
+ * arrived, a 5xx and a body that broke off do not tell. Send the same call again with this key
327
+ * as its `idempotencyKey`, never a new one: the API answers a key it has seen with the answer it
328
+ * kept, or runs the write where it made none, so the write is made once. A new key is a new
329
+ * write, made a second time where the first one landed.
330
+ */
331
+ idempotencyKey;
332
+ // The constructor narrows the signature rather than adding behaviour: `Error`'s `message`
333
+ // is optional and this family's is not. Dropping it makes
334
+ // `new MountayaConfigurationError()` compile, which is a thrown value carrying nothing a
335
+ // caller can read.
336
+ /**
337
+ * @param message - what went wrong and what to do about it, naming the call where there is one.
338
+ * @param options - the standard error options, for the `cause` behind it, and the
339
+ * `idempotencyKey` the call sent, where it sent one.
340
+ */
341
+ constructor(message, options) {
342
+ super(message, options);
343
+ this.idempotencyKey = options?.idempotencyKey;
344
+ }
345
+ };
346
+ var MountayaConfigurationError = class extends MountayaError {
347
+ name = "MountayaConfigurationError";
348
+ };
349
+ var describeType = (value) => {
350
+ if (value === null || value === void 0) {
351
+ return String(value);
352
+ }
353
+ const type = Array.isArray(value) ? "array" : typeof value;
354
+ return /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
355
+ };
356
+ var describeValue = (value) => {
357
+ if (typeof value === "string") {
358
+ return JSON.stringify(value);
359
+ }
360
+ try {
361
+ return String(value);
362
+ } catch {
363
+ return describeType(value);
364
+ }
365
+ };
366
+ var refuseOption = (path, value, remedy, context) => new MountayaConfigurationError(
367
+ `${context === void 0 ? "" : `${context}: `}${path} is ${describeValue(value)}; ${remedy}`
368
+ );
369
+ var MountayaConnectionError = class extends MountayaError {
370
+ name = "MountayaConnectionError";
371
+ /**
372
+ * @param message - the call, and which transport failure it met where the transport can tell.
373
+ * @param cause - the runtime's own failure, carried on `Error.cause`.
374
+ * @param idempotencyKey - the `Idempotency-Key` the call sent, where it sent one.
375
+ */
376
+ constructor(message, cause, idempotencyKey) {
377
+ super(message, { cause, idempotencyKey });
378
+ }
379
+ };
380
+ var MountayaApiError = class extends MountayaError {
381
+ name = "MountayaApiError";
382
+ /** The HTTP status the response carried. */
383
+ status;
384
+ /** Every entry of the envelope, in the order the API wrote them; empty for a bodiless answer. */
385
+ errors;
386
+ /**
387
+ * The envelope's `extensions.metadata`, exactly as sent, or undefined where the response
388
+ * carried none: see {@link ErrorMetadata}.
389
+ */
390
+ metadata;
391
+ /**
392
+ * The rate-limit state the answer's `RateLimit-Policy` and `RateLimit` describe, or undefined
393
+ * where they describe none, as on every Map Studio API answer.
394
+ */
395
+ rateLimit;
396
+ /**
397
+ * The answer's `X-Request-Id`, exactly as sent: 32 lowercase hex characters the API recorded
398
+ * the request under, and the one thing to quote to support. Undefined where the answer sent
399
+ * none; the client never makes one up.
400
+ */
401
+ requestId;
402
+ /**
403
+ * How many seconds the answer asked the caller to wait before asking again, from its
404
+ * `Retry-After` header, read as whole seconds or an HTTP date; undefined where the header was
405
+ * absent or neither.
406
+ *
407
+ * Every 429 of a limit names one, the wait a spent limit asks for
408
+ * ({@link MountayaRateLimitError}); a ceiling's 429, coded `LIMIT_REACHED`, names none, since no
409
+ * wait lifts it. A 503 names one where the API knows when it can answer, and a 409 whose
410
+ * `Idempotency-Key` is still in use names the second the first request may take. The client waits each out itself where it
411
+ * repeats the call and the wait fits its `retry.maxWaitMs`; an error that arrives carrying one
412
+ * is the wait a caller schedules the next call from, and one carrying none says nothing of when.
413
+ */
414
+ retryAfter;
415
+ /**
416
+ * @param message - the message {@link failureMessage} spells for the call.
417
+ * @param status - the HTTP status the response carried.
418
+ * @param errors - the envelope's entries, the first of which classifies the response.
419
+ * @param details - the envelope's metadata, the request id, the rate-limit state and the wait
420
+ * `Retry-After` names, where the answer sent them, the `Idempotency-Key` the call sent,
421
+ * where it sent one, and the `cause` that kept the answer from being read, where one did.
422
+ */
423
+ constructor(message, status, errors, details = {}) {
424
+ super(
425
+ message,
426
+ details.cause === void 0 ? { idempotencyKey: details.idempotencyKey } : { cause: details.cause, idempotencyKey: details.idempotencyKey }
427
+ );
428
+ this.status = status;
429
+ this.errors = errors;
430
+ this.metadata = details.metadata;
431
+ this.rateLimit = details.rateLimit;
432
+ this.requestId = details.requestId;
433
+ this.retryAfter = details.retryAfter;
434
+ }
435
+ /** The classifying code of the response, taken from its first entry. */
436
+ get code() {
437
+ return this.errors[0]?.extensions?.code;
438
+ }
439
+ /** Reports whether any entry carries the given code. */
440
+ hasCode(code) {
441
+ return this.errors.some((entry) => entry.extensions?.code === code);
442
+ }
443
+ };
444
+ var MountayaBadRequestError = class extends MountayaApiError {
445
+ name = "MountayaBadRequestError";
446
+ };
447
+ var MountayaAuthenticationError = class extends MountayaApiError {
448
+ name = "MountayaAuthenticationError";
449
+ };
450
+ var MountayaBillingError = class extends MountayaApiError {
451
+ name = "MountayaBillingError";
452
+ };
453
+ var MountayaForbiddenError = class extends MountayaApiError {
454
+ name = "MountayaForbiddenError";
455
+ };
456
+ var MountayaNotFoundError = class extends MountayaApiError {
457
+ name = "MountayaNotFoundError";
458
+ };
459
+ var MountayaMethodNotAllowedError = class extends MountayaApiError {
460
+ name = "MountayaMethodNotAllowedError";
461
+ };
462
+ var MountayaConflictError = class extends MountayaApiError {
463
+ // Typed as a string rather than as its literal, so each subclass can declare its own.
464
+ name = "MountayaConflictError";
465
+ };
466
+ var KEY_IN_USE_CODE = "IDEMPOTENCY_KEY_IN_USE";
467
+ var CEILING_CODE = "LIMIT_REACHED";
468
+ var MountayaIdempotencyKeyInUseError = class extends MountayaConflictError {
469
+ name = "MountayaIdempotencyKeyInUseError";
470
+ };
471
+ var IDEMPOTENT_ANSWER_UNAVAILABLE_CODE = "IDEMPOTENCY_ANSWER_UNAVAILABLE";
472
+ var MountayaIdempotentAnswerUnavailableError = class extends MountayaConflictError {
473
+ name = "MountayaIdempotentAnswerUnavailableError";
474
+ /** What the write's first answer was, as the metadata states it: see {@link IdempotentAnswer}. */
475
+ answer;
476
+ /**
477
+ * @param message - the message {@link failureMessage} spells for the call.
478
+ * @param status - the HTTP status the response carried, which is 409.
479
+ * @param errors - the envelope's entries, the first of which is coded
480
+ * `IDEMPOTENCY_ANSWER_UNAVAILABLE`.
481
+ * @param details - what the answer sent beside them, the first answer at `metadata` included.
482
+ */
483
+ constructor(message, status, errors, details = {}) {
484
+ super(message, status, errors, details);
485
+ const { etag: taggedAs, location: createdAt, status: answeredWith } = details.metadata ?? {};
486
+ this.answer = {
487
+ etag: typeof taggedAs === "string" ? taggedAs : void 0,
488
+ location: typeof createdAt === "string" ? createdAt : void 0,
489
+ status: typeof answeredWith === "number" && Number.isInteger(answeredWith) ? answeredWith : void 0
490
+ };
491
+ }
492
+ };
493
+ var MountayaPreconditionFailedError = class extends MountayaApiError {
494
+ name = "MountayaPreconditionFailedError";
495
+ /**
496
+ * The tag the resource carries now, from the 412's `ETag`, exactly as sent, or undefined where
497
+ * the answer carried none. It is what the resource was changed to, not what the caller has read:
498
+ * read the resource again before a write names it as its `ifMatch`, so the write is decided
499
+ * against what it holds.
500
+ */
501
+ etag;
502
+ /**
503
+ * @param message - the message {@link failureMessage} spells for the call.
504
+ * @param status - the HTTP status the response carried, which is 412.
505
+ * @param errors - the envelope's entries, the first of which classifies the response.
506
+ * @param details - what the answer sent beside them, its `ETag` included.
507
+ */
508
+ constructor(message, status, errors, details = {}) {
509
+ super(message, status, errors, details);
510
+ this.etag = details.etag;
511
+ }
512
+ };
513
+ var MountayaPayloadTooLargeError = class extends MountayaApiError {
514
+ name = "MountayaPayloadTooLargeError";
515
+ };
516
+ var MountayaRateLimitError = class extends MountayaApiError {
517
+ name = "MountayaRateLimitError";
518
+ };
519
+ var MountayaServerError = class extends MountayaApiError {
520
+ name = "MountayaServerError";
521
+ };
522
+ var MOUNTAYA_API_ERROR_NAMES = [
523
+ "MountayaApiError",
524
+ "MountayaAuthenticationError",
525
+ "MountayaBadRequestError",
526
+ "MountayaBillingError",
527
+ "MountayaConflictError",
528
+ "MountayaDataError",
529
+ "MountayaForbiddenError",
530
+ "MountayaIdempotencyKeyInUseError",
531
+ "MountayaIdempotentAnswerUnavailableError",
532
+ "MountayaMethodNotAllowedError",
533
+ "MountayaNotFoundError",
534
+ "MountayaPayloadTooLargeError",
535
+ "MountayaPreconditionFailedError",
536
+ "MountayaRateLimitError",
537
+ "MountayaServerError"
538
+ ];
539
+ var MOUNTAYA_ERROR_NAMES = [
540
+ ...MOUNTAYA_API_ERROR_NAMES,
541
+ "MountayaConfigurationError",
542
+ "MountayaConnectionError",
543
+ "MountayaError",
544
+ "MountayaSelectionError",
545
+ "MountayaWebhookSignatureError",
546
+ "SseBufferOverflowError"
547
+ ];
548
+ var declaresName = (value, names) => typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && names.includes(value.name);
549
+ var isMountayaError = (error) => declaresName(error, MOUNTAYA_ERROR_NAMES);
550
+ var isMountayaApiError = (error) => declaresName(error, MOUNTAYA_API_ERROR_NAMES) && "status" in error && typeof error.status === "number" && "errors" in error && Array.isArray(error.errors) && error.errors.every((entry) => typeof entry === "object" && entry !== null) && "hasCode" in error && typeof error.hasCode === "function";
551
+ var isErrorEntry = (entry) => typeof entry === "object" && entry !== null && "message" in entry && typeof entry.message === "string";
552
+ var errorsOf = (body) => typeof body === "object" && body !== null && "errors" in body ? body.errors : void 0;
553
+ var entriesOf = (body) => {
554
+ const errors = errorsOf(body);
555
+ return Array.isArray(errors) ? errors.filter(isErrorEntry) : [];
556
+ };
557
+ var isMetadata = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
558
+ var metadataOf = (body) => {
559
+ if (typeof body !== "object" || body === null || !("extensions" in body)) {
560
+ return void 0;
561
+ }
562
+ const { extensions } = body;
563
+ if (typeof extensions !== "object" || extensions === null || !("metadata" in extensions)) {
564
+ return void 0;
565
+ }
566
+ const { metadata } = extensions;
567
+ return isMetadata(metadata) ? metadata : void 0;
568
+ };
569
+ var BILLING_STEP = "The API's message says which applies: a product of the organization's agreement is changed with Mountaya (https://mountaya.com/en/contact/), and a missing payment method is added, or an invoice still owed paid, in the organization's billing settings.";
570
+ var CEILING_STEP = "No wait lifts a ceiling, so this call is not repeated: free a place in what the error's metadata names, or change the organization's agreement with Mountaya (https://mountaya.com/en/contact/) where it sets that ceiling.";
571
+ var secondsSpelled = (count) => `${count} ${count === 1 ? "second" : "seconds"}`;
572
+ var momentAfter = (seconds) => {
573
+ const end = new Date(Date.now() + seconds * 1e3);
574
+ return Number.isNaN(end.getTime()) ? void 0 : end.toISOString().replace(/\.\d{3}Z$/, "Z");
575
+ };
576
+ var monthlyAllowanceStep = (retryAfterSeconds) => {
577
+ const moment = retryAfterSeconds === void 0 ? void 0 : momentAfter(retryAfterSeconds);
578
+ const when = retryAfterSeconds === void 0 || retryAfterSeconds === 0 ? "" : ` in ${secondsSpelled(retryAfterSeconds)}${moment === void 0 ? "" : ` (at ${moment})`}`;
579
+ return `The organization's monthly allowance on this API is spent: it renews when the next billing period begins${when}, so this call is not repeated before then. A larger allowance is set in the organization's agreement with Mountaya (https://mountaya.com/en/contact/).`;
580
+ };
581
+ var spendsMonthlyAllowance = (rateLimit) => {
582
+ const policies = rateLimit?.policies ?? [];
583
+ return policies.some((policy) => policy.name === "month" && policy.remaining === 0) && policies.every((policy) => policy.name === "month" || policy.remaining !== 0);
584
+ };
585
+ var CREDENTIAL_STEP = "Check the credential this client sends: a key that is unknown, rotated or disabled, and a session token that has expired, are refused.";
586
+ var MEMBER_SESSION_STEP = "This call acts as the user its session token was minted for, so mint the token with postSession's user_id set to that user.";
587
+ var SECRET_KEY_STEP = "Check the secret key this client sends: one that is unknown, revoked or malformed, or one of a canceled organization, is refused.";
588
+ var FORBIDDEN_STEP = "Check that the key carries the scope this call needs, that the resource belongs to the key's organization, and that the page calling is one the organization allows.";
589
+ var ACTING_USER_STEP = "This call acts as the user its session token names (postSession's user_id), who must be a member of the key's organization holding the role the call asks.";
590
+ var MINT_REFUSAL_STEP = "Check that the publishable key in the body is one this secret key's organization issued, and that user_id names a member of that organization or a user holding an invitation to it.";
591
+ var PRECONDITION_STEP = "The resource changed since the etag this write names was read: read it again, and decide what the write should be now.";
592
+ var IDEMPOTENT_ANSWER_STEP = "The write was made, and its answer cannot be given again: read the resource again rather than sending the write once more.";
593
+ var KEY_IN_USE_STEP = "The first request with this Idempotency-Key is still running: send the same call again with the error's idempotencyKey, never a new key, which would make the write twice.";
594
+ var MINT_LIMIT_STEP = "Minting is limited per secret key, per client IP address and secret key whose requests keep failing, and per user_id it refuses, so check the publishable key and the user_id before asking again.";
595
+ var nextStepFor = (status, code, retryAfterSeconds, monthlyAllowanceSpent, declaration) => {
596
+ const mints = declaration.requiresSecretKey === true;
597
+ const actsAsMember = declaration.actsAsMember === true;
598
+ switch (status) {
599
+ case 401:
600
+ if (mints) {
601
+ return SECRET_KEY_STEP;
602
+ }
603
+ return actsAsMember ? `${CREDENTIAL_STEP} ${MEMBER_SESSION_STEP}` : CREDENTIAL_STEP;
604
+ case 402:
605
+ return BILLING_STEP;
606
+ case 403:
607
+ if (mints) {
608
+ return MINT_REFUSAL_STEP;
609
+ }
610
+ return actsAsMember ? `${FORBIDDEN_STEP} ${ACTING_USER_STEP}` : FORBIDDEN_STEP;
611
+ case 409:
612
+ return code === IDEMPOTENT_ANSWER_UNAVAILABLE_CODE ? IDEMPOTENT_ANSWER_STEP : code === KEY_IN_USE_CODE ? KEY_IN_USE_STEP : void 0;
613
+ case 412:
614
+ return PRECONDITION_STEP;
615
+ case 429: {
616
+ if (code === CEILING_CODE) {
617
+ return CEILING_STEP;
618
+ }
619
+ if (monthlyAllowanceSpent) {
620
+ return monthlyAllowanceStep(retryAfterSeconds);
621
+ }
622
+ const wait = retryAfterSeconds === void 0 || retryAfterSeconds === 0 ? "Wait before calling again." : `Wait ${secondsSpelled(retryAfterSeconds)} before calling again.`;
623
+ return mints ? `${wait} ${MINT_LIMIT_STEP}` : wait;
624
+ }
625
+ default:
626
+ return void 0;
627
+ }
628
+ };
629
+ var failureMessage = (context, status, entries, facts = {}) => {
630
+ const first = entries[0] ?? {};
631
+ const parts = [status, first.extensions?.code, first.message].map(
632
+ (part) => typeof part === "string" ? part.trim() : typeof part === "number" ? String(part) : ""
633
+ ).filter((part) => part !== "");
634
+ const summary = parts.length === 0 ? context : `${context}: ${parts.join(" ")}`;
635
+ const next = status === void 0 ? void 0 : nextStepFor(
636
+ status,
637
+ first.extensions?.code,
638
+ facts.retryAfterSeconds,
639
+ spendsMonthlyAllowance(facts.rateLimit),
640
+ facts.declaration ?? {}
641
+ );
642
+ const sentence = next === void 0 ? summary : `${/[.!?]$/.test(summary) ? summary : `${summary}.`} ${next}`;
643
+ return facts.requestId === void 0 ? sentence : `${sentence} (request ${facts.requestId})`;
644
+ };
645
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
646
+ var delaySecondsPattern = /^[ \t]*(\d+)[ \t]*$/;
647
+ var MAX_DELAY_SECONDS_COUNT = 9223372036854775807n;
648
+ var imfFixdatePattern = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) ([A-Z][a-z]{2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
649
+ var rfc850DatePattern = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-([A-Z][a-z]{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
650
+ var asctimeDatePattern = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) ([A-Z][a-z]{2}) ([ \d]\d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/;
651
+ var utcInstant = (year, month, day, hour, minute, second) => {
652
+ const monthIndex = MONTHS.indexOf(month);
653
+ if (monthIndex < 0 || hour > 23 || minute > 59 || second > 60) {
654
+ return void 0;
655
+ }
656
+ const midnight = /* @__PURE__ */ new Date(0);
657
+ midnight.setUTCFullYear(year, monthIndex, day);
658
+ if (midnight.getUTCMonth() !== monthIndex || midnight.getUTCDate() !== day) {
659
+ return void 0;
660
+ }
661
+ return midnight.getTime() + ((hour * 60 + minute) * 60 + second) * 1e3;
662
+ };
663
+ var httpDate = (value, now) => {
664
+ const fixdate = imfFixdatePattern.exec(value);
665
+ if (fixdate !== null) {
666
+ const [, day, month, year, hour, minute, second] = fixdate;
667
+ return utcInstant(
668
+ Number(year),
669
+ month ?? "",
670
+ Number(day),
671
+ Number(hour),
672
+ Number(minute),
673
+ Number(second)
674
+ );
675
+ }
676
+ const rfc850 = rfc850DatePattern.exec(value);
677
+ if (rfc850 !== null) {
678
+ const [, day, month, shortYear, hour, minute, second] = rfc850;
679
+ const currentYear = new Date(now).getUTCFullYear();
680
+ const sameDigits = currentYear - currentYear % 100 + Number(shortYear);
681
+ const year = sameDigits > currentYear + 50 ? sameDigits - 100 : sameDigits;
682
+ return utcInstant(year, month ?? "", Number(day), Number(hour), Number(minute), Number(second));
683
+ }
684
+ const asctime = asctimeDatePattern.exec(value);
685
+ if (asctime !== null) {
686
+ const [, month, day, hour, minute, second, year] = asctime;
687
+ return utcInstant(
688
+ Number(year),
689
+ month ?? "",
690
+ Number(day),
691
+ Number(hour),
692
+ Number(minute),
693
+ Number(second)
694
+ );
695
+ }
696
+ return void 0;
697
+ };
698
+ var parseRetryAfter = (header, now = Date.now) => {
699
+ if (header === null) {
700
+ return void 0;
701
+ }
702
+ const digits = delaySecondsPattern.exec(header)?.[1];
703
+ if (digits !== void 0) {
704
+ if (BigInt(digits) > MAX_DELAY_SECONDS_COUNT) {
705
+ return void 0;
706
+ }
707
+ return Math.min(Number(digits), Number.MAX_SAFE_INTEGER);
708
+ }
709
+ const current = now();
710
+ const instant = httpDate(header.replace(/^[ \t]+|[ \t]+$/g, ""), current);
711
+ return instant === void 0 ? void 0 : Math.max(0, Math.ceil((instant - current) / 1e3));
712
+ };
713
+ var answerDetailsOf = (headers) => {
714
+ const requestId = headers.get("X-Request-Id")?.trim();
715
+ return {
716
+ rateLimit: parseRateLimit(headers),
717
+ requestId: requestId === void 0 || requestId === "" ? void 0 : requestId
718
+ };
719
+ };
720
+ var errorOfBody = (body, answer, context, declaration, idempotencyKey) => {
721
+ const entries = entriesOf(body);
722
+ const retryAfterSeconds = parseRetryAfter(answer.headers.get("Retry-After"));
723
+ const details = answerDetailsOf(answer.headers);
724
+ return errorForStatus(
725
+ failureMessage(context, answer.status, entries, {
726
+ declaration,
727
+ rateLimit: details.rateLimit,
728
+ requestId: details.requestId,
729
+ retryAfterSeconds
730
+ }),
731
+ answer.status,
732
+ entries,
733
+ {
734
+ ...details,
735
+ etag: answer.headers.get("ETag") ?? void 0,
736
+ idempotencyKey,
737
+ metadata: metadataOf(body),
738
+ retryAfter: retryAfterSeconds
739
+ }
740
+ );
741
+ };
742
+ var errorFromResponse = async (response, context, declaration, idempotencyKey) => errorOfBody(
743
+ await response.json().catch(() => void 0),
744
+ response,
745
+ context,
746
+ declaration,
747
+ idempotencyKey
748
+ );
749
+ var errorFromBody = (text, answer, context, declaration, idempotencyKey) => {
750
+ let body;
751
+ try {
752
+ body = JSON.parse(text);
753
+ } catch {
754
+ body = void 0;
755
+ }
756
+ return errorOfBody(body, answer, context, declaration, idempotencyKey);
757
+ };
758
+ var errorForStatus = (message, status, entries = [], details = {}) => {
759
+ const { etag, ...rest } = details;
760
+ const args = [message, status, entries, rest];
761
+ switch (status) {
762
+ case 400:
763
+ return new MountayaBadRequestError(...args);
764
+ case 401:
765
+ return new MountayaAuthenticationError(...args);
766
+ case 402:
767
+ return new MountayaBillingError(...args);
768
+ case 403:
769
+ return new MountayaForbiddenError(...args);
770
+ case 404:
771
+ return new MountayaNotFoundError(...args);
772
+ case 405:
773
+ return new MountayaMethodNotAllowedError(...args);
774
+ case 409:
775
+ switch (entries[0]?.extensions?.code) {
776
+ case IDEMPOTENT_ANSWER_UNAVAILABLE_CODE:
777
+ return new MountayaIdempotentAnswerUnavailableError(...args);
778
+ case KEY_IN_USE_CODE:
779
+ return new MountayaIdempotencyKeyInUseError(...args);
780
+ default:
781
+ return new MountayaConflictError(...args);
782
+ }
783
+ case 412:
784
+ return new MountayaPreconditionFailedError(message, status, entries, { ...rest, etag });
785
+ case 413:
786
+ return new MountayaPayloadTooLargeError(...args);
787
+ case 429:
788
+ return new MountayaRateLimitError(...args);
789
+ default:
790
+ return status >= 500 ? new MountayaServerError(...args) : new MountayaApiError(...args);
791
+ }
792
+ };
793
+
794
+ // src/rest/dates.gen.ts
795
+ var agentRunDates = { created_at: true };
796
+ var collabCollectionChangedEventDates = { occurred_at: true };
797
+ var collabItineraryChangedEventDates = { occurred_at: true };
798
+ var collabMemberDates = { connected_at: true };
799
+ var collabPresenceJoinEventDates = { connected_at: true };
800
+ var collabPresenceSnapshotEventDates = { members: [collabMemberDates] };
801
+ var collabSegmentChangedEventDates = { occurred_at: true };
802
+ var collabWaypointChangedEventDates = { occurred_at: true };
803
+ var collabZoneChangedEventDates = { occurred_at: true };
804
+ var collabStreamEventDatesByType = { "collection.changed": collabCollectionChangedEventDates, "itinerary.changed": collabItineraryChangedEventDates, "presence.join": collabPresenceJoinEventDates, "presence.snapshot": collabPresenceSnapshotEventDates, "segment.changed": collabSegmentChangedEventDates, "waypoint.changed": collabWaypointChangedEventDates, "zone.changed": collabZoneChangedEventDates };
805
+
806
+ // src/rest/operations.gen.ts
807
+ var postAgentRun = (transport, args, options) => transport.request({
808
+ actsAsMember: true,
809
+ body: args.body,
810
+ dates: { data: agentRunDates },
811
+ idempotencyKey: args.idempotencyKey,
812
+ idempotent: false,
813
+ method: "POST",
814
+ operationId: "postAgentRun",
815
+ path: "/v1/agent/runs",
816
+ requiresSession: true,
817
+ retry: options?.retry,
818
+ serverBudgetMs: 3e4,
819
+ signal: options?.signal,
820
+ surface: "rest",
821
+ takesIdempotencyKey: true,
822
+ timeoutMs: options?.timeoutMs
823
+ });
824
+ var postAgentRunInput = (transport, args, options) => transport.request({
825
+ actsAsMember: true,
826
+ body: args.body,
827
+ idempotencyKey: args.idempotencyKey,
828
+ idempotent: false,
829
+ method: "POST",
830
+ operationId: "postAgentRunInput",
831
+ path: `/v1/agent/runs/${encodeURIComponent(String(args.run_id))}/input`,
832
+ requiresSession: true,
833
+ retry: options?.retry,
834
+ serverBudgetMs: 3e4,
835
+ signal: options?.signal,
836
+ surface: "rest",
837
+ takesIdempotencyKey: true,
838
+ timeoutMs: options?.timeoutMs
839
+ });
840
+ var postItineraryCollab = (transport, args, options) => transport.request({
841
+ actsAsMember: true,
842
+ body: args.body,
843
+ idempotent: true,
844
+ method: "POST",
845
+ operationId: "postItineraryCollab",
846
+ path: `/v1/itineraries/${encodeURIComponent(String(args.itinerary_id))}/collab`,
847
+ requiresSession: true,
848
+ retry: options?.retry,
849
+ serverBudgetMs: 3e4,
850
+ signal: options?.signal,
851
+ surface: "rest",
852
+ timeoutMs: options?.timeoutMs
853
+ });
854
+ var postZoneCollab = (transport, args, options) => transport.request({
855
+ actsAsMember: true,
856
+ body: args.body,
857
+ idempotent: true,
858
+ method: "POST",
859
+ operationId: "postZoneCollab",
860
+ path: `/v1/zones/${encodeURIComponent(String(args.zone_id))}/collab`,
861
+ requiresSession: true,
862
+ retry: options?.retry,
863
+ serverBudgetMs: 3e4,
864
+ signal: options?.signal,
865
+ surface: "rest",
866
+ timeoutMs: options?.timeoutMs
867
+ });
868
+
869
+ // src/core/rules/headerValue.ts
870
+ var printableAsciiPattern = /^[\x20-\x7e]*$/;
871
+ var isHeaderValue = (value) => printableAsciiPattern.test(value);
872
+
873
+ // src/core/rules/dates.ts
874
+ var isoDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;
875
+ var ISO_DATE_MIN_LENGTH = 20;
876
+ var ISO_DATE_SEPARATOR = 84;
877
+ var MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
878
+ var isLeapYear = (year) => year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
879
+ var daysIn = (year, month) => month === 2 && isLeapYear(year) ? 29 : MONTH_DAYS[month - 1] ?? 0;
880
+ var instantOf = (value) => {
881
+ if (value.length < ISO_DATE_MIN_LENGTH || value.charCodeAt(10) !== ISO_DATE_SEPARATOR) {
882
+ return void 0;
883
+ }
884
+ const fields = isoDate.exec(value);
885
+ if (fields === null) {
886
+ return void 0;
887
+ }
888
+ const field = (index) => Number(fields[index] ?? 0);
889
+ const year = field(1);
890
+ const month = field(2);
891
+ const day = field(3);
892
+ const named = month >= 1 && month <= 12 && day >= 1 && day <= daysIn(year, month) && field(4) <= 23 && field(5) <= 59 && field(6) <= 59 && field(7) <= 23 && field(8) <= 59;
893
+ if (!named) {
894
+ return void 0;
895
+ }
896
+ const instant = new Date(value);
897
+ return Number.isNaN(instant.getTime()) ? void 0 : instant;
898
+ };
899
+ var isListMask = (mask) => Array.isArray(mask);
900
+ var isList = (value) => Array.isArray(value);
901
+ var decodeDates = (value, mask, field = "the answer") => {
902
+ if (mask === void 0) {
903
+ return value;
904
+ }
905
+ if (mask === true) {
906
+ if (typeof value !== "string") {
907
+ return value;
908
+ }
909
+ const instant = instantOf(value);
910
+ if (instant === void 0) {
911
+ throw new MountayaError(
912
+ `${field}, which the contract declares an instant, holds a string that names none: an instant is a full ISO 8601 timestamp carrying its zone.`
913
+ );
914
+ }
915
+ return instant;
916
+ }
917
+ if (isListMask(mask)) {
918
+ if (isList(value)) {
919
+ const [element] = mask;
920
+ for (let index = 0; index < value.length; index += 1) {
921
+ value[index] = decodeDates(value[index], element, field);
922
+ }
923
+ }
924
+ return value;
925
+ }
926
+ if (typeof value === "object" && value !== null && !isList(value)) {
927
+ for (const [member, memberMask] of Object.entries(mask)) {
928
+ if (Object.hasOwn(value, member)) {
929
+ const current = Reflect.get(value, member);
930
+ const decoded = decodeDates(current, memberMask, member);
931
+ if (decoded !== current) {
932
+ Reflect.set(value, member, decoded);
933
+ }
934
+ }
935
+ }
936
+ }
937
+ return value;
938
+ };
939
+ var parseJsonWithDates = (text, mask) => text.length > 0 ? decodeDates(JSON.parse(text), mask) : void 0;
940
+
941
+ // src/core/rules/retry.ts
942
+ var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
943
+ var namedError = (name, message) => typeof DOMException === "function" ? new DOMException(message, name) : Object.assign(new Error(message), { name });
944
+ var abortReasonOf = (signal) => signal.reason ?? namedError("AbortError", "This operation was aborted");
945
+
946
+ // src/core/rules/responseBody.ts
947
+ var REFUSAL_WAIT_MS = 5e3;
948
+ var MAX_REFUSAL_BYTES = 64 * 1024;
949
+ var isAborted = (signal) => signal.aborted;
950
+ var settleOnAbort = async (work, signal) => {
951
+ if (signal === void 0) {
952
+ return work();
953
+ }
954
+ if (isAborted(signal)) {
955
+ throw abortReasonOf(signal);
956
+ }
957
+ let stopWatching = () => {
958
+ };
959
+ const aborted = new Promise((_resolve, reject) => {
960
+ const onAbort = () => {
961
+ reject(abortReasonOf(signal));
962
+ };
963
+ signal.addEventListener("abort", onAbort, { once: true });
964
+ stopWatching = () => {
965
+ signal.removeEventListener("abort", onAbort);
966
+ };
967
+ });
968
+ try {
969
+ const settled = await Promise.race([work(), aborted]);
970
+ if (isAborted(signal)) {
971
+ throw abortReasonOf(signal);
972
+ }
973
+ return settled;
974
+ } finally {
975
+ stopWatching();
976
+ }
977
+ };
978
+ var concat = (chunks, byteLength) => {
979
+ const bytes = new Uint8Array(byteLength);
980
+ let offset = 0;
981
+ for (const chunk of chunks) {
982
+ bytes.set(chunk, offset);
983
+ offset += chunk.byteLength;
984
+ }
985
+ return bytes;
986
+ };
987
+ var drain = async (body, bounds) => {
988
+ const { maxBytes, signal, timeoutMs } = bounds;
989
+ let reader;
990
+ try {
991
+ reader = body.getReader();
992
+ } catch (cause) {
993
+ if (signal !== void 0 && isAborted(signal)) {
994
+ throw abortReasonOf(signal);
995
+ }
996
+ return { brokeOff: { cause }, bytes: concat([], 0) };
997
+ }
998
+ const cancel = (reason) => {
999
+ reader.cancel(reason).catch(() => void 0);
1000
+ };
1001
+ const letGo = () => {
1002
+ try {
1003
+ reader.releaseLock();
1004
+ } catch {
1005
+ }
1006
+ };
1007
+ if (signal !== void 0 && isAborted(signal)) {
1008
+ cancel(abortReasonOf(signal));
1009
+ letGo();
1010
+ throw abortReasonOf(signal);
1011
+ }
1012
+ const onAbort = () => {
1013
+ if (signal !== void 0) {
1014
+ cancel(abortReasonOf(signal));
1015
+ }
1016
+ };
1017
+ signal?.addEventListener("abort", onAbort, { once: true });
1018
+ const deadline = setTimeout(cancel, timeoutMs);
1019
+ const chunks = [];
1020
+ let received = 0;
1021
+ let brokeOff;
1022
+ try {
1023
+ while (true) {
1024
+ const { done, value } = await reader.read();
1025
+ if (signal !== void 0 && isAborted(signal)) {
1026
+ throw abortReasonOf(signal);
1027
+ }
1028
+ if (done) {
1029
+ break;
1030
+ }
1031
+ received += value.byteLength;
1032
+ if (maxBytes !== void 0 && received > maxBytes) {
1033
+ chunks.length = 0;
1034
+ received = 0;
1035
+ break;
1036
+ }
1037
+ chunks.push(value);
1038
+ }
1039
+ } catch (cause) {
1040
+ if (signal !== void 0 && isAborted(signal)) {
1041
+ throw abortReasonOf(signal);
1042
+ }
1043
+ brokeOff = { cause };
1044
+ } finally {
1045
+ clearTimeout(deadline);
1046
+ signal?.removeEventListener("abort", onAbort);
1047
+ cancel();
1048
+ letGo();
1049
+ }
1050
+ return { brokeOff, bytes: concat(chunks, received) };
1051
+ };
1052
+ var streamOf = (response) => {
1053
+ const body = response.body;
1054
+ if (response.bodyUsed || body === null || body === void 0) {
1055
+ return void 0;
1056
+ }
1057
+ return typeof body.getReader === "function" ? body : void 0;
1058
+ };
1059
+ var readFailureText = async (response, signal) => {
1060
+ const body = streamOf(response);
1061
+ if (body === void 0) {
1062
+ return settleOnAbort(() => response.text().catch(() => ""), signal);
1063
+ }
1064
+ const { bytes } = await drain(body, {
1065
+ maxBytes: MAX_REFUSAL_BYTES,
1066
+ signal,
1067
+ timeoutMs: REFUSAL_WAIT_MS
1068
+ });
1069
+ return new TextDecoder().decode(bytes);
1070
+ };
1071
+ var readFailure = async (response, call) => {
1072
+ const declaration = {
1073
+ actsAsMember: call.actsAsMember,
1074
+ requiresSecretKey: call.requiresSecretKey
1075
+ };
1076
+ if (streamOf(response) === void 0) {
1077
+ return settleOnAbort(
1078
+ () => errorFromResponse(response, call.operationId, declaration, call.idempotencyKey),
1079
+ call.signal
1080
+ );
1081
+ }
1082
+ return errorFromBody(
1083
+ await readFailureText(response, call.signal),
1084
+ response,
1085
+ call.operationId,
1086
+ declaration,
1087
+ call.idempotencyKey
1088
+ );
1089
+ };
1090
+
1091
+ // src/events/rules/sse.ts
1092
+ var BYTE_ORDER_MARK = "\uFEFF";
1093
+ var MAX_SSE_BUFFER_CHARS = 8 * 1024 * 1024;
1094
+ var SseBufferOverflowError = class extends MountayaError {
1095
+ // The family's spelling, and not `this.name = …` in the constructor: every class here
1096
+ // declares its name as a string LITERAL on the class, because an identifier is what a
1097
+ // consumer's minifier renames and data is what survives it. `errors.test.ts` derives that
1098
+ // rule from the barrel, and this class is on it.
1099
+ name = "SseBufferOverflowError";
1100
+ /** The cap the parser enforced, in UTF-16 code units. */
1101
+ limit;
1102
+ /**
1103
+ * Builds the error a parser throws once its unterminated record passes the cap.
1104
+ *
1105
+ * @param limit - the cap the parser enforced, in UTF-16 code units.
1106
+ * @param operationId - the operation whose stream overflowed, where the thrower knows it: the
1107
+ * message then opens with it and ends with what a reopen would meet.
1108
+ * @param options - the standard error options, for the `cause` an opener hands on.
1109
+ */
1110
+ constructor(limit, operationId, options) {
1111
+ const overflow = `sse frame parser: unterminated frame exceeded ${limit} characters`;
1112
+ super(
1113
+ operationId === void 0 ? overflow : `${operationId}: ${overflow}. The producer never ended the record, and a reopen meets it again.`,
1114
+ options
1115
+ );
1116
+ this.limit = limit;
1117
+ }
1118
+ };
1119
+ var SseFrameParser = class {
1120
+ // The unterminated line, in the pieces the pushes delivered it in, and how long they are
1121
+ // together. Joined once, when the line ends, so a long line is never copied per push.
1122
+ lineParts = [];
1123
+ lineLength = 0;
1124
+ // What the current record holds: its data lines, its event name, and its own `id:`, which is
1125
+ // undefined until it names one.
1126
+ dataLines = [];
1127
+ event = "";
1128
+ recordId;
1129
+ // The characters of the current record's completed lines, line endings included. With the
1130
+ // unterminated line, it is what the cap bounds.
1131
+ recordLength = 0;
1132
+ // The stream's last event ID, moved when a record naming an `id:` ends, and undefined until one
1133
+ // does.
1134
+ lastId;
1135
+ // No character has arrived yet, so a byte-order mark opening the next one is still dropped.
1136
+ atStart = true;
1137
+ // Whether the last character read is a CR that ended a line, so an LF arriving next completes
1138
+ // a CRLF.
1139
+ afterCarriageReturn = false;
1140
+ // Set past the cap, for good.
1141
+ overflowed = false;
1142
+ // The cap on the unterminated record, checked at construction.
1143
+ maxBufferChars;
1144
+ /**
1145
+ * Builds a parser that holds at most `maxBufferChars` of a record it has not seen the end of.
1146
+ *
1147
+ * @param maxBufferChars - bounds the unterminated record this parser holds, in UTF-16 code
1148
+ * units: a whole number of 1 or more. A consumer whose frames are known small may tighten
1149
+ * it; the shared readers take the default. A cap that is not a number of characters would
1150
+ * bound nothing (`NaN` and `Infinity` are exceeded by no length) or refuse every push (zero
1151
+ * and below), so it is refused here.
1152
+ * @default MAX_SSE_BUFFER_CHARS
1153
+ * @throws `MountayaConfigurationError` for a cap that is not a whole number of 1 or more.
1154
+ */
1155
+ constructor(maxBufferChars = MAX_SSE_BUFFER_CHARS) {
1156
+ const given = maxBufferChars;
1157
+ if (typeof given !== "number" || !Number.isInteger(given) || given < 1) {
1158
+ throw refuseOption(
1159
+ "maxBufferChars",
1160
+ given,
1161
+ `pass a whole number of characters of 1 or more, or leave it out for the default of ${MAX_SSE_BUFFER_CHARS}.`
1162
+ );
1163
+ }
1164
+ this.maxBufferChars = given;
1165
+ }
1166
+ /**
1167
+ * lastEventId is the stream's last event ID, as the HTML standard defines it: the value of the
1168
+ * latest `id:` in a record the parser has seen the end of, whatever else that record carried.
1169
+ *
1170
+ * It is the position a reconnect resumes from, sent as `Last-Event-ID`. It carries over a
1171
+ * record that names no `id:`, an empty `id:` clears it to the empty string, and an `id:` holding
1172
+ * U+0000 is ignored. An `id:` in a record still unterminated has not moved it: a reconnect
1173
+ * discards that record, so resuming past it would skip it.
1174
+ *
1175
+ * It is `undefined` until the stream names a position, where the standard starts from the empty
1176
+ * string, so a stream that names none reads apart from one that clears it. A caller resuming
1177
+ * from a position an earlier connection named keeps that position through the first and drops
1178
+ * it at the second.
1179
+ */
1180
+ get lastEventId() {
1181
+ return this.lastId;
1182
+ }
1183
+ /**
1184
+ * push feeds the next decoded text chunk and returns every frame the records it completes
1185
+ * dispatch, in stream order. What it leaves unterminated stays held for the next push, unless it
1186
+ * passes the cap: then push throws {@link SseBufferOverflowError} instead of returning, dropping
1187
+ * the frames the same chunk completed. The stream is being torn down with them, and a caller
1188
+ * that resumes re-reads from the position it last recorded.
1189
+ */
1190
+ push(chunk) {
1191
+ if (this.overflowed) {
1192
+ throw new SseBufferOverflowError(this.maxBufferChars);
1193
+ }
1194
+ const frames = [];
1195
+ let start = 0;
1196
+ if (chunk.length > 0) {
1197
+ if (this.atStart) {
1198
+ this.atStart = false;
1199
+ if (chunk.startsWith(BYTE_ORDER_MARK)) {
1200
+ start = BYTE_ORDER_MARK.length;
1201
+ }
1202
+ }
1203
+ if (this.afterCarriageReturn) {
1204
+ this.afterCarriageReturn = false;
1205
+ if (chunk.startsWith("\n", start)) {
1206
+ start += 1;
1207
+ }
1208
+ }
1209
+ }
1210
+ let carriageReturn = chunk.indexOf("\r", start);
1211
+ let lineFeed = chunk.indexOf("\n", start);
1212
+ while (carriageReturn !== -1 || lineFeed !== -1) {
1213
+ const end = carriageReturn === -1 || lineFeed !== -1 && lineFeed < carriageReturn ? lineFeed : carriageReturn;
1214
+ let next = end + 1;
1215
+ if (end === carriageReturn) {
1216
+ if (next === chunk.length) {
1217
+ this.afterCarriageReturn = true;
1218
+ } else if (chunk.startsWith("\n", next)) {
1219
+ next += 1;
1220
+ }
1221
+ }
1222
+ const line = this.completeLine(chunk.slice(start, end));
1223
+ this.recordLength += line.length + (next - end);
1224
+ const frame = this.readLine(line);
1225
+ if (frame !== null) {
1226
+ frames.push(frame);
1227
+ }
1228
+ start = next;
1229
+ if (carriageReturn !== -1 && carriageReturn < start) {
1230
+ carriageReturn = chunk.indexOf("\r", start);
1231
+ }
1232
+ if (lineFeed !== -1 && lineFeed < start) {
1233
+ lineFeed = chunk.indexOf("\n", start);
1234
+ }
1235
+ }
1236
+ if (start < chunk.length) {
1237
+ this.lineParts.push(chunk.slice(start));
1238
+ this.lineLength += chunk.length - start;
1239
+ }
1240
+ if (this.recordLength + this.lineLength > this.maxBufferChars) {
1241
+ this.lineParts = [];
1242
+ this.lineLength = 0;
1243
+ this.startRecord();
1244
+ this.overflowed = true;
1245
+ throw new SseBufferOverflowError(this.maxBufferChars);
1246
+ }
1247
+ return frames;
1248
+ }
1249
+ /**
1250
+ * completeLine joins the line held from earlier pushes with its last piece, `tail`, and starts
1251
+ * the next line empty.
1252
+ */
1253
+ completeLine(tail) {
1254
+ if (this.lineParts.length === 0) {
1255
+ return tail;
1256
+ }
1257
+ this.lineParts.push(tail);
1258
+ const line = this.lineParts.join("");
1259
+ this.lineParts = [];
1260
+ this.lineLength = 0;
1261
+ return line;
1262
+ }
1263
+ /**
1264
+ * readLine applies one complete line to the current record, and returns the frame the record
1265
+ * dispatches when the line is the empty one that ends it.
1266
+ *
1267
+ * A field line is split at its first colon, and one space after the colon is dropped: only the
1268
+ * first space is the standard's separator, and a second one is part of the value. A line with no
1269
+ * colon is its whole self as the field name, with an empty value.
1270
+ */
1271
+ readLine(line) {
1272
+ if (line === "") {
1273
+ return this.endRecord();
1274
+ }
1275
+ if (line.startsWith(":")) {
1276
+ return null;
1277
+ }
1278
+ const colon = line.indexOf(":");
1279
+ const field = colon === -1 ? line : line.slice(0, colon);
1280
+ const raw = colon === -1 ? "" : line.slice(colon + 1);
1281
+ const value = raw.startsWith(" ") ? raw.slice(1) : raw;
1282
+ if (field === "data") {
1283
+ this.dataLines.push(value);
1284
+ } else if (field === "event") {
1285
+ this.event = value;
1286
+ } else if (field === "id" && !value.includes("\0")) {
1287
+ this.recordId = value;
1288
+ }
1289
+ return null;
1290
+ }
1291
+ /**
1292
+ * endRecord closes the current record: an `id:` it named becomes the stream's last event ID,
1293
+ * and it returns the frame the record dispatches, or null for a record with no data.
1294
+ */
1295
+ endRecord() {
1296
+ const { dataLines, event, recordId } = this;
1297
+ this.startRecord();
1298
+ if (recordId !== void 0) {
1299
+ this.lastId = recordId;
1300
+ }
1301
+ if (dataLines.length === 0) {
1302
+ return null;
1303
+ }
1304
+ return { data: dataLines.join("\n"), event, id: recordId ?? "" };
1305
+ }
1306
+ /** startRecord empties the record being read, so the next line begins the next one. */
1307
+ startRecord() {
1308
+ this.dataLines = [];
1309
+ this.event = "";
1310
+ this.recordId = void 0;
1311
+ this.recordLength = 0;
1312
+ }
1313
+ };
1314
+
1315
+ // src/events/rules/eventStream.ts
1316
+ var readEventStream = async (body, onFrame, onLastEventId) => {
1317
+ const reader = body.getReader();
1318
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
1319
+ const parser = new SseFrameParser();
1320
+ let known;
1321
+ try {
1322
+ while (true) {
1323
+ const { done, value } = await reader.read();
1324
+ if (done) {
1325
+ return "ended";
1326
+ }
1327
+ for (const frame of parser.push(decoder.decode(value, { stream: true }))) {
1328
+ if (frame.id !== "") {
1329
+ known = frame.id;
1330
+ }
1331
+ const stop = await onFrame(frame);
1332
+ if (stop) {
1333
+ return "stopped";
1334
+ }
1335
+ }
1336
+ const position = parser.lastEventId;
1337
+ if (position !== void 0 && position !== known) {
1338
+ known = position;
1339
+ onLastEventId?.(position);
1340
+ }
1341
+ }
1342
+ } finally {
1343
+ reader.releaseLock();
1344
+ }
1345
+ };
1346
+
1347
+ // src/events/rules/openSseStream.ts
1348
+ var STALL_WINDOW_MS = 45e3;
1349
+ var SILENCE = /* @__PURE__ */ Symbol("silence");
1350
+ var LET_GO = /* @__PURE__ */ Symbol("let go");
1351
+ var boundSilence = (body, operationId, signal) => {
1352
+ const reader = body.getReader();
1353
+ const letGo = () => {
1354
+ try {
1355
+ reader.releaseLock();
1356
+ } catch {
1357
+ }
1358
+ };
1359
+ let endWait;
1360
+ if (signal.aborted) {
1361
+ letGo();
1362
+ } else {
1363
+ signal.addEventListener(
1364
+ "abort",
1365
+ () => {
1366
+ endWait?.(LET_GO);
1367
+ letGo();
1368
+ },
1369
+ { once: true }
1370
+ );
1371
+ }
1372
+ return new ReadableStream(
1373
+ {
1374
+ cancel: (reason) => reader.cancel(reason),
1375
+ pull: async (controller) => {
1376
+ if (signal.aborted) {
1377
+ controller.close();
1378
+ return;
1379
+ }
1380
+ let timer;
1381
+ const ended = new Promise((resolve) => {
1382
+ endWait = resolve;
1383
+ timer = setTimeout(() => resolve(SILENCE), STALL_WINDOW_MS);
1384
+ });
1385
+ try {
1386
+ const next = await Promise.race([reader.read(), ended]);
1387
+ if (next === LET_GO) {
1388
+ controller.close();
1389
+ return;
1390
+ }
1391
+ if (next === SILENCE) {
1392
+ throw new MountayaConnectionError(
1393
+ `${operationId}: the stream went silent for ${STALL_WINDOW_MS} ms, past the heartbeat every live stream carries. Reopen it from the last position it named, and check the network path to the API if it keeps going silent.`
1394
+ );
1395
+ }
1396
+ if (next.done) {
1397
+ controller.close();
1398
+ } else {
1399
+ controller.enqueue(next.value);
1400
+ }
1401
+ } finally {
1402
+ endWait = void 0;
1403
+ clearTimeout(timer);
1404
+ if (signal.aborted) {
1405
+ letGo();
1406
+ }
1407
+ }
1408
+ }
1409
+ },
1410
+ // A read-ahead queue of none: the next chunk is asked for only when the reader asks.
1411
+ { highWaterMark: 0 }
1412
+ );
1413
+ };
1414
+ var openTimeoutOf = (timeoutMs, operationId) => {
1415
+ if (timeoutMs === void 0) {
1416
+ return STALL_WINDOW_MS;
1417
+ }
1418
+ if (Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= MAX_TIMER_DELAY_MS) {
1419
+ return timeoutMs;
1420
+ }
1421
+ throw refuseOption(
1422
+ "timeoutMs",
1423
+ timeoutMs,
1424
+ `pass a whole number of milliseconds from 1 to ${MAX_TIMER_DELAY_MS}, or leave it out to wait at most ${STALL_WINDOW_MS}.`,
1425
+ operationId
1426
+ );
1427
+ };
1428
+ var requestStream = async (options, state, declaration) => {
1429
+ const { operationId } = options;
1430
+ const openTimeout = openTimeoutOf(options.timeoutMs, operationId);
1431
+ const headers = new Headers({ Accept: "text/event-stream" });
1432
+ if (options.lastEventId) {
1433
+ const position = String(options.lastEventId);
1434
+ if (!isHeaderValue(position)) {
1435
+ throw new MountayaConfigurationError(
1436
+ `${operationId}: lastEventId holds a character no request header carries, so the stream cannot be resumed from it. Pass the position the stream named, as it named it, or leave it out to read from the start.`
1437
+ );
1438
+ }
1439
+ headers.set("Last-Event-ID", position);
1440
+ }
1441
+ const waiting = options.waitForSession?.(state.controller.signal);
1442
+ if (waiting !== void 0) {
1443
+ await waiting;
1444
+ }
1445
+ const url = typeof options.url === "function" ? options.url() : options.url;
1446
+ const init = options.applyAuth({ headers, signal: state.controller.signal }, "GET");
1447
+ let timedOut = false;
1448
+ const deadline = setTimeout(() => {
1449
+ timedOut = true;
1450
+ state.controller.abort();
1451
+ }, openTimeout);
1452
+ let response;
1453
+ try {
1454
+ response = await options.doFetch(url, init);
1455
+ } catch (cause) {
1456
+ if (state.closedByCaller) {
1457
+ throw cause;
1458
+ }
1459
+ if (timedOut) {
1460
+ throw new MountayaConnectionError(
1461
+ options.timeoutMs === void 0 ? `${operationId}: no response within ${openTimeout} ms. Check the network path to the API.` : `${operationId}: no response within ${openTimeout} ms. Raise timeoutMs for a stream that is slow to answer, or check the network path to the API.`
1462
+ );
1463
+ }
1464
+ if (isMountayaError(cause)) {
1465
+ throw cause;
1466
+ }
1467
+ throw new MountayaConnectionError(
1468
+ `${operationId}: the stream failed before a response arrived. Check the network, and that the stream's URL names a host that answers.`,
1469
+ cause
1470
+ );
1471
+ } finally {
1472
+ clearTimeout(deadline);
1473
+ }
1474
+ options.onResponse?.(response);
1475
+ if (!response.ok) {
1476
+ throw await readFailure(response, {
1477
+ ...declaration,
1478
+ operationId,
1479
+ signal: state.controller.signal
1480
+ });
1481
+ }
1482
+ const body = response.body;
1483
+ if (body === void 0) {
1484
+ throw new MountayaConfigurationError(
1485
+ `${operationId}: this runtime's fetch exposes no response body to read the stream from. Pass a fetch that streams response bodies.`
1486
+ );
1487
+ }
1488
+ if (body === null) {
1489
+ throw new MountayaConnectionError(
1490
+ `${operationId}: the ${response.status} answer carries no body, so something on the network path answered in the API's place. Check the network path to the API.`
1491
+ );
1492
+ }
1493
+ return body;
1494
+ };
1495
+ var openDeclaredSseStream = (options, declaration) => {
1496
+ const { operationId, signal } = options;
1497
+ const state = { closedByCaller: false, controller: new AbortController() };
1498
+ const close = () => {
1499
+ state.closedByCaller = true;
1500
+ state.controller.abort();
1501
+ };
1502
+ if (signal?.aborted) {
1503
+ close();
1504
+ } else {
1505
+ signal?.addEventListener("abort", close, { once: true });
1506
+ }
1507
+ let callerFault = false;
1508
+ const handle = async (frame) => {
1509
+ if (state.closedByCaller) {
1510
+ return true;
1511
+ }
1512
+ try {
1513
+ const event = options.decode(frame);
1514
+ if (event === null) {
1515
+ return false;
1516
+ }
1517
+ return await options.onFrame(event, frame.id || void 0);
1518
+ } catch (error) {
1519
+ callerFault = true;
1520
+ throw error;
1521
+ }
1522
+ };
1523
+ const report = (lastEventId) => {
1524
+ if (state.closedByCaller) {
1525
+ return;
1526
+ }
1527
+ try {
1528
+ options.onLastEventId?.(lastEventId || void 0);
1529
+ } catch (error) {
1530
+ callerFault = true;
1531
+ throw error;
1532
+ }
1533
+ };
1534
+ const read = async () => {
1535
+ const body = await requestStream(options, state, declaration);
1536
+ try {
1537
+ return await readEventStream(
1538
+ boundSilence(body, operationId, state.controller.signal),
1539
+ handle,
1540
+ report
1541
+ );
1542
+ } catch (cause) {
1543
+ if (state.closedByCaller || callerFault) {
1544
+ throw cause;
1545
+ }
1546
+ if (cause instanceof SseBufferOverflowError) {
1547
+ throw new SseBufferOverflowError(cause.limit, operationId, { cause });
1548
+ }
1549
+ if (isMountayaError(cause)) {
1550
+ throw cause;
1551
+ }
1552
+ throw new MountayaConnectionError(
1553
+ `${operationId}: the stream broke off before it ended. Reopen it from the last position it named, and check the network path to the API if it keeps breaking off.`,
1554
+ cause
1555
+ );
1556
+ }
1557
+ };
1558
+ void (async () => {
1559
+ if (state.closedByCaller) {
1560
+ return;
1561
+ }
1562
+ let settled;
1563
+ try {
1564
+ settled = { outcome: await read() };
1565
+ } catch (error) {
1566
+ settled = { error };
1567
+ }
1568
+ signal?.removeEventListener("abort", close);
1569
+ state.controller.abort();
1570
+ if (state.closedByCaller) {
1571
+ return;
1572
+ }
1573
+ if ("outcome" in settled) {
1574
+ options.onClose?.(settled.outcome);
1575
+ } else {
1576
+ options.onError?.(settled.error);
1577
+ }
1578
+ })();
1579
+ return close;
1580
+ };
1581
+ var openSseStream = (options) => openDeclaredSseStream(options, void 0);
1582
+
1583
+ // src/events/rules/agent.ts
1584
+ var agentRunEventTypes = {
1585
+ "awaiting-input": "awaiting-input",
1586
+ "budget-exhausted": "budget-exhausted",
1587
+ "checks-unmet": "checks-unmet",
1588
+ "confirm-required": "confirm-required",
1589
+ done: "done",
1590
+ error: "error",
1591
+ message: "message",
1592
+ "message-delta": "message-delta",
1593
+ reconnect: "reconnect",
1594
+ "tool-abandoned": "tool-abandoned",
1595
+ "tool-call": "tool-call",
1596
+ "tool-result": "tool-result"
1597
+ };
1598
+ var agentTerminalEventTypes = /* @__PURE__ */ new Set([
1599
+ agentRunEventTypes.done
1600
+ ]);
1601
+ var runIdFrom = (body) => {
1602
+ const id = body?.data?.id;
1603
+ return typeof id === "string" && id !== "" ? id : void 0;
1604
+ };
1605
+ var decodeAgentFrame = (frame) => {
1606
+ if (!Object.hasOwn(agentRunEventTypes, frame.event)) {
1607
+ return null;
1608
+ }
1609
+ let payload;
1610
+ try {
1611
+ payload = frame.data ? JSON.parse(frame.data) : {};
1612
+ } catch {
1613
+ return null;
1614
+ }
1615
+ if (typeof payload !== "object" || payload === null) {
1616
+ return null;
1617
+ }
1618
+ return { ...payload, type: frame.event };
1619
+ };
1620
+ var AGENT_EVENTS_OPERATION_ID = "getAgentRunEvents";
1621
+ var refuseServerToolsUnderKey = (transport, operationId, serverTools) => {
1622
+ if (serverTools === void 0 || serverTools.length === 0) {
1623
+ return;
1624
+ }
1625
+ if (transport.mapCredential.publishableKey === void 0) {
1626
+ return;
1627
+ }
1628
+ throw new MountayaConfigurationError(
1629
+ `${operationId}: a run under a publishable key calls no server tool, so server_tools must be empty. Turn routesServerTools off.`
1630
+ );
1631
+ };
1632
+ var isReconnect = (event) => event.type === agentRunEventTypes.reconnect;
1633
+ var createAgentTransport = (transport) => ({
1634
+ sendInput: async (runId, input, options) => {
1635
+ if (input.type === "manifest-update") {
1636
+ refuseServerToolsUnderKey(transport, "postAgentRunInput", input.server_tools);
1637
+ }
1638
+ await postAgentRunInput(transport, {
1639
+ body: input,
1640
+ idempotencyKey: options?.idempotencyKey,
1641
+ run_id: runId
1642
+ });
1643
+ },
1644
+ startRun: async (params, options) => {
1645
+ refuseServerToolsUnderKey(transport, "postAgentRun", params.server_tools);
1646
+ const body = await postAgentRun(transport, {
1647
+ body: params,
1648
+ idempotencyKey: options?.idempotencyKey
1649
+ });
1650
+ const runId = runIdFrom(body);
1651
+ if (runId === void 0) {
1652
+ throw new MountayaApiError("postAgentRun: 202 named no run", 202, []);
1653
+ }
1654
+ return { runId };
1655
+ },
1656
+ subscribe: (runId, handlers, options) => {
1657
+ const seam = transport.streamSeam;
1658
+ let expiresAt;
1659
+ let reconnected = false;
1660
+ return openDeclaredSseStream(
1661
+ {
1662
+ // What `getAgentRunEvents` declares, stated as its generated operation states it: its
1663
+ // only security requirement pairs the key with a session token, and the stream acts as
1664
+ // the member that token names. Stating both here is what refuses a credential carrying no
1665
+ // session token, or one a source reports as minted without `user_id`, before the open;
1666
+ // the refusal reaches onError like any other failed open. No share token reaches it, which
1667
+ // the absence of `acceptsShareToken` says.
1668
+ applyAuth: (init, method) => {
1669
+ const applied = seam.applyAuth(init, method, {
1670
+ actsAsMember: true,
1671
+ operationId: AGENT_EVENTS_OPERATION_ID,
1672
+ requiresSession: true
1673
+ });
1674
+ expiresAt = seam.sessionExpiresAt();
1675
+ return applied;
1676
+ },
1677
+ // A frame skipped is still one the stream delivered, which the subscriber is told of as it
1678
+ // is read, in order with the frames handed over.
1679
+ decode: (frame) => {
1680
+ const event = decodeAgentFrame(frame);
1681
+ if (event === null) {
1682
+ handlers.onSkippedFrame?.();
1683
+ }
1684
+ return event;
1685
+ },
1686
+ doFetch: seam.doFetch,
1687
+ lastEventId: options?.lastEventId,
1688
+ onClose: (outcome) => {
1689
+ if (outcome === "stopped") {
1690
+ handlers.onClose(reconnected ? "reconnect" : "terminal");
1691
+ return;
1692
+ }
1693
+ const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
1694
+ handlers.onClose(expired ? "reconnect" : "ended");
1695
+ },
1696
+ onError: (error) => handlers.onError(error),
1697
+ onFrame: async (event, id) => {
1698
+ if (isReconnect(event)) {
1699
+ reconnected = true;
1700
+ return true;
1701
+ }
1702
+ await handlers.onFrame({ event, id });
1703
+ return agentTerminalEventTypes.has(event.type);
1704
+ },
1705
+ onLastEventId: (lastEventId) => handlers.onLastEventId?.(lastEventId),
1706
+ onResponse: (response) => {
1707
+ seam.report(response, AGENT_EVENTS_OPERATION_ID);
1708
+ },
1709
+ operationId: AGENT_EVENTS_OPERATION_ID,
1710
+ signal: options?.signal,
1711
+ // The wait for the stream's response is the client's own per-attempt budget.
1712
+ timeoutMs: seam.timeoutMs,
1713
+ // Resolved when the open is made, so a run id the path cannot carry (an empty one, or a
1714
+ // dot segment) is refused through onError like any other failed open.
1715
+ url: () => seam.url(`/v1/agent/runs/${encodeURIComponent(runId)}/events`, AGENT_EVENTS_OPERATION_ID),
1716
+ waitForSession: (signal) => seam.waitForSession(AGENT_EVENTS_OPERATION_ID, signal)
1717
+ },
1718
+ // The same declaration the credential is stamped by, so a refused open names the step a
1719
+ // member reading their own run takes.
1720
+ { actsAsMember: true }
1721
+ );
1722
+ }
1723
+ });
1724
+
1725
+ // src/core/rules/nullMask.ts
1726
+ var isHolding = (mask) => Array.isArray(mask) && mask.length === 2 && mask[0] === true;
1727
+ var isVariants = (mask) => Array.isArray(mask) && mask.length === 2 && typeof mask[0] === "string";
1728
+ var isListMask2 = (mask) => Array.isArray(mask) && mask.length === 1;
1729
+ var isMembers = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1730
+ var withAbsentNulls = (value, mask) => {
1731
+ if (mask === void 0 || mask === true || isHolding(mask)) {
1732
+ return value;
1733
+ }
1734
+ if (isListMask2(mask)) {
1735
+ if (!Array.isArray(value)) {
1736
+ return value;
1737
+ }
1738
+ let copy2;
1739
+ for (const [index, element] of value.entries()) {
1740
+ const written = withAbsentNulls(element, mask[0]);
1741
+ if (written !== element) {
1742
+ copy2 ??= [...value];
1743
+ copy2[index] = written;
1744
+ }
1745
+ }
1746
+ return copy2 ?? value;
1747
+ }
1748
+ if (!isMembers(value)) {
1749
+ return value;
1750
+ }
1751
+ if (isVariants(mask)) {
1752
+ const [discriminator, variants] = mask;
1753
+ const variant = value[discriminator];
1754
+ return typeof variant === "string" && Object.hasOwn(variants, variant) ? withAbsentNulls(value, variants[variant]) : value;
1755
+ }
1756
+ let copy;
1757
+ for (const [member, inner] of Object.entries(mask)) {
1758
+ if (!Object.hasOwn(value, member)) {
1759
+ if (inner === true || isHolding(inner)) {
1760
+ copy ??= { ...value };
1761
+ copy[member] = null;
1762
+ }
1763
+ continue;
1764
+ }
1765
+ const held = value[member];
1766
+ const written = withAbsentNulls(held, isHolding(inner) ? inner[1] : inner);
1767
+ if (written !== held) {
1768
+ copy ??= { ...value };
1769
+ copy[member] = written;
1770
+ }
1771
+ }
1772
+ return copy ?? value;
1773
+ };
1774
+
1775
+ // src/events/rules/collabNulls.gen.ts
1776
+ var collabCursorEventNulls = { position: true };
1777
+ var collabSelectionEventNulls = { selection: true };
1778
+ var collabStreamEventNulls = ["type", { cursor: collabCursorEventNulls, selection: collabSelectionEventNulls }];
1779
+
1780
+ // src/events/rules/collab.ts
1781
+ var collabStreamEventTypes = {
1782
+ "collection.changed": "collection.changed",
1783
+ cursor: "cursor",
1784
+ "draft.clear": "draft.clear",
1785
+ "draft.update": "draft.update",
1786
+ "itinerary.changed": "itinerary.changed",
1787
+ "lock.acquired": "lock.acquired",
1788
+ "lock.released": "lock.released",
1789
+ "lock.snapshot": "lock.snapshot",
1790
+ "presence.join": "presence.join",
1791
+ "presence.leave": "presence.leave",
1792
+ "presence.snapshot": "presence.snapshot",
1793
+ reconnect: "reconnect",
1794
+ "segment.changed": "segment.changed",
1795
+ selection: "selection",
1796
+ "waypoint.changed": "waypoint.changed",
1797
+ "zone.changed": "zone.changed"
1798
+ };
1799
+ var collabEventDates = collabStreamEventDatesByType;
1800
+ var NIL_UUID = "00000000-0000-0000-0000-000000000000";
1801
+ var isTerminalStatus = (status) => status >= 400 && status < 500 && status !== 429;
1802
+ var REOPEN_REPEATS_ERROR_NAMES = [
1803
+ "MountayaConfigurationError",
1804
+ "SseBufferOverflowError"
1805
+ ];
1806
+ var holderIdOf = (metadata) => {
1807
+ const holder = metadata?.holder;
1808
+ if (typeof holder !== "object" || holder === null || !("id" in holder)) {
1809
+ return void 0;
1810
+ }
1811
+ const { id } = holder;
1812
+ return typeof id === "string" && id !== "" && id !== NIL_UUID ? id : void 0;
1813
+ };
1814
+ var decodeCollabFrame = (frame) => {
1815
+ if (!Object.hasOwn(collabStreamEventTypes, frame.event)) {
1816
+ return null;
1817
+ }
1818
+ let payload;
1819
+ try {
1820
+ payload = frame.data ? parseJsonWithDates(frame.data, collabEventDates[frame.event]) : {};
1821
+ } catch {
1822
+ return null;
1823
+ }
1824
+ if (typeof payload !== "object" || payload === null) {
1825
+ return null;
1826
+ }
1827
+ return withAbsentNulls({ ...payload, type: frame.event }, collabStreamEventNulls);
1828
+ };
1829
+ var createCollabTransport = (transport) => {
1830
+ const subscribeStream = (operationId, path, handlers, options) => {
1831
+ const seam = transport.streamSeam;
1832
+ let subscriberFault;
1833
+ const asSubscriber = (call) => {
1834
+ try {
1835
+ call();
1836
+ } catch (thrown) {
1837
+ subscriberFault = { thrown };
1838
+ throw thrown;
1839
+ }
1840
+ };
1841
+ let expiresAt;
1842
+ let userId;
1843
+ let reconnected = false;
1844
+ return openDeclaredSseStream(
1845
+ {
1846
+ // What each collaboration stream declares, stated as its generated operation states it:
1847
+ // its only security requirement pairs the key with a session token, and it acts as the
1848
+ // member that token names. Stating both here is what refuses a credential carrying no
1849
+ // session token, or one a source reports as minted without `user_id`, before the open,
1850
+ // and a share token, which no stream accepts; the refusal reaches onError below.
1851
+ applyAuth: (init, method) => {
1852
+ const applied = seam.applyAuth(init, method, {
1853
+ actsAsMember: true,
1854
+ operationId,
1855
+ requiresSession: true
1856
+ });
1857
+ expiresAt = seam.sessionExpiresAt();
1858
+ userId = seam.sessionUserId() ?? void 0;
1859
+ return applied;
1860
+ },
1861
+ // A frame skipped is still one the stream delivered, which the subscriber is told of as it
1862
+ // is read, in order with the frames handed over.
1863
+ decode: (frame) => {
1864
+ const event = decodeCollabFrame(frame);
1865
+ if (event === null) {
1866
+ asSubscriber(() => handlers.onSkippedFrame?.());
1867
+ }
1868
+ return event;
1869
+ },
1870
+ doFetch: seam.doFetch,
1871
+ lastEventId: options?.lastEventId,
1872
+ // The last record before a close can be lost on its way, so a close once the token has
1873
+ // expired is read as the `reconnect` the API would have written.
1874
+ onClose: () => {
1875
+ const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
1876
+ handlers.onClose(reconnected || expired ? "reconnect" : "ended");
1877
+ },
1878
+ // Classify the failure so a session stops its loop instead of reconnecting forever.
1879
+ // The unrecoverable faults arrive by different routes: a credential the seam refuses
1880
+ // before the open, which a reopen refuses again; a runtime whose fetch streams no body,
1881
+ // which every reopen meets again; a terminal status on the open, a 401 on the reopen
1882
+ // after a `reconnect` among them; a producer that never terminates a frame, whose read
1883
+ // the parser fails at its buffer cap, where reopening only re-buffers to the same cap
1884
+ // against the same producer; and a fault the subscriber's own `onFrame` or
1885
+ // `onLastEventId` threw, whatever it threw, since a reopen resumes from the subscriber's
1886
+ // cursor and hands the same durable frame to the same callback. Every other mid-stream
1887
+ // fault is the stream's, which a reconnect does fix.
1888
+ //
1889
+ // Read by the name each class declares rather than by constructor, so a failure a second
1890
+ // copy of this package threw is classified the same way.
1891
+ onError: (error) => {
1892
+ const terminal = subscriberFault !== void 0 && subscriberFault.thrown === error || isMountayaError(error) && REOPEN_REPEATS_ERROR_NAMES.includes(error.name) || isMountayaApiError(error) && isTerminalStatus(error.status);
1893
+ handlers.onError(error, { terminal });
1894
+ },
1895
+ onFrame: (event, id) => {
1896
+ if (event.type === collabStreamEventTypes.reconnect) {
1897
+ reconnected = true;
1898
+ return true;
1899
+ }
1900
+ asSubscriber(() => handlers.onFrame({ event, id }));
1901
+ return false;
1902
+ },
1903
+ onLastEventId: (lastEventId) => {
1904
+ asSubscriber(() => handlers.onLastEventId?.(lastEventId));
1905
+ },
1906
+ onResponse: (response) => {
1907
+ seam.report(response, operationId);
1908
+ if (response.ok) {
1909
+ asSubscriber(() => handlers.onOpen?.({ userId }));
1910
+ }
1911
+ },
1912
+ operationId,
1913
+ signal: options?.signal,
1914
+ // The wait for the stream's response is the client's own per-attempt budget.
1915
+ timeoutMs: seam.timeoutMs,
1916
+ // Resolved when the open is made, so an id the path cannot carry (an empty one, or a dot
1917
+ // segment) is refused through onError like any other failed open.
1918
+ url: () => seam.url(path, operationId),
1919
+ waitForSession: (signal) => seam.waitForSession(operationId, signal)
1920
+ },
1921
+ // The same declaration the credential is stamped by, so a refused open names the step a
1922
+ // member following the resource takes.
1923
+ { actsAsMember: true }
1924
+ );
1925
+ };
1926
+ return {
1927
+ sendSignal: async (resource, signal) => {
1928
+ try {
1929
+ if (resource.kind === "itineraries") {
1930
+ await postItineraryCollab(transport, { body: signal, itinerary_id: resource.id });
1931
+ } else {
1932
+ await postZoneCollab(transport, { body: signal, zone_id: resource.id });
1933
+ }
1934
+ } catch (error) {
1935
+ if (isMountayaApiError(error) && error.status === 409) {
1936
+ return { holderId: holderIdOf(error.metadata), ok: false };
1937
+ }
1938
+ throw error;
1939
+ }
1940
+ return { ok: true };
1941
+ },
1942
+ subscribeEditor: (resource, handlers, options) => (
1943
+ // resource.kind is a fixed collection literal, so it rides the path as-is; only the id
1944
+ // is percent-encoded.
1945
+ subscribeStream(
1946
+ resource.kind === "itineraries" ? "getItineraryEvents" : "getZoneEvents",
1947
+ `/v1/${resource.kind}/${encodeURIComponent(resource.id)}/events`,
1948
+ handlers,
1949
+ options
1950
+ )
1951
+ ),
1952
+ subscribeList: (organizationId, handlers, options) => subscribeStream(
1953
+ "getOrganizationEvents",
1954
+ `/v1/organizations/${encodeURIComponent(organizationId)}/events`,
1955
+ handlers,
1956
+ options
1957
+ )
1958
+ };
1959
+ };
1960
+
1961
+ exports.MAX_SSE_BUFFER_CHARS = MAX_SSE_BUFFER_CHARS;
1962
+ exports.SseBufferOverflowError = SseBufferOverflowError;
1963
+ exports.SseFrameParser = SseFrameParser;
1964
+ exports.agentTerminalEventTypes = agentTerminalEventTypes;
1965
+ exports.createAgentTransport = createAgentTransport;
1966
+ exports.createCollabTransport = createCollabTransport;
1967
+ exports.decodeAgentFrame = decodeAgentFrame;
1968
+ exports.decodeCollabFrame = decodeCollabFrame;
1969
+ exports.openSseStream = openSseStream;
1970
+ exports.readEventStream = readEventStream;
1971
+ //# sourceMappingURL=index.cjs.map
1972
+ //# sourceMappingURL=index.cjs.map