tempest-react-sdk 0.80.0 → 0.82.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -10
- package/bin/create-tempest-app.e2e.test.mjs +31 -0
- package/bin/create-tempest-app.mjs +11 -1
- package/bin/lib/component/generate.test.mjs +13 -1
- package/bin/lib/doctor/doctor.e2e.test.mjs +29 -0
- package/bin/lib/doctor/vitest.mjs +120 -0
- package/bin/lib/doctor/vitest.test.mjs +139 -0
- package/bin/lib/fs/contain.mjs +7 -0
- package/bin/lib/openapi/escape.mjs +68 -4
- package/bin/lib/openapi/generate.hostile.test.mjs +150 -1
- package/bin/lib/openapi/generate.mjs +78 -13
- package/bin/lib/openapi/generate.test.mjs +13 -1
- package/bin/lib/openapi/pattern-risk.mjs +134 -0
- package/bin/lib/openapi/pattern-risk.test.mjs +45 -0
- package/bin/tempest-gen.test.mjs +100 -0
- package/bin/tempest.mjs +24 -8
- package/dist/access/use-can.cjs +1 -1
- package/dist/access/use-can.cjs.map +1 -1
- package/dist/access/use-can.js +25 -28
- package/dist/access/use-can.js.map +1 -1
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +234 -122
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/auth/session-identity.cjs +2 -0
- package/dist/auth/session-identity.cjs.map +1 -0
- package/dist/auth/session-identity.js +12 -0
- package/dist/auth/session-identity.js.map +1 -0
- package/dist/br/boleto.cjs +1 -1
- package/dist/br/boleto.cjs.map +1 -1
- package/dist/br/boleto.js +2 -1
- package/dist/br/boleto.js.map +1 -1
- package/dist/br.d.ts +22 -3
- package/dist/components/AuthForm/AuthFieldControl.cjs +2 -0
- package/dist/components/AuthForm/AuthFieldControl.cjs.map +1 -0
- package/dist/components/AuthForm/AuthFieldControl.js +85 -0
- package/dist/components/AuthForm/AuthFieldControl.js.map +1 -0
- package/dist/components/AuthForm/AuthForm.cjs +2 -0
- package/dist/components/AuthForm/AuthForm.cjs.map +1 -0
- package/dist/components/AuthForm/AuthForm.js +83 -0
- package/dist/components/AuthForm/AuthForm.js.map +1 -0
- package/dist/components/AuthForm/AuthForm.module.cjs +3 -0
- package/dist/components/AuthForm/AuthForm.module.cjs.map +1 -0
- package/dist/components/AuthForm/AuthForm.module.js +14 -0
- package/dist/components/AuthForm/AuthForm.module.js.map +1 -0
- package/dist/components/AuthForm/AuthLinks.cjs +2 -0
- package/dist/components/AuthForm/AuthLinks.cjs.map +1 -0
- package/dist/components/AuthForm/AuthLinks.js +32 -0
- package/dist/components/AuthForm/AuthLinks.js.map +1 -0
- package/dist/components/AuthForm/ForgotPasswordForm.cjs +2 -0
- package/dist/components/AuthForm/ForgotPasswordForm.cjs.map +1 -0
- package/dist/components/AuthForm/ForgotPasswordForm.js +32 -0
- package/dist/components/AuthForm/ForgotPasswordForm.js.map +1 -0
- package/dist/components/AuthForm/LoginForm.cjs +2 -0
- package/dist/components/AuthForm/LoginForm.cjs.map +1 -0
- package/dist/components/AuthForm/LoginForm.js +39 -0
- package/dist/components/AuthForm/LoginForm.js.map +1 -0
- package/dist/components/AuthForm/ResetPasswordForm.cjs +2 -0
- package/dist/components/AuthForm/ResetPasswordForm.cjs.map +1 -0
- package/dist/components/AuthForm/ResetPasswordForm.js +39 -0
- package/dist/components/AuthForm/ResetPasswordForm.js.map +1 -0
- package/dist/components/AuthForm/SignUpForm.cjs +2 -0
- package/dist/components/AuthForm/SignUpForm.cjs.map +1 -0
- package/dist/components/AuthForm/SignUpForm.js +32 -0
- package/dist/components/AuthForm/SignUpForm.js.map +1 -0
- package/dist/components/AuthForm/auth-defaults.cjs +2 -0
- package/dist/components/AuthForm/auth-defaults.cjs.map +1 -0
- package/dist/components/AuthForm/auth-defaults.js +54 -0
- package/dist/components/AuthForm/auth-defaults.js.map +1 -0
- package/dist/components/AuthForm/auth-schemas.cjs +2 -0
- package/dist/components/AuthForm/auth-schemas.cjs.map +1 -0
- package/dist/components/AuthForm/auth-schemas.js +26 -0
- package/dist/components/AuthForm/auth-schemas.js.map +1 -0
- package/dist/components/AuthPage/AuthPage.cjs +2 -0
- package/dist/components/AuthPage/AuthPage.cjs.map +1 -0
- package/dist/components/AuthPage/AuthPage.js +97 -0
- package/dist/components/AuthPage/AuthPage.js.map +1 -0
- package/dist/components/AuthPage/AuthPage.module.cjs +3 -0
- package/dist/components/AuthPage/AuthPage.module.cjs.map +1 -0
- package/dist/components/AuthPage/AuthPage.module.js +24 -0
- package/dist/components/AuthPage/AuthPage.module.js.map +1 -0
- package/dist/components/Breadcrumbs/Breadcrumbs.cjs +1 -1
- package/dist/components/Breadcrumbs/Breadcrumbs.cjs.map +1 -1
- package/dist/components/Breadcrumbs/Breadcrumbs.js +22 -21
- package/dist/components/Breadcrumbs/Breadcrumbs.js.map +1 -1
- package/dist/components/Button/Button.cjs +1 -1
- package/dist/components/Button/Button.cjs.map +1 -1
- package/dist/components/Button/Button.js +41 -40
- package/dist/components/Button/Button.js.map +1 -1
- package/dist/components/Chat/ChatAttachments.cjs +1 -1
- package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
- package/dist/components/Chat/ChatAttachments.js +38 -38
- package/dist/components/FilterBar/filter-apply.cjs +1 -1
- package/dist/components/FilterBar/filter-apply.cjs.map +1 -1
- package/dist/components/FilterBar/filter-apply.js +7 -7
- package/dist/components/Form/Form.cjs +1 -1
- package/dist/components/Form/Form.cjs.map +1 -1
- package/dist/components/Form/Form.js +30 -32
- package/dist/components/Form/Form.js.map +1 -1
- package/dist/components/Layout/Layout.cjs +1 -1
- package/dist/components/Layout/Layout.cjs.map +1 -1
- package/dist/components/Layout/Layout.js +25 -24
- package/dist/components/Layout/Layout.js.map +1 -1
- package/dist/components/Layout/gap.cjs +2 -0
- package/dist/components/Layout/gap.cjs.map +1 -0
- package/dist/components/Layout/gap.js +15 -0
- package/dist/components/Layout/gap.js.map +1 -0
- package/dist/components/NavigationMenu/NavigationMenu.cjs +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.cjs.map +1 -1
- package/dist/components/NavigationMenu/NavigationMenu.js +71 -70
- package/dist/components/NavigationMenu/NavigationMenu.js.map +1 -1
- package/dist/components/Sidebar/Sidebar.cjs.map +1 -1
- package/dist/components/Sidebar/Sidebar.js.map +1 -1
- package/dist/components/Sidebar/SidebarEntry.cjs +1 -1
- package/dist/components/Sidebar/SidebarEntry.cjs.map +1 -1
- package/dist/components/Sidebar/SidebarEntry.js +30 -29
- package/dist/components/Sidebar/SidebarEntry.js.map +1 -1
- package/dist/data/create-data-provider.cjs +1 -1
- package/dist/data/create-data-provider.cjs.map +1 -1
- package/dist/data/create-data-provider.js +1 -2
- package/dist/data/create-data-provider.js.map +1 -1
- package/dist/forms/index.js +7 -7
- package/dist/forms/masked-inputs.cjs +1 -1
- package/dist/forms/masked-inputs.cjs.map +1 -1
- package/dist/forms/masked-inputs.js +15 -15
- package/dist/forms/validate-form.cjs +1 -1
- package/dist/forms/validate-form.cjs.map +1 -1
- package/dist/forms/validate-form.js +6 -1
- package/dist/forms/validate-form.js.map +1 -1
- package/dist/forms/zod-resolver.cjs +1 -1
- package/dist/forms/zod-resolver.cjs.map +1 -1
- package/dist/forms/zod-resolver.js +8 -3
- package/dist/forms/zod-resolver.js.map +1 -1
- package/dist/http/api-client.cjs +1 -1
- package/dist/http/api-client.cjs.map +1 -1
- package/dist/http/api-client.js +137 -116
- package/dist/http/api-client.js.map +1 -1
- package/dist/http/credential-scope.cjs +1 -1
- package/dist/http/credential-scope.cjs.map +1 -1
- package/dist/http/credential-scope.js +33 -9
- package/dist/http/credential-scope.js.map +1 -1
- package/dist/http/presigned-post.cjs.map +1 -1
- package/dist/http/presigned-post.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +140 -134
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/upload-with-progress.cjs +1 -1
- package/dist/http/upload-with-progress.cjs.map +1 -1
- package/dist/http/upload-with-progress.js +17 -17
- package/dist/http/upload-with-progress.js.map +1 -1
- package/dist/http/use-describe-api-error.cjs +1 -1
- package/dist/http/use-describe-api-error.cjs.map +1 -1
- package/dist/http/use-describe-api-error.js +9 -9
- package/dist/oauth/GoogleSignIn.cjs +1 -1
- package/dist/oauth/GoogleSignIn.cjs.map +1 -1
- package/dist/oauth/GoogleSignIn.js +5 -4
- package/dist/oauth/GoogleSignIn.js.map +1 -1
- package/dist/offline/create-offline-sync.cjs +1 -1
- package/dist/offline/create-offline-sync.cjs.map +1 -1
- package/dist/offline/create-offline-sync.js +108 -68
- package/dist/offline/create-offline-sync.js.map +1 -1
- package/dist/query/offline-persistence.cjs +1 -1
- package/dist/query/offline-persistence.cjs.map +1 -1
- package/dist/query/offline-persistence.js +54 -44
- package/dist/query/offline-persistence.js.map +1 -1
- package/dist/sse/create-event-stream.cjs +1 -1
- package/dist/sse/create-event-stream.cjs.map +1 -1
- package/dist/sse/create-event-stream.js +48 -41
- package/dist/sse/create-event-stream.js.map +1 -1
- package/dist/sse/ticket-event-stream.cjs +1 -1
- package/dist/sse/ticket-event-stream.cjs.map +1 -1
- package/dist/sse/ticket-event-stream.js +48 -19
- package/dist/sse/ticket-event-stream.js.map +1 -1
- package/dist/sse/use-event-stream.cjs +1 -1
- package/dist/sse/use-event-stream.cjs.map +1 -1
- package/dist/sse/use-event-stream.js +19 -14
- package/dist/sse/use-event-stream.js.map +1 -1
- package/dist/styles/AuthForm.css +2 -0
- package/dist/styles/AuthPage.css +2 -0
- package/dist/styles/component/AuthForm.css +9 -0
- package/dist/styles/component/AuthPage.css +29 -0
- package/dist/styles/forms.css +36 -0
- package/dist/styles/manifest.json +63 -0
- package/dist/styles.css +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +132 -112
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/cache.cjs +1 -1
- package/dist/sw/cache.cjs.map +1 -1
- package/dist/sw/cache.js +36 -30
- package/dist/sw/cache.js.map +1 -1
- package/dist/sw/create-push-handler.cjs +1 -1
- package/dist/sw/create-push-handler.cjs.map +1 -1
- package/dist/sw/create-push-handler.js +20 -10
- package/dist/sw/create-push-handler.js.map +1 -1
- package/dist/sw.d.ts +93 -28
- package/dist/tabular/compact.cjs +1 -1
- package/dist/tabular/compact.cjs.map +1 -1
- package/dist/tabular/compact.js +35 -16
- package/dist/tabular/compact.js.map +1 -1
- package/dist/tabular/manifest.cjs +1 -1
- package/dist/tabular/manifest.cjs.map +1 -1
- package/dist/tabular/manifest.js +33 -15
- package/dist/tabular/manifest.js.map +1 -1
- package/dist/tabular.d.ts +11 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +1057 -83
- package/dist/tempest-react-sdk.js +373 -365
- package/dist/theme/initial-theme.cjs +4 -4
- package/dist/theme/initial-theme.cjs.map +1 -1
- package/dist/theme/initial-theme.js +8 -5
- package/dist/theme/initial-theme.js.map +1 -1
- package/dist/utils/compressed-storage.cjs +1 -1
- package/dist/utils/compressed-storage.cjs.map +1 -1
- package/dist/utils/compressed-storage.js +13 -7
- package/dist/utils/compressed-storage.js.map +1 -1
- package/dist/utils/format.cjs +1 -1
- package/dist/utils/format.cjs.map +1 -1
- package/dist/utils/format.js +25 -25
- package/dist/utils/numbers.cjs +1 -1
- package/dist/utils/numbers.cjs.map +1 -1
- package/dist/utils/numbers.js +7 -7
- package/dist/utils/objects.cjs +1 -1
- package/dist/utils/objects.cjs.map +1 -1
- package/dist/utils/objects.js +13 -7
- package/dist/utils/objects.js.map +1 -1
- package/dist/utils/safe-url.cjs +1 -1
- package/dist/utils/safe-url.cjs.map +1 -1
- package/dist/utils/safe-url.js +4 -1
- package/dist/utils/safe-url.js.map +1 -1
- package/dist/webrtc/peer-mesh.cjs +1 -1
- package/dist/webrtc/peer-mesh.cjs.map +1 -1
- package/dist/webrtc/peer-mesh.js +7 -1
- package/dist/webrtc/peer-mesh.js.map +1 -1
- package/dist/ws/create-web-socket.cjs +1 -1
- package/dist/ws/create-web-socket.cjs.map +1 -1
- package/dist/ws/create-web-socket.js +77 -61
- package/dist/ws/create-web-socket.js.map +1 -1
- package/dist/ws/use-web-socket.cjs +1 -1
- package/dist/ws/use-web-socket.cjs.map +1 -1
- package/dist/ws/use-web-socket.js +4 -3
- package/dist/ws/use-web-socket.js.map +1 -1
- package/package.json +1 -1
- package/template-pwa/src/pwa.tsx +42 -0
- package/template-pwa/src/sw.ts +15 -10
|
@@ -1,72 +1,79 @@
|
|
|
1
1
|
import { decodeFrame as e } from "../utils/json-frame.js";
|
|
2
2
|
//#region src/sse/create-event-stream.ts
|
|
3
3
|
function t(t, n = {}) {
|
|
4
|
-
let { withCredentials: r = !1, namedEvents: i = [], heartbeatEvents: a = ["ping"], maxRetries: o = 10, initialBackoff: s = 1e3, maxBackoff: c = 3e4, parser: l, onOpen: u, onMessage: d, onError: f, onParseError: p, schema: m, onValidationError: h, onUrlError: g, shouldRetryUrl: _ = () => !0,
|
|
5
|
-
function
|
|
6
|
-
|
|
4
|
+
let { withCredentials: r = !1, namedEvents: i = [], heartbeatEvents: a = ["ping"], maxRetries: o = 10, initialBackoff: s = 1e3, maxBackoff: c = 3e4, parser: l, onOpen: u, onMessage: d, onError: f, onParseError: p, schema: m, onValidationError: h, onUrlError: g, shouldRetryUrl: _ = () => !0, sessionKey: v, onStatusChange: y } = n, b = null, x = null, S = 0, C = "idle", w = !1, T = 0, E;
|
|
5
|
+
function D(e) {
|
|
6
|
+
C !== e && (C = e, y?.(e));
|
|
7
7
|
}
|
|
8
|
-
function
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
function O() {
|
|
9
|
+
return v !== void 0 && !Object.is(v(), E);
|
|
10
|
+
}
|
|
11
|
+
function k(t, n, r) {
|
|
12
|
+
if (t !== b || a.includes(n)) return;
|
|
13
|
+
if (O()) {
|
|
14
|
+
F();
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
let i = e(typeof r.data == "string" ? r.data : "", "createEventStream", {
|
|
11
18
|
parser: l,
|
|
12
19
|
onParseError: p,
|
|
13
20
|
schema: m,
|
|
14
21
|
onValidationError: h
|
|
15
22
|
});
|
|
16
|
-
|
|
17
|
-
event:
|
|
18
|
-
data:
|
|
19
|
-
id:
|
|
20
|
-
raw:
|
|
23
|
+
i.delivered && d?.({
|
|
24
|
+
event: n,
|
|
25
|
+
data: i.data,
|
|
26
|
+
id: r.lastEventId || void 0,
|
|
27
|
+
raw: r
|
|
21
28
|
});
|
|
22
29
|
}
|
|
23
|
-
function
|
|
24
|
-
if (
|
|
25
|
-
if (
|
|
26
|
-
|
|
30
|
+
function A() {
|
|
31
|
+
if (w) return;
|
|
32
|
+
if (S >= o) {
|
|
33
|
+
D("error");
|
|
27
34
|
return;
|
|
28
35
|
}
|
|
29
|
-
let e = Math.min(s * 2 **
|
|
30
|
-
|
|
36
|
+
let e = Math.min(s * 2 ** S, c);
|
|
37
|
+
S += 1, x = setTimeout(M, e);
|
|
31
38
|
}
|
|
32
|
-
function
|
|
33
|
-
g?.(e), _(e) ? (
|
|
39
|
+
function j(e) {
|
|
40
|
+
g?.(e), _(e) ? (D("closed"), A()) : D("error");
|
|
34
41
|
}
|
|
35
|
-
function
|
|
36
|
-
if (
|
|
37
|
-
if (
|
|
38
|
-
|
|
42
|
+
function M() {
|
|
43
|
+
if (w) return;
|
|
44
|
+
if (b &&= (b.close(), null), D("connecting"), T += 1, E = v?.(), typeof t == "string") {
|
|
45
|
+
N(t);
|
|
39
46
|
return;
|
|
40
47
|
}
|
|
41
|
-
let e =
|
|
42
|
-
Promise.resolve().then(t).then((t) => {
|
|
43
|
-
|
|
48
|
+
let e = T;
|
|
49
|
+
Promise.resolve().then(() => w || e !== T ? null : t()).then((t) => {
|
|
50
|
+
t === null || w || e !== T || (O() ? M() : N(t));
|
|
44
51
|
}, (t) => {
|
|
45
|
-
!
|
|
52
|
+
!w && e === T && j(t);
|
|
46
53
|
});
|
|
47
54
|
}
|
|
48
|
-
function
|
|
55
|
+
function N(e) {
|
|
49
56
|
let t = new EventSource(e, { withCredentials: r });
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
}, t.onmessage = (e) =>
|
|
53
|
-
for (let e of i) t.addEventListener(e, (
|
|
57
|
+
b = t, t.onopen = () => {
|
|
58
|
+
S = 0, D("open"), u?.();
|
|
59
|
+
}, t.onmessage = (e) => k(t, "message", e);
|
|
60
|
+
for (let e of i) t.addEventListener(e, (n) => k(t, e, n));
|
|
54
61
|
for (let e of a) t.addEventListener(e, () => {});
|
|
55
62
|
t.onerror = (e) => {
|
|
56
|
-
f?.(e), t.close(),
|
|
63
|
+
f?.(e), t.close(), b = null, D("closed"), A();
|
|
57
64
|
};
|
|
58
65
|
}
|
|
59
|
-
function
|
|
60
|
-
|
|
66
|
+
function P() {
|
|
67
|
+
w = !0, x &&= (clearTimeout(x), null), S = 0, b &&= (b.close(), null), D("closed");
|
|
61
68
|
}
|
|
62
|
-
function
|
|
63
|
-
|
|
69
|
+
function F() {
|
|
70
|
+
x &&= (clearTimeout(x), null), S = 0, w = !1, M();
|
|
64
71
|
}
|
|
65
|
-
return
|
|
66
|
-
close:
|
|
67
|
-
reconnect:
|
|
72
|
+
return M(), {
|
|
73
|
+
close: P,
|
|
74
|
+
reconnect: F,
|
|
68
75
|
get status() {
|
|
69
|
-
return
|
|
76
|
+
return C;
|
|
70
77
|
}
|
|
71
78
|
};
|
|
72
79
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-event-stream.js","names":["createEventStream","options","source","retryTimer","retries","status","closed","attempt","setStatus","next","onStatusChange","emit","heartbeatEvents","eventName","decoded","decodeFrame","event","onMessage","scheduleReconnect","maxRetries","delay","initialBackoff","maxBackoff","connect","failUrl","onUrlError","error","shouldRetryUrl","url","current","open","resolved","es","target","onOpen","name","namedEvents","onError","close","reconnect"],"sources":["../../src/sse/create-event-stream.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — the body is the SSE line protocol — accumulate\n * `data:` lines until a blank line, track `id:` for Last-Event-ID, honour `retry:` —\n * plus the reconnect that uses the id it just tracked.\n */\nimport { decodeFrame } from \"../utils/json-frame\";\nimport type { SchemaIssue, SchemaLike } from \"../utils/schema-like\";\nexport type EventStreamStatus = \"idle\" | \"connecting\" | \"open\" | \"closed\" | \"error\";\n\n/**\n * Where the stream connects: a fixed URL, or a function resolved again before\n * every connection, the first one and each reconnect.\n *\n * The function form exists for short-lived credentials carried in the URL,\n * such as the `?ticket=` of the `tempest-fastapi-sdk` SSE router. `EventSource`\n * cannot send headers, so the credential has to ride in the query, and one that\n * expires makes a fixed URL a trap: the reconnect after the expiry presents the\n * same dead credential, gets a `401`, and burns every retry on it while the user\n * is still signed in.\n */\nexport type EventStreamUrl = string | (() => string | Promise<string>);\n\nexport interface EventStreamMessage<T> {\n /** Server-named event (default `\"message\"`). */\n event: string;\n /** Parsed payload — validated when `schema` is set, JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** Server-supplied id, if any. */\n id?: string;\n /** Raw `MessageEvent` for advanced cases. */\n raw: MessageEvent;\n}\n\nexport interface CreateEventStreamOptions<T> {\n /** Send cookies with the EventSource handshake. Default: false. */\n withCredentials?: boolean;\n /** Subscribe to named events in addition to `message`. */\n namedEvents?: readonly string[];\n /** Treat these named events as heartbeat-only (no callback). Default: `[\"ping\"]`. */\n heartbeatEvents?: readonly string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable reconnect. */\n maxRetries?: number;\n /** Initial backoff in ms; doubles per attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff in ms. Default: 30000. */\n maxBackoff?: number;\n /** Parse `event.data`. Defaults to JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n /**\n * A frame arrived that is not valid JSON, and no `parser` was supplied.\n *\n * Registering this drops the frame instead of delivering it: the previous\n * behaviour handed `onMessage` the raw `string` announced as your message\n * type, so the failure surfaced later, at the first property access, with\n * nothing left pointing at the parse. Leave it out and that behaviour is\n * kept, with a one-time warning in development builds.\n */\n onParseError?: (error: unknown, raw: string) => void;\n /**\n * Schema every decoded frame must satisfy, from zod, valibot, arktype or\n * anything else exposing `~standard` or `.safeParse`.\n *\n * Without it nothing changes: the payload reaches `onMessage` announced as\n * `T` on the strength of the type argument alone, which is a promise about\n * the server that TypeScript cannot keep. With it, a frame that does not\n * match is **not** delivered — the same rule `onParseError` already follows —\n * and `onValidationError` hears why. The value delivered is the schema's\n * output, so coercions and defaults are honoured.\n *\n * When `parser` is also supplied, it decodes first and the schema validates\n * what it returned.\n *\n * The validation must be synchronous. A frame is decoded inside the\n * `message` handler and delivered from it, so an async schema would deliver\n * frames in whatever order their validations settled; that case is reported\n * through `onValidationError` instead of awaited.\n */\n schema?: SchemaLike<T>;\n /**\n * A frame was decoded but the `schema` refused it, so it was dropped.\n *\n * The one signal that does not depend on how the app's bundler resolves\n * `process`: the one-time development warning behind `onParseError` needs\n * `isDevBuild()` to be able to answer, and this callback is the app's own.\n */\n onValidationError?: (issues: SchemaIssue[], raw: string) => void;\n /**\n * The URL function threw or rejected, so no connection was attempted.\n *\n * `onError` cannot carry this: it receives the `EventSource` `Event`, and a\n * URL that never resolved never had an `EventSource`.\n */\n onUrlError?: (error: unknown) => void;\n /**\n * Whether a URL-resolution failure is worth another attempt. Default: always.\n *\n * Return `false` for failures no backoff can fix — a `401` or a `403` when\n * fetching a ticket is a session decision, not a network blip — and the stream\n * stops at `status: \"error\"` instead of spending `maxRetries` on it.\n */\n shouldRetryUrl?: (error: unknown) => boolean;\n onOpen?: () => void;\n onMessage?: (message: EventStreamMessage<T>) => void;\n onError?: (error: Event) => void;\n onStatusChange?: (status: EventStreamStatus) => void;\n}\n\nexport interface EventStreamController {\n close: () => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /** Current connection status. */\n readonly status: EventStreamStatus;\n}\n\n/**\n * Open a Server-Sent Events stream with automatic exponential-backoff reconnect.\n *\n * Heartbeat events (default `\"ping\"`) keep the socket alive without firing\n * `onMessage`. Pass `withCredentials: true` when the backend authenticates via\n * cookies. Call `close()` from the returned controller to tear down.\n *\n * When `url` is a function it is called before every connection, so a\n * reconnect presents a fresh credential instead of the one that expired. A\n * resolution still pending when `close()` or `reconnect()` runs is discarded.\n *\n * @param url - Full SSE endpoint URL, or a function returning it per connection.\n * @param options - Stream configuration and callbacks.\n * @returns A controller exposing `close`, `reconnect` and the current `status`.\n */\nexport function createEventStream<T = unknown>(\n url: EventStreamUrl,\n options: CreateEventStreamOptions<T> = {},\n): EventStreamController {\n const {\n withCredentials = false,\n namedEvents = [],\n heartbeatEvents = [\"ping\"],\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n parser,\n onOpen,\n onMessage,\n onError,\n onParseError,\n schema,\n onValidationError,\n onUrlError,\n shouldRetryUrl = () => true,\n onStatusChange,\n } = options;\n\n let source: EventSource | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let retries = 0;\n let status: EventStreamStatus = \"idle\";\n let closed = false;\n let attempt = 0;\n\n function setStatus(next: EventStreamStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function emit(eventName: string, event: MessageEvent): void {\n if (heartbeatEvents.includes(eventName)) return;\n const decoded = decodeFrame<T>(\n typeof event.data === \"string\" ? event.data : \"\",\n \"createEventStream\",\n { parser, onParseError, schema, onValidationError },\n );\n if (!decoded.delivered) return;\n onMessage?.({\n event: eventName,\n data: decoded.data,\n id: event.lastEventId || undefined,\n raw: event,\n });\n }\n\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n setStatus(\"error\");\n return;\n }\n const delay = Math.min(initialBackoff * 2 ** retries, maxBackoff);\n retries += 1;\n retryTimer = setTimeout(connect, delay);\n }\n\n function failUrl(error: unknown): void {\n onUrlError?.(error);\n if (!shouldRetryUrl(error)) {\n setStatus(\"error\");\n return;\n }\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n function connect(): void {\n if (closed) return;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"connecting\");\n attempt += 1;\n if (typeof url === \"string\") {\n open(url);\n return;\n }\n const current = attempt;\n Promise.resolve()\n .then(url)\n .then(\n (resolved) => {\n if (!closed && current === attempt) open(resolved);\n },\n (error: unknown) => {\n if (!closed && current === attempt) failUrl(error);\n },\n );\n }\n\n function open(target: string): void {\n const es = new EventSource(target, { withCredentials });\n source = es;\n\n es.onopen = () => {\n retries = 0;\n setStatus(\"open\");\n onOpen?.();\n };\n\n es.onmessage = (event) => emit(\"message\", event);\n for (const name of namedEvents) {\n es.addEventListener(name, (event) => emit(name, event as MessageEvent));\n }\n for (const name of heartbeatEvents) {\n es.addEventListener(name, () => {\n /* heartbeat — keep socket alive */\n });\n }\n\n es.onerror = (event) => {\n onError?.(event);\n es.close();\n source = null;\n setStatus(\"closed\");\n scheduleReconnect();\n };\n }\n\n function close(): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"closed\");\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n closed = false;\n connect();\n }\n\n connect();\n\n return {\n close,\n reconnect,\n get status() {\n return status;\n },\n };\n}\n"],"mappings":";;AAkIA,SAAgBA,EACZ,GACA,IAAuC,CAAC,GACnB;CACrB,IAAM,EACF,qBAAkB,IAClB,iBAAc,CAAC,GACf,qBAAkB,CAAC,MAAM,GACzB,gBAAa,IACb,oBAAiB,KACjB,gBAAa,KACb,WACA,WACA,cACA,YACA,iBACA,WACA,sBACA,eACA,0BAAuB,IACvB,sBACAC,GAEAC,IAA6B,MAC7BC,IAAmD,MACnDC,IAAU,GACVC,IAA4B,QAC5BC,IAAS,IACTC,IAAU;CAEd,SAASC,EAAU,GAA+B;EAC9C,AAAIH,MAAWI,MACf,IAASA,GACTC,IAAiBD,CAAI;CACzB;CAEA,SAASE,EAAK,GAAmB,GAA2B;EACxD,IAAIC,EAAgB,SAASC,CAAS,GAAG;EACzC,IAAMC,IAAUC,EACZ,OAAOC,EAAM,QAAS,WAAWA,EAAM,OAAO,IAC9C,qBACA;GAAE;GAAQ;GAAc;GAAQ;EAAkB,CACtD;EACA,AAAKF,EAAQ,aACbG,IAAY;GACR,OAAOJ;GACP,MAAMC,EAAQ;GACd,IAAIE,EAAM,eAAe,KAAA;GACzB,KAAKA;EACT,CAAC;CACL;CAEA,SAASE,IAA0B;EAC/B,IAAIZ,GAAQ;EACZ,IAAIF,KAAWe,GAAY;GACvB,EAAU,OAAO;GACjB;EACJ;EACA,IAAMC,IAAQ,KAAK,IAAIC,IAAiB,KAAKjB,GAASkB,CAAU;EAEhE,AADA,KAAW,GACX,IAAa,WAAWC,GAASH,CAAK;CAC1C;CAEA,SAASI,EAAQ,GAAsB;EAEnC,AADAC,IAAaC,CAAK,GACbC,EAAeD,CAAK,KAIzBlB,EAAU,QAAQ,GAClBU,EAAkB,KAJdV,EAAU,OAAO;CAKzB;CAEA,SAASe,IAAgB;EACrB,IAAIjB,GAAQ;EAOZ,IANA,AAEIJ,OADAA,EAAO,MAAM,GACJ,OAEbM,EAAU,YAAY,GACtB,KAAW,GACP,OAAOoB,KAAQ,UAAU;GACzB,EAAKA,CAAG;GACR;EACJ;EACA,IAAMC,IAAUtB;EAChB,QAAQ,QAAQ,CAAC,CACZ,KAAKqB,CAAG,CAAC,CACT,MACI,MAAa;GACV,AAAI,CAACtB,KAAUuB,MAAYtB,KAASuB,EAAKC,CAAQ;EACrD,IACC,MAAmB;GAChB,AAAI,CAACzB,KAAUuB,MAAYtB,KAASiB,EAAQE,CAAK;EACrD,CACJ;CACR;CAEA,SAASI,EAAK,GAAsB;EAChC,IAAME,IAAK,IAAI,YAAYC,GAAQ,EAAE,mBAAgB,CAAC;EAStD,AARA,IAASD,GAET,EAAG,eAAe;GAGd,AAFA,IAAU,GACVxB,EAAU,MAAM,GAChB0B,IAAS;EACb,GAEA,EAAG,aAAa,MAAUvB,EAAK,WAAWK,CAAK;EAC/C,KAAK,IAAMmB,KAAQC,GACf,EAAG,iBAAiBD,IAAO,MAAUxB,EAAKwB,GAAMnB,CAAqB,CAAC;EAE1E,KAAK,IAAMmB,KAAQvB,GACf,EAAG,iBAAiBuB,SAAY,CAEhC,CAAC;EAGL,EAAG,WAAW,MAAU;GAKpB,AAJAE,IAAUrB,CAAK,GACfgB,EAAG,MAAM,GACT,IAAS,MACTxB,EAAU,QAAQ,GAClBU,EAAkB;EACtB;CACJ;CAEA,SAASoB,IAAc;EAWnB,AAVA,IAAS,IACT,AAEInC,OADA,aAAaA,CAAU,GACV,OAEjB,IAAU,GACV,AAEID,OADAA,EAAO,MAAM,GACJ,OAEbM,EAAU,QAAQ;CACtB;CAEA,SAAS+B,IAAkB;EAOvB,AANA,AAEIpC,OADA,aAAaA,CAAU,GACV,OAEjB,IAAU,GACV,IAAS,IACToB,EAAQ;CACZ;CAIA,OAFAA,EAAQ,GAED;EACH;EACA;EACA,IAAI,SAAS;GACT,OAAOlB;EACX;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"create-event-stream.js","names":["createEventStream","options","source","retryTimer","retries","status","closed","attempt","boundKey","setStatus","next","onStatusChange","sessionChanged","sessionKey","emit","from","heartbeatEvents","eventName","decoded","decodeFrame","event","onMessage","scheduleReconnect","maxRetries","delay","initialBackoff","maxBackoff","connect","failUrl","onUrlError","error","shouldRetryUrl","url","current","resolved","open","es","target","onOpen","name","namedEvents","onError","close","reconnect"],"sources":["../../src/sse/create-event-stream.ts"],"sourcesContent":["/**\n * @tempest-limits function-lines — the body is the SSE line protocol — accumulate\n * `data:` lines until a blank line, track `id:` for Last-Event-ID, honour `retry:` —\n * plus the reconnect that uses the id it just tracked.\n */\nimport { decodeFrame } from \"../utils/json-frame\";\nimport type { SchemaIssue, SchemaLike } from \"../utils/schema-like\";\nexport type EventStreamStatus = \"idle\" | \"connecting\" | \"open\" | \"closed\" | \"error\";\n\n/**\n * Where the stream connects: a fixed URL, or a function resolved again before\n * every connection, the first one and each reconnect.\n *\n * The function form exists for short-lived credentials carried in the URL,\n * such as the `?ticket=` of the `tempest-fastapi-sdk` SSE router. `EventSource`\n * cannot send headers, so the credential has to ride in the query, and one that\n * expires makes a fixed URL a trap: the reconnect after the expiry presents the\n * same dead credential, gets a `401`, and burns every retry on it while the user\n * is still signed in.\n */\nexport type EventStreamUrl = string | (() => string | Promise<string>);\n\n/**\n * Identifies the session a stream belongs to: the signed-in user's id, an\n * auth epoch, `null` when signed out.\n *\n * A primitive on purpose. The hook form lists it in its effect dependencies,\n * and an object built inline would be a new identity on every render, so the\n * stream would reopen on every render.\n */\nexport type SessionKey = string | number | boolean | null | undefined;\n\nexport interface EventStreamMessage<T> {\n /** Server-named event (default `\"message\"`). */\n event: string;\n /** Parsed payload — validated when `schema` is set, JSON-decoded when possible, raw string otherwise. */\n data: T;\n /** Server-supplied id, if any. */\n id?: string;\n /** Raw `MessageEvent` for advanced cases. */\n raw: MessageEvent;\n}\n\nexport interface CreateEventStreamOptions<T> {\n /** Send cookies with the EventSource handshake. Default: false. */\n withCredentials?: boolean;\n /** Subscribe to named events in addition to `message`. */\n namedEvents?: readonly string[];\n /** Treat these named events as heartbeat-only (no callback). Default: `[\"ping\"]`. */\n heartbeatEvents?: readonly string[];\n /** Max reconnect attempts. Default: 10. Pass 0 to disable reconnect. */\n maxRetries?: number;\n /** Initial backoff in ms; doubles per attempt, capped at `maxBackoff`. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff in ms. Default: 30000. */\n maxBackoff?: number;\n /** Parse `event.data`. Defaults to JSON with raw-string fallback. */\n parser?: (raw: string) => T;\n /**\n * A frame arrived that is not valid JSON, and no `parser` was supplied.\n *\n * Registering this drops the frame instead of delivering it: the previous\n * behaviour handed `onMessage` the raw `string` announced as your message\n * type, so the failure surfaced later, at the first property access, with\n * nothing left pointing at the parse. Leave it out and that behaviour is\n * kept, with a one-time warning in development builds.\n */\n onParseError?: (error: unknown, raw: string) => void;\n /**\n * Schema every decoded frame must satisfy, from zod, valibot, arktype or\n * anything else exposing `~standard` or `.safeParse`.\n *\n * Without it nothing changes: the payload reaches `onMessage` announced as\n * `T` on the strength of the type argument alone, which is a promise about\n * the server that TypeScript cannot keep. With it, a frame that does not\n * match is **not** delivered — the same rule `onParseError` already follows —\n * and `onValidationError` hears why. The value delivered is the schema's\n * output, so coercions and defaults are honoured.\n *\n * When `parser` is also supplied, it decodes first and the schema validates\n * what it returned.\n *\n * The validation must be synchronous. A frame is decoded inside the\n * `message` handler and delivered from it, so an async schema would deliver\n * frames in whatever order their validations settled; that case is reported\n * through `onValidationError` instead of awaited.\n */\n schema?: SchemaLike<T>;\n /**\n * A frame was decoded but the `schema` refused it, so it was dropped.\n *\n * The one signal that does not depend on how the app's bundler resolves\n * `process`: the one-time development warning behind `onParseError` needs\n * `isDevBuild()` to be able to answer, and this callback is the app's own.\n */\n onValidationError?: (issues: SchemaIssue[], raw: string) => void;\n /**\n * The URL function threw or rejected, so no connection was attempted.\n *\n * `onError` cannot carry this: it receives the `EventSource` `Event`, and a\n * URL that never resolved never had an `EventSource`.\n */\n onUrlError?: (error: unknown) => void;\n /**\n * Read the current session key; the stream belongs to the session that was\n * current when it connected.\n *\n * The server cannot end the stream for you. The `tempest-fastapi-sdk` SSE\n * router checks the ticket only when the stream opens, and neither logout\n * nor refresh-token revocation touches an open stream: it lives until the\n * client leaves. So a tab that switches from user A to user B without\n * closing the stream keeps receiving A's events under B.\n *\n * With this set, the key is read when each connection starts, again when\n * its URL resolved, and before every frame is delivered. A frame that\n * arrives after the key changed is dropped, never delivered, and the stream\n * reconnects for the session now current — with a fresh ticket, for the\n * ticket stream. A URL resolved while the key changed is discarded the same\n * way, since the ticket inside it may belong to either session.\n *\n * The check runs when a frame arrives: a stream that stays quiet holds its\n * connection until the next frame or until `close()`. The hook form closes\n * it as soon as the key changes.\n *\n * Keys are compared with `Object.is`. Leave it out and nothing changes.\n */\n sessionKey?: () => SessionKey;\n /**\n * Whether a URL-resolution failure is worth another attempt. Default: always.\n *\n * Return `false` for failures no backoff can fix — a `401` or a `403` when\n * fetching a ticket is a session decision, not a network blip — and the stream\n * stops at `status: \"error\"` instead of spending `maxRetries` on it.\n */\n shouldRetryUrl?: (error: unknown) => boolean;\n onOpen?: () => void;\n onMessage?: (message: EventStreamMessage<T>) => void;\n onError?: (error: Event) => void;\n onStatusChange?: (status: EventStreamStatus) => void;\n}\n\nexport interface EventStreamController {\n close: () => void;\n /** Force an immediate reconnect, resetting the retry counter. */\n reconnect: () => void;\n /** Current connection status. */\n readonly status: EventStreamStatus;\n}\n\n/**\n * Open a Server-Sent Events stream with automatic exponential-backoff reconnect.\n *\n * Heartbeat events (default `\"ping\"`) keep the socket alive without firing\n * `onMessage`. Pass `withCredentials: true` when the backend authenticates via\n * cookies. Call `close()` from the returned controller to tear down.\n *\n * When `url` is a function it is called before every connection, so a\n * reconnect presents a fresh credential instead of the one that expired. A\n * resolution still pending when `close()` or `reconnect()` runs is discarded, and\n * one that has not started yet is never made: a stream closed in the same tick\n * it was created asks for no URL — no ticket request, for the ticket stream.\n *\n * Pass `sessionKey` to bind the stream to the session it opened under: once\n * the key changes, no frame of the previous session reaches `onMessage`, and\n * the stream reconnects for the new one.\n *\n * @param url - Full SSE endpoint URL, or a function returning it per connection.\n * @param options - Stream configuration and callbacks.\n * @returns A controller exposing `close`, `reconnect` and the current `status`.\n */\nexport function createEventStream<T = unknown>(\n url: EventStreamUrl,\n options: CreateEventStreamOptions<T> = {},\n): EventStreamController {\n const {\n withCredentials = false,\n namedEvents = [],\n heartbeatEvents = [\"ping\"],\n maxRetries = 10,\n initialBackoff = 1000,\n maxBackoff = 30000,\n parser,\n onOpen,\n onMessage,\n onError,\n onParseError,\n schema,\n onValidationError,\n onUrlError,\n shouldRetryUrl = () => true,\n sessionKey,\n onStatusChange,\n } = options;\n\n let source: EventSource | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let retries = 0;\n let status: EventStreamStatus = \"idle\";\n let closed = false;\n let attempt = 0;\n let boundKey: SessionKey;\n\n function setStatus(next: EventStreamStatus): void {\n if (status === next) return;\n status = next;\n onStatusChange?.(next);\n }\n\n function sessionChanged(): boolean {\n return sessionKey !== undefined && !Object.is(sessionKey(), boundKey);\n }\n\n /**\n * Deliver one frame, unless it no longer belongs to this stream.\n *\n * A frame from a source other than the current one — closed by `close()`,\n * replaced by a reconnect — is ignored: it would otherwise reach `onMessage`\n * after the caller let go of the stream, and the session check below would\n * reopen a controller that `close()` already ended. A frame that arrives\n * after `sessionKey` changed is dropped and the stream reconnects for the\n * session now current.\n *\n * @param from - The `EventSource` the frame came from.\n * @param eventName - The SSE event name.\n * @param event - The raw message event.\n */\n function emit(from: EventSource, eventName: string, event: MessageEvent): void {\n if (from !== source || heartbeatEvents.includes(eventName)) return;\n if (sessionChanged()) {\n reconnect();\n return;\n }\n const decoded = decodeFrame<T>(\n typeof event.data === \"string\" ? event.data : \"\",\n \"createEventStream\",\n { parser, onParseError, schema, onValidationError },\n );\n if (!decoded.delivered) return;\n onMessage?.({\n event: eventName,\n data: decoded.data,\n id: event.lastEventId || undefined,\n raw: event,\n });\n }\n\n function scheduleReconnect(): void {\n if (closed) return;\n if (retries >= maxRetries) {\n setStatus(\"error\");\n return;\n }\n const delay = Math.min(initialBackoff * 2 ** retries, maxBackoff);\n retries += 1;\n retryTimer = setTimeout(connect, delay);\n }\n\n function failUrl(error: unknown): void {\n onUrlError?.(error);\n if (!shouldRetryUrl(error)) {\n setStatus(\"error\");\n return;\n }\n setStatus(\"closed\");\n scheduleReconnect();\n }\n\n function connect(): void {\n if (closed) return;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"connecting\");\n attempt += 1;\n boundKey = sessionKey?.();\n if (typeof url === \"string\") {\n open(url);\n return;\n }\n const current = attempt;\n Promise.resolve()\n .then(() => (closed || current !== attempt ? null : url()))\n .then(\n (resolved) => {\n if (resolved === null || closed || current !== attempt) return;\n if (sessionChanged()) {\n connect();\n return;\n }\n open(resolved);\n },\n (error: unknown) => {\n if (!closed && current === attempt) failUrl(error);\n },\n );\n }\n\n function open(target: string): void {\n const es = new EventSource(target, { withCredentials });\n source = es;\n\n es.onopen = () => {\n retries = 0;\n setStatus(\"open\");\n onOpen?.();\n };\n\n es.onmessage = (event) => emit(es, \"message\", event);\n for (const name of namedEvents) {\n es.addEventListener(name, (event) => emit(es, name, event as MessageEvent));\n }\n for (const name of heartbeatEvents) {\n es.addEventListener(name, () => {\n /* heartbeat — keep socket alive */\n });\n }\n\n es.onerror = (event) => {\n onError?.(event);\n es.close();\n source = null;\n setStatus(\"closed\");\n scheduleReconnect();\n };\n }\n\n function close(): void {\n closed = true;\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n if (source) {\n source.close();\n source = null;\n }\n setStatus(\"closed\");\n }\n\n function reconnect(): void {\n if (retryTimer) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n retries = 0;\n closed = false;\n connect();\n }\n\n connect();\n\n return {\n close,\n reconnect,\n get status() {\n return status;\n },\n };\n}\n"],"mappings":";;AA0KA,SAAgBA,EACZ,GACA,IAAuC,CAAC,GACnB;CACrB,IAAM,EACF,qBAAkB,IAClB,iBAAc,CAAC,GACf,qBAAkB,CAAC,MAAM,GACzB,gBAAa,IACb,oBAAiB,KACjB,gBAAa,KACb,WACA,WACA,cACA,YACA,iBACA,WACA,sBACA,eACA,0BAAuB,IACvB,eACA,sBACAC,GAEAC,IAA6B,MAC7BC,IAAmD,MACnDC,IAAU,GACVC,IAA4B,QAC5BC,IAAS,IACTC,IAAU,GACVC;CAEJ,SAASC,EAAU,GAA+B;EAC9C,AAAIJ,MAAWK,MACf,IAASA,GACTC,IAAiBD,CAAI;CACzB;CAEA,SAASE,IAA0B;EAC/B,OAAOC,MAAe,KAAA,KAAa,CAAC,OAAO,GAAGA,EAAW,GAAGL,CAAQ;CACxE;CAgBA,SAASM,EAAK,GAAmB,GAAmB,GAA2B;EAC3E,IAAIC,MAASb,KAAUc,EAAgB,SAASC,CAAS,GAAG;EAC5D,IAAIL,EAAe,GAAG;GAClB,EAAU;GACV;EACJ;EACA,IAAMM,IAAUC,EACZ,OAAOC,EAAM,QAAS,WAAWA,EAAM,OAAO,IAC9C,qBACA;GAAE;GAAQ;GAAc;GAAQ;EAAkB,CACtD;EACA,AAAKF,EAAQ,aACbG,IAAY;GACR,OAAOJ;GACP,MAAMC,EAAQ;GACd,IAAIE,EAAM,eAAe,KAAA;GACzB,KAAKA;EACT,CAAC;CACL;CAEA,SAASE,IAA0B;EAC/B,IAAIhB,GAAQ;EACZ,IAAIF,KAAWmB,GAAY;GACvB,EAAU,OAAO;GACjB;EACJ;EACA,IAAMC,IAAQ,KAAK,IAAIC,IAAiB,KAAKrB,GAASsB,CAAU;EAEhE,AADA,KAAW,GACX,IAAa,WAAWC,GAASH,CAAK;CAC1C;CAEA,SAASI,EAAQ,GAAsB;EAEnC,AADAC,IAAaC,CAAK,GACbC,EAAeD,CAAK,KAIzBrB,EAAU,QAAQ,GAClBa,EAAkB,KAJdb,EAAU,OAAO;CAKzB;CAEA,SAASkB,IAAgB;EACrB,IAAIrB,GAAQ;EAQZ,IAPA,AAEIJ,OADAA,EAAO,MAAM,GACJ,OAEbO,EAAU,YAAY,GACtB,KAAW,GACX,IAAWI,IAAa,GACpB,OAAOmB,KAAQ,UAAU;GACzB,EAAKA,CAAG;GACR;EACJ;EACA,IAAMC,IAAU1B;EAChB,QAAQ,QAAQ,CAAC,CACZ,WAAYD,KAAU2B,MAAY1B,IAAU,OAAOyB,EAAI,CAAE,CAAC,CAC1D,MACI,MAAa;GACV,AAAIE,MAAa,QAAQ5B,KAAU2B,MAAY1B,MAC3CK,EAAe,IACfe,EAAQ,IAGZQ,EAAKD,CAAQ;EACjB,IACC,MAAmB;GAChB,AAAI,CAAC5B,KAAU2B,MAAY1B,KAASqB,EAAQE,CAAK;EACrD,CACJ;CACR;CAEA,SAASK,EAAK,GAAsB;EAChC,IAAMC,IAAK,IAAI,YAAYC,GAAQ,EAAE,mBAAgB,CAAC;EAStD,AARA,IAASD,GAET,EAAG,eAAe;GAGd,AAFA,IAAU,GACV3B,EAAU,MAAM,GAChB6B,IAAS;EACb,GAEA,EAAG,aAAa,MAAUxB,EAAKsB,GAAI,WAAWhB,CAAK;EACnD,KAAK,IAAMmB,KAAQC,GACf,EAAG,iBAAiBD,IAAO,MAAUzB,EAAKsB,GAAIG,GAAMnB,CAAqB,CAAC;EAE9E,KAAK,IAAMmB,KAAQvB,GACf,EAAG,iBAAiBuB,SAAY,CAEhC,CAAC;EAGL,EAAG,WAAW,MAAU;GAKpB,AAJAE,IAAUrB,CAAK,GACfgB,EAAG,MAAM,GACT,IAAS,MACT3B,EAAU,QAAQ,GAClBa,EAAkB;EACtB;CACJ;CAEA,SAASoB,IAAc;EAWnB,AAVA,IAAS,IACT,AAEIvC,OADA,aAAaA,CAAU,GACV,OAEjB,IAAU,GACV,AAEID,OADAA,EAAO,MAAM,GACJ,OAEbO,EAAU,QAAQ;CACtB;CAEA,SAASkC,IAAkB;EAOvB,AANA,AAEIxC,OADA,aAAaA,CAAU,GACV,OAEjB,IAAU,GACV,IAAS,IACTwB,EAAQ;CACZ;CAIA,OAFAA,EAAQ,GAED;EACH;EACA;EACA,IAAI,SAAS;GACT,OAAOtB;EACX;CACJ;AACJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../http/errors.cjs"),t=require("./create-event-stream.cjs"),
|
|
1
|
+
const e=require("../http/errors.cjs"),t=require("../auth/session-identity.cjs"),n=require("./create-event-stream.cjs"),r=require("./use-event-stream.cjs");let i=require("react");function a(t){return e.isApiError(t)&&e.isRetriableStatus(t.status)}function o(e){let{client:t,prefix:n=`/sse`,ticketParam:r=`ticket`}=e;return async()=>{let e=await t.post(`${n}/ticket`);if(typeof e?.ticket!=`string`||e.ticket===``)throw TypeError(`createTicketEventStream: POST ${n}/ticket returned no "ticket" string.`);return t.url(`${n}/stream`,{[r]:e.ticket})}}function s(e){let{client:r,prefix:i,ticketParam:s,sessionKey:l,shouldRetryUrl:u=a,...d}=e,f=l===void 0?t.sessionIdentityOf(r):void 0,p=n.createEventStream(o({client:r,prefix:i,ticketParam:s}),{...d,sessionKey:l??f?.current,shouldRetryUrl:u});return f?c(p,f):p}function c(e,t){let n=t.current(),r=null;function i(){r??=t.subscribe(()=>{let r=t.current();Object.is(r,n)||(n=r,r===null?e.close():e.reconnect())})}return i(),n===null&&e.close(),{close:()=>{r?.(),r=null,e.close()},reconnect:()=>{n=t.current(),i(),e.reconnect()},get status(){return e.status}}}function l(e){let t=(0,i.useCallback)(t=>e?.subscribe(t)??(()=>void 0),[e]),n=()=>e?.current();return(0,i.useSyncExternalStore)(t,n,n)}function u(e){let{client:n,prefix:i,ticketParam:s,enabled:c=!0,sessionKey:u,shouldRetryUrl:d=a,...f}=e,p=l(u===void 0?t.sessionIdentityOf(n):void 0);return r.useEventStream(o({client:n,prefix:i,ticketParam:s}),{...f,enabled:c&&p!==null,sessionKey:u??p,shouldRetryUrl:d})}exports.createTicketEventStream=s,exports.isRetriableTicketError=a,exports.useTicketEventStream=u;
|
|
2
2
|
//# sourceMappingURL=ticket-event-stream.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ticket-event-stream.cjs","names":["isApiError","isRetriableStatus","createEventStream","useEventStream","require_errors","require_create_event_stream","require_use_event_stream","isRetriableTicketError","error","ticketStreamUrl","source","response","client","prefix","ticketParam","createTicketEventStream","rest","options","useTicketEventStream"],"sources":["../../src/sse/ticket-event-stream.ts"],"sourcesContent":["import { isApiError, isRetriableStatus } from \"../http/errors\";\nimport type { ApiClient } from \"../http/types\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamController,\n} from \"./create-event-stream\";\nimport {\n useEventStream,\n type UseEventStreamOptions,\n type UseEventStreamResult,\n} from \"./use-event-stream\";\n\n/** Body of `POST <prefix>/ticket` on the `tempest-fastapi-sdk` SSE router. */\nexport interface SseTicketResponse {\n /** Signed stream ticket, presented as a query param when opening the stream. */\n ticket: string;\n /** Seconds the ticket is accepted for opening a stream. */\n expires_in: number;\n}\n\n/** Where the ticket comes from and how the stream URL is built. */\nexport interface TicketEventStreamSource {\n /**\n * Authenticated client the ticket is requested through, so it carries the\n * `Authorization` header or the session cookie, the CSRF header, and the\n * 401 refresh-and-replay that a hand-rolled `fetch` would lose.\n */\n client: Pick<ApiClient, \"post\" | \"url\">;\n /** Router prefix, relative to the client's base URL. Default: `\"/sse\"`. */\n prefix?: string;\n /** Query param the stream reads the ticket from. Default: `\"ticket\"`. */\n ticketParam?: string;\n}\n\nexport type CreateTicketEventStreamOptions<T> = TicketEventStreamSource &\n CreateEventStreamOptions<T>;\n\nexport type UseTicketEventStreamOptions<T> = TicketEventStreamSource & UseEventStreamOptions<T>;\n\n/**\n * Whether a failure to obtain a ticket is worth another attempt.\n *\n * Only a failure the backoff can outlast is: no response at all, a timeout, a\n * rate limit, a `5xx`. A `401` reached the caller after the client already\n * tried its refresh, and a `403` (`ACCOUNT_INACTIVE`) is the backend saying no;\n * both are session decisions, and retrying them only delays the error state the\n * app has to show. Anything that is not an API error is a contract mismatch,\n * which a retry cannot fix either.\n *\n * @param error - What the ticket request threw.\n * @returns Whether to schedule a reconnect.\n */\nexport function isRetriableTicketError(error: unknown): boolean {\n return isApiError(error) && isRetriableStatus(error.status);\n}\n\n/**\n * Build the URL function that requests a ticket and points at the stream.\n *\n * A fresh ticket is requested for every connection rather than cached for its\n * `expires_in`. Every connection after the first follows a failure, and the\n * failure may have been the ticket itself; reusing it would spend the retries\n * on a credential that is already refused, while a new ticket costs one `POST`\n * per reconnect, which the backoff already spaces out.\n *\n * @param source - Client, router prefix and ticket param name.\n * @returns A function resolving the stream URL with a fresh ticket.\n * @throws TypeError When the ticket response has no `ticket` string.\n */\nfunction ticketStreamUrl(source: TicketEventStreamSource): () => Promise<string> {\n const { client, prefix = \"/sse\", ticketParam = \"ticket\" } = source;\n return async () => {\n const response = await client.post<SseTicketResponse>(`${prefix}/ticket`);\n if (typeof response?.ticket !== \"string\" || response.ticket === \"\") {\n throw new TypeError(\n `createTicketEventStream: POST ${prefix}/ticket returned no \"ticket\" string.`,\n );\n }\n return client.url(`${prefix}/stream`, { [ticketParam]: response.ticket });\n };\n}\n\n/**\n * Open the ticket-authenticated stream of the `tempest-fastapi-sdk` SSE router.\n *\n * `POST <prefix>/ticket` through the authenticated client, then\n * `GET <prefix>/stream?ticket=…` — and again for every reconnect, because the\n * ticket only opens streams for `expires_in` seconds and a reconnect after that\n * with the old one is a `401`. A ticket request refused with a status no\n * backoff fixes (`401`, `403 ACCOUNT_INACTIVE`) stops the stream at\n * `status: \"error\"` and reaches `onUrlError`; pass `shouldRetryUrl` to replace\n * {@link isRetriableTicketError}.\n *\n * The access token never enters the URL: it travels as the client's header (or\n * cookie) on the ticket request, and the ticket in the URL opens that stream\n * and nothing else.\n *\n * @example\n * const stream = createTicketEventStream<Notification>({\n * client: api,\n * onMessage: ({ data }) => addNotification(data),\n * onUrlError: (error) => toast.error(describeApiError(error)),\n * });\n *\n * @param options - Ticket source plus every {@link createEventStream} option.\n * @returns The stream controller.\n */\nexport function createTicketEventStream<T = unknown>(\n options: CreateTicketEventStreamOptions<T>,\n): EventStreamController {\n const {\n client,\n prefix,\n ticketParam,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n return createEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n shouldRetryUrl,\n });\n}\n\n/**\n * React form of {@link createTicketEventStream}: same ticket per connection,\n * lifecycle tied to the component like {@link useEventStream}.\n *\n * Changing `client`, `prefix` or `ticketParam` does not drop an open stream:\n * the next connection uses the new values, and `reconnect()` applies them now.\n * Reopening on identity would reconnect on every render for a client built\n * inline.\n *\n * @example\n * const { status } = useTicketEventStream<Notification>({\n * client: api,\n * enabled: isAuthenticated,\n * schema: notificationSchema,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @param options - Ticket source plus every {@link useEventStream} option.\n * @returns Status, last message and `reconnect`.\n */\nexport function useTicketEventStream<T = unknown>(\n options: UseTicketEventStreamOptions<T>,\n): UseEventStreamResult<T> {\n const {\n client,\n prefix,\n ticketParam,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n return useEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n shouldRetryUrl,\n });\n}\n"],"mappings":"A,iHAqDA,SAAgBO,EAAuB,EAAyB,CAC5D,OAAOP,EAAAA,WAAWQ,CAAK,GAAKP,EAAAA,kBAAkBO,EAAM,MAAM,CAC9D,CAeA,SAASC,EAAgB,EAAwD,CAC7E,GAAM,CAAE,SAAQ,SAAS,OAAQ,cAAc,UAAaC,EAC5D,OAAO,SAAY,CACf,IAAMC,EAAW,MAAMC,EAAO,KAAwB,GAAGC,EAAO,QAAQ,EACxE,GAAI,OAAOF,GAAU,QAAW,UAAYA,EAAS,SAAW,GAC5D,MAAU,UACN,iCAAiCE,EAAO,qCAC5C,EAEJ,OAAOD,EAAO,IAAI,GAAGC,EAAO,SAAU,EAAGC,GAAcH,EAAS,MAAO,CAAC,CAC5E,CACJ,CA2BA,SAAgBI,EACZ,EACqB,CACrB,GAAM,CACF,SACA,SACA,cACA,iBAAiBR,EACjB,GAAGS,GACHC,EACJ,OAAOf,EAAAA,kBAAqBO,EAAgB,CAAE,SAAQ,SAAQ,aAAY,CAAC,EAAG,CAC1E,GAAGO,EACH,gBACJ,CAAC,CACL,CAsBA,SAAgBE,EACZ,EACuB,CACvB,GAAM,CACF,SACA,SACA,cACA,iBAAiBX,EACjB,GAAGS,GACHC,EACJ,OAAOd,EAAAA,eAAkBM,EAAgB,CAAE,SAAQ,SAAQ,aAAY,CAAC,EAAG,CACvE,GAAGO,EACH,gBACJ,CAAC,CACL,C"}
|
|
1
|
+
{"version":3,"file":"ticket-event-stream.cjs","names":["isApiError","isRetriableStatus","sessionIdentityOf","createEventStream","useCallback","useSyncExternalStore","useEventStream","require_errors","require_session_identity","require_create_event_stream","require_use_event_stream","react","isRetriableTicketError","error","ticketStreamUrl","source","response","client","prefix","ticketParam","createTicketEventStream","rest","options","identity","sessionKey","controller","followSession","bound","unsubscribe","follow","next","useClientSession","subscribe","listener","read","useTicketEventStream","clientSession","enabled"],"sources":["../../src/sse/ticket-event-stream.ts"],"sourcesContent":["import { useCallback, useSyncExternalStore } from \"react\";\nimport { sessionIdentityOf, type SessionIdentity } from \"../auth/session-identity\";\nimport { isApiError, isRetriableStatus } from \"../http/errors\";\nimport type { ApiClient } from \"../http/types\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamController,\n} from \"./create-event-stream\";\nimport {\n useEventStream,\n type UseEventStreamOptions,\n type UseEventStreamResult,\n} from \"./use-event-stream\";\n\n/** Body of `POST <prefix>/ticket` on the `tempest-fastapi-sdk` SSE router. */\nexport interface SseTicketResponse {\n /** Signed stream ticket, presented as a query param when opening the stream. */\n ticket: string;\n /** Seconds the ticket is accepted for opening a stream. */\n expires_in: number;\n}\n\n/** Where the ticket comes from and how the stream URL is built. */\nexport interface TicketEventStreamSource {\n /**\n * Authenticated client the ticket is requested through, so it carries the\n * `Authorization` header or the session cookie, the CSRF header, and the\n * 401 refresh-and-replay that a hand-rolled `fetch` would lose.\n *\n * The `api` of `createTempestAuth` also carries the session it acts for,\n * and the stream binds to it when `sessionKey` is not passed — see\n * {@link useTicketEventStream}.\n */\n client: Pick<ApiClient, \"post\" | \"url\">;\n /** Router prefix, relative to the client's base URL. Default: `\"/sse\"`. */\n prefix?: string;\n /** Query param the stream reads the ticket from. Default: `\"ticket\"`. */\n ticketParam?: string;\n}\n\nexport type CreateTicketEventStreamOptions<T> = TicketEventStreamSource &\n CreateEventStreamOptions<T>;\n\nexport type UseTicketEventStreamOptions<T> = TicketEventStreamSource & UseEventStreamOptions<T>;\n\n/**\n * Whether a failure to obtain a ticket is worth another attempt.\n *\n * Only a failure the backoff can outlast is: no response at all, a timeout, a\n * rate limit, a `5xx`. A `401` reached the caller after the client already\n * tried its refresh, and a `403` (`ACCOUNT_INACTIVE`) is the backend saying no;\n * both are session decisions, and retrying them only delays the error state the\n * app has to show. Anything that is not an API error is a contract mismatch,\n * which a retry cannot fix either.\n *\n * @param error - What the ticket request threw.\n * @returns Whether to schedule a reconnect.\n */\nexport function isRetriableTicketError(error: unknown): boolean {\n return isApiError(error) && isRetriableStatus(error.status);\n}\n\n/**\n * Build the URL function that requests a ticket and points at the stream.\n *\n * A fresh ticket is requested for every connection rather than cached for its\n * `expires_in`. Every connection after the first follows a failure, and the\n * failure may have been the ticket itself; reusing it would spend the retries\n * on a credential that is already refused, while a new ticket costs one `POST`\n * per reconnect, which the backoff already spaces out.\n *\n * @param source - Client, router prefix and ticket param name.\n * @returns A function resolving the stream URL with a fresh ticket.\n * @throws TypeError When the ticket response has no `ticket` string.\n */\nfunction ticketStreamUrl(source: TicketEventStreamSource): () => Promise<string> {\n const { client, prefix = \"/sse\", ticketParam = \"ticket\" } = source;\n return async () => {\n const response = await client.post<SseTicketResponse>(`${prefix}/ticket`);\n if (typeof response?.ticket !== \"string\" || response.ticket === \"\") {\n throw new TypeError(\n `createTicketEventStream: POST ${prefix}/ticket returned no \"ticket\" string.`,\n );\n }\n return client.url(`${prefix}/stream`, { [ticketParam]: response.ticket });\n };\n}\n\n/**\n * Open the ticket-authenticated stream of the `tempest-fastapi-sdk` SSE router.\n *\n * `POST <prefix>/ticket` through the authenticated client, then\n * `GET <prefix>/stream?ticket=…` — and again for every reconnect, because the\n * ticket only opens streams for `expires_in` seconds and a reconnect after that\n * with the old one is a `401`. A ticket request refused with a status no\n * backoff fixes (`401`, `403 ACCOUNT_INACTIVE`) stops the stream at\n * `status: \"error\"` and reaches `onUrlError`; pass `shouldRetryUrl` to replace\n * {@link isRetriableTicketError}.\n *\n * The access token never enters the URL: it travels as the client's header (or\n * cookie) on the ticket request, and the ticket in the URL opens that stream\n * and nothing else.\n *\n * With the `api` of `createTempestAuth` as `client` and no `sessionKey`, the\n * stream follows that preset's session (since 0.82.0): it closes the moment\n * the session is replaced or ends, reopens with a fresh ticket for the next\n * one, stays closed while nobody is signed in, and ignores token rotation.\n * Any other client binds only through `sessionKey`, checked per frame.\n *\n * @example\n * const stream = createTicketEventStream<Notification>({\n * client: auth.api,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @example\n * // A client createTempestAuth did not build\n * const stream = createTicketEventStream<Notification>({\n * client: api,\n * sessionKey: () => useAuthStore.getState().user?.id ?? null,\n * onMessage: ({ data }) => addNotification(data),\n * onUrlError: (error) => toast.error(describeApiError(error)),\n * });\n *\n * @param options - Ticket source plus every {@link createEventStream} option.\n * @returns The stream controller.\n */\nexport function createTicketEventStream<T = unknown>(\n options: CreateTicketEventStreamOptions<T>,\n): EventStreamController {\n const {\n client,\n prefix,\n ticketParam,\n sessionKey,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n const identity = sessionKey === undefined ? sessionIdentityOf(client) : undefined;\n const controller = createEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n sessionKey: sessionKey ?? identity?.current,\n shouldRetryUrl,\n });\n return identity ? followSession(controller, identity) : controller;\n}\n\n/**\n * Close the stream the moment the session it opened under ends, instead of\n * at its next frame, and reopen it for the session that follows.\n *\n * Signed out, the stream stays closed: a ticket request with no session only\n * comes back `401`. Following stops at `close()`; `reconnect()` resumes it.\n *\n * @param controller - The stream, already bound to `identity` frame by frame.\n * @param identity - The session of the client the tickets go through.\n * @returns A controller whose `close()` also stops following.\n */\nfunction followSession(\n controller: EventStreamController,\n identity: SessionIdentity,\n): EventStreamController {\n let bound = identity.current();\n let unsubscribe: (() => void) | null = null;\n function follow(): void {\n unsubscribe ??= identity.subscribe(() => {\n const next = identity.current();\n if (Object.is(next, bound)) return;\n bound = next;\n if (next === null) controller.close();\n else controller.reconnect();\n });\n }\n follow();\n if (bound === null) controller.close();\n return {\n close: () => {\n unsubscribe?.();\n unsubscribe = null;\n controller.close();\n },\n reconnect: () => {\n bound = identity.current();\n follow();\n controller.reconnect();\n },\n get status() {\n return controller.status;\n },\n };\n}\n\n/**\n * Read the session key of a client `createTempestAuth` built, as React state.\n *\n * @param identity - The client's session, or `undefined` for any other client.\n * @returns The key, or `undefined` when the client carries no session.\n */\nfunction useClientSession(identity: SessionIdentity | undefined): string | null | undefined {\n const subscribe = useCallback(\n (listener: () => void) => identity?.subscribe(listener) ?? (() => undefined),\n [identity],\n );\n const read = (): string | null | undefined => identity?.current();\n return useSyncExternalStore(subscribe, read, read);\n}\n\n/**\n * React form of {@link createTicketEventStream}: same ticket per connection,\n * lifecycle tied to the component like {@link useEventStream}.\n *\n * Changing `client`, `prefix` or `ticketParam` does not drop an open stream:\n * the next connection uses the new values, and `reconnect()` applies them now.\n * Reopening on identity would reconnect on every render for a client built\n * inline.\n *\n * The stream is bound to a session: the ticket names the channel of the user\n * who asked for it, the server never ends an open stream on logout, and a tab\n * that switches accounts without `enabled` going `false` would otherwise keep\n * delivering the previous user's events. A change of session closes that\n * stream and asks a ticket for the new one.\n *\n * With the `api` of `createTempestAuth` as `client`, that binding is automatic\n * (since 0.82.0): the session is read from the client — `auth.sessionKey()`,\n * the lineage `login()` mints — so a switch closes the stream, a token\n * rotation of the same session does not, and while nobody is signed in the\n * stream stays `idle` without asking for a ticket. Any other client keeps the\n * behaviour it had: pass `sessionKey` (the signed-in user's id). A\n * `sessionKey` passed explicitly always wins over the client's.\n *\n * @example\n * const { status } = useTicketEventStream<Notification>({\n * client: auth.api,\n * schema: notificationSchema,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @example\n * // A client createTempestAuth did not build\n * const { status } = useTicketEventStream<Notification>({\n * client: api,\n * enabled: isAuthenticated,\n * sessionKey: user?.id ?? null,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @param options - Ticket source plus every {@link useEventStream} option.\n * @returns Status, last message and `reconnect`.\n */\nexport function useTicketEventStream<T = unknown>(\n options: UseTicketEventStreamOptions<T>,\n): UseEventStreamResult<T> {\n const {\n client,\n prefix,\n ticketParam,\n enabled = true,\n sessionKey,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n const identity = sessionKey === undefined ? sessionIdentityOf(client) : undefined;\n const clientSession = useClientSession(identity);\n return useEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n enabled: enabled && clientSession !== null,\n sessionKey: sessionKey ?? clientSession,\n shouldRetryUrl,\n });\n}\n"],"mappings":"A,kLA2DA,SAAgBY,EAAuB,EAAyB,CAC5D,OAAOZ,EAAAA,WAAWa,CAAK,GAAKZ,EAAAA,kBAAkBY,EAAM,MAAM,CAC9D,CAeA,SAASC,EAAgB,EAAwD,CAC7E,GAAM,CAAE,SAAQ,SAAS,OAAQ,cAAc,UAAaC,EAC5D,OAAO,SAAY,CACf,IAAMC,EAAW,MAAMC,EAAO,KAAwB,GAAGC,EAAO,QAAQ,EACxE,GAAI,OAAOF,GAAU,QAAW,UAAYA,EAAS,SAAW,GAC5D,MAAU,UACN,iCAAiCE,EAAO,qCAC5C,EAEJ,OAAOD,EAAO,IAAI,GAAGC,EAAO,SAAU,EAAGC,GAAcH,EAAS,MAAO,CAAC,CAC5E,CACJ,CAyCA,SAAgBI,EACZ,EACqB,CACrB,GAAM,CACF,SACA,SACA,cACA,aACA,iBAAiBR,EACjB,GAAGS,GACHC,EACEC,EAAWC,IAAe,IAAA,GAAYtB,EAAAA,kBAAkBe,CAAM,EAAI,IAAA,GAClEQ,EAAatB,EAAAA,kBAAqBW,EAAgB,CAAE,SAAQ,SAAQ,aAAY,CAAC,EAAG,CACtF,GAAGO,EACH,WAAYG,GAAcD,GAAU,QACpC,gBACJ,CAAC,EACD,OAAOA,EAAWG,EAAcD,EAAYF,CAAQ,EAAIE,CAC5D,CAaA,SAASC,EACL,EACA,EACqB,CACrB,IAAIC,EAAQJ,EAAS,QAAQ,EACzBK,EAAmC,KACvC,SAASC,GAAe,CACpB,IAAgBN,EAAS,cAAgB,CACrC,IAAMO,EAAOP,EAAS,QAAQ,EAC1B,OAAO,GAAGO,EAAMH,CAAK,IACzB,EAAQG,EACJA,IAAS,KAAML,EAAW,MAAM,EAC/BA,EAAW,UAAU,EAC9B,CAAC,CACL,CAGA,OAFAI,EAAO,EACHF,IAAU,MAAMF,EAAW,MAAM,EAC9B,CACH,UAAa,CACTG,IAAc,EACd,EAAc,KACdH,EAAW,MAAM,CACrB,EACA,cAAiB,CACb,EAAQF,EAAS,QAAQ,EACzBM,EAAO,EACPJ,EAAW,UAAU,CACzB,EACA,IAAI,QAAS,CACT,OAAOA,EAAW,MACtB,CACJ,CACJ,CAQA,SAASM,EAAiB,EAAkE,CACxF,IAAMC,GAAA,EAAY5B,EAAAA,YAAAA,CACb,GAAyBmB,GAAU,UAAUU,CAAQ,QAAY,IAAA,IAClE,CAACV,CAAQ,CACb,EACMW,MAAwCX,GAAU,QAAQ,EAChE,OAAA,EAAOlB,EAAAA,qBAAAA,CAAqB2B,EAAWE,EAAMA,CAAI,CACrD,CA4CA,SAAgBC,EACZ,EACuB,CACvB,GAAM,CACF,SACA,SACA,cACA,UAAU,GACV,aACA,iBAAiBvB,EACjB,GAAGS,GACHC,EAEEc,EAAgBL,EADLP,IAAe,IAAA,GAAYtB,EAAAA,kBAAkBe,CAAM,EAAI,IAAA,EACzB,EAC/C,OAAOX,EAAAA,eAAkBQ,EAAgB,CAAE,SAAQ,SAAQ,aAAY,CAAC,EAAG,CACvE,GAAGO,EACH,QAASgB,GAAWD,IAAkB,KACtC,WAAYZ,GAAcY,EAC1B,gBACJ,CAAC,CACL,C"}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { isApiError as e, isRetriableStatus as t } from "../http/errors.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { sessionIdentityOf as n } from "../auth/session-identity.js";
|
|
3
|
+
import { createEventStream as r } from "./create-event-stream.js";
|
|
4
|
+
import { useEventStream as i } from "./use-event-stream.js";
|
|
5
|
+
import { useCallback as a, useSyncExternalStore as o } from "react";
|
|
4
6
|
//#region src/sse/ticket-event-stream.ts
|
|
5
|
-
function
|
|
7
|
+
function s(n) {
|
|
6
8
|
return e(n) && t(n.status);
|
|
7
9
|
}
|
|
8
|
-
function
|
|
10
|
+
function c(e) {
|
|
9
11
|
let { client: t, prefix: n = "/sse", ticketParam: r = "ticket" } = e;
|
|
10
12
|
return async () => {
|
|
11
13
|
let e = await t.post(`${n}/ticket`);
|
|
@@ -13,29 +15,56 @@ function a(e) {
|
|
|
13
15
|
return t.url(`${n}/stream`, { [r]: e.ticket });
|
|
14
16
|
};
|
|
15
17
|
}
|
|
16
|
-
function
|
|
17
|
-
let { client: t, prefix:
|
|
18
|
-
return n(a({
|
|
18
|
+
function l(e) {
|
|
19
|
+
let { client: t, prefix: i, ticketParam: a, sessionKey: o, shouldRetryUrl: l = s, ...d } = e, f = o === void 0 ? n(t) : void 0, p = r(c({
|
|
19
20
|
client: t,
|
|
20
|
-
prefix:
|
|
21
|
-
ticketParam:
|
|
21
|
+
prefix: i,
|
|
22
|
+
ticketParam: a
|
|
22
23
|
}), {
|
|
23
|
-
...
|
|
24
|
-
|
|
24
|
+
...d,
|
|
25
|
+
sessionKey: o ?? f?.current,
|
|
26
|
+
shouldRetryUrl: l
|
|
25
27
|
});
|
|
28
|
+
return f ? u(p, f) : p;
|
|
29
|
+
}
|
|
30
|
+
function u(e, t) {
|
|
31
|
+
let n = t.current(), r = null;
|
|
32
|
+
function i() {
|
|
33
|
+
r ??= t.subscribe(() => {
|
|
34
|
+
let r = t.current();
|
|
35
|
+
Object.is(r, n) || (n = r, r === null ? e.close() : e.reconnect());
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return i(), n === null && e.close(), {
|
|
39
|
+
close: () => {
|
|
40
|
+
r?.(), r = null, e.close();
|
|
41
|
+
},
|
|
42
|
+
reconnect: () => {
|
|
43
|
+
n = t.current(), i(), e.reconnect();
|
|
44
|
+
},
|
|
45
|
+
get status() {
|
|
46
|
+
return e.status;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
26
49
|
}
|
|
27
|
-
function
|
|
28
|
-
let
|
|
29
|
-
return
|
|
50
|
+
function d(e) {
|
|
51
|
+
let t = a((t) => e?.subscribe(t) ?? (() => void 0), [e]), n = () => e?.current();
|
|
52
|
+
return o(t, n, n);
|
|
53
|
+
}
|
|
54
|
+
function f(e) {
|
|
55
|
+
let { client: t, prefix: r, ticketParam: a, enabled: o = !0, sessionKey: l, shouldRetryUrl: u = s, ...f } = e, p = d(l === void 0 ? n(t) : void 0);
|
|
56
|
+
return i(c({
|
|
30
57
|
client: t,
|
|
31
|
-
prefix:
|
|
32
|
-
ticketParam:
|
|
58
|
+
prefix: r,
|
|
59
|
+
ticketParam: a
|
|
33
60
|
}), {
|
|
34
|
-
...
|
|
35
|
-
|
|
61
|
+
...f,
|
|
62
|
+
enabled: o && p !== null,
|
|
63
|
+
sessionKey: l ?? p,
|
|
64
|
+
shouldRetryUrl: u
|
|
36
65
|
});
|
|
37
66
|
}
|
|
38
67
|
//#endregion
|
|
39
|
-
export {
|
|
68
|
+
export { l as createTicketEventStream, s as isRetriableTicketError, f as useTicketEventStream };
|
|
40
69
|
|
|
41
70
|
//# sourceMappingURL=ticket-event-stream.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ticket-event-stream.js","names":["isRetriableTicketError","isApiError","error","isRetriableStatus","ticketStreamUrl","source","response","client","prefix","ticketParam","createTicketEventStream","rest","options","createEventStream","useTicketEventStream","useEventStream"],"sources":["../../src/sse/ticket-event-stream.ts"],"sourcesContent":["import { isApiError, isRetriableStatus } from \"../http/errors\";\nimport type { ApiClient } from \"../http/types\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamController,\n} from \"./create-event-stream\";\nimport {\n useEventStream,\n type UseEventStreamOptions,\n type UseEventStreamResult,\n} from \"./use-event-stream\";\n\n/** Body of `POST <prefix>/ticket` on the `tempest-fastapi-sdk` SSE router. */\nexport interface SseTicketResponse {\n /** Signed stream ticket, presented as a query param when opening the stream. */\n ticket: string;\n /** Seconds the ticket is accepted for opening a stream. */\n expires_in: number;\n}\n\n/** Where the ticket comes from and how the stream URL is built. */\nexport interface TicketEventStreamSource {\n /**\n * Authenticated client the ticket is requested through, so it carries the\n * `Authorization` header or the session cookie, the CSRF header, and the\n * 401 refresh-and-replay that a hand-rolled `fetch` would lose.\n */\n client: Pick<ApiClient, \"post\" | \"url\">;\n /** Router prefix, relative to the client's base URL. Default: `\"/sse\"`. */\n prefix?: string;\n /** Query param the stream reads the ticket from. Default: `\"ticket\"`. */\n ticketParam?: string;\n}\n\nexport type CreateTicketEventStreamOptions<T> = TicketEventStreamSource &\n CreateEventStreamOptions<T>;\n\nexport type UseTicketEventStreamOptions<T> = TicketEventStreamSource & UseEventStreamOptions<T>;\n\n/**\n * Whether a failure to obtain a ticket is worth another attempt.\n *\n * Only a failure the backoff can outlast is: no response at all, a timeout, a\n * rate limit, a `5xx`. A `401` reached the caller after the client already\n * tried its refresh, and a `403` (`ACCOUNT_INACTIVE`) is the backend saying no;\n * both are session decisions, and retrying them only delays the error state the\n * app has to show. Anything that is not an API error is a contract mismatch,\n * which a retry cannot fix either.\n *\n * @param error - What the ticket request threw.\n * @returns Whether to schedule a reconnect.\n */\nexport function isRetriableTicketError(error: unknown): boolean {\n return isApiError(error) && isRetriableStatus(error.status);\n}\n\n/**\n * Build the URL function that requests a ticket and points at the stream.\n *\n * A fresh ticket is requested for every connection rather than cached for its\n * `expires_in`. Every connection after the first follows a failure, and the\n * failure may have been the ticket itself; reusing it would spend the retries\n * on a credential that is already refused, while a new ticket costs one `POST`\n * per reconnect, which the backoff already spaces out.\n *\n * @param source - Client, router prefix and ticket param name.\n * @returns A function resolving the stream URL with a fresh ticket.\n * @throws TypeError When the ticket response has no `ticket` string.\n */\nfunction ticketStreamUrl(source: TicketEventStreamSource): () => Promise<string> {\n const { client, prefix = \"/sse\", ticketParam = \"ticket\" } = source;\n return async () => {\n const response = await client.post<SseTicketResponse>(`${prefix}/ticket`);\n if (typeof response?.ticket !== \"string\" || response.ticket === \"\") {\n throw new TypeError(\n `createTicketEventStream: POST ${prefix}/ticket returned no \"ticket\" string.`,\n );\n }\n return client.url(`${prefix}/stream`, { [ticketParam]: response.ticket });\n };\n}\n\n/**\n * Open the ticket-authenticated stream of the `tempest-fastapi-sdk` SSE router.\n *\n * `POST <prefix>/ticket` through the authenticated client, then\n * `GET <prefix>/stream?ticket=…` — and again for every reconnect, because the\n * ticket only opens streams for `expires_in` seconds and a reconnect after that\n * with the old one is a `401`. A ticket request refused with a status no\n * backoff fixes (`401`, `403 ACCOUNT_INACTIVE`) stops the stream at\n * `status: \"error\"` and reaches `onUrlError`; pass `shouldRetryUrl` to replace\n * {@link isRetriableTicketError}.\n *\n * The access token never enters the URL: it travels as the client's header (or\n * cookie) on the ticket request, and the ticket in the URL opens that stream\n * and nothing else.\n *\n * @example\n * const stream = createTicketEventStream<Notification>({\n * client: api,\n * onMessage: ({ data }) => addNotification(data),\n * onUrlError: (error) => toast.error(describeApiError(error)),\n * });\n *\n * @param options - Ticket source plus every {@link createEventStream} option.\n * @returns The stream controller.\n */\nexport function createTicketEventStream<T = unknown>(\n options: CreateTicketEventStreamOptions<T>,\n): EventStreamController {\n const {\n client,\n prefix,\n ticketParam,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n return createEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n shouldRetryUrl,\n });\n}\n\n/**\n * React form of {@link createTicketEventStream}: same ticket per connection,\n * lifecycle tied to the component like {@link useEventStream}.\n *\n * Changing `client`, `prefix` or `ticketParam` does not drop an open stream:\n * the next connection uses the new values, and `reconnect()` applies them now.\n * Reopening on identity would reconnect on every render for a client built\n * inline.\n *\n * @example\n * const { status } = useTicketEventStream<Notification>({\n * client: api,\n * enabled: isAuthenticated,\n * schema: notificationSchema,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @param options - Ticket source plus every {@link useEventStream} option.\n * @returns Status, last message and `reconnect`.\n */\nexport function useTicketEventStream<T = unknown>(\n options: UseTicketEventStreamOptions<T>,\n): UseEventStreamResult<T> {\n const {\n client,\n prefix,\n ticketParam,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n return useEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n shouldRetryUrl,\n });\n}\n"],"mappings":";;;;AAqDA,SAAgBA,EAAuB,GAAyB;CAC5D,OAAOC,EAAWC,CAAK,KAAKC,EAAkBD,EAAM,MAAM;AAC9D;AAeA,SAASE,EAAgB,GAAwD;CAC7E,IAAM,EAAE,WAAQ,YAAS,QAAQ,iBAAc,aAAaC;CAC5D,OAAO,YAAY;EACf,IAAMC,IAAW,MAAMC,EAAO,KAAwB,GAAGC,EAAO,QAAQ;EACxE,IAAI,OAAOF,GAAU,UAAW,YAAYA,EAAS,WAAW,IAC5D,MAAU,UACN,iCAAiCE,EAAO,qCAC5C;EAEJ,OAAOD,EAAO,IAAI,GAAGC,EAAO,UAAU,GAAGC,IAAcH,EAAS,OAAO,CAAC;CAC5E;AACJ;AA2BA,SAAgBI,EACZ,GACqB;CACrB,IAAM,EACF,WACA,WACA,gBACA,oBAAiBV,GACjB,GAAGW,MACHC;CACJ,OAAOC,EAAqBT,EAAgB;EAAE;EAAQ;EAAQ;CAAY,CAAC,GAAG;EAC1E,GAAGO;EACH;CACJ,CAAC;AACL;AAsBA,SAAgBG,EACZ,GACuB;CACvB,IAAM,EACF,WACA,WACA,gBACA,oBAAiBd,GACjB,GAAGW,MACHC;CACJ,OAAOG,EAAkBX,EAAgB;EAAE;EAAQ;EAAQ;CAAY,CAAC,GAAG;EACvE,GAAGO;EACH;CACJ,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"ticket-event-stream.js","names":["isRetriableTicketError","isApiError","error","isRetriableStatus","ticketStreamUrl","source","response","client","prefix","ticketParam","createTicketEventStream","rest","options","identity","sessionKey","sessionIdentityOf","controller","createEventStream","followSession","bound","unsubscribe","follow","next","useClientSession","subscribe","useCallback","listener","read","useSyncExternalStore","useTicketEventStream","clientSession","useEventStream","enabled"],"sources":["../../src/sse/ticket-event-stream.ts"],"sourcesContent":["import { useCallback, useSyncExternalStore } from \"react\";\nimport { sessionIdentityOf, type SessionIdentity } from \"../auth/session-identity\";\nimport { isApiError, isRetriableStatus } from \"../http/errors\";\nimport type { ApiClient } from \"../http/types\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamController,\n} from \"./create-event-stream\";\nimport {\n useEventStream,\n type UseEventStreamOptions,\n type UseEventStreamResult,\n} from \"./use-event-stream\";\n\n/** Body of `POST <prefix>/ticket` on the `tempest-fastapi-sdk` SSE router. */\nexport interface SseTicketResponse {\n /** Signed stream ticket, presented as a query param when opening the stream. */\n ticket: string;\n /** Seconds the ticket is accepted for opening a stream. */\n expires_in: number;\n}\n\n/** Where the ticket comes from and how the stream URL is built. */\nexport interface TicketEventStreamSource {\n /**\n * Authenticated client the ticket is requested through, so it carries the\n * `Authorization` header or the session cookie, the CSRF header, and the\n * 401 refresh-and-replay that a hand-rolled `fetch` would lose.\n *\n * The `api` of `createTempestAuth` also carries the session it acts for,\n * and the stream binds to it when `sessionKey` is not passed — see\n * {@link useTicketEventStream}.\n */\n client: Pick<ApiClient, \"post\" | \"url\">;\n /** Router prefix, relative to the client's base URL. Default: `\"/sse\"`. */\n prefix?: string;\n /** Query param the stream reads the ticket from. Default: `\"ticket\"`. */\n ticketParam?: string;\n}\n\nexport type CreateTicketEventStreamOptions<T> = TicketEventStreamSource &\n CreateEventStreamOptions<T>;\n\nexport type UseTicketEventStreamOptions<T> = TicketEventStreamSource & UseEventStreamOptions<T>;\n\n/**\n * Whether a failure to obtain a ticket is worth another attempt.\n *\n * Only a failure the backoff can outlast is: no response at all, a timeout, a\n * rate limit, a `5xx`. A `401` reached the caller after the client already\n * tried its refresh, and a `403` (`ACCOUNT_INACTIVE`) is the backend saying no;\n * both are session decisions, and retrying them only delays the error state the\n * app has to show. Anything that is not an API error is a contract mismatch,\n * which a retry cannot fix either.\n *\n * @param error - What the ticket request threw.\n * @returns Whether to schedule a reconnect.\n */\nexport function isRetriableTicketError(error: unknown): boolean {\n return isApiError(error) && isRetriableStatus(error.status);\n}\n\n/**\n * Build the URL function that requests a ticket and points at the stream.\n *\n * A fresh ticket is requested for every connection rather than cached for its\n * `expires_in`. Every connection after the first follows a failure, and the\n * failure may have been the ticket itself; reusing it would spend the retries\n * on a credential that is already refused, while a new ticket costs one `POST`\n * per reconnect, which the backoff already spaces out.\n *\n * @param source - Client, router prefix and ticket param name.\n * @returns A function resolving the stream URL with a fresh ticket.\n * @throws TypeError When the ticket response has no `ticket` string.\n */\nfunction ticketStreamUrl(source: TicketEventStreamSource): () => Promise<string> {\n const { client, prefix = \"/sse\", ticketParam = \"ticket\" } = source;\n return async () => {\n const response = await client.post<SseTicketResponse>(`${prefix}/ticket`);\n if (typeof response?.ticket !== \"string\" || response.ticket === \"\") {\n throw new TypeError(\n `createTicketEventStream: POST ${prefix}/ticket returned no \"ticket\" string.`,\n );\n }\n return client.url(`${prefix}/stream`, { [ticketParam]: response.ticket });\n };\n}\n\n/**\n * Open the ticket-authenticated stream of the `tempest-fastapi-sdk` SSE router.\n *\n * `POST <prefix>/ticket` through the authenticated client, then\n * `GET <prefix>/stream?ticket=…` — and again for every reconnect, because the\n * ticket only opens streams for `expires_in` seconds and a reconnect after that\n * with the old one is a `401`. A ticket request refused with a status no\n * backoff fixes (`401`, `403 ACCOUNT_INACTIVE`) stops the stream at\n * `status: \"error\"` and reaches `onUrlError`; pass `shouldRetryUrl` to replace\n * {@link isRetriableTicketError}.\n *\n * The access token never enters the URL: it travels as the client's header (or\n * cookie) on the ticket request, and the ticket in the URL opens that stream\n * and nothing else.\n *\n * With the `api` of `createTempestAuth` as `client` and no `sessionKey`, the\n * stream follows that preset's session (since 0.82.0): it closes the moment\n * the session is replaced or ends, reopens with a fresh ticket for the next\n * one, stays closed while nobody is signed in, and ignores token rotation.\n * Any other client binds only through `sessionKey`, checked per frame.\n *\n * @example\n * const stream = createTicketEventStream<Notification>({\n * client: auth.api,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @example\n * // A client createTempestAuth did not build\n * const stream = createTicketEventStream<Notification>({\n * client: api,\n * sessionKey: () => useAuthStore.getState().user?.id ?? null,\n * onMessage: ({ data }) => addNotification(data),\n * onUrlError: (error) => toast.error(describeApiError(error)),\n * });\n *\n * @param options - Ticket source plus every {@link createEventStream} option.\n * @returns The stream controller.\n */\nexport function createTicketEventStream<T = unknown>(\n options: CreateTicketEventStreamOptions<T>,\n): EventStreamController {\n const {\n client,\n prefix,\n ticketParam,\n sessionKey,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n const identity = sessionKey === undefined ? sessionIdentityOf(client) : undefined;\n const controller = createEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n sessionKey: sessionKey ?? identity?.current,\n shouldRetryUrl,\n });\n return identity ? followSession(controller, identity) : controller;\n}\n\n/**\n * Close the stream the moment the session it opened under ends, instead of\n * at its next frame, and reopen it for the session that follows.\n *\n * Signed out, the stream stays closed: a ticket request with no session only\n * comes back `401`. Following stops at `close()`; `reconnect()` resumes it.\n *\n * @param controller - The stream, already bound to `identity` frame by frame.\n * @param identity - The session of the client the tickets go through.\n * @returns A controller whose `close()` also stops following.\n */\nfunction followSession(\n controller: EventStreamController,\n identity: SessionIdentity,\n): EventStreamController {\n let bound = identity.current();\n let unsubscribe: (() => void) | null = null;\n function follow(): void {\n unsubscribe ??= identity.subscribe(() => {\n const next = identity.current();\n if (Object.is(next, bound)) return;\n bound = next;\n if (next === null) controller.close();\n else controller.reconnect();\n });\n }\n follow();\n if (bound === null) controller.close();\n return {\n close: () => {\n unsubscribe?.();\n unsubscribe = null;\n controller.close();\n },\n reconnect: () => {\n bound = identity.current();\n follow();\n controller.reconnect();\n },\n get status() {\n return controller.status;\n },\n };\n}\n\n/**\n * Read the session key of a client `createTempestAuth` built, as React state.\n *\n * @param identity - The client's session, or `undefined` for any other client.\n * @returns The key, or `undefined` when the client carries no session.\n */\nfunction useClientSession(identity: SessionIdentity | undefined): string | null | undefined {\n const subscribe = useCallback(\n (listener: () => void) => identity?.subscribe(listener) ?? (() => undefined),\n [identity],\n );\n const read = (): string | null | undefined => identity?.current();\n return useSyncExternalStore(subscribe, read, read);\n}\n\n/**\n * React form of {@link createTicketEventStream}: same ticket per connection,\n * lifecycle tied to the component like {@link useEventStream}.\n *\n * Changing `client`, `prefix` or `ticketParam` does not drop an open stream:\n * the next connection uses the new values, and `reconnect()` applies them now.\n * Reopening on identity would reconnect on every render for a client built\n * inline.\n *\n * The stream is bound to a session: the ticket names the channel of the user\n * who asked for it, the server never ends an open stream on logout, and a tab\n * that switches accounts without `enabled` going `false` would otherwise keep\n * delivering the previous user's events. A change of session closes that\n * stream and asks a ticket for the new one.\n *\n * With the `api` of `createTempestAuth` as `client`, that binding is automatic\n * (since 0.82.0): the session is read from the client — `auth.sessionKey()`,\n * the lineage `login()` mints — so a switch closes the stream, a token\n * rotation of the same session does not, and while nobody is signed in the\n * stream stays `idle` without asking for a ticket. Any other client keeps the\n * behaviour it had: pass `sessionKey` (the signed-in user's id). A\n * `sessionKey` passed explicitly always wins over the client's.\n *\n * @example\n * const { status } = useTicketEventStream<Notification>({\n * client: auth.api,\n * schema: notificationSchema,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @example\n * // A client createTempestAuth did not build\n * const { status } = useTicketEventStream<Notification>({\n * client: api,\n * enabled: isAuthenticated,\n * sessionKey: user?.id ?? null,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @param options - Ticket source plus every {@link useEventStream} option.\n * @returns Status, last message and `reconnect`.\n */\nexport function useTicketEventStream<T = unknown>(\n options: UseTicketEventStreamOptions<T>,\n): UseEventStreamResult<T> {\n const {\n client,\n prefix,\n ticketParam,\n enabled = true,\n sessionKey,\n shouldRetryUrl = isRetriableTicketError,\n ...rest\n } = options;\n const identity = sessionKey === undefined ? sessionIdentityOf(client) : undefined;\n const clientSession = useClientSession(identity);\n return useEventStream<T>(ticketStreamUrl({ client, prefix, ticketParam }), {\n ...rest,\n enabled: enabled && clientSession !== null,\n sessionKey: sessionKey ?? clientSession,\n shouldRetryUrl,\n });\n}\n"],"mappings":";;;;;;AA2DA,SAAgBA,EAAuB,GAAyB;CAC5D,OAAOC,EAAWC,CAAK,KAAKC,EAAkBD,EAAM,MAAM;AAC9D;AAeA,SAASE,EAAgB,GAAwD;CAC7E,IAAM,EAAE,WAAQ,YAAS,QAAQ,iBAAc,aAAaC;CAC5D,OAAO,YAAY;EACf,IAAMC,IAAW,MAAMC,EAAO,KAAwB,GAAGC,EAAO,QAAQ;EACxE,IAAI,OAAOF,GAAU,UAAW,YAAYA,EAAS,WAAW,IAC5D,MAAU,UACN,iCAAiCE,EAAO,qCAC5C;EAEJ,OAAOD,EAAO,IAAI,GAAGC,EAAO,UAAU,GAAGC,IAAcH,EAAS,OAAO,CAAC;CAC5E;AACJ;AAyCA,SAAgBI,EACZ,GACqB;CACrB,IAAM,EACF,WACA,WACA,gBACA,eACA,oBAAiBV,GACjB,GAAGW,MACHC,GACEC,IAAWC,MAAe,KAAA,IAAYC,EAAkBR,CAAM,IAAI,KAAA,GAClES,IAAaC,EAAqBb,EAAgB;EAAE;EAAQ;EAAQ;CAAY,CAAC,GAAG;EACtF,GAAGO;EACH,YAAYG,KAAcD,GAAU;EACpC;CACJ,CAAC;CACD,OAAOA,IAAWK,EAAcF,GAAYH,CAAQ,IAAIG;AAC5D;AAaA,SAASE,EACL,GACA,GACqB;CACrB,IAAIC,IAAQN,EAAS,QAAQ,GACzBO,IAAmC;CACvC,SAASC,IAAe;EACpB,MAAgBR,EAAS,gBAAgB;GACrC,IAAMS,IAAOT,EAAS,QAAQ;GAC9B,AAAI,OAAO,GAAGS,GAAMH,CAAK,MACzB,IAAQG,GACJA,MAAS,OAAMN,EAAW,MAAM,IAC/BA,EAAW,UAAU;EAC9B,CAAC;CACL;CAGA,OAFAK,EAAO,GACHF,MAAU,QAAMH,EAAW,MAAM,GAC9B;EACH,aAAa;GAGT,AAFAI,IAAc,GACd,IAAc,MACdJ,EAAW,MAAM;EACrB;EACA,iBAAiB;GAGb,AAFA,IAAQH,EAAS,QAAQ,GACzBQ,EAAO,GACPL,EAAW,UAAU;EACzB;EACA,IAAI,SAAS;GACT,OAAOA,EAAW;EACtB;CACJ;AACJ;AAQA,SAASO,EAAiB,GAAkE;CACxF,IAAMC,IAAYC,GACb,MAAyBZ,GAAU,UAAUa,CAAQ,YAAY,KAAA,IAClE,CAACb,CAAQ,CACb,GACMc,UAAwCd,GAAU,QAAQ;CAChE,OAAOe,EAAqBJ,GAAWG,GAAMA,CAAI;AACrD;AA4CA,SAAgBE,EACZ,GACuB;CACvB,IAAM,EACF,WACA,WACA,gBACA,aAAU,IACV,eACA,oBAAiB7B,GACjB,GAAGW,MACHC,GAEEkB,IAAgBP,EADLT,MAAe,KAAA,IAAYC,EAAkBR,CAAM,IAAI,KAAA,CACzB;CAC/C,OAAOwB,EAAkB3B,EAAgB;EAAE;EAAQ;EAAQ;CAAY,CAAC,GAAG;EACvE,GAAGO;EACH,SAASqB,KAAWF,MAAkB;EACtC,YAAYhB,KAAcgB;EAC1B;CACJ,CAAC;AACL"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("../hooks/use-latest-ref.cjs"),t=require("./create-event-stream.cjs");let n=require("react");function r(r,i={}){let{enabled:a=!0,onMessage:
|
|
1
|
+
const e=require("../hooks/use-latest-ref.cjs"),t=require("./create-event-stream.cjs");let n=require("react");function r(r,i={}){let{enabled:a=!0,sessionKey:o,onMessage:s,...c}=i,[l,u]=(0,n.useState)(`idle`),[d,f]=(0,n.useState)(null),p=(0,n.useRef)(null),m=(0,n.useRef)(o),h=e.useLatestRef(s),g=e.useLatestRef(r),_=e.useLatestRef(o),v=typeof r==`string`?r:null;return(0,n.useEffect)(()=>{if(Object.is(m.current,o)||(m.current=o,f(null)),!a||v===``){u(`idle`);return}let e=t.createEventStream(v??(()=>{let e=g.current;return typeof e==`string`?e:e()}),{...c,sessionKey:()=>_.current,onStatusChange:u,onMessage:e=>{f(e),h.current?.(e)}});return p.current=e.reconnect,()=>{e.close(),p.current=null}},[v,a,o]),{status:l,lastMessage:d,reconnect:()=>p.current?.()}}exports.useEventStream=r;
|
|
2
2
|
//# sourceMappingURL=use-event-stream.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-event-stream.cjs","names":["useState","useRef","useLatestRef","createEventStream","require_use_latest_ref","require_create_event_stream","react","useEventStream","rest","options","status","setStatus","lastMessage","setLastMessage","reconnectRef","onMessageRef","onMessage","urlRef","url","fixedUrl","enabled","controller","latest","message"],"sources":["../../src/sse/use-event-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamMessage,\n type EventStreamStatus,\n type EventStreamUrl,\n} from \"./create-event-stream\";\n\nexport interface UseEventStreamOptions<T> extends Omit<\n CreateEventStreamOptions<T>,\n \"onStatusChange\"\n> {\n /** When false, the stream is not opened. Useful for \"wait for auth\". Default: true. */\n enabled?: boolean;\n}\n\nexport interface UseEventStreamResult<T> {\n status: EventStreamStatus;\n /** Last message received (excluding heartbeats). */\n lastMessage: EventStreamMessage<T> | null;\n /** Force a reconnect. */\n reconnect: () => void;\n}\n\n/**\n * React hook wrapper around {@link createEventStream}. Connection lifecycle is\n * tied to the component (and the `url`/`enabled` dependencies)
|
|
1
|
+
{"version":3,"file":"use-event-stream.cjs","names":["useState","useRef","useLatestRef","createEventStream","require_use_latest_ref","require_create_event_stream","react","useEventStream","rest","options","status","setStatus","lastMessage","setLastMessage","reconnectRef","lastSessionRef","sessionKey","onMessageRef","onMessage","urlRef","url","sessionKeyRef","fixedUrl","enabled","controller","latest","message"],"sources":["../../src/sse/use-event-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamMessage,\n type EventStreamStatus,\n type EventStreamUrl,\n type SessionKey,\n} from \"./create-event-stream\";\n\nexport interface UseEventStreamOptions<T> extends Omit<\n CreateEventStreamOptions<T>,\n \"onStatusChange\" | \"sessionKey\"\n> {\n /** When false, the stream is not opened. Useful for \"wait for auth\". Default: true. */\n enabled?: boolean;\n /**\n * The session the stream belongs to — the signed-in user's id, typically.\n *\n * A change closes the stream, clears `lastMessage` and, while `enabled`,\n * opens a new connection for the new session (a fresh ticket, for\n * {@link useTicketEventStream}). Without it, a tab that switches accounts\n * without passing through `enabled: false` keeps the previous user's\n * stream open and delivers its events under the new user: the server does\n * not end an open stream on logout or revocation, so the client has to.\n *\n * A frame that arrives between the render that changed the key and the\n * effect that closes the stream is dropped as well. Default: `undefined`,\n * which never changes, so the stream follows `url` and `enabled` alone.\n */\n sessionKey?: SessionKey;\n}\n\nexport interface UseEventStreamResult<T> {\n status: EventStreamStatus;\n /** Last message received (excluding heartbeats). */\n lastMessage: EventStreamMessage<T> | null;\n /** Force a reconnect. */\n reconnect: () => void;\n}\n\n/**\n * React hook wrapper around {@link createEventStream}. Connection lifecycle is\n * tied to the component (and the `url`/`enabled`/`sessionKey` dependencies);\n * the stream closes on unmount.\n *\n * Pass `sessionKey` (the signed-in user's id) whenever the stream carries one\n * user's data: a change of account then closes the previous user's stream and\n * clears `lastMessage`, even when `enabled` never went `false` in between.\n *\n * A string `url` reopens the stream when it changes. A function `url` does not:\n * an inline arrow is a new function every render, and keying on its identity\n * would reconnect on every render. The latest function is the one called on the\n * next connection, so call `reconnect()` when what it resolves to must change now.\n *\n * Pass `schema` to have every frame validated before it reaches `onMessage`,\n * instead of trusting the type argument: without it `data` is announced as `T`\n * on the strength of the generic alone, which is a promise about the server\n * that TypeScript cannot keep. It is read when the stream opens, so declare it\n * outside the component rather than building one inline per render.\n *\n * @example\n * useEventStream<Notification>(`${API}/notifications/stream`, {\n * enabled: !!user,\n * withCredentials: true,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @example\n * // Validated: a frame that does not match never reaches `onMessage`\n * const notificationSchema = z.object({ id: z.string(), message: z.string() });\n *\n * useEventStream<Notification>(`${API}/notifications/stream`, {\n * schema: notificationSchema,\n * onValidationError: (issues) => logger.warn(\"stream drift\", { issues }),\n * onMessage: ({ data }) => addNotification(data),\n * });\n */\nexport function useEventStream<T = unknown>(\n url: EventStreamUrl,\n options: UseEventStreamOptions<T> = {},\n): UseEventStreamResult<T> {\n const { enabled = true, sessionKey, onMessage, ...rest } = options;\n const [status, setStatus] = useState<EventStreamStatus>(\"idle\");\n const [lastMessage, setLastMessage] = useState<EventStreamMessage<T> | null>(null);\n const reconnectRef = useRef<(() => void) | null>(null);\n const lastSessionRef = useRef<SessionKey>(sessionKey);\n\n const onMessageRef = useLatestRef(onMessage);\n const urlRef = useLatestRef(url);\n const sessionKeyRef = useLatestRef(sessionKey);\n const fixedUrl = typeof url === \"string\" ? url : null;\n\n useEffect(() => {\n if (!Object.is(lastSessionRef.current, sessionKey)) {\n lastSessionRef.current = sessionKey;\n setLastMessage(null);\n }\n if (!enabled || fixedUrl === \"\") {\n setStatus(\"idle\");\n return;\n }\n\n const target: EventStreamUrl =\n fixedUrl ??\n (() => {\n const latest = urlRef.current;\n return typeof latest === \"string\" ? latest : latest();\n });\n const controller = createEventStream<T>(target, {\n ...rest,\n sessionKey: () => sessionKeyRef.current,\n onStatusChange: setStatus,\n onMessage: (message) => {\n setLastMessage(message);\n onMessageRef.current?.(message);\n },\n });\n reconnectRef.current = controller.reconnect;\n\n return () => {\n controller.close();\n reconnectRef.current = null;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [fixedUrl, enabled, sessionKey]);\n\n return {\n status,\n lastMessage,\n reconnect: () => reconnectRef.current?.(),\n };\n}\n"],"mappings":"A,6GA+EA,SAAgBO,EACZ,EACA,EAAoC,CAAC,EACd,CACvB,GAAM,CAAE,UAAU,GAAM,aAAY,YAAW,GAAGC,GAASC,EACrD,CAACC,EAAQC,IAAA,EAAaX,EAAAA,SAAAA,CAA4B,MAAM,EACxD,CAACY,EAAaC,IAAA,EAAkBb,EAAAA,SAAAA,CAAuC,IAAI,EAC3Ec,GAAA,EAAeb,EAAAA,OAAAA,CAA4B,IAAI,EAC/Cc,GAAA,EAAiBd,EAAAA,OAAAA,CAAmBe,CAAU,EAE9CC,EAAef,EAAAA,aAAagB,CAAS,EACrCC,EAASjB,EAAAA,aAAakB,CAAG,EACzBC,EAAgBnB,EAAAA,aAAac,CAAU,EACvCM,EAAW,OAAOF,GAAQ,SAAWA,EAAM,KAoCjD,OAlCA,EAAAd,EAAA,UAAA,KAAgB,CAKZ,GAJK,OAAO,GAAGS,EAAe,QAASC,CAAU,IAC7C,EAAe,QAAUA,EACzBH,EAAe,IAAI,GAEnB,CAACU,GAAWD,IAAa,GAAI,CAC7BX,EAAU,MAAM,EAChB,MACJ,CAQA,IAAMa,EAAarB,EAAAA,kBALfmB,QACO,CACH,IAAMG,EAASN,EAAO,QACtB,OAAO,OAAOM,GAAW,SAAWA,EAASA,EAAO,CACxD,GAC4C,CAC5C,GAAGjB,EACH,eAAkBa,EAAc,QAChC,eAAgBV,EAChB,UAAY,GAAY,CACpBE,EAAea,CAAO,EACtBT,EAAa,UAAUS,CAAO,CAClC,CACJ,CAAC,EAGD,MAFA,GAAa,QAAUF,EAAW,cAErB,CACTA,EAAW,MAAM,EACjB,EAAa,QAAU,IAC3B,CAEJ,EAAG,CAACF,EAAUC,EAASP,CAAU,CAAC,EAE3B,CACH,SACA,cACA,cAAiBF,EAAa,UAAU,CAC5C,CACJ,C"}
|
|
@@ -3,29 +3,34 @@ import { createEventStream as t } from "./create-event-stream.js";
|
|
|
3
3
|
import { useEffect as n, useRef as r, useState as i } from "react";
|
|
4
4
|
//#region src/sse/use-event-stream.ts
|
|
5
5
|
function a(a, o = {}) {
|
|
6
|
-
let { enabled: s = !0,
|
|
6
|
+
let { enabled: s = !0, sessionKey: c, onMessage: l, ...u } = o, [d, f] = i("idle"), [p, m] = i(null), h = r(null), g = r(c), _ = e(l), v = e(a), y = e(c), b = typeof a == "string" ? a : null;
|
|
7
7
|
return n(() => {
|
|
8
|
-
if (!s ||
|
|
9
|
-
|
|
8
|
+
if (Object.is(g.current, c) || (g.current = c, m(null)), !s || b === "") {
|
|
9
|
+
f("idle");
|
|
10
10
|
return;
|
|
11
11
|
}
|
|
12
|
-
let e = t(
|
|
13
|
-
let e =
|
|
12
|
+
let e = t(b ?? (() => {
|
|
13
|
+
let e = v.current;
|
|
14
14
|
return typeof e == "string" ? e : e();
|
|
15
15
|
}), {
|
|
16
|
-
...
|
|
17
|
-
|
|
16
|
+
...u,
|
|
17
|
+
sessionKey: () => y.current,
|
|
18
|
+
onStatusChange: f,
|
|
18
19
|
onMessage: (e) => {
|
|
19
|
-
|
|
20
|
+
m(e), _.current?.(e);
|
|
20
21
|
}
|
|
21
22
|
});
|
|
22
|
-
return
|
|
23
|
-
e.close(),
|
|
23
|
+
return h.current = e.reconnect, () => {
|
|
24
|
+
e.close(), h.current = null;
|
|
24
25
|
};
|
|
25
|
-
}, [
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
26
|
+
}, [
|
|
27
|
+
b,
|
|
28
|
+
s,
|
|
29
|
+
c
|
|
30
|
+
]), {
|
|
31
|
+
status: d,
|
|
32
|
+
lastMessage: p,
|
|
33
|
+
reconnect: () => h.current?.()
|
|
29
34
|
};
|
|
30
35
|
}
|
|
31
36
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-event-stream.js","names":["useEventStream","rest","options","status","setStatus","useState","lastMessage","setLastMessage","reconnectRef","useRef","onMessageRef","useLatestRef","onMessage","urlRef","url","fixedUrl","useEffect","enabled","controller","createEventStream","latest","message"],"sources":["../../src/sse/use-event-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamMessage,\n type EventStreamStatus,\n type EventStreamUrl,\n} from \"./create-event-stream\";\n\nexport interface UseEventStreamOptions<T> extends Omit<\n CreateEventStreamOptions<T>,\n \"onStatusChange\"\n> {\n /** When false, the stream is not opened. Useful for \"wait for auth\". Default: true. */\n enabled?: boolean;\n}\n\nexport interface UseEventStreamResult<T> {\n status: EventStreamStatus;\n /** Last message received (excluding heartbeats). */\n lastMessage: EventStreamMessage<T> | null;\n /** Force a reconnect. */\n reconnect: () => void;\n}\n\n/**\n * React hook wrapper around {@link createEventStream}. Connection lifecycle is\n * tied to the component (and the `url`/`enabled` dependencies)
|
|
1
|
+
{"version":3,"file":"use-event-stream.js","names":["useEventStream","rest","options","status","setStatus","useState","lastMessage","setLastMessage","reconnectRef","useRef","lastSessionRef","sessionKey","onMessageRef","useLatestRef","onMessage","urlRef","url","sessionKeyRef","fixedUrl","useEffect","enabled","controller","createEventStream","latest","message"],"sources":["../../src/sse/use-event-stream.ts"],"sourcesContent":["import { useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"@/hooks/use-latest-ref\";\nimport {\n createEventStream,\n type CreateEventStreamOptions,\n type EventStreamMessage,\n type EventStreamStatus,\n type EventStreamUrl,\n type SessionKey,\n} from \"./create-event-stream\";\n\nexport interface UseEventStreamOptions<T> extends Omit<\n CreateEventStreamOptions<T>,\n \"onStatusChange\" | \"sessionKey\"\n> {\n /** When false, the stream is not opened. Useful for \"wait for auth\". Default: true. */\n enabled?: boolean;\n /**\n * The session the stream belongs to — the signed-in user's id, typically.\n *\n * A change closes the stream, clears `lastMessage` and, while `enabled`,\n * opens a new connection for the new session (a fresh ticket, for\n * {@link useTicketEventStream}). Without it, a tab that switches accounts\n * without passing through `enabled: false` keeps the previous user's\n * stream open and delivers its events under the new user: the server does\n * not end an open stream on logout or revocation, so the client has to.\n *\n * A frame that arrives between the render that changed the key and the\n * effect that closes the stream is dropped as well. Default: `undefined`,\n * which never changes, so the stream follows `url` and `enabled` alone.\n */\n sessionKey?: SessionKey;\n}\n\nexport interface UseEventStreamResult<T> {\n status: EventStreamStatus;\n /** Last message received (excluding heartbeats). */\n lastMessage: EventStreamMessage<T> | null;\n /** Force a reconnect. */\n reconnect: () => void;\n}\n\n/**\n * React hook wrapper around {@link createEventStream}. Connection lifecycle is\n * tied to the component (and the `url`/`enabled`/`sessionKey` dependencies);\n * the stream closes on unmount.\n *\n * Pass `sessionKey` (the signed-in user's id) whenever the stream carries one\n * user's data: a change of account then closes the previous user's stream and\n * clears `lastMessage`, even when `enabled` never went `false` in between.\n *\n * A string `url` reopens the stream when it changes. A function `url` does not:\n * an inline arrow is a new function every render, and keying on its identity\n * would reconnect on every render. The latest function is the one called on the\n * next connection, so call `reconnect()` when what it resolves to must change now.\n *\n * Pass `schema` to have every frame validated before it reaches `onMessage`,\n * instead of trusting the type argument: without it `data` is announced as `T`\n * on the strength of the generic alone, which is a promise about the server\n * that TypeScript cannot keep. It is read when the stream opens, so declare it\n * outside the component rather than building one inline per render.\n *\n * @example\n * useEventStream<Notification>(`${API}/notifications/stream`, {\n * enabled: !!user,\n * withCredentials: true,\n * onMessage: ({ data }) => addNotification(data),\n * });\n *\n * @example\n * // Validated: a frame that does not match never reaches `onMessage`\n * const notificationSchema = z.object({ id: z.string(), message: z.string() });\n *\n * useEventStream<Notification>(`${API}/notifications/stream`, {\n * schema: notificationSchema,\n * onValidationError: (issues) => logger.warn(\"stream drift\", { issues }),\n * onMessage: ({ data }) => addNotification(data),\n * });\n */\nexport function useEventStream<T = unknown>(\n url: EventStreamUrl,\n options: UseEventStreamOptions<T> = {},\n): UseEventStreamResult<T> {\n const { enabled = true, sessionKey, onMessage, ...rest } = options;\n const [status, setStatus] = useState<EventStreamStatus>(\"idle\");\n const [lastMessage, setLastMessage] = useState<EventStreamMessage<T> | null>(null);\n const reconnectRef = useRef<(() => void) | null>(null);\n const lastSessionRef = useRef<SessionKey>(sessionKey);\n\n const onMessageRef = useLatestRef(onMessage);\n const urlRef = useLatestRef(url);\n const sessionKeyRef = useLatestRef(sessionKey);\n const fixedUrl = typeof url === \"string\" ? url : null;\n\n useEffect(() => {\n if (!Object.is(lastSessionRef.current, sessionKey)) {\n lastSessionRef.current = sessionKey;\n setLastMessage(null);\n }\n if (!enabled || fixedUrl === \"\") {\n setStatus(\"idle\");\n return;\n }\n\n const target: EventStreamUrl =\n fixedUrl ??\n (() => {\n const latest = urlRef.current;\n return typeof latest === \"string\" ? latest : latest();\n });\n const controller = createEventStream<T>(target, {\n ...rest,\n sessionKey: () => sessionKeyRef.current,\n onStatusChange: setStatus,\n onMessage: (message) => {\n setLastMessage(message);\n onMessageRef.current?.(message);\n },\n });\n reconnectRef.current = controller.reconnect;\n\n return () => {\n controller.close();\n reconnectRef.current = null;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [fixedUrl, enabled, sessionKey]);\n\n return {\n status,\n lastMessage,\n reconnect: () => reconnectRef.current?.(),\n };\n}\n"],"mappings":";;;;AA+EA,SAAgBA,EACZ,GACA,IAAoC,CAAC,GACd;CACvB,IAAM,EAAE,aAAU,IAAM,eAAY,cAAW,GAAGC,MAASC,GACrD,CAACC,GAAQC,KAAaC,EAA4B,MAAM,GACxD,CAACC,GAAaC,KAAkBF,EAAuC,IAAI,GAC3EG,IAAeC,EAA4B,IAAI,GAC/CC,IAAiBD,EAAmBE,CAAU,GAE9CC,IAAeC,EAAaC,CAAS,GACrCC,IAASF,EAAaG,CAAG,GACzBC,IAAgBJ,EAAaF,CAAU,GACvCO,IAAW,OAAOF,KAAQ,WAAWA,IAAM;CAoCjD,OAlCAG,QAAgB;EAKZ,IAJK,OAAO,GAAGT,EAAe,SAASC,CAAU,MAC7C,EAAe,UAAUA,GACzBJ,EAAe,IAAI,IAEnB,CAACa,KAAWF,MAAa,IAAI;GAC7B,EAAU,MAAM;GAChB;EACJ;EAQA,IAAMG,IAAaC,EALfJ,YACO;GACH,IAAMK,IAASR,EAAO;GACtB,OAAO,OAAOQ,KAAW,WAAWA,IAASA,EAAO;EACxD,IAC4C;GAC5C,GAAGtB;GACH,kBAAkBgB,EAAc;GAChC,gBAAgBb;GAChB,YAAY,MAAY;IAEpB,AADAG,EAAeiB,CAAO,GACtBZ,EAAa,UAAUY,CAAO;GAClC;EACJ,CAAC;EAGD,OAFA,EAAa,UAAUH,EAAW,iBAErB;GAET,AADAA,EAAW,MAAM,GACjB,EAAa,UAAU;EAC3B;CAEJ,GAAG;EAACH;EAAUE;EAAST;CAAU,CAAC,GAE3B;EACH;EACA;EACA,iBAAiBH,EAAa,UAAU;CAC5C;AACJ"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/* Generated by scripts/split-css.mjs — do not edit. */
|
|
2
|
+
.tempest_form_Ry1iO{width:100%}
|
|
3
|
+
.tempest_social_ZiYgW{align-items:stretch;gap:var(--tempest-space-2);flex-direction:column;display:flex}
|
|
4
|
+
.tempest_link_iisLJ{color:var(--tempest-primary);font-weight:var(--tempest-weight-semibold);border-radius:var(--tempest-radius-xs);text-decoration:none}
|
|
5
|
+
.tempest_link_iisLJ:hover{text-decoration:underline}
|
|
6
|
+
.tempest_link_iisLJ:focus-visible{outline:var(--tempest-focus-ring-width) solid var(--tempest-focus-ring-color);outline-offset:var(--tempest-focus-ring-offset)}
|
|
7
|
+
.tempest_forgot_kjNlS{font-size:var(--tempest-text-sm);align-self:flex-end}
|
|
8
|
+
.tempest_prompt_cuJKg{color:var(--tempest-text-muted);font-size:var(--tempest-text-sm);text-align:center;margin:0}
|
|
9
|
+
.tempest_hints_AYoGY{gap:var(--tempest-space-1);padding-left:var(--tempest-space-5);color:var(--tempest-text-muted);font-size:var(--tempest-text-sm);flex-direction:column;margin:0;display:flex}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/* Generated by scripts/split-css.mjs — do not edit. */
|
|
2
|
+
.tempest_root_7FM9A{--tempest-auth-page-bg:var(--tempest-auth-page-aside-bg,var(--tempest-primary));--tempest-auth-page-fg:var(--tempest-auth-page-aside-fg,var(--tempest-text-on-primary));box-sizing:border-box;width:100%;min-height:100dvh;color:var(--tempest-text);font-family:var(--tempest-font-sans)}
|
|
3
|
+
.tempest_aside_iQvZx{justify-content:center;align-items:center;gap:var(--tempest-space-4);color:var(--tempest-auth-page-fg);text-align:center;flex-direction:column;display:flex;position:relative}
|
|
4
|
+
.tempest_brand_ucf0I{align-items:center;gap:var(--tempest-space-2);font-size:var(--tempest-text-2xl);font-weight:var(--tempest-weight-bold);flex-direction:column;display:flex}
|
|
5
|
+
.tempest_brand_ucf0I img,.tempest_brand_ucf0I svg{max-width:100%;height:auto}
|
|
6
|
+
.tempest_asideContent_27MiH{max-width:28rem;font-size:var(--tempest-text-md);line-height:var(--tempest-leading-relaxed)}
|
|
7
|
+
.tempest_back_wf1QC{align-items:center;gap:var(--tempest-space-2);min-height:44px;padding:var(--tempest-space-2) var(--tempest-space-3);border-radius:var(--tempest-radius-md);color:inherit;font:inherit;font-size:var(--tempest-text-md);font-weight:var(--tempest-weight-medium);cursor:pointer;background:0 0;border:0;text-decoration:none;display:inline-flex}
|
|
8
|
+
.tempest_back_wf1QC:hover{text-decoration:underline}
|
|
9
|
+
.tempest_back_wf1QC:focus-visible{outline:var(--tempest-focus-ring-width) solid currentColor;outline-offset:var(--tempest-focus-ring-offset)}
|
|
10
|
+
.tempest_panel_4yoaM{background:var(--tempest-bg);justify-content:center;display:flex}
|
|
11
|
+
.tempest_sheet_BV27x{gap:var(--tempest-space-5);flex-direction:column;width:100%;max-width:28rem;display:flex}
|
|
12
|
+
.tempest_header_fglsK{gap:var(--tempest-space-1);flex-direction:column;display:flex}
|
|
13
|
+
.tempest_title_US-kY{color:var(--tempest-text);font-size:var(--tempest-text-3xl);font-weight:var(--tempest-weight-bold);line-height:var(--tempest-leading-tight);margin:0}
|
|
14
|
+
.tempest_subtitle_IHFzn{color:var(--tempest-text-muted);font-size:var(--tempest-text-md);margin:0}
|
|
15
|
+
.tempest_footer_n5iU8{color:var(--tempest-text-muted);font-size:var(--tempest-text-sm);text-align:center}
|
|
16
|
+
.tempest_stacked_r5S3c{background:var(--tempest-auth-page-bg);flex-direction:column;display:flex}
|
|
17
|
+
.tempest_stacked_r5S3c .tempest_aside_iQvZx{padding:calc(var(--tempest-space-16) + var(--tempest-safe-area-top,0px)) var(--tempest-space-5) var(--tempest-space-10)}
|
|
18
|
+
.tempest_stacked_r5S3c .tempest_back_wf1QC{top:calc(var(--tempest-space-3) + var(--tempest-safe-area-top,0px));left:var(--tempest-space-2);position:absolute}
|
|
19
|
+
.tempest_stacked_r5S3c .tempest_panel_4yoaM{padding:var(--tempest-space-8) var(--tempest-space-5) calc(var(--tempest-space-8) + var(--tempest-safe-area-bottom,0px));border-top-left-radius:calc(var(--tempest-radius-2xl) * 2);border-top-right-radius:calc(var(--tempest-radius-2xl) * 2);flex:1}
|
|
20
|
+
.tempest_split_Jd8Ru{grid-template-columns:1fr 1fr;display:grid}
|
|
21
|
+
.tempest_split_Jd8Ru .tempest_aside_iQvZx{padding:var(--tempest-space-12);background:var(--tempest-auth-page-bg)}
|
|
22
|
+
.tempest_split_Jd8Ru .tempest_back_wf1QC{top:var(--tempest-space-5);left:var(--tempest-space-5);position:absolute}
|
|
23
|
+
.tempest_split_Jd8Ru .tempest_panel_4yoaM{padding:var(--tempest-space-12) var(--tempest-space-8);align-items:center}
|
|
24
|
+
.tempest_card_DgL6v{justify-content:center;align-items:center;gap:var(--tempest-space-3);padding:var(--tempest-space-5);background:var(--tempest-auth-page-aside-bg,var(--tempest-surface));flex-direction:column;display:flex}
|
|
25
|
+
.tempest_cardBack_911m6{width:100%;max-width:28rem;color:var(--tempest-auth-page-aside-fg,var(--tempest-text))}
|
|
26
|
+
.tempest_card_DgL6v .tempest_panel_4yoaM{width:100%;max-width:28rem;padding:var(--tempest-space-8) var(--tempest-space-6);border:1px solid var(--tempest-border);border-radius:var(--tempest-radius-xl);box-shadow:var(--tempest-shadow-md)}
|
|
27
|
+
.tempest_cardBrand_U9HuK{align-items:center;gap:var(--tempest-space-2);color:var(--tempest-primary);font-size:var(--tempest-text-2xl);font-weight:var(--tempest-weight-bold);text-align:center;flex-direction:column;display:flex}
|
|
28
|
+
.tempest_card_DgL6v .tempest_header_fglsK{text-align:center}
|
|
29
|
+
@media (prefers-reduced-motion:no-preference){.tempest_back_wf1QC{transition:var(--tempest-transition-color)}}
|