@collective-intelligence/external-apps-client-sdk 0.1.34 → 0.1.36
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 +105 -0
- package/dist/effect.d.ts +33 -0
- package/dist/effect.js +2 -0
- package/dist/event-stream-Djqhj56G.d.ts +63 -0
- package/dist/federated-auth-lotz7RGT.d.ts +94 -0
- package/dist/index.d.ts +15 -63
- package/dist/index.js +159 -621
- package/dist/{resources-DVME85iC.js → resources-BFJrm_N2.js} +1 -21
- package/dist/{resources-GSZWfWkN.d.ts → resources-Czlu8xAB.d.ts} +5 -66
- package/dist/resources.d.ts +1 -1
- package/dist/resources.js +1 -1
- package/dist/rolldown-runtime-DC62tzP2.js +31 -0
- package/dist/service-4l3X16iR.js +750 -0
- package/package.json +15 -2
|
@@ -0,0 +1,750 @@
|
|
|
1
|
+
import { n as __exportAll } from "./rolldown-runtime-DC62tzP2.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 Context from "effect/Context";
|
|
6
|
+
import * as Effect from "effect/Effect";
|
|
7
|
+
import * as FiberHandle from "effect/FiberHandle";
|
|
8
|
+
import * as FiberMap from "effect/FiberMap";
|
|
9
|
+
import * as FetchHttpClient from "effect/http/FetchHttpClient";
|
|
10
|
+
import * as HttpBody from "effect/http/HttpBody";
|
|
11
|
+
import * as HttpClient from "effect/http/HttpClient";
|
|
12
|
+
import * as HttpClientRequest from "effect/http/HttpClientRequest";
|
|
13
|
+
import * as HttpClientResponse from "effect/http/HttpClientResponse";
|
|
14
|
+
import * as Latch from "effect/Latch";
|
|
15
|
+
import * as Layer from "effect/Layer";
|
|
16
|
+
import * as Queue from "effect/Queue";
|
|
17
|
+
import * as Random from "effect/Random";
|
|
18
|
+
import * as Stream from "effect/Stream";
|
|
19
|
+
/** Codes of the Expected Errors that CI returns. The `CiErrorCode` Schema of `./effect` uses this list. */
|
|
20
|
+
const ciErrorCodes = [
|
|
21
|
+
"unauthenticated",
|
|
22
|
+
"forbidden",
|
|
23
|
+
"not_found",
|
|
24
|
+
"conflict",
|
|
25
|
+
"invalid_request",
|
|
26
|
+
"rate_limited",
|
|
27
|
+
"unavailable",
|
|
28
|
+
"internal"
|
|
29
|
+
];
|
|
30
|
+
var errors_exports = /* @__PURE__ */ __exportAll({
|
|
31
|
+
CiError: () => CiError,
|
|
32
|
+
CiErrorCode: () => CiErrorCode,
|
|
33
|
+
CiTransportError: () => CiTransportError,
|
|
34
|
+
FederatedAuthError: () => FederatedAuthError,
|
|
35
|
+
FederatedAuthErrorCode: () => FederatedAuthErrorCode
|
|
36
|
+
});
|
|
37
|
+
/** Code of an Expected Error that CI returns for an operation. */
|
|
38
|
+
const CiErrorCode = Schema.Literals(ciErrorCodes);
|
|
39
|
+
/** Code of an Expected Error of the federated sign-in flow. */
|
|
40
|
+
const FederatedAuthErrorCode = Schema.Literals([
|
|
41
|
+
"configuration_error",
|
|
42
|
+
"invalid_return_target",
|
|
43
|
+
"invalid_callback",
|
|
44
|
+
"invalid_state",
|
|
45
|
+
"transaction_expired",
|
|
46
|
+
"authorization_failed",
|
|
47
|
+
"token_exchange_failed",
|
|
48
|
+
"reauthorization_required"
|
|
49
|
+
]);
|
|
50
|
+
/** An Expected Error that CI returns for an operation. */
|
|
51
|
+
var CiError = class extends Schema.TaggedError()("CiError", {
|
|
52
|
+
code: CiErrorCode,
|
|
53
|
+
details: Schema.optionalKey(Schema.Record(Schema.String, Schema.Json)),
|
|
54
|
+
message: Schema.String,
|
|
55
|
+
retryable: Schema.Boolean
|
|
56
|
+
}) {};
|
|
57
|
+
/** An Expected Error of the federated sign-in flow. */
|
|
58
|
+
var FederatedAuthError = class extends Schema.TaggedError()("FederatedAuthError", {
|
|
59
|
+
code: FederatedAuthErrorCode,
|
|
60
|
+
message: Schema.String
|
|
61
|
+
}) {
|
|
62
|
+
constructor(first, second) {
|
|
63
|
+
if (Predicate.isString(first)) super({
|
|
64
|
+
code: first,
|
|
65
|
+
message: Predicate.isString(second) ? second : ""
|
|
66
|
+
});
|
|
67
|
+
else super(first, Predicate.isString(second) ? void 0 : second);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
/** The request did not reach CI, or CI's response was not readable. */
|
|
71
|
+
var CiTransportError = class extends Schema.TaggedError()("CiTransportError", { cause: Schema.Defect() }) {};
|
|
72
|
+
const emptyBlock = () => ({
|
|
73
|
+
comment: false,
|
|
74
|
+
data: [],
|
|
75
|
+
id: void 0,
|
|
76
|
+
type: ""
|
|
77
|
+
});
|
|
78
|
+
/**
|
|
79
|
+
* A Server-Sent Events parser that, unlike `EventSource`, reports comments:
|
|
80
|
+
* the server's pings are comments, and the client's watchdog needs them.
|
|
81
|
+
*/
|
|
82
|
+
const createEventStreamParser = (handlers) => {
|
|
83
|
+
let buffer = "";
|
|
84
|
+
let block = emptyBlock();
|
|
85
|
+
let retry;
|
|
86
|
+
const dispatch = () => {
|
|
87
|
+
const ended = block;
|
|
88
|
+
block = emptyBlock();
|
|
89
|
+
if (ended.data.length > 0) handlers.onEvent({
|
|
90
|
+
data: ended.data.join("\n"),
|
|
91
|
+
id: ended.id,
|
|
92
|
+
type: ended.type === "" ? "message" : ended.type
|
|
93
|
+
});
|
|
94
|
+
else if (ended.comment || ended.id !== void 0) handlers.onPing(ended.id);
|
|
95
|
+
};
|
|
96
|
+
const line = (text) => {
|
|
97
|
+
if (text === "") {
|
|
98
|
+
dispatch();
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (text.startsWith(":")) {
|
|
102
|
+
block.comment = true;
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const colon = text.indexOf(":");
|
|
106
|
+
const field = colon === -1 ? text : text.slice(0, colon);
|
|
107
|
+
const raw = colon === -1 ? "" : text.slice(colon + 1);
|
|
108
|
+
const value = raw.startsWith(" ") ? raw.slice(1) : raw;
|
|
109
|
+
if (field === "data") block.data.push(value);
|
|
110
|
+
else if (field === "event") block.type = value;
|
|
111
|
+
else if (field === "id" && !value.includes("\0")) block.id = value;
|
|
112
|
+
else if (field === "retry" && /^\d+$/u.test(value)) retry = Number(value);
|
|
113
|
+
};
|
|
114
|
+
return {
|
|
115
|
+
push: (chunk) => {
|
|
116
|
+
buffer += chunk;
|
|
117
|
+
const lines = buffer.split("\n");
|
|
118
|
+
buffer = lines.pop() ?? "";
|
|
119
|
+
for (const text of lines) line(text.endsWith("\r") ? text.slice(0, -1) : text);
|
|
120
|
+
},
|
|
121
|
+
/** The last `retry:` the stream sent, in milliseconds. */
|
|
122
|
+
retry: () => retry
|
|
123
|
+
};
|
|
124
|
+
};
|
|
125
|
+
/** A `Retry-After` header value in milliseconds, seconds form only. */
|
|
126
|
+
const retryAfterMilliseconds = (value) => value !== null && value !== void 0 && /^\d+$/u.test(value) ? Number(value) * 1e3 : void 0;
|
|
127
|
+
/** Reads `text/event-stream` with `fetch`, so pings and refusals are visible. */
|
|
128
|
+
const createFetchEventSourceFactory = (fetch) => (url, handlers) => {
|
|
129
|
+
const abort = new AbortController();
|
|
130
|
+
const live = () => !abort.signal.aborted;
|
|
131
|
+
const parser = createEventStreamParser({
|
|
132
|
+
onEvent: (event) => {
|
|
133
|
+
if (live()) handlers.onEvent(event);
|
|
134
|
+
},
|
|
135
|
+
onPing: (id) => {
|
|
136
|
+
if (live()) handlers.onPing(id);
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
const read = async () => {
|
|
140
|
+
try {
|
|
141
|
+
const response = await fetch(url, {
|
|
142
|
+
cache: "no-store",
|
|
143
|
+
headers: { accept: "text/event-stream" },
|
|
144
|
+
signal: abort.signal
|
|
145
|
+
});
|
|
146
|
+
if (!response.ok || response.body === null) {
|
|
147
|
+
parser.push(`${await response.text()}\n\n`);
|
|
148
|
+
if (live()) handlers.onEnd({
|
|
149
|
+
retryMilliseconds: retryAfterMilliseconds(response.headers.get("retry-after")) ?? parser.retry(),
|
|
150
|
+
status: response.status
|
|
151
|
+
});
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (live()) handlers.onOpen();
|
|
155
|
+
const decoder = new TextDecoder();
|
|
156
|
+
const reader = response.body.getReader();
|
|
157
|
+
for (;;) {
|
|
158
|
+
const { done, value } = await reader.read();
|
|
159
|
+
if (done) break;
|
|
160
|
+
parser.push(decoder.decode(value, { stream: true }));
|
|
161
|
+
}
|
|
162
|
+
} catch {}
|
|
163
|
+
if (live()) handlers.onEnd({
|
|
164
|
+
retryMilliseconds: parser.retry(),
|
|
165
|
+
status: void 0
|
|
166
|
+
});
|
|
167
|
+
};
|
|
168
|
+
read();
|
|
169
|
+
return { close: () => abort.abort() };
|
|
170
|
+
};
|
|
171
|
+
const topicSetDebounceMilliseconds = 300;
|
|
172
|
+
const pingTimeoutMilliseconds = 45e3;
|
|
173
|
+
const backoffBaseMilliseconds = 1e3;
|
|
174
|
+
const backoffCapMilliseconds = 3e4;
|
|
175
|
+
const initialMachineState = (documentVisible) => ({
|
|
176
|
+
attempt: 0,
|
|
177
|
+
documentVisible,
|
|
178
|
+
lastEventId: void 0,
|
|
179
|
+
nextLinkId: 1,
|
|
180
|
+
pageShown: true,
|
|
181
|
+
phase: "idle",
|
|
182
|
+
topics: []
|
|
183
|
+
});
|
|
184
|
+
/** Full jitter over an exponential cap; a server hint is a lower bound. */
|
|
185
|
+
const backoffDelay = (attempt, retryMilliseconds, jitter) => {
|
|
186
|
+
const cap = Math.min(backoffCapMilliseconds, backoffBaseMilliseconds * 2 ** attempt);
|
|
187
|
+
return Math.max(retryMilliseconds ?? 0, Math.floor(jitter * cap));
|
|
188
|
+
};
|
|
189
|
+
const currentLink = (state) => "link" in state ? state.link : void 0;
|
|
190
|
+
const shared = (state) => ({
|
|
191
|
+
attempt: state.attempt,
|
|
192
|
+
documentVisible: state.documentVisible,
|
|
193
|
+
lastEventId: state.lastEventId,
|
|
194
|
+
nextLinkId: state.nextLinkId,
|
|
195
|
+
pageShown: state.pageShown,
|
|
196
|
+
topics: state.topics
|
|
197
|
+
});
|
|
198
|
+
const visible = (state) => state.documentVisible && state.pageShown;
|
|
199
|
+
const wanted = (state) => state.phase !== "closed" && visible(state) && state.topics.length > 0;
|
|
200
|
+
const sameTopics = (left, right) => left.length === right.length && left.every((key) => right.includes(key));
|
|
201
|
+
const unchanged = (state) => ({
|
|
202
|
+
commands: [],
|
|
203
|
+
state
|
|
204
|
+
});
|
|
205
|
+
/** Commands that end the current link, if any. */
|
|
206
|
+
const unlink = (state) => {
|
|
207
|
+
const link = currentLink(state);
|
|
208
|
+
return link === void 0 ? [] : [{
|
|
209
|
+
linkId: link.id,
|
|
210
|
+
type: "disconnect"
|
|
211
|
+
}, {
|
|
212
|
+
timer: "watchdog",
|
|
213
|
+
type: "cancel"
|
|
214
|
+
}];
|
|
215
|
+
};
|
|
216
|
+
const watchdog = (linkId) => ({
|
|
217
|
+
event: {
|
|
218
|
+
linkId,
|
|
219
|
+
type: "watchdogElapsed"
|
|
220
|
+
},
|
|
221
|
+
milliseconds: pingTimeoutMilliseconds,
|
|
222
|
+
timer: "watchdog",
|
|
223
|
+
type: "schedule"
|
|
224
|
+
});
|
|
225
|
+
const idle = (state) => ({
|
|
226
|
+
...shared(state),
|
|
227
|
+
phase: state.phase === "closed" ? "closed" : "idle"
|
|
228
|
+
});
|
|
229
|
+
const stop = (state) => ({
|
|
230
|
+
commands: [
|
|
231
|
+
{
|
|
232
|
+
timer: "debounce",
|
|
233
|
+
type: "cancel"
|
|
234
|
+
},
|
|
235
|
+
{
|
|
236
|
+
timer: "backoff",
|
|
237
|
+
type: "cancel"
|
|
238
|
+
},
|
|
239
|
+
...unlink(state)
|
|
240
|
+
],
|
|
241
|
+
state: idle(state)
|
|
242
|
+
});
|
|
243
|
+
const connect = (state) => {
|
|
244
|
+
if (!wanted(state)) return {
|
|
245
|
+
commands: unlink(state),
|
|
246
|
+
state: idle(state)
|
|
247
|
+
};
|
|
248
|
+
const link = {
|
|
249
|
+
id: state.nextLinkId,
|
|
250
|
+
topics: state.topics
|
|
251
|
+
};
|
|
252
|
+
return {
|
|
253
|
+
commands: [
|
|
254
|
+
...unlink(state),
|
|
255
|
+
watchdog(link.id),
|
|
256
|
+
{
|
|
257
|
+
link,
|
|
258
|
+
type: "mint"
|
|
259
|
+
}
|
|
260
|
+
],
|
|
261
|
+
state: {
|
|
262
|
+
...shared(state),
|
|
263
|
+
link,
|
|
264
|
+
nextLinkId: state.nextLinkId + 1,
|
|
265
|
+
phase: "connecting"
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
};
|
|
269
|
+
const retry = (state, retryMilliseconds) => {
|
|
270
|
+
if (!wanted(state)) return {
|
|
271
|
+
commands: unlink(state),
|
|
272
|
+
state: idle(state)
|
|
273
|
+
};
|
|
274
|
+
return {
|
|
275
|
+
commands: [...unlink(state), {
|
|
276
|
+
attempt: state.attempt,
|
|
277
|
+
retryMilliseconds,
|
|
278
|
+
type: "backoff"
|
|
279
|
+
}],
|
|
280
|
+
state: {
|
|
281
|
+
...shared(state),
|
|
282
|
+
attempt: state.attempt + 1,
|
|
283
|
+
phase: "backoff"
|
|
284
|
+
}
|
|
285
|
+
};
|
|
286
|
+
};
|
|
287
|
+
/** Brings the connection in line with the page and the topic set. */
|
|
288
|
+
const sync = (state) => {
|
|
289
|
+
if (!wanted(state)) return stop(state);
|
|
290
|
+
const link = currentLink(state);
|
|
291
|
+
if (state.phase === "backoff" || link !== void 0 && sameTopics(link.topics, state.topics)) return {
|
|
292
|
+
commands: [{
|
|
293
|
+
timer: "debounce",
|
|
294
|
+
type: "cancel"
|
|
295
|
+
}],
|
|
296
|
+
state
|
|
297
|
+
};
|
|
298
|
+
return connect(state);
|
|
299
|
+
};
|
|
300
|
+
const reactToPage = (state) => {
|
|
301
|
+
if (!visible(state)) return stop(state);
|
|
302
|
+
return currentLink(state) === void 0 && state.phase !== "backoff" ? sync(state) : unchanged(state);
|
|
303
|
+
};
|
|
304
|
+
const streamUrlAfter = (streamUrl, lastEventId) => {
|
|
305
|
+
const url = new URL(streamUrl);
|
|
306
|
+
if (lastEventId !== void 0) url.searchParams.set("lastEventId", lastEventId);
|
|
307
|
+
return url.href;
|
|
308
|
+
};
|
|
309
|
+
/** Events of the client, the page and its timers. */
|
|
310
|
+
const clientTransition = (state, event) => {
|
|
311
|
+
switch (event.type) {
|
|
312
|
+
case "topicsChanged": {
|
|
313
|
+
const next = {
|
|
314
|
+
...state,
|
|
315
|
+
topics: event.topics
|
|
316
|
+
};
|
|
317
|
+
return next.phase === "closed" ? unchanged(next) : {
|
|
318
|
+
commands: [{
|
|
319
|
+
event: { type: "debounceElapsed" },
|
|
320
|
+
milliseconds: topicSetDebounceMilliseconds,
|
|
321
|
+
timer: "debounce",
|
|
322
|
+
type: "schedule"
|
|
323
|
+
}],
|
|
324
|
+
state: next
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
case "debounceElapsed": return sync(state);
|
|
328
|
+
case "visibilityChanged": return reactToPage({
|
|
329
|
+
...state,
|
|
330
|
+
documentVisible: event.visible
|
|
331
|
+
});
|
|
332
|
+
case "pageHidden": return stop({
|
|
333
|
+
...state,
|
|
334
|
+
pageShown: false
|
|
335
|
+
});
|
|
336
|
+
case "pageShown": return reactToPage({
|
|
337
|
+
...state,
|
|
338
|
+
documentVisible: event.visible,
|
|
339
|
+
pageShown: true
|
|
340
|
+
});
|
|
341
|
+
case "backoffElapsed": return state.phase === "backoff" ? connect(state) : unchanged(state);
|
|
342
|
+
case "close": return {
|
|
343
|
+
...stop(state),
|
|
344
|
+
state: {
|
|
345
|
+
...shared(state),
|
|
346
|
+
phase: "closed"
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
default: return unchanged(state);
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
/** Events of one link; an event of an earlier link changes nothing. */
|
|
353
|
+
const linkTransition = (state, event) => {
|
|
354
|
+
const link = currentLink(state);
|
|
355
|
+
if (link?.id !== event.linkId) return unchanged(state);
|
|
356
|
+
switch (event.type) {
|
|
357
|
+
case "ticketMinted": return {
|
|
358
|
+
commands: [{
|
|
359
|
+
linkId: link.id,
|
|
360
|
+
type: "openStream",
|
|
361
|
+
url: streamUrlAfter(event.streamUrl, state.lastEventId)
|
|
362
|
+
}],
|
|
363
|
+
state
|
|
364
|
+
};
|
|
365
|
+
case "ticketFailed":
|
|
366
|
+
case "streamEnded": return retry(state, event.retryMilliseconds);
|
|
367
|
+
case "streamOpened": return {
|
|
368
|
+
commands: state.lastEventId === void 0 ? [watchdog(link.id), { type: "resync" }] : [watchdog(link.id)],
|
|
369
|
+
state: {
|
|
370
|
+
...shared(state),
|
|
371
|
+
link,
|
|
372
|
+
phase: "open"
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
case "received": {
|
|
376
|
+
const { eventId } = event;
|
|
377
|
+
return {
|
|
378
|
+
commands: [watchdog(link.id)],
|
|
379
|
+
state: {
|
|
380
|
+
...state,
|
|
381
|
+
attempt: 0,
|
|
382
|
+
lastEventId: eventId === void 0 || eventId === "" ? state.lastEventId : eventId
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
case "watchdogElapsed": return retry(state);
|
|
387
|
+
default: return unchanged(state);
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
const transition = (state, event) => "linkId" in event ? linkTransition(state, event) : clientTransition(state, event);
|
|
391
|
+
/**
|
|
392
|
+
* The page lifecycle that the realtime connection follows: it connects only
|
|
393
|
+
* while the document is visible and the page is shown. The browser layer
|
|
394
|
+
* listens to `visibilitychange` on the document and to `pagehide` and
|
|
395
|
+
* `pageshow` on the window.
|
|
396
|
+
*/
|
|
397
|
+
var PageLifecycle = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/PageLifecycle") {};
|
|
398
|
+
const listen = (target, type, listener) => Effect.acquireRelease(Effect.sync(() => target?.addEventListener(type, listener)), () => Effect.sync(() => target?.removeEventListener(type, listener)));
|
|
399
|
+
/** The page of `document` and `window`; a test passes its own. */
|
|
400
|
+
const layerBrowser = ({ document, window }) => {
|
|
401
|
+
const documentVisible = () => document === void 0 || document.visibilityState !== "hidden";
|
|
402
|
+
return Layer.succeed(PageLifecycle, PageLifecycle.of({
|
|
403
|
+
events: Stream.callback((queue) => {
|
|
404
|
+
const offer = (event) => () => {
|
|
405
|
+
Queue.offerUnsafe(queue, event());
|
|
406
|
+
};
|
|
407
|
+
return Effect.all([
|
|
408
|
+
listen(document, "visibilitychange", offer(() => ({
|
|
409
|
+
type: "visibilityChanged",
|
|
410
|
+
visible: documentVisible()
|
|
411
|
+
}))),
|
|
412
|
+
listen(window, "pagehide", offer(() => ({ type: "pageHidden" }))),
|
|
413
|
+
listen(window, "pageshow", offer(() => ({
|
|
414
|
+
type: "pageShown",
|
|
415
|
+
visible: documentVisible()
|
|
416
|
+
})))
|
|
417
|
+
]);
|
|
418
|
+
}),
|
|
419
|
+
visible: Effect.sync(documentVisible)
|
|
420
|
+
}));
|
|
421
|
+
};
|
|
422
|
+
/**
|
|
423
|
+
* The page of this runtime: the browser `document` and `window`, or a page
|
|
424
|
+
* that is always visible where they do not exist.
|
|
425
|
+
*/
|
|
426
|
+
const layer$2 = Layer.suspend(() => {
|
|
427
|
+
const host = globalThis;
|
|
428
|
+
return layerBrowser({
|
|
429
|
+
document: host.document,
|
|
430
|
+
window: host.window
|
|
431
|
+
});
|
|
432
|
+
});
|
|
433
|
+
/**
|
|
434
|
+
* The event stream of one link as a `Stream`: the stream request read with
|
|
435
|
+
* `fetch` (`./event-stream`), as `open`, `event`, `ping` and `end` items. The
|
|
436
|
+
* stream ends after its `end` item; a consumer that stops early closes the
|
|
437
|
+
* request, and no `end` follows.
|
|
438
|
+
*/
|
|
439
|
+
var EventStreams = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/EventStreams") {};
|
|
440
|
+
const fromFactory = (factory) => EventStreams.of({ open: (url) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => factory(url, {
|
|
441
|
+
onEnd: (end) => {
|
|
442
|
+
Queue.offerUnsafe(queue, {
|
|
443
|
+
end,
|
|
444
|
+
type: "end"
|
|
445
|
+
});
|
|
446
|
+
Queue.endUnsafe(queue);
|
|
447
|
+
},
|
|
448
|
+
onEvent: (event) => {
|
|
449
|
+
Queue.offerUnsafe(queue, {
|
|
450
|
+
event,
|
|
451
|
+
type: "event"
|
|
452
|
+
});
|
|
453
|
+
},
|
|
454
|
+
onOpen: () => {
|
|
455
|
+
Queue.offerUnsafe(queue, { type: "open" });
|
|
456
|
+
},
|
|
457
|
+
onPing: (id) => {
|
|
458
|
+
Queue.offerUnsafe(queue, {
|
|
459
|
+
id,
|
|
460
|
+
type: "ping"
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
})), (source) => Effect.sync(() => source.close()))) });
|
|
464
|
+
/** The streams of a `RealtimeEventSourceFactory`. */
|
|
465
|
+
const layerFromFactory = (factory) => Layer.succeed(EventStreams, fromFactory(factory));
|
|
466
|
+
/** Reads each stream with the `fetch` of `FetchHttpClient.Fetch`. */
|
|
467
|
+
const layer$1 = Layer.effect(EventStreams, FetchHttpClient.Fetch.pipe(Effect.map((fetch) => fromFactory(createFetchEventSourceFactory(fetch)))));
|
|
468
|
+
/** One stable key per topic, whatever the key order of the object. */
|
|
469
|
+
const realtimeTopicKey = ({ filter, schema }) => JSON.stringify(filter === void 0 ? [schema] : [
|
|
470
|
+
schema,
|
|
471
|
+
filter.field,
|
|
472
|
+
filter.eq
|
|
473
|
+
]);
|
|
474
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
475
|
+
const isFilterValue = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
476
|
+
const isTopic = (value) => isRecord(value) && typeof value.schema === "string" && (value.filter === void 0 || isRecord(value.filter) && typeof value.filter.field === "string" && isFilterValue(value.filter.eq));
|
|
477
|
+
const isOp = (value) => value === "create" || value === "update" || value === "delete";
|
|
478
|
+
/** The `data` of a `change` event, or undefined when it is malformed. */
|
|
479
|
+
const parseRealtimeChange = (data) => {
|
|
480
|
+
let value;
|
|
481
|
+
try {
|
|
482
|
+
value = JSON.parse(data);
|
|
483
|
+
} catch {
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
return isRecord(value) && typeof value.id === "string" && isOp(value.op) && typeof value.revision === "string" && isTopic(value.topic) ? {
|
|
487
|
+
id: value.id,
|
|
488
|
+
op: value.op,
|
|
489
|
+
revision: value.revision,
|
|
490
|
+
topic: value.topic
|
|
491
|
+
} : void 0;
|
|
492
|
+
};
|
|
493
|
+
var RealtimeClient = class extends Context.Service()("@collective-intelligence/external-apps-client-sdk/RealtimeClient") {};
|
|
494
|
+
/** The answer of the ticket route, as far as the client reads it. */
|
|
495
|
+
const TicketAnswer = Schema.Struct({ streamUrl: Schema.String });
|
|
496
|
+
/** The least wait before a delivery: a burst of changes joins one delivery. */
|
|
497
|
+
const changeWindowMilliseconds = 250;
|
|
498
|
+
/** The random extra wait, so that the tabs of many users refetch apart. */
|
|
499
|
+
const changeJitterMilliseconds = 750;
|
|
500
|
+
const resyncUpdate = { op: "resync" };
|
|
501
|
+
const register = (listeners, listener) => {
|
|
502
|
+
const own = () => listener();
|
|
503
|
+
listeners.add(own);
|
|
504
|
+
return () => {
|
|
505
|
+
listeners.delete(own);
|
|
506
|
+
};
|
|
507
|
+
};
|
|
508
|
+
/** Keeps the listener that `listen` adds for the life of the scope. */
|
|
509
|
+
const scoped = (listen) => Effect.acquireRelease(Effect.sync(listen), (unlisten) => Effect.sync(unlisten)).pipe(Effect.asVoid);
|
|
510
|
+
/** The `ticketFailed` of `link`, after a warning with the failure. */
|
|
511
|
+
const failed = (link, error, retryMilliseconds) => {
|
|
512
|
+
const event = {
|
|
513
|
+
linkId: link.id,
|
|
514
|
+
retryMilliseconds,
|
|
515
|
+
type: "ticketFailed"
|
|
516
|
+
};
|
|
517
|
+
return Effect.logWarning("The realtime ticket request failed", error).pipe(Effect.as(event));
|
|
518
|
+
};
|
|
519
|
+
/**
|
|
520
|
+
* Logs a defect of a forked fiber, then runs `recover`. `FiberMap` and
|
|
521
|
+
* `FiberHandle` keep the failure of a fiber only for `join`, and nothing joins
|
|
522
|
+
* them. It runs also when the fiber was interrupted: an event source can throw
|
|
523
|
+
* as it closes.
|
|
524
|
+
*/
|
|
525
|
+
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));
|
|
526
|
+
/** Opens the connection for the life of the scope. */
|
|
527
|
+
const makeConnection = Effect.fn("RealtimeClient.makeConnection")(function* makeConnection(options) {
|
|
528
|
+
const http = yield* HttpClient.HttpClient;
|
|
529
|
+
const page = yield* PageLifecycle;
|
|
530
|
+
const streams = yield* EventStreams;
|
|
531
|
+
const events = yield* Queue.unbounded();
|
|
532
|
+
const timers = yield* FiberMap.make();
|
|
533
|
+
const links = yield* FiberMap.make();
|
|
534
|
+
const delivery = yield* FiberHandle.make();
|
|
535
|
+
const closed = yield* Latch.make();
|
|
536
|
+
const registrations = /* @__PURE__ */ new Map();
|
|
537
|
+
const resyncListeners = /* @__PURE__ */ new Set();
|
|
538
|
+
const accessListeners = /* @__PURE__ */ new Set();
|
|
539
|
+
/** Per topic key, the latest change of each record, by last arrival. */
|
|
540
|
+
const pending = /* @__PURE__ */ new Map();
|
|
541
|
+
let resyncPending = false;
|
|
542
|
+
let machine = initialMachineState(yield* page.visible);
|
|
543
|
+
const send = (event) => Queue.offer(events, event);
|
|
544
|
+
const topicsChanged = () => {
|
|
545
|
+
if (machine.phase === "closed") return;
|
|
546
|
+
Queue.offerUnsafe(events, {
|
|
547
|
+
topics: [...registrations.keys()],
|
|
548
|
+
type: "topicsChanged"
|
|
549
|
+
});
|
|
550
|
+
};
|
|
551
|
+
/** Delivers the pending changes, or the pending Resync, to the current listeners. */
|
|
552
|
+
const deliver = Effect.sync(() => {
|
|
553
|
+
const batches = [...pending];
|
|
554
|
+
pending.clear();
|
|
555
|
+
if (resyncPending) {
|
|
556
|
+
resyncPending = false;
|
|
557
|
+
for (const onResync of resyncListeners) onResync();
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
for (const [key, changes] of batches) {
|
|
561
|
+
const batch = [...changes.values()];
|
|
562
|
+
for (const onChanges of registrations.get(key)?.listeners ?? []) onChanges(batch);
|
|
563
|
+
}
|
|
564
|
+
});
|
|
565
|
+
/**
|
|
566
|
+
* The first change or Resync after a delivery schedules the next one; later
|
|
567
|
+
* ones join it without delaying it.
|
|
568
|
+
*/
|
|
569
|
+
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 });
|
|
570
|
+
/**
|
|
571
|
+
* Replaces the pending changes with one Resync at the next delivery.
|
|
572
|
+
* Without a Resync listener no refetch covers them, so they stay.
|
|
573
|
+
*/
|
|
574
|
+
const resync = Effect.suspend(() => {
|
|
575
|
+
if (resyncListeners.size === 0) return Effect.void;
|
|
576
|
+
resyncPending = true;
|
|
577
|
+
return scheduleDelivery;
|
|
578
|
+
});
|
|
579
|
+
const route = (change) => Effect.suspend(() => {
|
|
580
|
+
const key = realtimeTopicKey(change.topic);
|
|
581
|
+
if (!registrations.has(key)) return Effect.void;
|
|
582
|
+
const changes = pending.get(key) ?? /* @__PURE__ */ new Map();
|
|
583
|
+
changes.delete(change.id);
|
|
584
|
+
changes.set(change.id, change);
|
|
585
|
+
pending.set(key, changes);
|
|
586
|
+
return scheduleDelivery;
|
|
587
|
+
});
|
|
588
|
+
const handle = (event) => {
|
|
589
|
+
switch (event.type) {
|
|
590
|
+
case "change": {
|
|
591
|
+
const change = parseRealtimeChange(event.data);
|
|
592
|
+
return change === void 0 ? Effect.void : route(change);
|
|
593
|
+
}
|
|
594
|
+
case "reset": return resync;
|
|
595
|
+
case "access-changed": return Effect.sync(() => {
|
|
596
|
+
for (const onAccessChanged of accessListeners) onAccessChanged();
|
|
597
|
+
}).pipe(Effect.andThen(options.resyncOnAccessChange ? resync : Effect.void));
|
|
598
|
+
default: return Effect.void;
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
const receive = (linkId, item) => {
|
|
602
|
+
switch (item.type) {
|
|
603
|
+
case "open": return send({
|
|
604
|
+
linkId,
|
|
605
|
+
type: "streamOpened"
|
|
606
|
+
});
|
|
607
|
+
case "event": return send({
|
|
608
|
+
event: item.event,
|
|
609
|
+
linkId,
|
|
610
|
+
type: "streamEvent"
|
|
611
|
+
});
|
|
612
|
+
case "ping": return send({
|
|
613
|
+
eventId: item.id,
|
|
614
|
+
linkId,
|
|
615
|
+
type: "received"
|
|
616
|
+
});
|
|
617
|
+
case "end": return send({
|
|
618
|
+
linkId,
|
|
619
|
+
retryMilliseconds: item.end.retryMilliseconds,
|
|
620
|
+
type: "streamEnded"
|
|
621
|
+
});
|
|
622
|
+
default: return Effect.void;
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
/** Mints the ticket of `link`; a failed ticket waits at least its `Retry-After`. */
|
|
626
|
+
const ticket = Effect.fn("RealtimeClient.ticket")(function* ticket(link) {
|
|
627
|
+
const topics = link.topics.flatMap((key) => {
|
|
628
|
+
const registration = registrations.get(key);
|
|
629
|
+
return registration === void 0 ? [] : [registration.topic];
|
|
630
|
+
});
|
|
631
|
+
const response = yield* http.execute(HttpClientRequest.post(options.ticketUrl, { body: HttpBody.raw(JSON.stringify({ topics }), { contentType: "application/json" }) }));
|
|
632
|
+
const { streamUrl } = yield* HttpClientResponse.filterStatusOk(response).pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(TicketAnswer)));
|
|
633
|
+
return {
|
|
634
|
+
linkId: link.id,
|
|
635
|
+
streamUrl,
|
|
636
|
+
type: "ticketMinted"
|
|
637
|
+
};
|
|
638
|
+
}, (effect, link) => effect.pipe(Effect.catchTags({
|
|
639
|
+
HttpClientError: (error) => failed(link, error, retryAfterMilliseconds(error.response?.headers["retry-after"])),
|
|
640
|
+
SchemaError: (error) => failed(link, error)
|
|
641
|
+
}), Effect.provideService(FetchHttpClient.RequestInit, { credentials: "same-origin" }), Effect.provideService(HttpClient.TracerPropagationEnabled, false)));
|
|
642
|
+
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 })));
|
|
643
|
+
const run = (command) => {
|
|
644
|
+
switch (command.type) {
|
|
645
|
+
case "schedule": return schedule(command.timer, command.milliseconds, command.event);
|
|
646
|
+
case "cancel": return FiberMap.remove(timers, command.timer);
|
|
647
|
+
case "backoff": return Random.next.pipe(Effect.flatMap((jitter) => schedule("backoff", backoffDelay(command.attempt, command.retryMilliseconds, jitter), { type: "backoffElapsed" })));
|
|
648
|
+
case "mint": {
|
|
649
|
+
const linkId = command.link.id;
|
|
650
|
+
return FiberMap.run(links, linkId, ticket(command.link).pipe(Effect.flatMap(send), surfaceDefects("The realtime ticket request failed with a defect", { linkId }, send({
|
|
651
|
+
linkId,
|
|
652
|
+
retryMilliseconds: void 0,
|
|
653
|
+
type: "ticketFailed"
|
|
654
|
+
}))));
|
|
655
|
+
}
|
|
656
|
+
case "openStream": {
|
|
657
|
+
const { linkId } = command;
|
|
658
|
+
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({
|
|
659
|
+
linkId,
|
|
660
|
+
retryMilliseconds: void 0,
|
|
661
|
+
type: "streamEnded"
|
|
662
|
+
}))));
|
|
663
|
+
}
|
|
664
|
+
case "disconnect": return FiberMap.remove(links, command.linkId);
|
|
665
|
+
case "resync": return resync;
|
|
666
|
+
default: return Effect.void;
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
const apply = Effect.fnUntraced(function* apply(event) {
|
|
670
|
+
const next = transition(machine, event);
|
|
671
|
+
machine = next.state;
|
|
672
|
+
for (const command of next.commands) yield* run(command);
|
|
673
|
+
});
|
|
674
|
+
const step = (event) => {
|
|
675
|
+
if (event.type !== "streamEvent") return apply(event);
|
|
676
|
+
const { linkId } = event;
|
|
677
|
+
const current = currentLink(machine)?.id === linkId;
|
|
678
|
+
return apply({
|
|
679
|
+
eventId: event.event.id,
|
|
680
|
+
linkId,
|
|
681
|
+
type: "received"
|
|
682
|
+
}).pipe(Effect.andThen(current ? handle(event.event) : Effect.void));
|
|
683
|
+
};
|
|
684
|
+
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 }));
|
|
685
|
+
yield* page.events.pipe(Stream.runForEach(send), Effect.forkScoped({ startImmediately: true }));
|
|
686
|
+
yield* Effect.addFinalizer(() => Effect.sync(() => {
|
|
687
|
+
machine = transition(machine, { type: "close" }).state;
|
|
688
|
+
pending.clear();
|
|
689
|
+
resyncPending = false;
|
|
690
|
+
}).pipe(Effect.andThen(closed.open)));
|
|
691
|
+
return {
|
|
692
|
+
closed: closed.await,
|
|
693
|
+
listen: (topic, onChanges) => {
|
|
694
|
+
const key = realtimeTopicKey(topic);
|
|
695
|
+
const listener = (changes) => onChanges(changes);
|
|
696
|
+
const registration = registrations.get(key) ?? {
|
|
697
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
698
|
+
topic
|
|
699
|
+
};
|
|
700
|
+
registration.listeners.add(listener);
|
|
701
|
+
if (!registrations.has(key)) {
|
|
702
|
+
registrations.set(key, registration);
|
|
703
|
+
topicsChanged();
|
|
704
|
+
}
|
|
705
|
+
return () => {
|
|
706
|
+
if (!registration.listeners.delete(listener)) return;
|
|
707
|
+
if (registration.listeners.size === 0) {
|
|
708
|
+
registrations.delete(key);
|
|
709
|
+
pending.delete(key);
|
|
710
|
+
topicsChanged();
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
},
|
|
714
|
+
listenAccessChanges: (onAccessChanged) => register(accessListeners, onAccessChanged),
|
|
715
|
+
listenResyncs: (onResync) => register(resyncListeners, onResync),
|
|
716
|
+
state: () => ({
|
|
717
|
+
machine,
|
|
718
|
+
topics: [...registrations.values()].map(({ topic }) => topic)
|
|
719
|
+
})
|
|
720
|
+
};
|
|
721
|
+
});
|
|
722
|
+
/** The `RealtimeClient` of one connection, open for the life of the scope. */
|
|
723
|
+
const make = Effect.fn("RealtimeClient.make")(function* make(options) {
|
|
724
|
+
const connection = yield* makeConnection({
|
|
725
|
+
...options,
|
|
726
|
+
resyncOnAccessChange: true
|
|
727
|
+
});
|
|
728
|
+
const untilClosed = Stream.interruptWhen(connection.closed);
|
|
729
|
+
return RealtimeClient.of({
|
|
730
|
+
accessChanges: Stream.callback((queue) => scoped(() => connection.listenAccessChanges(() => {
|
|
731
|
+
Queue.offerUnsafe(queue, void 0);
|
|
732
|
+
}))).pipe(untilClosed),
|
|
733
|
+
subscribe: (topic) => Stream.callback((queue) => Effect.andThen(scoped(() => connection.listen(topic, (changes) => {
|
|
734
|
+
Queue.offerAllUnsafe(queue, changes);
|
|
735
|
+
})), scoped(() => connection.listenResyncs(() => {
|
|
736
|
+
Queue.offerUnsafe(queue, resyncUpdate);
|
|
737
|
+
})))).pipe(untilClosed)
|
|
738
|
+
});
|
|
739
|
+
});
|
|
740
|
+
/** `RealtimeClient` over the `HttpClient`, `EventStreams` and `PageLifecycle` of the context. */
|
|
741
|
+
const layerWithoutDependencies = (options) => Layer.effect(RealtimeClient, make(options));
|
|
742
|
+
/** `RealtimeClient` with the `fetch` of `FetchHttpClient.Fetch` and the page of this runtime. */
|
|
743
|
+
const layer = (options) => layerWithoutDependencies(options).pipe(Layer.provide([
|
|
744
|
+
FetchHttpClient.layer,
|
|
745
|
+
layer$1,
|
|
746
|
+
layer$2
|
|
747
|
+
]));
|
|
748
|
+
/** The changes and Resyncs of `topic` from the `RealtimeClient` of the context. */
|
|
749
|
+
const subscribe = (topic) => Stream.unwrap(RealtimeClient.useSync((client) => client.subscribe(topic)));
|
|
750
|
+
export { realtimeTopicKey as a, layerBrowser as c, CiError as d, CiErrorCode as f, errors_exports as g, FederatedAuthErrorCode as h, subscribe as i, currentLink as l, FederatedAuthError as m, layer as n, layer$1 as o, CiTransportError as p, makeConnection as r, layerFromFactory as s, RealtimeClient as t, createFetchEventSourceFactory as u };
|