@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.
- package/LICENSE +202 -0
- package/README.md +482 -0
- package/dist/auto.d.ts +8 -0
- package/dist/errors.d.ts +252 -0
- package/dist/identity.d.ts +94 -0
- package/dist/index.d.ts +104 -0
- package/dist/index.js +2354 -0
- package/dist/index.mjs +2297 -0
- package/dist/network.d.ts +90 -0
- package/dist/privacy.d.ts +36 -0
- package/dist/recorder.d.ts +164 -0
- package/dist/redact.d.ts +47 -0
- package/dist/session-id.d.ts +32 -0
- package/dist/transport.d.ts +332 -0
- package/dist/types.d.ts +363 -0
- package/package.json +51 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2297 @@
|
|
|
1
|
+
// src/redact.ts
|
|
2
|
+
var SENSITIVE_KEYS = /* @__PURE__ */ new Set([
|
|
3
|
+
"password",
|
|
4
|
+
"passwd",
|
|
5
|
+
"pwd",
|
|
6
|
+
"secret",
|
|
7
|
+
"token",
|
|
8
|
+
"access_token",
|
|
9
|
+
"accesstoken",
|
|
10
|
+
"refresh_token",
|
|
11
|
+
"refreshtoken",
|
|
12
|
+
"id_token",
|
|
13
|
+
"idtoken",
|
|
14
|
+
"authorization",
|
|
15
|
+
"auth",
|
|
16
|
+
"apikey",
|
|
17
|
+
"api_key",
|
|
18
|
+
"client_secret",
|
|
19
|
+
"clientsecret",
|
|
20
|
+
"private_key",
|
|
21
|
+
"privatekey",
|
|
22
|
+
"session",
|
|
23
|
+
"sessionid",
|
|
24
|
+
"session_id",
|
|
25
|
+
"cookie",
|
|
26
|
+
"ssn",
|
|
27
|
+
"socialsecuritynumber",
|
|
28
|
+
"creditcard",
|
|
29
|
+
"credit_card",
|
|
30
|
+
"cardnumber",
|
|
31
|
+
"card_number",
|
|
32
|
+
"cvv",
|
|
33
|
+
"cvc",
|
|
34
|
+
"pin",
|
|
35
|
+
"otp"
|
|
36
|
+
]);
|
|
37
|
+
var REDACTED = "[REDACTED]";
|
|
38
|
+
var TRUNCATED_UNPARSEABLE = "[UNPARSEABLE_BODY_NOT_REDACTED]";
|
|
39
|
+
var NOT_RECORDED = [
|
|
40
|
+
/^\[Blob: \d+ bytes, truncated\]$/,
|
|
41
|
+
// The XHR path's Blob, which is named rather than read: its body has
|
|
42
|
+
// to be serialised inside send(), and Blob.text() is async.
|
|
43
|
+
/^\[Blob: \d+ bytes\]$/,
|
|
44
|
+
/^\[Binary: \d+ bytes\]$/,
|
|
45
|
+
/^\[Response body too large: \d+ bytes\]$/,
|
|
46
|
+
/^\[ReadableStream\]$/,
|
|
47
|
+
/^\[Unreadable body\]$/,
|
|
48
|
+
// `[${xhr.responseType} response]` — the XMLHttpRequestResponseType
|
|
49
|
+
// enum: "", arraybuffer, blob, document, json, text.
|
|
50
|
+
/^\[(?:arraybuffer|blob|document|json|text|) response\]$/
|
|
51
|
+
];
|
|
52
|
+
function isNotRecordedNote(body) {
|
|
53
|
+
return NOT_RECORDED.some((re) => re.test(body));
|
|
54
|
+
}
|
|
55
|
+
function normalizeKey(key) {
|
|
56
|
+
return key.toLowerCase().replace(/[-_\s]/g, "");
|
|
57
|
+
}
|
|
58
|
+
function isSensitiveKey(key) {
|
|
59
|
+
const n = normalizeKey(key);
|
|
60
|
+
if (SENSITIVE_KEYS.has(n)) return true;
|
|
61
|
+
return n.endsWith("password") || n.endsWith("secret") || n.endsWith("token") || n.endsWith("apikey") || n.endsWith("privatekey");
|
|
62
|
+
}
|
|
63
|
+
var EMAIL_RE = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;
|
|
64
|
+
var SSN_RE = /\b\d{3}-\d{2}-\d{4}\b/g;
|
|
65
|
+
var PHONE_RE = /(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)[ .-]?|\b\d{3}[ .-])\d{3}[ .-]\d{4}\b/g;
|
|
66
|
+
var JWT_RE = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g;
|
|
67
|
+
var IPV4_RE = /(?<![\d.])(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?![\d.])/g;
|
|
68
|
+
function passesLuhn(digits) {
|
|
69
|
+
let sum = 0;
|
|
70
|
+
let double = false;
|
|
71
|
+
for (let i = digits.length - 1; i >= 0; i--) {
|
|
72
|
+
let d = digits.charCodeAt(i) - 48;
|
|
73
|
+
if (d < 0 || d > 9) return false;
|
|
74
|
+
if (double) {
|
|
75
|
+
d *= 2;
|
|
76
|
+
if (d > 9) d -= 9;
|
|
77
|
+
}
|
|
78
|
+
sum += d;
|
|
79
|
+
double = !double;
|
|
80
|
+
}
|
|
81
|
+
return sum % 10 === 0;
|
|
82
|
+
}
|
|
83
|
+
function isLikelyCardNumber(digits) {
|
|
84
|
+
if (digits.length < 13 || digits.length > 19) return false;
|
|
85
|
+
const isVisa = digits[0] === "4" && (digits.length === 13 || digits.length === 16 || digits.length === 19);
|
|
86
|
+
const isMastercard = /^(5[1-5]|2[2-7])/.test(digits) && digits.length === 16;
|
|
87
|
+
const isAmex = /^3[47]/.test(digits) && digits.length === 15;
|
|
88
|
+
const isDiscover = /^6(?:011|5)/.test(digits) && digits.length === 16;
|
|
89
|
+
const isJcbDiners = /^(?:35|3[068])/.test(digits) && digits.length >= 14 && digits.length <= 19;
|
|
90
|
+
if (!(isVisa || isMastercard || isAmex || isDiscover || isJcbDiners))
|
|
91
|
+
return false;
|
|
92
|
+
return passesLuhn(digits);
|
|
93
|
+
}
|
|
94
|
+
function redactCards(s) {
|
|
95
|
+
return s.replace(/\b(?:\d[ -]?){12,18}\d\b/g, (match) => {
|
|
96
|
+
const digits = match.replace(/[^0-9]/g, "");
|
|
97
|
+
return isLikelyCardNumber(digits) ? REDACTED : match;
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function redactStringValue(value, extra = []) {
|
|
101
|
+
if (!value) return value;
|
|
102
|
+
let out = value;
|
|
103
|
+
out = out.replace(JWT_RE, REDACTED);
|
|
104
|
+
out = out.replace(EMAIL_RE, REDACTED);
|
|
105
|
+
out = out.replace(SSN_RE, REDACTED);
|
|
106
|
+
out = out.replace(PHONE_RE, REDACTED);
|
|
107
|
+
out = out.replace(IPV4_RE, REDACTED);
|
|
108
|
+
out = redactCards(out);
|
|
109
|
+
for (const re of extra) out = out.replace(re, REDACTED);
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
var MAX_DEPTH = 64;
|
|
113
|
+
function redactValue(value, keyHint, depth, extra) {
|
|
114
|
+
if (depth > MAX_DEPTH) return REDACTED;
|
|
115
|
+
if (value === null || value === void 0) return value;
|
|
116
|
+
const t = typeof value;
|
|
117
|
+
if (t === "number" || t === "boolean" || t === "bigint") {
|
|
118
|
+
if (keyHint && isSensitiveKey(keyHint)) return REDACTED;
|
|
119
|
+
if (typeof value === "number" && Number.isInteger(value)) {
|
|
120
|
+
const digits = String(value);
|
|
121
|
+
if (isLikelyCardNumber(digits)) return REDACTED;
|
|
122
|
+
}
|
|
123
|
+
return value;
|
|
124
|
+
}
|
|
125
|
+
if (t === "string") {
|
|
126
|
+
if (keyHint && isSensitiveKey(keyHint)) return REDACTED;
|
|
127
|
+
return redactStringValue(value, extra);
|
|
128
|
+
}
|
|
129
|
+
if (keyHint && isSensitiveKey(keyHint)) return REDACTED;
|
|
130
|
+
if (Array.isArray(value)) {
|
|
131
|
+
return value.map((v) => redactValue(v, keyHint, depth + 1, extra));
|
|
132
|
+
}
|
|
133
|
+
if (t === "object") {
|
|
134
|
+
const out = /* @__PURE__ */ Object.create(null);
|
|
135
|
+
for (const [k, v] of Object.entries(value)) {
|
|
136
|
+
out[k] = redactValue(v, isSensitiveKey(k) ? k : null, depth + 1, extra);
|
|
137
|
+
}
|
|
138
|
+
return { ...out };
|
|
139
|
+
}
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
function redactBody(body, contentType, extra = []) {
|
|
143
|
+
if (body === null || body === void 0 || body === "") return body ?? null;
|
|
144
|
+
if (isNotRecordedNote(body)) return body;
|
|
145
|
+
const looksJson = (contentType ?? "").toLowerCase().includes("json") || /^\s*[[{]/.test(body);
|
|
146
|
+
if (looksJson) {
|
|
147
|
+
try {
|
|
148
|
+
return JSON.stringify(redactValue(JSON.parse(body), null, 0, extra));
|
|
149
|
+
} catch {
|
|
150
|
+
return TRUNCATED_UNPARSEABLE;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return redactStringValue(body, extra);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/privacy.ts
|
|
157
|
+
var SENSITIVE_PARAMS = /* @__PURE__ */ new Set([
|
|
158
|
+
"token",
|
|
159
|
+
"accesstoken",
|
|
160
|
+
"idtoken",
|
|
161
|
+
"refreshtoken",
|
|
162
|
+
"password",
|
|
163
|
+
"secret",
|
|
164
|
+
"apikey",
|
|
165
|
+
"clientsecret",
|
|
166
|
+
"signature",
|
|
167
|
+
"authorization",
|
|
168
|
+
"sessionid"
|
|
169
|
+
]);
|
|
170
|
+
function isSensitiveParam(name) {
|
|
171
|
+
return SENSITIVE_PARAMS.has(name.toLowerCase().replace(/[-_]/g, ""));
|
|
172
|
+
}
|
|
173
|
+
function findContentType(headers) {
|
|
174
|
+
if (!headers) return void 0;
|
|
175
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
176
|
+
if (k.toLowerCase() === "content-type") return v;
|
|
177
|
+
}
|
|
178
|
+
return void 0;
|
|
179
|
+
}
|
|
180
|
+
var BUILTIN_PII_PATTERNS = [
|
|
181
|
+
{
|
|
182
|
+
name: "email",
|
|
183
|
+
pattern: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
name: "phone_us",
|
|
187
|
+
// Every leading group used to be optional, reducing this to "any
|
|
188
|
+
// 7-digit run": it matched order ids, invoice numbers, timestamps and
|
|
189
|
+
// Content-Length values. A separator or explicit country code is now
|
|
190
|
+
// required.
|
|
191
|
+
pattern: /(?:\+\d{1,3}[ .-]?)?(?:\(\d{3}\)[ .-]?|\b\d{3}[ .-])\d{3}[ .-]\d{4}\b/g
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
name: "ssn",
|
|
195
|
+
pattern: /\b\d{3}-\d{2}-\d{4}\b/g
|
|
196
|
+
},
|
|
197
|
+
// credit_card was removed from this list. The pattern
|
|
198
|
+
// /\b(?:\d[ -]*?){13,19}\b/ matched every 13-digit Date.now() and every
|
|
199
|
+
// long numeric id, and replacing inside a serialized number produced
|
|
200
|
+
// invalid JSON. Card numbers are now detected in redact.ts against
|
|
201
|
+
// string values only, requiring issuer prefix + length + Luhn.
|
|
202
|
+
{
|
|
203
|
+
name: "ipv4",
|
|
204
|
+
pattern: /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\b/g
|
|
205
|
+
}
|
|
206
|
+
];
|
|
207
|
+
var DEFAULT_SENSITIVE_HEADERS = [
|
|
208
|
+
"authorization",
|
|
209
|
+
"cookie",
|
|
210
|
+
"set-cookie",
|
|
211
|
+
"x-api-key",
|
|
212
|
+
"x-auth-token",
|
|
213
|
+
"proxy-authorization"
|
|
214
|
+
];
|
|
215
|
+
function defaultPrivacyConfig() {
|
|
216
|
+
return {
|
|
217
|
+
maskSelectors: [],
|
|
218
|
+
unmaskSelectors: [],
|
|
219
|
+
blockSelectors: [],
|
|
220
|
+
maskNetworkBodies: false,
|
|
221
|
+
sensitiveHeaders: [...DEFAULT_SENSITIVE_HEADERS],
|
|
222
|
+
piiPatterns: []
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function mergePrivacyConfig(base, partial) {
|
|
226
|
+
const defined = Object.fromEntries(
|
|
227
|
+
Object.entries(partial).filter(([, v]) => v !== void 0)
|
|
228
|
+
);
|
|
229
|
+
const merged = { ...base, ...defined };
|
|
230
|
+
if (defined.sensitiveHeaders) {
|
|
231
|
+
const seen = /* @__PURE__ */ new Set();
|
|
232
|
+
merged.sensitiveHeaders = [
|
|
233
|
+
...DEFAULT_SENSITIVE_HEADERS,
|
|
234
|
+
...base.sensitiveHeaders,
|
|
235
|
+
...defined.sensitiveHeaders
|
|
236
|
+
].filter((h) => {
|
|
237
|
+
const k = h.toLowerCase();
|
|
238
|
+
if (seen.has(k)) return false;
|
|
239
|
+
seen.add(k);
|
|
240
|
+
return true;
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
return merged;
|
|
244
|
+
}
|
|
245
|
+
function compileGlobal(patterns) {
|
|
246
|
+
return patterns.map(
|
|
247
|
+
({ pattern }) => pattern.flags.includes("g") ? new RegExp(pattern.source, pattern.flags) : new RegExp(pattern.source, pattern.flags + "g")
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
var PrivacyEngine = class {
|
|
251
|
+
config;
|
|
252
|
+
builtinPatterns;
|
|
253
|
+
/** The integrator's piiPatterns, compiled global once. */
|
|
254
|
+
userPatterns;
|
|
255
|
+
constructor(config = {}) {
|
|
256
|
+
this.config = mergePrivacyConfig(defaultPrivacyConfig(), config);
|
|
257
|
+
this.builtinPatterns = compileGlobal(BUILTIN_PII_PATTERNS);
|
|
258
|
+
this.userPatterns = compileGlobal(this.config.piiPatterns);
|
|
259
|
+
}
|
|
260
|
+
/* -------------------------------------------------------------- */
|
|
261
|
+
/* Text masking */
|
|
262
|
+
/* -------------------------------------------------------------- */
|
|
263
|
+
/**
|
|
264
|
+
* Replace every occurrence of known PII patterns in `text` with
|
|
265
|
+
* `[REDACTED]`. Returns the scrubbed string.
|
|
266
|
+
*/
|
|
267
|
+
maskText(text) {
|
|
268
|
+
if (!text) return text;
|
|
269
|
+
let result = redactStringValue(text, this.userPatterns);
|
|
270
|
+
for (const re of this.builtinPatterns) {
|
|
271
|
+
result = result.replace(re, "[REDACTED]");
|
|
272
|
+
}
|
|
273
|
+
return result;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Redact a URL without disturbing the parts that carry request identity.
|
|
277
|
+
*
|
|
278
|
+
* The path is left exactly as captured — it is what the canonical key is
|
|
279
|
+
* computed from, and rewriting it makes the recording unreplayable.
|
|
280
|
+
* Query values are redacted by parameter NAME (token, password, apikey,
|
|
281
|
+
* ... — the set canonkey.ts excludes from the key) and by nothing else:
|
|
282
|
+
* no regex, built-in or user-supplied, runs over a URL. Every other
|
|
283
|
+
* value and every name is kept, because they are part of identity too.
|
|
284
|
+
* An earlier version of this method scanned every value (the inline
|
|
285
|
+
* comment below records what that did to the key); this comment said
|
|
286
|
+
* so and outlived the fix.
|
|
287
|
+
*/
|
|
288
|
+
maskUrl(rawUrl) {
|
|
289
|
+
if (!rawUrl) return rawUrl;
|
|
290
|
+
const hashAt = rawUrl.indexOf("#");
|
|
291
|
+
const withoutHash = hashAt === -1 ? rawUrl : rawUrl.slice(0, hashAt);
|
|
292
|
+
const qAt = withoutHash.indexOf("?");
|
|
293
|
+
if (qAt === -1) return withoutHash;
|
|
294
|
+
const head = withoutHash.slice(0, qAt);
|
|
295
|
+
const query = withoutHash.slice(qAt + 1);
|
|
296
|
+
const parts = query.split("&").map((pair) => {
|
|
297
|
+
if (pair === "") return pair;
|
|
298
|
+
const eq = pair.indexOf("=");
|
|
299
|
+
if (eq === -1) return pair;
|
|
300
|
+
const name = pair.slice(0, eq);
|
|
301
|
+
if (isSensitiveParam(name)) return `${name}=[REDACTED]`;
|
|
302
|
+
return pair;
|
|
303
|
+
});
|
|
304
|
+
return `${head}?${parts.join("&")}`;
|
|
305
|
+
}
|
|
306
|
+
/* -------------------------------------------------------------- */
|
|
307
|
+
/* Network data masking */
|
|
308
|
+
/* -------------------------------------------------------------- */
|
|
309
|
+
/**
|
|
310
|
+
* Returns a deep-copy of the given {@link NetworkEvent} with sensitive
|
|
311
|
+
* headers redacted and (optionally) bodies masked.
|
|
312
|
+
*/
|
|
313
|
+
maskNetworkData(event) {
|
|
314
|
+
const masked = { ...event };
|
|
315
|
+
masked.requestHeaders = this.maskHeaders(event.requestHeaders);
|
|
316
|
+
masked.responseHeaders = this.maskHeaders(event.responseHeaders);
|
|
317
|
+
if (this.config.maskNetworkBodies) {
|
|
318
|
+
masked.requestBody = event.requestBody ? "[MASKED]" : null;
|
|
319
|
+
masked.responseBody = event.responseBody ? "[MASKED]" : null;
|
|
320
|
+
} else {
|
|
321
|
+
const reqCt = findContentType(event.requestHeaders);
|
|
322
|
+
const resCt = findContentType(event.responseHeaders);
|
|
323
|
+
masked.requestBody = redactBody(
|
|
324
|
+
event.requestBody,
|
|
325
|
+
reqCt,
|
|
326
|
+
this.userPatterns
|
|
327
|
+
);
|
|
328
|
+
masked.responseBody = redactBody(
|
|
329
|
+
event.responseBody,
|
|
330
|
+
resCt,
|
|
331
|
+
this.userPatterns
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
masked.url = this.maskUrl(event.url);
|
|
335
|
+
return masked;
|
|
336
|
+
}
|
|
337
|
+
/* -------------------------------------------------------------- */
|
|
338
|
+
/* Config accessors */
|
|
339
|
+
/* -------------------------------------------------------------- */
|
|
340
|
+
getConfig() {
|
|
341
|
+
return this.config;
|
|
342
|
+
}
|
|
343
|
+
updateConfig(partial) {
|
|
344
|
+
this.config = mergePrivacyConfig(this.config, partial);
|
|
345
|
+
this.userPatterns = compileGlobal(this.config.piiPatterns);
|
|
346
|
+
}
|
|
347
|
+
/* -------------------------------------------------------------- */
|
|
348
|
+
/* Internals */
|
|
349
|
+
/* -------------------------------------------------------------- */
|
|
350
|
+
maskHeaders(headers) {
|
|
351
|
+
const result = {};
|
|
352
|
+
const sensitiveSet = new Set(
|
|
353
|
+
this.config.sensitiveHeaders.map((h) => h.toLowerCase())
|
|
354
|
+
);
|
|
355
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
356
|
+
if (sensitiveSet.has(key.toLowerCase())) {
|
|
357
|
+
result[key] = "[REDACTED]";
|
|
358
|
+
} else {
|
|
359
|
+
result[key] = this.maskText(value);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return result;
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
// src/network.ts
|
|
367
|
+
function absolute(url) {
|
|
368
|
+
try {
|
|
369
|
+
const base = typeof document !== "undefined" ? document.baseURI : void 0;
|
|
370
|
+
return new URL(url, base).href;
|
|
371
|
+
} catch {
|
|
372
|
+
return url;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function headersToRecord(headers) {
|
|
376
|
+
const result = {};
|
|
377
|
+
if (!headers) return result;
|
|
378
|
+
if (headers instanceof Headers) {
|
|
379
|
+
headers.forEach((value, key) => {
|
|
380
|
+
result[key] = value;
|
|
381
|
+
});
|
|
382
|
+
} else if (Array.isArray(headers)) {
|
|
383
|
+
for (const [key, value] of headers) {
|
|
384
|
+
result[key] = value;
|
|
385
|
+
}
|
|
386
|
+
} else {
|
|
387
|
+
Object.assign(result, headers);
|
|
388
|
+
}
|
|
389
|
+
return result;
|
|
390
|
+
}
|
|
391
|
+
var TRUNCATED_SUFFIX = "...[truncated]";
|
|
392
|
+
function truncate(text, maxSize) {
|
|
393
|
+
return text.length > maxSize ? text.slice(0, maxSize) + TRUNCATED_SUFFIX : text;
|
|
394
|
+
}
|
|
395
|
+
function formDataText(body) {
|
|
396
|
+
const parts = [];
|
|
397
|
+
body.forEach((value, key) => {
|
|
398
|
+
parts.push(
|
|
399
|
+
typeof value === "string" ? `${key}=${value}` : `${key}=[File: ${value.name}, ${value.size} bytes]`
|
|
400
|
+
);
|
|
401
|
+
});
|
|
402
|
+
return parts.join("&");
|
|
403
|
+
}
|
|
404
|
+
function serializeXhrBody(body, maxSize) {
|
|
405
|
+
if (body == null) return null;
|
|
406
|
+
if (typeof body === "string") return truncate(body, maxSize);
|
|
407
|
+
if (body instanceof FormData) return truncate(formDataText(body), maxSize);
|
|
408
|
+
if (body instanceof URLSearchParams)
|
|
409
|
+
return truncate(body.toString(), maxSize);
|
|
410
|
+
if (typeof Blob !== "undefined" && body instanceof Blob)
|
|
411
|
+
return `[Blob: ${body.size} bytes]`;
|
|
412
|
+
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
|
|
413
|
+
return binaryBody(body, maxSize);
|
|
414
|
+
if (typeof Document !== "undefined" && body instanceof Document) {
|
|
415
|
+
try {
|
|
416
|
+
return truncate(new XMLSerializer().serializeToString(body), maxSize);
|
|
417
|
+
} catch {
|
|
418
|
+
return "[Unreadable body]";
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return "[Unreadable body]";
|
|
422
|
+
}
|
|
423
|
+
function binaryBody(body, maxSize) {
|
|
424
|
+
const bytes = body instanceof ArrayBuffer ? new Uint8Array(body) : new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
|
|
425
|
+
if (bytes.byteLength > maxSize) return `[Binary: ${bytes.byteLength} bytes]`;
|
|
426
|
+
try {
|
|
427
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
428
|
+
} catch {
|
|
429
|
+
return `[Binary: ${bytes.byteLength} bytes]`;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
async function serializeBody(body, maxSize) {
|
|
433
|
+
if (body == null) return null;
|
|
434
|
+
try {
|
|
435
|
+
if (typeof body === "string") return truncate(body, maxSize);
|
|
436
|
+
if (body instanceof URLSearchParams)
|
|
437
|
+
return truncate(body.toString(), maxSize);
|
|
438
|
+
if (body instanceof FormData) return truncate(formDataText(body), maxSize);
|
|
439
|
+
if (body instanceof Blob) {
|
|
440
|
+
if (body.size > maxSize) return `[Blob: ${body.size} bytes, truncated]`;
|
|
441
|
+
const text = await body.text();
|
|
442
|
+
return text;
|
|
443
|
+
}
|
|
444
|
+
if (body instanceof ArrayBuffer || ArrayBuffer.isView(body))
|
|
445
|
+
return binaryBody(body, maxSize);
|
|
446
|
+
return "[ReadableStream]";
|
|
447
|
+
} catch {
|
|
448
|
+
return "[Unreadable body]";
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
async function readResponseBody(response, maxSize) {
|
|
452
|
+
try {
|
|
453
|
+
const clone = response.clone();
|
|
454
|
+
const contentLength = Number(clone.headers.get("content-length") ?? 0);
|
|
455
|
+
if (contentLength > maxSize) {
|
|
456
|
+
return `[Response body too large: ${contentLength} bytes]`;
|
|
457
|
+
}
|
|
458
|
+
return truncate(await clone.text(), maxSize);
|
|
459
|
+
} catch {
|
|
460
|
+
return null;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function recordedUrl(raw) {
|
|
464
|
+
const base = typeof document !== "undefined" && document.baseURI ? document.baseURI : typeof location !== "undefined" ? location.href : void 0;
|
|
465
|
+
return new URL(raw, base).href;
|
|
466
|
+
}
|
|
467
|
+
var NetworkInterceptor = class {
|
|
468
|
+
callback = null;
|
|
469
|
+
privacyEngine;
|
|
470
|
+
maxBodySize;
|
|
471
|
+
/** Absolute URLs never observed — the SDK's own ingest endpoint. */
|
|
472
|
+
ignored;
|
|
473
|
+
active = false;
|
|
474
|
+
// Store originals so we can restore them on stop().
|
|
475
|
+
originalFetch = null;
|
|
476
|
+
originalXhrOpen = null;
|
|
477
|
+
originalXhrSend = null;
|
|
478
|
+
originalXhrSetHeader = null;
|
|
479
|
+
constructor(privacyConfig = {}, maxBodySize = 524288, ignoreUrls = []) {
|
|
480
|
+
this.privacyEngine = new PrivacyEngine(privacyConfig);
|
|
481
|
+
this.maxBodySize = maxBodySize;
|
|
482
|
+
this.ignored = new Set(ignoreUrls.map(absolute));
|
|
483
|
+
}
|
|
484
|
+
/** True for a request the interceptor must pass through untouched. */
|
|
485
|
+
ignores(url) {
|
|
486
|
+
return this.ignored.size > 0 && this.ignored.has(absolute(url));
|
|
487
|
+
}
|
|
488
|
+
/* -------------------------------------------------------------- */
|
|
489
|
+
/* Lifecycle */
|
|
490
|
+
/* -------------------------------------------------------------- */
|
|
491
|
+
start(callback) {
|
|
492
|
+
if (this.active) return;
|
|
493
|
+
this.active = true;
|
|
494
|
+
this.callback = callback;
|
|
495
|
+
this.patchFetch();
|
|
496
|
+
this.patchXHR();
|
|
497
|
+
}
|
|
498
|
+
stop() {
|
|
499
|
+
if (!this.active) return;
|
|
500
|
+
this.active = false;
|
|
501
|
+
this.callback = null;
|
|
502
|
+
this.restoreFetch();
|
|
503
|
+
this.restoreXHR();
|
|
504
|
+
}
|
|
505
|
+
/* -------------------------------------------------------------- */
|
|
506
|
+
/* Fetch patching */
|
|
507
|
+
/* -------------------------------------------------------------- */
|
|
508
|
+
patchFetch() {
|
|
509
|
+
if (typeof globalThis.fetch !== "function") return;
|
|
510
|
+
const originalFetch = globalThis.fetch;
|
|
511
|
+
this.originalFetch = originalFetch;
|
|
512
|
+
const patchedFetch = async (input, init) => {
|
|
513
|
+
const request = new Request(input, init);
|
|
514
|
+
if (this.ignores(request.url)) {
|
|
515
|
+
return originalFetch.call(globalThis, input, init);
|
|
516
|
+
}
|
|
517
|
+
const startTime = performance.now();
|
|
518
|
+
const method = request.method;
|
|
519
|
+
const url = recordedUrl(request.url);
|
|
520
|
+
const requestHeaders = headersToRecord(request.headers);
|
|
521
|
+
let requestBody = null;
|
|
522
|
+
if (init?.body != null) {
|
|
523
|
+
requestBody = await serializeBody(init.body, this.maxBodySize);
|
|
524
|
+
} else if (request.body) {
|
|
525
|
+
try {
|
|
526
|
+
const clone = request.clone();
|
|
527
|
+
requestBody = truncate(await clone.text(), this.maxBodySize);
|
|
528
|
+
} catch {
|
|
529
|
+
requestBody = null;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
let response;
|
|
533
|
+
try {
|
|
534
|
+
response = await originalFetch.call(globalThis, input, init);
|
|
535
|
+
} catch (err) {
|
|
536
|
+
const duration2 = performance.now() - startTime;
|
|
537
|
+
this.emit({
|
|
538
|
+
method,
|
|
539
|
+
url,
|
|
540
|
+
requestHeaders,
|
|
541
|
+
requestBody,
|
|
542
|
+
responseHeaders: {},
|
|
543
|
+
responseBody: null,
|
|
544
|
+
statusCode: 0,
|
|
545
|
+
duration: duration2,
|
|
546
|
+
type: "fetch"
|
|
547
|
+
});
|
|
548
|
+
throw err;
|
|
549
|
+
}
|
|
550
|
+
const duration = performance.now() - startTime;
|
|
551
|
+
const responseHeaders = headersToRecord(response.headers);
|
|
552
|
+
const responseBody = await readResponseBody(response, this.maxBodySize);
|
|
553
|
+
this.emit({
|
|
554
|
+
method,
|
|
555
|
+
url,
|
|
556
|
+
requestHeaders,
|
|
557
|
+
requestBody,
|
|
558
|
+
responseHeaders,
|
|
559
|
+
responseBody,
|
|
560
|
+
statusCode: response.status,
|
|
561
|
+
duration,
|
|
562
|
+
type: "fetch"
|
|
563
|
+
});
|
|
564
|
+
return response;
|
|
565
|
+
};
|
|
566
|
+
globalThis.fetch = patchedFetch;
|
|
567
|
+
}
|
|
568
|
+
restoreFetch() {
|
|
569
|
+
if (this.originalFetch) {
|
|
570
|
+
globalThis.fetch = this.originalFetch;
|
|
571
|
+
this.originalFetch = null;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/* -------------------------------------------------------------- */
|
|
575
|
+
/* XMLHttpRequest patching */
|
|
576
|
+
/* -------------------------------------------------------------- */
|
|
577
|
+
patchXHR() {
|
|
578
|
+
if (typeof XMLHttpRequest === "undefined") return;
|
|
579
|
+
const originalOpen = XMLHttpRequest.prototype.open;
|
|
580
|
+
const originalSend = XMLHttpRequest.prototype.send;
|
|
581
|
+
this.originalXhrOpen = originalOpen;
|
|
582
|
+
this.originalXhrSend = originalSend;
|
|
583
|
+
const maxBodySize = this.maxBodySize;
|
|
584
|
+
const isActive = () => this.active;
|
|
585
|
+
const emit = (event) => this.emit(event);
|
|
586
|
+
const ignores = (u) => this.ignores(u);
|
|
587
|
+
const meta = /* @__PURE__ */ new WeakMap();
|
|
588
|
+
const origSetHeader = XMLHttpRequest.prototype.setRequestHeader;
|
|
589
|
+
this.originalXhrSetHeader = origSetHeader;
|
|
590
|
+
XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
|
|
591
|
+
const m = meta.get(this);
|
|
592
|
+
if (m) {
|
|
593
|
+
m.requestHeaders[name] = value;
|
|
594
|
+
}
|
|
595
|
+
return origSetHeader.call(this, name, value);
|
|
596
|
+
};
|
|
597
|
+
const forwardOpen = originalOpen;
|
|
598
|
+
XMLHttpRequest.prototype.open = function(method, url, ...rest) {
|
|
599
|
+
const href = typeof url === "string" ? url : url.toString();
|
|
600
|
+
const result = forwardOpen.call(this, method, url, ...rest);
|
|
601
|
+
if (!ignores(href)) {
|
|
602
|
+
meta.set(this, {
|
|
603
|
+
method,
|
|
604
|
+
// RESOLVED, not the raw string the app typed. See recordedUrl.
|
|
605
|
+
url: recordedUrl(href),
|
|
606
|
+
requestHeaders: {},
|
|
607
|
+
startTime: 0
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
return result;
|
|
611
|
+
};
|
|
612
|
+
XMLHttpRequest.prototype.send = function(body) {
|
|
613
|
+
const m = meta.get(this);
|
|
614
|
+
if (m) {
|
|
615
|
+
m.startTime = performance.now();
|
|
616
|
+
}
|
|
617
|
+
const onFinish = () => {
|
|
618
|
+
if (!m || !isActive()) return;
|
|
619
|
+
const duration = performance.now() - m.startTime;
|
|
620
|
+
const rawHeaders = this.getAllResponseHeaders();
|
|
621
|
+
const responseHeaders = {};
|
|
622
|
+
if (rawHeaders) {
|
|
623
|
+
for (const line of rawHeaders.trim().split(/[\r\n]+/)) {
|
|
624
|
+
const idx = line.indexOf(": ");
|
|
625
|
+
if (idx > 0) {
|
|
626
|
+
responseHeaders[line.slice(0, idx)] = line.slice(idx + 2);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
let responseBody = null;
|
|
631
|
+
try {
|
|
632
|
+
if (typeof this.responseText === "string") {
|
|
633
|
+
responseBody = truncate(this.responseText, maxBodySize);
|
|
634
|
+
}
|
|
635
|
+
} catch {
|
|
636
|
+
responseBody = `[${this.responseType} response]`;
|
|
637
|
+
}
|
|
638
|
+
const requestBody = serializeXhrBody(body, maxBodySize);
|
|
639
|
+
emit({
|
|
640
|
+
method: m.method,
|
|
641
|
+
url: m.url,
|
|
642
|
+
requestHeaders: m.requestHeaders,
|
|
643
|
+
requestBody,
|
|
644
|
+
responseHeaders,
|
|
645
|
+
responseBody,
|
|
646
|
+
statusCode: this.status,
|
|
647
|
+
duration,
|
|
648
|
+
type: "xhr"
|
|
649
|
+
});
|
|
650
|
+
};
|
|
651
|
+
this.addEventListener("loadend", onFinish, { once: true });
|
|
652
|
+
return originalSend.call(this, body);
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
restoreXHR() {
|
|
656
|
+
if (typeof XMLHttpRequest === "undefined") return;
|
|
657
|
+
if (this.originalXhrOpen) {
|
|
658
|
+
XMLHttpRequest.prototype.open = this.originalXhrOpen;
|
|
659
|
+
this.originalXhrOpen = null;
|
|
660
|
+
}
|
|
661
|
+
if (this.originalXhrSend) {
|
|
662
|
+
XMLHttpRequest.prototype.send = this.originalXhrSend;
|
|
663
|
+
this.originalXhrSend = null;
|
|
664
|
+
}
|
|
665
|
+
if (this.originalXhrSetHeader) {
|
|
666
|
+
XMLHttpRequest.prototype.setRequestHeader = this.originalXhrSetHeader;
|
|
667
|
+
this.originalXhrSetHeader = null;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
/* -------------------------------------------------------------- */
|
|
671
|
+
/* Internal */
|
|
672
|
+
/* -------------------------------------------------------------- */
|
|
673
|
+
emit(raw) {
|
|
674
|
+
if (!this.callback) return;
|
|
675
|
+
try {
|
|
676
|
+
const masked = this.privacyEngine.maskNetworkData(raw);
|
|
677
|
+
this.callback(masked);
|
|
678
|
+
} catch {
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
|
|
683
|
+
// src/session-id.ts
|
|
684
|
+
var SESSION_ID_MAX_LENGTH = 200;
|
|
685
|
+
var SESSION_ID_PATTERN = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
|
|
686
|
+
var SESSION_ID_RULE = `must be 1-${SESSION_ID_MAX_LENGTH} characters of letters, digits, dot, dash and underscore, with no empty dot-separated segment`;
|
|
687
|
+
function isValidSessionId(value) {
|
|
688
|
+
return typeof value === "string" && value.length > 0 && value.length <= SESSION_ID_MAX_LENGTH && SESSION_ID_PATTERN.test(value);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// src/errors.ts
|
|
692
|
+
var SERVER_EVIDENCE = [
|
|
693
|
+
"status",
|
|
694
|
+
"serverMessage",
|
|
695
|
+
"endpoint",
|
|
696
|
+
"sessionId"
|
|
697
|
+
];
|
|
698
|
+
var SERVER_OPTIONAL_EVIDENCE = ["issues"];
|
|
699
|
+
var SDK_ERRORS = {
|
|
700
|
+
KUI_E_INGEST_KEY_REJECTED: {
|
|
701
|
+
summary: "The ingest server refused the SDK's API key (401 or 403), so no events from this page can be stored. Capture has stopped.",
|
|
702
|
+
remedy: {
|
|
703
|
+
command: null,
|
|
704
|
+
manual: "The key is missing, unknown, expired, revoked, or not a UI INGEST key (a personal access token is refused with 403 however it is scoped). Mint a UI ingest key for this app with the api-server GraphQL mutation `createUIIngestKey(appId, name, ttlDays)`, authenticated as a member of the app's organisation, and pass the returned token as `apiKey` to KeployCapture.init(). No CLI verb mints one yet; a new key takes effect on the next page load."
|
|
705
|
+
},
|
|
706
|
+
evidence: SERVER_EVIDENCE,
|
|
707
|
+
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
708
|
+
},
|
|
709
|
+
KUI_E_INGEST_ENDPOINT_NOT_FOUND: {
|
|
710
|
+
summary: "The ingest server answered 404 or 405: nothing at `endpoint` accepts a POST, so no events from this page can be stored. Capture has stopped.",
|
|
711
|
+
remedy: {
|
|
712
|
+
command: null,
|
|
713
|
+
manual: "`endpoint` is wrong, not the key. The documented ingest route is `<api-server>/ui/v1/ingest` (the SDK never calls anything else). A 404 or 405 the SDK can read comes from a path typo under `/ui/v1/` or from a same-origin proxy that does not forward the route. Fix the `endpoint` passed to KeployCapture.init() and reload. If the endpoint is on another origin and its path is outside `/ui/v1/` (or the api-server has no UI ingest route), the browser refuses the CORS preflight instead and no status reaches the SDK: it retries as a network error and this code is never raised, so check the endpoint before trusting silence."
|
|
714
|
+
},
|
|
715
|
+
evidence: SERVER_EVIDENCE,
|
|
716
|
+
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
717
|
+
},
|
|
718
|
+
KUI_E_SESSION_CONFLICT: {
|
|
719
|
+
summary: "The ingest server answered 409: this session id is already claimed by a completed session or a different capture, or a batchId was re-used with different events. Capture has stopped.",
|
|
720
|
+
remedy: {
|
|
721
|
+
command: null,
|
|
722
|
+
manual: "Give each run its own session id. The usual cause is a `sessionIdGenerator` that returns a fixed value, so a second run of the same scenario posts into the first run's session; a session completed from the dashboard while the page was still recording answers the same way. Remove the override or make it return a fresh id per page load. Events already stored under this session are intact."
|
|
723
|
+
},
|
|
724
|
+
evidence: SERVER_EVIDENCE,
|
|
725
|
+
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
726
|
+
},
|
|
727
|
+
KUI_E_INGEST_REJECTED: {
|
|
728
|
+
summary: "The ingest server refused a batch with a terminal 4xx it will keep refusing: the body is malformed (400), its encoding is unsupported (415), or it is over a size limit (413). Capture has stopped.",
|
|
729
|
+
remedy: {
|
|
730
|
+
command: null,
|
|
731
|
+
manual: "Read `serverMessage`, which is the server's own sentence. 413 is one of two things the server does not tell apart by status: `ui session has reached its size limit` means this session is complete -- call KeployCapture.stop() and then init() for a new one; a sentence containing `request body exceeds` (`request body exceeds N bytes` on the wire size, `decoded request body exceeds N bytes` after gzip) means the server's body cap is lower than the 10 MiB this SDK forms every batch under, an SDK/server version mismatch. 400 and 415 are the same mismatch: the SDK builds every byte it sends, checks the session id (the one integrator-supplied value) against the server's rule before sending, clamps `batchSize` to the 5000-event cap it knows and cuts every batch at the 10 MiB decoded cap, so a 4xx of this kind means the server's rules are newer than this SDK's; `evidence.issues` names the field the server refused. Upgrade @keploy/capture-sdk to the version the server documents."
|
|
732
|
+
},
|
|
733
|
+
evidence: SERVER_EVIDENCE,
|
|
734
|
+
optionalEvidence: SERVER_OPTIONAL_EVIDENCE
|
|
735
|
+
},
|
|
736
|
+
KUI_E_SESSION_ID_INVALID: {
|
|
737
|
+
summary: "The configured `sessionIdGenerator` did not produce a session id the ingest server would accept -- it returned a string outside the rule, returned a non-string, or threw -- so capture did not start and nothing was sent.",
|
|
738
|
+
remedy: {
|
|
739
|
+
command: null,
|
|
740
|
+
manual: "`evidence.received` says what the generator produced (`string <value>`, `number 42`, `object Map {}`, `a Promise (sessionIdGenerator must return a string synchronously)`, or `threw <error>`), `evidence.sessionId` is the string it returned or null when it returned no string, and `evidence.rule` is the server's rule for one: a session id must be 1-200 characters of letters, digits, dot, dash and underscore, with no empty dot-separated segment. Make `sessionIdGenerator` return a string inside that rule (encode a `user:42/session 1`-style correlation id, e.g. base64url it) and not throw, or remove the override and let the SDK mint a UUID. The check runs before the first byte is sent, so the fix takes effect on the next init()."
|
|
741
|
+
},
|
|
742
|
+
evidence: ["sessionId", "received", "rule"],
|
|
743
|
+
optionalEvidence: []
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
var SDK_WARNINGS = {
|
|
747
|
+
KUI_E_EVENT_UNSERIALISABLE: {
|
|
748
|
+
summary: "The SDK dropped one captured event because it could not be serialised to JSON (a cycle, a BigInt, a getter that throws). The capture continues without it.",
|
|
749
|
+
remedy: {
|
|
750
|
+
command: null,
|
|
751
|
+
manual: "`evidence.eventId` and `evidence.eventType` say which event and `evidence.reason` is the message of the error JSON.stringify threw (its own for a cycle or a BigInt; a getter's or toJSON's own when one throws). A `custom` event comes from integrator code (KeployCaptureRecorder.emitEvent): make its payload plain JSON (no cycles, no BigInt, no throwing getters). Any other type is the SDK's own serialisation and a defect to report. The SDK says this once per capture -- the first such event after each init(); later unserialisable events in that capture are dropped silently."
|
|
752
|
+
},
|
|
753
|
+
evidence: ["eventId", "eventType", "reason"],
|
|
754
|
+
optionalEvidence: []
|
|
755
|
+
},
|
|
756
|
+
KUI_E_EVENT_OVERSIZED: {
|
|
757
|
+
summary: "The SDK dropped one captured event because, alone in a request body, it is over the ingest server's decoded cap (`evidence.cap` bytes); no batch could carry it. The capture continues without it.",
|
|
758
|
+
remedy: {
|
|
759
|
+
command: null,
|
|
760
|
+
manual: "`evidence.bytes` is the size of a request body carrying only this event (its JSON plus the batch envelope) and `evidence.cap` the server's limit on one body. A `dom` event this large is an rrweb FullSnapshot of a very large page, and without it later events in the recording name nodes the recording never showed: leave the heaviest subtrees out of the snapshot with `privacy.blockSelectors`; a `network` event this large is a captured body under a raised `maxBodySize` -- lower it in KeployCapture.init() so bodies are truncated before capture. The SDK says this once per capture -- the first such event after each init(); later oversized events in that capture are dropped silently."
|
|
761
|
+
},
|
|
762
|
+
evidence: ["eventId", "eventType", "bytes", "cap"],
|
|
763
|
+
optionalEvidence: []
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
function oneLine(text) {
|
|
767
|
+
return text.replace(/\s+/g, " ").trim();
|
|
768
|
+
}
|
|
769
|
+
function warningLine(evidence, prose) {
|
|
770
|
+
const { code, ...fields } = evidence;
|
|
771
|
+
return `[keploy] ${code}: dropped an event: ${oneLine(prose)} The capture continues; any further such events in this capture are dropped silently. evidence=${evidenceJson(fields)}`;
|
|
772
|
+
}
|
|
773
|
+
function evidenceJson(fields) {
|
|
774
|
+
try {
|
|
775
|
+
return JSON.stringify(fields);
|
|
776
|
+
} catch {
|
|
777
|
+
const rendered = {};
|
|
778
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
779
|
+
rendered[key] = typeof value === "string" || typeof value === "number" ? value : describeValue(value);
|
|
780
|
+
}
|
|
781
|
+
return JSON.stringify(rendered);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
function codeForStatus(status) {
|
|
785
|
+
if (status === 401 || status === 403) return "KUI_E_INGEST_KEY_REJECTED";
|
|
786
|
+
if (status === 404 || status === 405) {
|
|
787
|
+
return "KUI_E_INGEST_ENDPOINT_NOT_FOUND";
|
|
788
|
+
}
|
|
789
|
+
if (status === 409) return "KUI_E_SESSION_CONFLICT";
|
|
790
|
+
if (status >= 400 && status < 500 && status !== 429) {
|
|
791
|
+
return "KUI_E_INGEST_REJECTED";
|
|
792
|
+
}
|
|
793
|
+
return null;
|
|
794
|
+
}
|
|
795
|
+
var NO_SERVER_ERROR = { message: null, issues: null };
|
|
796
|
+
var SERVER_TEXT_LIMIT = 500;
|
|
797
|
+
function parseServerError(body) {
|
|
798
|
+
if (body === null) return NO_SERVER_ERROR;
|
|
799
|
+
const text = body.trim();
|
|
800
|
+
if (text === "") return NO_SERVER_ERROR;
|
|
801
|
+
try {
|
|
802
|
+
const parsed = JSON.parse(text);
|
|
803
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
804
|
+
const shaped = parsed;
|
|
805
|
+
if (typeof shaped.error === "string") {
|
|
806
|
+
const sentence = shaped.error.trim();
|
|
807
|
+
return {
|
|
808
|
+
message: sentence === "" ? null : sentence.slice(0, SERVER_TEXT_LIMIT),
|
|
809
|
+
issues: issuesOf(shaped.issues)
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
} catch {
|
|
814
|
+
}
|
|
815
|
+
return { message: text.slice(0, SERVER_TEXT_LIMIT), issues: null };
|
|
816
|
+
}
|
|
817
|
+
var ISSUES_LIMIT = 100;
|
|
818
|
+
function issuesOf(raw) {
|
|
819
|
+
if (!Array.isArray(raw)) return null;
|
|
820
|
+
const out = [];
|
|
821
|
+
for (const item of raw) {
|
|
822
|
+
if (out.length === ISSUES_LIMIT) break;
|
|
823
|
+
if (item === null || typeof item !== "object") continue;
|
|
824
|
+
const { path, message } = item;
|
|
825
|
+
if (typeof path !== "string" || typeof message !== "string") continue;
|
|
826
|
+
out.push({
|
|
827
|
+
path: path.slice(0, SERVER_TEXT_LIMIT),
|
|
828
|
+
message: message.slice(0, SERVER_TEXT_LIMIT)
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
return out.length > 0 ? out : null;
|
|
832
|
+
}
|
|
833
|
+
function describeValue(value) {
|
|
834
|
+
if (typeof value === "string") return value;
|
|
835
|
+
if (value instanceof Error) return `${value.name}: ${value.message}`;
|
|
836
|
+
if (typeof value === "function") return `[function ${value.name}]`;
|
|
837
|
+
if (typeof value !== "object" || value === null) return String(value);
|
|
838
|
+
try {
|
|
839
|
+
return JSON.stringify(value);
|
|
840
|
+
} catch {
|
|
841
|
+
const ctor = value.constructor;
|
|
842
|
+
const name = typeof ctor?.name === "string" ? ctor.name : "object";
|
|
843
|
+
return `[${name} not JSON-serialisable]`;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
var ISSUES_IN_PROSE = 5;
|
|
847
|
+
var CaptureError = class extends Error {
|
|
848
|
+
code;
|
|
849
|
+
/** The HTTP status that produced this, or null for a code raised before anything was sent. */
|
|
850
|
+
status;
|
|
851
|
+
/** The server's own sentence (the `error` field of its body, or the body's text), or null when there was none. */
|
|
852
|
+
serverMessage;
|
|
853
|
+
/** The server's `issues[]` -- which fields it refused -- or null when its body carried none. */
|
|
854
|
+
issues;
|
|
855
|
+
remedy;
|
|
856
|
+
evidence;
|
|
857
|
+
constructor(code, message, status, server, evidence) {
|
|
858
|
+
super(message);
|
|
859
|
+
this.name = "CaptureError";
|
|
860
|
+
this.code = code;
|
|
861
|
+
this.remedy = SDK_ERRORS[code].remedy;
|
|
862
|
+
this.status = status;
|
|
863
|
+
this.serverMessage = server.message;
|
|
864
|
+
this.issues = server.issues;
|
|
865
|
+
this.evidence = evidence;
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
var IngestRejection = class extends CaptureError {
|
|
869
|
+
constructor(init) {
|
|
870
|
+
const { message, issues } = init.server;
|
|
871
|
+
let text = `[keploy] capture stopped: the server rejected this batch with ${init.status} and will reject the rest, so capture has stopped (${init.code}). ${message === null ? "(no response body)" : message}`;
|
|
872
|
+
if (issues !== null) {
|
|
873
|
+
const named = issues.slice(0, ISSUES_IN_PROSE).map((i) => `${i.path === "" ? "body" : i.path}: ${i.message}`).join("; ");
|
|
874
|
+
const more = issues.length - ISSUES_IN_PROSE;
|
|
875
|
+
text += ` -- ${named}${more > 0 ? ` (+${more} more)` : ""}`;
|
|
876
|
+
}
|
|
877
|
+
super(init.code, text, init.status, init.server, {
|
|
878
|
+
status: init.status,
|
|
879
|
+
serverMessage: message,
|
|
880
|
+
endpoint: init.endpoint,
|
|
881
|
+
sessionId: init.sessionId,
|
|
882
|
+
...issues !== null ? { issues } : {}
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
var SessionIdRefusal = class extends CaptureError {
|
|
887
|
+
constructor(init) {
|
|
888
|
+
const what = init.sessionId !== null ? `returned ${JSON.stringify(init.sessionId)}, which the ingest server would refuse` : init.received.startsWith("threw ") ? init.received : `returned ${init.received}, which is not a session id`;
|
|
889
|
+
super(
|
|
890
|
+
"KUI_E_SESSION_ID_INVALID",
|
|
891
|
+
`[keploy] capture did not start: sessionIdGenerator ${what} (KUI_E_SESSION_ID_INVALID). A session id ${SESSION_ID_RULE}.`,
|
|
892
|
+
null,
|
|
893
|
+
NO_SERVER_ERROR,
|
|
894
|
+
{
|
|
895
|
+
sessionId: init.sessionId,
|
|
896
|
+
received: init.received,
|
|
897
|
+
rule: SESSION_ID_RULE
|
|
898
|
+
}
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
function describeReceived(outcome) {
|
|
903
|
+
if ("threw" in outcome) return `threw ${describeValue(outcome.threw)}`;
|
|
904
|
+
const value = outcome.returned;
|
|
905
|
+
if (typeof value === "object" && value !== null) {
|
|
906
|
+
if (typeof value.then === "function") {
|
|
907
|
+
return "a Promise (sessionIdGenerator must return a string synchronously)";
|
|
908
|
+
}
|
|
909
|
+
const ctor = value.constructor;
|
|
910
|
+
const name = typeof ctor?.name === "string" ? ctor.name : "";
|
|
911
|
+
if (name !== "" && name !== "Object") {
|
|
912
|
+
return `object ${name} ${describeValue(value)}`;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
return `${typeof value} ${describeValue(value)}`;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// package.json
|
|
919
|
+
var version = "3.0.1";
|
|
920
|
+
|
|
921
|
+
// src/transport.ts
|
|
922
|
+
var SDK_NAME = "@keploy/capture-sdk";
|
|
923
|
+
var SDK_VERSION = version;
|
|
924
|
+
var MAX_RETRY_ATTEMPTS = 3;
|
|
925
|
+
var BASE_RETRY_DELAY_MS = 1e3;
|
|
926
|
+
var KEEPALIVE_QUOTA_BYTES = 65536;
|
|
927
|
+
function sleep(ms) {
|
|
928
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
929
|
+
}
|
|
930
|
+
function utf8Length(text) {
|
|
931
|
+
return new TextEncoder().encode(text).length;
|
|
932
|
+
}
|
|
933
|
+
async function compressPayload(data) {
|
|
934
|
+
if (typeof CompressionStream !== "undefined" && typeof Response !== "undefined") {
|
|
935
|
+
try {
|
|
936
|
+
const compressed = new Response(data).body.pipeThrough(
|
|
937
|
+
new CompressionStream("gzip")
|
|
938
|
+
);
|
|
939
|
+
const buf = await new Response(compressed).arrayBuffer();
|
|
940
|
+
const plain = utf8Length(data);
|
|
941
|
+
if (buf.byteLength < plain) {
|
|
942
|
+
return { body: buf, bytes: buf.byteLength, encoding: "gzip" };
|
|
943
|
+
}
|
|
944
|
+
return { body: data, bytes: plain, encoding: null };
|
|
945
|
+
} catch {
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
return { body: data, bytes: utf8Length(data), encoding: null };
|
|
949
|
+
}
|
|
950
|
+
var MAX_EVENTS_PER_BATCH = 5e3;
|
|
951
|
+
var MAX_BATCH_BYTES = 10 * 1024 * 1024;
|
|
952
|
+
var Transport = class {
|
|
953
|
+
config;
|
|
954
|
+
queue = [];
|
|
955
|
+
/**
|
|
956
|
+
* Flights that failed to send and must go out again AS THEY WERE.
|
|
957
|
+
* Drained ahead of the event queue by run(). Never merged back into
|
|
958
|
+
* `queue`: re-splicing a dispatched flight's events with newer ones
|
|
959
|
+
* would put already-stored events under a new batchId, which is the
|
|
960
|
+
* duplication the id exists to prevent -- and re-using the id over a
|
|
961
|
+
* different event set is the 409 the server answers instead.
|
|
962
|
+
*/
|
|
963
|
+
retryQueue = [];
|
|
964
|
+
/** Only used by the no-randomUUID fallback of mintBatchId(). */
|
|
965
|
+
batchCounter = 0;
|
|
966
|
+
flushTimer = null;
|
|
967
|
+
/** The flush in progress, or null. One at a time: batches stay ordered. */
|
|
968
|
+
current = null;
|
|
969
|
+
sessionId = null;
|
|
970
|
+
metadata = null;
|
|
971
|
+
/*
|
|
972
|
+
* The browser half of the offline backend join, or null when this
|
|
973
|
+
* capture cannot be joined. Sent on EVERY batch rather than once at
|
|
974
|
+
* session start: a batch is the only thing the server is guaranteed to
|
|
975
|
+
* receive, and an identity that arrives only with the first one is
|
|
976
|
+
* lost whenever that batch is the one that fails.
|
|
977
|
+
*/
|
|
978
|
+
captureIdentity = null;
|
|
979
|
+
online = true;
|
|
980
|
+
started = false;
|
|
981
|
+
/** The stamp the next queued event gets; see enqueue(). */
|
|
982
|
+
nextSeq = 1;
|
|
983
|
+
/** Set by a drain request that arrived while a flush was running. */
|
|
984
|
+
drainPending = false;
|
|
985
|
+
/**
|
|
986
|
+
* Set when an event over the keepalive quota was queued while the
|
|
987
|
+
* browser said it was offline, so the online handler drains for it
|
|
988
|
+
* instead of taking one batch. Cleared once the queue has run empty.
|
|
989
|
+
*/
|
|
990
|
+
rushDeferred = false;
|
|
991
|
+
/*
|
|
992
|
+
* Bytes of keepalive request bodies currently on the wire, so the
|
|
993
|
+
* unload flush can size itself against what is LEFT of the quota
|
|
994
|
+
* rather than the whole of it.
|
|
995
|
+
*/
|
|
996
|
+
inflightKeepaliveBytes = 0;
|
|
997
|
+
/**
|
|
998
|
+
* Bytes of a request carrying no events: the fixed cost every request
|
|
999
|
+
* pays, so an event's own size can be measured against the quota.
|
|
1000
|
+
*/
|
|
1001
|
+
envelopeBytes = 0;
|
|
1002
|
+
/** Set by the first event JSON.stringify refused; see reportUnserialisable(). */
|
|
1003
|
+
reportedUnserialisable = false;
|
|
1004
|
+
reportedOversized = false;
|
|
1005
|
+
/**
|
|
1006
|
+
* Each queued event's JSON bytes, measured once at enqueue (the
|
|
1007
|
+
* keepalive rush needs the number there anyway) and read wherever a
|
|
1008
|
+
* cut is sized: the timed flight and the unload flush.
|
|
1009
|
+
*/
|
|
1010
|
+
bytesOf = /* @__PURE__ */ new WeakMap();
|
|
1011
|
+
/** The batch run() is working on, so the unload flush can take it back. */
|
|
1012
|
+
inFlight = null;
|
|
1013
|
+
constructor(config) {
|
|
1014
|
+
this.config = {
|
|
1015
|
+
...config,
|
|
1016
|
+
batchSize: Math.min(config.batchSize, MAX_EVENTS_PER_BATCH)
|
|
1017
|
+
};
|
|
1018
|
+
}
|
|
1019
|
+
/* -------------------------------------------------------------- */
|
|
1020
|
+
/* Lifecycle */
|
|
1021
|
+
/* -------------------------------------------------------------- */
|
|
1022
|
+
/**
|
|
1023
|
+
* Report a condition that ends the capture, and end it.
|
|
1024
|
+
*
|
|
1025
|
+
* NOT a throw: this runs inside a flush that nobody awaits, so a throw
|
|
1026
|
+
* becomes an unhandled rejection and is exactly as invisible as the
|
|
1027
|
+
* bare `return` it replaces. An integrator gets the callback; everyone
|
|
1028
|
+
* else gets a console error, which is the floor.
|
|
1029
|
+
*/
|
|
1030
|
+
fail(code, status, detail) {
|
|
1031
|
+
this.queue = [];
|
|
1032
|
+
this.retryQueue = [];
|
|
1033
|
+
const err = new IngestRejection({
|
|
1034
|
+
code,
|
|
1035
|
+
status,
|
|
1036
|
+
server: parseServerError(detail),
|
|
1037
|
+
endpoint: this.config.endpoint,
|
|
1038
|
+
sessionId: this.sessionId ?? null
|
|
1039
|
+
});
|
|
1040
|
+
console.error(err.message);
|
|
1041
|
+
void this.stop();
|
|
1042
|
+
try {
|
|
1043
|
+
this.config.onCaptureEnd?.();
|
|
1044
|
+
} catch {
|
|
1045
|
+
}
|
|
1046
|
+
try {
|
|
1047
|
+
this.config.onError?.(err);
|
|
1048
|
+
} catch {
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
start(sessionId, metadata, captureIdentity = null) {
|
|
1052
|
+
if (this.started) return;
|
|
1053
|
+
this.started = true;
|
|
1054
|
+
this.sessionId = sessionId;
|
|
1055
|
+
this.metadata = metadata;
|
|
1056
|
+
this.captureIdentity = captureIdentity;
|
|
1057
|
+
this.envelopeBytes = utf8Length(
|
|
1058
|
+
JSON.stringify(this.payload([], this.mintBatchId()))
|
|
1059
|
+
);
|
|
1060
|
+
this.flushTimer = setInterval(() => {
|
|
1061
|
+
void this.flush();
|
|
1062
|
+
}, this.config.batchInterval);
|
|
1063
|
+
if (typeof window !== "undefined") {
|
|
1064
|
+
window.addEventListener("online", this.handleOnline);
|
|
1065
|
+
window.addEventListener("offline", this.handleOffline);
|
|
1066
|
+
window.addEventListener("pagehide", this.handleUnload);
|
|
1067
|
+
window.addEventListener("beforeunload", this.handleUnload);
|
|
1068
|
+
document.addEventListener("visibilitychange", this.handleVisibility);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Stop accepting events and send what is queued.
|
|
1073
|
+
*
|
|
1074
|
+
* Resolves when the final flush has settled — a caller that needs to
|
|
1075
|
+
* know the tail arrived (a test, an integrator about to navigate)
|
|
1076
|
+
* can await it; nothing requires it.
|
|
1077
|
+
*/
|
|
1078
|
+
stop() {
|
|
1079
|
+
if (!this.started) return this.current ?? Promise.resolve();
|
|
1080
|
+
this.started = false;
|
|
1081
|
+
if (this.flushTimer) {
|
|
1082
|
+
clearInterval(this.flushTimer);
|
|
1083
|
+
this.flushTimer = null;
|
|
1084
|
+
}
|
|
1085
|
+
const drained = this.flush(true);
|
|
1086
|
+
if (typeof window !== "undefined") {
|
|
1087
|
+
window.removeEventListener("online", this.handleOnline);
|
|
1088
|
+
window.removeEventListener("offline", this.handleOffline);
|
|
1089
|
+
void drained.finally(() => this.disarmWhenDrained());
|
|
1090
|
+
}
|
|
1091
|
+
return drained;
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Removes the unload and hidden-tab listeners once there is nothing
|
|
1095
|
+
* left for them to send: after stop(), the first time the queue is
|
|
1096
|
+
* empty. Called wherever the queue can become empty — the drain
|
|
1097
|
+
* stop() started, a later drain (a hidden tab, or fail() on a
|
|
1098
|
+
* terminal rejection), the unload flush itself — because a listener
|
|
1099
|
+
* kept past that point is a leak for the life of the document: a
|
|
1100
|
+
* drain that failed on logout kept them, and the hidden-tab drain
|
|
1101
|
+
* that later emptied the queue removed nothing, so the Transport was
|
|
1102
|
+
* retained by pagehide, beforeunload and visibilitychange for as
|
|
1103
|
+
* long as the document lived. Idempotent; a no-op while started or
|
|
1104
|
+
* while events remain.
|
|
1105
|
+
*/
|
|
1106
|
+
disarmWhenDrained() {
|
|
1107
|
+
if (this.started || this.pendingCount() > 0) return;
|
|
1108
|
+
if (typeof window === "undefined") return;
|
|
1109
|
+
window.removeEventListener("pagehide", this.handleUnload);
|
|
1110
|
+
window.removeEventListener("beforeunload", this.handleUnload);
|
|
1111
|
+
document.removeEventListener("visibilitychange", this.handleVisibility);
|
|
1112
|
+
}
|
|
1113
|
+
/* -------------------------------------------------------------- */
|
|
1114
|
+
/* Enqueue */
|
|
1115
|
+
/* -------------------------------------------------------------- */
|
|
1116
|
+
enqueue(event) {
|
|
1117
|
+
if (!this.started) return;
|
|
1118
|
+
event.seq = this.nextSeq++;
|
|
1119
|
+
let bytes;
|
|
1120
|
+
try {
|
|
1121
|
+
const own = utf8Length(JSON.stringify(event));
|
|
1122
|
+
this.bytesOf.set(event, own);
|
|
1123
|
+
bytes = this.envelopeBytes + own;
|
|
1124
|
+
} catch (err) {
|
|
1125
|
+
this.reportUnserialisable(event, err);
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
1128
|
+
if (bytes > MAX_BATCH_BYTES) {
|
|
1129
|
+
this.reportOversized(event, bytes);
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
this.queue.push(event);
|
|
1133
|
+
while (this.queue.length > this.config.maxQueueSize) {
|
|
1134
|
+
this.queue.shift();
|
|
1135
|
+
}
|
|
1136
|
+
if (bytes > KEEPALIVE_QUOTA_BYTES) {
|
|
1137
|
+
if (this.online) void this.flush(true);
|
|
1138
|
+
else this.rushDeferred = true;
|
|
1139
|
+
} else if (this.queue.length >= this.config.batchSize) {
|
|
1140
|
+
void this.flush();
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Say that an event was dropped because it could not be serialised —
|
|
1145
|
+
* ONCE per transport, and the line says so.
|
|
1146
|
+
*
|
|
1147
|
+
* Not a throw: the caller is rrweb's emit callback or the
|
|
1148
|
+
* integrator's own code, and the SDK has no business ending their
|
|
1149
|
+
* turn. Not `onError` either: that one is reserved for a terminal
|
|
1150
|
+
* condition that ENDS the capture, and this one does not — the
|
|
1151
|
+
* session goes on without this event.
|
|
1152
|
+
*
|
|
1153
|
+
* Once, because a custom event emitted from a render or a timer would
|
|
1154
|
+
* otherwise write a console line every few milliseconds for the life
|
|
1155
|
+
* of the page: the SDK degrading the page it is there to record. The
|
|
1156
|
+
* first line carries the event's id and the reason, which is what a
|
|
1157
|
+
* developer needs to find the emitter; the rest would only repeat it.
|
|
1158
|
+
*/
|
|
1159
|
+
reportUnserialisable(event, err) {
|
|
1160
|
+
if (this.reportedUnserialisable) return;
|
|
1161
|
+
this.reportedUnserialisable = true;
|
|
1162
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
1163
|
+
console.error(
|
|
1164
|
+
warningLine(
|
|
1165
|
+
{
|
|
1166
|
+
code: "KUI_E_EVENT_UNSERIALISABLE",
|
|
1167
|
+
eventId: event.id,
|
|
1168
|
+
eventType: event.type,
|
|
1169
|
+
reason
|
|
1170
|
+
},
|
|
1171
|
+
// The reason rides in the evidence JSON only, escaped: repeated
|
|
1172
|
+
// here it would put V8's three-line cycle message, or an
|
|
1173
|
+
// "evidence=" of its own, into the prose. See warningLine.
|
|
1174
|
+
`it cannot be serialised to JSON.`
|
|
1175
|
+
)
|
|
1176
|
+
);
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Say that an event was dropped because, alone in a body, it is over
|
|
1180
|
+
* the server's decoded cap -- ONCE per transport, like
|
|
1181
|
+
* reportUnserialisable and for the same reasons: not a throw into the
|
|
1182
|
+
* emitter's turn, not `onError` (the capture goes on), and not a line
|
|
1183
|
+
* per event.
|
|
1184
|
+
*/
|
|
1185
|
+
reportOversized(event, bytes) {
|
|
1186
|
+
if (this.reportedOversized) return;
|
|
1187
|
+
this.reportedOversized = true;
|
|
1188
|
+
console.error(
|
|
1189
|
+
warningLine(
|
|
1190
|
+
{
|
|
1191
|
+
code: "KUI_E_EVENT_OVERSIZED",
|
|
1192
|
+
eventId: event.id,
|
|
1193
|
+
eventType: event.type,
|
|
1194
|
+
bytes,
|
|
1195
|
+
cap: MAX_BATCH_BYTES
|
|
1196
|
+
},
|
|
1197
|
+
`${bytes} bytes in a body, over the ingest server's ${MAX_BATCH_BYTES}-byte cap, so no batch could carry it.`
|
|
1198
|
+
)
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
/** The request body for `events`, with everything a batch carries. */
|
|
1202
|
+
payload(events, batchId) {
|
|
1203
|
+
return {
|
|
1204
|
+
sessionId: this.sessionId,
|
|
1205
|
+
batchId,
|
|
1206
|
+
events,
|
|
1207
|
+
metadata: this.metadata,
|
|
1208
|
+
sdk: { name: SDK_NAME, version: SDK_VERSION },
|
|
1209
|
+
captureIdentity: this.captureIdentity
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
/* -------------------------------------------------------------- */
|
|
1213
|
+
/* Flush */
|
|
1214
|
+
/* -------------------------------------------------------------- */
|
|
1215
|
+
/**
|
|
1216
|
+
* Send queued events.
|
|
1217
|
+
*
|
|
1218
|
+
* `drain` sends EVERYTHING queued — batch after batch, each one sized
|
|
1219
|
+
* like a timed batch, so the server's body limit is the same one a
|
|
1220
|
+
* timed batch faces — and if a flush is already running it is picked
|
|
1221
|
+
* up by that flush when its current batch finishes. A drain that
|
|
1222
|
+
* silently returned because a batch happened to be in flight would
|
|
1223
|
+
* leave a hidden tab holding events it may never get another chance
|
|
1224
|
+
* to send. A drain also ignores the `offline` flag: it is the last
|
|
1225
|
+
* attempt, the browser's offline signal is advisory, and a fetch that
|
|
1226
|
+
* fails retries and re-queues anyway. The promise resolves when the
|
|
1227
|
+
* running flush, drain included, has settled.
|
|
1228
|
+
*/
|
|
1229
|
+
flush(drain = false) {
|
|
1230
|
+
if (drain) this.drainPending = true;
|
|
1231
|
+
if (this.current) return this.current;
|
|
1232
|
+
if (this.pendingCount() === 0 || !this.online && !this.drainPending) {
|
|
1233
|
+
this.drainPending = false;
|
|
1234
|
+
return Promise.resolve();
|
|
1235
|
+
}
|
|
1236
|
+
this.current = this.run();
|
|
1237
|
+
return this.current;
|
|
1238
|
+
}
|
|
1239
|
+
async run() {
|
|
1240
|
+
try {
|
|
1241
|
+
do {
|
|
1242
|
+
const flight = this.reviveNext() ?? this.formFlight();
|
|
1243
|
+
if (flight === null) return;
|
|
1244
|
+
this.inFlight = flight;
|
|
1245
|
+
try {
|
|
1246
|
+
await this.sendWithRetry(flight);
|
|
1247
|
+
} catch {
|
|
1248
|
+
if (!flight.abandoned) {
|
|
1249
|
+
this.retryQueue.unshift(flight);
|
|
1250
|
+
this.trimToCapacity();
|
|
1251
|
+
}
|
|
1252
|
+
return;
|
|
1253
|
+
} finally {
|
|
1254
|
+
if (this.inFlight === flight) this.inFlight = null;
|
|
1255
|
+
}
|
|
1256
|
+
} while (this.drainPending && this.pendingCount() > 0);
|
|
1257
|
+
} finally {
|
|
1258
|
+
this.drainPending = false;
|
|
1259
|
+
if (this.pendingCount() === 0) this.rushDeferred = false;
|
|
1260
|
+
this.current = null;
|
|
1261
|
+
this.disarmWhenDrained();
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
/* -------------------------------------------------------------- */
|
|
1265
|
+
/* Network send */
|
|
1266
|
+
/* -------------------------------------------------------------- */
|
|
1267
|
+
async sendWithRetry(flight) {
|
|
1268
|
+
const json = flight.json;
|
|
1269
|
+
for (let attempt = 0; attempt < MAX_RETRY_ATTEMPTS; attempt++) {
|
|
1270
|
+
if (flight.abandoned) return;
|
|
1271
|
+
try {
|
|
1272
|
+
const { body, bytes, encoding } = await compressPayload(json);
|
|
1273
|
+
if (flight.abandoned) return;
|
|
1274
|
+
const headers = {
|
|
1275
|
+
"Content-Type": "application/json",
|
|
1276
|
+
"X-API-Key": this.config.apiKey
|
|
1277
|
+
};
|
|
1278
|
+
if (encoding) {
|
|
1279
|
+
headers["Content-Encoding"] = encoding;
|
|
1280
|
+
}
|
|
1281
|
+
const keepalive = bytes <= KEEPALIVE_QUOTA_BYTES;
|
|
1282
|
+
if (keepalive) this.inflightKeepaliveBytes += bytes;
|
|
1283
|
+
let response;
|
|
1284
|
+
let detail;
|
|
1285
|
+
flight.onWire = true;
|
|
1286
|
+
flight.dispatched = true;
|
|
1287
|
+
try {
|
|
1288
|
+
response = await fetch(this.config.endpoint, {
|
|
1289
|
+
method: "POST",
|
|
1290
|
+
headers,
|
|
1291
|
+
body,
|
|
1292
|
+
keepalive
|
|
1293
|
+
});
|
|
1294
|
+
try {
|
|
1295
|
+
detail = await response.text();
|
|
1296
|
+
} catch {
|
|
1297
|
+
detail = null;
|
|
1298
|
+
}
|
|
1299
|
+
} finally {
|
|
1300
|
+
flight.onWire = false;
|
|
1301
|
+
if (keepalive) this.inflightKeepaliveBytes -= bytes;
|
|
1302
|
+
}
|
|
1303
|
+
if (response.ok) return;
|
|
1304
|
+
const code = codeForStatus(response.status);
|
|
1305
|
+
if (code !== null) {
|
|
1306
|
+
this.fail(code, response.status, detail);
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
} catch {
|
|
1310
|
+
}
|
|
1311
|
+
const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt) * (0.5 + Math.random() * 0.5);
|
|
1312
|
+
await sleep(delay);
|
|
1313
|
+
}
|
|
1314
|
+
throw new Error("Transport: all retry attempts failed");
|
|
1315
|
+
}
|
|
1316
|
+
/* -------------------------------------------------------------- */
|
|
1317
|
+
/* Page-unload flush */
|
|
1318
|
+
/* -------------------------------------------------------------- */
|
|
1319
|
+
/**
|
|
1320
|
+
* The last flush, issued while the document is being torn down.
|
|
1321
|
+
*
|
|
1322
|
+
* THIS WAS navigator.sendBeacon, AND EVERY SESSION LOST ITS TAIL.
|
|
1323
|
+
* sendBeacon cannot set headers, so the batch arrived at the ingest
|
|
1324
|
+
* endpoint with no X-API-Key and was refused with 401 — after the
|
|
1325
|
+
* events had been spliced out of the queue, and with no response for
|
|
1326
|
+
* anything here to read. MEASURED in Chromium 145.0.7632.6 with a
|
|
1327
|
+
* cross-origin endpoint, 5 runs per scenario: the beacon's
|
|
1328
|
+
* application/json Blob also forces a CORS preflight the beacon does
|
|
1329
|
+
* not survive, 0/5 delivered on navigate-away and 0/5 on tab close.
|
|
1330
|
+
*
|
|
1331
|
+
* fetch with keepalive:true is what sendBeacon is specified as, plus
|
|
1332
|
+
* headers: same measurement, 5/5 and 5/5, key attached. The request
|
|
1333
|
+
* is dispatched SYNCHRONOUSLY inside the unload handler — no
|
|
1334
|
+
* compression, because CompressionStream is async and an await here
|
|
1335
|
+
* lands after the document is gone.
|
|
1336
|
+
*
|
|
1337
|
+
* THE PAYLOAD IS CUT AT THE KEEPALIVE QUOTA, oldest events first. A
|
|
1338
|
+
* keepalive request over the quota is refused by the browser before
|
|
1339
|
+
* it leaves, and one refused request loses everything; one cut at the
|
|
1340
|
+
* quota ships the prefix that fits. The quota is on the SUM of
|
|
1341
|
+
* in-flight keepalive bodies, so a timed batch still on the wire is
|
|
1342
|
+
* subtracted.
|
|
1343
|
+
*
|
|
1344
|
+
* THE CUT IS AT THE FIRST EVENT THAT DOES NOT FIT, in order — not
|
|
1345
|
+
* skip-and-continue. An event over the quota on its own (a network
|
|
1346
|
+
* event with a large body; an rrweb FullSnapshot of a big page) holds
|
|
1347
|
+
* back everything queued behind it, small or not. Not for order's
|
|
1348
|
+
* sake — every event carries its `seq` and the server sorts by it, so
|
|
1349
|
+
* a document that survives its pagehide (a back/forward-cache entry)
|
|
1350
|
+
* and later ships the held-back event from its timer is stored in
|
|
1351
|
+
* order regardless. For the node map: the flow engine's extractor.ts
|
|
1352
|
+
* builds it from the FullSnapshot, and every incremental event
|
|
1353
|
+
* behind a snapshot names its nodes by that snapshot's ids. Shipped
|
|
1354
|
+
* without it, they are resolved against a map that does not hold
|
|
1355
|
+
* their nodes, and selectorFromNode answers `body` for a node it
|
|
1356
|
+
* cannot find — a click on `body` in the generated test, silently,
|
|
1357
|
+
* where the session ending at the snapshot would have been the
|
|
1358
|
+
* truth. So what does not fit holds back what depends on it.
|
|
1359
|
+
*
|
|
1360
|
+
* Events that do not fit stay in the queue: there is no way to send
|
|
1361
|
+
* them from a dying page, and no way to report it — this is the one
|
|
1362
|
+
* flush that is fire-and-forget, and only because the document is
|
|
1363
|
+
* leaving. Which is why an event that can never fit is not left to
|
|
1364
|
+
* wait here: enqueue() sends it as soon as it is queued.
|
|
1365
|
+
*/
|
|
1366
|
+
/**
|
|
1367
|
+
* Take back the batch run() is holding, if no request for it has been
|
|
1368
|
+
* dispatched yet.
|
|
1369
|
+
*
|
|
1370
|
+
* THE GAP THIS CLOSES. run() splices a batch out of the queue and
|
|
1371
|
+
* hands it to sendWithRetry, and a request does not leave the browser
|
|
1372
|
+
* straight away: compressPayload is asynchronous, and after a failed
|
|
1373
|
+
* attempt sendWithRetry sleeps 0.5–1 s, then 1–2 s, before the next
|
|
1374
|
+
* one. Through all of that the events are in neither the queue nor a
|
|
1375
|
+
* request, and the unload flush could not see them. pagehide in that
|
|
1376
|
+
* window shipped the events queued AFTER them with keepalive and
|
|
1377
|
+
* never dispatched these, because an await does not resume in a
|
|
1378
|
+
* document that is gone — so the server's seq-sorted file got the
|
|
1379
|
+
* tail with a hole in the body. A hole is worse than a short
|
|
1380
|
+
* recording: the events after it name node ids the missing batch
|
|
1381
|
+
* introduced, and the flow engine resolves them against a map that
|
|
1382
|
+
* does not hold them.
|
|
1383
|
+
*
|
|
1384
|
+
* ONLY WHILE NOTHING IS ON THE WIRE. A dispatched keepalive request
|
|
1385
|
+
* outlives the document by design, and one without keepalive may
|
|
1386
|
+
* still arrive; re-sending those events would duplicate them in a
|
|
1387
|
+
* file the server appends to by seq. That request in flight when the
|
|
1388
|
+
* document dies is the residual limit, and it is the same one every
|
|
1389
|
+
* in-flight request has.
|
|
1390
|
+
*
|
|
1391
|
+
* `abandoned` stops every further attempt, so a document that
|
|
1392
|
+
* SURVIVES its pagehide (a back/forward-cache entry, a cancelled
|
|
1393
|
+
* navigation) does not send the batch a second time when the backoff
|
|
1394
|
+
* resumes, and run()'s catch does not unshift what has already gone.
|
|
1395
|
+
*/
|
|
1396
|
+
reclaimInFlight() {
|
|
1397
|
+
const flight = this.inFlight;
|
|
1398
|
+
if (!flight || flight.onWire || flight.abandoned) return;
|
|
1399
|
+
flight.abandoned = true;
|
|
1400
|
+
this.inFlight = null;
|
|
1401
|
+
if (flight.dispatched) {
|
|
1402
|
+
this.retryQueue.unshift(flight);
|
|
1403
|
+
this.trimToCapacity();
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
this.queue.unshift(...flight.events);
|
|
1407
|
+
this.trimToCapacity();
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* The next waiting flight as a FRESH ATTEMPT CONTEXT, or null.
|
|
1411
|
+
*
|
|
1412
|
+
* `abandoned` does one job: it stops the sendWithRetry loop that was
|
|
1413
|
+
* running when the unload flush took the flight. That loop still
|
|
1414
|
+
* holds the OLD object, so it must keep seeing `abandoned === true`
|
|
1415
|
+
* -- but the re-send must not, or it returns from sendWithRetry
|
|
1416
|
+
* before its first attempt and run() counts the flight as delivered.
|
|
1417
|
+
* MEASURED: a flight over the keepalive quota, reclaimed at pagehide
|
|
1418
|
+
* during its backoff on a document that survived (a download click,
|
|
1419
|
+
* a cancelled navigation, a bfcache restore), was shifted by the next
|
|
1420
|
+
* flush and dropped -- queueSize 2 -> 0, zero requests, where the
|
|
1421
|
+
* pre-batchId transport delivered both events. So the flags are
|
|
1422
|
+
* per attempt and the id and bytes are per flight.
|
|
1423
|
+
*/
|
|
1424
|
+
reviveNext() {
|
|
1425
|
+
const waiting = this.retryQueue.shift();
|
|
1426
|
+
if (!waiting) return null;
|
|
1427
|
+
return {
|
|
1428
|
+
events: waiting.events,
|
|
1429
|
+
batchId: waiting.batchId,
|
|
1430
|
+
json: waiting.json,
|
|
1431
|
+
dispatched: waiting.dispatched,
|
|
1432
|
+
onWire: false,
|
|
1433
|
+
abandoned: false
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* A new flight from the head of the queue, or null when it is empty.
|
|
1438
|
+
* The id and the bytes are minted together, once.
|
|
1439
|
+
*
|
|
1440
|
+
* CUT BY BYTES AS WELL AS BY COUNT, the way the unload flush cuts
|
|
1441
|
+
* against the keepalive quota: at the first event that would take the
|
|
1442
|
+
* decoded body over MAX_BATCH_BYTES, everything behind it holding for
|
|
1443
|
+
* the next flight. The first event always fits -- enqueue() refused
|
|
1444
|
+
* anything that alone would not -- so a flight is never empty while
|
|
1445
|
+
* the queue is not.
|
|
1446
|
+
*/
|
|
1447
|
+
formFlight() {
|
|
1448
|
+
if (this.queue.length === 0) return null;
|
|
1449
|
+
let bytes = this.envelopeBytes;
|
|
1450
|
+
let count = 0;
|
|
1451
|
+
const most = Math.min(this.config.batchSize, this.queue.length);
|
|
1452
|
+
while (count < most) {
|
|
1453
|
+
const cost = this.eventBytes(this.queue[count]) + (count === 0 ? 0 : 1);
|
|
1454
|
+
if (bytes + cost > MAX_BATCH_BYTES) break;
|
|
1455
|
+
bytes += cost;
|
|
1456
|
+
count++;
|
|
1457
|
+
}
|
|
1458
|
+
const batch = this.queue.splice(0, Math.max(count, 1));
|
|
1459
|
+
const batchId = this.mintBatchId();
|
|
1460
|
+
return {
|
|
1461
|
+
events: batch,
|
|
1462
|
+
batchId,
|
|
1463
|
+
json: JSON.stringify(this.payload(batch, batchId)),
|
|
1464
|
+
dispatched: false,
|
|
1465
|
+
onWire: false,
|
|
1466
|
+
abandoned: false
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
/** The event's JSON bytes: what enqueue() measured, or measured now for an event that reached the queue another way. */
|
|
1470
|
+
eventBytes(event) {
|
|
1471
|
+
let own = this.bytesOf.get(event);
|
|
1472
|
+
if (own === void 0) {
|
|
1473
|
+
own = utf8Length(JSON.stringify(event));
|
|
1474
|
+
this.bytesOf.set(event, own);
|
|
1475
|
+
}
|
|
1476
|
+
return own;
|
|
1477
|
+
}
|
|
1478
|
+
/**
|
|
1479
|
+
* The SDK's idempotency key for one POST: 36 characters of a UUID,
|
|
1480
|
+
* which is within the server's session-id shape (letters, digits,
|
|
1481
|
+
* dot, dash, underscore). Falls back to time plus a counter and a
|
|
1482
|
+
* random suffix where crypto.randomUUID is not available; only
|
|
1483
|
+
* uniqueness within one session matters, since the server scopes the
|
|
1484
|
+
* id to the session.
|
|
1485
|
+
*/
|
|
1486
|
+
mintBatchId() {
|
|
1487
|
+
const c = typeof crypto !== "undefined" ? crypto : void 0;
|
|
1488
|
+
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
1489
|
+
this.batchCounter += 1;
|
|
1490
|
+
const rand = Math.floor(Math.random() * 4294967295).toString(16).padStart(8, "0");
|
|
1491
|
+
return `${Date.now().toString(16).padStart(12, "0")}-${(this.batchCounter % 4294967296).toString(16).padStart(8, "0")}-` + rand;
|
|
1492
|
+
}
|
|
1493
|
+
/** Events waiting to be sent, retry flights included. */
|
|
1494
|
+
pendingCount() {
|
|
1495
|
+
let n = this.queue.length;
|
|
1496
|
+
for (const f of this.retryQueue) n += f.events.length;
|
|
1497
|
+
return n;
|
|
1498
|
+
}
|
|
1499
|
+
/**
|
|
1500
|
+
* On a re-queue, hold the total at maxQueueSize by dropping the NEWEST
|
|
1501
|
+
* queued events, as the old unshift-then-pop did. enqueue() trims the
|
|
1502
|
+
* queue alone (oldest first) and does not see waiting flights, so
|
|
1503
|
+
* between re-queues the total can stand one batch over maxQueueSize
|
|
1504
|
+
* -- the same bound the old code had, where one batch sat off the
|
|
1505
|
+
* queue in flight. A retry flight is never trimmed: dropping events
|
|
1506
|
+
* from it would change the set its batchId is bound to, and the
|
|
1507
|
+
* server answers that with a 409.
|
|
1508
|
+
*/
|
|
1509
|
+
trimToCapacity() {
|
|
1510
|
+
let retry = 0;
|
|
1511
|
+
for (const f of this.retryQueue) retry += f.events.length;
|
|
1512
|
+
while (this.queue.length > 0 && retry + this.queue.length > this.config.maxQueueSize) {
|
|
1513
|
+
this.queue.pop();
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
flushOnUnload() {
|
|
1517
|
+
this.reclaimInFlight();
|
|
1518
|
+
if (typeof fetch !== "function") return;
|
|
1519
|
+
while (this.retryQueue.length > 0) {
|
|
1520
|
+
const flight = this.retryQueue[0];
|
|
1521
|
+
const size = utf8Length(flight.json);
|
|
1522
|
+
if (size > KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes) return;
|
|
1523
|
+
this.retryQueue.shift();
|
|
1524
|
+
flight.dispatched = true;
|
|
1525
|
+
this.postKeepalive(flight.json, size);
|
|
1526
|
+
}
|
|
1527
|
+
if (this.queue.length === 0) return;
|
|
1528
|
+
const budget = KEEPALIVE_QUOTA_BYTES - this.inflightKeepaliveBytes;
|
|
1529
|
+
const envelope = this.payload([], this.mintBatchId());
|
|
1530
|
+
let bytes = this.envelopeBytes;
|
|
1531
|
+
let count = 0;
|
|
1532
|
+
for (const event of this.queue) {
|
|
1533
|
+
const cost = this.eventBytes(event) + (count === 0 ? 0 : 1);
|
|
1534
|
+
if (bytes + cost > budget) break;
|
|
1535
|
+
bytes += cost;
|
|
1536
|
+
count++;
|
|
1537
|
+
}
|
|
1538
|
+
if (count === 0) return;
|
|
1539
|
+
envelope.events = this.queue.splice(0, count);
|
|
1540
|
+
const json = JSON.stringify(envelope);
|
|
1541
|
+
this.postKeepalive(json, utf8Length(json));
|
|
1542
|
+
}
|
|
1543
|
+
/** One fire-and-forget keepalive POST, accounted against the quota. */
|
|
1544
|
+
postKeepalive(json, size) {
|
|
1545
|
+
try {
|
|
1546
|
+
this.inflightKeepaliveBytes += size;
|
|
1547
|
+
fetch(this.config.endpoint, {
|
|
1548
|
+
method: "POST",
|
|
1549
|
+
headers: {
|
|
1550
|
+
"Content-Type": "application/json",
|
|
1551
|
+
"X-API-Key": this.config.apiKey
|
|
1552
|
+
},
|
|
1553
|
+
body: json,
|
|
1554
|
+
keepalive: true
|
|
1555
|
+
}).then((response) => response.arrayBuffer()).catch(() => {
|
|
1556
|
+
}).finally(() => {
|
|
1557
|
+
this.inflightKeepaliveBytes -= size;
|
|
1558
|
+
});
|
|
1559
|
+
} catch {
|
|
1560
|
+
this.inflightKeepaliveBytes -= size;
|
|
1561
|
+
}
|
|
1562
|
+
}
|
|
1563
|
+
/* -------------------------------------------------------------- */
|
|
1564
|
+
/* Event handlers */
|
|
1565
|
+
/* -------------------------------------------------------------- */
|
|
1566
|
+
handleOnline = () => {
|
|
1567
|
+
this.online = true;
|
|
1568
|
+
void this.flush(this.rushDeferred);
|
|
1569
|
+
};
|
|
1570
|
+
handleOffline = () => {
|
|
1571
|
+
this.online = false;
|
|
1572
|
+
};
|
|
1573
|
+
handleUnload = () => {
|
|
1574
|
+
this.flushOnUnload();
|
|
1575
|
+
this.disarmWhenDrained();
|
|
1576
|
+
};
|
|
1577
|
+
handleVisibility = () => {
|
|
1578
|
+
if (document.visibilityState === "hidden") {
|
|
1579
|
+
void this.flush(true);
|
|
1580
|
+
}
|
|
1581
|
+
};
|
|
1582
|
+
/* -------------------------------------------------------------- */
|
|
1583
|
+
/* Accessors */
|
|
1584
|
+
/* -------------------------------------------------------------- */
|
|
1585
|
+
/** Events waiting to be sent, including those in flights waiting to be re-sent. */
|
|
1586
|
+
get queueSize() {
|
|
1587
|
+
return this.pendingCount();
|
|
1588
|
+
}
|
|
1589
|
+
};
|
|
1590
|
+
|
|
1591
|
+
// src/recorder.ts
|
|
1592
|
+
function uuid() {
|
|
1593
|
+
if (typeof crypto !== "undefined" && crypto.randomUUID) {
|
|
1594
|
+
return crypto.randomUUID();
|
|
1595
|
+
}
|
|
1596
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
1597
|
+
const r = Math.random() * 16 | 0;
|
|
1598
|
+
return (c === "x" ? r : r & 3 | 8).toString(16);
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
function gatherMetadata() {
|
|
1602
|
+
const w = typeof window !== "undefined" ? window : void 0;
|
|
1603
|
+
return {
|
|
1604
|
+
url: w?.location?.href ?? "",
|
|
1605
|
+
userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "",
|
|
1606
|
+
viewport: {
|
|
1607
|
+
width: w?.innerWidth ?? 0,
|
|
1608
|
+
height: w?.innerHeight ?? 0
|
|
1609
|
+
},
|
|
1610
|
+
referrer: typeof document !== "undefined" ? document.referrer : "",
|
|
1611
|
+
language: typeof navigator !== "undefined" ? navigator.language : "",
|
|
1612
|
+
devicePixelRatio: w?.devicePixelRatio ?? 1,
|
|
1613
|
+
timestamp: Date.now()
|
|
1614
|
+
};
|
|
1615
|
+
}
|
|
1616
|
+
var rrwebImport = null;
|
|
1617
|
+
function loadRRWeb() {
|
|
1618
|
+
if (!rrwebImport) {
|
|
1619
|
+
rrwebImport = import("rrweb").then(
|
|
1620
|
+
(rrweb) => rrweb.record,
|
|
1621
|
+
() => {
|
|
1622
|
+
rrwebImport = null;
|
|
1623
|
+
return void 0;
|
|
1624
|
+
}
|
|
1625
|
+
);
|
|
1626
|
+
}
|
|
1627
|
+
return rrwebImport;
|
|
1628
|
+
}
|
|
1629
|
+
var KeployCaptureRecorder = class {
|
|
1630
|
+
/*
|
|
1631
|
+
* TWO GATES, AND WHAT EACH ONE HOLDS.
|
|
1632
|
+
*
|
|
1633
|
+
* `phase` is the lifecycle; the two flags are the two independent
|
|
1634
|
+
* reasons an active session is not emitting everything. They are
|
|
1635
|
+
* independent on purpose: a visibilitychange used to call resume()
|
|
1636
|
+
* unconditionally, so a tab coming back into view silently undid a
|
|
1637
|
+
* pause the integrator had asked for with KeployCapture.pause(). Now
|
|
1638
|
+
* a hidden tab and a manual pause each shut their own gate, and only
|
|
1639
|
+
* their own transition reopens it.
|
|
1640
|
+
*
|
|
1641
|
+
* THE TWO GATES HOLD DIFFERENT EVENTS, and collapsing them into one
|
|
1642
|
+
* was a regression of its own:
|
|
1643
|
+
*
|
|
1644
|
+
* sessionOpen — phase "active" and not userPaused. This gate holds
|
|
1645
|
+
* EVERY event. That is what pause() promises and what a session
|
|
1646
|
+
* that has ended means.
|
|
1647
|
+
*
|
|
1648
|
+
* getState() === "recording" — sessionOpen and not hidden. The DOM
|
|
1649
|
+
* gate. It decides where rrweb may start (record() emits its Meta
|
|
1650
|
+
* and FullSnapshot synchronously, so starting into a shut gate
|
|
1651
|
+
* loses both for good) and whether rrweb's events are emitted.
|
|
1652
|
+
*
|
|
1653
|
+
* A hidden tab therefore pauses DOM emission and NOT the network
|
|
1654
|
+
* exchanges the page makes. Gating those on `hidden` too meant a user
|
|
1655
|
+
* who clicked Submit and switched tab had the click recorded with no
|
|
1656
|
+
* mock for its request, and a page init()'d in a background tab
|
|
1657
|
+
* recorded none of its load-time API calls — in both cases the
|
|
1658
|
+
* request had already been issued and the page was still doing the
|
|
1659
|
+
* work. The DOM is the part that genuinely is not happening while
|
|
1660
|
+
* nobody is looking, and the mutations that are get their baseline
|
|
1661
|
+
* back from the full snapshot taken when the gate reopens (see
|
|
1662
|
+
* openDomGate()).
|
|
1663
|
+
*/
|
|
1664
|
+
phase = "idle";
|
|
1665
|
+
userPaused = false;
|
|
1666
|
+
hidden = false;
|
|
1667
|
+
/**
|
|
1668
|
+
* A dom event has been dropped since the DOM gate last shut — i.e.
|
|
1669
|
+
* the recording has a hole that only a new baseline can close.
|
|
1670
|
+
*
|
|
1671
|
+
* Set in emitEvent, which is the single place a dom event is
|
|
1672
|
+
* dropped, and cleared by the baseline that closes it. Without it
|
|
1673
|
+
* openDomGate() re-serialised the document on EVERY transition: a
|
|
1674
|
+
* visitor who alt-tabs thirty times on a page that mutates nothing
|
|
1675
|
+
* while hidden paid thirty FullSnapshots of a document that had not
|
|
1676
|
+
* changed. A snapshot of a real page is large — transport.ts's own
|
|
1677
|
+
* measurement is 236 KB for one — and any event over
|
|
1678
|
+
* KEEPALIVE_QUOTA_BYTES (64 KiB) is sent the moment it is queued as
|
|
1679
|
+
* a full drain, so each one is also an upload of its own.
|
|
1680
|
+
*/
|
|
1681
|
+
droppedWhileShut = false;
|
|
1682
|
+
sessionId = null;
|
|
1683
|
+
metadata = null;
|
|
1684
|
+
config;
|
|
1685
|
+
onEvent = null;
|
|
1686
|
+
onSessionEnd = null;
|
|
1687
|
+
rrwebStopFn = null;
|
|
1688
|
+
/** rrweb's record(), once its import has landed. Held for takeFullSnapshot. */
|
|
1689
|
+
rrwebRecord = null;
|
|
1690
|
+
/** Set the moment rrweb's start is requested, so it is requested once. */
|
|
1691
|
+
rrwebRequested = false;
|
|
1692
|
+
/**
|
|
1693
|
+
* Counts start() calls. Both awaits below — start()'s on startRRWeb()
|
|
1694
|
+
* and startRRWeb()'s on the import — resume into whatever session is
|
|
1695
|
+
* current by then, and compare this against the value they captured
|
|
1696
|
+
* before yielding: a continuation of a superseded session does
|
|
1697
|
+
* nothing. See startRRWeb().
|
|
1698
|
+
*/
|
|
1699
|
+
generation = 0;
|
|
1700
|
+
sessionTimer = null;
|
|
1701
|
+
visibilityHandler = null;
|
|
1702
|
+
constructor(config) {
|
|
1703
|
+
this.config = config;
|
|
1704
|
+
}
|
|
1705
|
+
/* -------------------------------------------------------------- */
|
|
1706
|
+
/* Lifecycle */
|
|
1707
|
+
/* -------------------------------------------------------------- */
|
|
1708
|
+
async start(onEvent, onSessionEnd = null) {
|
|
1709
|
+
if (this.phase === "active") return this.sessionId;
|
|
1710
|
+
const sampleRate = this.config.sampleRate ?? 1;
|
|
1711
|
+
if (Math.random() > sampleRate) {
|
|
1712
|
+
this.phase = "stopped";
|
|
1713
|
+
return "";
|
|
1714
|
+
}
|
|
1715
|
+
this.onEvent = onEvent;
|
|
1716
|
+
this.onSessionEnd = onSessionEnd;
|
|
1717
|
+
let produced;
|
|
1718
|
+
try {
|
|
1719
|
+
produced = this.config.sessionIdGenerator ? this.config.sessionIdGenerator() : uuid();
|
|
1720
|
+
} catch (threw) {
|
|
1721
|
+
this.phase = "stopped";
|
|
1722
|
+
throw new SessionIdRefusal({
|
|
1723
|
+
sessionId: null,
|
|
1724
|
+
received: describeReceived({ threw })
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
if (!isValidSessionId(produced)) {
|
|
1728
|
+
this.phase = "stopped";
|
|
1729
|
+
throw new SessionIdRefusal({
|
|
1730
|
+
sessionId: typeof produced === "string" ? produced : null,
|
|
1731
|
+
received: describeReceived({ returned: produced })
|
|
1732
|
+
});
|
|
1733
|
+
}
|
|
1734
|
+
this.sessionId = produced;
|
|
1735
|
+
this.metadata = gatherMetadata();
|
|
1736
|
+
this.phase = "active";
|
|
1737
|
+
this.userPaused = false;
|
|
1738
|
+
this.droppedWhileShut = false;
|
|
1739
|
+
this.hidden = typeof document !== "undefined" && document.visibilityState === "hidden";
|
|
1740
|
+
this.rrwebRequested = false;
|
|
1741
|
+
const generation = ++this.generation;
|
|
1742
|
+
if (typeof document !== "undefined") {
|
|
1743
|
+
this.visibilityHandler = () => {
|
|
1744
|
+
this.hidden = document.visibilityState === "hidden";
|
|
1745
|
+
if (this.getState() === "recording") this.openDomGate();
|
|
1746
|
+
};
|
|
1747
|
+
document.addEventListener("visibilitychange", this.visibilityHandler);
|
|
1748
|
+
}
|
|
1749
|
+
await this.startRRWeb();
|
|
1750
|
+
if (generation !== this.generation || this.phase !== "active") return "";
|
|
1751
|
+
const maxDuration = this.config.maxSessionDuration ?? 6e5;
|
|
1752
|
+
this.sessionTimer = setTimeout(() => {
|
|
1753
|
+
this.stop();
|
|
1754
|
+
this.onSessionEnd?.();
|
|
1755
|
+
}, maxDuration);
|
|
1756
|
+
return this.sessionId;
|
|
1757
|
+
}
|
|
1758
|
+
stop() {
|
|
1759
|
+
if (this.phase !== "active") return;
|
|
1760
|
+
if (this.rrwebStopFn) {
|
|
1761
|
+
this.rrwebStopFn();
|
|
1762
|
+
this.rrwebStopFn = null;
|
|
1763
|
+
}
|
|
1764
|
+
this.rrwebRecord = null;
|
|
1765
|
+
if (this.sessionTimer) {
|
|
1766
|
+
clearTimeout(this.sessionTimer);
|
|
1767
|
+
this.sessionTimer = null;
|
|
1768
|
+
}
|
|
1769
|
+
if (this.visibilityHandler && typeof document !== "undefined") {
|
|
1770
|
+
document.removeEventListener("visibilitychange", this.visibilityHandler);
|
|
1771
|
+
this.visibilityHandler = null;
|
|
1772
|
+
}
|
|
1773
|
+
this.phase = "stopped";
|
|
1774
|
+
}
|
|
1775
|
+
/** Close the gate until resume(). A visibility change cannot reopen it. */
|
|
1776
|
+
pause() {
|
|
1777
|
+
if (this.phase !== "active") return;
|
|
1778
|
+
this.userPaused = true;
|
|
1779
|
+
}
|
|
1780
|
+
/**
|
|
1781
|
+
* Reopen the manual pause. A hidden tab still keeps the gate shut.
|
|
1782
|
+
*
|
|
1783
|
+
* And start rrweb if it has been waiting for this — the same way the
|
|
1784
|
+
* visibilitychange that shows the tab does. A pause() before rrweb's
|
|
1785
|
+
* import landed (init() and pause() in one tick behind a consent
|
|
1786
|
+
* gate) meant the import resolved into a shut gate; the decision
|
|
1787
|
+
* there read `hidden` alone, so record() went ahead, Meta and
|
|
1788
|
+
* FullSnapshot were dropped, and with nothing here to start it
|
|
1789
|
+
* again, the session stayed snapshotless for good.
|
|
1790
|
+
*/
|
|
1791
|
+
resume() {
|
|
1792
|
+
if (this.phase !== "active") return;
|
|
1793
|
+
this.userPaused = false;
|
|
1794
|
+
if (this.getState() === "recording") this.openDomGate();
|
|
1795
|
+
}
|
|
1796
|
+
/**
|
|
1797
|
+
* The DOM gate has just reopened: give the recording a baseline.
|
|
1798
|
+
*
|
|
1799
|
+
* rrweb HAS NO PAUSE, so while the gate was shut it went on observing
|
|
1800
|
+
* and emitEvent dropped what it emitted. Every incremental event
|
|
1801
|
+
* rrweb produces names its nodes by the ids of the last FullSnapshot
|
|
1802
|
+
* — an `add` introduces an id and the `attributes`, `texts` and
|
|
1803
|
+
* `removes` after it refer to it — so the events from here on refer
|
|
1804
|
+
* to nodes the recording never showed. The flow engine resolves those
|
|
1805
|
+
* ids against the node map it builds from the snapshot
|
|
1806
|
+
* (flow-engine/src/extractor.ts) and selectorFromNode answers `body`
|
|
1807
|
+
* for an id it cannot find: a click on a button added while the tab
|
|
1808
|
+
* was hidden becomes a click on `body` in the generated test, and it
|
|
1809
|
+
* passes. Nothing anywhere said the recording had a hole.
|
|
1810
|
+
*
|
|
1811
|
+
* So a reopened gate re-serialises the document and re-numbers
|
|
1812
|
+
* rrweb's mirror. Two ways in, and exactly one of them fires:
|
|
1813
|
+
*
|
|
1814
|
+
* - rrweb has not started (hidden or paused since init, where
|
|
1815
|
+
* starting it would have emitted Meta and FullSnapshot into the
|
|
1816
|
+
* shut gate). Start it now; the snapshot record() takes inside
|
|
1817
|
+
* that call IS the baseline.
|
|
1818
|
+
* - rrweb is running. takeFullSnapshot(), which also throws before
|
|
1819
|
+
* record() has run — inside a visibilitychange handler that would
|
|
1820
|
+
* be an exception in the integrator's document.
|
|
1821
|
+
*/
|
|
1822
|
+
openDomGate() {
|
|
1823
|
+
if (!this.rrwebStopFn) {
|
|
1824
|
+
this.droppedWhileShut = false;
|
|
1825
|
+
void this.startRRWeb();
|
|
1826
|
+
return;
|
|
1827
|
+
}
|
|
1828
|
+
if (!this.droppedWhileShut) return;
|
|
1829
|
+
const takeFullSnapshot = this.rrwebRecord?.takeFullSnapshot;
|
|
1830
|
+
if (!takeFullSnapshot) return;
|
|
1831
|
+
try {
|
|
1832
|
+
takeFullSnapshot.call(this.rrwebRecord);
|
|
1833
|
+
this.droppedWhileShut = false;
|
|
1834
|
+
} catch {
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
/**
|
|
1838
|
+
* The id of the session that is LIVE, or null when none is.
|
|
1839
|
+
*
|
|
1840
|
+
* Null once the session has ended, including when the
|
|
1841
|
+
* maxSessionDuration timer ended it — this used to keep answering
|
|
1842
|
+
* with the id of a session its own timer had stopped, so an
|
|
1843
|
+
* integrator tagging their logs with it went on tagging them with a
|
|
1844
|
+
* session that had finished ten minutes earlier. A pause does not
|
|
1845
|
+
* end a session, so this keeps answering through one.
|
|
1846
|
+
*/
|
|
1847
|
+
getSessionId() {
|
|
1848
|
+
return this.phase === "active" ? this.sessionId : null;
|
|
1849
|
+
}
|
|
1850
|
+
/**
|
|
1851
|
+
* The SESSION gate: a live session the integrator has not paused.
|
|
1852
|
+
*
|
|
1853
|
+
* Deliberately not derived from getState(), which is the narrower DOM
|
|
1854
|
+
* gate and answers "paused" for a hidden tab.
|
|
1855
|
+
*/
|
|
1856
|
+
get sessionOpen() {
|
|
1857
|
+
return this.phase === "active" && !this.userPaused;
|
|
1858
|
+
}
|
|
1859
|
+
/**
|
|
1860
|
+
* The DOM gate, as a public state.
|
|
1861
|
+
*
|
|
1862
|
+
* "recording" means rrweb may run and its events are emitted; a
|
|
1863
|
+
* hidden tab reads "paused" here while the session itself is still
|
|
1864
|
+
* open and still recording the exchanges the page makes. This is the
|
|
1865
|
+
* meaning the state has always had — every caller of it decides
|
|
1866
|
+
* something about rrweb — and it is the only one it can have while
|
|
1867
|
+
* one enum stands for two independent gates.
|
|
1868
|
+
*/
|
|
1869
|
+
getState() {
|
|
1870
|
+
if (this.phase === "idle") return "idle";
|
|
1871
|
+
if (this.phase === "stopped") return "stopped";
|
|
1872
|
+
return this.userPaused || this.hidden ? "paused" : "recording";
|
|
1873
|
+
}
|
|
1874
|
+
getMetadata() {
|
|
1875
|
+
return this.metadata;
|
|
1876
|
+
}
|
|
1877
|
+
/* -------------------------------------------------------------- */
|
|
1878
|
+
/* rrweb integration */
|
|
1879
|
+
/* -------------------------------------------------------------- */
|
|
1880
|
+
async startRRWeb() {
|
|
1881
|
+
if (this.rrwebRequested) return;
|
|
1882
|
+
this.rrwebRequested = true;
|
|
1883
|
+
const generation = this.generation;
|
|
1884
|
+
const rrwebRecord = await loadRRWeb();
|
|
1885
|
+
if (!rrwebRecord) return;
|
|
1886
|
+
if (generation !== this.generation) return;
|
|
1887
|
+
if (this.getState() !== "recording") {
|
|
1888
|
+
this.rrwebRequested = false;
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
this.rrwebRecord = rrwebRecord;
|
|
1892
|
+
this.rrwebStopFn = rrwebRecord(this.rrwebOptions()) ?? null;
|
|
1893
|
+
}
|
|
1894
|
+
/**
|
|
1895
|
+
* Everything the SDK's privacy configuration means to rrweb.
|
|
1896
|
+
*
|
|
1897
|
+
* NO `maskAllInputs`. MEASURED in rrweb 2.0.0-alpha.20's record()
|
|
1898
|
+
* (rrweb.js:13778-13795): `maskAllInputs: true` DISCARDS the
|
|
1899
|
+
* maskInputOptions object it was handed and substitutes a fixed map
|
|
1900
|
+
* of 16 input types, and neither `hidden` nor `file` is among them —
|
|
1901
|
+
* so the SDK's own map was dead in balanced and strict, and a CSRF
|
|
1902
|
+
* token, a session id or an internal record id in `<input
|
|
1903
|
+
* type="hidden">` was serialised in the clear in every mode.
|
|
1904
|
+
* Leaving `maskAllInputs` unset makes rrweb use the map below
|
|
1905
|
+
* verbatim (the `_maskInputOptions !== void 0` branch of the same
|
|
1906
|
+
* expression), which is the only way to name a type rrweb's fixed
|
|
1907
|
+
* map omits.
|
|
1908
|
+
*
|
|
1909
|
+
* The map is the ONLY statement of what each mode masks. Three
|
|
1910
|
+
* things are held to it and none of them keeps a second copy:
|
|
1911
|
+
* dom-masking.test.ts drives one case per entry through real rrweb
|
|
1912
|
+
* and asserts the serialised `value`, readme.test.ts holds the npm
|
|
1913
|
+
* page's privacy table to it, and readme.test.ts also requires every
|
|
1914
|
+
* input type the HTML spec has to be either in it or named in the
|
|
1915
|
+
* page's carve-out. Before that, thirteen of its rows were untested:
|
|
1916
|
+
* MEASURED, flipping `email`, `select`, `month`, `tel` and `number`
|
|
1917
|
+
* to `false` left the whole SDK suite green.
|
|
1918
|
+
*/
|
|
1919
|
+
rrwebOptions() {
|
|
1920
|
+
const privacyMode = this.config.privacyMode ?? "balanced";
|
|
1921
|
+
const privacy = this.config.privacy ?? {};
|
|
1922
|
+
const maskSelectors = [
|
|
1923
|
+
...this.config.maskSelectors ?? [],
|
|
1924
|
+
...privacy.maskSelectors ?? []
|
|
1925
|
+
];
|
|
1926
|
+
const unmaskSelectors = [
|
|
1927
|
+
...this.config.unmaskSelectors ?? [],
|
|
1928
|
+
...privacy.unmaskSelectors ?? []
|
|
1929
|
+
];
|
|
1930
|
+
const typed = privacyMode !== "off";
|
|
1931
|
+
const maskInputOptions = {
|
|
1932
|
+
color: typed,
|
|
1933
|
+
date: typed,
|
|
1934
|
+
"datetime-local": typed,
|
|
1935
|
+
email: typed,
|
|
1936
|
+
file: typed,
|
|
1937
|
+
month: typed,
|
|
1938
|
+
number: typed,
|
|
1939
|
+
range: typed,
|
|
1940
|
+
search: typed,
|
|
1941
|
+
tel: typed,
|
|
1942
|
+
text: typed,
|
|
1943
|
+
time: typed,
|
|
1944
|
+
url: typed,
|
|
1945
|
+
week: typed,
|
|
1946
|
+
textarea: typed,
|
|
1947
|
+
select: typed,
|
|
1948
|
+
password: true,
|
|
1949
|
+
hidden: true
|
|
1950
|
+
};
|
|
1951
|
+
const unmask = unmaskSelectors.join(",");
|
|
1952
|
+
const maskTextFn = unmask ? (text, element) => {
|
|
1953
|
+
try {
|
|
1954
|
+
if (element?.closest(unmask)) return text;
|
|
1955
|
+
} catch {
|
|
1956
|
+
}
|
|
1957
|
+
return text.replace(/[\S]/g, "*");
|
|
1958
|
+
} : void 0;
|
|
1959
|
+
return {
|
|
1960
|
+
// Gated inside emitEvent, like every other emitter.
|
|
1961
|
+
emit: (event) => this.emitEvent("dom", event),
|
|
1962
|
+
maskTextSelector: privacyMode === "strict" ? "*" : maskSelectors.join(",") || void 0,
|
|
1963
|
+
...maskTextFn ? { maskTextFn } : {},
|
|
1964
|
+
blockSelector: privacy.blockSelectors?.join(",") || void 0,
|
|
1965
|
+
maskInputOptions
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
/* -------------------------------------------------------------- */
|
|
1969
|
+
/* Event emission */
|
|
1970
|
+
/* -------------------------------------------------------------- */
|
|
1971
|
+
/**
|
|
1972
|
+
* Emit an event to the registered callback. This is also called
|
|
1973
|
+
* externally by the main KeployCapture orchestrator for network
|
|
1974
|
+
* events.
|
|
1975
|
+
*
|
|
1976
|
+
* THE GATES ARE HERE, so every emitter faces the same two. They used
|
|
1977
|
+
* to sit only in rrweb's emit callback, which meant "paused" and
|
|
1978
|
+
* "stopped" applied to DOM events and to nothing else.
|
|
1979
|
+
*/
|
|
1980
|
+
emitEvent(type, data) {
|
|
1981
|
+
if (type === "dom" && this.phase === "active" && this.getState() !== "recording") {
|
|
1982
|
+
this.droppedWhileShut = true;
|
|
1983
|
+
}
|
|
1984
|
+
if (!this.sessionOpen) return;
|
|
1985
|
+
if (type === "dom" && this.hidden) return;
|
|
1986
|
+
if (!this.onEvent || !this.sessionId) return;
|
|
1987
|
+
const event = {
|
|
1988
|
+
id: uuid(),
|
|
1989
|
+
sessionId: this.sessionId,
|
|
1990
|
+
timestamp: Date.now(),
|
|
1991
|
+
type,
|
|
1992
|
+
data
|
|
1993
|
+
};
|
|
1994
|
+
this.onEvent(event);
|
|
1995
|
+
}
|
|
1996
|
+
};
|
|
1997
|
+
|
|
1998
|
+
// src/identity.ts
|
|
1999
|
+
function mintSessionNonce() {
|
|
2000
|
+
const c = typeof crypto !== "undefined" ? crypto : void 0;
|
|
2001
|
+
if (!c || typeof c.getRandomValues !== "function") return null;
|
|
2002
|
+
const bytes = new Uint8Array(16);
|
|
2003
|
+
c.getRandomValues(bytes);
|
|
2004
|
+
let out = "";
|
|
2005
|
+
for (const b of bytes) out += b.toString(16).padStart(2, "0");
|
|
2006
|
+
return out;
|
|
2007
|
+
}
|
|
2008
|
+
function currentOrigin() {
|
|
2009
|
+
if (typeof window === "undefined" || !window.location) return null;
|
|
2010
|
+
const origin = window.location.origin;
|
|
2011
|
+
if (typeof origin !== "string" || origin === "" || origin === "null") {
|
|
2012
|
+
return null;
|
|
2013
|
+
}
|
|
2014
|
+
return origin;
|
|
2015
|
+
}
|
|
2016
|
+
var CaptureIdentityBuilder = class {
|
|
2017
|
+
captureId;
|
|
2018
|
+
nonce;
|
|
2019
|
+
t0WallMs;
|
|
2020
|
+
origins;
|
|
2021
|
+
constructor(captureId, now = Date.now()) {
|
|
2022
|
+
this.captureId = captureId;
|
|
2023
|
+
this.nonce = mintSessionNonce();
|
|
2024
|
+
this.t0WallMs = now;
|
|
2025
|
+
const origin = currentOrigin();
|
|
2026
|
+
this.origins = origin === null ? [] : [origin];
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* The identity, or the reason there is none.
|
|
2030
|
+
*
|
|
2031
|
+
* FAILS CLOSED on every incomplete case, matching Validate() on the Go
|
|
2032
|
+
* side: an identity missing the nonce or the origins is not a weaker
|
|
2033
|
+
* identity, it is one that would make the joiner confident about a
|
|
2034
|
+
* pairing it cannot actually establish.
|
|
2035
|
+
*/
|
|
2036
|
+
/*
|
|
2037
|
+
* IDENTITY AND JOINABILITY ARE DIFFERENT THINGS.
|
|
2038
|
+
*
|
|
2039
|
+
* This used to refuse the whole identity when no usable document origin
|
|
2040
|
+
* existed — a sandboxed iframe, a data: or file: URL — so those captures
|
|
2041
|
+
* sent `captureIdentity: null`. The server then had no token to tell one
|
|
2042
|
+
* run from another, and two runs sharing a session id merged their
|
|
2043
|
+
* events into one file at 200 OK. The guard that was supposed to stop
|
|
2044
|
+
* that could only fire when BOTH runs identified themselves, so the
|
|
2045
|
+
* degraded case — where the data is least trustworthy — was the one that
|
|
2046
|
+
* slipped through.
|
|
2047
|
+
*
|
|
2048
|
+
* The origin is what makes a capture JOINABLE to backend traffic. The
|
|
2049
|
+
* nonce is what makes it IDENTIFIABLE, and mintSessionNonce succeeds in
|
|
2050
|
+
* every browser that can run rrweb. So the identity is always sent when
|
|
2051
|
+
* a CSPRNG exists, `appOrigins` may be empty, and "can this be joined?"
|
|
2052
|
+
* is a question about that array rather than about the identity's
|
|
2053
|
+
* existence.
|
|
2054
|
+
*/
|
|
2055
|
+
build() {
|
|
2056
|
+
if (this.nonce === null) return { refusal: "no-csprng" };
|
|
2057
|
+
return {
|
|
2058
|
+
identity: {
|
|
2059
|
+
captureId: this.captureId,
|
|
2060
|
+
sessionNonce: this.nonce,
|
|
2061
|
+
t0WallMs: this.t0WallMs,
|
|
2062
|
+
// A copy, so a caller cannot mutate the builder's array through
|
|
2063
|
+
// an identity it was handed.
|
|
2064
|
+
appOrigins: [...this.origins]
|
|
2065
|
+
}
|
|
2066
|
+
};
|
|
2067
|
+
}
|
|
2068
|
+
};
|
|
2069
|
+
|
|
2070
|
+
// src/index.ts
|
|
2071
|
+
var KeployCapture = class _KeployCapture {
|
|
2072
|
+
static instance = null;
|
|
2073
|
+
recorder;
|
|
2074
|
+
network;
|
|
2075
|
+
transport;
|
|
2076
|
+
config;
|
|
2077
|
+
started = false;
|
|
2078
|
+
identity = null;
|
|
2079
|
+
constructor(config) {
|
|
2080
|
+
this.config = config;
|
|
2081
|
+
this.recorder = new KeployCaptureRecorder(config);
|
|
2082
|
+
this.network = new NetworkInterceptor(
|
|
2083
|
+
config.privacy ?? {},
|
|
2084
|
+
config.maxBodySize ?? 524288,
|
|
2085
|
+
[config.endpoint]
|
|
2086
|
+
);
|
|
2087
|
+
const transportConfig = {
|
|
2088
|
+
endpoint: config.endpoint,
|
|
2089
|
+
apiKey: config.apiKey,
|
|
2090
|
+
batchSize: config.batchSize ?? 50,
|
|
2091
|
+
batchInterval: config.batchInterval ?? 5e3,
|
|
2092
|
+
maxQueueSize: config.maxQueueSize ?? 5e3,
|
|
2093
|
+
...config.onError !== void 0 ? { onError: config.onError } : {},
|
|
2094
|
+
// A terminal rejection ends the CAPTURE, through the same path
|
|
2095
|
+
// the recorder's onSessionEnd takes. See endCapture().
|
|
2096
|
+
onCaptureEnd: () => this.endCapture()
|
|
2097
|
+
};
|
|
2098
|
+
this.transport = new Transport(transportConfig);
|
|
2099
|
+
}
|
|
2100
|
+
/* -------------------------------------------------------------- */
|
|
2101
|
+
/* Static API */
|
|
2102
|
+
/* -------------------------------------------------------------- */
|
|
2103
|
+
/**
|
|
2104
|
+
* Initialise and start capturing. This is the **only** call users need.
|
|
2105
|
+
*
|
|
2106
|
+
* ```ts
|
|
2107
|
+
* import { KeployCapture } from '@keploy/capture-sdk';
|
|
2108
|
+
* KeployCapture.init({ endpoint: '…', apiKey: '…' });
|
|
2109
|
+
* ```
|
|
2110
|
+
*/
|
|
2111
|
+
static async init(config) {
|
|
2112
|
+
if (_KeployCapture.instance) {
|
|
2113
|
+
return _KeployCapture.instance;
|
|
2114
|
+
}
|
|
2115
|
+
const capture = new _KeployCapture(config);
|
|
2116
|
+
_KeployCapture.instance = capture;
|
|
2117
|
+
try {
|
|
2118
|
+
await capture.start();
|
|
2119
|
+
} catch (err) {
|
|
2120
|
+
if (_KeployCapture.instance === capture) _KeployCapture.instance = null;
|
|
2121
|
+
throw err;
|
|
2122
|
+
}
|
|
2123
|
+
return capture;
|
|
2124
|
+
}
|
|
2125
|
+
/**
|
|
2126
|
+
* Stop all recording and flush remaining events.
|
|
2127
|
+
*
|
|
2128
|
+
* Resolves once the final flush has settled; awaiting it is optional.
|
|
2129
|
+
*/
|
|
2130
|
+
static stop() {
|
|
2131
|
+
const instance = _KeployCapture.instance;
|
|
2132
|
+
_KeployCapture.instance = null;
|
|
2133
|
+
return instance ? instance.stop() : Promise.resolve();
|
|
2134
|
+
}
|
|
2135
|
+
/**
|
|
2136
|
+
* Pause recording: no event of any kind — DOM or network — is
|
|
2137
|
+
* emitted until {@link resume}. The tab going hidden and visible in
|
|
2138
|
+
* between does not end the pause.
|
|
2139
|
+
*/
|
|
2140
|
+
static pause() {
|
|
2141
|
+
_KeployCapture.instance?.pause();
|
|
2142
|
+
}
|
|
2143
|
+
/** Resume recording after {@link pause}. A hidden tab stays paused until it is visible. */
|
|
2144
|
+
static resume() {
|
|
2145
|
+
_KeployCapture.instance?.resume();
|
|
2146
|
+
}
|
|
2147
|
+
/** Current session ID (empty string if not recording). */
|
|
2148
|
+
static getSessionId() {
|
|
2149
|
+
return _KeployCapture.instance?.recorder.getSessionId() ?? "";
|
|
2150
|
+
}
|
|
2151
|
+
/** Get the singleton instance (null if not initialised). */
|
|
2152
|
+
static getInstance() {
|
|
2153
|
+
return _KeployCapture.instance;
|
|
2154
|
+
}
|
|
2155
|
+
/**
|
|
2156
|
+
* The browser half of the offline backend join, exactly as it was
|
|
2157
|
+
* SENT — or the reason there isn't one, or null before a capture has
|
|
2158
|
+
* started.
|
|
2159
|
+
*
|
|
2160
|
+
* Rebuilding here is safe because the builder is IMMUTABLE: everything
|
|
2161
|
+
* it holds is assigned once in its constructor, so this returns the
|
|
2162
|
+
* same value start() handed the transport. An earlier version of the
|
|
2163
|
+
* builder accumulated origins, which would have made these two diverge
|
|
2164
|
+
* — and this method's docstring also claimed it could be consulted
|
|
2165
|
+
* "BEFORE the run", which was never true, since nothing is minted
|
|
2166
|
+
* until start().
|
|
2167
|
+
*
|
|
2168
|
+
* Three distinguishable answers, deliberately: `null` is "no capture
|
|
2169
|
+
* has started", `{refusal}` is "this capture cannot be joined and here
|
|
2170
|
+
* is why", `{identity}` is the value the server received.
|
|
2171
|
+
*/
|
|
2172
|
+
static getCaptureIdentity() {
|
|
2173
|
+
const builder = _KeployCapture.instance?.identity;
|
|
2174
|
+
return builder ? builder.build() : null;
|
|
2175
|
+
}
|
|
2176
|
+
/* -------------------------------------------------------------- */
|
|
2177
|
+
/* Instance methods */
|
|
2178
|
+
/* -------------------------------------------------------------- */
|
|
2179
|
+
async start() {
|
|
2180
|
+
if (this.started) return;
|
|
2181
|
+
this.started = true;
|
|
2182
|
+
let held = [];
|
|
2183
|
+
const handleEvent = (event) => {
|
|
2184
|
+
if (held) held.push(event);
|
|
2185
|
+
else this.transport.enqueue(event);
|
|
2186
|
+
};
|
|
2187
|
+
let sessionId;
|
|
2188
|
+
try {
|
|
2189
|
+
sessionId = await this.recorder.start(
|
|
2190
|
+
handleEvent,
|
|
2191
|
+
() => this.endCapture()
|
|
2192
|
+
);
|
|
2193
|
+
} catch (err) {
|
|
2194
|
+
if (!(err instanceof SessionIdRefusal)) throw err;
|
|
2195
|
+
this.refuse(err);
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
if (!sessionId) {
|
|
2199
|
+
this.started = false;
|
|
2200
|
+
return;
|
|
2201
|
+
}
|
|
2202
|
+
const metadata = this.recorder.getMetadata();
|
|
2203
|
+
this.identity = new CaptureIdentityBuilder(sessionId);
|
|
2204
|
+
const built = this.identity.build();
|
|
2205
|
+
this.transport.start(
|
|
2206
|
+
sessionId,
|
|
2207
|
+
metadata,
|
|
2208
|
+
"identity" in built ? built.identity : null
|
|
2209
|
+
);
|
|
2210
|
+
const first = held;
|
|
2211
|
+
held = null;
|
|
2212
|
+
for (const event of first) this.transport.enqueue(event);
|
|
2213
|
+
if (this.config.networkCapture !== false) {
|
|
2214
|
+
this.network.start((netEvent) => {
|
|
2215
|
+
this.recorder.emitEvent("network", netEvent);
|
|
2216
|
+
});
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
stop() {
|
|
2220
|
+
this.recorder.stop();
|
|
2221
|
+
this.network.stop();
|
|
2222
|
+
this.started = false;
|
|
2223
|
+
return this.transport.stop();
|
|
2224
|
+
}
|
|
2225
|
+
/**
|
|
2226
|
+
* The recorder refused to start: the configured sessionIdGenerator
|
|
2227
|
+
* did not produce a session id -- a string outside the server's
|
|
2228
|
+
* rule, a non-string, or a throw (KUI_E_SESSION_ID_INVALID). Nothing
|
|
2229
|
+
* has been sent and nothing is patched, but the singleton is set, so
|
|
2230
|
+
* this takes the path a server rejection takes and in the same order
|
|
2231
|
+
* -- the console line, the capture ended and the singleton released,
|
|
2232
|
+
* THEN onError -- so a handler that fixes the generator and calls
|
|
2233
|
+
* init() again gets a fresh capture, not this dead one.
|
|
2234
|
+
*/
|
|
2235
|
+
refuse(err) {
|
|
2236
|
+
console.error(err.message);
|
|
2237
|
+
this.endCapture();
|
|
2238
|
+
try {
|
|
2239
|
+
this.config.onError?.(err);
|
|
2240
|
+
} catch {
|
|
2241
|
+
}
|
|
2242
|
+
}
|
|
2243
|
+
/**
|
|
2244
|
+
* A subsystem ended this capture on its own. ONE path, two callers:
|
|
2245
|
+
*
|
|
2246
|
+
* - the recorder, when `maxSessionDuration` elapses;
|
|
2247
|
+
* - the transport, when the server answers a batch with a terminal
|
|
2248
|
+
* 4xx — a revoked key, a key for another app, or a second run
|
|
2249
|
+
* claiming a live session id. That one used to stop the transport
|
|
2250
|
+
* alone, so rrweb kept recording, fetch and XHR stayed patched and
|
|
2251
|
+
* the session timer stayed armed for a capture that could never
|
|
2252
|
+
* post another byte.
|
|
2253
|
+
*
|
|
2254
|
+
* The singleton is released either way, so a later init() starts a
|
|
2255
|
+
* NEW session rather than handing back a finished or dead one — which
|
|
2256
|
+
* is the whole recovery path after a key is rotated.
|
|
2257
|
+
*/
|
|
2258
|
+
endCapture() {
|
|
2259
|
+
void this.stop();
|
|
2260
|
+
if (_KeployCapture.instance === this) _KeployCapture.instance = null;
|
|
2261
|
+
}
|
|
2262
|
+
/*
|
|
2263
|
+
* pause()/resume() touch the recorder only. Its gate is what every
|
|
2264
|
+
* emitter honours, so there is nothing else to switch; the network
|
|
2265
|
+
* interceptor stays installed for the life of the capture rather
|
|
2266
|
+
* than being unpatched and re-patched around each pause.
|
|
2267
|
+
*/
|
|
2268
|
+
pause() {
|
|
2269
|
+
this.recorder.pause();
|
|
2270
|
+
}
|
|
2271
|
+
resume() {
|
|
2272
|
+
this.recorder.resume();
|
|
2273
|
+
}
|
|
2274
|
+
};
|
|
2275
|
+
export {
|
|
2276
|
+
CaptureError,
|
|
2277
|
+
CaptureIdentityBuilder,
|
|
2278
|
+
IngestRejection,
|
|
2279
|
+
KeployCapture,
|
|
2280
|
+
KeployCaptureRecorder,
|
|
2281
|
+
NetworkInterceptor,
|
|
2282
|
+
PrivacyEngine,
|
|
2283
|
+
SDK_ERRORS,
|
|
2284
|
+
SDK_WARNINGS,
|
|
2285
|
+
SESSION_ID_MAX_LENGTH,
|
|
2286
|
+
SESSION_ID_PATTERN,
|
|
2287
|
+
SESSION_ID_RULE,
|
|
2288
|
+
SessionIdRefusal,
|
|
2289
|
+
Transport,
|
|
2290
|
+
codeForStatus,
|
|
2291
|
+
currentOrigin,
|
|
2292
|
+
defaultPrivacyConfig,
|
|
2293
|
+
describeValue,
|
|
2294
|
+
isValidSessionId,
|
|
2295
|
+
mintSessionNonce,
|
|
2296
|
+
parseServerError
|
|
2297
|
+
};
|