@collective-intelligence/external-apps-client-sdk 0.2.13 → 0.2.14
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.
- package/README.md +9 -3
- package/dist/effect.d.ts +6 -0
- package/dist/effect.js +1 -1
- package/dist/index.js +1 -1
- package/dist/{service-ZWwY3AJB.js → service-dVoDg4IP.js} +349 -148
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -337,6 +337,9 @@ const unsubscribe = realtime.subscribe(
|
|
|
337
337
|
back off with full jitter between 1 and 30 seconds; `Retry-After` and the
|
|
338
338
|
server's `retry:` set the lower bound. The server ends each connection after
|
|
339
339
|
its lifetime; the client reconnects with a new ticket.
|
|
340
|
+
- A 401 or 403 on the ticket, the stream or a grant renewal stops the
|
|
341
|
+
connection: its status is `idle`, and it asks no ticket until the topics
|
|
342
|
+
change, the page is shown or its visibility changes.
|
|
340
343
|
- The default stream reader uses `fetch`, because `EventSource` does not expose
|
|
341
344
|
the server's ping comments or a refused stream's status. Inject
|
|
342
345
|
`eventSourceFactory`, `document`, `window`, `timers` and `random` to test.
|
|
@@ -375,9 +378,9 @@ const unsubscribe = realtime.subscribe(
|
|
|
375
378
|
and tries again after 15 seconds, 30 seconds, then every 60 seconds, and
|
|
376
379
|
at least after the `Retry-After` of the refusal; after a renewal that
|
|
377
380
|
succeeds, the 8-minute cycle goes on. A retry that would come after the
|
|
378
|
-
token expires does not run: the
|
|
379
|
-
|
|
380
|
-
|
|
381
|
+
token expires does not run: the connection ends and reconnects with a new
|
|
382
|
+
ticket after the backoff, because the Revalidate Route refuses an expired
|
|
383
|
+
token. A renewal refused with 401 or 403 stops the connection. Without a
|
|
381
384
|
token in the ticket answer (a ticket route
|
|
382
385
|
without `secrets`) the client posts nothing. The resync after a cursorless
|
|
383
386
|
open posts nothing. A failed post logs a warning; `fetch` gets
|
|
@@ -427,6 +430,9 @@ Effect.runFork(
|
|
|
427
430
|
- `layerRealtimeClient({ ticketUrl, revalidateUrl })` posts to the Revalidate
|
|
428
431
|
Route as `createRealtimeClient` does; a relative `revalidateUrl` also
|
|
429
432
|
resolves against `location`.
|
|
433
|
+
- `onRefused` of `RealtimeClientLayerOptions` runs once when the server
|
|
434
|
+
refuses the ticket, the stream or a grant renewal with 401 or 403 and the
|
|
435
|
+
connection stops, for example to re-check the session.
|
|
430
436
|
- Timers use `Clock` and the jitter uses `Random`, so a test can use `TestClock`
|
|
431
437
|
and a fixed `Random`.
|
|
432
438
|
|
package/dist/effect.d.ts
CHANGED
|
@@ -64,6 +64,12 @@ type RealtimeClientLayerOptions = Readonly<{
|
|
|
64
64
|
* posted.
|
|
65
65
|
*/
|
|
66
66
|
revalidateUrl?: string;
|
|
67
|
+
/**
|
|
68
|
+
* The server refused the ticket, the stream or a grant renewal with 401 or
|
|
69
|
+
* 403. The connection stops and shows `"idle"`; it asks no ticket until the
|
|
70
|
+
* topics change, the page is shown or its visibility changes.
|
|
71
|
+
*/
|
|
72
|
+
onRefused?: () => void;
|
|
67
73
|
}>;
|
|
68
74
|
/** `RealtimeClient` with the `fetch` of `FetchHttpClient.Fetch` and the page of this runtime. */
|
|
69
75
|
declare const layer$2: (options: RealtimeClientLayerOptions) => Layer.Layer<RealtimeClient, never, never>;
|
package/dist/effect.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { D as CiTransportError, E as CiErrorCode, O as FederatedAuthError, T as CiError, a as layerConfig$3, c as layerLegacyConfig, f as makeEntityHttpExecute, i as layer$3, k as FederatedAuthErrorCode, n as Resources, o as layerFromEntityTransport, s as layerLegacy, t as LegacyResources } from "./service-DaANR0QD.js";
|
|
2
|
-
import { C as RealtimeClient, D as subscribe, T as layerConfig$2, _ as layerDirect, a as layer$1, b as layerProxy, c as layerFederated, d as layerServerSessionConfig, f as DEFAULT_FOLLOW_RUN_DEADLINE_MS, g as CiClient, h as layer$4, i as FixedWorkflows, l as layerFederatedConfig, n as layer, o as layerConfig$1, p as Runs, r as layerConfig, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, v as layerDirectConfig, w as layer$2, x as layerProxyConfig, y as layerFromExecutor } from "./service-
|
|
2
|
+
import { C as RealtimeClient, D as subscribe, T as layerConfig$2, _ as layerDirect, a as layer$1, b as layerProxy, c as layerFederated, d as layerServerSessionConfig, f as DEFAULT_FOLLOW_RUN_DEADLINE_MS, g as CiClient, h as layer$4, i as FixedWorkflows, l as layerFederatedConfig, n as layer, o as layerConfig$1, p as Runs, r as layerConfig, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, v as layerDirectConfig, w as layer$2, x as layerProxyConfig, y as layerFromExecutor } from "./service-dVoDg4IP.js";
|
|
3
3
|
import * as Schema from "effect/Schema";
|
|
4
4
|
/**
|
|
5
5
|
* The wire Schemas of the CI envelopes that `./effect` exports. The Type of
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { A as errors_exports, C as isClientOperationId, D as CiTransportError, O as FederatedAuthError, b as proxyHttpOptions, d as createEntityHttpTransport, g as isEntityReadLimitError, h as isEntityBatchRefusedError, m as createEntityProtocol, v as directHttpOptions, w as toCiResult, x as clientOperationIds, y as makeHttpExecute } from "./service-DaANR0QD.js";
|
|
2
|
-
import { A as layerFromFactory, E as makeConnection, M as currentLink, N as createFetchEventSourceFactory, O as realtimeTopicKey, S as make, a as layer$2, c as layerFederated, f as DEFAULT_FOLLOW_RUN_DEADLINE_MS, g as CiClient, h as layer, i as FixedWorkflows, j as layerBrowser, k as layer$3, m as followSource, n as layer$1, p as Runs, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, y as layerFromExecutor } from "./service-
|
|
2
|
+
import { A as layerFromFactory, E as makeConnection, M as currentLink, N as createFetchEventSourceFactory, O as realtimeTopicKey, S as make, a as layer$2, c as layerFederated, f as DEFAULT_FOLLOW_RUN_DEADLINE_MS, g as CiClient, h as layer, i as FixedWorkflows, j as layerBrowser, k as layer$3, m as followSource, n as layer$1, p as Runs, s as FederatedAuth, t as DelegatedRuntime, u as layerServerSession, y as layerFromExecutor } from "./service-dVoDg4IP.js";
|
|
3
3
|
import { t as createResourceClient } from "./resources-BedkrCzl.js";
|
|
4
4
|
import * as Clock from "effect/Clock";
|
|
5
5
|
import * as Context from "effect/Context";
|
|
@@ -24,6 +24,8 @@ import * as Random from "effect/Random";
|
|
|
24
24
|
import * as Schedule from "effect/Schedule";
|
|
25
25
|
import * as Stream from "effect/Stream";
|
|
26
26
|
import * as Deferred from "effect/Deferred";
|
|
27
|
+
import * as Data from "effect/Data";
|
|
28
|
+
import * as Equal from "effect/Equal";
|
|
27
29
|
import * as Exit from "effect/Exit";
|
|
28
30
|
const emptyBlock = () => ({
|
|
29
31
|
comment: false,
|
|
@@ -131,6 +133,7 @@ const backoffCapMilliseconds = 3e4;
|
|
|
131
133
|
const initialMachineState = (documentVisible) => ({
|
|
132
134
|
attempt: 0,
|
|
133
135
|
documentVisible,
|
|
136
|
+
grant: void 0,
|
|
134
137
|
lastEventId: void 0,
|
|
135
138
|
nextLinkId: 1,
|
|
136
139
|
pageShown: true,
|
|
@@ -146,6 +149,7 @@ const currentLink = (state) => "link" in state ? state.link : void 0;
|
|
|
146
149
|
const shared = (state) => ({
|
|
147
150
|
attempt: state.attempt,
|
|
148
151
|
documentVisible: state.documentVisible,
|
|
152
|
+
grant: state.grant,
|
|
149
153
|
lastEventId: state.lastEventId,
|
|
150
154
|
nextLinkId: state.nextLinkId,
|
|
151
155
|
pageShown: state.pageShown,
|
|
@@ -161,13 +165,20 @@ const unchanged = (state) => ({
|
|
|
161
165
|
/** Commands that end the current link, if any. */
|
|
162
166
|
const unlink = (state) => {
|
|
163
167
|
const link = currentLink(state);
|
|
164
|
-
return link === void 0 ? [] : [
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
168
|
+
return link === void 0 ? [] : [
|
|
169
|
+
{
|
|
170
|
+
linkId: link.id,
|
|
171
|
+
type: "disconnect"
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
timer: "watchdog",
|
|
175
|
+
type: "cancel"
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
timer: "grant_renewal",
|
|
179
|
+
type: "cancel"
|
|
180
|
+
}
|
|
181
|
+
];
|
|
171
182
|
};
|
|
172
183
|
const watchdog = (linkId) => ({
|
|
173
184
|
event: {
|
|
@@ -240,6 +251,33 @@ const retry = (state, retryMilliseconds) => {
|
|
|
240
251
|
}
|
|
241
252
|
};
|
|
242
253
|
};
|
|
254
|
+
/**
|
|
255
|
+
* The server refused the link (401 or 403): it ends, its grant goes, and the
|
|
256
|
+
* client calls `onRefused` once. The link stays `idle` and mints no ticket
|
|
257
|
+
* until a page event: a topic change, the page shown or a visibility change.
|
|
258
|
+
*/
|
|
259
|
+
const refuse = (state) => ({
|
|
260
|
+
commands: [...unlink(state), { type: "refused" }],
|
|
261
|
+
state: {
|
|
262
|
+
...shared(state),
|
|
263
|
+
grant: void 0,
|
|
264
|
+
phase: "idle"
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
/** Ends the link on `failure`: a refusal stops it, a retryable failure backs off. */
|
|
268
|
+
const fail = (state, failure, retryMilliseconds) => failure === "refused" ? refuse(state) : retry(state, retryMilliseconds);
|
|
269
|
+
/** Keeps `grant` and renews it before it expires, if there is one. */
|
|
270
|
+
const holdGrant = (state, link, grant) => ({
|
|
271
|
+
commands: grant === void 0 ? [] : [{
|
|
272
|
+
grant,
|
|
273
|
+
link,
|
|
274
|
+
type: "renewGrant"
|
|
275
|
+
}],
|
|
276
|
+
state: {
|
|
277
|
+
...state,
|
|
278
|
+
grant
|
|
279
|
+
}
|
|
280
|
+
});
|
|
243
281
|
/** Brings the connection in line with the page and the topic set. */
|
|
244
282
|
const sync = (state) => {
|
|
245
283
|
if (!wanted(state)) return stop(state);
|
|
@@ -310,16 +348,21 @@ const linkTransition = (state, event) => {
|
|
|
310
348
|
const link = currentLink(state);
|
|
311
349
|
if (link?.id !== event.linkId) return unchanged(state);
|
|
312
350
|
switch (event.type) {
|
|
313
|
-
case "ticketMinted":
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
351
|
+
case "ticketMinted": {
|
|
352
|
+
const held = holdGrant(state, link, event.grant);
|
|
353
|
+
return {
|
|
354
|
+
commands: [{
|
|
355
|
+
linkId: link.id,
|
|
356
|
+
type: "openStream",
|
|
357
|
+
url: streamUrlAfter(event.streamUrl, state.lastEventId)
|
|
358
|
+
}, ...held.commands],
|
|
359
|
+
state: held.state
|
|
360
|
+
};
|
|
361
|
+
}
|
|
321
362
|
case "ticketFailed":
|
|
322
|
-
case "streamEnded": return
|
|
363
|
+
case "streamEnded": return fail(state, event.failure, event.retryMilliseconds);
|
|
364
|
+
case "grantRenewed": return holdGrant(state, link, event.grant);
|
|
365
|
+
case "grantRenewalFailed": return fail(state, event.failure);
|
|
323
366
|
case "streamOpened": return {
|
|
324
367
|
commands: state.lastEventId === void 0 ? [watchdog(link.id), { type: "resync" }] : [watchdog(link.id)],
|
|
325
368
|
state: {
|
|
@@ -343,7 +386,7 @@ const linkTransition = (state, event) => {
|
|
|
343
386
|
default: return unchanged(state);
|
|
344
387
|
}
|
|
345
388
|
};
|
|
346
|
-
const transition = (state, event) => "linkId" in event ? linkTransition(state, event) : clientTransition(state, event);
|
|
389
|
+
const transition$1 = (state, event) => "linkId" in event ? linkTransition(state, event) : clientTransition(state, event);
|
|
347
390
|
/**
|
|
348
391
|
* The page lifecycle that the realtime connection follows: it connects only
|
|
349
392
|
* while the document is visible and the page is shown. The browser layer
|
|
@@ -462,17 +505,26 @@ const revalidateWaitMilliseconds = 1e3;
|
|
|
462
505
|
const grantLifetimeMilliseconds = 6e5;
|
|
463
506
|
/** The wait from a grant token to its renewal: the tab renews it 2 minutes before it expires (Q108). */
|
|
464
507
|
const grantRenewalMilliseconds = 48e4;
|
|
508
|
+
/** A 401 or a 403 refuses the link; every other failure is retryable. */
|
|
509
|
+
const failureOfStatus = (status) => status === 401 || status === 403 ? "refused" : "retryable";
|
|
510
|
+
const failureOf = (error) => error._tag === "HttpClientError" ? failureOfStatus(error.response?.status) : "retryable";
|
|
465
511
|
/**
|
|
466
512
|
* The waits after a failed renewal: 15 s, 30 s, then 60 s each time, and at
|
|
467
|
-
* least the `Retry-After` of the
|
|
468
|
-
* the expiry of
|
|
513
|
+
* least the `Retry-After` of the failure. A retry that would come at or after
|
|
514
|
+
* the expiry of `grant` does not run (Q108), and a refusal is not retried.
|
|
469
515
|
*/
|
|
470
|
-
const grantRetry = (
|
|
516
|
+
const grantRetry = (grant) => Schedule.min([Schedule.exponential("15 seconds"), Schedule.spaced("1 minute")]).pipe(Schedule.modifyDelay(({ duration, input }) => Effect.succeed(input._tag === "HttpClientError" ? Duration.max(duration, Duration.millis(retryAfterMilliseconds(input.response?.headers["retry-after"]) ?? 0)) : duration)), Schedule.while(({ duration, input, now }) => failureOf(input) === "retryable" && now + Duration.toMillis(duration) < grant.expiresAt));
|
|
471
517
|
/** The least wait before a delivery: a burst of changes joins one delivery. */
|
|
472
518
|
const changeWindowMilliseconds = 250;
|
|
473
519
|
/** The random extra wait, so that the tabs of many users refetch apart. */
|
|
474
520
|
const changeJitterMilliseconds = 750;
|
|
475
521
|
const resyncUpdate = { op: "resync" };
|
|
522
|
+
const nothingWaiting = () => ({
|
|
523
|
+
changes: /* @__PURE__ */ new Map(),
|
|
524
|
+
reset: false,
|
|
525
|
+
resync: false,
|
|
526
|
+
revalidations: /* @__PURE__ */ new Map()
|
|
527
|
+
});
|
|
476
528
|
const register = (listeners, listener) => {
|
|
477
529
|
const own = () => listener();
|
|
478
530
|
listeners.add(own);
|
|
@@ -485,6 +537,7 @@ const scoped = (listen) => Effect.acquireRelease(Effect.sync(listen), (unlisten)
|
|
|
485
537
|
/** The `ticketFailed` of `link`, after a warning with the failure. */
|
|
486
538
|
const failed = (link, error, retryMilliseconds) => {
|
|
487
539
|
const event = {
|
|
540
|
+
failure: failureOf(error),
|
|
488
541
|
linkId: link.id,
|
|
489
542
|
retryMilliseconds,
|
|
490
543
|
type: "ticketFailed"
|
|
@@ -508,20 +561,11 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
508
561
|
const links = yield* FiberMap.make();
|
|
509
562
|
const delivery = yield* FiberHandle.make();
|
|
510
563
|
const revalidatePosts = yield* FiberSet.make();
|
|
511
|
-
/** The grant renewal of the current link. */
|
|
512
|
-
const renewal = yield* FiberHandle.make();
|
|
513
564
|
const closed = yield* Latch.make();
|
|
514
565
|
const registrations = /* @__PURE__ */ new Map();
|
|
515
566
|
const resyncListeners = /* @__PURE__ */ new Set();
|
|
516
567
|
const accessListeners = /* @__PURE__ */ new Set();
|
|
517
|
-
|
|
518
|
-
const pending = /* @__PURE__ */ new Map();
|
|
519
|
-
let resyncPending = false;
|
|
520
|
-
/** The grant of the last ticket: this tab's own token, in memory only. */
|
|
521
|
-
let grant;
|
|
522
|
-
/** Per topic key and record id, the changes to revalidate, by last arrival. */
|
|
523
|
-
const revalidations = /* @__PURE__ */ new Map();
|
|
524
|
-
let revalidateReset = false;
|
|
568
|
+
let waiting = nothingWaiting();
|
|
525
569
|
let machine = initialMachineState(yield* page.visible);
|
|
526
570
|
const send = (event) => Queue.offer(events, event);
|
|
527
571
|
const topicsChanged = () => {
|
|
@@ -539,13 +583,12 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
539
583
|
* The Revalidate Route refuses an expired token, so the client does not
|
|
540
584
|
* post it, and the listeners do not wait.
|
|
541
585
|
*/
|
|
542
|
-
const postRevalidation = Clock.clockWith((clock) => {
|
|
586
|
+
const postRevalidation = (taken) => Clock.clockWith((clock) => {
|
|
543
587
|
const now = clock.currentTimeMillisUnsafe();
|
|
544
588
|
const { revalidateUrl } = options;
|
|
545
|
-
const
|
|
546
|
-
const
|
|
547
|
-
|
|
548
|
-
revalidateReset = false;
|
|
589
|
+
const { grant } = machine;
|
|
590
|
+
const changes = [...taken.revalidations.values()];
|
|
591
|
+
const { reset } = taken;
|
|
549
592
|
if (revalidateUrl === void 0 || grant === void 0 || grant.expiresAt <= now || changes.length === 0 && !reset) return Effect.void;
|
|
550
593
|
const { token } = grant;
|
|
551
594
|
const parts = changes.length === 0 ? [changes] : Arr.chunksOf(changes, revalidateMaxChanges);
|
|
@@ -566,23 +609,21 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
566
609
|
* reads through the server cache then reads the revalidated entry.
|
|
567
610
|
*/
|
|
568
611
|
const deliver = Effect.suspend(() => {
|
|
569
|
-
const
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
return postRevalidation.pipe(Effect.andThen(Effect.sync(() => {
|
|
574
|
-
if (resynced) {
|
|
612
|
+
const taken = waiting;
|
|
613
|
+
waiting = nothingWaiting();
|
|
614
|
+
return postRevalidation(taken).pipe(Effect.andThen(Effect.sync(() => {
|
|
615
|
+
if (taken.resync) {
|
|
575
616
|
for (const onResync of resyncListeners) onResync();
|
|
576
617
|
return;
|
|
577
618
|
}
|
|
578
|
-
for (const [key, changes] of
|
|
619
|
+
for (const [key, changes] of taken.changes) {
|
|
579
620
|
const batch = [...changes.values()];
|
|
580
621
|
for (const onChanges of registrations.get(key)?.listeners ?? []) onChanges(batch);
|
|
581
622
|
}
|
|
582
623
|
})));
|
|
583
624
|
});
|
|
584
625
|
/** Whether a change, a Resync or a revalidation waits for a delivery. */
|
|
585
|
-
const deliveryPending = () =>
|
|
626
|
+
const deliveryPending = () => waiting.changes.size > 0 || waiting.resync || waiting.revalidations.size > 0 || waiting.reset;
|
|
586
627
|
/**
|
|
587
628
|
* The first change or Resync after a delivery schedules the next one; later
|
|
588
629
|
* ones join it without delaying it. What arrives while a delivery waits
|
|
@@ -595,26 +636,26 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
595
636
|
*/
|
|
596
637
|
const resync = Effect.suspend(() => {
|
|
597
638
|
if (resyncListeners.size === 0) return Effect.void;
|
|
598
|
-
|
|
639
|
+
waiting.resync = true;
|
|
599
640
|
return scheduleDelivery;
|
|
600
641
|
});
|
|
601
642
|
/** A `reset` or `access-changed` event: revalidate every topic of the token. */
|
|
602
643
|
const revalidateAll = Effect.suspend(() => {
|
|
603
644
|
if (options.revalidateUrl === void 0) return Effect.void;
|
|
604
|
-
|
|
645
|
+
waiting.reset = true;
|
|
605
646
|
return scheduleDelivery;
|
|
606
647
|
});
|
|
607
648
|
const route = (change) => Effect.suspend(() => {
|
|
608
649
|
const key = realtimeTopicKey(change.topic);
|
|
609
650
|
if (!registrations.has(key)) return Effect.void;
|
|
610
|
-
const changes =
|
|
651
|
+
const changes = waiting.changes.get(key) ?? /* @__PURE__ */ new Map();
|
|
611
652
|
changes.delete(change.id);
|
|
612
653
|
changes.set(change.id, change);
|
|
613
|
-
|
|
654
|
+
waiting.changes.set(key, changes);
|
|
614
655
|
if (options.revalidateUrl !== void 0) {
|
|
615
656
|
const revalidated = JSON.stringify([key, change.id]);
|
|
616
|
-
revalidations.delete(revalidated);
|
|
617
|
-
revalidations.set(revalidated, {
|
|
657
|
+
waiting.revalidations.delete(revalidated);
|
|
658
|
+
waiting.revalidations.set(revalidated, {
|
|
618
659
|
id: change.id,
|
|
619
660
|
topic: change.topic
|
|
620
661
|
});
|
|
@@ -651,6 +692,7 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
651
692
|
type: "received"
|
|
652
693
|
});
|
|
653
694
|
case "end": return send({
|
|
695
|
+
failure: failureOfStatus(item.end.status),
|
|
654
696
|
linkId,
|
|
655
697
|
retryMilliseconds: item.end.retryMilliseconds,
|
|
656
698
|
type: "streamEnded"
|
|
@@ -670,13 +712,14 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
670
712
|
* The stream URL of a ticket for `link`, and the grant of its token. The
|
|
671
713
|
* ticket route seals the token after the request starts, so the token is
|
|
672
714
|
* valid at least until 10 minutes after that start, on the clock of the
|
|
673
|
-
* tab.
|
|
715
|
+
* tab. Only the Revalidate Route reads the token, so without
|
|
716
|
+
* `revalidateUrl` there is no grant.
|
|
674
717
|
*/
|
|
675
718
|
const requestGrant = Effect.fnUntraced(function* requestGrant(link) {
|
|
676
719
|
const requestedAt = yield* Clock.currentTimeMillis;
|
|
677
720
|
const { grantToken, streamUrl } = yield* requestTicket(link);
|
|
678
721
|
return {
|
|
679
|
-
grant: grantToken === void 0 ? void 0 : {
|
|
722
|
+
grant: grantToken === void 0 || options.revalidateUrl === void 0 ? void 0 : {
|
|
680
723
|
expiresAt: requestedAt + grantLifetimeMilliseconds,
|
|
681
724
|
token: grantToken
|
|
682
725
|
},
|
|
@@ -684,31 +727,30 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
684
727
|
};
|
|
685
728
|
});
|
|
686
729
|
/**
|
|
687
|
-
* Renews
|
|
730
|
+
* Renews `grant` of `link` 8 minutes after it: a new ticket for its topics
|
|
688
731
|
* brings a new token, which takes the place of the old one when it
|
|
689
732
|
* arrives (Q108). The stream stays open, and the ticket goes unused. A
|
|
690
|
-
* failed renewal
|
|
733
|
+
* failed renewal tries again after the waits of `grantRetry`. When no try
|
|
734
|
+
* is left before the token expires, or the server refuses it, the machine
|
|
735
|
+
* gets `grantRenewalFailed` and ends the link.
|
|
691
736
|
*/
|
|
692
|
-
const renewGrant = Effect.fn("RealtimeClient.renewGrant")(function* renewGrant(link) {
|
|
693
|
-
const
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
message: "The realtime grant renewal stopped: the grant token expires before the next try"
|
|
705
|
-
}), surfaceDefects("The realtime grant renewal failed with a defect", { linkId: link.id }));
|
|
737
|
+
const renewGrant = Effect.fn("RealtimeClient.renewGrant")(function* renewGrant(link, grant) {
|
|
738
|
+
const renewal = yield* requestGrant(link).pipe(Effect.tapError((cause) => Effect.logWarning("The realtime grant renewal failed", cause)), Effect.retry(grantRetry(grant)), Effect.delay(grantRenewalMilliseconds), Effect.result);
|
|
739
|
+
return renewal._tag === "Success" ? {
|
|
740
|
+
grant: renewal.success.grant,
|
|
741
|
+
linkId: link.id,
|
|
742
|
+
type: "grantRenewed"
|
|
743
|
+
} : {
|
|
744
|
+
failure: failureOf(renewal.failure),
|
|
745
|
+
linkId: link.id,
|
|
746
|
+
type: "grantRenewalFailed"
|
|
747
|
+
};
|
|
748
|
+
});
|
|
706
749
|
/** Mints the ticket of `link`; a failed ticket waits at least its `Retry-After`. */
|
|
707
750
|
const ticket = Effect.fn("RealtimeClient.ticket")(function* ticket(link) {
|
|
708
|
-
const { grant
|
|
709
|
-
grant = renewed;
|
|
710
|
-
if (options.revalidateUrl !== void 0 && grant !== void 0) yield* FiberHandle.run(renewal, renewGrants(link));
|
|
751
|
+
const { grant, streamUrl } = yield* requestGrant(link);
|
|
711
752
|
return {
|
|
753
|
+
grant,
|
|
712
754
|
linkId: link.id,
|
|
713
755
|
streamUrl,
|
|
714
756
|
type: "ticketMinted"
|
|
@@ -726,6 +768,7 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
726
768
|
case "mint": {
|
|
727
769
|
const linkId = command.link.id;
|
|
728
770
|
return FiberMap.run(links, linkId, ticket(command.link).pipe(Effect.flatMap(send), surfaceDefects("The realtime ticket request failed with a defect", { linkId }, send({
|
|
771
|
+
failure: "retryable",
|
|
729
772
|
linkId,
|
|
730
773
|
retryMilliseconds: void 0,
|
|
731
774
|
type: "ticketFailed"
|
|
@@ -734,18 +777,28 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
734
777
|
case "openStream": {
|
|
735
778
|
const { linkId } = command;
|
|
736
779
|
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({
|
|
780
|
+
failure: "retryable",
|
|
737
781
|
linkId,
|
|
738
782
|
retryMilliseconds: void 0,
|
|
739
783
|
type: "streamEnded"
|
|
740
784
|
}))));
|
|
741
785
|
}
|
|
742
|
-
case "disconnect": return FiberMap.remove(links, command.linkId)
|
|
786
|
+
case "disconnect": return FiberMap.remove(links, command.linkId);
|
|
743
787
|
case "resync": return resync;
|
|
788
|
+
case "renewGrant": {
|
|
789
|
+
const linkId = command.link.id;
|
|
790
|
+
return FiberMap.run(timers, "grant_renewal", renewGrant(command.link, command.grant).pipe(Effect.flatMap(send), surfaceDefects("The realtime grant renewal failed with a defect", { linkId }, send({
|
|
791
|
+
failure: "retryable",
|
|
792
|
+
linkId,
|
|
793
|
+
type: "grantRenewalFailed"
|
|
794
|
+
}))));
|
|
795
|
+
}
|
|
796
|
+
case "refused": return Effect.sync(() => options.onRefused?.());
|
|
744
797
|
default: return Effect.void;
|
|
745
798
|
}
|
|
746
799
|
};
|
|
747
800
|
const apply = Effect.fnUntraced(function* apply(event) {
|
|
748
|
-
const next = transition(machine, event);
|
|
801
|
+
const next = transition$1(machine, event);
|
|
749
802
|
machine = next.state;
|
|
750
803
|
for (const command of next.commands) yield* run(command);
|
|
751
804
|
});
|
|
@@ -762,11 +815,8 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
762
815
|
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 }));
|
|
763
816
|
yield* page.events.pipe(Stream.runForEach(send), Effect.forkScoped({ startImmediately: true }));
|
|
764
817
|
yield* Effect.addFinalizer(() => Effect.sync(() => {
|
|
765
|
-
machine = transition(machine, { type: "close" }).state;
|
|
766
|
-
|
|
767
|
-
resyncPending = false;
|
|
768
|
-
revalidations.clear();
|
|
769
|
-
revalidateReset = false;
|
|
818
|
+
machine = transition$1(machine, { type: "close" }).state;
|
|
819
|
+
waiting = nothingWaiting();
|
|
770
820
|
}).pipe(Effect.andThen(closed.open)));
|
|
771
821
|
return {
|
|
772
822
|
closed: closed.await,
|
|
@@ -786,7 +836,7 @@ const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* make
|
|
|
786
836
|
if (!registration.listeners.delete(listener)) return;
|
|
787
837
|
if (registration.listeners.size === 0) {
|
|
788
838
|
registrations.delete(key);
|
|
789
|
-
|
|
839
|
+
waiting.changes.delete(key);
|
|
790
840
|
topicsChanged();
|
|
791
841
|
}
|
|
792
842
|
};
|
|
@@ -986,6 +1036,68 @@ const createPkcePair = async (crypto = globalThis.crypto) => {
|
|
|
986
1036
|
verifier
|
|
987
1037
|
};
|
|
988
1038
|
};
|
|
1039
|
+
/**
|
|
1040
|
+
* Internal. The client SDK Session of one `FederatedAuth`: one tagged enum,
|
|
1041
|
+
* the pure `transition` that the store applies to its value
|
|
1042
|
+
* `{ epoch, session }`, and `toPublicState`, the public projection. The access
|
|
1043
|
+
* token is a field of `Authenticated`, so no other state holds one.
|
|
1044
|
+
*/
|
|
1045
|
+
const SessionEnum = Data.taggedEnum();
|
|
1046
|
+
const matchSession = SessionEnum.$match;
|
|
1047
|
+
const { Anonymous, Authenticated, Expired, Failed, Redirecting } = SessionEnum;
|
|
1048
|
+
const SessionEventEnum = Data.taggedEnum();
|
|
1049
|
+
const matchSessionEvent = SessionEventEnum.$match;
|
|
1050
|
+
const { LoggedOut, LoginStarted, Settled, TokenExpired } = SessionEventEnum;
|
|
1051
|
+
const initialSessionValue = {
|
|
1052
|
+
epoch: 0,
|
|
1053
|
+
session: Anonymous()
|
|
1054
|
+
};
|
|
1055
|
+
/**
|
|
1056
|
+
* The next value; `value` itself when the event changes nothing. The epoch
|
|
1057
|
+
* check is here: a `Settled` result of an older epoch changes nothing.
|
|
1058
|
+
*/
|
|
1059
|
+
const transition = (value, event) => {
|
|
1060
|
+
const next = matchSessionEvent(event, {
|
|
1061
|
+
LoggedOut: () => ({
|
|
1062
|
+
epoch: value.epoch + 1,
|
|
1063
|
+
session: Anonymous()
|
|
1064
|
+
}),
|
|
1065
|
+
LoginStarted: () => ({
|
|
1066
|
+
epoch: value.epoch,
|
|
1067
|
+
session: Redirecting()
|
|
1068
|
+
}),
|
|
1069
|
+
Settled: ({ epoch, session }) => epoch === value.epoch ? {
|
|
1070
|
+
epoch,
|
|
1071
|
+
session
|
|
1072
|
+
} : value,
|
|
1073
|
+
TokenExpired: () => value.session._tag === "Authenticated" ? {
|
|
1074
|
+
epoch: value.epoch,
|
|
1075
|
+
session: Expired()
|
|
1076
|
+
} : value
|
|
1077
|
+
});
|
|
1078
|
+
if (!Equal.equals(next.session, value.session)) return next;
|
|
1079
|
+
return next.epoch === value.epoch ? value : {
|
|
1080
|
+
epoch: next.epoch,
|
|
1081
|
+
session: value.session
|
|
1082
|
+
};
|
|
1083
|
+
};
|
|
1084
|
+
const toPublicState = (session) => matchSession(session, {
|
|
1085
|
+
Anonymous: () => ({ status: "anonymous" }),
|
|
1086
|
+
Authenticated: ({ expiresAt, identity }) => identity === null ? {
|
|
1087
|
+
expiresAt,
|
|
1088
|
+
status: "authenticated"
|
|
1089
|
+
} : {
|
|
1090
|
+
expiresAt,
|
|
1091
|
+
identity,
|
|
1092
|
+
status: "authenticated"
|
|
1093
|
+
},
|
|
1094
|
+
Expired: () => ({ status: "expired" }),
|
|
1095
|
+
Failed: ({ error }) => ({
|
|
1096
|
+
error,
|
|
1097
|
+
status: "error"
|
|
1098
|
+
}),
|
|
1099
|
+
Redirecting: () => ({ status: "redirecting" })
|
|
1100
|
+
});
|
|
989
1101
|
var FederatedAuth = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/FederatedAuth") {};
|
|
990
1102
|
const configurationError = (message) => new FederatedAuthError("configuration_error", message);
|
|
991
1103
|
const transportError = (cause) => new CiTransportError({ cause });
|
|
@@ -1007,26 +1119,55 @@ const navigation = (navigate) => {
|
|
|
1007
1119
|
return Effect.void;
|
|
1008
1120
|
});
|
|
1009
1121
|
};
|
|
1010
|
-
/**
|
|
1122
|
+
/**
|
|
1123
|
+
* The synchronous store of one Session: one value `{ epoch, session }` that
|
|
1124
|
+
* only `dispatch` changes. `dispatch` assigns the next value, then notifies
|
|
1125
|
+
* when the Session changed, so a listener reads the new state. A dispatch
|
|
1126
|
+
* that a listener makes is applied after the current notification ends. A
|
|
1127
|
+
* listener that throws stops no other listener and no queued change; the
|
|
1128
|
+
* first error is thrown when the queue is empty.
|
|
1129
|
+
*/
|
|
1011
1130
|
const makeState = () => {
|
|
1012
1131
|
const listeners = /* @__PURE__ */ new Set();
|
|
1013
|
-
let
|
|
1132
|
+
let value = initialSessionValue;
|
|
1133
|
+
let state = toPublicState(value.session);
|
|
1134
|
+
const queued = [];
|
|
1135
|
+
let notifying = false;
|
|
1014
1136
|
const subscribe = (listener) => {
|
|
1015
1137
|
listeners.add(listener);
|
|
1016
1138
|
return () => {
|
|
1017
1139
|
listeners.delete(listener);
|
|
1018
1140
|
};
|
|
1019
1141
|
};
|
|
1142
|
+
const dispatch = (event) => {
|
|
1143
|
+
queued.push(event);
|
|
1144
|
+
if (notifying) return;
|
|
1145
|
+
notifying = true;
|
|
1146
|
+
const failures = [];
|
|
1147
|
+
for (let next = queued.shift(); next !== void 0; next = queued.shift()) {
|
|
1148
|
+
const previous = value;
|
|
1149
|
+
value = transition(previous, next);
|
|
1150
|
+
if (value.session === previous.session) continue;
|
|
1151
|
+
state = toPublicState(value.session);
|
|
1152
|
+
for (const listener of listeners) try {
|
|
1153
|
+
listener(state);
|
|
1154
|
+
} catch (error) {
|
|
1155
|
+
failures.push(error);
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
notifying = false;
|
|
1159
|
+
if (failures.length > 0) throw failures[0];
|
|
1160
|
+
};
|
|
1020
1161
|
return {
|
|
1021
1162
|
changes: Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => subscribe((next) => {
|
|
1022
1163
|
Queue.offerUnsafe(queue, next);
|
|
1023
1164
|
})), (unsubscribe) => Effect.sync(unsubscribe))),
|
|
1165
|
+
dispatch,
|
|
1166
|
+
/** The epoch that a code exchange or a session read starts under. */
|
|
1167
|
+
epoch: () => value.epoch,
|
|
1024
1168
|
getState: () => state,
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
state = next;
|
|
1028
|
-
for (const listener of listeners) listener(next);
|
|
1029
|
-
}
|
|
1169
|
+
session: () => value.session,
|
|
1170
|
+
subscribe
|
|
1030
1171
|
};
|
|
1031
1172
|
};
|
|
1032
1173
|
/**
|
|
@@ -1113,18 +1254,9 @@ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
|
|
|
1113
1254
|
if (options.clientId.length === 0) return yield* configurationError("clientId is required");
|
|
1114
1255
|
if (crypto === void 0 || storage === void 0 || fetch === void 0) return yield* configurationError("Browser crypto, fetch, and sessionStorage are required");
|
|
1115
1256
|
const storageKey = `ci:federated-auth:${redirectUri.origin}:${options.clientId}`;
|
|
1116
|
-
const { changes, getState,
|
|
1257
|
+
const { changes, dispatch, epoch, getState, session, subscribe } = makeState();
|
|
1117
1258
|
const completion = makeCompletion();
|
|
1118
|
-
let token;
|
|
1119
1259
|
let rememberedReturnTo;
|
|
1120
|
-
const fail = (error) => Effect.suspend(() => {
|
|
1121
|
-
token = void 0;
|
|
1122
|
-
transition({
|
|
1123
|
-
error,
|
|
1124
|
-
status: "error"
|
|
1125
|
-
});
|
|
1126
|
-
return Effect.fail(error);
|
|
1127
|
-
});
|
|
1128
1260
|
const normalizedReturnTarget = (value) => Effect.suspend(() => {
|
|
1129
1261
|
if (value.length > maxReturnTargetLength) return Effect.fail(new FederatedAuthError("invalid_return_target", "The return target is too long"));
|
|
1130
1262
|
const target = new URL(value, redirectUri.origin);
|
|
@@ -1148,13 +1280,20 @@ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
|
|
|
1148
1280
|
authorizationUrl.searchParams.set("state", transaction.state);
|
|
1149
1281
|
authorizationUrl.searchParams.set("code_challenge", pkce.challenge);
|
|
1150
1282
|
authorizationUrl.searchParams.set("code_challenge_method", pkce.method);
|
|
1151
|
-
token = void 0;
|
|
1152
1283
|
completion.reset();
|
|
1153
|
-
|
|
1284
|
+
dispatch(LoginStarted());
|
|
1154
1285
|
yield* navigate(authorizationUrl.href);
|
|
1155
1286
|
return authorizationUrl.href;
|
|
1156
1287
|
});
|
|
1157
1288
|
const complete = Effect.fnUntraced(function* complete(callbackUrl) {
|
|
1289
|
+
const started = epoch();
|
|
1290
|
+
const fail = (error) => Effect.suspend(() => {
|
|
1291
|
+
dispatch(Settled({
|
|
1292
|
+
epoch: started,
|
|
1293
|
+
session: Failed({ error })
|
|
1294
|
+
}));
|
|
1295
|
+
return Effect.fail(error);
|
|
1296
|
+
});
|
|
1158
1297
|
const callback = absoluteUrl(callbackUrl);
|
|
1159
1298
|
if (callback === null) {
|
|
1160
1299
|
storage.removeItem(storageKey);
|
|
@@ -1193,11 +1332,13 @@ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
|
|
|
1193
1332
|
if (!response.ok) return yield* fail(new FederatedAuthError("token_exchange_failed", "The authorization code exchange failed"));
|
|
1194
1333
|
const exchanged = parseToken(yield* readJson(response), now());
|
|
1195
1334
|
if (exchanged === null) return yield* fail(new FederatedAuthError("token_exchange_failed", "The authorization server returned an invalid token"));
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1335
|
+
dispatch(Settled({
|
|
1336
|
+
epoch: started,
|
|
1337
|
+
session: Authenticated({
|
|
1338
|
+
...exchanged,
|
|
1339
|
+
identity: null
|
|
1340
|
+
})
|
|
1341
|
+
}));
|
|
1201
1342
|
rememberedReturnTo = transaction.returnTo;
|
|
1202
1343
|
return { returnTo: transaction.returnTo };
|
|
1203
1344
|
});
|
|
@@ -1210,22 +1351,23 @@ const makeFederated = Effect.fnUntraced(function* makeFederated(options) {
|
|
|
1210
1351
|
changes,
|
|
1211
1352
|
completeLogin: (callbackUrl) => completion.run(complete(callbackUrl)),
|
|
1212
1353
|
getAccessToken: Effect.suspend(() => {
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1354
|
+
const current = session();
|
|
1355
|
+
if (current._tag !== "Authenticated" || current.accessToken === null) return Effect.fail(loginRequired());
|
|
1356
|
+
if (current.expiresAt <= now()) {
|
|
1357
|
+
dispatch(TokenExpired());
|
|
1358
|
+
return Effect.fail(loginRequired());
|
|
1217
1359
|
}
|
|
1218
|
-
return
|
|
1360
|
+
return Effect.succeed(current.accessToken);
|
|
1219
1361
|
}),
|
|
1220
1362
|
getState,
|
|
1221
1363
|
logout: Effect.suspend(() => {
|
|
1222
|
-
const
|
|
1223
|
-
|
|
1364
|
+
const current = session();
|
|
1365
|
+
const accessToken = current._tag === "Authenticated" ? current.accessToken : null;
|
|
1224
1366
|
completion.reset();
|
|
1225
1367
|
rememberedReturnTo = void 0;
|
|
1226
1368
|
storage.removeItem(storageKey);
|
|
1227
|
-
|
|
1228
|
-
return accessToken ===
|
|
1369
|
+
dispatch(LoggedOut());
|
|
1370
|
+
return accessToken === null ? Effect.void : Effect.tryPromise((signal) => fetch(new URL("/oauth/logout", tenantOrigin), {
|
|
1229
1371
|
headers: { authorization: `Bearer ${accessToken}` },
|
|
1230
1372
|
method: "POST",
|
|
1231
1373
|
signal
|
|
@@ -1281,16 +1423,20 @@ const makeServerSession = Effect.fnUntraced(function* makeServerSession(options)
|
|
|
1281
1423
|
const origin = options.origin ?? "";
|
|
1282
1424
|
const now = options.now ?? Date.now;
|
|
1283
1425
|
const navigate = navigation(options.navigate);
|
|
1284
|
-
const { changes, getState, subscribe
|
|
1426
|
+
const { changes, dispatch, epoch, getState, subscribe } = makeState();
|
|
1285
1427
|
const completion = makeCompletion();
|
|
1286
1428
|
let rememberedReturnTo;
|
|
1287
|
-
const invalidSession = (message) => {
|
|
1288
|
-
transition({
|
|
1289
|
-
error: new FederatedAuthError("authorization_failed", message),
|
|
1290
|
-
status: "error"
|
|
1291
|
-
});
|
|
1292
|
-
};
|
|
1293
1429
|
const refresh = Effect.fnUntraced(function* refresh() {
|
|
1430
|
+
const started = epoch();
|
|
1431
|
+
const settle = (session) => {
|
|
1432
|
+
dispatch(Settled({
|
|
1433
|
+
epoch: started,
|
|
1434
|
+
session
|
|
1435
|
+
}));
|
|
1436
|
+
};
|
|
1437
|
+
const invalidSession = (message) => {
|
|
1438
|
+
settle(Failed({ error: new FederatedAuthError("authorization_failed", message) }));
|
|
1439
|
+
};
|
|
1294
1440
|
const response = yield* Effect.tryPromise({
|
|
1295
1441
|
catch: transportError,
|
|
1296
1442
|
try: (signal) => fetch(`${origin}${basePath}/session`, {
|
|
@@ -1300,7 +1446,7 @@ const makeServerSession = Effect.fnUntraced(function* makeServerSession(options)
|
|
|
1300
1446
|
})
|
|
1301
1447
|
});
|
|
1302
1448
|
if (response.status === 401) {
|
|
1303
|
-
|
|
1449
|
+
settle(Anonymous());
|
|
1304
1450
|
return;
|
|
1305
1451
|
}
|
|
1306
1452
|
if (!response.ok) {
|
|
@@ -1315,16 +1461,16 @@ const makeServerSession = Effect.fnUntraced(function* makeServerSession(options)
|
|
|
1315
1461
|
invalidSession("The application session is invalid");
|
|
1316
1462
|
return;
|
|
1317
1463
|
}
|
|
1318
|
-
|
|
1464
|
+
settle(expiresAt <= now() ? Expired() : Authenticated({
|
|
1465
|
+
accessToken: null,
|
|
1319
1466
|
expiresAt,
|
|
1320
|
-
identity
|
|
1321
|
-
|
|
1322
|
-
});
|
|
1467
|
+
identity
|
|
1468
|
+
}));
|
|
1323
1469
|
});
|
|
1324
1470
|
const beginLogin = ({ returnTo }) => Effect.suspend(() => {
|
|
1325
1471
|
rememberedReturnTo = returnTo;
|
|
1326
1472
|
const url = `${origin}${basePath}/login?returnTo=${encodeURIComponent(returnTo)}`;
|
|
1327
|
-
|
|
1473
|
+
dispatch(LoginStarted());
|
|
1328
1474
|
return Effect.as(navigate(url), url);
|
|
1329
1475
|
});
|
|
1330
1476
|
return FederatedAuth.of({
|
|
@@ -1343,7 +1489,7 @@ const makeServerSession = Effect.fnUntraced(function* makeServerSession(options)
|
|
|
1343
1489
|
credentials: "same-origin",
|
|
1344
1490
|
method: "POST",
|
|
1345
1491
|
signal
|
|
1346
|
-
})).pipe(Effect.ignore, Effect.andThen(Effect.sync(() =>
|
|
1492
|
+
})).pipe(Effect.ignore, Effect.andThen(Effect.sync(() => dispatch(LoggedOut()))));
|
|
1347
1493
|
}),
|
|
1348
1494
|
reauthorize: (input) => Effect.suspend(() => {
|
|
1349
1495
|
const returnTo = input?.returnTo ?? rememberedReturnTo;
|
|
@@ -1442,7 +1588,8 @@ const layerConfig$1 = (config) => Layer.unwrap(Effect.map(Config.unwrap(config),
|
|
|
1442
1588
|
/**
|
|
1443
1589
|
* The delegated application runtime on the Effect Core: the session of a
|
|
1444
1590
|
* sealed-cookie BFF, the CI client over the app's proxy and run follow, in
|
|
1445
|
-
* one context. `DelegatedRuntime`
|
|
1591
|
+
* one context. `DelegatedRuntime` stores no copy of the Session: its state is
|
|
1592
|
+
* the projection of the `FederatedAuth` Session and of its own facts, with
|
|
1446
1593
|
* synchronous listeners, so that the `.` facade keeps `getSnapshot` and
|
|
1447
1594
|
* `subscribe`.
|
|
1448
1595
|
*/
|
|
@@ -1476,34 +1623,85 @@ const resolvedPaths = (options) => ({
|
|
|
1476
1623
|
authBasePath: options.authBasePath ?? "/api/auth",
|
|
1477
1624
|
proxyPath: options.proxyPath ?? "/api"
|
|
1478
1625
|
});
|
|
1626
|
+
const checking = { status: "checking" };
|
|
1627
|
+
/**
|
|
1628
|
+
* `checking` while the first read is not finished; else `unavailable` when a
|
|
1629
|
+
* read failed outside the Session; else the projection of the Session (SDK-2).
|
|
1630
|
+
*/
|
|
1631
|
+
const project = (session, local) => {
|
|
1632
|
+
if (!local.firstReadDone) return checking;
|
|
1633
|
+
return local.transportFailure === void 0 ? mapAuthState(session) : {
|
|
1634
|
+
message: local.transportFailure,
|
|
1635
|
+
status: "unavailable"
|
|
1636
|
+
};
|
|
1637
|
+
};
|
|
1479
1638
|
const make = Effect.fnUntraced(function* make(options) {
|
|
1480
1639
|
const auth = yield* FederatedAuth;
|
|
1481
1640
|
const runs = yield* Runs;
|
|
1482
1641
|
const { authBasePath } = resolvedPaths(options);
|
|
1483
1642
|
const listeners = /* @__PURE__ */ new Set();
|
|
1484
|
-
let
|
|
1643
|
+
let local = {
|
|
1644
|
+
firstReadDone: false,
|
|
1645
|
+
transportFailure: void 0
|
|
1646
|
+
};
|
|
1485
1647
|
let generation = 0;
|
|
1486
|
-
|
|
1487
|
-
|
|
1648
|
+
let memo = {
|
|
1649
|
+
local,
|
|
1650
|
+
session: auth.getState(),
|
|
1651
|
+
snapshot: checking
|
|
1652
|
+
};
|
|
1653
|
+
/** The memoized projection; an equal projection keeps its reference. */
|
|
1654
|
+
const getSnapshot = () => {
|
|
1655
|
+
const session = auth.getState();
|
|
1656
|
+
if (memo.session !== session || memo.local !== local) {
|
|
1657
|
+
const next = project(session, local);
|
|
1658
|
+
memo = {
|
|
1659
|
+
local,
|
|
1660
|
+
session,
|
|
1661
|
+
snapshot: Equal.equals(next, memo.snapshot) ? memo.snapshot : next
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
return memo.snapshot;
|
|
1665
|
+
};
|
|
1666
|
+
let published = getSnapshot();
|
|
1667
|
+
/** Notifies each listener when the snapshot changed. */
|
|
1668
|
+
const publish = () => {
|
|
1669
|
+
const next = getSnapshot();
|
|
1670
|
+
if (next === published) return;
|
|
1671
|
+
published = next;
|
|
1488
1672
|
for (const notify of listeners) notify();
|
|
1489
1673
|
};
|
|
1674
|
+
const setLocal = (next) => {
|
|
1675
|
+
local = next;
|
|
1676
|
+
publish();
|
|
1677
|
+
};
|
|
1678
|
+
yield* Effect.acquireRelease(Effect.sync(() => auth.subscribe(publish)), (unsubscribe) => Effect.sync(unsubscribe));
|
|
1490
1679
|
const refresh = Effect.suspend(() => {
|
|
1491
1680
|
generation += 1;
|
|
1492
1681
|
const current = generation;
|
|
1493
|
-
publish({ status: "checking" });
|
|
1494
1682
|
return Effect.map(Effect.exit(auth.completeLogin(`${options.origin}${authBasePath}/callback`)), (exit) => {
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1683
|
+
let { transportFailure } = local;
|
|
1684
|
+
if (current === generation) transportFailure = Exit.isFailure(exit) && auth.getState().status !== "error" ? failureMessage(Cause.squash(exit.cause)) : void 0;
|
|
1685
|
+
setLocal({
|
|
1686
|
+
firstReadDone: true,
|
|
1687
|
+
transportFailure
|
|
1499
1688
|
});
|
|
1500
1689
|
});
|
|
1501
1690
|
});
|
|
1502
|
-
|
|
1691
|
+
/**
|
|
1692
|
+
* Runs a login or logout. It supersedes a running refresh; when it ends,
|
|
1693
|
+
* the Session decides the snapshot again, not an earlier failed read.
|
|
1694
|
+
*/
|
|
1695
|
+
const supersede = (change) => Effect.suspend(() => {
|
|
1503
1696
|
generation += 1;
|
|
1504
|
-
|
|
1505
|
-
|
|
1697
|
+
return Effect.tap(change, () => Effect.sync(() => {
|
|
1698
|
+
setLocal({
|
|
1699
|
+
...local,
|
|
1700
|
+
transportFailure: void 0
|
|
1701
|
+
});
|
|
1702
|
+
}));
|
|
1506
1703
|
});
|
|
1704
|
+
const login = (returnTo) => Effect.asVoid(supersede(auth.beginLogin({ returnTo })));
|
|
1507
1705
|
const subscribe = (notify) => {
|
|
1508
1706
|
listeners.add(notify);
|
|
1509
1707
|
return () => {
|
|
@@ -1513,19 +1711,22 @@ const make = Effect.fnUntraced(function* make(options) {
|
|
|
1513
1711
|
return DelegatedRuntime.of({
|
|
1514
1712
|
applicationId: options.applicationId,
|
|
1515
1713
|
changes: Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => subscribe(() => {
|
|
1516
|
-
Queue.offerUnsafe(queue,
|
|
1714
|
+
Queue.offerUnsafe(queue, getSnapshot());
|
|
1517
1715
|
})), (unsubscribe) => Effect.sync(unsubscribe))),
|
|
1518
|
-
followRun: (runId) => Effect.suspend(() =>
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
login,
|
|
1525
|
-
logout: Effect.suspend(() => {
|
|
1526
|
-
generation += 1;
|
|
1527
|
-
return Effect.andThen(auth.logout, Effect.sync(() => publish({ status: "anonymous" })));
|
|
1716
|
+
followRun: (runId) => Effect.suspend(() => {
|
|
1717
|
+
const state = getSnapshot();
|
|
1718
|
+
return state.status === "authenticated" ? runs.follow({
|
|
1719
|
+
organizationId: state.identity.organizationId,
|
|
1720
|
+
runId
|
|
1721
|
+
}) : Effect.fail(new FederatedAuthError("reauthorization_required", "A CI session is required to follow a run"));
|
|
1528
1722
|
}),
|
|
1723
|
+
getSnapshot,
|
|
1724
|
+
initialize: (url) => Effect.andThen(refresh, () => {
|
|
1725
|
+
const { status } = getSnapshot();
|
|
1726
|
+
return status === "anonymous" || status === "expired" ? login(url) : Effect.void;
|
|
1727
|
+
}),
|
|
1728
|
+
login,
|
|
1729
|
+
logout: supersede(auth.logout),
|
|
1529
1730
|
refresh,
|
|
1530
1731
|
subscribe
|
|
1531
1732
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/external-apps-client-sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.14",
|
|
4
4
|
"description": "Framework-neutral client for Collective Intelligence external applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -74,5 +74,5 @@
|
|
|
74
74
|
"ultracite": "7.10.7",
|
|
75
75
|
"vitest": "5.0.2"
|
|
76
76
|
},
|
|
77
|
-
"gitHead": "
|
|
77
|
+
"gitHead": "c417a35ab790e3f72c3e32651face1cc3de00eb9"
|
|
78
78
|
}
|