@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,554 @@
1
+ import { type DateMask, parseJsonWithDates } from "../../core/rules/dates.js";
2
+ import {
3
+ type ErrorMetadata,
4
+ isMountayaApiError,
5
+ isMountayaError,
6
+ } from "../../core/rules/errors.js";
7
+ import { withAbsentNulls } from "../../core/rules/nullMask.js";
8
+ import type { MountayaTransport } from "../../core/rules/transport.js";
9
+ import { collabStreamEventDatesByType } from "../../rest/dates.gen.js";
10
+ import { postItineraryCollab, postZoneCollab } from "../../rest/operations.gen.js";
11
+ import type {
12
+ CollabChangeAction,
13
+ CollabSignalParams,
14
+ CollabStreamEvent,
15
+ CollabStreamEventType,
16
+ } from "../../rest/schema.gen.js";
17
+ import { collabStreamEventNulls } from "./collabNulls.gen.js";
18
+ import { openDeclaredSseStream } from "./openSseStream.js";
19
+ import type { SseFrame } from "./sse.js";
20
+
21
+ /**
22
+ * The collaboration streams: the three `text/event-stream` feeds a live editor reads, and
23
+ * the signal endpoint it writes back to.
24
+ *
25
+ * The vocabulary is entirely the contract's. `CollabStreamEvent` is a union discriminated on
26
+ * `type`, and the generator synthesizes a per-variant literal from the spec's `discriminator`,
27
+ * so `event.type === "cursor"` narrows to the cursor frame without a validator in between. A
28
+ * Zod transcription of that union would be a second declaration of the same thing, so what
29
+ * lives here is only the part a generated type cannot state: that the `event:` line is the
30
+ * discriminant, that a frame naming an unknown one is skipped rather than fatal, and which
31
+ * failures a reconnect cannot fix.
32
+ */
33
+
34
+ /**
35
+ * collabStreamEventTypes is every frame kind the streams carry, and the assertion that
36
+ * this module knows exactly the set the contract declares.
37
+ *
38
+ * Both `satisfies` clauses are load-bearing and they fail in opposite directions.
39
+ * `Record<CollabStreamEventType, …>` fails when the contract gains a kind this file has not
40
+ * listed: without it the decoder would silently drop a whole class of frame, which reads
41
+ * to a user as presence quietly not updating rather than as an error. Keyed the other way
42
+ * it fails when this file lists one the contract does not declare, which is a frame nothing
43
+ * can ever send, kept alive because nothing contradicted it.
44
+ *
45
+ * It is also the runtime membership set the decoder tests `frame.event` against, so the
46
+ * type-level pin and the check that actually runs cannot come apart.
47
+ */
48
+ const collabStreamEventTypes = {
49
+ "collection.changed": "collection.changed",
50
+ cursor: "cursor",
51
+ "draft.clear": "draft.clear",
52
+ "draft.update": "draft.update",
53
+ "itinerary.changed": "itinerary.changed",
54
+ "lock.acquired": "lock.acquired",
55
+ "lock.released": "lock.released",
56
+ "lock.snapshot": "lock.snapshot",
57
+ "presence.join": "presence.join",
58
+ "presence.leave": "presence.leave",
59
+ "presence.snapshot": "presence.snapshot",
60
+ reconnect: "reconnect",
61
+ "segment.changed": "segment.changed",
62
+ selection: "selection",
63
+ "waypoint.changed": "waypoint.changed",
64
+ "zone.changed": "zone.changed",
65
+ } satisfies Record<CollabStreamEventType, CollabStreamEvent["type"]> satisfies Record<
66
+ CollabStreamEvent["type"],
67
+ CollabStreamEventType
68
+ >;
69
+
70
+ /**
71
+ * collabEventDates is the mask of each event's instants, by the event's name: the contract's
72
+ * per-event masks, read by a name the wire sends and this build may not know.
73
+ */
74
+ const collabEventDates: { readonly [event: string]: DateMask | undefined } =
75
+ collabStreamEventDatesByType;
76
+
77
+ /**
78
+ * CollabEvent is one decoded frame off a collaboration stream: the contract's union,
79
+ * re-exported under the name the reading code uses.
80
+ */
81
+ export type CollabEvent = CollabStreamEvent;
82
+
83
+ /**
84
+ * CollabSignal is one signal a member publishes upstream: a selection, a cursor move, a
85
+ * lock acquire or release, a draft update or clear.
86
+ *
87
+ * The inbound and outbound vocabularies are deliberately NOT one type. The server stamps
88
+ * `user_id` on every frame it republishes, and the lock pair disagrees on the discriminant
89
+ * itself (`lock.acquire` goes up, `lock.acquired` comes back), so a shared schema would
90
+ * have to be wrong about one of them.
91
+ */
92
+ export type CollabSignal = CollabSignalParams;
93
+
94
+ /**
95
+ * CollabDurableChange is the subset of frames reporting a COMMITTED change to a resource,
96
+ * as opposed to the live-only presence, cursor, lock and draft traffic. Its members are the
97
+ * frames carrying an `action`, which is what selects them here: a new change family joins by
98
+ * carrying one rather than by being listed.
99
+ */
100
+ export type CollabDurableChange = Extract<CollabEvent, { action: CollabChangeAction }>;
101
+
102
+ /**
103
+ * CollabStreamResource is the resource whose editor stream is being read: the collection
104
+ * segment of its path and its id.
105
+ *
106
+ * It is the wire's own spelling rather than a domain handle (`itineraries` and `zones` are
107
+ * path segments here, not model names), which is why this package declares it instead of
108
+ * naming one from a package it must not depend on. `@mountaya/elements`' `CollabResource`
109
+ * is structurally identical and assignable to it, and a twin test pins the two.
110
+ */
111
+ export interface CollabStreamResource {
112
+ /** The resource's id, as its path carries it. */
113
+ readonly id: string;
114
+ /** The collection segment of the resource's path. */
115
+ readonly kind: "itineraries" | "zones";
116
+ }
117
+
118
+ /**
119
+ * CollabStreamFrame is one decoded frame paired with its stream position id. A reader
120
+ * records the id of the last frame it consumed so a reconnect passes it back as
121
+ * `Last-Event-ID` and resumes after it. The id is optional because not every producer
122
+ * numbers its frames, in which case a resume falls back to a full replay.
123
+ */
124
+ export interface CollabStreamFrame {
125
+ /** The decoded frame, discriminated on `type`. */
126
+ event: CollabEvent;
127
+ /** The record's own `id:`, the position a resume passes back; absent where it names none. */
128
+ id?: string | undefined;
129
+ }
130
+
131
+ /**
132
+ * CollabStreamErrorOptions classify a stream failure for the reader that has to decide
133
+ * whether to reconnect.
134
+ */
135
+ export interface CollabStreamErrorOptions {
136
+ /**
137
+ * Whether reopening cannot help: a credential refused before the open, a runtime whose fetch
138
+ * streams no body, a 4xx other than 429 on the open, a producer that never ends a frame, and a
139
+ * fault the subscriber's own `onFrame` or `onLastEventId` threw, which a reopen would hand the
140
+ * same frame again. `false` for a failure a reopen can get past: a dropped connection, a
141
+ * stream gone silent, a 429 and a 5xx.
142
+ */
143
+ terminal?: boolean | undefined;
144
+ }
145
+
146
+ /**
147
+ * CollabStreamCloseReason says how a collaboration stream finished without an error:
148
+ * `reconnect` means the API ended it and asks for a reopen at once. It says so with a `reconnect`
149
+ * event, when the credential the stream was opened with ends (the session token expires or the
150
+ * key is revoked) and when it cannot keep delivering the stream (`interrupted`: the reader fell
151
+ * behind or the subscription was lost), and a close at or after the token's expiry says the same.
152
+ * None is a failure: the reopen goes at once with the token the client holds then, a new one
153
+ * where the credential ended and the one already held where the stream was interrupted, and the
154
+ * last event id. `ended` means the body closed on its own, a drop like any other.
155
+ */
156
+ export type CollabStreamCloseReason = "reconnect" | "ended";
157
+
158
+ /**
159
+ * CollabStreamHandlers are the callbacks a subscriber wires into a collaboration stream.
160
+ * The transport drives them as it reads: `onOpen` once the API has answered the open, `onFrame`
161
+ * per decoded frame, `onSkippedFrame` per frame it skips, `onLastEventId` when the stream's
162
+ * position moves without a frame to carry it, then exactly one of `onClose` (the body finished)
163
+ * or `onError` (it failed). An abort is the subscriber's own teardown and fires none of them
164
+ * after it.
165
+ */
166
+ export interface CollabStreamHandlers {
167
+ /** onClose is told once the stream's body finished with no error, and why. */
168
+ onClose: (reason: CollabStreamCloseReason) => void;
169
+ /**
170
+ * onError receives the failure once, classified. It is an error of the client's family, except
171
+ * a fault the subscriber's own `onOpen`, `onFrame`, `onSkippedFrame` or `onLastEventId` threw,
172
+ * which arrives as it was thrown and classified terminal: an open the API refused raises the
173
+ * class a request answered the same way raises, and a connection that failed or broke off raises
174
+ * a `MountayaConnectionError` naming the stream's operation.
175
+ */
176
+ onError: (error: unknown, options?: CollabStreamErrorOptions) => void;
177
+ /** onFrame receives each decoded frame, in the order the stream wrote them. */
178
+ onFrame: (frame: CollabStreamFrame) => void;
179
+ /**
180
+ * onLastEventId receives the stream position when it moves to one no frame carries: a record
181
+ * that names an `id:` and no event, or an empty `id:`, which clears the position and arrives as
182
+ * `undefined`. A subscriber keeping a resume cursor records it, so a reopen resumes from the
183
+ * last position the stream named rather than replaying what it has read.
184
+ *
185
+ * A frame {@link decodeCollabFrame} skips (a kind this build does not know, or a payload that is
186
+ * not an object) is neither handed to onFrame nor reported here, whatever id it carries, so its
187
+ * position reaches a cursor only once a later frame or record names one. A reopen before then
188
+ * replays it, and it is skipped again.
189
+ */
190
+ onLastEventId?: ((lastEventId: string | undefined) => void) | undefined;
191
+ /**
192
+ * onOpen is told once the API has answered the open, before any frame of it, with the user the
193
+ * stream is read as: the user the session token it was opened with names, `userId`, undefined
194
+ * where the credential's source does not say or the token is held as a string or a function,
195
+ * whose user the client is not told. A reader judging its own member's `presence.join` reads
196
+ * that user first, and a user it is told otherwise only where it is undefined.
197
+ */
198
+ onOpen?: ((open: { readonly userId: string | undefined }) => void) | undefined;
199
+ /**
200
+ * onSkippedFrame is told of each frame the stream delivers that {@link decodeCollabFrame} skips:
201
+ * one naming a kind this build does not know, or carrying data it cannot read. Nothing of it is
202
+ * handed over, and it moves no position, but it is a frame the stream delivered, so a reader
203
+ * telling an open that made progress from one that did not counts it as one past those every
204
+ * open begins with. A `reconnect`, which is the transport's own, is not one.
205
+ */
206
+ onSkippedFrame?: (() => void) | undefined;
207
+ }
208
+
209
+ /**
210
+ * CollabSubscribeOptions tune one open. `lastEventId` resumes the durable history after a
211
+ * position; `signal` tears the open stream down from outside, exactly as the returned
212
+ * unsubscribe does.
213
+ */
214
+ export interface CollabSubscribeOptions {
215
+ /** The position to resume after, sent as `Last-Event-ID`; left out, the stream replays whole. */
216
+ lastEventId?: string | undefined;
217
+ /** Closes the stream once it aborts, as the unsubscribe a subscribe returns does. */
218
+ signal?: AbortSignal | undefined;
219
+ }
220
+
221
+ /**
222
+ * CollabSignalResult is how a published signal settled. A lock contention is a RESULT
223
+ * rather than a throw: the caller asked whether it may edit an entity and the answer is
224
+ * "no, that member is", which is an outcome of the question rather than a failure to ask
225
+ * it. Every other non-ok status throws from the client's own error family, as the generated
226
+ * operation raises it. A success throws a `MountayaConnectionError` when its body breaks off
227
+ * before it is complete, where the signal was answered and the answer lost, and the base
228
+ * `MountayaApiError` when its body is not JSON, where something on the network path may have
229
+ * answered in the API's place.
230
+ */
231
+ export type CollabSignalResult = { ok: true } | { holderId?: string | undefined; ok: false };
232
+
233
+ /**
234
+ * CollabTransport is the seam a collaboration session drives: publish one signal, and open
235
+ * either the editor stream for one resource or the organization's event stream.
236
+ *
237
+ * A session takes this interface rather than a client, so an offline or scripted
238
+ * implementation is a plain object. {@link createCollabTransport} is the live one, which gives
239
+ * up an open that never answers and a stream gone silent as connection errors. A transport of
240
+ * your own bounds both waits the same way: the engine waits as long as a stream says nothing.
241
+ */
242
+ export interface CollabTransport {
243
+ /**
244
+ * sendSignal publishes one signal for a resource, and answers how it settled: a lock another
245
+ * member holds is a result naming them, never a throw.
246
+ *
247
+ * @throws the client's own error family for every other refusal: see {@link CollabSignalResult}.
248
+ */
249
+ sendSignal: (resource: CollabStreamResource, signal: CollabSignal) => Promise<CollabSignalResult>;
250
+ /**
251
+ * subscribeEditor opens the editor stream of one resource and returns the function that closes
252
+ * it. Every failure reaches `handlers.onError`, classified; the call itself never throws.
253
+ */
254
+ subscribeEditor: (
255
+ resource: CollabStreamResource,
256
+ handlers: CollabStreamHandlers,
257
+ options?: CollabSubscribeOptions,
258
+ ) => () => void;
259
+ /**
260
+ * subscribeList opens an organization's event stream, the changes to its itineraries, zones and
261
+ * collections, and returns the function that closes it. Every failure reaches `handlers.onError`, classified; the call itself never throws.
262
+ */
263
+ subscribeList: (
264
+ organizationId: string,
265
+ handlers: CollabStreamHandlers,
266
+ options?: CollabSubscribeOptions,
267
+ ) => () => void;
268
+ }
269
+
270
+ /**
271
+ * NIL_UUID is the zero user id a 409 carries when the rejected operation named an entity
272
+ * that is simply unlocked (a draft sent without holding its lock) rather than one held by
273
+ * a member. It names no holder, so it never surfaces.
274
+ */
275
+ const NIL_UUID = "00000000-0000-0000-0000-000000000000";
276
+
277
+ /**
278
+ * isTerminalStatus reports whether a stream open answered with a status that reopening cannot
279
+ * change, so a session stops its loop and surfaces the error rather than reconnect into the
280
+ * same answer forever.
281
+ *
282
+ * Every 4xx is a statement about the request itself (a malformed open, a credential the API
283
+ * does not accept, an organization that does not hold the product, a member
284
+ * without access, a resource that is not there), and the contract's retry rule says the same
285
+ * of every one of them: repeating it unchanged produces the identical answer. A 400 and a 402
286
+ * are as final as a 401, a 403 or a 404: a stream refused with any of them reopens into the
287
+ * same answer every fifteen seconds for as long as the page stays open. 429 is the one 4xx
288
+ * that says "later" rather than "no", and every 5xx and every network drop is transient, so
289
+ * those keep the backoff-and-retry.
290
+ */
291
+ const isTerminalStatus = (status: number): boolean =>
292
+ status >= 400 && status < 500 && status !== 429;
293
+
294
+ /**
295
+ * REOPEN_REPEATS_ERROR_NAMES names the failures a reopen repeats whatever answers it: a
296
+ * configuration refusal (a credential the transport refuses before the open, or a runtime whose
297
+ * fetch exposes no response body to stream), and a producer the frame parser stopped at its
298
+ * buffer cap. Names rather than classes, so a failure a second copy of this package threw is
299
+ * read the same way.
300
+ */
301
+ const REOPEN_REPEATS_ERROR_NAMES: readonly string[] = [
302
+ "MountayaConfigurationError",
303
+ "SseBufferOverflowError",
304
+ ];
305
+
306
+ /**
307
+ * holderIdOf reads the contending member's id out of a 409's metadata, which names the lock's
308
+ * holder at `holder.id`.
309
+ *
310
+ * Read member by member, because the metadata is typed as the record the envelope sent rather
311
+ * than as the lock shape. Returns undefined when it names none: no metadata, a shape without a
312
+ * holder, or the nil-uuid holder of an entity that is merely unlocked.
313
+ */
314
+ const holderIdOf = (metadata: ErrorMetadata | undefined): string | undefined => {
315
+ const holder = metadata?.holder;
316
+ if (typeof holder !== "object" || holder === null || !("id" in holder)) {
317
+ return undefined;
318
+ }
319
+
320
+ const { id } = holder;
321
+
322
+ return typeof id === "string" && id !== "" && id !== NIL_UUID ? id : undefined;
323
+ };
324
+
325
+ /**
326
+ * decodeCollabFrame turns one raw SSE frame into a typed event, or null to skip it.
327
+ *
328
+ * The `event:` line is the discriminant and the `data:` line is the payload without it, so
329
+ * the two are combined and the event line wins over any stray `type` in the body. A frame
330
+ * naming a kind this build does not know is skipped rather than fatal: that is what makes
331
+ * a newer API release adding a frame a compatible change rather than a broken stream. The kind
332
+ * is looked up among the table's own keys, so a name every object inherits (`constructor`,
333
+ * `toString`) is one this build does not know.
334
+ *
335
+ * The payload decodes the instants its own event declares, by the mask the contract generates
336
+ * for that event, as every response decodes its operation's. Without it `connected_at` and
337
+ * `occurred_at` would be ISO strings behind a generated type that says `Date`, which is a
338
+ * `getTime is not a function` waiting for the first reader. A member its event types required and
339
+ * nullable, a cursor's `position` or a selection's `selection`, reads null where the frame leaves
340
+ * it out, as it does in an answer. Nothing else is decoded: a draft is an open object a peer is
341
+ * typing, so a timestamp in it stays the string the peer wrote.
342
+ *
343
+ * The cast is the decision this module is built on: the contract generates the union, so a
344
+ * frame is TYPED by it rather than re-validated against a hand-written transcription of it.
345
+ * What is checked at runtime is the one field the wire and the type disagree about (the
346
+ * discriminant, which arrives on a separate line) and nothing below it.
347
+ */
348
+ export const decodeCollabFrame = (frame: SseFrame): CollabEvent | null => {
349
+ if (!Object.hasOwn(collabStreamEventTypes, frame.event)) {
350
+ return null;
351
+ }
352
+
353
+ let payload: unknown;
354
+ try {
355
+ payload = frame.data ? parseJsonWithDates(frame.data, collabEventDates[frame.event]) : {};
356
+ } catch {
357
+ return null;
358
+ }
359
+
360
+ if (typeof payload !== "object" || payload === null) {
361
+ return null;
362
+ }
363
+
364
+ // The wire's boundary: a frame is typed by the kind its `event:` line names, as the contract
365
+ // declares it, and is not validated against that type here.
366
+ return withAbsentNulls({ ...payload, type: frame.event }, collabStreamEventNulls) as CollabEvent;
367
+ };
368
+
369
+ /**
370
+ * createCollabTransport binds the collaboration streams to one client's transport.
371
+ *
372
+ * It reads the three feeds over `fetch` rather than `EventSource` because they must ride
373
+ * the transport's credential (a cookie session, a publishable key with a session token)
374
+ * and set `Last-Event-ID` on a reconnect, and `EventSource` supports neither. A
375
+ * collaboration stream has no terminal event, so a read finishes only when the body closes,
376
+ * a fault occurs, or the returned unsubscribe aborts it.
377
+ *
378
+ * An open waits for a session token the credential's source reports on its way, as a request
379
+ * does. The `reconnect` event the API ends a stream with, when its credential ends or when it
380
+ * cannot keep delivering it (`interrupted`), is never handed to `onFrame`: it ends the read and
381
+ * closes it as `reconnect`, whatever reason it names, and so does a close at or after the expiry
382
+ * of the token the open carried, where the credential's source reports one. An open the API
383
+ * answers tells `onOpen` the user that token names, and a frame it skips is told to
384
+ * `onSkippedFrame`.
385
+ */
386
+ export const createCollabTransport = (transport: MountayaTransport): CollabTransport => {
387
+ const subscribeStream = (
388
+ operationId: string,
389
+ path: string,
390
+ handlers: CollabStreamHandlers,
391
+ options?: CollabSubscribeOptions,
392
+ ): (() => void) => {
393
+ const seam = transport.streamSeam;
394
+
395
+ // What the subscriber's own callback threw, held so the failure the opener hands back can be
396
+ // told from one the stream met: the opener reports both through `onError`, as thrown.
397
+ let subscriberFault: { readonly thrown: unknown } | undefined;
398
+ const asSubscriber = (call: () => void): void => {
399
+ try {
400
+ call();
401
+ } catch (thrown) {
402
+ subscriberFault = { thrown };
403
+
404
+ throw thrown;
405
+ }
406
+ };
407
+
408
+ // When the token this open carries expires, read as the open applies it, and whether the
409
+ // stream ended on a `reconnect`: either makes a close a prompt reopen rather than a drop. The
410
+ // user that token names is read as the open applies it too, so `onOpen` tells the user the
411
+ // open was made as, whatever the source holds by the time the API answers.
412
+ let expiresAt: Date | undefined;
413
+ let userId: string | undefined;
414
+ let reconnected = false;
415
+
416
+ // The shared opener owns the abort, resume, read and error scaffolding; what this supplies
417
+ // is the collaboration policy alone: which failure is terminal, how a close reads, and a
418
+ // per-frame handler that stops the read on a `reconnect` alone.
419
+ return openDeclaredSseStream<CollabEvent>(
420
+ {
421
+ // What each collaboration stream declares, stated as its generated operation states it:
422
+ // its only security requirement pairs the key with a session token, and it acts as the
423
+ // member that token names. Stating both here is what refuses a credential carrying no
424
+ // session token, or one a source reports as minted without `user_id`, before the open,
425
+ // and a share token, which no stream accepts; the refusal reaches onError below.
426
+ applyAuth: (init, method) => {
427
+ const applied = seam.applyAuth(init, method, {
428
+ actsAsMember: true,
429
+ operationId,
430
+ requiresSession: true,
431
+ });
432
+ expiresAt = seam.sessionExpiresAt();
433
+ // A source reporting a token minted without `user_id` is refused above, as no stream
434
+ // acts as nobody, so what is left is a user or a source that does not say.
435
+ userId = seam.sessionUserId() ?? undefined;
436
+
437
+ return applied;
438
+ },
439
+ // A frame skipped is still one the stream delivered, which the subscriber is told of as it
440
+ // is read, in order with the frames handed over.
441
+ decode: (frame) => {
442
+ const event = decodeCollabFrame(frame);
443
+ if (event === null) {
444
+ asSubscriber(() => handlers.onSkippedFrame?.());
445
+ }
446
+
447
+ return event;
448
+ },
449
+ doFetch: seam.doFetch,
450
+ lastEventId: options?.lastEventId,
451
+ // The last record before a close can be lost on its way, so a close once the token has
452
+ // expired is read as the `reconnect` the API would have written.
453
+ onClose: () => {
454
+ const expired = expiresAt !== undefined && Date.now() >= expiresAt.getTime();
455
+ handlers.onClose(reconnected || expired ? "reconnect" : "ended");
456
+ },
457
+ // Classify the failure so a session stops its loop instead of reconnecting forever.
458
+ // The unrecoverable faults arrive by different routes: a credential the seam refuses
459
+ // before the open, which a reopen refuses again; a runtime whose fetch streams no body,
460
+ // which every reopen meets again; a terminal status on the open, a 401 on the reopen
461
+ // after a `reconnect` among them; a producer that never terminates a frame, whose read
462
+ // the parser fails at its buffer cap, where reopening only re-buffers to the same cap
463
+ // against the same producer; and a fault the subscriber's own `onFrame` or
464
+ // `onLastEventId` threw, whatever it threw, since a reopen resumes from the subscriber's
465
+ // cursor and hands the same durable frame to the same callback. Every other mid-stream
466
+ // fault is the stream's, which a reconnect does fix.
467
+ //
468
+ // Read by the name each class declares rather than by constructor, so a failure a second
469
+ // copy of this package threw is classified the same way.
470
+ onError: (error) => {
471
+ const terminal =
472
+ (subscriberFault !== undefined && subscriberFault.thrown === error) ||
473
+ (isMountayaError(error) && REOPEN_REPEATS_ERROR_NAMES.includes(error.name)) ||
474
+ (isMountayaApiError(error) && isTerminalStatus(error.status));
475
+ handlers.onError(error, { terminal });
476
+ },
477
+ onFrame: (event, id) => {
478
+ if (event.type === collabStreamEventTypes.reconnect) {
479
+ reconnected = true;
480
+
481
+ return true;
482
+ }
483
+
484
+ asSubscriber(() => handlers.onFrame({ event, id }));
485
+
486
+ return false;
487
+ },
488
+ onLastEventId: (lastEventId) => {
489
+ asSubscriber(() => handlers.onLastEventId?.(lastEventId));
490
+ },
491
+ onResponse: (response) => {
492
+ seam.report(response, operationId);
493
+ if (response.ok) {
494
+ asSubscriber(() => handlers.onOpen?.({ userId }));
495
+ }
496
+ },
497
+ operationId,
498
+ signal: options?.signal,
499
+ // The wait for the stream's response is the client's own per-attempt budget.
500
+ timeoutMs: seam.timeoutMs,
501
+ // Resolved when the open is made, so an id the path cannot carry (an empty one, or a dot
502
+ // segment) is refused through onError like any other failed open.
503
+ url: () => seam.url(path, operationId),
504
+ waitForSession: (signal) => seam.waitForSession(operationId, signal),
505
+ },
506
+ // The same declaration the credential is stamped by, so a refused open names the step a
507
+ // member following the resource takes.
508
+ { actsAsMember: true },
509
+ );
510
+ };
511
+
512
+ return {
513
+ sendSignal: async (resource, signal) => {
514
+ // Through the generated operation, so every fact the contract declares about the signal
515
+ // (the session it takes, the member it acts as, its budget) is the contract's. A lock
516
+ // contention is a result rather than a throw, so the 409 it raises is read into the answer
517
+ // below instead of escaping. A signal is idempotent (`x-idempotent: true`), so the client
518
+ // repeats one whose answer never came; it carries no `Idempotency-Key`, since a repeat
519
+ // restates the signal and needs no stored answer to be safe.
520
+ try {
521
+ if (resource.kind === "itineraries") {
522
+ await postItineraryCollab(transport, { body: signal, itinerary_id: resource.id });
523
+ } else {
524
+ await postZoneCollab(transport, { body: signal, zone_id: resource.id });
525
+ }
526
+ } catch (error) {
527
+ // Its metadata is where a 409 names the member holding the lock.
528
+ if (isMountayaApiError(error) && error.status === 409) {
529
+ return { holderId: holderIdOf(error.metadata), ok: false };
530
+ }
531
+
532
+ throw error;
533
+ }
534
+
535
+ return { ok: true };
536
+ },
537
+ subscribeEditor: (resource, handlers, options) =>
538
+ // resource.kind is a fixed collection literal, so it rides the path as-is; only the id
539
+ // is percent-encoded.
540
+ subscribeStream(
541
+ resource.kind === "itineraries" ? "getItineraryEvents" : "getZoneEvents",
542
+ `/v1/${resource.kind}/${encodeURIComponent(resource.id)}/events`,
543
+ handlers,
544
+ options,
545
+ ),
546
+ subscribeList: (organizationId, handlers, options) =>
547
+ subscribeStream(
548
+ "getOrganizationEvents",
549
+ `/v1/organizations/${encodeURIComponent(organizationId)}/events`,
550
+ handlers,
551
+ options,
552
+ ),
553
+ };
554
+ };
@@ -0,0 +1,17 @@
1
+ // GENERATED FILE. DO NOT EDIT.
2
+ //
3
+ // The members a collaboration frame reads null where it leaves them out, by the frame's `type`,
4
+ // generated from the mountaya/schemas contract (sdk/model.json, `rest`) by
5
+ // scripts/generate-null-masks.mjs. The same masks stand in core/rules/nullMasks.gen.ts, and are
6
+ // printed apart so that `@mountaya/client/events` carries them alone.
7
+ //
8
+ // Edit the contract in mountaya/schemas, not this file.
9
+
10
+ /** The members of `CollabCursorEvent` that read null where a value leaves them out. */
11
+ export const collabCursorEventNulls = { position: true } as const;
12
+
13
+ /** The members of `CollabSelectionEvent` that read null where a value leaves them out. */
14
+ export const collabSelectionEventNulls = { selection: true } as const;
15
+
16
+ /** The members of `CollabStreamEvent` that read null where a value leaves them out. */
17
+ export const collabStreamEventNulls = ["type", { cursor: collabCursorEventNulls, selection: collabSelectionEventNulls }] as const;
@@ -0,0 +1,94 @@
1
+ import { type SseFrame, SseFrameParser } from "./sse.js";
2
+
3
+ /**
4
+ * FrameHandler receives one framed record as readEventStream decodes it. It is
5
+ * awaited, so returning a promise backpressures the read: the next chunk is
6
+ * pulled only once the current frame is handled. Returning (or resolving to)
7
+ * `true` asks the reader to stop early: the caller has seen its own end-of-stream
8
+ * marker and need not wait for the body to close.
9
+ */
10
+ export type FrameHandler = (frame: SseFrame) => boolean | void | Promise<boolean> | Promise<void>;
11
+
12
+ /**
13
+ * EventStreamOutcome reports why readEventStream returned: `stopped` when a frame
14
+ * handler asked to stop early (it recognized the caller's terminator), `ended`
15
+ * when the body closed on its own with no such request.
16
+ */
17
+ export type EventStreamOutcome = "stopped" | "ended";
18
+
19
+ /**
20
+ * readEventStream reads a `text/event-stream` body to its end. It pulls each chunk from the body's
21
+ * reader, decodes it as UTF-8 across reads (so a character two reads split arrives whole), frames
22
+ * it with {@link SseFrameParser}, and hands every frame to `onFrame`. It knows nothing of the
23
+ * payload's shape or vocabulary: the caller decodes and validates each frame's data. Awaiting
24
+ * `onFrame` lets a slow handler backpressure the read, and a handler that returns `true` stops
25
+ * the read at once rather than waiting on the producer to hang up. It returns `stopped` when a
26
+ * handler stopped the read and `ended` when the body closed first.
27
+ *
28
+ * `onLastEventId`, where the caller passes one, receives the stream's last event ID (see
29
+ * {@link SseFrameParser.lastEventId}) whenever it moves to a value the frames handed to `onFrame`
30
+ * do not carry: after a record that names an `id:` and carries no `data:`, which dispatches no
31
+ * frame, and after an empty `id:`, which clears the position to the empty string while the frame's
32
+ * own id reads empty either way. An empty `id:` is reported even before the stream names any other
33
+ * position, so a cursor carried over from an earlier connection is dropped, while a stream that
34
+ * names no `id:` at all reports nothing and leaves it where it was. A frame carries its record's
35
+ * id itself, so a caller keeping a resume cursor records both, and its cursor is the position a
36
+ * reconnect resumes from. The callback runs once the frames a read completed are handled, so the
37
+ * position it reports never passes a frame `onFrame` has not seen, and a read that stops or fails
38
+ * before then reports none.
39
+ *
40
+ * A producer that never terminates a record is the one fault the reader raises on its own: past
41
+ * the parser's cap the read throws `SseBufferOverflowError` rather than buffer without bound.
42
+ * That is deliberately not an outcome: `stopped` and `ended` both describe a stream that framed
43
+ * what it was sent, and a caller reconnecting on a clean close must not mistake a broken producer
44
+ * for one.
45
+ *
46
+ * The reader's lock is released however the read finishes, and the body is left as it is: after
47
+ * `stopped` or a throw, the connection behind it stays open until the caller, whose body it is,
48
+ * cancels it or aborts the request that opened it.
49
+ */
50
+ export const readEventStream = async (
51
+ body: ReadableStream<Uint8Array>,
52
+ onFrame: FrameHandler,
53
+ onLastEventId?: (lastEventId: string) => void,
54
+ ): Promise<EventStreamOutcome> => {
55
+ const reader = body.getReader();
56
+ // `ignoreBOM` hands a leading byte-order mark through to the parser, which drops the one the
57
+ // standard allows. A decoder that dropped it as well would drop two.
58
+ const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
59
+ const parser = new SseFrameParser();
60
+ // The position the caller can already tell: the last id a frame carried or the callback
61
+ // reported, and undefined until the stream names one. The parser's moving past it is what the
62
+ // callback reports.
63
+ let known: string | undefined;
64
+
65
+ try {
66
+ while (true) {
67
+ const { done, value } = await reader.read();
68
+ if (done) {
69
+ return "ended";
70
+ }
71
+
72
+ for (const frame of parser.push(decoder.decode(value, { stream: true }))) {
73
+ if (frame.id !== "") {
74
+ known = frame.id;
75
+ }
76
+
77
+ const stop = await onFrame(frame);
78
+ if (stop) {
79
+ return "stopped";
80
+ }
81
+ }
82
+
83
+ const position = parser.lastEventId;
84
+ if (position !== undefined && position !== known) {
85
+ known = position;
86
+ onLastEventId?.(position);
87
+ }
88
+ }
89
+ } finally {
90
+ // Releasing the lock lets an aborted or abandoned body be garbage-collected
91
+ // even when the read stops early on the caller's terminator or an abort.
92
+ reader.releaseLock();
93
+ }
94
+ };