@mountaya/client 0.0.0-stage → 0.2.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 (97) hide show
  1. package/CHANGELOG.md +149 -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 +2895 -0
  6. package/dist/admin/index.cjs.map +1 -0
  7. package/dist/admin/index.d.cts +889 -0
  8. package/dist/admin/index.d.ts +889 -0
  9. package/dist/admin/index.js +204 -0
  10. package/dist/admin/index.js.map +1 -0
  11. package/dist/browser.cjs +5993 -0
  12. package/dist/browser.cjs.map +1 -0
  13. package/dist/browser.d.cts +70 -0
  14. package/dist/browser.d.ts +70 -0
  15. package/dist/browser.js +22 -0
  16. package/dist/browser.js.map +1 -0
  17. package/dist/chunk-CeEX7ayk.d.cts +75531 -0
  18. package/dist/chunk-CeEX7ayk.d.ts +75531 -0
  19. package/dist/chunk-Cg7Dtcb4.js +2987 -0
  20. package/dist/chunk-Cg7Dtcb4.js.map +1 -0
  21. package/dist/chunk-DJqUsgsy.d.ts +1463 -0
  22. package/dist/chunk-DNc8T5K1.js +241 -0
  23. package/dist/chunk-DNc8T5K1.js.map +1 -0
  24. package/dist/chunk-DTxzw3hu.d.cts +1463 -0
  25. package/dist/chunk-DmxQID5X.js +2289 -0
  26. package/dist/chunk-DmxQID5X.js.map +1 -0
  27. package/dist/chunk-DoZt_oIV.d.ts +3991 -0
  28. package/dist/chunk-DpJrqANO.js +11 -0
  29. package/dist/chunk-Dx8mPAdC.d.cts +3991 -0
  30. package/dist/chunk-X2ukY3ho.js +419 -0
  31. package/dist/chunk-X2ukY3ho.js.map +1 -0
  32. package/dist/events/index.cjs +1436 -0
  33. package/dist/events/index.cjs.map +1 -0
  34. package/dist/events/index.d.cts +772 -0
  35. package/dist/events/index.d.ts +772 -0
  36. package/dist/events/index.js +543 -0
  37. package/dist/events/index.js.map +1 -0
  38. package/dist/index.cjs +5992 -0
  39. package/dist/index.cjs.map +1 -0
  40. package/dist/index.d.cts +44 -0
  41. package/dist/index.d.ts +44 -0
  42. package/dist/index.js +21 -0
  43. package/dist/index.js.map +1 -0
  44. package/package.json +126 -4
  45. package/src/admin/index.ts +47 -0
  46. package/src/admin/rules/mountayaAdmin.ts +102 -0
  47. package/src/browser.ts +233 -0
  48. package/src/core/engines/sessionToken.ts +870 -0
  49. package/src/core/rules/auth.ts +1017 -0
  50. package/src/core/rules/clientHeader.ts +28 -0
  51. package/src/core/rules/dates.ts +200 -0
  52. package/src/core/rules/decode.ts +154 -0
  53. package/src/core/rules/envelope.ts +41 -0
  54. package/src/core/rules/errors.ts +1486 -0
  55. package/src/core/rules/graphql.ts +576 -0
  56. package/src/core/rules/headerValue.ts +42 -0
  57. package/src/core/rules/idempotencyKey.ts +64 -0
  58. package/src/core/rules/nullMask.ts +127 -0
  59. package/src/core/rules/nullMasks.gen.ts +428 -0
  60. package/src/core/rules/paginate.ts +316 -0
  61. package/src/core/rules/rateLimit.ts +507 -0
  62. package/src/core/rules/redaction.ts +219 -0
  63. package/src/core/rules/resourceRef.ts +110 -0
  64. package/src/core/rules/responseBody.ts +492 -0
  65. package/src/core/rules/retry.ts +386 -0
  66. package/src/core/rules/selection.ts +416 -0
  67. package/src/core/rules/sessionAnswer.ts +90 -0
  68. package/src/core/rules/sessionSchedule.ts +131 -0
  69. package/src/core/rules/sessionWait.ts +112 -0
  70. package/src/core/rules/transport.ts +2386 -0
  71. package/src/core/rules/version.gen.ts +16 -0
  72. package/src/core/rules/webAddress.ts +165 -0
  73. package/src/core/rules/webAddresses.gen.ts +30 -0
  74. package/src/data/operations.gen.ts +603 -0
  75. package/src/data/schema.gen.ts +8078 -0
  76. package/src/data/selection.gen.ts +472 -0
  77. package/src/events/index.ts +63 -0
  78. package/src/events/rules/agent.ts +439 -0
  79. package/src/events/rules/collab.ts +554 -0
  80. package/src/events/rules/collabNulls.gen.ts +17 -0
  81. package/src/events/rules/eventStream.ts +94 -0
  82. package/src/events/rules/openSseStream.ts +594 -0
  83. package/src/events/rules/sse.ts +349 -0
  84. package/src/index.ts +231 -0
  85. package/src/rest/adminOperations.gen.ts +70 -0
  86. package/src/rest/adminResources.gen.ts +138 -0
  87. package/src/rest/coreOperations.gen.ts +74 -0
  88. package/src/rest/coreResources.gen.ts +244 -0
  89. package/src/rest/dates.gen.ts +217 -0
  90. package/src/rest/operations.gen.ts +4341 -0
  91. package/src/rest/resources.gen.ts +371 -0
  92. package/src/rest/schema.gen.ts +57027 -0
  93. package/src/tiles/operations.gen.ts +206 -0
  94. package/src/tiles/schema.gen.ts +8406 -0
  95. package/src/webhooks/rules/constructWebhookEvent.ts +482 -0
  96. package/src/webhooks/rules/webhookEvent.ts +38 -0
  97. package/src/webhooks/rules/webhookEvents.gen.ts +732 -0
@@ -0,0 +1,1436 @@
1
+ "use strict";
2
+ Object.defineProperties(exports, {
3
+ __esModule: { value: true },
4
+ [Symbol.toStringTag]: { value: "Module" }
5
+ });
6
+ const digitPattern = /[0-9]/;
7
+ const alphaPattern = /[A-Za-z]/;
8
+ const lowercaseAlphaPattern = /[a-z]/;
9
+ const keyCharPattern = /[a-z0-9_.*-]/;
10
+ const tokenCharPattern = /[!#$%&'*+\-.^_`|~0-9A-Za-z:/]/;
11
+ const base64CharPattern = /[A-Za-z0-9+/=]/;
12
+ var Cursor = class {
13
+ text;
14
+ index = 0;
15
+ constructor(text) {
16
+ this.text = text;
17
+ }
18
+ get done() {
19
+ return this.index >= this.text.length;
20
+ }
21
+ peek() {
22
+ return this.text[this.index] ?? "";
23
+ }
24
+ take() {
25
+ const char = this.peek();
26
+ this.index += 1;
27
+ return char;
28
+ }
29
+ skipSpaces() {
30
+ while (this.peek() === " ") this.index += 1;
31
+ }
32
+ skipWhitespace() {
33
+ while (this.peek() === " " || this.peek() === " ") this.index += 1;
34
+ }
35
+ consume(char) {
36
+ return this.take() === char;
37
+ }
38
+ member() {
39
+ if (this.peek() === "(") {
40
+ if (!this.innerList()) return;
41
+ const parameters = this.parameters();
42
+ return parameters === void 0 ? void 0 : {
43
+ item: void 0,
44
+ parameters
45
+ };
46
+ }
47
+ const item = this.bareItem();
48
+ const parameters = item === void 0 ? void 0 : this.parameters();
49
+ return parameters === void 0 ? void 0 : {
50
+ item,
51
+ parameters
52
+ };
53
+ }
54
+ innerList() {
55
+ this.index += 1;
56
+ for (;;) {
57
+ this.skipSpaces();
58
+ if (this.peek() === ")") {
59
+ this.index += 1;
60
+ return true;
61
+ }
62
+ if (this.bareItem() === void 0 || this.parameters() === void 0) return false;
63
+ if (this.peek() !== " " && this.peek() !== ")") return false;
64
+ }
65
+ }
66
+ parameters() {
67
+ const parameters = /* @__PURE__ */ new Map();
68
+ while (this.peek() === ";") {
69
+ this.index += 1;
70
+ this.skipSpaces();
71
+ const key = this.key();
72
+ if (key === void 0) return;
73
+ let value = {
74
+ kind: "boolean",
75
+ value: true
76
+ };
77
+ if (this.peek() === "=") {
78
+ this.index += 1;
79
+ value = this.bareItem();
80
+ }
81
+ if (value === void 0) return;
82
+ parameters.set(key, value);
83
+ }
84
+ return parameters;
85
+ }
86
+ key() {
87
+ if (!lowercaseAlphaPattern.test(this.peek()) && this.peek() !== "*") return;
88
+ let key = this.take();
89
+ while (keyCharPattern.test(this.peek())) key += this.take();
90
+ return key;
91
+ }
92
+ bareItem() {
93
+ const first = this.peek();
94
+ if (first === "-" || digitPattern.test(first)) return this.number();
95
+ if (first === "\"") {
96
+ const value = this.string();
97
+ return value === void 0 ? void 0 : {
98
+ kind: "string",
99
+ value
100
+ };
101
+ }
102
+ if (first === "*" || alphaPattern.test(first)) return {
103
+ kind: "token",
104
+ value: this.token()
105
+ };
106
+ if (first === ":") return this.bytes() ? { kind: "bytes" } : void 0;
107
+ if (first === "?") {
108
+ this.index += 1;
109
+ const value = this.take();
110
+ return value === "0" || value === "1" ? {
111
+ kind: "boolean",
112
+ value: value === "1"
113
+ } : void 0;
114
+ }
115
+ if (first === "@") {
116
+ this.index += 1;
117
+ const date = this.number();
118
+ return date?.kind === "integer" ? {
119
+ kind: "date",
120
+ value: date.value
121
+ } : void 0;
122
+ }
123
+ if (first === "%") {
124
+ this.index += 1;
125
+ const value = this.displayString();
126
+ return value === void 0 ? void 0 : {
127
+ kind: "display",
128
+ value
129
+ };
130
+ }
131
+ }
132
+ number() {
133
+ let sign = 1;
134
+ if (this.peek() === "-") {
135
+ sign = -1;
136
+ this.index += 1;
137
+ }
138
+ let digits = "";
139
+ let decimal = false;
140
+ while (digitPattern.test(this.peek()) || this.peek() === "." && !decimal) {
141
+ if (this.peek() === ".") {
142
+ if (digits.length > 12) return;
143
+ decimal = true;
144
+ }
145
+ digits += this.take();
146
+ if (!decimal && digits.length > 15 || decimal && digits.length > 16) return;
147
+ }
148
+ if (digits === "" || digits.startsWith(".")) return;
149
+ if (!decimal) return {
150
+ kind: "integer",
151
+ value: sign * Number(digits)
152
+ };
153
+ const fraction = digits.slice(digits.indexOf(".") + 1);
154
+ if (fraction.length === 0 || fraction.length > 3) return;
155
+ return {
156
+ kind: "decimal",
157
+ value: sign * Number(digits)
158
+ };
159
+ }
160
+ string() {
161
+ this.index += 1;
162
+ let value = "";
163
+ for (;;) {
164
+ if (this.done) return;
165
+ const char = this.take();
166
+ if (char === "\"") return value;
167
+ if (char === "\\") {
168
+ const escaped = this.take();
169
+ if (escaped !== "\"" && escaped !== "\\") return;
170
+ value += escaped;
171
+ continue;
172
+ }
173
+ const code = char.charCodeAt(0);
174
+ if (code < 32 || code > 126) return;
175
+ value += char;
176
+ }
177
+ }
178
+ token() {
179
+ let value = this.take();
180
+ while (tokenCharPattern.test(this.peek())) value += this.take();
181
+ return value;
182
+ }
183
+ bytes() {
184
+ this.index += 1;
185
+ while (base64CharPattern.test(this.peek())) this.index += 1;
186
+ return this.consume(":");
187
+ }
188
+ displayString() {
189
+ if (!this.consume("\"")) return;
190
+ const bytes = [];
191
+ for (;;) {
192
+ if (this.done) return;
193
+ const char = this.take();
194
+ const code = char.charCodeAt(0);
195
+ if (code < 32 || code > 126) return;
196
+ if (char === "\"") try {
197
+ return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes));
198
+ } catch {
199
+ return;
200
+ }
201
+ if (char === "%") {
202
+ const hex = this.take() + this.take();
203
+ if (!/^[0-9a-f]{2}$/.test(hex)) return;
204
+ bytes.push(Number.parseInt(hex, 16));
205
+ continue;
206
+ }
207
+ bytes.push(code);
208
+ }
209
+ }
210
+ };
211
+ const parseList = (text) => {
212
+ const cursor = new Cursor(text);
213
+ const members = [];
214
+ cursor.skipSpaces();
215
+ while (!cursor.done) {
216
+ const member = cursor.member();
217
+ if (member === void 0) return;
218
+ members.push(member);
219
+ cursor.skipWhitespace();
220
+ if (cursor.done) break;
221
+ if (!cursor.consume(",")) return;
222
+ cursor.skipWhitespace();
223
+ if (cursor.done) return;
224
+ }
225
+ return members;
226
+ };
227
+ const wholeNumber = (item) => item?.kind === "integer" && item.value >= 0 ? item.value : void 0;
228
+ const policyName = (member) => member.item?.kind === "string" ? member.item.value : void 0;
229
+ const parseRateLimit = (headers) => {
230
+ const policyField = headers.get("RateLimit-Policy");
231
+ const declared = policyField === null ? void 0 : parseList(policyField);
232
+ if (declared === void 0) return;
233
+ const stateField = headers.get("RateLimit");
234
+ const states = /* @__PURE__ */ new Map();
235
+ for (const member of (stateField === null ? void 0 : parseList(stateField)) ?? []) {
236
+ const name = policyName(member);
237
+ if (name !== void 0 && !states.has(name)) states.set(name, member);
238
+ }
239
+ const policies = [];
240
+ for (const member of declared) {
241
+ const name = policyName(member);
242
+ const quota = wholeNumber(member.parameters.get("q"));
243
+ if (name === void 0 || quota === void 0) continue;
244
+ const state = states.get(name)?.parameters;
245
+ policies.push({
246
+ name,
247
+ quota,
248
+ remaining: wholeNumber(state?.get("r")),
249
+ resetSeconds: wholeNumber(state?.get("t")),
250
+ windowSeconds: wholeNumber(member.parameters.get("w"))
251
+ });
252
+ }
253
+ return policies.length === 0 ? void 0 : { policies };
254
+ };
255
+ var MountayaError = class extends Error {
256
+ name = "MountayaError";
257
+ idempotencyKey;
258
+ constructor(message, options) {
259
+ super(message, options);
260
+ this.idempotencyKey = options?.idempotencyKey;
261
+ }
262
+ };
263
+ var MountayaConfigurationError = class extends MountayaError {
264
+ name = "MountayaConfigurationError";
265
+ };
266
+ const describeType = (value) => {
267
+ if (value === null || value === void 0) return String(value);
268
+ const type = Array.isArray(value) ? "array" : typeof value;
269
+ return /^[aeiou]/.test(type) ? `an ${type}` : `a ${type}`;
270
+ };
271
+ const describeValue = (value) => {
272
+ if (typeof value === "string") return JSON.stringify(value);
273
+ try {
274
+ return String(value);
275
+ } catch {
276
+ return describeType(value);
277
+ }
278
+ };
279
+ const refuseOption = (path, value, remedy, context) => new MountayaConfigurationError(`${context === void 0 ? "" : `${context}: `}${path} is ${describeValue(value)}; ${remedy}`);
280
+ var MountayaConnectionError = class extends MountayaError {
281
+ name = "MountayaConnectionError";
282
+ constructor(message, cause, idempotencyKey) {
283
+ super(message, {
284
+ cause,
285
+ idempotencyKey
286
+ });
287
+ }
288
+ };
289
+ var MountayaApiError = class extends MountayaError {
290
+ name = "MountayaApiError";
291
+ status;
292
+ errors;
293
+ metadata;
294
+ rateLimit;
295
+ requestId;
296
+ retryAfter;
297
+ constructor(message, status, errors, details = {}) {
298
+ super(message, details.cause === void 0 ? { idempotencyKey: details.idempotencyKey } : {
299
+ cause: details.cause,
300
+ idempotencyKey: details.idempotencyKey
301
+ });
302
+ this.status = status;
303
+ this.errors = errors;
304
+ this.metadata = details.metadata;
305
+ this.rateLimit = details.rateLimit;
306
+ this.requestId = details.requestId;
307
+ this.retryAfter = details.retryAfter;
308
+ }
309
+ get code() {
310
+ return this.errors[0]?.extensions?.code;
311
+ }
312
+ hasCode(code) {
313
+ return this.errors.some((entry) => entry.extensions?.code === code);
314
+ }
315
+ };
316
+ var MountayaBadRequestError = class extends MountayaApiError {
317
+ name = "MountayaBadRequestError";
318
+ };
319
+ var MountayaAuthenticationError = class extends MountayaApiError {
320
+ name = "MountayaAuthenticationError";
321
+ };
322
+ var MountayaBillingError = class extends MountayaApiError {
323
+ name = "MountayaBillingError";
324
+ };
325
+ var MountayaForbiddenError = class extends MountayaApiError {
326
+ name = "MountayaForbiddenError";
327
+ };
328
+ var MountayaNotFoundError = class extends MountayaApiError {
329
+ name = "MountayaNotFoundError";
330
+ };
331
+ var MountayaMethodNotAllowedError = class extends MountayaApiError {
332
+ name = "MountayaMethodNotAllowedError";
333
+ };
334
+ var MountayaConflictError = class extends MountayaApiError {
335
+ name = "MountayaConflictError";
336
+ };
337
+ const KEY_IN_USE_CODE = "IDEMPOTENCY_KEY_IN_USE";
338
+ var MountayaIdempotencyKeyInUseError = class extends MountayaConflictError {
339
+ name = "MountayaIdempotencyKeyInUseError";
340
+ };
341
+ const IDEMPOTENT_ANSWER_UNAVAILABLE_CODE = "IDEMPOTENCY_ANSWER_UNAVAILABLE";
342
+ var MountayaIdempotentAnswerUnavailableError = class extends MountayaConflictError {
343
+ name = "MountayaIdempotentAnswerUnavailableError";
344
+ answer;
345
+ constructor(message, status, errors, details = {}) {
346
+ super(message, status, errors, details);
347
+ const { etag: taggedAs, location: createdAt, status: answeredWith } = details.metadata ?? {};
348
+ this.answer = {
349
+ etag: typeof taggedAs === "string" ? taggedAs : void 0,
350
+ location: typeof createdAt === "string" ? createdAt : void 0,
351
+ status: typeof answeredWith === "number" && Number.isInteger(answeredWith) ? answeredWith : void 0
352
+ };
353
+ }
354
+ };
355
+ var MountayaPreconditionFailedError = class extends MountayaApiError {
356
+ name = "MountayaPreconditionFailedError";
357
+ etag;
358
+ constructor(message, status, errors, details = {}) {
359
+ super(message, status, errors, details);
360
+ this.etag = details.etag;
361
+ }
362
+ };
363
+ var MountayaPayloadTooLargeError = class extends MountayaApiError {
364
+ name = "MountayaPayloadTooLargeError";
365
+ };
366
+ var MountayaRateLimitError = class extends MountayaApiError {
367
+ name = "MountayaRateLimitError";
368
+ };
369
+ var MountayaServerError = class extends MountayaApiError {
370
+ name = "MountayaServerError";
371
+ };
372
+ const MOUNTAYA_API_ERROR_NAMES = [
373
+ "MountayaApiError",
374
+ "MountayaAuthenticationError",
375
+ "MountayaBadRequestError",
376
+ "MountayaBillingError",
377
+ "MountayaConflictError",
378
+ "MountayaDataError",
379
+ "MountayaForbiddenError",
380
+ "MountayaIdempotencyKeyInUseError",
381
+ "MountayaIdempotentAnswerUnavailableError",
382
+ "MountayaMethodNotAllowedError",
383
+ "MountayaNotFoundError",
384
+ "MountayaPayloadTooLargeError",
385
+ "MountayaPreconditionFailedError",
386
+ "MountayaRateLimitError",
387
+ "MountayaServerError"
388
+ ];
389
+ const MOUNTAYA_ERROR_NAMES = [
390
+ ...MOUNTAYA_API_ERROR_NAMES,
391
+ "MountayaConfigurationError",
392
+ "MountayaConnectionError",
393
+ "MountayaError",
394
+ "MountayaSelectionError",
395
+ "MountayaWebhookSignatureError",
396
+ "SseBufferOverflowError"
397
+ ];
398
+ const declaresName = (value, names) => typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && names.includes(value.name);
399
+ const isMountayaError = (error) => declaresName(error, MOUNTAYA_ERROR_NAMES);
400
+ const 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";
401
+ const isErrorEntry = (entry) => typeof entry === "object" && entry !== null && "message" in entry && typeof entry.message === "string";
402
+ const errorsOf = (body) => typeof body === "object" && body !== null && "errors" in body ? body.errors : void 0;
403
+ const entriesOf = (body) => {
404
+ const errors = errorsOf(body);
405
+ return Array.isArray(errors) ? errors.filter(isErrorEntry) : [];
406
+ };
407
+ const isMetadata = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
408
+ const metadataOf = (body) => {
409
+ if (typeof body !== "object" || body === null || !("extensions" in body)) return;
410
+ const { extensions } = body;
411
+ if (typeof extensions !== "object" || extensions === null || !("metadata" in extensions)) return;
412
+ const { metadata } = extensions;
413
+ return isMetadata(metadata) ? metadata : void 0;
414
+ };
415
+ const 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.";
416
+ const 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.";
417
+ const secondsSpelled = (count) => `${count} ${count === 1 ? "second" : "seconds"}`;
418
+ const momentAfter = (seconds) => {
419
+ const end = new Date(Date.now() + seconds * 1e3);
420
+ return Number.isNaN(end.getTime()) ? void 0 : end.toISOString().replace(/\.\d{3}Z$/, "Z");
421
+ };
422
+ const monthlyAllowanceStep = (retryAfterSeconds) => {
423
+ const moment = retryAfterSeconds === void 0 ? void 0 : momentAfter(retryAfterSeconds);
424
+ return `The organization's monthly allowance on this API is spent: it renews when the next billing period begins${retryAfterSeconds === void 0 || retryAfterSeconds === 0 ? "" : ` in ${secondsSpelled(retryAfterSeconds)}${moment === void 0 ? "" : ` (at ${moment})`}`}, 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/).`;
425
+ };
426
+ const spendsMonthlyAllowance = (rateLimit) => {
427
+ const policies = rateLimit?.policies ?? [];
428
+ return policies.some((policy) => policy.name === "month" && policy.remaining === 0) && policies.every((policy) => policy.name === "month" || policy.remaining !== 0);
429
+ };
430
+ const 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.";
431
+ const 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.";
432
+ const 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.";
433
+ const 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.";
434
+ const 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.";
435
+ const 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.";
436
+ const PRECONDITION_STEP = "The resource changed since the etag this write names was read: read it again, and decide what the write should be now.";
437
+ const 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.";
438
+ const 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.";
439
+ const 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.";
440
+ const nextStepFor = (status, code, retryAfterSeconds, monthlyAllowanceSpent, declaration) => {
441
+ const mints = declaration.requiresSecretKey === true;
442
+ const actsAsMember = declaration.actsAsMember === true;
443
+ switch (status) {
444
+ case 401:
445
+ if (mints) return SECRET_KEY_STEP;
446
+ return actsAsMember ? `${CREDENTIAL_STEP} ${MEMBER_SESSION_STEP}` : CREDENTIAL_STEP;
447
+ case 402: return BILLING_STEP;
448
+ case 403:
449
+ if (mints) return MINT_REFUSAL_STEP;
450
+ return actsAsMember ? `${FORBIDDEN_STEP} ${ACTING_USER_STEP}` : FORBIDDEN_STEP;
451
+ case 409: return code === "IDEMPOTENCY_ANSWER_UNAVAILABLE" ? IDEMPOTENT_ANSWER_STEP : code === "IDEMPOTENCY_KEY_IN_USE" ? KEY_IN_USE_STEP : void 0;
452
+ case 412: return PRECONDITION_STEP;
453
+ case 429: {
454
+ if (code === "LIMIT_REACHED") return CEILING_STEP;
455
+ if (monthlyAllowanceSpent) return monthlyAllowanceStep(retryAfterSeconds);
456
+ const wait = retryAfterSeconds === void 0 || retryAfterSeconds === 0 ? "Wait before calling again." : `Wait ${secondsSpelled(retryAfterSeconds)} before calling again.`;
457
+ return mints ? `${wait} ${MINT_LIMIT_STEP}` : wait;
458
+ }
459
+ default: return;
460
+ }
461
+ };
462
+ const failureMessage = (context, status, entries, facts = {}) => {
463
+ const first = entries[0] ?? {};
464
+ const parts = [
465
+ status,
466
+ first.extensions?.code,
467
+ first.message
468
+ ].map((part) => typeof part === "string" ? part.trim() : typeof part === "number" ? String(part) : "").filter((part) => part !== "");
469
+ const summary = parts.length === 0 ? context : `${context}: ${parts.join(" ")}`;
470
+ const next = status === void 0 ? void 0 : nextStepFor(status, first.extensions?.code, facts.retryAfterSeconds, spendsMonthlyAllowance(facts.rateLimit), facts.declaration ?? {});
471
+ const sentence = next === void 0 ? summary : `${/[.!?]$/.test(summary) ? summary : `${summary}.`} ${next}`;
472
+ return facts.requestId === void 0 ? sentence : `${sentence} (request ${facts.requestId})`;
473
+ };
474
+ const MONTHS = [
475
+ "Jan",
476
+ "Feb",
477
+ "Mar",
478
+ "Apr",
479
+ "May",
480
+ "Jun",
481
+ "Jul",
482
+ "Aug",
483
+ "Sep",
484
+ "Oct",
485
+ "Nov",
486
+ "Dec"
487
+ ];
488
+ const delaySecondsPattern = /^[ \t]*(\d+)[ \t]*$/;
489
+ const MAX_DELAY_SECONDS_COUNT = 9223372036854775807n;
490
+ const imfFixdatePattern = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) ([A-Z][a-z]{2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
491
+ const rfc850DatePattern = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-([A-Z][a-z]{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
492
+ const asctimeDatePattern = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) ([A-Z][a-z]{2}) ([ \d]\d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/;
493
+ const utcInstant = (year, month, day, hour, minute, second) => {
494
+ const monthIndex = MONTHS.indexOf(month);
495
+ if (monthIndex < 0 || hour > 23 || minute > 59 || second > 60) return;
496
+ const midnight = /* @__PURE__ */ new Date(0);
497
+ midnight.setUTCFullYear(year, monthIndex, day);
498
+ if (midnight.getUTCMonth() !== monthIndex || midnight.getUTCDate() !== day) return;
499
+ return midnight.getTime() + ((hour * 60 + minute) * 60 + second) * 1e3;
500
+ };
501
+ const httpDate = (value, now) => {
502
+ const fixdate = imfFixdatePattern.exec(value);
503
+ if (fixdate !== null) {
504
+ const [, day, month, year, hour, minute, second] = fixdate;
505
+ return utcInstant(Number(year), month ?? "", Number(day), Number(hour), Number(minute), Number(second));
506
+ }
507
+ const rfc850 = rfc850DatePattern.exec(value);
508
+ if (rfc850 !== null) {
509
+ const [, day, month, shortYear, hour, minute, second] = rfc850;
510
+ const currentYear = new Date(now).getUTCFullYear();
511
+ const sameDigits = currentYear - currentYear % 100 + Number(shortYear);
512
+ const year = sameDigits > currentYear + 50 ? sameDigits - 100 : sameDigits;
513
+ return utcInstant(year, month ?? "", Number(day), Number(hour), Number(minute), Number(second));
514
+ }
515
+ const asctime = asctimeDatePattern.exec(value);
516
+ if (asctime !== null) {
517
+ const [, month, day, hour, minute, second, year] = asctime;
518
+ return utcInstant(Number(year), month ?? "", Number(day), Number(hour), Number(minute), Number(second));
519
+ }
520
+ };
521
+ const parseRetryAfter = (header, now = Date.now) => {
522
+ if (header === null) return;
523
+ const digits = delaySecondsPattern.exec(header)?.[1];
524
+ if (digits !== void 0) {
525
+ if (BigInt(digits) > MAX_DELAY_SECONDS_COUNT) return;
526
+ return Math.min(Number(digits), Number.MAX_SAFE_INTEGER);
527
+ }
528
+ const current = now();
529
+ const instant = httpDate(header.replace(/^[ \t]+|[ \t]+$/g, ""), current);
530
+ return instant === void 0 ? void 0 : Math.max(0, Math.ceil((instant - current) / 1e3));
531
+ };
532
+ const answerDetailsOf = (headers) => {
533
+ const requestId = headers.get("X-Request-Id")?.trim();
534
+ return {
535
+ rateLimit: parseRateLimit(headers),
536
+ requestId: requestId === void 0 || requestId === "" ? void 0 : requestId
537
+ };
538
+ };
539
+ const errorOfBody = (body, answer, context, declaration, idempotencyKey) => {
540
+ const entries = entriesOf(body);
541
+ const retryAfterSeconds = parseRetryAfter(answer.headers.get("Retry-After"));
542
+ const details = answerDetailsOf(answer.headers);
543
+ return errorForStatus(failureMessage(context, answer.status, entries, {
544
+ declaration,
545
+ rateLimit: details.rateLimit,
546
+ requestId: details.requestId,
547
+ retryAfterSeconds
548
+ }), answer.status, entries, {
549
+ ...details,
550
+ etag: answer.headers.get("ETag") ?? void 0,
551
+ idempotencyKey,
552
+ metadata: metadataOf(body),
553
+ retryAfter: retryAfterSeconds
554
+ });
555
+ };
556
+ const errorFromResponse = async (response, context, declaration, idempotencyKey) => errorOfBody(await response.json().catch(() => void 0), response, context, declaration, idempotencyKey);
557
+ const errorFromBody = (text, answer, context, declaration, idempotencyKey) => {
558
+ let body;
559
+ try {
560
+ body = JSON.parse(text);
561
+ } catch {
562
+ body = void 0;
563
+ }
564
+ return errorOfBody(body, answer, context, declaration, idempotencyKey);
565
+ };
566
+ const errorForStatus = (message, status, entries = [], details = {}) => {
567
+ const { etag, ...rest } = details;
568
+ const args = [
569
+ message,
570
+ status,
571
+ entries,
572
+ rest
573
+ ];
574
+ switch (status) {
575
+ case 400: return new MountayaBadRequestError(...args);
576
+ case 401: return new MountayaAuthenticationError(...args);
577
+ case 402: return new MountayaBillingError(...args);
578
+ case 403: return new MountayaForbiddenError(...args);
579
+ case 404: return new MountayaNotFoundError(...args);
580
+ case 405: return new MountayaMethodNotAllowedError(...args);
581
+ case 409: switch (entries[0]?.extensions?.code) {
582
+ case IDEMPOTENT_ANSWER_UNAVAILABLE_CODE: return new MountayaIdempotentAnswerUnavailableError(...args);
583
+ case KEY_IN_USE_CODE: return new MountayaIdempotencyKeyInUseError(...args);
584
+ default: return new MountayaConflictError(...args);
585
+ }
586
+ case 412: return new MountayaPreconditionFailedError(message, status, entries, {
587
+ ...rest,
588
+ etag
589
+ });
590
+ case 413: return new MountayaPayloadTooLargeError(...args);
591
+ case 429: return new MountayaRateLimitError(...args);
592
+ default: return status >= 500 ? new MountayaServerError(...args) : new MountayaApiError(...args);
593
+ }
594
+ };
595
+ const agentRunDates = { created_at: true };
596
+ const collabStreamEventDatesByType = {
597
+ "collection.changed": { occurred_at: true },
598
+ "itinerary.changed": { occurred_at: true },
599
+ "presence.join": { connected_at: true },
600
+ "presence.snapshot": { members: [{ connected_at: true }] },
601
+ "segment.changed": { occurred_at: true },
602
+ "waypoint.changed": { occurred_at: true },
603
+ "zone.changed": { occurred_at: true }
604
+ };
605
+ const postAgentRun = (transport, args, options) => transport.request({
606
+ actsAsMember: true,
607
+ body: args.body,
608
+ dates: { data: agentRunDates },
609
+ idempotencyKey: args.idempotencyKey,
610
+ idempotent: false,
611
+ method: "POST",
612
+ operationId: "postAgentRun",
613
+ path: "/v1/agent/runs",
614
+ requiresSession: true,
615
+ retry: options?.retry,
616
+ serverBudgetMs: 3e4,
617
+ signal: options?.signal,
618
+ surface: "rest",
619
+ takesIdempotencyKey: true,
620
+ timeoutMs: options?.timeoutMs
621
+ });
622
+ const postAgentRunInput = (transport, args, options) => transport.request({
623
+ actsAsMember: true,
624
+ body: args.body,
625
+ idempotencyKey: args.idempotencyKey,
626
+ idempotent: false,
627
+ method: "POST",
628
+ operationId: "postAgentRunInput",
629
+ path: `/v1/agent/runs/${encodeURIComponent(String(args.run_id))}/input`,
630
+ requiresSession: true,
631
+ retry: options?.retry,
632
+ serverBudgetMs: 3e4,
633
+ signal: options?.signal,
634
+ surface: "rest",
635
+ takesIdempotencyKey: true,
636
+ timeoutMs: options?.timeoutMs
637
+ });
638
+ const postItineraryCollab = (transport, args, options) => transport.request({
639
+ actsAsMember: true,
640
+ body: args.body,
641
+ idempotent: true,
642
+ method: "POST",
643
+ operationId: "postItineraryCollab",
644
+ path: `/v1/itineraries/${encodeURIComponent(String(args.itinerary_id))}/collab`,
645
+ requiresSession: true,
646
+ retry: options?.retry,
647
+ serverBudgetMs: 3e4,
648
+ signal: options?.signal,
649
+ surface: "rest",
650
+ timeoutMs: options?.timeoutMs
651
+ });
652
+ const postZoneCollab = (transport, args, options) => transport.request({
653
+ actsAsMember: true,
654
+ body: args.body,
655
+ idempotent: true,
656
+ method: "POST",
657
+ operationId: "postZoneCollab",
658
+ path: `/v1/zones/${encodeURIComponent(String(args.zone_id))}/collab`,
659
+ requiresSession: true,
660
+ retry: options?.retry,
661
+ serverBudgetMs: 3e4,
662
+ signal: options?.signal,
663
+ surface: "rest",
664
+ timeoutMs: options?.timeoutMs
665
+ });
666
+ const printableAsciiPattern = /^[\x20-\x7e]*$/;
667
+ const isHeaderValue = (value) => printableAsciiPattern.test(value);
668
+ const isoDate = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;
669
+ const ISO_DATE_MIN_LENGTH = 20;
670
+ const ISO_DATE_SEPARATOR = 84;
671
+ const MONTH_DAYS = [
672
+ 31,
673
+ 28,
674
+ 31,
675
+ 30,
676
+ 31,
677
+ 30,
678
+ 31,
679
+ 31,
680
+ 30,
681
+ 31,
682
+ 30,
683
+ 31
684
+ ];
685
+ const isLeapYear = (year) => year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
686
+ const daysIn = (year, month) => month === 2 && isLeapYear(year) ? 29 : MONTH_DAYS[month - 1] ?? 0;
687
+ const instantOf = (value) => {
688
+ if (value.length < ISO_DATE_MIN_LENGTH || value.charCodeAt(10) !== ISO_DATE_SEPARATOR) return;
689
+ const fields = isoDate.exec(value);
690
+ if (fields === null) return;
691
+ const field = (index) => Number(fields[index] ?? 0);
692
+ const year = field(1);
693
+ const month = field(2);
694
+ const day = field(3);
695
+ if (!(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)) return;
696
+ const instant = new Date(value);
697
+ return Number.isNaN(instant.getTime()) ? void 0 : instant;
698
+ };
699
+ const isListMask$1 = (mask) => Array.isArray(mask);
700
+ const isList = (value) => Array.isArray(value);
701
+ const decodeDates = (value, mask, field = "the answer") => {
702
+ if (mask === void 0) return value;
703
+ if (mask === true) {
704
+ if (typeof value !== "string") return value;
705
+ const instant = instantOf(value);
706
+ if (instant === void 0) throw new MountayaError(`${field}, which the contract declares an instant, holds a string that names none: an instant is a full ISO 8601 timestamp carrying its zone.`);
707
+ return instant;
708
+ }
709
+ if (isListMask$1(mask)) {
710
+ if (isList(value)) {
711
+ const [element] = mask;
712
+ for (let index = 0; index < value.length; index += 1) value[index] = decodeDates(value[index], element, field);
713
+ }
714
+ return value;
715
+ }
716
+ if (typeof value === "object" && value !== null && !isList(value)) {
717
+ for (const [member, memberMask] of Object.entries(mask)) if (Object.hasOwn(value, member)) {
718
+ const current = Reflect.get(value, member);
719
+ const decoded = decodeDates(current, memberMask, member);
720
+ if (decoded !== current) Reflect.set(value, member, decoded);
721
+ }
722
+ }
723
+ return value;
724
+ };
725
+ const parseJsonWithDates = (text, mask) => text.length > 0 ? decodeDates(JSON.parse(text), mask) : void 0;
726
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
727
+ const namedError = (name, message) => typeof DOMException === "function" ? new DOMException(message, name) : Object.assign(new Error(message), { name });
728
+ const abortReasonOf = (signal) => signal.reason ?? namedError("AbortError", "This operation was aborted");
729
+ const REFUSAL_WAIT_MS = 5e3;
730
+ const MAX_REFUSAL_BYTES = 65536;
731
+ const isAborted = (signal) => signal.aborted;
732
+ const settleOnAbort = async (work, signal) => {
733
+ if (signal === void 0) return work();
734
+ if (isAborted(signal)) throw abortReasonOf(signal);
735
+ let stopWatching = () => {};
736
+ const aborted = new Promise((_resolve, reject) => {
737
+ const onAbort = () => {
738
+ reject(abortReasonOf(signal));
739
+ };
740
+ signal.addEventListener("abort", onAbort, { once: true });
741
+ stopWatching = () => {
742
+ signal.removeEventListener("abort", onAbort);
743
+ };
744
+ });
745
+ try {
746
+ const settled = await Promise.race([work(), aborted]);
747
+ if (isAborted(signal)) throw abortReasonOf(signal);
748
+ return settled;
749
+ } finally {
750
+ stopWatching();
751
+ }
752
+ };
753
+ const concat = (chunks, byteLength) => {
754
+ const bytes = new Uint8Array(byteLength);
755
+ let offset = 0;
756
+ for (const chunk of chunks) {
757
+ bytes.set(chunk, offset);
758
+ offset += chunk.byteLength;
759
+ }
760
+ return bytes;
761
+ };
762
+ const drain = async (body, bounds) => {
763
+ const { maxBytes, signal, timeoutMs } = bounds;
764
+ let reader;
765
+ try {
766
+ reader = body.getReader();
767
+ } catch (cause) {
768
+ if (signal !== void 0 && isAborted(signal)) throw abortReasonOf(signal);
769
+ return {
770
+ brokeOff: { cause },
771
+ bytes: concat([], 0)
772
+ };
773
+ }
774
+ const cancel = (reason) => {
775
+ reader.cancel(reason).catch(() => void 0);
776
+ };
777
+ const letGo = () => {
778
+ try {
779
+ reader.releaseLock();
780
+ } catch {}
781
+ };
782
+ if (signal !== void 0 && isAborted(signal)) {
783
+ cancel(abortReasonOf(signal));
784
+ letGo();
785
+ throw abortReasonOf(signal);
786
+ }
787
+ const onAbort = () => {
788
+ if (signal !== void 0) cancel(abortReasonOf(signal));
789
+ };
790
+ signal?.addEventListener("abort", onAbort, { once: true });
791
+ const deadline = timeoutMs === void 0 ? void 0 : setTimeout(cancel, timeoutMs);
792
+ const chunks = [];
793
+ let received = 0;
794
+ let brokeOff;
795
+ try {
796
+ while (true) {
797
+ const { done, value } = await reader.read();
798
+ if (signal !== void 0 && isAborted(signal)) throw abortReasonOf(signal);
799
+ if (done) break;
800
+ received += value.byteLength;
801
+ if (maxBytes !== void 0 && received > maxBytes) {
802
+ chunks.length = 0;
803
+ received = 0;
804
+ break;
805
+ }
806
+ chunks.push(value);
807
+ }
808
+ } catch (cause) {
809
+ if (signal !== void 0 && isAborted(signal)) throw abortReasonOf(signal);
810
+ brokeOff = { cause };
811
+ } finally {
812
+ clearTimeout(deadline);
813
+ signal?.removeEventListener("abort", onAbort);
814
+ cancel();
815
+ letGo();
816
+ }
817
+ return {
818
+ brokeOff,
819
+ bytes: concat(chunks, received)
820
+ };
821
+ };
822
+ const streamOf = (response) => {
823
+ const body = response.body;
824
+ if (response.bodyUsed || body === null || body === void 0) return;
825
+ return typeof body.getReader === "function" ? body : void 0;
826
+ };
827
+ const readFailureText = async (response, signal) => {
828
+ const body = streamOf(response);
829
+ if (body === void 0) return settleOnAbort(() => response.text().catch(() => ""), signal);
830
+ const { bytes } = await drain(body, {
831
+ maxBytes: MAX_REFUSAL_BYTES,
832
+ signal,
833
+ timeoutMs: REFUSAL_WAIT_MS
834
+ });
835
+ return new TextDecoder().decode(bytes);
836
+ };
837
+ const readFailure = async (response, call) => {
838
+ const declaration = {
839
+ actsAsMember: call.actsAsMember,
840
+ requiresSecretKey: call.requiresSecretKey
841
+ };
842
+ if (streamOf(response) === void 0) return settleOnAbort(() => errorFromResponse(response, call.operationId, declaration, call.idempotencyKey), call.signal);
843
+ return errorFromBody(await readFailureText(response, call.signal), response, call.operationId, declaration, call.idempotencyKey);
844
+ };
845
+ const BYTE_ORDER_MARK = "";
846
+ const MAX_SSE_BUFFER_CHARS = 8388608;
847
+ var SseBufferOverflowError = class extends MountayaError {
848
+ name = "SseBufferOverflowError";
849
+ limit;
850
+ constructor(limit, operationId, options) {
851
+ const overflow = `sse frame parser: unterminated frame exceeded ${limit} characters`;
852
+ super(operationId === void 0 ? overflow : `${operationId}: ${overflow}. The producer never ended the record, and a reopen meets it again.`, options);
853
+ this.limit = limit;
854
+ }
855
+ };
856
+ var SseFrameParser = class {
857
+ lineParts = [];
858
+ lineLength = 0;
859
+ dataLines = [];
860
+ event = "";
861
+ recordId;
862
+ recordLength = 0;
863
+ lastId;
864
+ atStart = true;
865
+ afterCarriageReturn = false;
866
+ overflowed = false;
867
+ maxBufferChars;
868
+ constructor(maxBufferChars = MAX_SSE_BUFFER_CHARS) {
869
+ const given = maxBufferChars;
870
+ if (typeof given !== "number" || !Number.isInteger(given) || given < 1) throw refuseOption("maxBufferChars", given, `pass a whole number of characters of 1 or more, or leave it out for the default of ${MAX_SSE_BUFFER_CHARS}.`);
871
+ this.maxBufferChars = given;
872
+ }
873
+ get lastEventId() {
874
+ return this.lastId;
875
+ }
876
+ push(chunk) {
877
+ if (this.overflowed) throw new SseBufferOverflowError(this.maxBufferChars);
878
+ const frames = [];
879
+ let start = 0;
880
+ if (chunk.length > 0) {
881
+ if (this.atStart) {
882
+ this.atStart = false;
883
+ if (chunk.startsWith(BYTE_ORDER_MARK)) start = 1;
884
+ }
885
+ if (this.afterCarriageReturn) {
886
+ this.afterCarriageReturn = false;
887
+ if (chunk.startsWith("\n", start)) start += 1;
888
+ }
889
+ }
890
+ let carriageReturn = chunk.indexOf("\r", start);
891
+ let lineFeed = chunk.indexOf("\n", start);
892
+ while (carriageReturn !== -1 || lineFeed !== -1) {
893
+ const end = carriageReturn === -1 || lineFeed !== -1 && lineFeed < carriageReturn ? lineFeed : carriageReturn;
894
+ let next = end + 1;
895
+ if (end === carriageReturn) {
896
+ if (next === chunk.length) this.afterCarriageReturn = true;
897
+ else if (chunk.startsWith("\n", next)) next += 1;
898
+ }
899
+ const line = this.completeLine(chunk.slice(start, end));
900
+ this.recordLength += line.length + (next - end);
901
+ const frame = this.readLine(line);
902
+ if (frame !== null) frames.push(frame);
903
+ start = next;
904
+ if (carriageReturn !== -1 && carriageReturn < start) carriageReturn = chunk.indexOf("\r", start);
905
+ if (lineFeed !== -1 && lineFeed < start) lineFeed = chunk.indexOf("\n", start);
906
+ }
907
+ if (start < chunk.length) {
908
+ this.lineParts.push(chunk.slice(start));
909
+ this.lineLength += chunk.length - start;
910
+ }
911
+ if (this.recordLength + this.lineLength > this.maxBufferChars) {
912
+ this.lineParts = [];
913
+ this.lineLength = 0;
914
+ this.startRecord();
915
+ this.overflowed = true;
916
+ throw new SseBufferOverflowError(this.maxBufferChars);
917
+ }
918
+ return frames;
919
+ }
920
+ completeLine(tail) {
921
+ if (this.lineParts.length === 0) return tail;
922
+ this.lineParts.push(tail);
923
+ const line = this.lineParts.join("");
924
+ this.lineParts = [];
925
+ this.lineLength = 0;
926
+ return line;
927
+ }
928
+ readLine(line) {
929
+ if (line === "") return this.endRecord();
930
+ if (line.startsWith(":")) return null;
931
+ const colon = line.indexOf(":");
932
+ const field = colon === -1 ? line : line.slice(0, colon);
933
+ const raw = colon === -1 ? "" : line.slice(colon + 1);
934
+ const value = raw.startsWith(" ") ? raw.slice(1) : raw;
935
+ if (field === "data") this.dataLines.push(value);
936
+ else if (field === "event") this.event = value;
937
+ else if (field === "id" && !value.includes("\0")) this.recordId = value;
938
+ return null;
939
+ }
940
+ endRecord() {
941
+ const { dataLines, event, recordId } = this;
942
+ this.startRecord();
943
+ if (recordId !== void 0) this.lastId = recordId;
944
+ if (dataLines.length === 0) return null;
945
+ return {
946
+ data: dataLines.join("\n"),
947
+ event,
948
+ id: recordId ?? ""
949
+ };
950
+ }
951
+ startRecord() {
952
+ this.dataLines = [];
953
+ this.event = "";
954
+ this.recordId = void 0;
955
+ this.recordLength = 0;
956
+ }
957
+ };
958
+ const readEventStream = async (body, onFrame, onLastEventId) => {
959
+ const reader = body.getReader();
960
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
961
+ const parser = new SseFrameParser();
962
+ let known;
963
+ try {
964
+ while (true) {
965
+ const { done, value } = await reader.read();
966
+ if (done) return "ended";
967
+ for (const frame of parser.push(decoder.decode(value, { stream: true }))) {
968
+ if (frame.id !== "") known = frame.id;
969
+ if (await onFrame(frame)) return "stopped";
970
+ }
971
+ const position = parser.lastEventId;
972
+ if (position !== void 0 && position !== known) {
973
+ known = position;
974
+ onLastEventId?.(position);
975
+ }
976
+ }
977
+ } finally {
978
+ reader.releaseLock();
979
+ }
980
+ };
981
+ const STALL_WINDOW_MS = 45e3;
982
+ const SILENCE = Symbol("silence");
983
+ const LET_GO = Symbol("let go");
984
+ const boundSilence = (body, operationId, signal) => {
985
+ const reader = body.getReader();
986
+ const letGo = () => {
987
+ try {
988
+ reader.releaseLock();
989
+ } catch {}
990
+ };
991
+ let endWait;
992
+ if (signal.aborted) letGo();
993
+ else signal.addEventListener("abort", () => {
994
+ endWait?.(LET_GO);
995
+ letGo();
996
+ }, { once: true });
997
+ return new ReadableStream({
998
+ cancel: (reason) => reader.cancel(reason),
999
+ pull: async (controller) => {
1000
+ if (signal.aborted) {
1001
+ controller.close();
1002
+ return;
1003
+ }
1004
+ let timer;
1005
+ const ended = new Promise((resolve) => {
1006
+ endWait = resolve;
1007
+ timer = setTimeout(() => resolve(SILENCE), STALL_WINDOW_MS);
1008
+ });
1009
+ try {
1010
+ const next = await Promise.race([reader.read(), ended]);
1011
+ if (next === LET_GO) {
1012
+ controller.close();
1013
+ return;
1014
+ }
1015
+ if (next === SILENCE) throw new MountayaConnectionError(`${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.`);
1016
+ if (next.done) controller.close();
1017
+ else controller.enqueue(next.value);
1018
+ } finally {
1019
+ endWait = void 0;
1020
+ clearTimeout(timer);
1021
+ if (signal.aborted) letGo();
1022
+ }
1023
+ }
1024
+ }, { highWaterMark: 0 });
1025
+ };
1026
+ const openTimeoutOf = (timeoutMs, operationId) => {
1027
+ if (timeoutMs === void 0) return STALL_WINDOW_MS;
1028
+ if (Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= MAX_TIMER_DELAY_MS) return timeoutMs;
1029
+ throw refuseOption("timeoutMs", timeoutMs, `pass a whole number of milliseconds from 1 to ${MAX_TIMER_DELAY_MS}, or leave it out to wait at most ${STALL_WINDOW_MS}.`, operationId);
1030
+ };
1031
+ const requestStream = async (options, state, declaration) => {
1032
+ const { operationId } = options;
1033
+ const openTimeout = openTimeoutOf(options.timeoutMs, operationId);
1034
+ const headers = new Headers({ Accept: "text/event-stream" });
1035
+ if (options.lastEventId) {
1036
+ const position = String(options.lastEventId);
1037
+ if (!isHeaderValue(position)) throw new MountayaConfigurationError(`${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.`);
1038
+ headers.set("Last-Event-ID", position);
1039
+ }
1040
+ const waiting = options.waitForSession?.(state.controller.signal);
1041
+ if (waiting !== void 0) await waiting;
1042
+ const url = typeof options.url === "function" ? options.url() : options.url;
1043
+ const init = options.applyAuth({
1044
+ headers,
1045
+ signal: state.controller.signal
1046
+ }, "GET");
1047
+ let timedOut = false;
1048
+ const deadline = setTimeout(() => {
1049
+ timedOut = true;
1050
+ state.controller.abort();
1051
+ }, openTimeout);
1052
+ let response;
1053
+ try {
1054
+ response = await options.doFetch(url, init);
1055
+ } catch (cause) {
1056
+ if (state.closedByCaller) throw cause;
1057
+ if (timedOut) throw new MountayaConnectionError(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.`);
1058
+ if (isMountayaError(cause)) throw cause;
1059
+ throw new MountayaConnectionError(`${operationId}: the stream failed before a response arrived. Check the network, and that the stream's URL names a host that answers.`, cause);
1060
+ } finally {
1061
+ clearTimeout(deadline);
1062
+ }
1063
+ options.onResponse?.(response);
1064
+ if (!response.ok) throw await readFailure(response, {
1065
+ ...declaration,
1066
+ operationId,
1067
+ signal: state.controller.signal
1068
+ });
1069
+ const body = response.body;
1070
+ if (body === void 0) throw new MountayaConfigurationError(`${operationId}: this runtime's fetch exposes no response body to read the stream from. Pass a fetch that streams response bodies.`);
1071
+ if (body === null) throw new MountayaConnectionError(`${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.`);
1072
+ return body;
1073
+ };
1074
+ const openDeclaredSseStream = (options, declaration) => {
1075
+ const { operationId, signal } = options;
1076
+ const state = {
1077
+ closedByCaller: false,
1078
+ controller: new AbortController()
1079
+ };
1080
+ const close = () => {
1081
+ state.closedByCaller = true;
1082
+ state.controller.abort();
1083
+ };
1084
+ if (signal?.aborted) close();
1085
+ else signal?.addEventListener("abort", close, { once: true });
1086
+ let callerFault = false;
1087
+ const handle = async (frame) => {
1088
+ if (state.closedByCaller) return true;
1089
+ try {
1090
+ const event = options.decode(frame);
1091
+ if (event === null) return false;
1092
+ return await options.onFrame(event, frame.id || void 0);
1093
+ } catch (error) {
1094
+ callerFault = true;
1095
+ throw error;
1096
+ }
1097
+ };
1098
+ const report = (lastEventId) => {
1099
+ if (state.closedByCaller) return;
1100
+ try {
1101
+ options.onLastEventId?.(lastEventId || void 0);
1102
+ } catch (error) {
1103
+ callerFault = true;
1104
+ throw error;
1105
+ }
1106
+ };
1107
+ const read = async () => {
1108
+ const body = await requestStream(options, state, declaration);
1109
+ try {
1110
+ return await readEventStream(boundSilence(body, operationId, state.controller.signal), handle, report);
1111
+ } catch (cause) {
1112
+ if (state.closedByCaller || callerFault) throw cause;
1113
+ if (cause instanceof SseBufferOverflowError) throw new SseBufferOverflowError(cause.limit, operationId, { cause });
1114
+ if (isMountayaError(cause)) throw cause;
1115
+ throw new MountayaConnectionError(`${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.`, cause);
1116
+ }
1117
+ };
1118
+ (async () => {
1119
+ if (state.closedByCaller) return;
1120
+ let settled;
1121
+ try {
1122
+ settled = { outcome: await read() };
1123
+ } catch (error) {
1124
+ settled = { error };
1125
+ }
1126
+ signal?.removeEventListener("abort", close);
1127
+ state.controller.abort();
1128
+ if (state.closedByCaller) return;
1129
+ if ("outcome" in settled) options.onClose?.(settled.outcome);
1130
+ else options.onError?.(settled.error);
1131
+ })();
1132
+ return close;
1133
+ };
1134
+ const openSseStream = (options) => openDeclaredSseStream(options, void 0);
1135
+ const agentRunEventTypes = {
1136
+ "awaiting-input": "awaiting-input",
1137
+ "budget-exhausted": "budget-exhausted",
1138
+ "checks-unmet": "checks-unmet",
1139
+ "confirm-required": "confirm-required",
1140
+ done: "done",
1141
+ error: "error",
1142
+ message: "message",
1143
+ "message-delta": "message-delta",
1144
+ reconnect: "reconnect",
1145
+ "tool-abandoned": "tool-abandoned",
1146
+ "tool-call": "tool-call",
1147
+ "tool-result": "tool-result"
1148
+ };
1149
+ const agentTerminalEventTypes = /* @__PURE__ */ new Set([agentRunEventTypes.done]);
1150
+ const runIdFrom = (body) => {
1151
+ const id = body?.data?.id;
1152
+ return typeof id === "string" && id !== "" ? id : void 0;
1153
+ };
1154
+ const decodeAgentFrame = (frame) => {
1155
+ if (!Object.hasOwn(agentRunEventTypes, frame.event)) return null;
1156
+ let payload;
1157
+ try {
1158
+ payload = frame.data ? JSON.parse(frame.data) : {};
1159
+ } catch {
1160
+ return null;
1161
+ }
1162
+ if (typeof payload !== "object" || payload === null) return null;
1163
+ return {
1164
+ ...payload,
1165
+ type: frame.event
1166
+ };
1167
+ };
1168
+ const AGENT_EVENTS_OPERATION_ID = "getAgentRunEvents";
1169
+ const refuseServerToolsUnderKey = (transport, operationId, serverTools) => {
1170
+ if (serverTools === void 0 || serverTools.length === 0) return;
1171
+ if (transport.mapCredential.publishableKey === void 0) return;
1172
+ throw new MountayaConfigurationError(`${operationId}: a run under a publishable key calls no server tool, so server_tools must be empty. Turn routesServerTools off.`);
1173
+ };
1174
+ const isReconnect = (event) => event.type === agentRunEventTypes.reconnect;
1175
+ const createAgentTransport = (transport) => ({
1176
+ sendInput: async (runId, input, options) => {
1177
+ if (input.type === "manifest-update") refuseServerToolsUnderKey(transport, "postAgentRunInput", input.server_tools);
1178
+ await postAgentRunInput(transport, {
1179
+ body: input,
1180
+ idempotencyKey: options?.idempotencyKey,
1181
+ run_id: runId
1182
+ });
1183
+ },
1184
+ startRun: async (params, options) => {
1185
+ refuseServerToolsUnderKey(transport, "postAgentRun", params.server_tools);
1186
+ const body = await postAgentRun(transport, {
1187
+ body: params,
1188
+ idempotencyKey: options?.idempotencyKey
1189
+ });
1190
+ const runId = runIdFrom(body);
1191
+ if (runId === void 0) throw new MountayaApiError("postAgentRun: 202 named no run", 202, []);
1192
+ return { runId };
1193
+ },
1194
+ subscribe: (runId, handlers, options) => {
1195
+ const seam = transport.streamSeam;
1196
+ let expiresAt;
1197
+ let reconnected = false;
1198
+ return openDeclaredSseStream({
1199
+ applyAuth: (init, method) => {
1200
+ const applied = seam.applyAuth(init, method, {
1201
+ actsAsMember: true,
1202
+ operationId: AGENT_EVENTS_OPERATION_ID,
1203
+ requiresSession: true
1204
+ });
1205
+ expiresAt = seam.sessionExpiresAt();
1206
+ return applied;
1207
+ },
1208
+ decode: (frame) => {
1209
+ const event = decodeAgentFrame(frame);
1210
+ if (event === null) handlers.onSkippedFrame?.();
1211
+ return event;
1212
+ },
1213
+ doFetch: seam.doFetch,
1214
+ lastEventId: options?.lastEventId,
1215
+ onClose: (outcome) => {
1216
+ if (outcome === "stopped") {
1217
+ handlers.onClose(reconnected ? "reconnect" : "terminal");
1218
+ return;
1219
+ }
1220
+ const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
1221
+ handlers.onClose(expired ? "reconnect" : "ended");
1222
+ },
1223
+ onError: (error) => handlers.onError(error),
1224
+ onFrame: async (event, id) => {
1225
+ if (isReconnect(event)) {
1226
+ reconnected = true;
1227
+ return true;
1228
+ }
1229
+ await handlers.onFrame({
1230
+ event,
1231
+ id
1232
+ });
1233
+ return agentTerminalEventTypes.has(event.type);
1234
+ },
1235
+ onLastEventId: (lastEventId) => handlers.onLastEventId?.(lastEventId),
1236
+ onResponse: (response) => {
1237
+ seam.report(response, AGENT_EVENTS_OPERATION_ID);
1238
+ },
1239
+ operationId: AGENT_EVENTS_OPERATION_ID,
1240
+ signal: options?.signal,
1241
+ timeoutMs: seam.timeoutMs,
1242
+ url: () => seam.url(`/v1/agent/runs/${encodeURIComponent(runId)}/events`, AGENT_EVENTS_OPERATION_ID),
1243
+ waitForSession: (signal) => seam.waitForSession(AGENT_EVENTS_OPERATION_ID, signal)
1244
+ }, { actsAsMember: true });
1245
+ }
1246
+ });
1247
+ const isHolding = (mask) => Array.isArray(mask) && mask.length === 2 && mask[0] === true;
1248
+ const isVariants = (mask) => Array.isArray(mask) && mask.length === 2 && typeof mask[0] === "string";
1249
+ const isListMask = (mask) => Array.isArray(mask) && mask.length === 1;
1250
+ const isMembers = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1251
+ const withAbsentNulls = (value, mask) => {
1252
+ if (mask === void 0 || mask === true || isHolding(mask)) return value;
1253
+ if (isListMask(mask)) {
1254
+ if (!Array.isArray(value)) return value;
1255
+ let copy;
1256
+ for (const [index, element] of value.entries()) {
1257
+ const written = withAbsentNulls(element, mask[0]);
1258
+ if (written !== element) {
1259
+ copy ??= [...value];
1260
+ copy[index] = written;
1261
+ }
1262
+ }
1263
+ return copy ?? value;
1264
+ }
1265
+ if (!isMembers(value)) return value;
1266
+ if (isVariants(mask)) {
1267
+ const [discriminator, variants] = mask;
1268
+ const variant = value[discriminator];
1269
+ return typeof variant === "string" && Object.hasOwn(variants, variant) ? withAbsentNulls(value, variants[variant]) : value;
1270
+ }
1271
+ let copy;
1272
+ for (const [member, inner] of Object.entries(mask)) {
1273
+ if (!Object.hasOwn(value, member)) {
1274
+ if (inner === true || isHolding(inner)) {
1275
+ copy ??= { ...value };
1276
+ copy[member] = null;
1277
+ }
1278
+ continue;
1279
+ }
1280
+ const held = value[member];
1281
+ const written = withAbsentNulls(held, isHolding(inner) ? inner[1] : inner);
1282
+ if (written !== held) {
1283
+ copy ??= { ...value };
1284
+ copy[member] = written;
1285
+ }
1286
+ }
1287
+ return copy ?? value;
1288
+ };
1289
+ const collabStreamEventNulls = ["type", {
1290
+ cursor: { position: true },
1291
+ selection: { selection: true }
1292
+ }];
1293
+ const collabStreamEventTypes = {
1294
+ "collection.changed": "collection.changed",
1295
+ cursor: "cursor",
1296
+ "draft.clear": "draft.clear",
1297
+ "draft.update": "draft.update",
1298
+ "itinerary.changed": "itinerary.changed",
1299
+ "lock.acquired": "lock.acquired",
1300
+ "lock.released": "lock.released",
1301
+ "lock.snapshot": "lock.snapshot",
1302
+ "presence.join": "presence.join",
1303
+ "presence.leave": "presence.leave",
1304
+ "presence.snapshot": "presence.snapshot",
1305
+ reconnect: "reconnect",
1306
+ "segment.changed": "segment.changed",
1307
+ selection: "selection",
1308
+ "waypoint.changed": "waypoint.changed",
1309
+ "zone.changed": "zone.changed"
1310
+ };
1311
+ const collabEventDates = collabStreamEventDatesByType;
1312
+ const NIL_UUID = "00000000-0000-0000-0000-000000000000";
1313
+ const isTerminalStatus = (status) => status >= 400 && status < 500 && status !== 429;
1314
+ const REOPEN_REPEATS_ERROR_NAMES = ["MountayaConfigurationError", "SseBufferOverflowError"];
1315
+ const holderIdOf = (metadata) => {
1316
+ const holder = metadata?.holder;
1317
+ if (typeof holder !== "object" || holder === null || !("id" in holder)) return;
1318
+ const { id } = holder;
1319
+ return typeof id === "string" && id !== "" && id !== NIL_UUID ? id : void 0;
1320
+ };
1321
+ const decodeCollabFrame = (frame) => {
1322
+ if (!Object.hasOwn(collabStreamEventTypes, frame.event)) return null;
1323
+ let payload;
1324
+ try {
1325
+ payload = frame.data ? parseJsonWithDates(frame.data, collabEventDates[frame.event]) : {};
1326
+ } catch {
1327
+ return null;
1328
+ }
1329
+ if (typeof payload !== "object" || payload === null) return null;
1330
+ return withAbsentNulls({
1331
+ ...payload,
1332
+ type: frame.event
1333
+ }, collabStreamEventNulls);
1334
+ };
1335
+ const createCollabTransport = (transport) => {
1336
+ const subscribeStream = (operationId, path, handlers, options) => {
1337
+ const seam = transport.streamSeam;
1338
+ let subscriberFault;
1339
+ const asSubscriber = (call) => {
1340
+ try {
1341
+ call();
1342
+ } catch (thrown) {
1343
+ subscriberFault = { thrown };
1344
+ throw thrown;
1345
+ }
1346
+ };
1347
+ let expiresAt;
1348
+ let userId;
1349
+ let reconnected = false;
1350
+ return openDeclaredSseStream({
1351
+ applyAuth: (init, method) => {
1352
+ const applied = seam.applyAuth(init, method, {
1353
+ actsAsMember: true,
1354
+ operationId,
1355
+ requiresSession: true
1356
+ });
1357
+ expiresAt = seam.sessionExpiresAt();
1358
+ userId = seam.sessionUserId() ?? void 0;
1359
+ return applied;
1360
+ },
1361
+ decode: (frame) => {
1362
+ const event = decodeCollabFrame(frame);
1363
+ if (event === null) asSubscriber(() => handlers.onSkippedFrame?.());
1364
+ return event;
1365
+ },
1366
+ doFetch: seam.doFetch,
1367
+ lastEventId: options?.lastEventId,
1368
+ onClose: () => {
1369
+ const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
1370
+ handlers.onClose(reconnected || expired ? "reconnect" : "ended");
1371
+ },
1372
+ onError: (error) => {
1373
+ const terminal = subscriberFault !== void 0 && subscriberFault.thrown === error || isMountayaError(error) && REOPEN_REPEATS_ERROR_NAMES.includes(error.name) || isMountayaApiError(error) && isTerminalStatus(error.status);
1374
+ handlers.onError(error, { terminal });
1375
+ },
1376
+ onFrame: (event, id) => {
1377
+ if (event.type === collabStreamEventTypes.reconnect) {
1378
+ reconnected = true;
1379
+ return true;
1380
+ }
1381
+ asSubscriber(() => handlers.onFrame({
1382
+ event,
1383
+ id
1384
+ }));
1385
+ return false;
1386
+ },
1387
+ onLastEventId: (lastEventId) => {
1388
+ asSubscriber(() => handlers.onLastEventId?.(lastEventId));
1389
+ },
1390
+ onResponse: (response) => {
1391
+ seam.report(response, operationId);
1392
+ if (response.ok) asSubscriber(() => handlers.onOpen?.({ userId }));
1393
+ },
1394
+ operationId,
1395
+ signal: options?.signal,
1396
+ timeoutMs: seam.timeoutMs,
1397
+ url: () => seam.url(path, operationId),
1398
+ waitForSession: (signal) => seam.waitForSession(operationId, signal)
1399
+ }, { actsAsMember: true });
1400
+ };
1401
+ return {
1402
+ sendSignal: async (resource, signal) => {
1403
+ try {
1404
+ if (resource.kind === "itineraries") await postItineraryCollab(transport, {
1405
+ body: signal,
1406
+ itinerary_id: resource.id
1407
+ });
1408
+ else await postZoneCollab(transport, {
1409
+ body: signal,
1410
+ zone_id: resource.id
1411
+ });
1412
+ } catch (error) {
1413
+ if (isMountayaApiError(error) && error.status === 409) return {
1414
+ holderId: holderIdOf(error.metadata),
1415
+ ok: false
1416
+ };
1417
+ throw error;
1418
+ }
1419
+ return { ok: true };
1420
+ },
1421
+ subscribeEditor: (resource, handlers, options) => subscribeStream(resource.kind === "itineraries" ? "getItineraryEvents" : "getZoneEvents", `/v1/${resource.kind}/${encodeURIComponent(resource.id)}/events`, handlers, options),
1422
+ subscribeList: (organizationId, handlers, options) => subscribeStream("getOrganizationEvents", `/v1/organizations/${encodeURIComponent(organizationId)}/events`, handlers, options)
1423
+ };
1424
+ };
1425
+ exports.MAX_SSE_BUFFER_CHARS = MAX_SSE_BUFFER_CHARS;
1426
+ exports.SseBufferOverflowError = SseBufferOverflowError;
1427
+ exports.SseFrameParser = SseFrameParser;
1428
+ exports.agentTerminalEventTypes = agentTerminalEventTypes;
1429
+ exports.createAgentTransport = createAgentTransport;
1430
+ exports.createCollabTransport = createCollabTransport;
1431
+ exports.decodeAgentFrame = decodeAgentFrame;
1432
+ exports.decodeCollabFrame = decodeCollabFrame;
1433
+ exports.openSseStream = openSseStream;
1434
+ exports.readEventStream = readEventStream;
1435
+
1436
+ //# sourceMappingURL=index.cjs.map