@keploy/capture-sdk 3.0.1

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,363 @@
1
+ /**
2
+ * Top-level configuration accepted by the SDK initializer.
3
+ *
4
+ * WHAT LEAVES THE PAGE WHEN IT UNLOADS. Events are posted in batches
5
+ * (`batchSize`, `batchInterval`), gzipped where the browser can. When
6
+ * the document unloads — a navigation, a tab close — whatever is still
7
+ * queued is sent in one keepalive request, and the browser caps a
8
+ * document's keepalive bodies at 64 KiB: MEASURED in Chromium 145, a
9
+ * 65,536-byte body is accepted and a 65,537-byte body refused. That
10
+ * request carries the oldest queued events that fit, uncompressed; the
11
+ * first event that does not fit holds back everything behind it, and a
12
+ * document that is gone has no other way to send.
13
+ *
14
+ * So an event whose JSON alone is over 64 KiB — the DOM snapshot of a
15
+ * big page, a network event whose bodies approach `maxBodySize` — does
16
+ * not wait for the timer: it is posted as soon as it is queued (behind
17
+ * a batch already on the wire, if there is one; not while the browser
18
+ * reports itself offline), with keepalive when its gzipped body fits
19
+ * the quota. A body that does not fit even gzipped goes without
20
+ * keepalive, and a navigation before its upload completes cancels it.
21
+ * MEASURED in Chromium 145 on a 50 KB/s uplink, navigation once the
22
+ * request had left the browser and while its body was still uploading,
23
+ * 40 runs each at 4 parallel workers: a 90 KB gzipped body without
24
+ * keepalive arrived 0/40; a 60 KB gzipped body with keepalive arrived
25
+ * 40/40. The 90 KB body followed by a tab close instead of a
26
+ * navigation arrived 5/5 (5 runs). That loss is a gap the SDK cannot
27
+ * close from a document that is leaving.
28
+ *
29
+ * The post is gzipped before it leaves, and the browser's compression
30
+ * is asynchronous: a navigation that commits inside that window — a
31
+ * few milliseconds after the event was queued — finds no request on
32
+ * the wire yet, and the event is lost with the document like anything
33
+ * it never sent. MEASURED in the same setup with the navigation issued
34
+ * in the tick the event was queued, against a loopback server that
35
+ * commits the navigation in 2–3 ms: the 60 KB keepalive body arrived
36
+ * 38/40, and both losses had no POST in the browser's network log.
37
+ * `maxBodySize` bounds a network event's size; `privacy.blockSelectors`
38
+ * leaves subtrees out of the snapshot.
39
+ */
40
+ export interface CaptureConfig {
41
+ /** URL the captured events are shipped to. */
42
+ endpoint: string;
43
+ /** Project / workspace API key for authentication. */
44
+ apiKey: string;
45
+ /**
46
+ * Quick privacy preset. @default "balanced"
47
+ *
48
+ * - "balanced": the value of every input, textarea and select is
49
+ * masked, except the six listed below; visible text is recorded.
50
+ * - "strict" : that, and every visible text node is replaced with
51
+ * asterisks.
52
+ * - "off" : typed values are recorded — EXCEPT password fields
53
+ * and `<input type="hidden">`, which are masked in every mode.
54
+ * This docstring used to say "no automatic masking", which was
55
+ * never true: rrweb's maskInputOptions keeps `password: true` here,
56
+ * MEASURED in record() (rrweb.js:13778-13795), and a hidden field
57
+ * is machinery the user never typed into, so `off` is not asking
58
+ * for it either.
59
+ *
60
+ * NOT MASKED IN ANY MODE, `strict` included, and measured through
61
+ * the FullSnapshot in dom-masking.test.ts: the `value` of `radio`,
62
+ * `checkbox`, `submit` and `button`, which rrweb serialises before
63
+ * masking is consulted, and of `reset` and `image`, whose value is a
64
+ * button caption or author-set metadata rather than anything the
65
+ * person using the page entered. `privacy.blockSelectors` is the
66
+ * only lever for those, and it drops the element entirely.
67
+ *
68
+ * The map that decides this is `rrwebOptions()` in recorder.ts —
69
+ * the one statement of it — and the README's privacy table, its
70
+ * carve-out paragraph and one masking case per row of the map are
71
+ * all held to it.
72
+ */
73
+ privacyMode?: "strict" | "balanced" | "off";
74
+ /**
75
+ * Whether to intercept network requests. @default true
76
+ *
77
+ * `fetch` and `XMLHttpRequest`, which is everything network.ts
78
+ * patches. WebSocket frames are NOT captured; there is no request
79
+ * type for them, because a declared type nothing produces is a
80
+ * promise to a reader that the recording does not keep.
81
+ *
82
+ * The SDK's own requests to `endpoint` are never captured.
83
+ */
84
+ networkCapture?: boolean;
85
+ /**
86
+ * Fraction of sessions to actually record (0 - 1).
87
+ * e.g. 0.1 = record 10 % of users.
88
+ * @default 1
89
+ */
90
+ sampleRate?: number;
91
+ /**
92
+ * Maximum duration (ms) for a single recording session.
93
+ * @default 600_000 (10 min)
94
+ *
95
+ * When it elapses the WHOLE capture ends: DOM and network recording
96
+ * stop, the queued tail is flushed, and the singleton is released so
97
+ * a later `KeployCapture.init()` starts a new session.
98
+ */
99
+ maxSessionDuration?: number;
100
+ /**
101
+ * Number of events to batch before flushing -- a ceiling, not a
102
+ * promise. Clamped to 5000, the most the ingest server accepts in one
103
+ * batch, and a batch is also cut at the server's 10 MiB decoded body
104
+ * cap, so a large value with large events posts more, smaller
105
+ * batches rather than one the server would refuse. @default 50
106
+ */
107
+ batchSize?: number;
108
+ /** Interval (ms) to flush queued events even if batch is not full. @default 5_000 */
109
+ batchInterval?: number;
110
+ /**
111
+ * CSS selectors whose matched elements have their TEXT masked —
112
+ * the element's own text nodes and every one below it, because that
113
+ * is how rrweb decides masking (`closest`, not `matches`).
114
+ *
115
+ * Merged with {@link PrivacyConfig.maskSelectors}; neither spelling
116
+ * wins over the other. Input values are not affected: those are
117
+ * decided by {@link privacyMode} alone.
118
+ */
119
+ maskSelectors?: string[];
120
+ /**
121
+ * CSS selectors whose matched elements have their text left in the
122
+ * clear, overriding {@link maskSelectors} and `privacyMode: "strict"`
123
+ * for the subtree below them.
124
+ *
125
+ * Implemented through rrweb's `maskTextFn`, which is the only hook
126
+ * rrweb 2.0.0-alpha.20 offers for this: its recordOptions has no
127
+ * `unmaskTextSelector`. TEXT ONLY — it cannot unmask an input value,
128
+ * so the guarantee `privacyMode` makes about typed values holds
129
+ * whatever is configured here.
130
+ *
131
+ * Merged with {@link PrivacyConfig.unmaskSelectors}.
132
+ */
133
+ unmaskSelectors?: string[];
134
+ /**
135
+ * Custom session-ID generator. When omitted the SDK produces a UUID v4.
136
+ * Useful if you already have your own session / correlation ID.
137
+ *
138
+ * The value must be inside the ingest server's rule for a session id:
139
+ * 1-200 characters of letters, digits, dot, dash and underscore, with
140
+ * no empty dot-separated segment (`tenant-7.user_42.run-3`, not
141
+ * `user:42/session 1` -- encode such an id first). The SDK checks it
142
+ * before sending anything and, if it is outside the rule -- or not a
143
+ * string, or the generator throws -- does not start: `onError`
144
+ * receives a `SessionIdRefusal` (code `KUI_E_SESSION_ID_INVALID`)
145
+ * naming what was produced and the rule.
146
+ */
147
+ sessionIdGenerator?: () => string;
148
+ /** Fine-grained privacy overrides. */
149
+ privacy?: Partial<PrivacyConfig>;
150
+ /**
151
+ * How much of a request or response body is recorded.
152
+ * @default 524_288 (512 KB)
153
+ *
154
+ * Counted in UTF-16 code units — the unit a JS string is measured in,
155
+ * equal to bytes for ASCII and up to 2x under it for multi-byte text.
156
+ * A bound on what is recorded, not an exact byte budget: counting
157
+ * bytes would mean a TextEncoder pass over every body the page sends.
158
+ *
159
+ * WHAT A BODY OVER IT LOOKS LIKE, and there are three answers, not
160
+ * one. Text the SDK read is cut at the cap and marked
161
+ * `...[truncated]`. A cut body that was JSON no longer parses, and
162
+ * there is no safe way to redact a fragment — the original defect
163
+ * here was a regex over the serialised form turning
164
+ * `{"ts":1699999999999}` into `{"ts":[REDACTED]}` — so it is refused
165
+ * whole and recorded as `[UNPARSEABLE_BODY_NOT_REDACTED]`, never
166
+ * partly redacted and never in the clear.
167
+ *
168
+ * A body the SDK does not read at all is recorded as a note naming
169
+ * what it was, with a size where there is one to give — a stream, a
170
+ * response it could not read as text and a body it never read carry
171
+ * none. There are SEVEN, and this list was
172
+ * four while network.ts wrote a fifth — `[Binary/Document body]`,
173
+ * for every XHR Blob, buffer and Document alike, with neither the
174
+ * kind nor the size on it. readme.test.ts now holds both this list
175
+ * and the npm page to what network.ts writes:
176
+ *
177
+ * - `[Blob: N bytes, truncated]` — a `fetch` Blob over the cap.
178
+ * - `[Blob: N bytes]` — any Blob sent through `XMLHttpRequest`,
179
+ * whose body is serialised inside `send()`, where reading a Blob
180
+ * would mean holding the request up for an async call.
181
+ * - `[Binary: N bytes]` — a buffer over the cap, or one that is not
182
+ * UTF-8 text; a buffer that is text and fits is recorded as text.
183
+ * - `[Response body too large: N bytes]` — from a `Content-Length`
184
+ * over the cap, so the body is never downloaded.
185
+ * - `[ReadableStream]` — a streaming request body, which reading
186
+ * would consume out from under the page. No size: measuring a
187
+ * stream means consuming it too.
188
+ * - `[<responseType> response]` — an XHR whose `responseType` makes
189
+ * `responseText` throw. No size: the response is there in a form
190
+ * this note does not measure.
191
+ * - `[Unreadable body]` — the fail-closed answer for a body that
192
+ * could not be read at all. No size: nothing there was read, so
193
+ * there was nothing to measure.
194
+ *
195
+ * A network event carrying a body over 64 KiB cannot travel in the
196
+ * page-unload flush; see the note on {@link CaptureConfig}.
197
+ */
198
+ maxBodySize?: number;
199
+ /** Maximum number of events to queue in memory before dropping oldest. @default 5_000 */
200
+ maxQueueSize?: number;
201
+ /**
202
+ * Called once when a terminal condition ends the capture.
203
+ *
204
+ * A 4xx from the server is not retryable and not recoverable — a
205
+ * revoked key, a wrong endpoint, or two runs claiming one session id —
206
+ * and it used to be swallowed: no throw, no log, a capture with zero
207
+ * events and nothing to say why. This is how an integrator finds out.
208
+ * A console error is emitted regardless, so omitting this is not a
209
+ * way to be uninformed.
210
+ *
211
+ * The argument is a CaptureError, for the PROGRAM reading it: branch
212
+ * on `code` (a KUI_E_* from the contract's error corpus) -- which
213
+ * narrows it to an IngestRejection (`evidence.status`, `.issues`) or
214
+ * a SessionIdRefusal (`evidence.received`, `.rule`) -- and read
215
+ * `serverMessage` (the server's own sentence) and `remedy.manual`;
216
+ * `message` is the prose a human read before. It is called after the
217
+ * capture has ended and the singleton is released, so a handler may
218
+ * call KeployCapture.init() again and get a fresh capture. It is
219
+ * ALSO how a `sessionIdGenerator` that returns the wrong thing or
220
+ * throws is reported: the capture never starts, and init() resolves.
221
+ */
222
+ onError?: (err: AnyCaptureError) => void;
223
+ }
224
+ import type { AnyCaptureError } from "./errors";
225
+ import type { CaptureIdentity } from "./identity";
226
+ export type SessionEventType = "dom" | "network" | "custom";
227
+ export interface SessionEvent {
228
+ /** Unique event ID (UUID v4). */
229
+ id: string;
230
+ /** Session this event belongs to. */
231
+ sessionId: string;
232
+ /** Unix epoch ms when the event was captured. */
233
+ timestamp: number;
234
+ /** Discriminator for the payload stored in `data`. */
235
+ type: SessionEventType;
236
+ /** Payload - shape depends on `type`. */
237
+ data: unknown;
238
+ /**
239
+ * The event's position in its session, from 1, stamped by the
240
+ * transport as the event is queued; absent until then.
241
+ *
242
+ * The server orders a session by it, because arrival order is not
243
+ * queue order: the page-unload flush is dispatched while the batch
244
+ * before it is still being gzipped, so the later request can arrive
245
+ * first. Stamped when queued rather than when sent, so a batch that
246
+ * failed and was re-sent keeps its place.
247
+ */
248
+ seq?: number;
249
+ }
250
+ export type NetworkRequestType = "fetch" | "xhr";
251
+ export interface NetworkEvent {
252
+ method: string;
253
+ url: string;
254
+ requestHeaders: Record<string, string>;
255
+ requestBody: string | null;
256
+ responseHeaders: Record<string, string>;
257
+ responseBody: string | null;
258
+ statusCode: number;
259
+ /** Round-trip duration in ms. */
260
+ duration: number;
261
+ type: NetworkRequestType;
262
+ }
263
+ export interface SessionMetadata {
264
+ url: string;
265
+ userAgent: string;
266
+ viewport: {
267
+ width: number;
268
+ height: number;
269
+ };
270
+ referrer: string;
271
+ language: string;
272
+ devicePixelRatio: number;
273
+ timestamp: number;
274
+ }
275
+ export interface CaptureSession {
276
+ id: string;
277
+ startedAt: number;
278
+ endedAt: number | null;
279
+ events: SessionEvent[];
280
+ metadata: SessionMetadata;
281
+ }
282
+ /**
283
+ * Fine-grained privacy overrides.
284
+ *
285
+ * `maskAllInputs` and `maskAllText` were members here and nothing read
286
+ * either: what every input and every text node does is decided by
287
+ * {@link CaptureConfig.privacyMode}, which is the one control for it.
288
+ * Two of them would have been two answers to one question, and the
289
+ * loser would have been a switch an integrator could flip with no
290
+ * effect — on a privacy control, which is the worst place for it.
291
+ * Every member below IS read; recorder.ts's rrwebOptions() reads the
292
+ * three selector lists and PrivacyEngine reads the other three.
293
+ */
294
+ export interface PrivacyConfig {
295
+ /**
296
+ * CSS selectors whose matched elements have their TEXT masked,
297
+ * including every text node below them. Merged with
298
+ * {@link CaptureConfig.maskSelectors}.
299
+ */
300
+ maskSelectors: string[];
301
+ /**
302
+ * CSS selectors whose matched elements have their text left in the
303
+ * clear, overriding `maskSelectors` and `privacyMode: "strict"` for
304
+ * the subtree below them. Text only: it cannot unmask an input
305
+ * value. Merged with {@link CaptureConfig.unmaskSelectors}.
306
+ */
307
+ unmaskSelectors: string[];
308
+ /** CSS selectors whose matched elements are completely removed from the recording. */
309
+ blockSelectors: string[];
310
+ /** Replace network request/response bodies with "[MASKED]". @default false */
311
+ maskNetworkBodies: boolean;
312
+ /**
313
+ * Header names (case-insensitive) whose values are replaced with
314
+ * "[REDACTED]" in captured requests and responses.
315
+ *
316
+ * EXTENDS the built-in list — authorization, cookie, set-cookie,
317
+ * x-api-key, x-auth-token, proxy-authorization — and cannot shrink
318
+ * it: those are redacted whatever is configured here. An earlier
319
+ * version replaced the list, so adding one header un-redacted all
320
+ * six.
321
+ */
322
+ sensitiveHeaders: string[];
323
+ /**
324
+ * Extra RegExp patterns to scrub; matched text is replaced with
325
+ * "[REDACTED]". Each entry is `{ name: string; pattern: RegExp }`.
326
+ *
327
+ * Applied wherever the engine scans text: header values, string
328
+ * values inside JSON bodies (numbers and keys are never touched, so
329
+ * the JSON stays valid), and non-JSON bodies as a whole. Every
330
+ * occurrence is replaced whether or not the pattern has the `g` flag.
331
+ *
332
+ * NOT applied to URLs. The path and the query values are what the
333
+ * replay key is computed from, so rewriting them makes the recording
334
+ * unmatchable; URLs are redacted by query-parameter NAME instead
335
+ * (token, password, apikey, ...). Put identifiers in headers or the
336
+ * body if they must be scrubbable by pattern.
337
+ */
338
+ piiPatterns: PiiPattern[];
339
+ }
340
+ export interface PiiPattern {
341
+ name: string;
342
+ pattern: RegExp;
343
+ }
344
+ export interface TransportPayload {
345
+ sessionId: string;
346
+ /**
347
+ * The SDK's idempotency key for this POST, minted once per batch and
348
+ * re-sent unchanged with the same events on every retry. The server
349
+ * stores the batch under an id derived from it, so a re-post after a
350
+ * lost response is a success that stores nothing rather than a
351
+ * duplicate. Same shape as a session id.
352
+ */
353
+ batchId: string;
354
+ events: SessionEvent[];
355
+ metadata: SessionMetadata | null;
356
+ sdk: {
357
+ name: string;
358
+ version: string;
359
+ };
360
+ captureIdentity: CaptureIdentity | null;
361
+ }
362
+ export type EventCallback = (event: SessionEvent) => void;
363
+ export type NetworkEventCallback = (event: NetworkEvent) => void;
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@keploy/capture-sdk",
3
+ "version": "3.0.1",
4
+ "description": "Lightweight SDK to capture UI flows from real users - DOM recording, network interception, PII masking",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "LICENSE",
19
+ "README.md"
20
+ ],
21
+ "dependencies": {
22
+ "rrweb": "^2.1.6"
23
+ },
24
+ "devDependencies": {
25
+ "@keploy/contract": "0.1.0",
26
+ "@types/node": "~24.13.5",
27
+ "jsdom": "^30.1.0",
28
+ "tsup": "^8.3.0",
29
+ "typescript": "^7.0.2",
30
+ "vitest": "^5.0.1"
31
+ },
32
+ "peerDependencies": {},
33
+ "keywords": [
34
+ "keploy",
35
+ "ui-testing",
36
+ "session-recording",
37
+ "e2e",
38
+ "capture"
39
+ ],
40
+ "license": "Apache-2.0",
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup src/index.ts --format cjs,esm && tsc -p tsconfig.build.json",
46
+ "dev": "tsup src/index.ts --format cjs,esm --watch --onSuccess \"tsc -p tsconfig.build.json\"",
47
+ "test": "vitest run",
48
+ "clean": "rm -rf dist",
49
+ "typecheck": "tsc --noEmit"
50
+ }
51
+ }