@spotify-confidence/csr-common 0.0.0 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,103 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { installMockWsServer } from '../../test-utils';
3
+ import { WebSocketTransport } from './web-socket-transport';
4
+
5
+ const URL = 'ws://localhost:1234/sessions/stream?session_token=abc';
6
+
7
+ describe('WebSocketTransport', () => {
8
+ const setup = () => installMockWsServer(URL);
9
+
10
+ it('resolves ready() once the server accepts the connection', async () => {
11
+ setup();
12
+ const t = new WebSocketTransport(URL);
13
+ await expect(t.ready()).resolves.toBeUndefined();
14
+ });
15
+
16
+ it('rejects ready() when no server is reachable', async () => {
17
+ // Decoy server patches global WebSocket without registering one at URL — mock-socket
18
+ // fires close(1000) synchronously instead of leaning on the OS to refuse the connect.
19
+ installMockWsServer('ws://localhost:9999/decoy');
20
+ const t = new WebSocketTransport(URL);
21
+ await expect(t.ready()).rejects.toThrow(/initial-failed/);
22
+ });
23
+
24
+ it('sends frames as JSON once open', async () => {
25
+ const { nextMessage } = setup();
26
+ const t = new WebSocketTransport(URL);
27
+ await t.ready();
28
+
29
+ t.send({ tabId: 'tab-1', eventCounter: 0, data: { hello: 'world' } });
30
+
31
+ expect(JSON.parse(await nextMessage())).toEqual({
32
+ tabId: 'tab-1',
33
+ eventCounter: 0,
34
+ data: { hello: 'world' },
35
+ });
36
+ });
37
+
38
+ it('buffers frames sent before open and flushes them on connect', async () => {
39
+ const { nextMessages } = setup();
40
+ const t = new WebSocketTransport(URL);
41
+ // Synchronously enqueue before the open event fires.
42
+ t.send({ tabId: 'a', eventCounter: 0, data: 1 });
43
+ t.send({ tabId: 'a', eventCounter: 1, data: 2 });
44
+ await t.ready();
45
+
46
+ const [first, second] = await nextMessages(2);
47
+ expect([JSON.parse(first).eventCounter, JSON.parse(second).eventCounter]).toEqual([0, 1]);
48
+ });
49
+
50
+ it('reconnects on a graceful drain (code 1000) and emits state changes', async () => {
51
+ const { waitForConnection } = setup();
52
+ const t = new WebSocketTransport(URL);
53
+ const states: boolean[] = [];
54
+ t.onStateChange(({ connected }) => states.push(connected));
55
+ await t.ready();
56
+
57
+ const first = await waitForConnection();
58
+ first.close({ code: 1000, reason: 'drain', wasClean: true });
59
+ await waitForConnection(); // reconnect lands
60
+
61
+ // First open → no state event (welcome implies connected).
62
+ // Drain → state(false). Reconnect open → state(true).
63
+ await vi.waitFor(() => expect(states).toEqual([false, true]));
64
+ });
65
+
66
+ it('fires onClose with reason on abrupt close after open', async () => {
67
+ const { waitForConnection } = setup();
68
+ const t = new WebSocketTransport(URL);
69
+ const closeReasons: string[] = [];
70
+ t.onClose(({ reason }) => closeReasons.push(reason));
71
+ await t.ready();
72
+
73
+ const ws = await waitForConnection();
74
+ ws.close({ code: 1011, reason: 'server crash', wasClean: false });
75
+
76
+ await vi.waitFor(() => expect(closeReasons).toHaveLength(1));
77
+ expect(closeReasons[0]).toMatch(/code=1011/);
78
+ });
79
+
80
+ it('drops sends after close()', async () => {
81
+ const { messages, nextMessage } = setup();
82
+ const t = new WebSocketTransport(URL);
83
+ await t.ready();
84
+
85
+ // Send a frame before close — should arrive. Use it as a synchronization
86
+ // point so we know the server has caught up; anything after close() that
87
+ // had leaked through would already be in `messages` too.
88
+ t.send({ tabId: 'a', eventCounter: 0, data: 'before' });
89
+ await nextMessage();
90
+
91
+ t.close('test-shutdown');
92
+ t.send({ tabId: 'a', eventCounter: 99, data: 'after' });
93
+
94
+ // Send another marker on a *fresh* transport to the same server. Once it
95
+ // arrives, the closed transport's bad send (if it had leaked) would have
96
+ // landed first — assert by counting.
97
+ const t2 = new WebSocketTransport(URL);
98
+ await t2.ready();
99
+ t2.send({ tabId: 'b', eventCounter: 0, data: 'marker' });
100
+ await vi.waitFor(() => expect(messages).toHaveLength(2));
101
+ expect(messages.map(m => JSON.parse(m).data)).toEqual(['before', 'marker']);
102
+ });
103
+ });
@@ -0,0 +1,113 @@
1
+ import type { Frame, Transport } from '../types';
2
+
3
+ /**
4
+ * WebSocket-backed Transport. Internal retry policy: clean server-initiated close after the
5
+ * first successful open → reconnect and resume; abrupt close (or any close before the first
6
+ * open) → fire `onClose` and stop. Frames received while a (re)connect is in progress are
7
+ * buffered and flushed on open.
8
+ *
9
+ * `ready()` resolves on the first successful open and rejects on close-before-open. Callers
10
+ * should await it before treating the Transport as live, so a failure to open can be caught
11
+ * (e.g. 4404 unknown session) and recovered from.
12
+ */
13
+ export class WebSocketTransport implements Transport {
14
+ private ws: WebSocket | null = null;
15
+ private onCloseCb: ((info: { reason: string }) => void) | null = null;
16
+ private onStateChangeCb: ((info: { connected: boolean }) => void) | null = null;
17
+ private intentionallyClosed = false;
18
+ private dead = false;
19
+ /** Frames buffered while a (re)connect is in progress. */
20
+ private pending: Frame[] = [];
21
+ private readyPromise: Promise<void>;
22
+
23
+ constructor(private readonly url: string) {
24
+ this.readyPromise = new Promise<void>((resolve, reject) => {
25
+ this.connect(false, resolve, reject);
26
+ });
27
+ // Always attach a noop catch so an unawaited failure doesn't surface as an unhandled
28
+ // rejection; callers that care will await `ready()` themselves.
29
+ this.readyPromise.catch(() => {});
30
+ }
31
+
32
+ ready(): Promise<void> {
33
+ return this.readyPromise;
34
+ }
35
+
36
+ send(frame: Frame): void {
37
+ if (this.dead || this.intentionallyClosed) return;
38
+ if (this.ws?.readyState === WebSocket.OPEN) {
39
+ this.ws.send(JSON.stringify(frame));
40
+ } else {
41
+ this.pending.push(frame);
42
+ }
43
+ }
44
+
45
+ close(reason = 'transport-close'): void {
46
+ this.intentionallyClosed = true;
47
+ this.ws?.close(1000, reason);
48
+ }
49
+
50
+ onClose(cb: (info: { reason: string }) => void): void {
51
+ this.onCloseCb = cb;
52
+ }
53
+
54
+ onStateChange(cb: (info: { connected: boolean }) => void): void {
55
+ this.onStateChangeCb = cb;
56
+ }
57
+
58
+ private connect(isReconnect: boolean, onReady?: () => void, onReadyFail?: (err: Error) => void): void {
59
+ const ws = new WebSocket(this.url);
60
+ this.ws = ws;
61
+ let opened = false;
62
+
63
+ ws.onopen = () => {
64
+ opened = true;
65
+ onReady?.();
66
+ // Emit state on every successful open EXCEPT the very first one (welcome already
67
+ // implies connected=true). isReconnect distinguishes those.
68
+ if (isReconnect) {
69
+ this.onStateChangeCb?.({ connected: true });
70
+ }
71
+ while (this.pending.length > 0) {
72
+ const f = this.pending.shift()!;
73
+ ws.send(JSON.stringify(f));
74
+ }
75
+ };
76
+
77
+ ws.onclose = event => {
78
+ if (this.intentionallyClosed) return;
79
+ if (!opened) {
80
+ // Server rejected the connection before it opened (e.g. unknown session).
81
+ const stage = isReconnect ? 'reconnect' : 'initial';
82
+ const reason = `${stage}-failed code=${event.code}`;
83
+ if (onReadyFail) {
84
+ // First attempt — surface the failure to whoever is awaiting `ready()` so they
85
+ // can decide whether to recover (e.g. fall back to a fresh initSession).
86
+ onReadyFail(new Error(reason));
87
+ this.dead = true;
88
+ } else {
89
+ // Reconnect failed; the consumer is past `ready()` and only learns about it via onClose.
90
+ this.die(reason);
91
+ }
92
+ return;
93
+ }
94
+ // The WS opened and is now closing. Distinguish graceful drain (retry) from app
95
+ // rejection (terminal). Both can have wasClean=true at the protocol level, so we have
96
+ // to inspect the code: 1000/1001 are lifecycle closes ("come back"), 4xxx are
97
+ // application-level rejections ("don't come back"), anything else (1006 etc.) is
98
+ // abnormal.
99
+ const isGracefulDrain = event.wasClean && (event.code === 1000 || event.code === 1001);
100
+ if (isGracefulDrain) {
101
+ this.onStateChangeCb?.({ connected: false });
102
+ this.connect(true);
103
+ } else {
104
+ this.die(`close code=${event.code} wasClean=${event.wasClean}`);
105
+ }
106
+ };
107
+ }
108
+
109
+ private die(reason: string): void {
110
+ this.dead = true;
111
+ this.onCloseCb?.({ reason });
112
+ }
113
+ }
@@ -0,0 +1,3 @@
1
+ // Generated by scripts/build-worker.mjs at build time. Do not edit.
2
+ // Run `yarn workspace @spotify-confidence/csr-common build:worker` to regenerate.
3
+ export const workerScript: string = "//#region src/uploader/worker/web-socket-transport.ts\n/**\n* WebSocket-backed Transport. Internal retry policy: clean server-initiated close after the\n* first successful open → reconnect and resume; abrupt close (or any close before the first\n* open) → fire `onClose` and stop. Frames received while a (re)connect is in progress are\n* buffered and flushed on open.\n*\n* `ready()` resolves on the first successful open and rejects on close-before-open. Callers\n* should await it before treating the Transport as live, so a failure to open can be caught\n* (e.g. 4404 unknown session) and recovered from.\n*/\nvar WebSocketTransport = class {\n\turl;\n\tws = null;\n\tonCloseCb = null;\n\tonStateChangeCb = null;\n\tintentionallyClosed = false;\n\tdead = false;\n\t/** Frames buffered while a (re)connect is in progress. */\n\tpending = [];\n\treadyPromise;\n\tconstructor(url) {\n\t\tthis.url = url;\n\t\tthis.readyPromise = new Promise((resolve, reject) => {\n\t\t\tthis.connect(false, resolve, reject);\n\t\t});\n\t\tthis.readyPromise.catch(() => {});\n\t}\n\tready() {\n\t\treturn this.readyPromise;\n\t}\n\tsend(frame) {\n\t\tif (this.dead || this.intentionallyClosed) return;\n\t\tif (this.ws?.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(frame));\n\t\telse this.pending.push(frame);\n\t}\n\tclose(reason = \"transport-close\") {\n\t\tthis.intentionallyClosed = true;\n\t\tthis.ws?.close(1e3, reason);\n\t}\n\tonClose(cb) {\n\t\tthis.onCloseCb = cb;\n\t}\n\tonStateChange(cb) {\n\t\tthis.onStateChangeCb = cb;\n\t}\n\tconnect(isReconnect, onReady, onReadyFail) {\n\t\tconst ws = new WebSocket(this.url);\n\t\tthis.ws = ws;\n\t\tlet opened = false;\n\t\tws.onopen = () => {\n\t\t\topened = true;\n\t\t\tonReady?.();\n\t\t\tif (isReconnect) this.onStateChangeCb?.({ connected: true });\n\t\t\twhile (this.pending.length > 0) {\n\t\t\t\tconst f = this.pending.shift();\n\t\t\t\tws.send(JSON.stringify(f));\n\t\t\t}\n\t\t};\n\t\tws.onclose = (event) => {\n\t\t\tif (this.intentionallyClosed) return;\n\t\t\tif (!opened) {\n\t\t\t\tconst reason = `${isReconnect ? \"reconnect\" : \"initial\"}-failed code=${event.code}`;\n\t\t\t\tif (onReadyFail) {\n\t\t\t\t\tonReadyFail(new Error(reason));\n\t\t\t\t\tthis.dead = true;\n\t\t\t\t} else this.die(reason);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (event.wasClean && (event.code === 1e3 || event.code === 1001)) {\n\t\t\t\tthis.onStateChangeCb?.({ connected: false });\n\t\t\t\tthis.connect(true);\n\t\t\t} else this.die(`close code=${event.code} wasClean=${event.wasClean}`);\n\t\t};\n\t}\n\tdie(reason) {\n\t\tthis.dead = true;\n\t\tthis.onCloseCb?.({ reason });\n\t}\n};\n//#endregion\n//#region src/uploader/worker/csr-client.ts\n/**\n* Single Client implementation that talks to the recording backend's REST + WS protocol.\n* Both dev-server and prod implement the same protocol, so we don't need polymorphism here yet.\n*/\nvar CsrClient = class {\n\tapiUrl;\n\tclientSecret;\n\ttargetingKey;\n\tcontext;\n\twebsocketUrl;\n\tlog;\n\tforceRecord;\n\tconstructor(apiUrl, clientSecret, targetingKey, context, websocketUrl, log = () => {}, forceRecord) {\n\t\tthis.apiUrl = apiUrl;\n\t\tthis.clientSecret = clientSecret;\n\t\tthis.targetingKey = targetingKey;\n\t\tthis.context = context;\n\t\tthis.websocketUrl = websocketUrl;\n\t\tthis.log = log;\n\t\tthis.forceRecord = forceRecord;\n\t}\n\tasync initSession() {\n\t\tconst url = `${this.trimSlash(this.apiUrl)}/v1/sessions:initSession`;\n\t\tthis.log(`fetch POST ${url}`);\n\t\tconst res = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\tclientSecret: this.clientSecret,\n\t\t\t\t...this.targetingKey ? { targetingKey: this.targetingKey } : {},\n\t\t\t\t...this.context && Object.keys(this.context).length > 0 ? { context: this.context } : {},\n\t\t\t\t...this.forceRecord ? { forceRecord: true } : {}\n\t\t\t})\n\t\t});\n\t\tif (!res.ok) throw new Error(`init-session failed: HTTP ${res.status}`);\n\t\tconst data = await res.json();\n\t\tif (data.skipRecording) return { skipRecording: true };\n\t\tif (!data.sessionId || !data.sessionToken) throw new Error(\"init-session response missing sessionId or sessionToken\");\n\t\treturn {\n\t\t\tsessionId: data.sessionId,\n\t\t\tsessionToken: data.sessionToken\n\t\t};\n\t}\n\tasync openTransport(sessionToken) {\n\t\tconst wsBase = this.websocketUrl ?? `${this.toWsScheme(this.trimSlash(this.apiUrl))}/sessions/stream`;\n\t\tconst url = `${wsBase}${wsBase.includes(\"?\") ? \"&\" : \"?\"}session_token=${encodeURIComponent(sessionToken)}`;\n\t\tthis.log(`WebSocket connect ${url}`);\n\t\tconst transport = new WebSocketTransport(url);\n\t\tawait transport.ready();\n\t\treturn transport;\n\t}\n\ttrimSlash(s) {\n\t\treturn s.endsWith(\"/\") ? s.slice(0, -1) : s;\n\t}\n\ttoWsScheme(base) {\n\t\tif (base.startsWith(\"https://\")) return `wss://${base.slice(8)}`;\n\t\tif (base.startsWith(\"http://\")) return `ws://${base.slice(7)}`;\n\t\treturn base;\n\t}\n};\n//#endregion\n//#region src/uploader/worker/core.ts\nconst IDLE_GRACE_MS = 5e3;\nlet state = { phase: \"init\" };\nconst ports = [];\nlet idleTimer = null;\nfunction cancelIdleTimer() {\n\tif (idleTimer !== null) {\n\t\tclearTimeout(idleTimer);\n\t\tidleTimer = null;\n\t}\n}\nfunction log(msg) {\n\tfor (const handle of ports) if (handle.debugLogs) handle.port.postMessage({\n\t\ttype: \"log\",\n\t\tmsg\n\t});\n}\n/**\n* The first hello \"locks in\" the session's apiUrl/clientSecret. Any later tab arriving\n* with different values is misconfigured — we reject it rather than silently using the\n* locked values. In SharedWorker mode the `name = hash(clientSecret)` scoping already\n* prevents secret-mismatch from sharing a worker, but this defends against the dedicated\n* path and against future bugs.\n*/\nlet lockedConfig = null;\nfunction registerPort(adapter) {\n\tcancelIdleTimer();\n\tconst handle = {\n\t\tport: adapter,\n\t\thello: null,\n\t\tdebugLogs: false\n\t};\n\tports.push(handle);\n\tadapter.onmessage((data) => {\n\t\thandleMessage(handle, data);\n\t});\n}\nfunction handleMessage(handle, message) {\n\tswitch (message.type) {\n\t\tcase \"hello\":\n\t\t\thandle.hello = message;\n\t\t\thandle.debugLogs = message.debugLogs ?? false;\n\t\t\tif (rejectIfIncompatible(handle)) return;\n\t\t\tif (state.phase !== \"dead\" && state.phase !== \"skipping\") detectDuplicateTab(handle);\n\t\t\tonHello(handle);\n\t\t\treturn;\n\t\tcase \"frame\":\n\t\t\tonFrame(message.frame);\n\t\t\treturn;\n\t\tcase \"bye\":\n\t\t\tonBye(handle);\n\t\t\treturn;\n\t\tdefault: break;\n\t}\n}\n/**\n* Reject hellos whose `apiUrl`/`clientSecret` don't match the values established by the\n* first hello. Returns true if the port was rejected (caller should not continue\n* processing this hello).\n*/\nfunction rejectIfIncompatible(handle) {\n\tif (lockedConfig === null) return false;\n\tconst incoming = handle.hello;\n\tif (incoming.apiUrl === lockedConfig.apiUrl && incoming.websocketUrl === lockedConfig.websocketUrl && incoming.clientSecret === lockedConfig.clientSecret) return false;\n\thandle.port.postMessage({\n\t\ttype: \"dead\",\n\t\treason: \"incompatible-options: apiUrl/websocketUrl/clientSecret differ from the worker session\"\n\t});\n\tconst idx = ports.indexOf(handle);\n\tif (idx >= 0) ports.splice(idx, 1);\n\treturn true;\n}\n/**\n* If another already-connected port has the same `tabId`, this hello is from a duplicate\n* tab (browser \"Duplicate\" command clones sessionStorage). Mint a fresh `tabId` so the two\n* tabs don't collide on the same `(sessionId, tabId)` Recording. The new tabId is returned\n* to the tab in `welcome` so it can update its own state and sessionStorage.\n*/\nfunction detectDuplicateTab(handle) {\n\tconst tabId = handle.hello.tabId;\n\tif (!ports.some((p) => p !== handle && p.hello?.tabId === tabId)) return;\n\tconst fresh = crypto.randomUUID();\n\thandle.newTabId = fresh;\n\thandle.hello.tabId = fresh;\n}\nfunction onHello(handle) {\n\tswitch (state.phase) {\n\t\tcase \"init\":\n\t\t\tlockedConfig = {\n\t\t\t\tapiUrl: handle.hello.apiUrl,\n\t\t\t\twebsocketUrl: handle.hello.websocketUrl,\n\t\t\t\tclientSecret: handle.hello.clientSecret\n\t\t\t};\n\t\t\tlog(`hello received apiUrl=${handle.hello.apiUrl} websocketUrl=${handle.hello.websocketUrl ?? \"(derive)\"} sessionIdHint=${handle.hello.sessionIdHint ?? \"(none)\"}`);\n\t\t\tstate = { phase: \"initializing\" };\n\t\t\tinitializeSession(handle.hello).then(flushPendingWelcomes);\n\t\t\treturn;\n\t\tcase \"initializing\": return;\n\t\tcase \"active\":\n\t\t\tsendActiveWelcome(handle, state.sessionId, state.sessionToken);\n\t\t\treturn;\n\t\tcase \"idle\": {\n\t\t\tconst { client, sessionId, sessionToken } = state;\n\t\t\tstate = { phase: \"initializing\" };\n\t\t\tresumeTransport(client, sessionId, sessionToken).then(flushPendingWelcomes);\n\t\t\treturn;\n\t\t}\n\t\tcase \"skipping\":\n\t\t\tif (handle.hello.forceRecord) {\n\t\t\t\tlog(\"forceRecord set; re-initializing from skipping state\");\n\t\t\t\tstate = { phase: \"initializing\" };\n\t\t\t\tinitializeSession(handle.hello).then(flushPendingWelcomes);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\thandle.port.postMessage({\n\t\t\t\ttype: \"welcome\",\n\t\t\t\tresult: { skipRecording: true }\n\t\t\t});\n\t\t\treturn;\n\t\tcase \"dead\":\n\t\t\thandle.port.postMessage({\n\t\t\t\ttype: \"dead\",\n\t\t\t\treason: state.reason\n\t\t\t});\n\t\t\treturn;\n\t\tdefault: break;\n\t}\n}\nasync function initializeSession(firstHello) {\n\tconst client = new CsrClient(firstHello.apiUrl, firstHello.clientSecret, firstHello.targetingKey, firstHello.context, firstHello.websocketUrl, log, firstHello.forceRecord);\n\tif (firstHello.sessionIdHint && firstHello.sessionTokenHint) {\n\t\tlog(`adopting sessionIdHint=${firstHello.sessionIdHint}`);\n\t\ttry {\n\t\t\tconst transport = await client.openTransport(firstHello.sessionTokenHint);\n\t\t\twireTransport(transport);\n\t\t\tstate = {\n\t\t\t\tphase: \"active\",\n\t\t\t\tclient,\n\t\t\t\ttransport,\n\t\t\t\tsessionId: firstHello.sessionIdHint,\n\t\t\t\tsessionToken: firstHello.sessionTokenHint\n\t\t\t};\n\t\t\tlog(\"hint adopted; transport open\");\n\t\t\tif (ports.length === 0) idleTimer = setTimeout(enterIdle, IDLE_GRACE_MS);\n\t\t\treturn;\n\t\t} catch (err) {\n\t\t\tlog(`hint rejected (${String(err)}); falling back to fresh init`);\n\t\t}\n\t}\n\tlet result;\n\ttry {\n\t\tresult = await client.initSession();\n\t} catch (err) {\n\t\tlog(`init-session threw: ${String(err)}`);\n\t\ttransitionToDead(`init-session-failed: ${String(err)}`);\n\t\treturn;\n\t}\n\tif (\"skipRecording\" in result) {\n\t\tlog(\"init-session: skipRecording\");\n\t\tstate = { phase: \"skipping\" };\n\t\treturn;\n\t}\n\tlog(`init-session ok sessionId=${result.sessionId}`);\n\tlet transport;\n\ttry {\n\t\ttransport = await client.openTransport(result.sessionToken);\n\t} catch (err) {\n\t\tlog(`openTransport threw: ${String(err)}`);\n\t\ttransitionToDead(`open-transport-failed: ${String(err)}`);\n\t\treturn;\n\t}\n\twireTransport(transport);\n\tlog(\"transport open; session active\");\n\tstate = {\n\t\tphase: \"active\",\n\t\tclient,\n\t\ttransport,\n\t\tsessionId: result.sessionId,\n\t\tsessionToken: result.sessionToken\n\t};\n\tif (ports.length === 0) idleTimer = setTimeout(enterIdle, IDLE_GRACE_MS);\n}\nasync function resumeTransport(client, sessionId, sessionToken) {\n\tlog(\"resuming transport from idle\");\n\tlet transport;\n\ttry {\n\t\ttransport = await client.openTransport(sessionToken);\n\t} catch (err) {\n\t\tlog(`resume-transport threw: ${String(err)}`);\n\t\ttransitionToDead(`resume-transport-failed: ${String(err)}`);\n\t\treturn;\n\t}\n\twireTransport(transport);\n\tlog(\"transport resumed\");\n\tstate = {\n\t\tphase: \"active\",\n\t\tclient,\n\t\ttransport,\n\t\tsessionId,\n\t\tsessionToken\n\t};\n\tif (ports.length === 0) idleTimer = setTimeout(enterIdle, IDLE_GRACE_MS);\n}\nfunction wireTransport(transport) {\n\ttransport.onClose((info) => {\n\t\tif (state.phase !== \"active\") return;\n\t\ttransitionToDead(info.reason);\n\t});\n\ttransport.onStateChange((info) => {\n\t\tif (state.phase !== \"active\") return;\n\t\tfor (const handle of ports) handle.port.postMessage({\n\t\t\ttype: \"state\",\n\t\t\tconnected: info.connected\n\t\t});\n\t});\n}\nfunction transitionToDead(reason) {\n\tstate = {\n\t\tphase: \"dead\",\n\t\treason\n\t};\n\tfor (const handle of ports) handle.port.postMessage({\n\t\ttype: \"dead\",\n\t\treason\n\t});\n}\nfunction flushPendingWelcomes() {\n\tfor (const handle of ports) {\n\t\tif (handle.hello === null) continue;\n\t\tif (state.phase === \"active\") sendActiveWelcome(handle, state.sessionId, state.sessionToken);\n\t\telse if (state.phase === \"skipping\") handle.port.postMessage({\n\t\t\ttype: \"welcome\",\n\t\t\tresult: { skipRecording: true }\n\t\t});\n\t\telse if (state.phase === \"dead\") handle.port.postMessage({\n\t\t\ttype: \"dead\",\n\t\t\treason: state.reason\n\t\t});\n\t}\n}\nfunction sendActiveWelcome(handle, currentSessionId, currentSessionToken) {\n\tconst hint = handle.hello?.sessionIdHint;\n\tconst adopted = hint !== void 0 && hint !== currentSessionId;\n\tconst newTabId = handle.newTabId;\n\thandle.port.postMessage({\n\t\ttype: \"welcome\",\n\t\tresult: {\n\t\t\tsessionId: currentSessionId,\n\t\t\tsessionToken: currentSessionToken\n\t\t},\n\t\tadoptedFromSessionId: adopted ? hint : void 0,\n\t\tnewTabId,\n\t\tresetCounter: adopted || newTabId !== void 0\n\t});\n}\nfunction onFrame(frame) {\n\tif (state.phase !== \"active\") return;\n\tstate.transport.send(frame);\n}\nfunction onBye(handle) {\n\tconst idx = ports.indexOf(handle);\n\tif (idx >= 0) ports.splice(idx, 1);\n\tif (ports.length === 0 && state.phase === \"active\") {\n\t\tlog(`last tab disconnected; closing transport in ${IDLE_GRACE_MS}ms`);\n\t\tidleTimer = setTimeout(enterIdle, IDLE_GRACE_MS);\n\t}\n}\nfunction enterIdle() {\n\tidleTimer = null;\n\tif (state.phase !== \"active\" || ports.length > 0) return;\n\tlog(\"idle timeout; closing transport\");\n\tstate.transport.close(\"idle\");\n\tstate = {\n\t\tphase: \"idle\",\n\t\tclient: state.client,\n\t\tsessionId: state.sessionId,\n\t\tsessionToken: state.sessionToken\n\t};\n}\n//#endregion\n//#region src/uploader/worker/entry.ts\nconst SharedWorkerScopeCtor = globalThis.SharedWorkerGlobalScope;\nif (typeof SharedWorkerScopeCtor === \"function\" && self instanceof SharedWorkerScopeCtor) self.onconnect = (event) => {\n\tconst port = event.ports[0];\n\tport.start();\n\tregisterPort(adaptMessagePort(port));\n};\nelse registerPort(adaptDedicatedSelf());\nfunction adaptMessagePort(port) {\n\treturn {\n\t\tpostMessage: (message) => port.postMessage(message),\n\t\tonmessage: (cb) => {\n\t\t\tport.onmessage = (e) => cb(e.data);\n\t\t}\n\t};\n}\nfunction adaptDedicatedSelf() {\n\tconst ws = self;\n\treturn {\n\t\tpostMessage: (message) => ws.postMessage(message),\n\t\tonmessage: (cb) => {\n\t\t\tws.onmessage = (e) => cb(e.data);\n\t\t}\n\t};\n}\n//#endregion\n";
package/src/url.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Extract only the pathname from a URL, stripping origin, query string, and
3
+ * hash. Used across recorder and analyzer to avoid capturing PII in route data.
4
+ */
5
+ export function stripUrl(url: string): string {
6
+ try {
7
+ return new URL(url).pathname;
8
+ } catch (_e) {
9
+ return url;
10
+ }
11
+ }