@collective-intelligence/external-apps-client-sdk 0.1.36 → 0.1.37

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.
@@ -0,0 +1,1439 @@
1
+ import { C as CiError, E as FederatedAuthError, S as toCiResult, T as CiTransportError, _ as makeHttpExecute, b as fromCiResult, g as directHttpOptions, h as backendErrorCode, k as ciErrorCodes, v as proxyHttpOptions } from "./service-C7kswu6e.js";
2
+ import * as Predicate from "effect/Predicate";
3
+ import * as Schema from "effect/Schema";
4
+ import * as Cause from "effect/Cause";
5
+ import * as Config from "effect/Config";
6
+ import * as Context from "effect/Context";
7
+ import * as Effect from "effect/Effect";
8
+ import * as FiberHandle from "effect/FiberHandle";
9
+ import * as FiberMap from "effect/FiberMap";
10
+ import * as FetchHttpClient from "effect/http/FetchHttpClient";
11
+ import * as HttpBody from "effect/http/HttpBody";
12
+ import * as HttpClient from "effect/http/HttpClient";
13
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
14
+ import * as HttpClientResponse from "effect/http/HttpClientResponse";
15
+ import * as Latch from "effect/Latch";
16
+ import * as Layer from "effect/Layer";
17
+ import * as Queue from "effect/Queue";
18
+ import * as Random from "effect/Random";
19
+ import * as Stream from "effect/Stream";
20
+ import * as Clock from "effect/Clock";
21
+ import * as Deferred from "effect/Deferred";
22
+ import * as Exit from "effect/Exit";
23
+ const emptyBlock = () => ({
24
+ comment: false,
25
+ data: [],
26
+ id: void 0,
27
+ type: ""
28
+ });
29
+ /**
30
+ * A Server-Sent Events parser that, unlike `EventSource`, reports comments:
31
+ * the server's pings are comments, and the client's watchdog needs them.
32
+ */
33
+ const createEventStreamParser = (handlers) => {
34
+ let buffer = "";
35
+ let block = emptyBlock();
36
+ let retry;
37
+ const dispatch = () => {
38
+ const ended = block;
39
+ block = emptyBlock();
40
+ if (ended.data.length > 0) handlers.onEvent({
41
+ data: ended.data.join("\n"),
42
+ id: ended.id,
43
+ type: ended.type === "" ? "message" : ended.type
44
+ });
45
+ else if (ended.comment || ended.id !== void 0) handlers.onPing(ended.id);
46
+ };
47
+ const line = (text) => {
48
+ if (text === "") {
49
+ dispatch();
50
+ return;
51
+ }
52
+ if (text.startsWith(":")) {
53
+ block.comment = true;
54
+ return;
55
+ }
56
+ const colon = text.indexOf(":");
57
+ const field = colon === -1 ? text : text.slice(0, colon);
58
+ const raw = colon === -1 ? "" : text.slice(colon + 1);
59
+ const value = raw.startsWith(" ") ? raw.slice(1) : raw;
60
+ if (field === "data") block.data.push(value);
61
+ else if (field === "event") block.type = value;
62
+ else if (field === "id" && !value.includes("\0")) block.id = value;
63
+ else if (field === "retry" && /^\d+$/u.test(value)) retry = Number(value);
64
+ };
65
+ return {
66
+ push: (chunk) => {
67
+ buffer += chunk;
68
+ const lines = buffer.split("\n");
69
+ buffer = lines.pop() ?? "";
70
+ for (const text of lines) line(text.endsWith("\r") ? text.slice(0, -1) : text);
71
+ },
72
+ /** The last `retry:` the stream sent, in milliseconds. */
73
+ retry: () => retry
74
+ };
75
+ };
76
+ /** A `Retry-After` header value in milliseconds, seconds form only. */
77
+ const retryAfterMilliseconds = (value) => value !== null && value !== void 0 && /^\d+$/u.test(value) ? Number(value) * 1e3 : void 0;
78
+ /** Reads `text/event-stream` with `fetch`, so pings and refusals are visible. */
79
+ const createFetchEventSourceFactory = (fetch) => (url, handlers) => {
80
+ const abort = new AbortController();
81
+ const live = () => !abort.signal.aborted;
82
+ const parser = createEventStreamParser({
83
+ onEvent: (event) => {
84
+ if (live()) handlers.onEvent(event);
85
+ },
86
+ onPing: (id) => {
87
+ if (live()) handlers.onPing(id);
88
+ }
89
+ });
90
+ const read = async () => {
91
+ try {
92
+ const response = await fetch(url, {
93
+ cache: "no-store",
94
+ headers: { accept: "text/event-stream" },
95
+ signal: abort.signal
96
+ });
97
+ if (!response.ok || response.body === null) {
98
+ parser.push(`${await response.text()}\n\n`);
99
+ if (live()) handlers.onEnd({
100
+ retryMilliseconds: retryAfterMilliseconds(response.headers.get("retry-after")) ?? parser.retry(),
101
+ status: response.status
102
+ });
103
+ return;
104
+ }
105
+ if (live()) handlers.onOpen();
106
+ const decoder = new TextDecoder();
107
+ const reader = response.body.getReader();
108
+ for (;;) {
109
+ const { done, value } = await reader.read();
110
+ if (done) break;
111
+ parser.push(decoder.decode(value, { stream: true }));
112
+ }
113
+ } catch {}
114
+ if (live()) handlers.onEnd({
115
+ retryMilliseconds: parser.retry(),
116
+ status: void 0
117
+ });
118
+ };
119
+ read();
120
+ return { close: () => abort.abort() };
121
+ };
122
+ const topicSetDebounceMilliseconds = 300;
123
+ const pingTimeoutMilliseconds = 45e3;
124
+ const backoffBaseMilliseconds = 1e3;
125
+ const backoffCapMilliseconds = 3e4;
126
+ const initialMachineState = (documentVisible) => ({
127
+ attempt: 0,
128
+ documentVisible,
129
+ lastEventId: void 0,
130
+ nextLinkId: 1,
131
+ pageShown: true,
132
+ phase: "idle",
133
+ topics: []
134
+ });
135
+ /** Full jitter over an exponential cap; a server hint is a lower bound. */
136
+ const backoffDelay = (attempt, retryMilliseconds, jitter) => {
137
+ const cap = Math.min(backoffCapMilliseconds, backoffBaseMilliseconds * 2 ** attempt);
138
+ return Math.max(retryMilliseconds ?? 0, Math.floor(jitter * cap));
139
+ };
140
+ const currentLink = (state) => "link" in state ? state.link : void 0;
141
+ const shared = (state) => ({
142
+ attempt: state.attempt,
143
+ documentVisible: state.documentVisible,
144
+ lastEventId: state.lastEventId,
145
+ nextLinkId: state.nextLinkId,
146
+ pageShown: state.pageShown,
147
+ topics: state.topics
148
+ });
149
+ const visible = (state) => state.documentVisible && state.pageShown;
150
+ const wanted = (state) => state.phase !== "closed" && visible(state) && state.topics.length > 0;
151
+ const sameTopics = (left, right) => left.length === right.length && left.every((key) => right.includes(key));
152
+ const unchanged = (state) => ({
153
+ commands: [],
154
+ state
155
+ });
156
+ /** Commands that end the current link, if any. */
157
+ const unlink = (state) => {
158
+ const link = currentLink(state);
159
+ return link === void 0 ? [] : [{
160
+ linkId: link.id,
161
+ type: "disconnect"
162
+ }, {
163
+ timer: "watchdog",
164
+ type: "cancel"
165
+ }];
166
+ };
167
+ const watchdog = (linkId) => ({
168
+ event: {
169
+ linkId,
170
+ type: "watchdogElapsed"
171
+ },
172
+ milliseconds: pingTimeoutMilliseconds,
173
+ timer: "watchdog",
174
+ type: "schedule"
175
+ });
176
+ const idle = (state) => ({
177
+ ...shared(state),
178
+ phase: state.phase === "closed" ? "closed" : "idle"
179
+ });
180
+ const stop = (state) => ({
181
+ commands: [
182
+ {
183
+ timer: "debounce",
184
+ type: "cancel"
185
+ },
186
+ {
187
+ timer: "backoff",
188
+ type: "cancel"
189
+ },
190
+ ...unlink(state)
191
+ ],
192
+ state: idle(state)
193
+ });
194
+ const connect = (state) => {
195
+ if (!wanted(state)) return {
196
+ commands: unlink(state),
197
+ state: idle(state)
198
+ };
199
+ const link = {
200
+ id: state.nextLinkId,
201
+ topics: state.topics
202
+ };
203
+ return {
204
+ commands: [
205
+ ...unlink(state),
206
+ watchdog(link.id),
207
+ {
208
+ link,
209
+ type: "mint"
210
+ }
211
+ ],
212
+ state: {
213
+ ...shared(state),
214
+ link,
215
+ nextLinkId: state.nextLinkId + 1,
216
+ phase: "connecting"
217
+ }
218
+ };
219
+ };
220
+ const retry = (state, retryMilliseconds) => {
221
+ if (!wanted(state)) return {
222
+ commands: unlink(state),
223
+ state: idle(state)
224
+ };
225
+ return {
226
+ commands: [...unlink(state), {
227
+ attempt: state.attempt,
228
+ retryMilliseconds,
229
+ type: "backoff"
230
+ }],
231
+ state: {
232
+ ...shared(state),
233
+ attempt: state.attempt + 1,
234
+ phase: "backoff"
235
+ }
236
+ };
237
+ };
238
+ /** Brings the connection in line with the page and the topic set. */
239
+ const sync = (state) => {
240
+ if (!wanted(state)) return stop(state);
241
+ const link = currentLink(state);
242
+ if (state.phase === "backoff" || link !== void 0 && sameTopics(link.topics, state.topics)) return {
243
+ commands: [{
244
+ timer: "debounce",
245
+ type: "cancel"
246
+ }],
247
+ state
248
+ };
249
+ return connect(state);
250
+ };
251
+ const reactToPage = (state) => {
252
+ if (!visible(state)) return stop(state);
253
+ return currentLink(state) === void 0 && state.phase !== "backoff" ? sync(state) : unchanged(state);
254
+ };
255
+ const streamUrlAfter = (streamUrl, lastEventId) => {
256
+ const url = new URL(streamUrl);
257
+ if (lastEventId !== void 0) url.searchParams.set("lastEventId", lastEventId);
258
+ return url.href;
259
+ };
260
+ /** Events of the client, the page and its timers. */
261
+ const clientTransition = (state, event) => {
262
+ switch (event.type) {
263
+ case "topicsChanged": {
264
+ const next = {
265
+ ...state,
266
+ topics: event.topics
267
+ };
268
+ return next.phase === "closed" ? unchanged(next) : {
269
+ commands: [{
270
+ event: { type: "debounceElapsed" },
271
+ milliseconds: topicSetDebounceMilliseconds,
272
+ timer: "debounce",
273
+ type: "schedule"
274
+ }],
275
+ state: next
276
+ };
277
+ }
278
+ case "debounceElapsed": return sync(state);
279
+ case "visibilityChanged": return reactToPage({
280
+ ...state,
281
+ documentVisible: event.visible
282
+ });
283
+ case "pageHidden": return stop({
284
+ ...state,
285
+ pageShown: false
286
+ });
287
+ case "pageShown": return reactToPage({
288
+ ...state,
289
+ documentVisible: event.visible,
290
+ pageShown: true
291
+ });
292
+ case "backoffElapsed": return state.phase === "backoff" ? connect(state) : unchanged(state);
293
+ case "close": return {
294
+ ...stop(state),
295
+ state: {
296
+ ...shared(state),
297
+ phase: "closed"
298
+ }
299
+ };
300
+ default: return unchanged(state);
301
+ }
302
+ };
303
+ /** Events of one link; an event of an earlier link changes nothing. */
304
+ const linkTransition = (state, event) => {
305
+ const link = currentLink(state);
306
+ if (link?.id !== event.linkId) return unchanged(state);
307
+ switch (event.type) {
308
+ case "ticketMinted": return {
309
+ commands: [{
310
+ linkId: link.id,
311
+ type: "openStream",
312
+ url: streamUrlAfter(event.streamUrl, state.lastEventId)
313
+ }],
314
+ state
315
+ };
316
+ case "ticketFailed":
317
+ case "streamEnded": return retry(state, event.retryMilliseconds);
318
+ case "streamOpened": return {
319
+ commands: state.lastEventId === void 0 ? [watchdog(link.id), { type: "resync" }] : [watchdog(link.id)],
320
+ state: {
321
+ ...shared(state),
322
+ link,
323
+ phase: "open"
324
+ }
325
+ };
326
+ case "received": {
327
+ const { eventId } = event;
328
+ return {
329
+ commands: [watchdog(link.id)],
330
+ state: {
331
+ ...state,
332
+ attempt: 0,
333
+ lastEventId: eventId === void 0 || eventId === "" ? state.lastEventId : eventId
334
+ }
335
+ };
336
+ }
337
+ case "watchdogElapsed": return retry(state);
338
+ default: return unchanged(state);
339
+ }
340
+ };
341
+ const transition = (state, event) => "linkId" in event ? linkTransition(state, event) : clientTransition(state, event);
342
+ /**
343
+ * The page lifecycle that the realtime connection follows: it connects only
344
+ * while the document is visible and the page is shown. The browser layer
345
+ * listens to `visibilitychange` on the document and to `pagehide` and
346
+ * `pageshow` on the window.
347
+ */
348
+ var PageLifecycle = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/PageLifecycle") {};
349
+ const listen = (target, type, listener) => Effect.acquireRelease(Effect.sync(() => target?.addEventListener(type, listener)), () => Effect.sync(() => target?.removeEventListener(type, listener)));
350
+ /** The page of `document` and `window`; a test passes its own. */
351
+ const layerBrowser = ({ document, window }) => {
352
+ const documentVisible = () => document === void 0 || document.visibilityState !== "hidden";
353
+ return Layer.succeed(PageLifecycle, PageLifecycle.of({
354
+ events: Stream.callback((queue) => {
355
+ const offer = (event) => () => {
356
+ Queue.offerUnsafe(queue, event());
357
+ };
358
+ return Effect.all([
359
+ listen(document, "visibilitychange", offer(() => ({
360
+ type: "visibilityChanged",
361
+ visible: documentVisible()
362
+ }))),
363
+ listen(window, "pagehide", offer(() => ({ type: "pageHidden" }))),
364
+ listen(window, "pageshow", offer(() => ({
365
+ type: "pageShown",
366
+ visible: documentVisible()
367
+ })))
368
+ ]);
369
+ }),
370
+ visible: Effect.sync(documentVisible)
371
+ }));
372
+ };
373
+ /**
374
+ * The page of this runtime: the browser `document` and `window`, or a page
375
+ * that is always visible where they do not exist.
376
+ */
377
+ const layer$5 = Layer.suspend(() => {
378
+ const host = globalThis;
379
+ return layerBrowser({
380
+ document: host.document,
381
+ window: host.window
382
+ });
383
+ });
384
+ /**
385
+ * The event stream of one link as a `Stream`: the stream request read with
386
+ * `fetch` (`./event-stream`), as `open`, `event`, `ping` and `end` items. The
387
+ * stream ends after its `end` item; a consumer that stops early closes the
388
+ * request, and no `end` follows.
389
+ */
390
+ var EventStreams = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/EventStreams") {};
391
+ const fromFactory = (factory) => EventStreams.of({ open: (url) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => factory(url, {
392
+ onEnd: (end) => {
393
+ Queue.offerUnsafe(queue, {
394
+ end,
395
+ type: "end"
396
+ });
397
+ Queue.endUnsafe(queue);
398
+ },
399
+ onEvent: (event) => {
400
+ Queue.offerUnsafe(queue, {
401
+ event,
402
+ type: "event"
403
+ });
404
+ },
405
+ onOpen: () => {
406
+ Queue.offerUnsafe(queue, { type: "open" });
407
+ },
408
+ onPing: (id) => {
409
+ Queue.offerUnsafe(queue, {
410
+ id,
411
+ type: "ping"
412
+ });
413
+ }
414
+ })), (source) => Effect.sync(() => source.close()))) });
415
+ /** The streams of a `RealtimeEventSourceFactory`. */
416
+ const layerFromFactory = (factory) => Layer.succeed(EventStreams, fromFactory(factory));
417
+ /** Reads each stream with the `fetch` of `FetchHttpClient.Fetch`. */
418
+ const layer$4 = Layer.effect(EventStreams, FetchHttpClient.Fetch.pipe(Effect.map((fetch) => fromFactory(createFetchEventSourceFactory(fetch)))));
419
+ /** One stable key per topic, whatever the key order of the object. */
420
+ const realtimeTopicKey = ({ filter, schema }) => JSON.stringify(filter === void 0 ? [schema] : [
421
+ schema,
422
+ filter.field,
423
+ filter.eq
424
+ ]);
425
+ const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
426
+ const isFilterValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
427
+ const isTopic = (value) => isRecord$1(value) && typeof value.schema === "string" && (value.filter === void 0 || isRecord$1(value.filter) && typeof value.filter.field === "string" && isFilterValue(value.filter.eq));
428
+ const isOp = (value) => value === "create" || value === "update" || value === "delete";
429
+ /** The `data` of a `change` event, or undefined when it is malformed. */
430
+ const parseRealtimeChange = (data) => {
431
+ let value;
432
+ try {
433
+ value = JSON.parse(data);
434
+ } catch {
435
+ return;
436
+ }
437
+ return isRecord$1(value) && typeof value.id === "string" && isOp(value.op) && typeof value.revision === "string" && isTopic(value.topic) ? {
438
+ id: value.id,
439
+ op: value.op,
440
+ revision: value.revision,
441
+ topic: value.topic
442
+ } : void 0;
443
+ };
444
+ var RealtimeClient = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/RealtimeClient") {};
445
+ /** The answer of the ticket route, as far as the client reads it. */
446
+ const TicketAnswer = Schema.Struct({ streamUrl: Schema.String });
447
+ /** The least wait before a delivery: a burst of changes joins one delivery. */
448
+ const changeWindowMilliseconds = 250;
449
+ /** The random extra wait, so that the tabs of many users refetch apart. */
450
+ const changeJitterMilliseconds = 750;
451
+ const resyncUpdate = { op: "resync" };
452
+ const register = (listeners, listener) => {
453
+ const own = () => listener();
454
+ listeners.add(own);
455
+ return () => {
456
+ listeners.delete(own);
457
+ };
458
+ };
459
+ /** Keeps the listener that `listen` adds for the life of the scope. */
460
+ const scoped = (listen) => Effect.acquireRelease(Effect.sync(listen), (unlisten) => Effect.sync(unlisten)).pipe(Effect.asVoid);
461
+ /** The `ticketFailed` of `link`, after a warning with the failure. */
462
+ const failed = (link, error, retryMilliseconds) => {
463
+ const event = {
464
+ linkId: link.id,
465
+ retryMilliseconds,
466
+ type: "ticketFailed"
467
+ };
468
+ return Effect.logWarning("The realtime ticket request failed", error).pipe(Effect.as(event));
469
+ };
470
+ /**
471
+ * Logs a defect of a forked fiber, then runs `recover`. `FiberMap` and
472
+ * `FiberHandle` keep the failure of a fiber only for `join`, and nothing joins
473
+ * them. It runs also when the fiber was interrupted: an event source can throw
474
+ * as it closes.
475
+ */
476
+ const surfaceDefects = (message, annotations = {}, recover = Effect.void) => (effect) => Effect.onErrorIf(effect, Cause.hasDies, (cause) => Effect.logError(message, cause).pipe(Effect.annotateLogs(annotations), Effect.andThen(recover), Effect.asVoid));
477
+ /** Opens the connection for the life of the scope. */
478
+ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* makeConnection(options) {
479
+ const http = yield* HttpClient.HttpClient;
480
+ const page = yield* PageLifecycle;
481
+ const streams = yield* EventStreams;
482
+ const events = yield* Queue.unbounded();
483
+ const timers = yield* FiberMap.make();
484
+ const links = yield* FiberMap.make();
485
+ const delivery = yield* FiberHandle.make();
486
+ const closed = yield* Latch.make();
487
+ const registrations = /* @__PURE__ */ new Map();
488
+ const resyncListeners = /* @__PURE__ */ new Set();
489
+ const accessListeners = /* @__PURE__ */ new Set();
490
+ /** Per topic key, the latest change of each record, by last arrival. */
491
+ const pending = /* @__PURE__ */ new Map();
492
+ let resyncPending = false;
493
+ let machine = initialMachineState(yield* page.visible);
494
+ const send = (event) => Queue.offer(events, event);
495
+ const topicsChanged = () => {
496
+ if (machine.phase === "closed") return;
497
+ Queue.offerUnsafe(events, {
498
+ topics: [...registrations.keys()],
499
+ type: "topicsChanged"
500
+ });
501
+ };
502
+ /** Delivers the pending changes, or the pending Resync, to the current listeners. */
503
+ const deliver = Effect.sync(() => {
504
+ const batches = [...pending];
505
+ pending.clear();
506
+ if (resyncPending) {
507
+ resyncPending = false;
508
+ for (const onResync of resyncListeners) onResync();
509
+ return;
510
+ }
511
+ for (const [key, changes] of batches) {
512
+ const batch = [...changes.values()];
513
+ for (const onChanges of registrations.get(key)?.listeners ?? []) onChanges(batch);
514
+ }
515
+ });
516
+ /**
517
+ * The first change or Resync after a delivery schedules the next one; later
518
+ * ones join it without delaying it.
519
+ */
520
+ const scheduleDelivery = FiberHandle.run(delivery, Random.nextIntBetween(0, changeJitterMilliseconds, { halfOpen: true }).pipe(Effect.flatMap((jitter) => Effect.sleep(changeWindowMilliseconds + jitter)), Effect.andThen(deliver), surfaceDefects("A realtime delivery failed with a defect")), { onlyIfMissing: true });
521
+ /**
522
+ * Replaces the pending changes with one Resync at the next delivery.
523
+ * Without a Resync listener no refetch covers them, so they stay.
524
+ */
525
+ const resync = Effect.suspend(() => {
526
+ if (resyncListeners.size === 0) return Effect.void;
527
+ resyncPending = true;
528
+ return scheduleDelivery;
529
+ });
530
+ const route = (change) => Effect.suspend(() => {
531
+ const key = realtimeTopicKey(change.topic);
532
+ if (!registrations.has(key)) return Effect.void;
533
+ const changes = pending.get(key) ?? /* @__PURE__ */ new Map();
534
+ changes.delete(change.id);
535
+ changes.set(change.id, change);
536
+ pending.set(key, changes);
537
+ return scheduleDelivery;
538
+ });
539
+ const handle = (event) => {
540
+ switch (event.type) {
541
+ case "change": {
542
+ const change = parseRealtimeChange(event.data);
543
+ return change === void 0 ? Effect.void : route(change);
544
+ }
545
+ case "reset": return resync;
546
+ case "access-changed": return Effect.sync(() => {
547
+ for (const onAccessChanged of accessListeners) onAccessChanged();
548
+ }).pipe(Effect.andThen(options.resyncOnAccessChange ? resync : Effect.void));
549
+ default: return Effect.void;
550
+ }
551
+ };
552
+ const receive = (linkId, item) => {
553
+ switch (item.type) {
554
+ case "open": return send({
555
+ linkId,
556
+ type: "streamOpened"
557
+ });
558
+ case "event": return send({
559
+ event: item.event,
560
+ linkId,
561
+ type: "streamEvent"
562
+ });
563
+ case "ping": return send({
564
+ eventId: item.id,
565
+ linkId,
566
+ type: "received"
567
+ });
568
+ case "end": return send({
569
+ linkId,
570
+ retryMilliseconds: item.end.retryMilliseconds,
571
+ type: "streamEnded"
572
+ });
573
+ default: return Effect.void;
574
+ }
575
+ };
576
+ /** Mints the ticket of `link`; a failed ticket waits at least its `Retry-After`. */
577
+ const ticket = Effect.fn("RealtimeClient.ticket")(function* ticket(link) {
578
+ const topics = link.topics.flatMap((key) => {
579
+ const registration = registrations.get(key);
580
+ return registration === void 0 ? [] : [registration.topic];
581
+ });
582
+ const response = yield* http.execute(HttpClientRequest.post(options.ticketUrl, { body: HttpBody.raw(JSON.stringify({ topics }), { contentType: "application/json" }) }));
583
+ const { streamUrl } = yield* HttpClientResponse.filterStatusOk(response).pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(TicketAnswer)));
584
+ return {
585
+ linkId: link.id,
586
+ streamUrl,
587
+ type: "ticketMinted"
588
+ };
589
+ }, (effect, link) => effect.pipe(Effect.catchTags({
590
+ HttpClientError: (error) => failed(link, error, retryAfterMilliseconds(error.response?.headers["retry-after"])),
591
+ SchemaError: (error) => failed(link, error)
592
+ }), Effect.provideService(FetchHttpClient.RequestInit, { credentials: "same-origin" }), Effect.provideService(HttpClient.TracerPropagationEnabled, false)));
593
+ const schedule = (timer, milliseconds, event) => FiberMap.run(timers, timer, Effect.sleep(milliseconds).pipe(Effect.andThen(send(event)), surfaceDefects("A realtime timer failed with a defect", { timer })));
594
+ const run = (command) => {
595
+ switch (command.type) {
596
+ case "schedule": return schedule(command.timer, command.milliseconds, command.event);
597
+ case "cancel": return FiberMap.remove(timers, command.timer);
598
+ case "backoff": return Random.next.pipe(Effect.flatMap((jitter) => schedule("backoff", backoffDelay(command.attempt, command.retryMilliseconds, jitter), { type: "backoffElapsed" })));
599
+ case "mint": {
600
+ const linkId = command.link.id;
601
+ return FiberMap.run(links, linkId, ticket(command.link).pipe(Effect.flatMap(send), surfaceDefects("The realtime ticket request failed with a defect", { linkId }, send({
602
+ linkId,
603
+ retryMilliseconds: void 0,
604
+ type: "ticketFailed"
605
+ }))));
606
+ }
607
+ case "openStream": {
608
+ const { linkId } = command;
609
+ return FiberMap.run(links, linkId, streams.open(command.url).pipe(Stream.runForEach((item) => receive(linkId, item)), surfaceDefects("The realtime event stream failed with a defect", { linkId }, send({
610
+ linkId,
611
+ retryMilliseconds: void 0,
612
+ type: "streamEnded"
613
+ }))));
614
+ }
615
+ case "disconnect": return FiberMap.remove(links, command.linkId);
616
+ case "resync": return resync;
617
+ default: return Effect.void;
618
+ }
619
+ };
620
+ const apply = Effect.fnUntraced(function* apply(event) {
621
+ const next = transition(machine, event);
622
+ machine = next.state;
623
+ for (const command of next.commands) yield* run(command);
624
+ });
625
+ const step = (event) => {
626
+ if (event.type !== "streamEvent") return apply(event);
627
+ const { linkId } = event;
628
+ const current = currentLink(machine)?.id === linkId;
629
+ return apply({
630
+ eventId: event.event.id,
631
+ linkId,
632
+ type: "received"
633
+ }).pipe(Effect.andThen(current ? handle(event.event) : Effect.void));
634
+ };
635
+ yield* Queue.take(events).pipe(Effect.flatMap((event) => step(event).pipe(Effect.catchDefect((defect) => Effect.logError("A realtime connection step failed", defect).pipe(Effect.annotateLogs({ event: event.type }))))), Effect.forever, Effect.forkScoped({ startImmediately: true }));
636
+ yield* page.events.pipe(Stream.runForEach(send), Effect.forkScoped({ startImmediately: true }));
637
+ yield* Effect.addFinalizer(() => Effect.sync(() => {
638
+ machine = transition(machine, { type: "close" }).state;
639
+ pending.clear();
640
+ resyncPending = false;
641
+ }).pipe(Effect.andThen(closed.open)));
642
+ return {
643
+ closed: closed.await,
644
+ listen: (topic, onChanges) => {
645
+ const key = realtimeTopicKey(topic);
646
+ const listener = (changes) => onChanges(changes);
647
+ const registration = registrations.get(key) ?? {
648
+ listeners: /* @__PURE__ */ new Set(),
649
+ topic
650
+ };
651
+ registration.listeners.add(listener);
652
+ if (!registrations.has(key)) {
653
+ registrations.set(key, registration);
654
+ topicsChanged();
655
+ }
656
+ return () => {
657
+ if (!registration.listeners.delete(listener)) return;
658
+ if (registration.listeners.size === 0) {
659
+ registrations.delete(key);
660
+ pending.delete(key);
661
+ topicsChanged();
662
+ }
663
+ };
664
+ },
665
+ listenAccessChanges: (onAccessChanged) => register(accessListeners, onAccessChanged),
666
+ listenResyncs: (onResync) => register(resyncListeners, onResync),
667
+ state: () => ({
668
+ machine,
669
+ topics: [...registrations.values()].map(({ topic }) => topic)
670
+ })
671
+ };
672
+ });
673
+ /** The `RealtimeClient` of one connection, open for the life of the scope. */
674
+ const make$4 = Effect.fn("RealtimeClient.make")(function* make(options) {
675
+ const connection = yield* makeConnection({
676
+ ...options,
677
+ resyncOnAccessChange: true
678
+ });
679
+ const untilClosed = Stream.interruptWhen(connection.closed);
680
+ return RealtimeClient.of({
681
+ accessChanges: Stream.callback((queue) => scoped(() => connection.listenAccessChanges(() => {
682
+ Queue.offerUnsafe(queue, void 0);
683
+ }))).pipe(untilClosed),
684
+ subscribe: (topic) => Stream.callback((queue) => Effect.andThen(scoped(() => connection.listen(topic, (changes) => {
685
+ Queue.offerAllUnsafe(queue, changes);
686
+ })), scoped(() => connection.listenResyncs(() => {
687
+ Queue.offerUnsafe(queue, resyncUpdate);
688
+ })))).pipe(untilClosed)
689
+ });
690
+ });
691
+ /** `RealtimeClient` over the `HttpClient`, `EventStreams` and `PageLifecycle` of the context. */
692
+ const layerWithoutDependencies = (options) => Layer.effect(RealtimeClient, make$4(options));
693
+ /** `RealtimeClient` with the `fetch` of `FetchHttpClient.Fetch` and the page of this runtime. */
694
+ const layer$3 = (options) => layerWithoutDependencies(options).pipe(Layer.provide([
695
+ FetchHttpClient.layer,
696
+ layer$4,
697
+ layer$5
698
+ ]));
699
+ /** `layer` with options that Effect `Config` reads. */
700
+ const layerConfig$2 = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layer$3));
701
+ /** The changes and Resyncs of `topic` from the `RealtimeClient` of the context. */
702
+ const subscribe = (topic) => Stream.unwrap(RealtimeClient.useSync((client) => client.subscribe(topic)));
703
+ /**
704
+ * The CI client on the Effect Core: the operations of `createClient` and of
705
+ * its transports. An adapter gives each operation as its `CiResult`
706
+ * envelope: the HTTP adapter (`./http`) for the direct and proxy transports,
707
+ * or an executor of the app. Only a transport failure fails the envelope;
708
+ * `execute` moves the `CiError` of a failed envelope to the typed channel.
709
+ */
710
+ var CiClient = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/CiClient") {};
711
+ /** The `CiClient` over one adapter. */
712
+ const make$3 = (executeResult) => CiClient.of({
713
+ execute: (operationId, input, options) => Effect.flatMap(executeResult(operationId, input, options), fromCiResult),
714
+ executeResult
715
+ });
716
+ /**
717
+ * The adapter over an executor of the app. A `CiTransportError` rejection
718
+ * fails with it; a rejection after the caller's signal aborted interrupts;
719
+ * any other rejection, such as the `TypeError` of bad input, is a Defect
720
+ * that keeps its error.
721
+ */
722
+ const executeOf = (executor) => (operationId, input, options) => Effect.tryPromise({
723
+ catch: (error) => {
724
+ if (error instanceof CiTransportError) return error;
725
+ throw error;
726
+ },
727
+ try: (signal) => executor.execute(operationId, input, {
728
+ ...options,
729
+ signal: options.signal === void 0 ? signal : AbortSignal.any([options.signal, signal])
730
+ })
731
+ }).pipe(Effect.catchCauseIf(() => options.signal?.aborted === true, () => Effect.interrupt), Effect.map(toCiResult));
732
+ /** `CiClient` over the tenant Application HTTP API; a bad `tenantUrl` dies with `TypeError`. */
733
+ const layerDirect = (options) => Layer.sync(CiClient, () => make$3(makeHttpExecute(directHttpOptions(options))));
734
+ /** `CiClient` over the app's protocol proxy; a bad `serverUrl` or `path` dies with `TypeError`. */
735
+ const layerProxy = (options) => Layer.sync(CiClient, () => make$3(makeHttpExecute(proxyHttpOptions(options))));
736
+ /** `CiClient` over a `TypedOperationExecutor`, such as the transport of `createClient`. */
737
+ const layerFromExecutor = (executor) => Layer.succeed(CiClient, make$3(executeOf(executor)));
738
+ /** `layerDirect` with options that Effect `Config` reads. */
739
+ const layerDirectConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layerDirect));
740
+ /** `layerProxy` with options that Effect `Config` reads. */
741
+ const layerProxyConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layerProxy));
742
+ /**
743
+ * Run follow on the Effect Core: polls a run's snapshot and event pages
744
+ * until a terminal event or status. Time comes from `Clock`; a failed read
745
+ * fails with its `CiError`, so the caller keeps the code of CI.
746
+ */
747
+ /**
748
+ * Ten minutes: a skill run's five-minute AI deadline plus queueing and
749
+ * delivery slack. Long runs return a `runId` immediately; follow is how
750
+ * callers wait for their outcome.
751
+ */
752
+ const DEFAULT_FOLLOW_RUN_DEADLINE_MS = 6e5;
753
+ const DEFAULT_IDLE_MS = 50;
754
+ const MAX_BACKOFF_IDLE_MS = 1e3;
755
+ const terminalEventKinds = /* @__PURE__ */ new Set([
756
+ "cancelled",
757
+ "completed",
758
+ "failed"
759
+ ]);
760
+ const terminalSnapshotStatuses = /* @__PURE__ */ new Set([
761
+ "cancelled",
762
+ "failed",
763
+ "succeeded"
764
+ ]);
765
+ const asRecord$2 = (value) => {
766
+ if (typeof value !== "object" || value === null) return null;
767
+ return value;
768
+ };
769
+ const readString$1 = (record, key) => {
770
+ const candidate = record[key];
771
+ return typeof candidate === "string" ? candidate : null;
772
+ };
773
+ const snapshotStatus = (value) => {
774
+ const record = asRecord$2(value);
775
+ if (record === null) return null;
776
+ const nested = asRecord$2(record.result);
777
+ return readString$1(record, "status") ?? (nested === null ? null : readString$1(nested, "status"));
778
+ };
779
+ const isTerminalEvent = (event) => {
780
+ const record = asRecord$2(event);
781
+ const kind = record === null ? null : readString$1(record, "kind");
782
+ return kind !== null && terminalEventKinds.has(kind);
783
+ };
784
+ /**
785
+ * Reads the pages after `page` of a run that has already finished and
786
+ * returns the last non-empty one. Stops at the first terminal event.
787
+ */
788
+ const readRemainingPages = Effect.fnUntraced(function* readRemainingPages(source, runId, page) {
789
+ let last = page;
790
+ while (last.nextCursor !== null && !last.events.some(isTerminalEvent)) {
791
+ const next = yield* Effect.flatMap(source.stream({
792
+ afterCursor: last.nextCursor,
793
+ runId
794
+ }), fromCiResult);
795
+ if (next.events.length === 0) return last;
796
+ last = next;
797
+ }
798
+ return last;
799
+ });
800
+ /**
801
+ * Internal. Follows dedicated run events until a terminal event or snapshot
802
+ * status, and succeeds with the last event page read.
803
+ */
804
+ const followSource = Effect.fnUntraced(function* followSource(source, options) {
805
+ const deadlineMs = options.deadlineMs ?? 6e5;
806
+ const idleMs = options.idleMs ?? DEFAULT_IDLE_MS;
807
+ const maxIdleMs = Math.max(idleMs, MAX_BACKOFF_IDLE_MS);
808
+ const { runId } = options;
809
+ const deadline = (yield* Clock.currentTimeMillis) + deadlineMs;
810
+ let afterCursor;
811
+ let emptyPolls = 0;
812
+ while ((yield* Clock.currentTimeMillis) < deadline) {
813
+ const snapshot = yield* Effect.flatMap(source.get({ runId }), fromCiResult);
814
+ const page = yield* Effect.flatMap(source.stream(afterCursor === void 0 ? { runId } : {
815
+ afterCursor,
816
+ runId
817
+ }), fromCiResult);
818
+ if (page.events.some(isTerminalEvent)) return page;
819
+ const status = snapshotStatus(snapshot);
820
+ if (status !== null && terminalSnapshotStatuses.has(status)) return yield* readRemainingPages(source, runId, page);
821
+ if (page.nextCursor !== null) afterCursor = page.nextCursor;
822
+ emptyPolls = page.events.length === 0 ? emptyPolls + 1 : 0;
823
+ const wait = Math.min(idleMs * 2 ** emptyPolls, maxIdleMs);
824
+ if (wait > 0) yield* Effect.sleep(wait);
825
+ }
826
+ return yield* new CiError({
827
+ code: "unavailable",
828
+ message: "Run did not finish",
829
+ retryable: true
830
+ });
831
+ });
832
+ var Runs = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/Runs") {};
833
+ const make$2 = Effect.gen(function* make() {
834
+ const client = yield* CiClient;
835
+ return Runs.of({ follow: (options) => {
836
+ const execution = { organizationId: options.organizationId };
837
+ return followSource({
838
+ get: (input) => client.executeResult("runs_get", input, execution),
839
+ stream: (input) => client.executeResult("runs_stream", input, execution)
840
+ }, options);
841
+ } });
842
+ });
843
+ /** `Runs` over the `CiClient` of the context. */
844
+ const layer$2 = Layer.effect(Runs, make$2);
845
+ const base64Url = (bytes) => {
846
+ let binary = "";
847
+ for (const byte of bytes) binary += String.fromCodePoint(byte);
848
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/[=]+$/u, "");
849
+ };
850
+ const createOauthRandomValue = (crypto = globalThis.crypto) => base64Url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
851
+ const createPkcePair = async (crypto = globalThis.crypto) => {
852
+ const verifier = createOauthRandomValue(crypto);
853
+ const challengeBytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)));
854
+ return {
855
+ challenge: base64Url(challengeBytes),
856
+ method: "S256",
857
+ verifier
858
+ };
859
+ };
860
+ var FederatedAuth = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/FederatedAuth") {};
861
+ const configurationError = (message) => new FederatedAuthError("configuration_error", message);
862
+ const transportError = (cause) => new CiTransportError({ cause });
863
+ const loginRequired = () => new FederatedAuthError("reauthorization_required", "A new CI login is required");
864
+ const readJson = (response) => Effect.promise(async () => {
865
+ try {
866
+ return await response.json();
867
+ } catch {
868
+ return null;
869
+ }
870
+ });
871
+ /** The browser navigation; without one, a configuration error. */
872
+ const navigation = (navigate) => {
873
+ if (navigate !== void 0) return (url) => Effect.sync(() => navigate(url));
874
+ return (url) => Effect.suspend(() => {
875
+ const { location } = globalThis;
876
+ if (!location || !("assign" in location) || typeof location.assign !== "function") return Effect.fail(configurationError("Provide navigate when browser navigation is unavailable"));
877
+ location.assign(url);
878
+ return Effect.void;
879
+ });
880
+ };
881
+ /** The state and listeners of a session. */
882
+ const makeState = () => {
883
+ const listeners = /* @__PURE__ */ new Set();
884
+ let state = { status: "anonymous" };
885
+ const subscribe = (listener) => {
886
+ listeners.add(listener);
887
+ return () => {
888
+ listeners.delete(listener);
889
+ };
890
+ };
891
+ return {
892
+ changes: Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => subscribe((next) => {
893
+ Queue.offerUnsafe(queue, next);
894
+ })), (unsubscribe) => Effect.sync(unsubscribe))),
895
+ getState: () => state,
896
+ subscribe,
897
+ transition: (next) => {
898
+ state = next;
899
+ for (const listener of listeners) listener(next);
900
+ }
901
+ };
902
+ };
903
+ /**
904
+ * One completion at a time: a second call while the first runs gets its
905
+ * result. `reset` forgets the running one.
906
+ */
907
+ const makeCompletion = () => {
908
+ let running;
909
+ return {
910
+ reset: () => {
911
+ running = void 0;
912
+ },
913
+ run: (complete) => Effect.suspend(() => {
914
+ if (running !== void 0) return Deferred.await(running);
915
+ const current = Deferred.makeUnsafe();
916
+ running = current;
917
+ return complete.pipe(Effect.onExit((exit) => Effect.suspend(() => {
918
+ if (running === current) running = void 0;
919
+ return Deferred.done(current, exit);
920
+ })));
921
+ })
922
+ };
923
+ };
924
+ const transactionLifetimeMs = 6e5;
925
+ const maxReturnTargetLength = 2048;
926
+ /** An absolute URL without credentials, else `null`. */
927
+ const absoluteUrl = (value) => {
928
+ try {
929
+ const url = new URL(value);
930
+ return url.username === "" && url.password === "" ? url : null;
931
+ } catch {
932
+ return null;
933
+ }
934
+ };
935
+ const parseUrl = (value, field) => {
936
+ const url = absoluteUrl(value);
937
+ return url === null ? Effect.fail(configurationError(`${field} must be an absolute URL without credentials`)) : Effect.succeed(url);
938
+ };
939
+ const isRecord = (value) => value !== null && Object(value) === value && !Array.isArray(value);
940
+ const parseTransaction = (serialized) => {
941
+ try {
942
+ const value = JSON.parse(serialized);
943
+ if (!isRecord(value) || typeof value.expiresAt !== "number" || typeof value.returnTo !== "string" || typeof value.state !== "string" || typeof value.verifier !== "string") return null;
944
+ return {
945
+ expiresAt: value.expiresAt,
946
+ returnTo: value.returnTo,
947
+ state: value.state,
948
+ verifier: value.verifier
949
+ };
950
+ } catch {
951
+ return null;
952
+ }
953
+ };
954
+ const asRecord$1 = (value) => {
955
+ if (typeof value !== "object" || value === null) return null;
956
+ return value;
957
+ };
958
+ const parseToken = (value, now) => {
959
+ const record = asRecord$1(value);
960
+ const own = (key) => record !== null && Object.hasOwn(record, key) ? record[key] : void 0;
961
+ const accessToken = own("access_token");
962
+ const expiresIn = own("expires_in");
963
+ if (typeof accessToken !== "string" || accessToken.length === 0 || typeof expiresIn !== "number" || !Number.isFinite(expiresIn) || expiresIn <= 0 || own("token_type") !== "Bearer") return null;
964
+ return {
965
+ accessToken,
966
+ expiresAt: now + expiresIn * 1e3
967
+ };
968
+ };
969
+ /**
970
+ * The session of browser federated sign-in: one PKCE login transaction in
971
+ * `sessionStorage`, and the access token in memory only. A configuration
972
+ * error fails with `FederatedAuthError`.
973
+ */
974
+ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
975
+ const tenantUrl = yield* parseUrl(options.tenantUrl, "tenantUrl");
976
+ if (tenantUrl.pathname !== "/" || tenantUrl.search !== "" || tenantUrl.hash !== "") return yield* configurationError("tenantUrl must contain only the tenant origin");
977
+ const tenantOrigin = tenantUrl.origin;
978
+ const redirectUri = yield* parseUrl(options.redirectUri, "redirectUri");
979
+ const crypto = options.crypto ?? globalThis.crypto;
980
+ const fetch = options.fetch ?? globalThis.fetch;
981
+ const now = options.now ?? Date.now;
982
+ const storage = options.sessionStorage ?? globalThis.sessionStorage;
983
+ const navigate = navigation(options.navigate);
984
+ if (options.clientId.length === 0 || options.scopes.length === 0) return yield* configurationError("clientId and at least one scope are required");
985
+ if (crypto === void 0 || storage === void 0 || fetch === void 0) return yield* configurationError("Browser crypto, fetch, and sessionStorage are required");
986
+ const storageKey = `ci:federated-auth:${redirectUri.origin}:${options.clientId}`;
987
+ const { changes, getState, subscribe, transition } = makeState();
988
+ const completion = makeCompletion();
989
+ let token;
990
+ let rememberedReturnTo;
991
+ const fail = (error) => Effect.suspend(() => {
992
+ token = void 0;
993
+ transition({
994
+ error,
995
+ status: "error"
996
+ });
997
+ return Effect.fail(error);
998
+ });
999
+ const normalizedReturnTarget = (value) => Effect.suspend(() => {
1000
+ if (value.length > maxReturnTargetLength) return Effect.fail(new FederatedAuthError("invalid_return_target", "The return target is too long"));
1001
+ const target = new URL(value, redirectUri.origin);
1002
+ return target.origin === redirectUri.origin ? Effect.succeed(target.href) : Effect.fail(new FederatedAuthError("invalid_return_target", "The return target must share the callback origin"));
1003
+ });
1004
+ const beginLogin = Effect.fnUntraced(function* beginLogin({ returnTo }) {
1005
+ const normalizedReturnTo = yield* normalizedReturnTarget(returnTo);
1006
+ rememberedReturnTo = normalizedReturnTo;
1007
+ const pkce = yield* Effect.promise(() => createPkcePair(crypto));
1008
+ const transaction = {
1009
+ expiresAt: now() + transactionLifetimeMs,
1010
+ returnTo: normalizedReturnTo,
1011
+ state: createOauthRandomValue(crypto),
1012
+ verifier: pkce.verifier
1013
+ };
1014
+ storage.setItem(storageKey, JSON.stringify(transaction));
1015
+ const authorizationUrl = new URL("/oauth/authorize", tenantOrigin);
1016
+ authorizationUrl.searchParams.set("client_id", options.clientId);
1017
+ authorizationUrl.searchParams.set("redirect_uri", redirectUri.href);
1018
+ authorizationUrl.searchParams.set("response_type", "code");
1019
+ authorizationUrl.searchParams.set("scope", options.scopes.join(" "));
1020
+ authorizationUrl.searchParams.set("state", transaction.state);
1021
+ authorizationUrl.searchParams.set("code_challenge", pkce.challenge);
1022
+ authorizationUrl.searchParams.set("code_challenge_method", pkce.method);
1023
+ token = void 0;
1024
+ completion.reset();
1025
+ transition({ status: "redirecting" });
1026
+ yield* navigate(authorizationUrl.href);
1027
+ return authorizationUrl.href;
1028
+ });
1029
+ const complete = Effect.fnUntraced(function* complete(callbackUrl) {
1030
+ const callback = absoluteUrl(callbackUrl);
1031
+ if (callback === null) {
1032
+ storage.removeItem(storageKey);
1033
+ return yield* fail(new FederatedAuthError("invalid_callback", "The callback URL is invalid"));
1034
+ }
1035
+ if (callback.origin !== redirectUri.origin || callback.pathname !== redirectUri.pathname) {
1036
+ storage.removeItem(storageKey);
1037
+ return yield* fail(new FederatedAuthError("invalid_callback", "The callback URL does not match redirectUri"));
1038
+ }
1039
+ const serialized = storage.getItem(storageKey);
1040
+ storage.removeItem(storageKey);
1041
+ if (serialized === null) return yield* fail(new FederatedAuthError("invalid_state", "No login transaction exists"));
1042
+ const transaction = parseTransaction(serialized);
1043
+ if (transaction === null) return yield* fail(new FederatedAuthError("invalid_state", "Invalid login transaction"));
1044
+ if (transaction.expiresAt <= now()) return yield* fail(new FederatedAuthError("transaction_expired", "The login transaction expired"));
1045
+ if (callback.searchParams.get("state") !== transaction.state) return yield* fail(new FederatedAuthError("invalid_state", "OAuth state mismatch"));
1046
+ const authorizationError = callback.searchParams.get("error");
1047
+ const code = callback.searchParams.get("code");
1048
+ if (authorizationError !== null || code === null || code.length === 0) return yield* fail(new FederatedAuthError("authorization_failed", authorizationError ?? "The callback did not include a code"));
1049
+ const body = new URLSearchParams({
1050
+ client_id: options.clientId,
1051
+ code,
1052
+ code_verifier: transaction.verifier,
1053
+ grant_type: "authorization_code",
1054
+ redirect_uri: redirectUri.href
1055
+ });
1056
+ const response = yield* Effect.tryPromise({
1057
+ catch: transportError,
1058
+ try: (signal) => fetch(new URL("/oauth/token", tenantOrigin), {
1059
+ body,
1060
+ headers: { "content-type": "application/x-www-form-urlencoded" },
1061
+ method: "POST",
1062
+ signal
1063
+ })
1064
+ });
1065
+ if (!response.ok) return yield* fail(new FederatedAuthError("token_exchange_failed", "The authorization code exchange failed"));
1066
+ const exchanged = parseToken(yield* readJson(response), now());
1067
+ if (exchanged === null) return yield* fail(new FederatedAuthError("token_exchange_failed", "The authorization server returned an invalid token"));
1068
+ token = exchanged;
1069
+ transition({
1070
+ expiresAt: exchanged.expiresAt,
1071
+ status: "authenticated"
1072
+ });
1073
+ rememberedReturnTo = transaction.returnTo;
1074
+ return { returnTo: transaction.returnTo };
1075
+ });
1076
+ const reauthorize = (input) => Effect.suspend(() => {
1077
+ const returnTo = input?.returnTo ?? rememberedReturnTo;
1078
+ return returnTo === void 0 ? Effect.fail(new FederatedAuthError("reauthorization_required", "A same-origin return target is required to restart CI login")) : beginLogin({ returnTo });
1079
+ });
1080
+ return FederatedAuth.of({
1081
+ beginLogin,
1082
+ changes,
1083
+ completeLogin: (callbackUrl) => completion.run(complete(callbackUrl)),
1084
+ getAccessToken: Effect.suspend(() => {
1085
+ if (token !== void 0 && token.expiresAt <= now()) {
1086
+ token = void 0;
1087
+ transition({ status: "expired" });
1088
+ return Effect.andThen(reauthorize(), Effect.fail(loginRequired()));
1089
+ }
1090
+ return token === void 0 ? Effect.fail(loginRequired()) : Effect.succeed(token.accessToken);
1091
+ }),
1092
+ getState,
1093
+ logout: Effect.suspend(() => {
1094
+ const accessToken = token?.accessToken;
1095
+ token = void 0;
1096
+ completion.reset();
1097
+ rememberedReturnTo = void 0;
1098
+ storage.removeItem(storageKey);
1099
+ transition({ status: "anonymous" });
1100
+ return accessToken === void 0 ? Effect.void : Effect.tryPromise((signal) => fetch(new URL("/oauth/logout", tenantOrigin), {
1101
+ headers: { authorization: `Bearer ${accessToken}` },
1102
+ method: "POST",
1103
+ signal
1104
+ })).pipe(Effect.ignore);
1105
+ }),
1106
+ reauthorize,
1107
+ subscribe
1108
+ });
1109
+ });
1110
+ const parseExpiresAt = (value) => {
1111
+ if (typeof value === "string") {
1112
+ const parsed = Date.parse(value);
1113
+ return Number.isFinite(parsed) ? parsed : null;
1114
+ }
1115
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1116
+ return null;
1117
+ };
1118
+ const readString = (record, key) => {
1119
+ const candidate = record[key];
1120
+ return typeof candidate === "string" ? candidate : null;
1121
+ };
1122
+ const readStrings = (record, key) => {
1123
+ const candidate = record[key];
1124
+ if (!Array.isArray(candidate)) return null;
1125
+ const items = candidate;
1126
+ return items.every((item) => typeof item === "string") ? items : null;
1127
+ };
1128
+ const readKind = (record) => {
1129
+ const { kind } = record;
1130
+ return kind === "member" || kind === "external_app_user" ? kind : null;
1131
+ };
1132
+ const parseIdentity = (value) => {
1133
+ const identity = asRecord$1(asRecord$1(value)?.identity);
1134
+ if (identity === null) return null;
1135
+ const appId = readString(identity, "appId");
1136
+ const appPermissions = readStrings(identity, "appPermissions");
1137
+ const kind = readKind(identity);
1138
+ const organizationId = readString(identity, "organizationId");
1139
+ const roles = readStrings(identity, "roles");
1140
+ const userId = readString(identity, "userId");
1141
+ if (appId === null || appPermissions === null || kind === null || organizationId === null || roles === null || userId === null) return null;
1142
+ return {
1143
+ appId,
1144
+ appPermissions,
1145
+ email: readString(identity, "email"),
1146
+ kind,
1147
+ name: readString(identity, "name"),
1148
+ organizationId,
1149
+ roles,
1150
+ userId
1151
+ };
1152
+ };
1153
+ /**
1154
+ * The session of a sealed-cookie BFF; the access token never leaves the
1155
+ * server. A session that cannot be read is an `authorization_failed` error
1156
+ * state.
1157
+ */
1158
+ const makeServerSession = Effect.fnUntraced(function* makeServerSession(options) {
1159
+ const { basePath } = options;
1160
+ if (!/^\/[\w/-]+$/u.test(basePath) || basePath.endsWith("/")) return yield* configurationError("basePath must be an absolute path without a trailing slash");
1161
+ const fetch = options.fetch ?? globalThis.fetch;
1162
+ const origin = options.origin ?? "";
1163
+ const now = options.now ?? Date.now;
1164
+ const navigate = navigation(options.navigate);
1165
+ const { changes, getState, subscribe, transition } = makeState();
1166
+ const completion = makeCompletion();
1167
+ let rememberedReturnTo;
1168
+ const invalidSession = (message) => {
1169
+ transition({
1170
+ error: new FederatedAuthError("authorization_failed", message),
1171
+ status: "error"
1172
+ });
1173
+ };
1174
+ const refresh = Effect.fnUntraced(function* refresh() {
1175
+ const response = yield* Effect.tryPromise({
1176
+ catch: transportError,
1177
+ try: (signal) => fetch(`${origin}${basePath}/session`, {
1178
+ credentials: "same-origin",
1179
+ headers: { accept: "application/json" },
1180
+ signal
1181
+ })
1182
+ });
1183
+ if (response.status === 401) {
1184
+ transition({ status: "anonymous" });
1185
+ return;
1186
+ }
1187
+ if (!response.ok) {
1188
+ invalidSession("The application session could not be read");
1189
+ return;
1190
+ }
1191
+ const payload = yield* readJson(response);
1192
+ const record = asRecord$1(payload);
1193
+ const expiresAt = record === null ? null : parseExpiresAt(record.expiresAt);
1194
+ const identity = parseIdentity(payload);
1195
+ if (expiresAt === null || identity === null) {
1196
+ invalidSession("The application session is invalid");
1197
+ return;
1198
+ }
1199
+ transition(expiresAt <= now() ? { status: "expired" } : {
1200
+ expiresAt,
1201
+ identity,
1202
+ status: "authenticated"
1203
+ });
1204
+ });
1205
+ const beginLogin = ({ returnTo }) => Effect.suspend(() => {
1206
+ rememberedReturnTo = returnTo;
1207
+ const url = `${origin}${basePath}/login?returnTo=${encodeURIComponent(returnTo)}`;
1208
+ transition({ status: "redirecting" });
1209
+ return Effect.as(navigate(url), url);
1210
+ });
1211
+ return FederatedAuth.of({
1212
+ beginLogin,
1213
+ changes,
1214
+ completeLogin: () => completion.run(Effect.flatMap(refresh(), () => {
1215
+ const state = getState();
1216
+ return state.status === "error" ? Effect.fail(state.error) : Effect.succeed({ returnTo: rememberedReturnTo ?? "/" });
1217
+ })),
1218
+ getAccessToken: Effect.fail(new FederatedAuthError("reauthorization_required", "The CI access token stays on the application server")),
1219
+ getState,
1220
+ logout: Effect.suspend(() => {
1221
+ rememberedReturnTo = void 0;
1222
+ completion.reset();
1223
+ return Effect.tryPromise((signal) => fetch(`${origin}${basePath}/logout`, {
1224
+ credentials: "same-origin",
1225
+ method: "POST",
1226
+ signal
1227
+ })).pipe(Effect.ignore, Effect.andThen(Effect.sync(() => transition({ status: "anonymous" }))));
1228
+ }),
1229
+ reauthorize: (input) => Effect.suspend(() => {
1230
+ const returnTo = input?.returnTo ?? rememberedReturnTo;
1231
+ return returnTo === void 0 ? Effect.fail(new FederatedAuthError("reauthorization_required", "A same-origin return target is required to restart CI login")) : beginLogin({ returnTo });
1232
+ }),
1233
+ subscribe
1234
+ });
1235
+ });
1236
+ /** `FederatedAuth` of browser federated sign-in; a bad option fails with `configuration_error`. */
1237
+ const layerFederated = (options) => Layer.effect(FederatedAuth, makeFederated(options));
1238
+ /** `FederatedAuth` of a sealed-cookie BFF session; a bad option fails with `configuration_error`. */
1239
+ const layerServerSession = (options) => Layer.effect(FederatedAuth, makeServerSession(options));
1240
+ /** `layerFederated` with options that Effect `Config` reads. */
1241
+ const layerFederatedConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layerFederated));
1242
+ /** `layerServerSession` with options that Effect `Config` reads. */
1243
+ const layerServerSessionConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layerServerSession));
1244
+ /**
1245
+ * Fixed workflow invocation on the Effect Core: one POST to a Fixed workflow
1246
+ * route of the app's BFF, which admits one run. A refused or failed
1247
+ * invocation fails with `CiError`; a request that does not reach the BFF
1248
+ * fails with `CiTransportError`.
1249
+ */
1250
+ var FixedWorkflows = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/FixedWorkflows") {};
1251
+ const asRecord = (value) => {
1252
+ if (typeof value !== "object" || value === null) return null;
1253
+ return value;
1254
+ };
1255
+ const isCiErrorCode = (value) => ciErrorCodes.some((code) => code === value);
1256
+ /** The code of a refused route answer: the code that the body names, else the HTTP status. */
1257
+ const failureCode = (status, error) => {
1258
+ if (isCiErrorCode(error)) return error;
1259
+ const forwarded = asRecord(error)?.code;
1260
+ if (Predicate.isString(forwarded)) return backendErrorCode(forwarded);
1261
+ if (status === 401) return "unauthenticated";
1262
+ if (status === 403) return "forbidden";
1263
+ if (status === 404 || status === 405) return "not_found";
1264
+ if (status === 409) return "conflict";
1265
+ if (status === 429) return "rate_limited";
1266
+ if (status >= 500) return status === 500 ? "internal" : "unavailable";
1267
+ return "invalid_request";
1268
+ };
1269
+ const noRunId = "Fixed workflow did not return a run id";
1270
+ /**
1271
+ * The run id of a route answer, or the `CiError` of a refused one. The BFF
1272
+ * answers its own refusals with `{ error: "<code>" }` and forwards the error
1273
+ * envelope of CI.
1274
+ */
1275
+ const runIdOf = (response, payload) => {
1276
+ const record = asRecord(payload);
1277
+ const runId = record?.runId;
1278
+ if (response.ok && Predicate.isString(runId)) return Effect.succeed({ runId });
1279
+ if (response.ok) return Effect.fail(new CiError({
1280
+ code: "internal",
1281
+ message: noRunId,
1282
+ retryable: false
1283
+ }));
1284
+ const message = asRecord(record?.error)?.message;
1285
+ return Effect.fail(new CiError({
1286
+ code: failureCode(response.status, record?.error),
1287
+ message: Predicate.isString(message) ? message : noRunId,
1288
+ retryable: response.status === 429 || response.status >= 500
1289
+ }));
1290
+ };
1291
+ const make$1 = (options) => {
1292
+ const fetch = options.fetch ?? globalThis.fetch;
1293
+ return FixedWorkflows.of({ invoke: Effect.fnUntraced(function* invoke(request) {
1294
+ const idempotencyKey = globalThis.crypto.randomUUID();
1295
+ const body = JSON.stringify(request.body);
1296
+ const response = yield* Effect.tryPromise({
1297
+ catch: (cause) => new CiTransportError({ cause }),
1298
+ try: (signal) => fetch(request.url, {
1299
+ body,
1300
+ credentials: "same-origin",
1301
+ headers: {
1302
+ "content-type": "application/json",
1303
+ "x-idempotency-key": idempotencyKey
1304
+ },
1305
+ method: "POST",
1306
+ signal
1307
+ })
1308
+ });
1309
+ const payload = yield* Effect.promise(async () => {
1310
+ try {
1311
+ return await response.json();
1312
+ } catch {
1313
+ return null;
1314
+ }
1315
+ });
1316
+ return yield* runIdOf(response, payload);
1317
+ }) });
1318
+ };
1319
+ /** `FixedWorkflows` over the `fetch` of `options`. */
1320
+ const layer$1 = (options = {}) => Layer.sync(FixedWorkflows, () => make$1(options));
1321
+ /** `layer` with options that Effect `Config` reads. */
1322
+ const layerConfig$1 = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layer$1));
1323
+ /**
1324
+ * The delegated application runtime on the Effect Core: the session of a
1325
+ * sealed-cookie BFF, the CI client over the app's proxy and run follow, in
1326
+ * one context. `DelegatedRuntime` holds the state of one runtime with
1327
+ * synchronous listeners, so that the `.` facade keeps `getSnapshot` and
1328
+ * `subscribe`.
1329
+ */
1330
+ var DelegatedRuntime = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/DelegatedRuntime") {};
1331
+ const mapAuthState = (state) => {
1332
+ switch (state.status) {
1333
+ case "authenticated":
1334
+ if (state.identity === void 0) return {
1335
+ message: "The application session is invalid",
1336
+ status: "unavailable"
1337
+ };
1338
+ return {
1339
+ expiresAt: new Date(state.expiresAt).toISOString(),
1340
+ identity: state.identity,
1341
+ status: "authenticated"
1342
+ };
1343
+ case "expired": return { status: "expired" };
1344
+ case "error": return {
1345
+ message: state.error.message,
1346
+ status: "unavailable"
1347
+ };
1348
+ default: return { status: "anonymous" };
1349
+ }
1350
+ };
1351
+ /** The message of a failed session read; a transport failure names its cause. */
1352
+ const failureMessage = (error) => {
1353
+ if (error instanceof CiTransportError) return failureMessage(error.cause);
1354
+ return error instanceof Error && error.message !== "" ? error.message : "CI session verification is unavailable";
1355
+ };
1356
+ const resolvedPaths = (options) => ({
1357
+ authBasePath: options.authBasePath ?? "/api/auth",
1358
+ proxyPath: options.proxyPath ?? "/api"
1359
+ });
1360
+ const make = Effect.fnUntraced(function* make(options) {
1361
+ const auth = yield* FederatedAuth;
1362
+ const runs = yield* Runs;
1363
+ const { authBasePath } = resolvedPaths(options);
1364
+ const listeners = /* @__PURE__ */ new Set();
1365
+ let state = { status: "checking" };
1366
+ let generation = 0;
1367
+ const publish = (next) => {
1368
+ state = next;
1369
+ for (const notify of listeners) notify();
1370
+ };
1371
+ const refresh = Effect.suspend(() => {
1372
+ generation += 1;
1373
+ const current = generation;
1374
+ publish({ status: "checking" });
1375
+ return Effect.map(Effect.exit(auth.completeLogin(`${options.origin}${authBasePath}/callback`)), (exit) => {
1376
+ if (current !== generation) return;
1377
+ publish(Exit.isSuccess(exit) ? mapAuthState(auth.getState()) : {
1378
+ message: failureMessage(Cause.squash(exit.cause)),
1379
+ status: "unavailable"
1380
+ });
1381
+ });
1382
+ });
1383
+ const login = (returnTo) => Effect.suspend(() => {
1384
+ generation += 1;
1385
+ publish({ status: "anonymous" });
1386
+ return Effect.asVoid(auth.beginLogin({ returnTo }));
1387
+ });
1388
+ const subscribe = (notify) => {
1389
+ listeners.add(notify);
1390
+ return () => {
1391
+ listeners.delete(notify);
1392
+ };
1393
+ };
1394
+ return DelegatedRuntime.of({
1395
+ applicationId: options.applicationId,
1396
+ changes: Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => subscribe(() => {
1397
+ Queue.offerUnsafe(queue, state);
1398
+ })), (unsubscribe) => Effect.sync(unsubscribe))),
1399
+ followRun: (runId) => Effect.suspend(() => state.status === "authenticated" ? runs.follow({
1400
+ organizationId: state.identity.organizationId,
1401
+ runId
1402
+ }) : Effect.fail(new FederatedAuthError("reauthorization_required", "A CI session is required to follow a run"))),
1403
+ getSnapshot: () => state,
1404
+ initialize: (url) => Effect.andThen(refresh, () => state.status === "anonymous" || state.status === "expired" ? login(url) : Effect.void),
1405
+ login,
1406
+ logout: Effect.suspend(() => {
1407
+ generation += 1;
1408
+ return Effect.andThen(auth.logout, Effect.sync(() => publish({ status: "anonymous" })));
1409
+ }),
1410
+ refresh,
1411
+ subscribe
1412
+ });
1413
+ });
1414
+ /**
1415
+ * `DelegatedRuntime` for a sealed-cookie BFF, merged with its own
1416
+ * `FederatedAuth`, `CiClient` and `Runs`. A bad `authBasePath` fails with
1417
+ * `configuration_error`; a bad `origin` or `proxyPath` dies with `TypeError`.
1418
+ */
1419
+ const layer = (options) => {
1420
+ const fetch = options.fetch ?? globalThis.fetch;
1421
+ const { authBasePath, proxyPath } = resolvedPaths(options);
1422
+ return Layer.effect(DelegatedRuntime, make(options)).pipe(Layer.provideMerge(layer$2), Layer.provideMerge(layerProxy({
1423
+ authentication: {
1424
+ credentials: "same-origin",
1425
+ mode: "server_delegated"
1426
+ },
1427
+ fetch,
1428
+ path: proxyPath,
1429
+ serverUrl: options.origin
1430
+ })), Layer.provideMerge(layerServerSession({
1431
+ basePath: authBasePath,
1432
+ fetch,
1433
+ ...options.navigate && { navigate: options.navigate },
1434
+ origin: options.origin
1435
+ })));
1436
+ };
1437
+ /** `layer` with options that Effect `Config` reads. */
1438
+ const layerConfig = (config) => Layer.unwrap(Effect.map(Config.unwrap(config), layer));
1439
+ export { layerFromFactory as A, RealtimeClient as C, subscribe as D, makeConnection as E, currentLink as M, createFetchEventSourceFactory as N, realtimeTopicKey as O, make$3 as S, layerConfig$2 as T, layerDirect as _, layer$1 as a, layerProxy as b, layerFederated as c, layerServerSessionConfig as d, DEFAULT_FOLLOW_RUN_DEADLINE_MS as f, CiClient as g, layer$2 as h, FixedWorkflows as i, layerBrowser as j, layer$4 as k, layerFederatedConfig as l, followSource as m, layer as n, layerConfig$1 as o, Runs as p, layerConfig as r, FederatedAuth as s, DelegatedRuntime as t, layerServerSession as u, layerDirectConfig as v, layer$3 as w, layerProxyConfig as x, layerFromExecutor as y };