@mountaya/client 0.1.0 → 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 (67) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +2 -2
  3. package/dist/admin/index.cjs +2876 -3502
  4. package/dist/admin/index.cjs.map +1 -1
  5. package/dist/admin/index.d.cts +731 -912
  6. package/dist/admin/index.d.ts +731 -912
  7. package/dist/admin/index.js +188 -285
  8. package/dist/admin/index.js.map +1 -1
  9. package/dist/browser.cjs +5913 -7993
  10. package/dist/browser.cjs.map +1 -1
  11. package/dist/browser.d.cts +42 -78
  12. package/dist/browser.d.ts +42 -78
  13. package/dist/browser.js +18 -49
  14. package/dist/browser.js.map +1 -1
  15. package/dist/chunk-CeEX7ayk.d.cts +75531 -0
  16. package/dist/chunk-CeEX7ayk.d.ts +75531 -0
  17. package/dist/chunk-Cg7Dtcb4.js +2987 -0
  18. package/dist/chunk-Cg7Dtcb4.js.map +1 -0
  19. package/dist/chunk-DJqUsgsy.d.ts +1463 -0
  20. package/dist/chunk-DNc8T5K1.js +241 -0
  21. package/dist/chunk-DNc8T5K1.js.map +1 -0
  22. package/dist/chunk-DTxzw3hu.d.cts +1463 -0
  23. package/dist/chunk-DmxQID5X.js +2289 -0
  24. package/dist/chunk-DmxQID5X.js.map +1 -0
  25. package/dist/chunk-DoZt_oIV.d.ts +3991 -0
  26. package/dist/chunk-DpJrqANO.js +11 -0
  27. package/dist/chunk-Dx8mPAdC.d.cts +3991 -0
  28. package/dist/chunk-X2ukY3ho.js +419 -0
  29. package/dist/chunk-X2ukY3ho.js.map +1 -0
  30. package/dist/events/index.cjs +1338 -1874
  31. package/dist/events/index.cjs.map +1 -1
  32. package/dist/events/index.d.cts +373 -382
  33. package/dist/events/index.d.ts +373 -382
  34. package/dist/events/index.js +523 -806
  35. package/dist/events/index.js.map +1 -1
  36. package/dist/index.cjs +5908 -7988
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +37 -69
  39. package/dist/index.d.ts +37 -69
  40. package/dist/index.js +17 -48
  41. package/dist/index.js.map +1 -1
  42. package/package.json +7 -8
  43. package/src/browser.ts +1 -0
  44. package/src/core/rules/clientHeader.ts +1 -1
  45. package/src/core/rules/errors.ts +1 -1
  46. package/src/core/rules/nullMasks.gen.ts +14 -2
  47. package/src/core/rules/version.gen.ts +1 -1
  48. package/src/events/index.ts +1 -5
  49. package/src/rest/adminResources.gen.ts +2 -0
  50. package/src/rest/dates.gen.ts +1 -1
  51. package/src/rest/resources.gen.ts +2 -0
  52. package/src/rest/schema.gen.ts +247 -60
  53. package/src/tiles/schema.gen.ts +1 -3
  54. package/dist/chunk-BM526BHG.js +0 -342
  55. package/dist/chunk-BM526BHG.js.map +0 -1
  56. package/dist/chunk-D2YEVTG7.js +0 -327
  57. package/dist/chunk-D2YEVTG7.js.map +0 -1
  58. package/dist/chunk-OHKVUREN.js +0 -3500
  59. package/dist/chunk-OHKVUREN.js.map +0 -1
  60. package/dist/chunk-TDTK2L5H.js +0 -3842
  61. package/dist/chunk-TDTK2L5H.js.map +0 -1
  62. package/dist/coreOperations.gen-BMYPoBbz.d.ts +0 -1760
  63. package/dist/coreOperations.gen-BxX5xRxw.d.cts +0 -1760
  64. package/dist/errors-B-GqAtQv.d.cts +0 -75960
  65. package/dist/errors-B-GqAtQv.d.ts +0 -75960
  66. package/dist/operations.gen-CvTyzKNF.d.cts +0 -3993
  67. package/dist/operations.gen-DUD406TV.d.ts +0 -3993
@@ -1,826 +1,543 @@
1
- import { isHeaderValue, readFailure, MAX_TIMER_DELAY_MS } from '../chunk-D2YEVTG7.js';
2
- import { MountayaError, refuseOption, postAgentRun, MountayaApiError, postAgentRunInput, parseJsonWithDates, collabStreamEventDatesByType, withAbsentNulls, postItineraryCollab, postZoneCollab, isMountayaApiError, MountayaConfigurationError, isMountayaError, MountayaConnectionError } from '../chunk-TDTK2L5H.js';
3
-
4
- // src/events/rules/sse.ts
5
- var BYTE_ORDER_MARK = "\uFEFF";
6
- var MAX_SSE_BUFFER_CHARS = 8 * 1024 * 1024;
1
+ import { An as MountayaConnectionError, Bt as postItineraryCollab, Mn as MountayaError, Nt as postAgentRunInput, On as MountayaConfigurationError, Xn as isMountayaApiError, Zn as isMountayaError, bn as parseJsonWithDates, er as refuseOption, gn as collabStreamEventDatesByType, jt as postAgentRun, mn as postZoneCollab, wn as MountayaApiError, xn as withAbsentNulls } from "../chunk-Cg7Dtcb4.js";
2
+ import { a as readFailure, b as isHeaderValue, l as MAX_TIMER_DELAY_MS } from "../chunk-DNc8T5K1.js";
3
+ const BYTE_ORDER_MARK = "";
4
+ const MAX_SSE_BUFFER_CHARS = 8388608;
7
5
  var SseBufferOverflowError = class extends MountayaError {
8
- // The family's spelling, and not `this.name = …` in the constructor: every class here
9
- // declares its name as a string LITERAL on the class, because an identifier is what a
10
- // consumer's minifier renames and data is what survives it. `errors.test.ts` derives that
11
- // rule from the barrel, and this class is on it.
12
- name = "SseBufferOverflowError";
13
- /** The cap the parser enforced, in UTF-16 code units. */
14
- limit;
15
- /**
16
- * Builds the error a parser throws once its unterminated record passes the cap.
17
- *
18
- * @param limit - the cap the parser enforced, in UTF-16 code units.
19
- * @param operationId - the operation whose stream overflowed, where the thrower knows it: the
20
- * message then opens with it and ends with what a reopen would meet.
21
- * @param options - the standard error options, for the `cause` an opener hands on.
22
- */
23
- constructor(limit, operationId, options) {
24
- const overflow = `sse frame parser: unterminated frame exceeded ${limit} characters`;
25
- super(
26
- operationId === void 0 ? overflow : `${operationId}: ${overflow}. The producer never ended the record, and a reopen meets it again.`,
27
- options
28
- );
29
- this.limit = limit;
30
- }
6
+ name = "SseBufferOverflowError";
7
+ limit;
8
+ constructor(limit, operationId, options) {
9
+ const overflow = `sse frame parser: unterminated frame exceeded ${limit} characters`;
10
+ super(operationId === void 0 ? overflow : `${operationId}: ${overflow}. The producer never ended the record, and a reopen meets it again.`, options);
11
+ this.limit = limit;
12
+ }
31
13
  };
32
14
  var SseFrameParser = class {
33
- // The unterminated line, in the pieces the pushes delivered it in, and how long they are
34
- // together. Joined once, when the line ends, so a long line is never copied per push.
35
- lineParts = [];
36
- lineLength = 0;
37
- // What the current record holds: its data lines, its event name, and its own `id:`, which is
38
- // undefined until it names one.
39
- dataLines = [];
40
- event = "";
41
- recordId;
42
- // The characters of the current record's completed lines, line endings included. With the
43
- // unterminated line, it is what the cap bounds.
44
- recordLength = 0;
45
- // The stream's last event ID, moved when a record naming an `id:` ends, and undefined until one
46
- // does.
47
- lastId;
48
- // No character has arrived yet, so a byte-order mark opening the next one is still dropped.
49
- atStart = true;
50
- // Whether the last character read is a CR that ended a line, so an LF arriving next completes
51
- // a CRLF.
52
- afterCarriageReturn = false;
53
- // Set past the cap, for good.
54
- overflowed = false;
55
- // The cap on the unterminated record, checked at construction.
56
- maxBufferChars;
57
- /**
58
- * Builds a parser that holds at most `maxBufferChars` of a record it has not seen the end of.
59
- *
60
- * @param maxBufferChars - bounds the unterminated record this parser holds, in UTF-16 code
61
- * units: a whole number of 1 or more. A consumer whose frames are known small may tighten
62
- * it; the shared readers take the default. A cap that is not a number of characters would
63
- * bound nothing (`NaN` and `Infinity` are exceeded by no length) or refuse every push (zero
64
- * and below), so it is refused here.
65
- * @default MAX_SSE_BUFFER_CHARS
66
- * @throws `MountayaConfigurationError` for a cap that is not a whole number of 1 or more.
67
- */
68
- constructor(maxBufferChars = MAX_SSE_BUFFER_CHARS) {
69
- const given = maxBufferChars;
70
- if (typeof given !== "number" || !Number.isInteger(given) || given < 1) {
71
- throw refuseOption(
72
- "maxBufferChars",
73
- given,
74
- `pass a whole number of characters of 1 or more, or leave it out for the default of ${MAX_SSE_BUFFER_CHARS}.`
75
- );
76
- }
77
- this.maxBufferChars = given;
78
- }
79
- /**
80
- * lastEventId is the stream's last event ID, as the HTML standard defines it: the value of the
81
- * latest `id:` in a record the parser has seen the end of, whatever else that record carried.
82
- *
83
- * It is the position a reconnect resumes from, sent as `Last-Event-ID`. It carries over a
84
- * record that names no `id:`, an empty `id:` clears it to the empty string, and an `id:` holding
85
- * U+0000 is ignored. An `id:` in a record still unterminated has not moved it: a reconnect
86
- * discards that record, so resuming past it would skip it.
87
- *
88
- * It is `undefined` until the stream names a position, where the standard starts from the empty
89
- * string, so a stream that names none reads apart from one that clears it. A caller resuming
90
- * from a position an earlier connection named keeps that position through the first and drops
91
- * it at the second.
92
- */
93
- get lastEventId() {
94
- return this.lastId;
95
- }
96
- /**
97
- * push feeds the next decoded text chunk and returns every frame the records it completes
98
- * dispatch, in stream order. What it leaves unterminated stays held for the next push, unless it
99
- * passes the cap: then push throws {@link SseBufferOverflowError} instead of returning, dropping
100
- * the frames the same chunk completed. The stream is being torn down with them, and a caller
101
- * that resumes re-reads from the position it last recorded.
102
- */
103
- push(chunk) {
104
- if (this.overflowed) {
105
- throw new SseBufferOverflowError(this.maxBufferChars);
106
- }
107
- const frames = [];
108
- let start = 0;
109
- if (chunk.length > 0) {
110
- if (this.atStart) {
111
- this.atStart = false;
112
- if (chunk.startsWith(BYTE_ORDER_MARK)) {
113
- start = BYTE_ORDER_MARK.length;
114
- }
115
- }
116
- if (this.afterCarriageReturn) {
117
- this.afterCarriageReturn = false;
118
- if (chunk.startsWith("\n", start)) {
119
- start += 1;
120
- }
121
- }
122
- }
123
- let carriageReturn = chunk.indexOf("\r", start);
124
- let lineFeed = chunk.indexOf("\n", start);
125
- while (carriageReturn !== -1 || lineFeed !== -1) {
126
- const end = carriageReturn === -1 || lineFeed !== -1 && lineFeed < carriageReturn ? lineFeed : carriageReturn;
127
- let next = end + 1;
128
- if (end === carriageReturn) {
129
- if (next === chunk.length) {
130
- this.afterCarriageReturn = true;
131
- } else if (chunk.startsWith("\n", next)) {
132
- next += 1;
133
- }
134
- }
135
- const line = this.completeLine(chunk.slice(start, end));
136
- this.recordLength += line.length + (next - end);
137
- const frame = this.readLine(line);
138
- if (frame !== null) {
139
- frames.push(frame);
140
- }
141
- start = next;
142
- if (carriageReturn !== -1 && carriageReturn < start) {
143
- carriageReturn = chunk.indexOf("\r", start);
144
- }
145
- if (lineFeed !== -1 && lineFeed < start) {
146
- lineFeed = chunk.indexOf("\n", start);
147
- }
148
- }
149
- if (start < chunk.length) {
150
- this.lineParts.push(chunk.slice(start));
151
- this.lineLength += chunk.length - start;
152
- }
153
- if (this.recordLength + this.lineLength > this.maxBufferChars) {
154
- this.lineParts = [];
155
- this.lineLength = 0;
156
- this.startRecord();
157
- this.overflowed = true;
158
- throw new SseBufferOverflowError(this.maxBufferChars);
159
- }
160
- return frames;
161
- }
162
- /**
163
- * completeLine joins the line held from earlier pushes with its last piece, `tail`, and starts
164
- * the next line empty.
165
- */
166
- completeLine(tail) {
167
- if (this.lineParts.length === 0) {
168
- return tail;
169
- }
170
- this.lineParts.push(tail);
171
- const line = this.lineParts.join("");
172
- this.lineParts = [];
173
- this.lineLength = 0;
174
- return line;
175
- }
176
- /**
177
- * readLine applies one complete line to the current record, and returns the frame the record
178
- * dispatches when the line is the empty one that ends it.
179
- *
180
- * A field line is split at its first colon, and one space after the colon is dropped: only the
181
- * first space is the standard's separator, and a second one is part of the value. A line with no
182
- * colon is its whole self as the field name, with an empty value.
183
- */
184
- readLine(line) {
185
- if (line === "") {
186
- return this.endRecord();
187
- }
188
- if (line.startsWith(":")) {
189
- return null;
190
- }
191
- const colon = line.indexOf(":");
192
- const field = colon === -1 ? line : line.slice(0, colon);
193
- const raw = colon === -1 ? "" : line.slice(colon + 1);
194
- const value = raw.startsWith(" ") ? raw.slice(1) : raw;
195
- if (field === "data") {
196
- this.dataLines.push(value);
197
- } else if (field === "event") {
198
- this.event = value;
199
- } else if (field === "id" && !value.includes("\0")) {
200
- this.recordId = value;
201
- }
202
- return null;
203
- }
204
- /**
205
- * endRecord closes the current record: an `id:` it named becomes the stream's last event ID,
206
- * and it returns the frame the record dispatches, or null for a record with no data.
207
- */
208
- endRecord() {
209
- const { dataLines, event, recordId } = this;
210
- this.startRecord();
211
- if (recordId !== void 0) {
212
- this.lastId = recordId;
213
- }
214
- if (dataLines.length === 0) {
215
- return null;
216
- }
217
- return { data: dataLines.join("\n"), event, id: recordId ?? "" };
218
- }
219
- /** startRecord empties the record being read, so the next line begins the next one. */
220
- startRecord() {
221
- this.dataLines = [];
222
- this.event = "";
223
- this.recordId = void 0;
224
- this.recordLength = 0;
225
- }
15
+ lineParts = [];
16
+ lineLength = 0;
17
+ dataLines = [];
18
+ event = "";
19
+ recordId;
20
+ recordLength = 0;
21
+ lastId;
22
+ atStart = true;
23
+ afterCarriageReturn = false;
24
+ overflowed = false;
25
+ maxBufferChars;
26
+ constructor(maxBufferChars = MAX_SSE_BUFFER_CHARS) {
27
+ const given = maxBufferChars;
28
+ 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}.`);
29
+ this.maxBufferChars = given;
30
+ }
31
+ get lastEventId() {
32
+ return this.lastId;
33
+ }
34
+ push(chunk) {
35
+ if (this.overflowed) throw new SseBufferOverflowError(this.maxBufferChars);
36
+ const frames = [];
37
+ let start = 0;
38
+ if (chunk.length > 0) {
39
+ if (this.atStart) {
40
+ this.atStart = false;
41
+ if (chunk.startsWith(BYTE_ORDER_MARK)) start = 1;
42
+ }
43
+ if (this.afterCarriageReturn) {
44
+ this.afterCarriageReturn = false;
45
+ if (chunk.startsWith("\n", start)) start += 1;
46
+ }
47
+ }
48
+ let carriageReturn = chunk.indexOf("\r", start);
49
+ let lineFeed = chunk.indexOf("\n", start);
50
+ while (carriageReturn !== -1 || lineFeed !== -1) {
51
+ const end = carriageReturn === -1 || lineFeed !== -1 && lineFeed < carriageReturn ? lineFeed : carriageReturn;
52
+ let next = end + 1;
53
+ if (end === carriageReturn) {
54
+ if (next === chunk.length) this.afterCarriageReturn = true;
55
+ else if (chunk.startsWith("\n", next)) next += 1;
56
+ }
57
+ const line = this.completeLine(chunk.slice(start, end));
58
+ this.recordLength += line.length + (next - end);
59
+ const frame = this.readLine(line);
60
+ if (frame !== null) frames.push(frame);
61
+ start = next;
62
+ if (carriageReturn !== -1 && carriageReturn < start) carriageReturn = chunk.indexOf("\r", start);
63
+ if (lineFeed !== -1 && lineFeed < start) lineFeed = chunk.indexOf("\n", start);
64
+ }
65
+ if (start < chunk.length) {
66
+ this.lineParts.push(chunk.slice(start));
67
+ this.lineLength += chunk.length - start;
68
+ }
69
+ if (this.recordLength + this.lineLength > this.maxBufferChars) {
70
+ this.lineParts = [];
71
+ this.lineLength = 0;
72
+ this.startRecord();
73
+ this.overflowed = true;
74
+ throw new SseBufferOverflowError(this.maxBufferChars);
75
+ }
76
+ return frames;
77
+ }
78
+ completeLine(tail) {
79
+ if (this.lineParts.length === 0) return tail;
80
+ this.lineParts.push(tail);
81
+ const line = this.lineParts.join("");
82
+ this.lineParts = [];
83
+ this.lineLength = 0;
84
+ return line;
85
+ }
86
+ readLine(line) {
87
+ if (line === "") return this.endRecord();
88
+ if (line.startsWith(":")) return null;
89
+ const colon = line.indexOf(":");
90
+ const field = colon === -1 ? line : line.slice(0, colon);
91
+ const raw = colon === -1 ? "" : line.slice(colon + 1);
92
+ const value = raw.startsWith(" ") ? raw.slice(1) : raw;
93
+ if (field === "data") this.dataLines.push(value);
94
+ else if (field === "event") this.event = value;
95
+ else if (field === "id" && !value.includes("\0")) this.recordId = value;
96
+ return null;
97
+ }
98
+ endRecord() {
99
+ const { dataLines, event, recordId } = this;
100
+ this.startRecord();
101
+ if (recordId !== void 0) this.lastId = recordId;
102
+ if (dataLines.length === 0) return null;
103
+ return {
104
+ data: dataLines.join("\n"),
105
+ event,
106
+ id: recordId ?? ""
107
+ };
108
+ }
109
+ startRecord() {
110
+ this.dataLines = [];
111
+ this.event = "";
112
+ this.recordId = void 0;
113
+ this.recordLength = 0;
114
+ }
226
115
  };
227
-
228
- // src/events/rules/eventStream.ts
229
- var readEventStream = async (body, onFrame, onLastEventId) => {
230
- const reader = body.getReader();
231
- const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
232
- const parser = new SseFrameParser();
233
- let known;
234
- try {
235
- while (true) {
236
- const { done, value } = await reader.read();
237
- if (done) {
238
- return "ended";
239
- }
240
- for (const frame of parser.push(decoder.decode(value, { stream: true }))) {
241
- if (frame.id !== "") {
242
- known = frame.id;
243
- }
244
- const stop = await onFrame(frame);
245
- if (stop) {
246
- return "stopped";
247
- }
248
- }
249
- const position = parser.lastEventId;
250
- if (position !== void 0 && position !== known) {
251
- known = position;
252
- onLastEventId?.(position);
253
- }
254
- }
255
- } finally {
256
- reader.releaseLock();
257
- }
116
+ const readEventStream = async (body, onFrame, onLastEventId) => {
117
+ const reader = body.getReader();
118
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
119
+ const parser = new SseFrameParser();
120
+ let known;
121
+ try {
122
+ while (true) {
123
+ const { done, value } = await reader.read();
124
+ if (done) return "ended";
125
+ for (const frame of parser.push(decoder.decode(value, { stream: true }))) {
126
+ if (frame.id !== "") known = frame.id;
127
+ if (await onFrame(frame)) return "stopped";
128
+ }
129
+ const position = parser.lastEventId;
130
+ if (position !== void 0 && position !== known) {
131
+ known = position;
132
+ onLastEventId?.(position);
133
+ }
134
+ }
135
+ } finally {
136
+ reader.releaseLock();
137
+ }
258
138
  };
259
-
260
- // src/events/rules/openSseStream.ts
261
- var STALL_WINDOW_MS = 45e3;
262
- var SILENCE = /* @__PURE__ */ Symbol("silence");
263
- var LET_GO = /* @__PURE__ */ Symbol("let go");
264
- var boundSilence = (body, operationId, signal) => {
265
- const reader = body.getReader();
266
- const letGo = () => {
267
- try {
268
- reader.releaseLock();
269
- } catch {
270
- }
271
- };
272
- let endWait;
273
- if (signal.aborted) {
274
- letGo();
275
- } else {
276
- signal.addEventListener(
277
- "abort",
278
- () => {
279
- endWait?.(LET_GO);
280
- letGo();
281
- },
282
- { once: true }
283
- );
284
- }
285
- return new ReadableStream(
286
- {
287
- cancel: (reason) => reader.cancel(reason),
288
- pull: async (controller) => {
289
- if (signal.aborted) {
290
- controller.close();
291
- return;
292
- }
293
- let timer;
294
- const ended = new Promise((resolve) => {
295
- endWait = resolve;
296
- timer = setTimeout(() => resolve(SILENCE), STALL_WINDOW_MS);
297
- });
298
- try {
299
- const next = await Promise.race([reader.read(), ended]);
300
- if (next === LET_GO) {
301
- controller.close();
302
- return;
303
- }
304
- if (next === SILENCE) {
305
- throw new MountayaConnectionError(
306
- `${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.`
307
- );
308
- }
309
- if (next.done) {
310
- controller.close();
311
- } else {
312
- controller.enqueue(next.value);
313
- }
314
- } finally {
315
- endWait = void 0;
316
- clearTimeout(timer);
317
- if (signal.aborted) {
318
- letGo();
319
- }
320
- }
321
- }
322
- },
323
- // A read-ahead queue of none: the next chunk is asked for only when the reader asks.
324
- { highWaterMark: 0 }
325
- );
139
+ const STALL_WINDOW_MS = 45e3;
140
+ const SILENCE = Symbol("silence");
141
+ const LET_GO = Symbol("let go");
142
+ const boundSilence = (body, operationId, signal) => {
143
+ const reader = body.getReader();
144
+ const letGo = () => {
145
+ try {
146
+ reader.releaseLock();
147
+ } catch {}
148
+ };
149
+ let endWait;
150
+ if (signal.aborted) letGo();
151
+ else signal.addEventListener("abort", () => {
152
+ endWait?.(LET_GO);
153
+ letGo();
154
+ }, { once: true });
155
+ return new ReadableStream({
156
+ cancel: (reason) => reader.cancel(reason),
157
+ pull: async (controller) => {
158
+ if (signal.aborted) {
159
+ controller.close();
160
+ return;
161
+ }
162
+ let timer;
163
+ const ended = new Promise((resolve) => {
164
+ endWait = resolve;
165
+ timer = setTimeout(() => resolve(SILENCE), STALL_WINDOW_MS);
166
+ });
167
+ try {
168
+ const next = await Promise.race([reader.read(), ended]);
169
+ if (next === LET_GO) {
170
+ controller.close();
171
+ return;
172
+ }
173
+ 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.`);
174
+ if (next.done) controller.close();
175
+ else controller.enqueue(next.value);
176
+ } finally {
177
+ endWait = void 0;
178
+ clearTimeout(timer);
179
+ if (signal.aborted) letGo();
180
+ }
181
+ }
182
+ }, { highWaterMark: 0 });
326
183
  };
327
- var openTimeoutOf = (timeoutMs, operationId) => {
328
- if (timeoutMs === void 0) {
329
- return STALL_WINDOW_MS;
330
- }
331
- if (Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= MAX_TIMER_DELAY_MS) {
332
- return timeoutMs;
333
- }
334
- throw refuseOption(
335
- "timeoutMs",
336
- timeoutMs,
337
- `pass a whole number of milliseconds from 1 to ${MAX_TIMER_DELAY_MS}, or leave it out to wait at most ${STALL_WINDOW_MS}.`,
338
- operationId
339
- );
184
+ const openTimeoutOf = (timeoutMs, operationId) => {
185
+ if (timeoutMs === void 0) return STALL_WINDOW_MS;
186
+ if (Number.isInteger(timeoutMs) && timeoutMs >= 1 && timeoutMs <= MAX_TIMER_DELAY_MS) return timeoutMs;
187
+ 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);
340
188
  };
341
- var requestStream = async (options, state, declaration) => {
342
- const { operationId } = options;
343
- const openTimeout = openTimeoutOf(options.timeoutMs, operationId);
344
- const headers = new Headers({ Accept: "text/event-stream" });
345
- if (options.lastEventId) {
346
- const position = String(options.lastEventId);
347
- if (!isHeaderValue(position)) {
348
- throw new MountayaConfigurationError(
349
- `${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.`
350
- );
351
- }
352
- headers.set("Last-Event-ID", position);
353
- }
354
- const waiting = options.waitForSession?.(state.controller.signal);
355
- if (waiting !== void 0) {
356
- await waiting;
357
- }
358
- const url = typeof options.url === "function" ? options.url() : options.url;
359
- const init = options.applyAuth({ headers, signal: state.controller.signal }, "GET");
360
- let timedOut = false;
361
- const deadline = setTimeout(() => {
362
- timedOut = true;
363
- state.controller.abort();
364
- }, openTimeout);
365
- let response;
366
- try {
367
- response = await options.doFetch(url, init);
368
- } catch (cause) {
369
- if (state.closedByCaller) {
370
- throw cause;
371
- }
372
- if (timedOut) {
373
- throw new MountayaConnectionError(
374
- 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.`
375
- );
376
- }
377
- if (isMountayaError(cause)) {
378
- throw cause;
379
- }
380
- throw new MountayaConnectionError(
381
- `${operationId}: the stream failed before a response arrived. Check the network, and that the stream's URL names a host that answers.`,
382
- cause
383
- );
384
- } finally {
385
- clearTimeout(deadline);
386
- }
387
- options.onResponse?.(response);
388
- if (!response.ok) {
389
- throw await readFailure(response, {
390
- ...declaration,
391
- operationId,
392
- signal: state.controller.signal
393
- });
394
- }
395
- const body = response.body;
396
- if (body === void 0) {
397
- throw new MountayaConfigurationError(
398
- `${operationId}: this runtime's fetch exposes no response body to read the stream from. Pass a fetch that streams response bodies.`
399
- );
400
- }
401
- if (body === null) {
402
- throw new MountayaConnectionError(
403
- `${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.`
404
- );
405
- }
406
- return body;
189
+ const requestStream = async (options, state, declaration) => {
190
+ const { operationId } = options;
191
+ const openTimeout = openTimeoutOf(options.timeoutMs, operationId);
192
+ const headers = new Headers({ Accept: "text/event-stream" });
193
+ if (options.lastEventId) {
194
+ const position = String(options.lastEventId);
195
+ 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.`);
196
+ headers.set("Last-Event-ID", position);
197
+ }
198
+ const waiting = options.waitForSession?.(state.controller.signal);
199
+ if (waiting !== void 0) await waiting;
200
+ const url = typeof options.url === "function" ? options.url() : options.url;
201
+ const init = options.applyAuth({
202
+ headers,
203
+ signal: state.controller.signal
204
+ }, "GET");
205
+ let timedOut = false;
206
+ const deadline = setTimeout(() => {
207
+ timedOut = true;
208
+ state.controller.abort();
209
+ }, openTimeout);
210
+ let response;
211
+ try {
212
+ response = await options.doFetch(url, init);
213
+ } catch (cause) {
214
+ if (state.closedByCaller) throw cause;
215
+ 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.`);
216
+ if (isMountayaError(cause)) throw cause;
217
+ 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);
218
+ } finally {
219
+ clearTimeout(deadline);
220
+ }
221
+ options.onResponse?.(response);
222
+ if (!response.ok) throw await readFailure(response, {
223
+ ...declaration,
224
+ operationId,
225
+ signal: state.controller.signal
226
+ });
227
+ const body = response.body;
228
+ 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.`);
229
+ 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.`);
230
+ return body;
407
231
  };
408
- var openDeclaredSseStream = (options, declaration) => {
409
- const { operationId, signal } = options;
410
- const state = { closedByCaller: false, controller: new AbortController() };
411
- const close = () => {
412
- state.closedByCaller = true;
413
- state.controller.abort();
414
- };
415
- if (signal?.aborted) {
416
- close();
417
- } else {
418
- signal?.addEventListener("abort", close, { once: true });
419
- }
420
- let callerFault = false;
421
- const handle = async (frame) => {
422
- if (state.closedByCaller) {
423
- return true;
424
- }
425
- try {
426
- const event = options.decode(frame);
427
- if (event === null) {
428
- return false;
429
- }
430
- return await options.onFrame(event, frame.id || void 0);
431
- } catch (error) {
432
- callerFault = true;
433
- throw error;
434
- }
435
- };
436
- const report = (lastEventId) => {
437
- if (state.closedByCaller) {
438
- return;
439
- }
440
- try {
441
- options.onLastEventId?.(lastEventId || void 0);
442
- } catch (error) {
443
- callerFault = true;
444
- throw error;
445
- }
446
- };
447
- const read = async () => {
448
- const body = await requestStream(options, state, declaration);
449
- try {
450
- return await readEventStream(
451
- boundSilence(body, operationId, state.controller.signal),
452
- handle,
453
- report
454
- );
455
- } catch (cause) {
456
- if (state.closedByCaller || callerFault) {
457
- throw cause;
458
- }
459
- if (cause instanceof SseBufferOverflowError) {
460
- throw new SseBufferOverflowError(cause.limit, operationId, { cause });
461
- }
462
- if (isMountayaError(cause)) {
463
- throw cause;
464
- }
465
- throw new MountayaConnectionError(
466
- `${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.`,
467
- cause
468
- );
469
- }
470
- };
471
- void (async () => {
472
- if (state.closedByCaller) {
473
- return;
474
- }
475
- let settled;
476
- try {
477
- settled = { outcome: await read() };
478
- } catch (error) {
479
- settled = { error };
480
- }
481
- signal?.removeEventListener("abort", close);
482
- state.controller.abort();
483
- if (state.closedByCaller) {
484
- return;
485
- }
486
- if ("outcome" in settled) {
487
- options.onClose?.(settled.outcome);
488
- } else {
489
- options.onError?.(settled.error);
490
- }
491
- })();
492
- return close;
232
+ const openDeclaredSseStream = (options, declaration) => {
233
+ const { operationId, signal } = options;
234
+ const state = {
235
+ closedByCaller: false,
236
+ controller: new AbortController()
237
+ };
238
+ const close = () => {
239
+ state.closedByCaller = true;
240
+ state.controller.abort();
241
+ };
242
+ if (signal?.aborted) close();
243
+ else signal?.addEventListener("abort", close, { once: true });
244
+ let callerFault = false;
245
+ const handle = async (frame) => {
246
+ if (state.closedByCaller) return true;
247
+ try {
248
+ const event = options.decode(frame);
249
+ if (event === null) return false;
250
+ return await options.onFrame(event, frame.id || void 0);
251
+ } catch (error) {
252
+ callerFault = true;
253
+ throw error;
254
+ }
255
+ };
256
+ const report = (lastEventId) => {
257
+ if (state.closedByCaller) return;
258
+ try {
259
+ options.onLastEventId?.(lastEventId || void 0);
260
+ } catch (error) {
261
+ callerFault = true;
262
+ throw error;
263
+ }
264
+ };
265
+ const read = async () => {
266
+ const body = await requestStream(options, state, declaration);
267
+ try {
268
+ return await readEventStream(boundSilence(body, operationId, state.controller.signal), handle, report);
269
+ } catch (cause) {
270
+ if (state.closedByCaller || callerFault) throw cause;
271
+ if (cause instanceof SseBufferOverflowError) throw new SseBufferOverflowError(cause.limit, operationId, { cause });
272
+ if (isMountayaError(cause)) throw cause;
273
+ 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);
274
+ }
275
+ };
276
+ (async () => {
277
+ if (state.closedByCaller) return;
278
+ let settled;
279
+ try {
280
+ settled = { outcome: await read() };
281
+ } catch (error) {
282
+ settled = { error };
283
+ }
284
+ signal?.removeEventListener("abort", close);
285
+ state.controller.abort();
286
+ if (state.closedByCaller) return;
287
+ if ("outcome" in settled) options.onClose?.(settled.outcome);
288
+ else options.onError?.(settled.error);
289
+ })();
290
+ return close;
493
291
  };
494
- var openSseStream = (options) => openDeclaredSseStream(options, void 0);
495
-
496
- // src/events/rules/agent.ts
497
- var agentRunEventTypes = {
498
- "awaiting-input": "awaiting-input",
499
- "budget-exhausted": "budget-exhausted",
500
- "checks-unmet": "checks-unmet",
501
- "confirm-required": "confirm-required",
502
- done: "done",
503
- error: "error",
504
- message: "message",
505
- "message-delta": "message-delta",
506
- reconnect: "reconnect",
507
- "tool-abandoned": "tool-abandoned",
508
- "tool-call": "tool-call",
509
- "tool-result": "tool-result"
292
+ const openSseStream = (options) => openDeclaredSseStream(options, void 0);
293
+ const agentRunEventTypes = {
294
+ "awaiting-input": "awaiting-input",
295
+ "budget-exhausted": "budget-exhausted",
296
+ "checks-unmet": "checks-unmet",
297
+ "confirm-required": "confirm-required",
298
+ done: "done",
299
+ error: "error",
300
+ message: "message",
301
+ "message-delta": "message-delta",
302
+ reconnect: "reconnect",
303
+ "tool-abandoned": "tool-abandoned",
304
+ "tool-call": "tool-call",
305
+ "tool-result": "tool-result"
510
306
  };
511
- var agentTerminalEventTypes = /* @__PURE__ */ new Set([
512
- agentRunEventTypes.done
513
- ]);
514
- var runIdFrom = (body) => {
515
- const id = body?.data?.id;
516
- return typeof id === "string" && id !== "" ? id : void 0;
307
+ const agentTerminalEventTypes = /* @__PURE__ */ new Set([agentRunEventTypes.done]);
308
+ const runIdFrom = (body) => {
309
+ const id = body?.data?.id;
310
+ return typeof id === "string" && id !== "" ? id : void 0;
517
311
  };
518
- var decodeAgentFrame = (frame) => {
519
- if (!Object.hasOwn(agentRunEventTypes, frame.event)) {
520
- return null;
521
- }
522
- let payload;
523
- try {
524
- payload = frame.data ? JSON.parse(frame.data) : {};
525
- } catch {
526
- return null;
527
- }
528
- if (typeof payload !== "object" || payload === null) {
529
- return null;
530
- }
531
- return { ...payload, type: frame.event };
312
+ const decodeAgentFrame = (frame) => {
313
+ if (!Object.hasOwn(agentRunEventTypes, frame.event)) return null;
314
+ let payload;
315
+ try {
316
+ payload = frame.data ? JSON.parse(frame.data) : {};
317
+ } catch {
318
+ return null;
319
+ }
320
+ if (typeof payload !== "object" || payload === null) return null;
321
+ return {
322
+ ...payload,
323
+ type: frame.event
324
+ };
532
325
  };
533
- var AGENT_EVENTS_OPERATION_ID = "getAgentRunEvents";
534
- var refuseServerToolsUnderKey = (transport, operationId, serverTools) => {
535
- if (serverTools === void 0 || serverTools.length === 0) {
536
- return;
537
- }
538
- if (transport.mapCredential.publishableKey === void 0) {
539
- return;
540
- }
541
- throw new MountayaConfigurationError(
542
- `${operationId}: a run under a publishable key calls no server tool, so server_tools must be empty. Turn routesServerTools off.`
543
- );
326
+ const AGENT_EVENTS_OPERATION_ID = "getAgentRunEvents";
327
+ const refuseServerToolsUnderKey = (transport, operationId, serverTools) => {
328
+ if (serverTools === void 0 || serverTools.length === 0) return;
329
+ if (transport.mapCredential.publishableKey === void 0) return;
330
+ throw new MountayaConfigurationError(`${operationId}: a run under a publishable key calls no server tool, so server_tools must be empty. Turn routesServerTools off.`);
544
331
  };
545
- var isReconnect = (event) => event.type === agentRunEventTypes.reconnect;
546
- var createAgentTransport = (transport) => ({
547
- sendInput: async (runId, input, options) => {
548
- if (input.type === "manifest-update") {
549
- refuseServerToolsUnderKey(transport, "postAgentRunInput", input.server_tools);
550
- }
551
- await postAgentRunInput(transport, {
552
- body: input,
553
- idempotencyKey: options?.idempotencyKey,
554
- run_id: runId
555
- });
556
- },
557
- startRun: async (params, options) => {
558
- refuseServerToolsUnderKey(transport, "postAgentRun", params.server_tools);
559
- const body = await postAgentRun(transport, {
560
- body: params,
561
- idempotencyKey: options?.idempotencyKey
562
- });
563
- const runId = runIdFrom(body);
564
- if (runId === void 0) {
565
- throw new MountayaApiError("postAgentRun: 202 named no run", 202, []);
566
- }
567
- return { runId };
568
- },
569
- subscribe: (runId, handlers, options) => {
570
- const seam = transport.streamSeam;
571
- let expiresAt;
572
- let reconnected = false;
573
- return openDeclaredSseStream(
574
- {
575
- // What `getAgentRunEvents` declares, stated as its generated operation states it: its
576
- // only security requirement pairs the key with a session token, and the stream acts as
577
- // the member that token names. Stating both here is what refuses a credential carrying no
578
- // session token, or one a source reports as minted without `user_id`, before the open;
579
- // the refusal reaches onError like any other failed open. No share token reaches it, which
580
- // the absence of `acceptsShareToken` says.
581
- applyAuth: (init, method) => {
582
- const applied = seam.applyAuth(init, method, {
583
- actsAsMember: true,
584
- operationId: AGENT_EVENTS_OPERATION_ID,
585
- requiresSession: true
586
- });
587
- expiresAt = seam.sessionExpiresAt();
588
- return applied;
589
- },
590
- // A frame skipped is still one the stream delivered, which the subscriber is told of as it
591
- // is read, in order with the frames handed over.
592
- decode: (frame) => {
593
- const event = decodeAgentFrame(frame);
594
- if (event === null) {
595
- handlers.onSkippedFrame?.();
596
- }
597
- return event;
598
- },
599
- doFetch: seam.doFetch,
600
- lastEventId: options?.lastEventId,
601
- onClose: (outcome) => {
602
- if (outcome === "stopped") {
603
- handlers.onClose(reconnected ? "reconnect" : "terminal");
604
- return;
605
- }
606
- const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
607
- handlers.onClose(expired ? "reconnect" : "ended");
608
- },
609
- onError: (error) => handlers.onError(error),
610
- onFrame: async (event, id) => {
611
- if (isReconnect(event)) {
612
- reconnected = true;
613
- return true;
614
- }
615
- await handlers.onFrame({ event, id });
616
- return agentTerminalEventTypes.has(event.type);
617
- },
618
- onLastEventId: (lastEventId) => handlers.onLastEventId?.(lastEventId),
619
- onResponse: (response) => {
620
- seam.report(response, AGENT_EVENTS_OPERATION_ID);
621
- },
622
- operationId: AGENT_EVENTS_OPERATION_ID,
623
- signal: options?.signal,
624
- // The wait for the stream's response is the client's own per-attempt budget.
625
- timeoutMs: seam.timeoutMs,
626
- // Resolved when the open is made, so a run id the path cannot carry (an empty one, or a
627
- // dot segment) is refused through onError like any other failed open.
628
- url: () => seam.url(`/v1/agent/runs/${encodeURIComponent(runId)}/events`, AGENT_EVENTS_OPERATION_ID),
629
- waitForSession: (signal) => seam.waitForSession(AGENT_EVENTS_OPERATION_ID, signal)
630
- },
631
- // The same declaration the credential is stamped by, so a refused open names the step a
632
- // member reading their own run takes.
633
- { actsAsMember: true }
634
- );
635
- }
332
+ const isReconnect = (event) => event.type === agentRunEventTypes.reconnect;
333
+ const createAgentTransport = (transport) => ({
334
+ sendInput: async (runId, input, options) => {
335
+ if (input.type === "manifest-update") refuseServerToolsUnderKey(transport, "postAgentRunInput", input.server_tools);
336
+ await postAgentRunInput(transport, {
337
+ body: input,
338
+ idempotencyKey: options?.idempotencyKey,
339
+ run_id: runId
340
+ });
341
+ },
342
+ startRun: async (params, options) => {
343
+ refuseServerToolsUnderKey(transport, "postAgentRun", params.server_tools);
344
+ const body = await postAgentRun(transport, {
345
+ body: params,
346
+ idempotencyKey: options?.idempotencyKey
347
+ });
348
+ const runId = runIdFrom(body);
349
+ if (runId === void 0) throw new MountayaApiError("postAgentRun: 202 named no run", 202, []);
350
+ return { runId };
351
+ },
352
+ subscribe: (runId, handlers, options) => {
353
+ const seam = transport.streamSeam;
354
+ let expiresAt;
355
+ let reconnected = false;
356
+ return openDeclaredSseStream({
357
+ applyAuth: (init, method) => {
358
+ const applied = seam.applyAuth(init, method, {
359
+ actsAsMember: true,
360
+ operationId: AGENT_EVENTS_OPERATION_ID,
361
+ requiresSession: true
362
+ });
363
+ expiresAt = seam.sessionExpiresAt();
364
+ return applied;
365
+ },
366
+ decode: (frame) => {
367
+ const event = decodeAgentFrame(frame);
368
+ if (event === null) handlers.onSkippedFrame?.();
369
+ return event;
370
+ },
371
+ doFetch: seam.doFetch,
372
+ lastEventId: options?.lastEventId,
373
+ onClose: (outcome) => {
374
+ if (outcome === "stopped") {
375
+ handlers.onClose(reconnected ? "reconnect" : "terminal");
376
+ return;
377
+ }
378
+ const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
379
+ handlers.onClose(expired ? "reconnect" : "ended");
380
+ },
381
+ onError: (error) => handlers.onError(error),
382
+ onFrame: async (event, id) => {
383
+ if (isReconnect(event)) {
384
+ reconnected = true;
385
+ return true;
386
+ }
387
+ await handlers.onFrame({
388
+ event,
389
+ id
390
+ });
391
+ return agentTerminalEventTypes.has(event.type);
392
+ },
393
+ onLastEventId: (lastEventId) => handlers.onLastEventId?.(lastEventId),
394
+ onResponse: (response) => {
395
+ seam.report(response, AGENT_EVENTS_OPERATION_ID);
396
+ },
397
+ operationId: AGENT_EVENTS_OPERATION_ID,
398
+ signal: options?.signal,
399
+ timeoutMs: seam.timeoutMs,
400
+ url: () => seam.url(`/v1/agent/runs/${encodeURIComponent(runId)}/events`, AGENT_EVENTS_OPERATION_ID),
401
+ waitForSession: (signal) => seam.waitForSession(AGENT_EVENTS_OPERATION_ID, signal)
402
+ }, { actsAsMember: true });
403
+ }
636
404
  });
637
-
638
- // src/events/rules/collabNulls.gen.ts
639
- var collabCursorEventNulls = { position: true };
640
- var collabSelectionEventNulls = { selection: true };
641
- var collabStreamEventNulls = ["type", { cursor: collabCursorEventNulls, selection: collabSelectionEventNulls }];
642
-
643
- // src/events/rules/collab.ts
644
- var collabStreamEventTypes = {
645
- "collection.changed": "collection.changed",
646
- cursor: "cursor",
647
- "draft.clear": "draft.clear",
648
- "draft.update": "draft.update",
649
- "itinerary.changed": "itinerary.changed",
650
- "lock.acquired": "lock.acquired",
651
- "lock.released": "lock.released",
652
- "lock.snapshot": "lock.snapshot",
653
- "presence.join": "presence.join",
654
- "presence.leave": "presence.leave",
655
- "presence.snapshot": "presence.snapshot",
656
- reconnect: "reconnect",
657
- "segment.changed": "segment.changed",
658
- selection: "selection",
659
- "waypoint.changed": "waypoint.changed",
660
- "zone.changed": "zone.changed"
405
+ const collabStreamEventNulls = ["type", {
406
+ cursor: { position: true },
407
+ selection: { selection: true }
408
+ }];
409
+ const collabStreamEventTypes = {
410
+ "collection.changed": "collection.changed",
411
+ cursor: "cursor",
412
+ "draft.clear": "draft.clear",
413
+ "draft.update": "draft.update",
414
+ "itinerary.changed": "itinerary.changed",
415
+ "lock.acquired": "lock.acquired",
416
+ "lock.released": "lock.released",
417
+ "lock.snapshot": "lock.snapshot",
418
+ "presence.join": "presence.join",
419
+ "presence.leave": "presence.leave",
420
+ "presence.snapshot": "presence.snapshot",
421
+ reconnect: "reconnect",
422
+ "segment.changed": "segment.changed",
423
+ selection: "selection",
424
+ "waypoint.changed": "waypoint.changed",
425
+ "zone.changed": "zone.changed"
661
426
  };
662
- var collabEventDates = collabStreamEventDatesByType;
663
- var NIL_UUID = "00000000-0000-0000-0000-000000000000";
664
- var isTerminalStatus = (status) => status >= 400 && status < 500 && status !== 429;
665
- var REOPEN_REPEATS_ERROR_NAMES = [
666
- "MountayaConfigurationError",
667
- "SseBufferOverflowError"
668
- ];
669
- var holderIdOf = (metadata) => {
670
- const holder = metadata?.holder;
671
- if (typeof holder !== "object" || holder === null || !("id" in holder)) {
672
- return void 0;
673
- }
674
- const { id } = holder;
675
- return typeof id === "string" && id !== "" && id !== NIL_UUID ? id : void 0;
427
+ const collabEventDates = collabStreamEventDatesByType;
428
+ const NIL_UUID = "00000000-0000-0000-0000-000000000000";
429
+ const isTerminalStatus = (status) => status >= 400 && status < 500 && status !== 429;
430
+ const REOPEN_REPEATS_ERROR_NAMES = ["MountayaConfigurationError", "SseBufferOverflowError"];
431
+ const holderIdOf = (metadata) => {
432
+ const holder = metadata?.holder;
433
+ if (typeof holder !== "object" || holder === null || !("id" in holder)) return;
434
+ const { id } = holder;
435
+ return typeof id === "string" && id !== "" && id !== NIL_UUID ? id : void 0;
676
436
  };
677
- var decodeCollabFrame = (frame) => {
678
- if (!Object.hasOwn(collabStreamEventTypes, frame.event)) {
679
- return null;
680
- }
681
- let payload;
682
- try {
683
- payload = frame.data ? parseJsonWithDates(frame.data, collabEventDates[frame.event]) : {};
684
- } catch {
685
- return null;
686
- }
687
- if (typeof payload !== "object" || payload === null) {
688
- return null;
689
- }
690
- return withAbsentNulls({ ...payload, type: frame.event }, collabStreamEventNulls);
437
+ const decodeCollabFrame = (frame) => {
438
+ if (!Object.hasOwn(collabStreamEventTypes, frame.event)) return null;
439
+ let payload;
440
+ try {
441
+ payload = frame.data ? parseJsonWithDates(frame.data, collabEventDates[frame.event]) : {};
442
+ } catch {
443
+ return null;
444
+ }
445
+ if (typeof payload !== "object" || payload === null) return null;
446
+ return withAbsentNulls({
447
+ ...payload,
448
+ type: frame.event
449
+ }, collabStreamEventNulls);
691
450
  };
692
- var createCollabTransport = (transport) => {
693
- const subscribeStream = (operationId, path, handlers, options) => {
694
- const seam = transport.streamSeam;
695
- let subscriberFault;
696
- const asSubscriber = (call) => {
697
- try {
698
- call();
699
- } catch (thrown) {
700
- subscriberFault = { thrown };
701
- throw thrown;
702
- }
703
- };
704
- let expiresAt;
705
- let userId;
706
- let reconnected = false;
707
- return openDeclaredSseStream(
708
- {
709
- // What each collaboration stream declares, stated as its generated operation states it:
710
- // its only security requirement pairs the key with a session token, and it acts as the
711
- // member that token names. Stating both here is what refuses a credential carrying no
712
- // session token, or one a source reports as minted without `user_id`, before the open,
713
- // and a share token, which no stream accepts; the refusal reaches onError below.
714
- applyAuth: (init, method) => {
715
- const applied = seam.applyAuth(init, method, {
716
- actsAsMember: true,
717
- operationId,
718
- requiresSession: true
719
- });
720
- expiresAt = seam.sessionExpiresAt();
721
- userId = seam.sessionUserId() ?? void 0;
722
- return applied;
723
- },
724
- // A frame skipped is still one the stream delivered, which the subscriber is told of as it
725
- // is read, in order with the frames handed over.
726
- decode: (frame) => {
727
- const event = decodeCollabFrame(frame);
728
- if (event === null) {
729
- asSubscriber(() => handlers.onSkippedFrame?.());
730
- }
731
- return event;
732
- },
733
- doFetch: seam.doFetch,
734
- lastEventId: options?.lastEventId,
735
- // The last record before a close can be lost on its way, so a close once the token has
736
- // expired is read as the `reconnect` the API would have written.
737
- onClose: () => {
738
- const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
739
- handlers.onClose(reconnected || expired ? "reconnect" : "ended");
740
- },
741
- // Classify the failure so a session stops its loop instead of reconnecting forever.
742
- // The unrecoverable faults arrive by different routes: a credential the seam refuses
743
- // before the open, which a reopen refuses again; a runtime whose fetch streams no body,
744
- // which every reopen meets again; a terminal status on the open, a 401 on the reopen
745
- // after a `reconnect` among them; a producer that never terminates a frame, whose read
746
- // the parser fails at its buffer cap, where reopening only re-buffers to the same cap
747
- // against the same producer; and a fault the subscriber's own `onFrame` or
748
- // `onLastEventId` threw, whatever it threw, since a reopen resumes from the subscriber's
749
- // cursor and hands the same durable frame to the same callback. Every other mid-stream
750
- // fault is the stream's, which a reconnect does fix.
751
- //
752
- // Read by the name each class declares rather than by constructor, so a failure a second
753
- // copy of this package threw is classified the same way.
754
- onError: (error) => {
755
- const terminal = subscriberFault !== void 0 && subscriberFault.thrown === error || isMountayaError(error) && REOPEN_REPEATS_ERROR_NAMES.includes(error.name) || isMountayaApiError(error) && isTerminalStatus(error.status);
756
- handlers.onError(error, { terminal });
757
- },
758
- onFrame: (event, id) => {
759
- if (event.type === collabStreamEventTypes.reconnect) {
760
- reconnected = true;
761
- return true;
762
- }
763
- asSubscriber(() => handlers.onFrame({ event, id }));
764
- return false;
765
- },
766
- onLastEventId: (lastEventId) => {
767
- asSubscriber(() => handlers.onLastEventId?.(lastEventId));
768
- },
769
- onResponse: (response) => {
770
- seam.report(response, operationId);
771
- if (response.ok) {
772
- asSubscriber(() => handlers.onOpen?.({ userId }));
773
- }
774
- },
775
- operationId,
776
- signal: options?.signal,
777
- // The wait for the stream's response is the client's own per-attempt budget.
778
- timeoutMs: seam.timeoutMs,
779
- // Resolved when the open is made, so an id the path cannot carry (an empty one, or a dot
780
- // segment) is refused through onError like any other failed open.
781
- url: () => seam.url(path, operationId),
782
- waitForSession: (signal) => seam.waitForSession(operationId, signal)
783
- },
784
- // The same declaration the credential is stamped by, so a refused open names the step a
785
- // member following the resource takes.
786
- { actsAsMember: true }
787
- );
788
- };
789
- return {
790
- sendSignal: async (resource, signal) => {
791
- try {
792
- if (resource.kind === "itineraries") {
793
- await postItineraryCollab(transport, { body: signal, itinerary_id: resource.id });
794
- } else {
795
- await postZoneCollab(transport, { body: signal, zone_id: resource.id });
796
- }
797
- } catch (error) {
798
- if (isMountayaApiError(error) && error.status === 409) {
799
- return { holderId: holderIdOf(error.metadata), ok: false };
800
- }
801
- throw error;
802
- }
803
- return { ok: true };
804
- },
805
- subscribeEditor: (resource, handlers, options) => (
806
- // resource.kind is a fixed collection literal, so it rides the path as-is; only the id
807
- // is percent-encoded.
808
- subscribeStream(
809
- resource.kind === "itineraries" ? "getItineraryEvents" : "getZoneEvents",
810
- `/v1/${resource.kind}/${encodeURIComponent(resource.id)}/events`,
811
- handlers,
812
- options
813
- )
814
- ),
815
- subscribeList: (organizationId, handlers, options) => subscribeStream(
816
- "getOrganizationEvents",
817
- `/v1/organizations/${encodeURIComponent(organizationId)}/events`,
818
- handlers,
819
- options
820
- )
821
- };
451
+ const createCollabTransport = (transport) => {
452
+ const subscribeStream = (operationId, path, handlers, options) => {
453
+ const seam = transport.streamSeam;
454
+ let subscriberFault;
455
+ const asSubscriber = (call) => {
456
+ try {
457
+ call();
458
+ } catch (thrown) {
459
+ subscriberFault = { thrown };
460
+ throw thrown;
461
+ }
462
+ };
463
+ let expiresAt;
464
+ let userId;
465
+ let reconnected = false;
466
+ return openDeclaredSseStream({
467
+ applyAuth: (init, method) => {
468
+ const applied = seam.applyAuth(init, method, {
469
+ actsAsMember: true,
470
+ operationId,
471
+ requiresSession: true
472
+ });
473
+ expiresAt = seam.sessionExpiresAt();
474
+ userId = seam.sessionUserId() ?? void 0;
475
+ return applied;
476
+ },
477
+ decode: (frame) => {
478
+ const event = decodeCollabFrame(frame);
479
+ if (event === null) asSubscriber(() => handlers.onSkippedFrame?.());
480
+ return event;
481
+ },
482
+ doFetch: seam.doFetch,
483
+ lastEventId: options?.lastEventId,
484
+ onClose: () => {
485
+ const expired = expiresAt !== void 0 && Date.now() >= expiresAt.getTime();
486
+ handlers.onClose(reconnected || expired ? "reconnect" : "ended");
487
+ },
488
+ onError: (error) => {
489
+ const terminal = subscriberFault !== void 0 && subscriberFault.thrown === error || isMountayaError(error) && REOPEN_REPEATS_ERROR_NAMES.includes(error.name) || isMountayaApiError(error) && isTerminalStatus(error.status);
490
+ handlers.onError(error, { terminal });
491
+ },
492
+ onFrame: (event, id) => {
493
+ if (event.type === collabStreamEventTypes.reconnect) {
494
+ reconnected = true;
495
+ return true;
496
+ }
497
+ asSubscriber(() => handlers.onFrame({
498
+ event,
499
+ id
500
+ }));
501
+ return false;
502
+ },
503
+ onLastEventId: (lastEventId) => {
504
+ asSubscriber(() => handlers.onLastEventId?.(lastEventId));
505
+ },
506
+ onResponse: (response) => {
507
+ seam.report(response, operationId);
508
+ if (response.ok) asSubscriber(() => handlers.onOpen?.({ userId }));
509
+ },
510
+ operationId,
511
+ signal: options?.signal,
512
+ timeoutMs: seam.timeoutMs,
513
+ url: () => seam.url(path, operationId),
514
+ waitForSession: (signal) => seam.waitForSession(operationId, signal)
515
+ }, { actsAsMember: true });
516
+ };
517
+ return {
518
+ sendSignal: async (resource, signal) => {
519
+ try {
520
+ if (resource.kind === "itineraries") await postItineraryCollab(transport, {
521
+ body: signal,
522
+ itinerary_id: resource.id
523
+ });
524
+ else await postZoneCollab(transport, {
525
+ body: signal,
526
+ zone_id: resource.id
527
+ });
528
+ } catch (error) {
529
+ if (isMountayaApiError(error) && error.status === 409) return {
530
+ holderId: holderIdOf(error.metadata),
531
+ ok: false
532
+ };
533
+ throw error;
534
+ }
535
+ return { ok: true };
536
+ },
537
+ subscribeEditor: (resource, handlers, options) => subscribeStream(resource.kind === "itineraries" ? "getItineraryEvents" : "getZoneEvents", `/v1/${resource.kind}/${encodeURIComponent(resource.id)}/events`, handlers, options),
538
+ subscribeList: (organizationId, handlers, options) => subscribeStream("getOrganizationEvents", `/v1/organizations/${encodeURIComponent(organizationId)}/events`, handlers, options)
539
+ };
822
540
  };
823
-
824
541
  export { MAX_SSE_BUFFER_CHARS, SseBufferOverflowError, SseFrameParser, agentTerminalEventTypes, createAgentTransport, createCollabTransport, decodeAgentFrame, decodeCollabFrame, openSseStream, readEventStream };
825
- //# sourceMappingURL=index.js.map
542
+
826
543
  //# sourceMappingURL=index.js.map