@keploy/capture-sdk 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,252 @@
1
+ /**
2
+ * THE SDK'S TERMINAL FAILURES, AS AN AGENT CAN ACT ON THEM.
3
+ *
4
+ * A rejected ingest key, a wrong endpoint, a session-id collision and an
5
+ * over-sized batch used to reach the integrator's onError as one prose
6
+ * Error -- "[keploy] capture stopped: the server rejected this batch
7
+ * with 401 ..." -- readable by a human and useless to an agent, which
8
+ * cannot tell "mint a key" from "fix the URL" without parsing English.
9
+ * Every terminal failure now carries a `code` from the contract's error
10
+ * corpus, the server's own sentence as `serverMessage`, its `issues[]`
11
+ * when the body had them, and the corpus remedy, so a program reading
12
+ * onError can branch on `code` alone.
13
+ *
14
+ * THIS TABLE IS A COPY, AND IS HELD TO THE CORPUS BY A TEST. The SDK's
15
+ * only runtime dependency is rrweb (its README says so and a test holds
16
+ * the bundle size), so it cannot import @keploy/contract at runtime.
17
+ * errors-drift.test.ts imports the contract as a dev dependency and
18
+ * requires every code's summary, remedy and evidence field sets here to
19
+ * equal the corpus entry -- and builds a CaptureError of every code and
20
+ * hands its evidence to the corpus's own makeToolError, so the fields
21
+ * the SDK sends are the fields the corpus declares. Edit the corpus,
22
+ * then this, and the test says which one is behind. The copy carries
23
+ * `summary`, `remedy.{command,manual}`, `evidence` and
24
+ * `optionalEvidence` only; the corpus's `docs`, `alternatives` and
25
+ * `autofixable` are not copied because nothing in the SDK reads them.
26
+ *
27
+ * THE STATUS MAPPING IS THE TRANSPORT'S TERMINAL PREDICATE, not a
28
+ * parallel copy of one: the transport calls codeForStatus on every
29
+ * response and stops capture exactly when it answers a code.
30
+ * spec/sdk-errors.v1.json is emitted from it and executed from the file
31
+ * by sdk-errors.test.ts. JS-only: the SDK runs in the browser, and the
32
+ * Go side answers these statuses rather than consuming this mapping.
33
+ *
34
+ * ONE CODE IS RAISED BEFORE A BYTE IS SENT. The session id is the one
35
+ * integrator-supplied VALUE on the wire (`sessionIdGenerator`; the
36
+ * other integrator option that shapes a batch, `batchSize`, is clamped
37
+ * to the server's cap by the transport), and the server's 400 for a bad
38
+ * one -- "Invalid request", `issues: [{path: "sessionId"}]` -- came
39
+ * with a remedy blaming a version mismatch. The recorder now checks
40
+ * the value against the server's own rule (session-id.ts,
41
+ * spec/session-id.v1.json) and refuses to start with
42
+ * KUI_E_SESSION_ID_INVALID, naming what the generator produced -- a
43
+ * string outside the rule, a non-string, or a throw -- and the rule.
44
+ *
45
+ * TWO CLASSES, ONE BASE, SO `err.code` NARROWS `err.evidence`. The
46
+ * remedies tell a program to read `evidence.rule` or `evidence.issues`;
47
+ * with one class carrying a union evidence type, a TypeScript handler
48
+ * that branched on `code` and then did as told got TS2339 on every
49
+ * field. IngestRejection and SessionIdRefusal each declare `code` as
50
+ * the literal(s) they carry, and onError receives their union.
51
+ */
52
+ /** The four codes the server's status can produce. */
53
+ export type ServerAnsweredCode = "KUI_E_INGEST_KEY_REJECTED" | "KUI_E_INGEST_ENDPOINT_NOT_FOUND" | "KUI_E_SESSION_CONFLICT" | "KUI_E_INGEST_REJECTED";
54
+ /** The five codes the SDK raises. Everything else it retries or ignores. */
55
+ export type CaptureErrorCode = ServerAnsweredCode | "KUI_E_SESSION_ID_INVALID";
56
+ export interface CaptureRemedy {
57
+ /** null on all five: this build has no verb that mints a key, edits a config, rotates a session or shrinks a batch. */
58
+ command: null;
59
+ manual: string;
60
+ }
61
+ export interface CaptureErrorEntry {
62
+ summary: string;
63
+ remedy: CaptureRemedy;
64
+ /** The evidence fields a CaptureError of this code always carries; the corpus declares the same set. */
65
+ evidence: readonly string[];
66
+ /** The fields it carries only when it has them; the corpus declares the same set. */
67
+ optionalEvidence: readonly string[];
68
+ }
69
+ /** One entry of the server's `issues[]`: which field, and what was wrong with it. */
70
+ export interface ServerIssue {
71
+ readonly path: string;
72
+ readonly message: string;
73
+ }
74
+ export declare const SDK_ERRORS: Record<CaptureErrorCode, CaptureErrorEntry>;
75
+ /** The two codes the SDK writes to the console for a DROPPED event; the capture continues. */
76
+ export type CaptureWarningCode = "KUI_E_EVENT_UNSERIALISABLE" | "KUI_E_EVENT_OVERSIZED";
77
+ /**
78
+ * A COPY OF THE TWO WARNING ENTRIES, held to the corpus by
79
+ * errors-drift.test.ts like SDK_ERRORS. These never reach onError --
80
+ * that channel is terminal-only, and a dropped event ends nothing --
81
+ * so the console line is their only surface, and it names the code so
82
+ * the corpus's own scanner ("an agent that finds KUI_E_... in a log can
83
+ * resolve it") can find it. Before this table the two lines carried no
84
+ * code, and a dropped rrweb FullSnapshot of a huge page left a
85
+ * recording whose selectors could not resolve with a line nothing
86
+ * could look up. Each is said once per Transport, i.e. once per
87
+ * capture: a later init() on the same page starts a new count.
88
+ */
89
+ export declare const SDK_WARNINGS: Record<CaptureWarningCode, CaptureErrorEntry>;
90
+ /** The evidence a warning line carries: exactly the corpus entry's `evidence` fields. */
91
+ export type CaptureWarningEvidence = {
92
+ code: "KUI_E_EVENT_UNSERIALISABLE";
93
+ eventId: string;
94
+ eventType: string;
95
+ reason: string;
96
+ } | {
97
+ code: "KUI_E_EVENT_OVERSIZED";
98
+ eventId: string;
99
+ eventType: string;
100
+ bytes: number;
101
+ cap: number;
102
+ };
103
+ /**
104
+ * The console line for a dropped event: the code first, as a token the
105
+ * corpus scanner matches, then the prose a human reads, then the
106
+ * evidence as JSON so a program that only has the log can still read
107
+ * the fields the remedy names. `prose` is the caller's sentence about
108
+ * this drop; the "once per capture" tail is the same on both lines.
109
+ *
110
+ * ONE LINE, LITERALLY, AND NOTHING INTEGRATOR-SUPPLIED BEFORE THE
111
+ * MARKER. A log reader is line-oriented, and the JSON has to be on the
112
+ * line that carries the code; and "parse the JSON after the first
113
+ * `evidence=`" is only a rule if nothing before that marker can contain
114
+ * the marker. So the id and the type of the event ride in the JSON
115
+ * ONLY -- a first version wrote `dropped event <id> (<type>)` in the
116
+ * prose, and an id of `evidence={"fake":1}` (any string, through the
117
+ * exported Transport) sat before the real marker, and a type with a
118
+ * newline made two lines. The prose is the caller's fixed sentence
119
+ * (never free text such as `reason`; the JSON carries it, escaped) and
120
+ * is collapsed to single spaces in case it ever is not.
121
+ */
122
+ export declare function warningLine(evidence: CaptureWarningEvidence, prose: string): string;
123
+ /**
124
+ * The code for an ingest response status, or null when the status is
125
+ * not terminal. THIS IS THE TRANSPORT'S PREDICATE: it stops capture iff
126
+ * this answers a code, so 429 and every 5xx (retried) and every 2xx
127
+ * (not an error) are null here and nowhere else.
128
+ *
129
+ * 401 and 403 are both the key -- the route answers 403 to a personal
130
+ * access token however it is scoped, and 401 to a key it does not know.
131
+ * 404 and 405 are the endpoint: the SDK only ever POSTs to the ingest
132
+ * route, so nothing accepting the POST means the URL is wrong. 409 is
133
+ * every way one session id can be claimed twice. Every other terminal
134
+ * 4xx is the server refusing the bytes, and says why in its body.
135
+ */
136
+ export declare function codeForStatus(status: number): ServerAnsweredCode | null;
137
+ /** What the server said, out of its body: the sentence and, on a 400, which fields it refused. */
138
+ export interface ServerError {
139
+ readonly message: string | null;
140
+ readonly issues: readonly ServerIssue[] | null;
141
+ }
142
+ /**
143
+ * The server's explanation out of its response body. The ingest route
144
+ * answers `{"error": "..."}` plus `issues: [{path, message}]` on a 400;
145
+ * the sentence and the issues are what an agent should read, not the
146
+ * JSON around them, and the raw body sliced at 500 characters could cut
147
+ * that JSON mid-string. A body that is not that shape -- a proxy's
148
+ * HTML, a plain-text 404 -- is kept as text, trimmed to 500 characters.
149
+ * An empty or blank body, or an empty `error`, is null: "no message",
150
+ * not a message of spaces.
151
+ */
152
+ export declare function parseServerError(body: string | null): ServerError;
153
+ /**
154
+ * A value of unknown shape, rendered for a message. The same table as
155
+ * @keploy/contract's describeValue (errors-drift.test.ts holds the two
156
+ * to each other on the inputs that matter here), copied because the SDK
157
+ * cannot import the contract: `String(value)` turns every plain object
158
+ * into `[object Object]`, which names nothing, and THROWS on an object
159
+ * with no prototype -- MEASURED, a `sessionIdGenerator` returning
160
+ * `Object.create(null)` made the SDK's own hardening path throw.
161
+ */
162
+ export declare function describeValue(value: unknown): string;
163
+ /** What every server-answered code carries as evidence; `issues` only when the server sent them. */
164
+ export type IngestEvidence = Readonly<{
165
+ status: number;
166
+ serverMessage: string | null;
167
+ endpoint: string;
168
+ sessionId: string | null;
169
+ issues?: readonly ServerIssue[];
170
+ }>;
171
+ /** What KUI_E_SESSION_ID_INVALID carries: the string returned (or null), what was produced, and the rule. */
172
+ export type SessionIdEvidence = Readonly<{
173
+ sessionId: string | null;
174
+ received: string;
175
+ rule: string;
176
+ }>;
177
+ export type CaptureEvidence = IngestEvidence | SessionIdEvidence;
178
+ /**
179
+ * What onError receives when capture stops (or did not start). This is
180
+ * the BASE: every handler can read `code`, `remedy`, `message` and
181
+ * `evidence` on it, and `instanceof CaptureError` is true of both
182
+ * subclasses. A handler that branches on `code` gets the subclass, and
183
+ * with it the evidence shape the remedy tells it to read (see
184
+ * AnyCaptureError). `message` is the prose a human reads; it is
185
+ * composed by the subclass from the same fields the evidence carries,
186
+ * so what the console says and what the program gets cannot drift.
187
+ */
188
+ export declare class CaptureError extends Error {
189
+ readonly code: CaptureErrorCode;
190
+ /** The HTTP status that produced this, or null for a code raised before anything was sent. */
191
+ readonly status: number | null;
192
+ /** The server's own sentence (the `error` field of its body, or the body's text), or null when there was none. */
193
+ readonly serverMessage: string | null;
194
+ /** The server's `issues[]` -- which fields it refused -- or null when its body carried none. */
195
+ readonly issues: readonly ServerIssue[] | null;
196
+ readonly remedy: CaptureRemedy;
197
+ readonly evidence: CaptureEvidence;
198
+ protected constructor(code: CaptureErrorCode, message: string, status: number | null, server: ServerError, evidence: CaptureEvidence);
199
+ }
200
+ /** What the transport builds from a terminal response. */
201
+ export interface IngestRejectionInit {
202
+ code: ServerAnsweredCode;
203
+ status: number;
204
+ server: ServerError;
205
+ endpoint: string;
206
+ sessionId: string | null;
207
+ }
208
+ /** The server answered a batch with a terminal 4xx: one of the four server-answered codes. */
209
+ export declare class IngestRejection extends CaptureError {
210
+ readonly code: ServerAnsweredCode;
211
+ readonly status: number;
212
+ readonly evidence: IngestEvidence;
213
+ constructor(init: IngestRejectionInit);
214
+ }
215
+ /** What the recorder builds when sessionIdGenerator does not produce a session id. */
216
+ export interface SessionIdRefusalInit {
217
+ /** The string the generator returned, or null when it returned no string or threw. */
218
+ sessionId: string | null;
219
+ /** `string <value>`, `number 42`, `object {}`, `threw Error: boom` -- see describeReceived(). */
220
+ received: string;
221
+ }
222
+ /** The SDK refused to start: KUI_E_SESSION_ID_INVALID, raised before a byte was sent. */
223
+ export declare class SessionIdRefusal extends CaptureError {
224
+ readonly code: "KUI_E_SESSION_ID_INVALID";
225
+ readonly status: null;
226
+ readonly evidence: SessionIdEvidence;
227
+ constructor(init: SessionIdRefusalInit);
228
+ }
229
+ /**
230
+ * Every CaptureError a handler can receive, as a union its `code`
231
+ * discriminates: after `if (err.code === "KUI_E_SESSION_ID_INVALID")`
232
+ * the evidence is SessionIdEvidence, and otherwise IngestEvidence.
233
+ */
234
+ export type AnyCaptureError = IngestRejection | SessionIdRefusal;
235
+ /**
236
+ * What a sessionIdGenerator produced, for the evidence: the type and
237
+ * the value, so a number 42 cannot be mistaken for the string "42"
238
+ * (which the server would accept), and a throw is named as one.
239
+ *
240
+ * ONE RULE MORE THAN describeValue, which was built for CLI values: an
241
+ * object is named by its class. describeValue renders a Promise, a
242
+ * Map and a prototype-less object identically as `{}` -- MEASURED, an
243
+ * `async () => "abc"` generator (the most plausible non-string
244
+ * mistake) came back as `object {}`, and a reader looking for an empty
245
+ * object was looking for the wrong bug. A thenable is called what it
246
+ * is, with the fix: the generator must return synchronously.
247
+ */
248
+ export declare function describeReceived(outcome: {
249
+ returned: unknown;
250
+ } | {
251
+ threw: unknown;
252
+ }): string;
@@ -0,0 +1,94 @@
1
+ /** The browser half of the join, as the server side needs it. */
2
+ export interface CaptureIdentity {
3
+ /** The capture session. Equal to the SDK's sessionId. */
4
+ captureId: string;
5
+ /** Distinguishes this RUN from another run of the same session id. */
6
+ sessionNonce: string;
7
+ /** Unix epoch ms at which the browser half started. */
8
+ t0WallMs: number;
9
+ /**
10
+ * Origins the app under test was served from.
11
+ *
12
+ * MAY BE EMPTY, and an empty array is a real answer: the document had
13
+ * no usable origin (a sandboxed iframe, a data: or file: URL). The
14
+ * capture is still identified — see build() — it just cannot be joined
15
+ * to backend traffic by origin. A consumer asking "is this joinable?"
16
+ * asks about this array.
17
+ */
18
+ appOrigins: string[];
19
+ }
20
+ /**
21
+ * Why no identity is available, when none is.
22
+ *
23
+ * Returned rather than thrown, and rather than substituting a weaker
24
+ * value: a capture with no identity is still a perfectly good capture,
25
+ * it just cannot be joined. Degrading the capture because the join is
26
+ * unavailable would be the wrong trade.
27
+ */
28
+ export type IdentityRefusal = "no-csprng";
29
+ /**
30
+ * Mint a session nonce.
31
+ *
32
+ * CSPRNG ONLY, with no Math.random fallback. The fallback would not be a
33
+ * weaker nonce, it would be a nonce that reads as proof of same-run while
34
+ * two concurrent runs can collide — and the resulting join is wrong in a
35
+ * way that still returns pairs, so nothing downstream can notice. When
36
+ * there is no CSPRNG the answer is that this capture is not joinable.
37
+ */
38
+ export declare function mintSessionNonce(): string | null;
39
+ /**
40
+ * The origin of the document being captured.
41
+ *
42
+ * `location.origin` is absent on a few older engines and is the string
43
+ * "null" for an opaque origin (a sandboxed iframe, a data: or file: URL).
44
+ * An opaque origin cannot identify an app, so it is refused rather than
45
+ * recorded — an appOrigins of ["null"] would make every exchange look
46
+ * FOREIGN_ORIGIN, which is a silent empty join rather than a reported
47
+ * one.
48
+ */
49
+ export declare function currentOrigin(): string | null;
50
+ /**
51
+ * The identity for one capture, fixed at the moment it starts.
52
+ *
53
+ * FIXED, NOT ACCUMULATED. An earlier version collected origins as the
54
+ * capture proceeded, on the reasoning that a single-page app can move
55
+ * between them. That is true and it was still wrong here, for two
56
+ * reasons that only became visible once the wire protocol existed:
57
+ *
58
+ * - The transport takes a SNAPSHOT at start and sends that same value
59
+ * on every batch, so an origin observed later was never transmitted.
60
+ * - The server takes the first identity it sees and refuses to let a
61
+ * later batch replace it, because the nonce is what distinguishes
62
+ * this run from another run of the same session id.
63
+ *
64
+ * So the accumulation was unreachable from production — nothing outside
65
+ * the constructor ever called it — while three tests pinned its
66
+ * dedup-and-copy behaviour, which is a test suite describing a feature
67
+ * the product does not have.
68
+ *
69
+ * The consequence is a real and stated limitation: a capture that
70
+ * navigates across origins records only the one it started on. Widening
71
+ * that needs the server to accept an origin set that grows without the
72
+ * rest of the identity changing, which is a protocol decision, not a
73
+ * line of glue.
74
+ */
75
+ export declare class CaptureIdentityBuilder {
76
+ private readonly captureId;
77
+ private readonly nonce;
78
+ private readonly t0WallMs;
79
+ private readonly origins;
80
+ constructor(captureId: string, now?: number);
81
+ /**
82
+ * The identity, or the reason there is none.
83
+ *
84
+ * FAILS CLOSED on every incomplete case, matching Validate() on the Go
85
+ * side: an identity missing the nonce or the origins is not a weaker
86
+ * identity, it is one that would make the joiner confident about a
87
+ * pairing it cannot actually establish.
88
+ */
89
+ build(): {
90
+ identity: CaptureIdentity;
91
+ } | {
92
+ refusal: IdentityRefusal;
93
+ };
94
+ }
@@ -0,0 +1,104 @@
1
+ export type { CaptureConfig, SessionEvent, SessionEventType, NetworkEvent, NetworkRequestType, SessionMetadata, CaptureSession, PrivacyConfig, PiiPattern, TransportPayload, EventCallback, NetworkEventCallback, } from "./types";
2
+ export { PrivacyEngine, defaultPrivacyConfig } from "./privacy";
3
+ export { NetworkInterceptor } from "./network";
4
+ export { Transport } from "./transport";
5
+ export { CaptureError, IngestRejection, SessionIdRefusal, SDK_ERRORS, SDK_WARNINGS, codeForStatus, describeValue, parseServerError, } from "./errors";
6
+ export type { AnyCaptureError, CaptureErrorCode, CaptureWarningCode, CaptureWarningEvidence, CaptureEvidence, CaptureRemedy, IngestEvidence, ServerAnsweredCode, ServerError, ServerIssue, SessionIdEvidence, } from "./errors";
7
+ export { SESSION_ID_MAX_LENGTH, SESSION_ID_PATTERN, SESSION_ID_RULE, isValidSessionId, } from "./session-id";
8
+ export type { TransportConfig } from "./transport";
9
+ export { KeployCaptureRecorder } from "./recorder";
10
+ export type { RecorderState, OnEventCallback, OnSessionEndCallback, } from "./recorder";
11
+ export { CaptureIdentityBuilder, mintSessionNonce, currentOrigin, } from "./identity";
12
+ export type { CaptureIdentity, IdentityRefusal } from "./identity";
13
+ import type { CaptureConfig } from "./types";
14
+ import { type CaptureIdentity, type IdentityRefusal } from "./identity";
15
+ export declare class KeployCapture {
16
+ private static instance;
17
+ private recorder;
18
+ private network;
19
+ private transport;
20
+ private config;
21
+ private started;
22
+ private identity;
23
+ private constructor();
24
+ /**
25
+ * Initialise and start capturing. This is the **only** call users need.
26
+ *
27
+ * ```ts
28
+ * import { KeployCapture } from '@keploy/capture-sdk';
29
+ * KeployCapture.init({ endpoint: '…', apiKey: '…' });
30
+ * ```
31
+ */
32
+ static init(config: CaptureConfig): Promise<KeployCapture>;
33
+ /**
34
+ * Stop all recording and flush remaining events.
35
+ *
36
+ * Resolves once the final flush has settled; awaiting it is optional.
37
+ */
38
+ static stop(): Promise<void>;
39
+ /**
40
+ * Pause recording: no event of any kind — DOM or network — is
41
+ * emitted until {@link resume}. The tab going hidden and visible in
42
+ * between does not end the pause.
43
+ */
44
+ static pause(): void;
45
+ /** Resume recording after {@link pause}. A hidden tab stays paused until it is visible. */
46
+ static resume(): void;
47
+ /** Current session ID (empty string if not recording). */
48
+ static getSessionId(): string;
49
+ /** Get the singleton instance (null if not initialised). */
50
+ static getInstance(): KeployCapture | null;
51
+ /**
52
+ * The browser half of the offline backend join, exactly as it was
53
+ * SENT — or the reason there isn't one, or null before a capture has
54
+ * started.
55
+ *
56
+ * Rebuilding here is safe because the builder is IMMUTABLE: everything
57
+ * it holds is assigned once in its constructor, so this returns the
58
+ * same value start() handed the transport. An earlier version of the
59
+ * builder accumulated origins, which would have made these two diverge
60
+ * — and this method's docstring also claimed it could be consulted
61
+ * "BEFORE the run", which was never true, since nothing is minted
62
+ * until start().
63
+ *
64
+ * Three distinguishable answers, deliberately: `null` is "no capture
65
+ * has started", `{refusal}` is "this capture cannot be joined and here
66
+ * is why", `{identity}` is the value the server received.
67
+ */
68
+ static getCaptureIdentity(): {
69
+ identity: CaptureIdentity;
70
+ } | {
71
+ refusal: IdentityRefusal;
72
+ } | null;
73
+ private start;
74
+ private stop;
75
+ /**
76
+ * The recorder refused to start: the configured sessionIdGenerator
77
+ * did not produce a session id -- a string outside the server's
78
+ * rule, a non-string, or a throw (KUI_E_SESSION_ID_INVALID). Nothing
79
+ * has been sent and nothing is patched, but the singleton is set, so
80
+ * this takes the path a server rejection takes and in the same order
81
+ * -- the console line, the capture ended and the singleton released,
82
+ * THEN onError -- so a handler that fixes the generator and calls
83
+ * init() again gets a fresh capture, not this dead one.
84
+ */
85
+ private refuse;
86
+ /**
87
+ * A subsystem ended this capture on its own. ONE path, two callers:
88
+ *
89
+ * - the recorder, when `maxSessionDuration` elapses;
90
+ * - the transport, when the server answers a batch with a terminal
91
+ * 4xx — a revoked key, a key for another app, or a second run
92
+ * claiming a live session id. That one used to stop the transport
93
+ * alone, so rrweb kept recording, fetch and XHR stayed patched and
94
+ * the session timer stayed armed for a capture that could never
95
+ * post another byte.
96
+ *
97
+ * The singleton is released either way, so a later init() starts a
98
+ * NEW session rather than handing back a finished or dead one — which
99
+ * is the whole recovery path after a key is rotated.
100
+ */
101
+ private endCapture;
102
+ private pause;
103
+ private resume;
104
+ }