@nagoorkani/session-capture-vue 0.1.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/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ PROPRIETARY SOFTWARE LICENSE
2
+
3
+ Copyright (c) 2026 Nagoorkani2393. All rights reserved.
4
+
5
+ This software, its source code, and its accompanying documentation (the
6
+ "Software") are the proprietary and confidential property of the copyright
7
+ holder.
8
+
9
+ NO LICENSE IS GRANTED. No person or entity is permitted to use, copy, modify,
10
+ merge, publish, distribute, sublicense, reverse engineer, create derivative
11
+ works from, or sell the Software, in whole or in part, by any means, except
12
+ under a separate written agreement signed by the copyright holder.
13
+
14
+ Availability of the Software through a public package registry, source
15
+ repository, or any other distribution channel is for the convenience of
16
+ authorized licensees only. It does not grant any license, right, or permission
17
+ to the general public, and no such license may be implied from that
18
+ availability. Unauthorized use, reproduction, or distribution is prohibited.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,110 @@
1
+ # @nagoorkani/session-capture-vue
2
+
3
+ Session capture and observability for Vue 3 applications. The capture itself is
4
+ [`@nagoorkani/session-capture-core`](../core/README.md), shared with the Expo SDK; this
5
+ package is the browser and the Vue of it.
6
+
7
+ Not published to npm yet — install the directory from a checkout.
8
+
9
+ ## Setup
10
+
11
+ ```ts
12
+ import { createApp } from 'vue'
13
+ import { sessionCapture } from '@nagoorkani/session-capture-vue'
14
+ import router from './router'
15
+
16
+ createApp(App)
17
+ .use(router)
18
+ .use(
19
+ sessionCapture({
20
+ apiKey: 'pk_live_…',
21
+ projectId: 'project_…',
22
+ endpoint: 'https://your-ingestion-host',
23
+ appVersion: '1.4.0',
24
+ // Optional: route changes become screen views. Passed in rather than
25
+ // imported, so the SDK never makes vue-router a dependency of an
26
+ // application that routes some other way.
27
+ router,
28
+ }),
29
+ )
30
+ .mount('#app')
31
+ ```
32
+
33
+ The ingestion key is public by design — it may only write events, never read
34
+ them, and on the web it is visible in the page source whatever you do.
35
+
36
+ Installing during server rendering is a no-op. There is no session, no storage
37
+ and no user on the server, and a `fetch` patch installed in a Node process
38
+ would capture every request that process makes for every visitor at once.
39
+
40
+ ## Capturing
41
+
42
+ ```ts
43
+ import { track, screen, identify, breadcrumb, captureException } from '@nagoorkani/session-capture-vue'
44
+
45
+ track('checkout_started', { cart: 3 })
46
+ identify('user_42', { plan: 'pro' })
47
+ breadcrumb('coupon applied')
48
+ captureException(error, { where: 'checkout' })
49
+ ```
50
+
51
+ `useSessionCapture()` returns the same functions for components that prefer an
52
+ injection. They are module-level, so a store, an interceptor or a plain utility
53
+ can import them directly — most of the code that wants to report something is
54
+ not a component.
55
+
56
+ Uncaught errors and unhandled rejections are captured automatically. So are
57
+ errors thrown inside components, which Vue catches itself and would otherwise
58
+ never reach `window` — the plugin chains `app.config.errorHandler` rather than
59
+ replacing it, so whatever the application already had there still runs.
60
+
61
+ ## Sessions
62
+
63
+ **One per tab.** A session lives in `sessionStorage`, so a reload continues it
64
+ — on the web a full navigation is normal, not a crash, and cutting the timeline
65
+ at every one of them would make sessions meaningless. Two tabs are two visits
66
+ and get two sessions; both carry the same `anonymousId`, which lives in
67
+ `localStorage` beside the queue.
68
+
69
+ A session also ends after 30 minutes of inactivity, and the backend closes one
70
+ that stops reporting. Sampling is decided once, at session start, and never
71
+ per event.
72
+
73
+ ## Delivery
74
+
75
+ Batches are written to `localStorage` before any network attempt, so a tab
76
+ closed between capture and send loses nothing — the batch goes out on the next
77
+ visit. The batch captured *as* the tab closes goes out immediately instead, on
78
+ a `keepalive` request, which is the only kind a browser promises to finish
79
+ after the page is gone.
80
+
81
+ `beforeunload` is deliberately not used: registering one disqualifies the page
82
+ from the back/forward cache in every current browser, which is a real
83
+ performance regression to impose on a host application for the sake of
84
+ telemetry.
85
+
86
+ ## Size
87
+
88
+ ```bash
89
+ pnpm --filter @nagoorkani/session-capture-vue size
90
+ ```
91
+
92
+ Budgeted at 30 KB minified, tighter than the mobile SDK's 50 KB: this one is
93
+ fetched over the network on every cold visit rather than shipped inside a
94
+ binary once.
95
+
96
+ ## Visual replay
97
+
98
+ [`@nagoorkani/session-capture-vue-replay`](../vue-replay/README.md) records the DOM with
99
+ rrweb and the dashboard replays it. A separate package because rrweb is several
100
+ times the size of this one, and most projects will not turn it on.
101
+
102
+ ## Requirements
103
+
104
+ Vue 3.3 or newer, and an ingestion service that allows the page's origin.
105
+
106
+ ## License
107
+
108
+ Proprietary — all rights reserved. See [LICENSE](./LICENSE). No use, copying,
109
+ modification or distribution is permitted without a written agreement with the
110
+ copyright holder.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * What the browser is, attached to `session_start`.
3
+ *
4
+ * Three short fields, sized to the columns that hold them: `platform` is an
5
+ * enum, `osVersion` is 32 characters and `deviceModel` is 64. A raw user-agent
6
+ * string is neither short enough nor useful enough to put in either.
7
+ *
8
+ * ponytail: four string checks, not a user-agent parser. Those are a
9
+ * dependency-sized thing that is wrong again within months, and these fields
10
+ * are display-only — the dashboard shows them beside a session and nothing
11
+ * branches on them. `navigator.userAgentData` is used where it exists because
12
+ * it is the answer the browser gives directly.
13
+ */
14
+ export interface WebContext {
15
+ platform?: 'web';
16
+ osVersion?: string;
17
+ deviceModel?: string;
18
+ appVersion?: string;
19
+ }
20
+ export declare function readWebContext(appVersion?: string): WebContext;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * What the browser is, attached to `session_start`.
3
+ *
4
+ * Three short fields, sized to the columns that hold them: `platform` is an
5
+ * enum, `osVersion` is 32 characters and `deviceModel` is 64. A raw user-agent
6
+ * string is neither short enough nor useful enough to put in either.
7
+ *
8
+ * ponytail: four string checks, not a user-agent parser. Those are a
9
+ * dependency-sized thing that is wrong again within months, and these fields
10
+ * are display-only — the dashboard shows them beside a session and nothing
11
+ * branches on them. `navigator.userAgentData` is used where it exists because
12
+ * it is the answer the browser gives directly.
13
+ */
14
+ /** The browser's own name for itself, in order of who impersonates whom. */
15
+ const BROWSERS = [
16
+ ['Edge', 'Edg/'],
17
+ ['Firefox', 'Firefox/'],
18
+ ['Chrome', 'Chrome/'],
19
+ ['Safari', 'Version/'],
20
+ ];
21
+ function browserName(userAgent) {
22
+ for (const [name, marker] of BROWSERS) {
23
+ const at = userAgent.indexOf(marker);
24
+ if (at === -1)
25
+ continue;
26
+ const version = userAgent.slice(at + marker.length).split(/[ .]/)[0];
27
+ return version ? `${name} ${version}` : name;
28
+ }
29
+ return undefined;
30
+ }
31
+ export function readWebContext(appVersion) {
32
+ const context = { platform: 'web' };
33
+ if (appVersion)
34
+ context.appVersion = appVersion;
35
+ try {
36
+ const navigator = globalThis.navigator;
37
+ if (!navigator)
38
+ return context;
39
+ const platform = navigator.userAgentData?.platform;
40
+ if (platform)
41
+ context.osVersion = platform.slice(0, 32);
42
+ const named = browserName(navigator.userAgent ?? '');
43
+ if (named)
44
+ context.deviceModel = named.slice(0, 64);
45
+ }
46
+ catch {
47
+ // A browser that hides all of this still gets a session, with the columns
48
+ // left null — which the dashboard already renders as "unknown".
49
+ }
50
+ return context;
51
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * @nagoorkani/session-capture-vue
3
+ *
4
+ * Public surface and browser wiring. Everything the SDK does to the host page
5
+ * — patching `fetch`, listening for errors and visibility, holding a queue in
6
+ * `localStorage` — is installed here and unwound by `shutdown()`.
7
+ *
8
+ * The capture itself is `@nagoorkani/session-capture-core`, shared with the Expo SDK.
9
+ * What differs on the web is three things and this file is all three: where
10
+ * bytes are stored, what a session boundary is, and that Vue swallows its own
11
+ * component errors.
12
+ */
13
+ import { type InitOptions, type RemoteConfig } from '@nagoorkani/session-capture-core';
14
+ export type { CaptureEvent, EventBatch, EventType, InitOptions, RemoteConfig, Breadcrumb, CapturedError, NetworkEvent, } from '@nagoorkani/session-capture-core';
15
+ export { SCHEMA_VERSION, DEFAULT_CONFIG, SDK_VERSION } from '@nagoorkani/session-capture-core';
16
+ export { isSelfDisabled, safe, safeAsync } from '@nagoorkani/session-capture-core';
17
+ export { isSampled } from '@nagoorkani/session-capture-core';
18
+ /**
19
+ * Start the SDK.
20
+ *
21
+ * Safe to call during server rendering, where it does nothing. Pass
22
+ * `enabled: false` to initialize without capturing, then `setEnabled(true)`
23
+ * once the user consents — nothing is captured *or* buffered while disabled.
24
+ */
25
+ export declare const init: (options: InitOptions) => void | undefined;
26
+ /** Enable or disable capture at runtime. The consent gate. */
27
+ export declare const setEnabled: (enabled: boolean) => void | undefined;
28
+ /** Whether the SDK is currently capturing. */
29
+ export declare const isEnabled: () => boolean;
30
+ /** A custom event. */
31
+ export declare const track: (name: string, properties?: Record<string, unknown> | undefined) => void | undefined;
32
+ /** The route the user is now on. Called for you if you pass a router. */
33
+ export declare const screen: (name: string) => void | undefined;
34
+ /** Attach a known user to this session. The erasure target. */
35
+ export declare const identify: (userId: string, traits?: Record<string, unknown> | undefined) => void | undefined;
36
+ /** Send everything held right now. */
37
+ export declare const flush: () => Promise<void | undefined>;
38
+ /** Batches waiting in the queue, for tests and diagnostics. */
39
+ export declare const pendingBatches: () => Promise<number>;
40
+ /** The config in force, after remote config has loaded. */
41
+ export declare const currentConfig: () => RemoteConfig;
42
+ /** Report a caught error the page handled itself. */
43
+ export declare const captureException: (error: unknown, extra?: Record<string, unknown> | undefined) => void | undefined;
44
+ /** Leave a note for whatever error comes next. */
45
+ export declare const breadcrumb: (message: string, data?: Record<string, unknown> | undefined) => void | undefined;
46
+ /**
47
+ * Notified as each session begins — the seam the optional replay package
48
+ * hangs off. Core does not know what replay is and must not.
49
+ */
50
+ export declare const onSession: (listener: (sessionId: string) => void) => () => void;
51
+ /** Notified after an error is captured. Replay records those regardless of sampling. */
52
+ export declare const onError: (listener: (sessionId: string) => void) => () => void;
53
+ /**
54
+ * Count recording as activity.
55
+ *
56
+ * A page nobody is clicking still emits no events, so a session being recorded
57
+ * would idle out underneath the recorder and the segments would arrive for a
58
+ * session the backend had already closed.
59
+ */
60
+ export declare const keepSessionAlive: () => void | undefined;
61
+ /** Stop capturing and unwind everything installed on the page. */
62
+ export declare const shutdown: () => void | undefined;
63
+ /** A `vue-router` instance, described by the two members used here. */
64
+ export interface RouterLike {
65
+ afterEach(hook: (to: {
66
+ name?: unknown;
67
+ path: string;
68
+ }) => void): void;
69
+ currentRoute?: {
70
+ value?: {
71
+ name?: unknown;
72
+ path: string;
73
+ };
74
+ };
75
+ }
76
+ /** Just enough of `App` to install, without importing `vue`. */
77
+ interface AppLike {
78
+ config: {
79
+ errorHandler?: unknown;
80
+ globalProperties: Record<string, unknown>;
81
+ };
82
+ provide(key: symbol | string, value: unknown): void;
83
+ }
84
+ export interface VuePluginOptions extends InitOptions {
85
+ /**
86
+ * Your router, if you want route changes recorded as screen views.
87
+ *
88
+ * Passed in rather than imported: `vue-router` is optional in a Vue app, and
89
+ * an SDK that imports it makes it mandatory. Applications that route some
90
+ * other way call `screen()` themselves.
91
+ */
92
+ router?: RouterLike;
93
+ /**
94
+ * Chain to whatever error handler the app already has. Defaults to true;
95
+ * the SDK never replaces one silently.
96
+ */
97
+ chainErrorHandler?: boolean;
98
+ }
99
+ /** What `useSessionCapture()` hands back. */
100
+ export interface SessionCaptureApi {
101
+ track: typeof track;
102
+ screen: typeof screen;
103
+ identify: typeof identify;
104
+ breadcrumb: typeof breadcrumb;
105
+ captureException: typeof captureException;
106
+ }
107
+ export declare const SESSION_CAPTURE_KEY: unique symbol;
108
+ /**
109
+ * `app.use(sessionCapture({ apiKey, projectId, endpoint }))`.
110
+ *
111
+ * Installing during server rendering is a no-op inside `init`, so the same
112
+ * application entry file works for both.
113
+ */
114
+ export declare function sessionCapture(options: VuePluginOptions): {
115
+ install(app: AppLike): void;
116
+ };
117
+ /**
118
+ * The same functions, for components that prefer an injection.
119
+ *
120
+ * Deliberately not `inject()` from `vue`: these are module-level functions
121
+ * with no per-app state, so there is nothing an injection would resolve that
122
+ * an import does not — and importing `vue` here would make it a hard
123
+ * dependency of a package that otherwise has none.
124
+ */
125
+ export declare function useSessionCapture(): SessionCaptureApi;
package/dist/index.js ADDED
@@ -0,0 +1,327 @@
1
+ /**
2
+ * @nagoorkani/session-capture-vue
3
+ *
4
+ * Public surface and browser wiring. Everything the SDK does to the host page
5
+ * — patching `fetch`, listening for errors and visibility, holding a queue in
6
+ * `localStorage` — is installed here and unwound by `shutdown()`.
7
+ *
8
+ * The capture itself is `@nagoorkani/session-capture-core`, shared with the Expo SDK.
9
+ * What differs on the web is three things and this file is all three: where
10
+ * bytes are stored, what a session boundary is, and that Vue swallows its own
11
+ * component errors.
12
+ */
13
+ import { addBreadcrumb, CONFIG_DIR, DEFAULT_CONFIG, Dispatcher, fetchRemoteConfig, installErrorHandlers, installNetworkCapture, loadCachedConfig, MemoryStore, safe, safeAsync, saveConfig, SDK_VERSION, SdkCore, SendQueue, } from '@nagoorkani/session-capture-core';
14
+ import { readWebContext } from "./context.js";
15
+ import { installLifecycleListener } from "./lifecycle-browser.js";
16
+ import { loadSession, saveSession } from "./session-store.js";
17
+ import { createBrowserStore } from "./store-browser.js";
18
+ export { SCHEMA_VERSION, DEFAULT_CONFIG, SDK_VERSION } from '@nagoorkani/session-capture-core';
19
+ export { isSelfDisabled, safe, safeAsync } from '@nagoorkani/session-capture-core';
20
+ export { isSampled } from '@nagoorkani/session-capture-core';
21
+ /** How often the queue is drained in the background. */
22
+ const DRAIN_INTERVAL_MS = 30000;
23
+ /** Background config refresh. */
24
+ const CONFIG_REFRESH_MS = 6 * 60 * 60 * 1000;
25
+ /**
26
+ * Floor between config fetches, so a tab switched to and from constantly does
27
+ * not become a poll. Refetching on focus is what makes the kill switch take
28
+ * effect in minutes rather than hours.
29
+ */
30
+ const CONFIG_MIN_INTERVAL_MS = 15 * 60 * 1000;
31
+ let core = null;
32
+ let dispatcher = null;
33
+ let queue = null;
34
+ let configStore = null;
35
+ let drainTimer = null;
36
+ let configTimer = null;
37
+ let lastConfigFetch = 0;
38
+ const teardown = [];
39
+ /**
40
+ * True while the page is going away.
41
+ *
42
+ * Read by the transport on every send: an ordinary drain is a normal request,
43
+ * and the one made as the tab closes asks the browser to finish it anyway.
44
+ * Turning it on permanently would put every batch under the 64 KB keepalive
45
+ * cap for no reason.
46
+ */
47
+ let unloading = false;
48
+ /** Live options for the `fetch` patch, widened by remote config in place. */
49
+ const networkOptions = {
50
+ maskedKeys: [],
51
+ urlDenyList: [],
52
+ captureBodies: false,
53
+ };
54
+ /**
55
+ * Whether there is a page to instrument.
56
+ *
57
+ * Vue applications render on the server routinely. There is no session, no
58
+ * storage and no user there — and a `fetch` patch installed in a Node process
59
+ * would capture every other request the server makes, for every visitor at
60
+ * once. Initializing is therefore a no-op rather than an error.
61
+ */
62
+ function inBrowser() {
63
+ return typeof globalThis.window !== 'undefined' && typeof globalThis.document !== 'undefined';
64
+ }
65
+ function applyConfig(config) {
66
+ core?.applyConfig(config);
67
+ networkOptions.maskedKeys = config.maskedKeys;
68
+ networkOptions.urlDenyList = config.urlDenyList;
69
+ networkOptions.captureBodies = config.captureBodies;
70
+ }
71
+ /**
72
+ * Refresh remote config, honouring the fetch floor.
73
+ *
74
+ * A failed fetch leaves the current config alone rather than reverting to
75
+ * defaults — reverting would silently re-enable an SDK that was deliberately
76
+ * killed, at exactly the moment the network is unreliable.
77
+ */
78
+ async function refreshConfig(options, force = false) {
79
+ const now = Date.now();
80
+ if (!force && now - lastConfigFetch < CONFIG_MIN_INTERVAL_MS)
81
+ return;
82
+ lastConfigFetch = now;
83
+ const config = await fetchRemoteConfig({
84
+ endpoint: options.endpoint,
85
+ apiKey: options.apiKey,
86
+ projectId: options.projectId,
87
+ });
88
+ if (!config || !core)
89
+ return;
90
+ applyConfig(config);
91
+ if (configStore)
92
+ await saveConfig(configStore, config);
93
+ }
94
+ /** Cached copy first, so a cold load starts from the last known config. */
95
+ async function bootstrapConfig(options) {
96
+ if (configStore) {
97
+ const cached = await loadCachedConfig(configStore);
98
+ if (cached && core)
99
+ applyConfig(cached);
100
+ }
101
+ await refreshConfig(options, true);
102
+ }
103
+ /** Write the session down, so a reload resumes it instead of cutting it. */
104
+ function persistSession() {
105
+ saveSession(core?.session() ?? null);
106
+ }
107
+ /**
108
+ * Start the SDK.
109
+ *
110
+ * Safe to call during server rendering, where it does nothing. Pass
111
+ * `enabled: false` to initialize without capturing, then `setEnabled(true)`
112
+ * once the user consents — nothing is captured *or* buffered while disabled.
113
+ */
114
+ export const init = safe((options) => {
115
+ if (core || !inBrowser())
116
+ return;
117
+ // Persist first, send second. A batch is durable before any network attempt,
118
+ // so a tab closed between capture and delivery loses nothing.
119
+ const store = createBrowserStore() ?? new MemoryStore();
120
+ queue = new SendQueue({ store });
121
+ // A directory of its own: the queue deletes anything in its own directory
122
+ // that does not parse as a batch, which a config file does not.
123
+ configStore = createBrowserStore(CONFIG_DIR) ?? new MemoryStore();
124
+ dispatcher = new Dispatcher({
125
+ queue,
126
+ transport: {
127
+ endpoint: options.endpoint,
128
+ apiKey: options.apiKey,
129
+ sdkVersion: SDK_VERSION,
130
+ get keepalive() {
131
+ return unloading;
132
+ },
133
+ },
134
+ });
135
+ core = new SdkCore({
136
+ onFlush: async (batch) => {
137
+ await queue?.enqueue(batch);
138
+ void dispatcher?.drain();
139
+ },
140
+ deviceContext: () => ({ ...readWebContext(options.appVersion) }),
141
+ // One session per tab: `sessionStorage` survives a reload and dies with
142
+ // the tab, which is the same definition from the other side.
143
+ restoreSession: loadSession,
144
+ });
145
+ core.init(options);
146
+ persistSession();
147
+ // Not awaited: `init` stays synchronous and the session opens immediately.
148
+ void bootstrapConfig(options).catch(() => { });
149
+ teardown.push(installLifecycleListener((state) => {
150
+ core?.onAppStateChange(state);
151
+ if (state === 'background') {
152
+ // The last chance to do anything. A hidden tab may never run again —
153
+ // frozen into the back/forward cache, or simply closed — so the
154
+ // session is written down and the queue is drained with `keepalive`,
155
+ // which is the only request a browser promises to finish after the
156
+ // page is gone.
157
+ unloading = true;
158
+ persistSession();
159
+ void core?.flush().catch(() => { });
160
+ void dispatcher?.drain().catch(() => { });
161
+ return;
162
+ }
163
+ // Coming back is when a kill switch flipped overnight should take
164
+ // effect, and the most likely moment for connectivity to have returned.
165
+ unloading = false;
166
+ void refreshConfig(options).catch(() => { });
167
+ dispatcher?.resume();
168
+ void dispatcher?.drain();
169
+ }));
170
+ drainTimer = setInterval(() => {
171
+ void dispatcher?.drain();
172
+ persistSession();
173
+ }, DRAIN_INTERVAL_MS);
174
+ drainTimer?.unref?.();
175
+ configTimer = setInterval(() => {
176
+ void refreshConfig(options).catch(() => { });
177
+ }, CONFIG_REFRESH_MS);
178
+ configTimer?.unref?.();
179
+ teardown.push(installErrorHandlers((error) => core?.captureCrash(error)));
180
+ if (options.captureNetwork !== false) {
181
+ teardown.push(installNetworkCapture({
182
+ ingestEndpoint: options.endpoint,
183
+ get urlDenyList() {
184
+ return networkOptions.urlDenyList;
185
+ },
186
+ get maskedKeys() {
187
+ return networkOptions.maskedKeys;
188
+ },
189
+ get captureBodies() {
190
+ return networkOptions.captureBodies;
191
+ },
192
+ onEvent: (event) => core?.captureNetwork(event),
193
+ }));
194
+ }
195
+ }, undefined, 'init');
196
+ /** Enable or disable capture at runtime. The consent gate. */
197
+ export const setEnabled = safe((enabled) => {
198
+ core?.setEnabled(enabled);
199
+ }, undefined, 'setEnabled');
200
+ /** Whether the SDK is currently capturing. */
201
+ export const isEnabled = safe(() => core?.isEnabled() ?? false, false, 'isEnabled');
202
+ /** A custom event. */
203
+ export const track = safe((name, properties) => {
204
+ core?.capture('custom', { name, ...properties });
205
+ persistSession();
206
+ }, undefined, 'track');
207
+ /** The route the user is now on. Called for you if you pass a router. */
208
+ export const screen = safe((name) => {
209
+ core?.screen(name);
210
+ persistSession();
211
+ }, undefined, 'screen');
212
+ /** Attach a known user to this session. The erasure target. */
213
+ export const identify = safe((userId, traits) => {
214
+ core?.capture('user_action', { action: 'identify', userId, ...traits });
215
+ persistSession();
216
+ }, undefined, 'identify');
217
+ /** Send everything held right now. */
218
+ export const flush = safeAsync(async () => {
219
+ await core?.flush();
220
+ await dispatcher?.drain();
221
+ }, undefined, 'flush');
222
+ /** Batches waiting in the queue, for tests and diagnostics. */
223
+ export const pendingBatches = safeAsync(async () => (await queue?.size()) ?? 0, 0, 'pendingBatches');
224
+ /** The config in force, after remote config has loaded. */
225
+ export const currentConfig = safe(() => core?.currentConfig() ?? DEFAULT_CONFIG, DEFAULT_CONFIG, 'currentConfig');
226
+ /** Report a caught error the page handled itself. */
227
+ export const captureException = safe((error, extra) => {
228
+ core?.captureError(error, true, extra);
229
+ persistSession();
230
+ }, undefined, 'captureException');
231
+ /** Leave a note for whatever error comes next. */
232
+ export const breadcrumb = safe((message, data) => {
233
+ addBreadcrumb('custom', message, data);
234
+ }, undefined, 'breadcrumb');
235
+ /**
236
+ * Notified as each session begins — the seam the optional replay package
237
+ * hangs off. Core does not know what replay is and must not.
238
+ */
239
+ export const onSession = safe((listener) => core?.onSession(listener) ?? (() => { }), () => { }, 'onSession');
240
+ /** Notified after an error is captured. Replay records those regardless of sampling. */
241
+ export const onError = safe((listener) => core?.onError(listener) ?? (() => { }), () => { }, 'onError');
242
+ /**
243
+ * Count recording as activity.
244
+ *
245
+ * A page nobody is clicking still emits no events, so a session being recorded
246
+ * would idle out underneath the recorder and the segments would arrive for a
247
+ * session the backend had already closed.
248
+ */
249
+ export const keepSessionAlive = safe(() => {
250
+ core?.keepAlive();
251
+ persistSession();
252
+ }, undefined, 'keepSessionAlive');
253
+ /** Stop capturing and unwind everything installed on the page. */
254
+ export const shutdown = safe(() => {
255
+ for (const undo of teardown.splice(0)) {
256
+ try {
257
+ undo();
258
+ }
259
+ catch {
260
+ // Teardown must never throw into the host app.
261
+ }
262
+ }
263
+ if (drainTimer)
264
+ clearInterval(drainTimer);
265
+ if (configTimer)
266
+ clearInterval(configTimer);
267
+ drainTimer = null;
268
+ configTimer = null;
269
+ unloading = false;
270
+ core?.shutdown();
271
+ persistSession();
272
+ core = null;
273
+ dispatcher = null;
274
+ queue = null;
275
+ configStore = null;
276
+ lastConfigFetch = 0;
277
+ }, undefined, 'shutdown');
278
+ const api = { track, screen, identify, breadcrumb, captureException };
279
+ export const SESSION_CAPTURE_KEY = Symbol.for('session-capture');
280
+ /**
281
+ * `app.use(sessionCapture({ apiKey, projectId, endpoint }))`.
282
+ *
283
+ * Installing during server rendering is a no-op inside `init`, so the same
284
+ * application entry file works for both.
285
+ */
286
+ export function sessionCapture(options) {
287
+ return {
288
+ install(app) {
289
+ init(options);
290
+ // Vue catches errors thrown inside components and hands them here
291
+ // instead of letting them reach `window`. Without this hook a broken
292
+ // render — the most visible failure a user can have — would be the one
293
+ // error the SDK never sees.
294
+ if (options.chainErrorHandler !== false) {
295
+ const previous = app.config.errorHandler;
296
+ app.config.errorHandler = (error, instance, info) => {
297
+ captureException(error, { vueInfo: info });
298
+ // Always chain: swallowing this would take away the app's own
299
+ // reporting and Vue's development console warning.
300
+ previous?.(error, instance, info);
301
+ };
302
+ }
303
+ if (options.router) {
304
+ const name = (route) => typeof route.name === 'string' && route.name ? route.name : route.path;
305
+ // The route the app started on. `afterEach` fires on navigation, and
306
+ // the first page load is not one.
307
+ const current = options.router.currentRoute?.value;
308
+ if (current)
309
+ screen(name(current));
310
+ options.router.afterEach((to) => screen(name(to)));
311
+ }
312
+ app.provide(SESSION_CAPTURE_KEY, api);
313
+ app.config.globalProperties.$sessionCapture = api;
314
+ },
315
+ };
316
+ }
317
+ /**
318
+ * The same functions, for components that prefer an injection.
319
+ *
320
+ * Deliberately not `inject()` from `vue`: these are module-level functions
321
+ * with no per-app state, so there is nothing an injection would resolve that
322
+ * an import does not — and importing `vue` here would make it a hard
323
+ * dependency of a package that otherwise has none.
324
+ */
325
+ export function useSessionCapture() {
326
+ return api;
327
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Foreground and background, as a browser reports them.
3
+ *
4
+ * `visibilitychange` is the tab being switched away from or minimized;
5
+ * `pagehide` is it being closed, navigated away from, or frozen into the back/
6
+ * forward cache. Both mean the same thing to the SDK — stop, flush what is
7
+ * held — so both arrive as `'background'`.
8
+ *
9
+ * Deliberately not `beforeunload`. Registering one disqualifies the page from
10
+ * the back/forward cache in every current browser, which is a real performance
11
+ * regression to impose on a host app for the sake of telemetry.
12
+ */
13
+ export type AppStateKind = 'active' | 'background';
14
+ export type Unsubscribe = () => void;
15
+ export declare function installLifecycleListener(onChange: (state: AppStateKind) => void): Unsubscribe;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Foreground and background, as a browser reports them.
3
+ *
4
+ * `visibilitychange` is the tab being switched away from or minimized;
5
+ * `pagehide` is it being closed, navigated away from, or frozen into the back/
6
+ * forward cache. Both mean the same thing to the SDK — stop, flush what is
7
+ * held — so both arrive as `'background'`.
8
+ *
9
+ * Deliberately not `beforeunload`. Registering one disqualifies the page from
10
+ * the back/forward cache in every current browser, which is a real performance
11
+ * regression to impose on a host app for the sake of telemetry.
12
+ */
13
+ export function installLifecycleListener(onChange) {
14
+ const target = globalThis;
15
+ if (typeof target.addEventListener !== 'function')
16
+ return () => { };
17
+ const notify = (state) => {
18
+ try {
19
+ onChange(state);
20
+ }
21
+ catch {
22
+ // A listener must never be the reason a page fails to hide.
23
+ }
24
+ };
25
+ const onVisibility = () => {
26
+ notify(target.document?.visibilityState === 'hidden' ? 'background' : 'active');
27
+ };
28
+ const onHide = () => notify('background');
29
+ try {
30
+ target.addEventListener('visibilitychange', onVisibility);
31
+ target.addEventListener('pagehide', onHide);
32
+ }
33
+ catch {
34
+ return () => { };
35
+ }
36
+ return () => {
37
+ try {
38
+ target.removeEventListener?.('visibilitychange', onVisibility);
39
+ target.removeEventListener?.('pagehide', onHide);
40
+ }
41
+ catch {
42
+ // Ignore.
43
+ }
44
+ };
45
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The session, in `sessionStorage`.
3
+ *
4
+ * One session per tab, which is what `sessionStorage` already means: it
5
+ * survives a reload and dies with the tab. Two tabs are two visits and get two
6
+ * sessions; they are still one person, because `anonymousId` lives in
7
+ * `localStorage` alongside the queue.
8
+ *
9
+ * Without this a reload would start a new session, cutting every timeline at
10
+ * every full navigation — which on the web is a normal thing to do, not a
11
+ * crash.
12
+ */
13
+ import type { SessionState } from '@nagoorkani/session-capture-core';
14
+ /**
15
+ * Whatever was stored, if it still looks like a session.
16
+ *
17
+ * Validated field by field rather than trusted: this is a string another tab,
18
+ * a browser extension, or an older version of this SDK could have written, and
19
+ * a malformed one would poison every event's sequence number.
20
+ */
21
+ export declare function loadSession(): SessionState | null;
22
+ export declare function saveSession(state: SessionState | null): void;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The session, in `sessionStorage`.
3
+ *
4
+ * One session per tab, which is what `sessionStorage` already means: it
5
+ * survives a reload and dies with the tab. Two tabs are two visits and get two
6
+ * sessions; they are still one person, because `anonymousId` lives in
7
+ * `localStorage` alongside the queue.
8
+ *
9
+ * Without this a reload would start a new session, cutting every timeline at
10
+ * every full navigation — which on the web is a normal thing to do, not a
11
+ * crash.
12
+ */
13
+ const KEY = 'session-capture:session';
14
+ function storage() {
15
+ try {
16
+ return globalThis.sessionStorage ?? null;
17
+ }
18
+ catch {
19
+ // Blocked site data. The session simply does not survive a reload.
20
+ return null;
21
+ }
22
+ }
23
+ /**
24
+ * Whatever was stored, if it still looks like a session.
25
+ *
26
+ * Validated field by field rather than trusted: this is a string another tab,
27
+ * a browser extension, or an older version of this SDK could have written, and
28
+ * a malformed one would poison every event's sequence number.
29
+ */
30
+ export function loadSession() {
31
+ try {
32
+ const raw = storage()?.getItem(KEY);
33
+ if (!raw)
34
+ return null;
35
+ const value = JSON.parse(raw);
36
+ if (typeof value?.sessionId !== 'string' ||
37
+ typeof value.startedAt !== 'number' ||
38
+ typeof value.lastActivityAt !== 'number' ||
39
+ typeof value.sequence !== 'number' ||
40
+ typeof value.sampled !== 'boolean') {
41
+ return null;
42
+ }
43
+ return {
44
+ sessionId: value.sessionId,
45
+ startedAt: value.startedAt,
46
+ lastActivityAt: value.lastActivityAt,
47
+ sequence: value.sequence,
48
+ sampled: value.sampled,
49
+ screen: typeof value.screen === 'string' ? value.screen : null,
50
+ };
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ }
56
+ export function saveSession(state) {
57
+ try {
58
+ const store = storage();
59
+ if (!store)
60
+ return;
61
+ if (state === null)
62
+ store.removeItem(KEY);
63
+ else
64
+ store.setItem(KEY, JSON.stringify(state));
65
+ }
66
+ catch {
67
+ // Quota or blocked storage. The session lives in memory either way; only
68
+ // surviving a reload is lost.
69
+ }
70
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Durable storage in `localStorage`.
3
+ *
4
+ * The core's `FileStore` is four operations over named entries, which
5
+ * `localStorage` is already — the only work here is namespacing keys by
6
+ * directory so the queue and the config cache cannot see each other's files.
7
+ * `SendQueue.peek()` deletes everything it cannot parse as a batch, and a
8
+ * config file is one of those things.
9
+ *
10
+ * ponytail: `localStorage`, not IndexedDB. Its ~5 MB is far more than the
11
+ * queue's fifty batches, and it is synchronous, which removes a class of
12
+ * "tab closed mid-write" bug. IndexedDB when something needs to store frames.
13
+ */
14
+ import { type FileStore } from '@nagoorkani/session-capture-core';
15
+ /** Returns null where the browser has no usable storage. */
16
+ export declare function createBrowserStore(directory?: string): FileStore | null;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Durable storage in `localStorage`.
3
+ *
4
+ * The core's `FileStore` is four operations over named entries, which
5
+ * `localStorage` is already — the only work here is namespacing keys by
6
+ * directory so the queue and the config cache cannot see each other's files.
7
+ * `SendQueue.peek()` deletes everything it cannot parse as a batch, and a
8
+ * config file is one of those things.
9
+ *
10
+ * ponytail: `localStorage`, not IndexedDB. Its ~5 MB is far more than the
11
+ * queue's fifty batches, and it is synchronous, which removes a class of
12
+ * "tab closed mid-write" bug. IndexedDB when something needs to store frames.
13
+ */
14
+ import { QUEUE_DIR } from '@nagoorkani/session-capture-core';
15
+ /** Prefix, so one origin's other software is never mistaken for a batch. */
16
+ const NAMESPACE = 'session-capture';
17
+ /**
18
+ * `localStorage`, or null where it cannot be used.
19
+ *
20
+ * Reading the property itself throws in a browser configured to block site
21
+ * data, and is absent during server rendering — both are ordinary, and both
22
+ * mean the caller falls back to memory rather than failing to start.
23
+ */
24
+ function webStorage() {
25
+ try {
26
+ const storage = globalThis.localStorage;
27
+ if (!storage)
28
+ return null;
29
+ // Blocked storage can be present and throw only on use.
30
+ const probe = `${NAMESPACE}:probe`;
31
+ storage.setItem(probe, '1');
32
+ storage.removeItem(probe);
33
+ return storage;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ class BrowserStore {
40
+ // Explicit fields rather than parameter properties: Node's strip-only
41
+ // TypeScript mode rejects the shorthand, and running these files without a
42
+ // build step is worth more than the brevity.
43
+ constructor(storage, directory) {
44
+ this.storage = storage;
45
+ this.prefix = `${NAMESPACE}/${directory}/`;
46
+ }
47
+ async list() {
48
+ const names = [];
49
+ for (let index = 0; index < this.storage.length; index += 1) {
50
+ const key = this.storage.key(index);
51
+ if (key?.startsWith(this.prefix))
52
+ names.push(key.slice(this.prefix.length));
53
+ }
54
+ // The queue drains oldest first, and its names sort that way.
55
+ return names.sort();
56
+ }
57
+ async read(name) {
58
+ try {
59
+ return this.storage.getItem(this.prefix + name);
60
+ }
61
+ catch {
62
+ return null;
63
+ }
64
+ }
65
+ async write(name, contents) {
66
+ try {
67
+ this.storage.setItem(this.prefix + name, contents);
68
+ }
69
+ catch {
70
+ // Out of quota. Drop the oldest entry and try once more: losing the
71
+ // stalest batch is better than losing the one just captured, and better
72
+ // than throwing into whatever the host app was doing.
73
+ const [oldest] = await this.list();
74
+ if (oldest === undefined)
75
+ return;
76
+ try {
77
+ this.storage.removeItem(this.prefix + oldest);
78
+ this.storage.setItem(this.prefix + name, contents);
79
+ }
80
+ catch {
81
+ // Still no room. The batch is lost, which is what a full queue means.
82
+ }
83
+ }
84
+ }
85
+ async remove(name) {
86
+ try {
87
+ this.storage.removeItem(this.prefix + name);
88
+ }
89
+ catch {
90
+ // Ignore: a file that cannot be deleted is re-read and re-dropped.
91
+ }
92
+ }
93
+ }
94
+ /** Returns null where the browser has no usable storage. */
95
+ export function createBrowserStore(directory = QUEUE_DIR) {
96
+ const storage = webStorage();
97
+ return storage ? new BrowserStore(storage, directory) : null;
98
+ }
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@nagoorkani/session-capture-vue",
3
+ "version": "0.1.0",
4
+ "description": "Session capture and observability for Vue 3 applications",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "sideEffects": false,
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "keywords": [
22
+ "vue",
23
+ "observability",
24
+ "session-replay",
25
+ "analytics"
26
+ ],
27
+ "dependencies": {
28
+ "@nagoorkani/session-capture-core": "0.1.0"
29
+ },
30
+ "peerDependencies": {
31
+ "vue": ">=3.3"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "vue": {
35
+ "optional": true
36
+ }
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^22.0.0",
40
+ "esbuild": "^0.24.2",
41
+ "typescript": "^5.6.0"
42
+ },
43
+ "engines": {
44
+ "node": ">=22.6"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/Nagoorkani2393/session-capture.git",
49
+ "directory": "sdk/vue"
50
+ },
51
+ "homepage": "https://github.com/Nagoorkani2393/session-capture/tree/main/sdk/vue#readme",
52
+ "bugs": {
53
+ "url": "https://github.com/Nagoorkani2393/session-capture/issues"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "scripts": {
59
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
60
+ "typecheck": "tsc --noEmit",
61
+ "test": "node --test --experimental-strip-types \"src/**/*.test.ts\"",
62
+ "size": "node scripts/size.mjs"
63
+ }
64
+ }