@nagoorkani/session-capture-core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +25 -0
- package/README.md +42 -0
- package/dist/batcher.d.ts +58 -0
- package/dist/batcher.js +106 -0
- package/dist/breadcrumbs.d.ts +22 -0
- package/dist/breadcrumbs.js +45 -0
- package/dist/config.d.ts +60 -0
- package/dist/config.js +134 -0
- package/dist/container.d.ts +33 -0
- package/dist/container.js +48 -0
- package/dist/core.d.ts +175 -0
- package/dist/core.js +414 -0
- package/dist/dispatcher.d.ts +43 -0
- package/dist/dispatcher.js +74 -0
- package/dist/errors.d.ts +40 -0
- package/dist/errors.js +186 -0
- package/dist/ids.d.ts +29 -0
- package/dist/ids.js +58 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.js +39 -0
- package/dist/network.d.ts +123 -0
- package/dist/network.js +510 -0
- package/dist/performance.d.ts +33 -0
- package/dist/performance.js +54 -0
- package/dist/queue.d.ts +70 -0
- package/dist/queue.js +105 -0
- package/dist/redact.d.ts +19 -0
- package/dist/redact.js +61 -0
- package/dist/replay-gate.d.ts +69 -0
- package/dist/replay-gate.js +78 -0
- package/dist/safe.d.ts +26 -0
- package/dist/safe.js +88 -0
- package/dist/session.d.ts +80 -0
- package/dist/session.js +111 -0
- package/dist/store.d.ts +44 -0
- package/dist/store.js +49 -0
- package/dist/transport.d.ts +62 -0
- package/dist/transport.js +84 -0
- package/dist/types.d.ts +92 -0
- package/dist/types.js +26 -0
- package/package.json +45 -0
package/dist/queue.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable send queue.
|
|
3
|
+
*
|
|
4
|
+
* One file per batch, not one append-only log. A batch is therefore written
|
|
5
|
+
* and deleted atomically: a process killed mid-write leaves one unparseable
|
|
6
|
+
* file rather than a truncated line that corrupts everything after it in a
|
|
7
|
+
* shared log.
|
|
8
|
+
*
|
|
9
|
+
* Names sort oldest-first, so ordering falls out of `list()` without tracking
|
|
10
|
+
* an index that could disagree with what is on disk.
|
|
11
|
+
*/
|
|
12
|
+
const DEFAULT_MAX_BATCHES = 50;
|
|
13
|
+
const DEFAULT_MAX_ATTEMPTS = 8;
|
|
14
|
+
export class SendQueue {
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this.counter = 0;
|
|
17
|
+
this.droppedCount = 0;
|
|
18
|
+
this.abandonedCount = 0;
|
|
19
|
+
this.store = options.store;
|
|
20
|
+
this.maxBatches = options.maxBatches ?? DEFAULT_MAX_BATCHES;
|
|
21
|
+
this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
22
|
+
}
|
|
23
|
+
/** Batches dropped because the queue was full. */
|
|
24
|
+
get dropped() {
|
|
25
|
+
return this.droppedCount;
|
|
26
|
+
}
|
|
27
|
+
/** Batches abandoned after exhausting their attempts. */
|
|
28
|
+
get abandoned() {
|
|
29
|
+
return this.abandonedCount;
|
|
30
|
+
}
|
|
31
|
+
async size() {
|
|
32
|
+
return (await this.store.list()).length;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Persist a batch for sending.
|
|
36
|
+
*
|
|
37
|
+
* Called before any network attempt, so a crash between capture and delivery
|
|
38
|
+
* loses nothing.
|
|
39
|
+
*/
|
|
40
|
+
async enqueue(batch, now = Date.now()) {
|
|
41
|
+
await this.prune();
|
|
42
|
+
// Timestamp orders them; the counter breaks ties within a millisecond,
|
|
43
|
+
// which happens whenever several batches flush together.
|
|
44
|
+
this.counter = (this.counter + 1) % 1000000;
|
|
45
|
+
const name = `${String(now).padStart(15, '0')}-${String(this.counter).padStart(6, '0')}.json`;
|
|
46
|
+
const envelope = { batch, attempts: 0 };
|
|
47
|
+
await this.store.write(name, JSON.stringify(envelope));
|
|
48
|
+
return name;
|
|
49
|
+
}
|
|
50
|
+
/** Oldest queued batches, oldest first. */
|
|
51
|
+
async peek(limit = 5) {
|
|
52
|
+
const names = (await this.store.list()).sort().slice(0, limit);
|
|
53
|
+
const out = [];
|
|
54
|
+
for (const name of names) {
|
|
55
|
+
const raw = await this.store.read(name);
|
|
56
|
+
if (raw === null)
|
|
57
|
+
continue;
|
|
58
|
+
try {
|
|
59
|
+
const envelope = JSON.parse(raw);
|
|
60
|
+
if (!envelope?.batch?.events)
|
|
61
|
+
throw new Error('missing events');
|
|
62
|
+
out.push({ name, batch: envelope.batch, attempts: envelope.attempts ?? 0 });
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Unparseable, most likely a write interrupted by process death.
|
|
66
|
+
// Discard it rather than retrying something that can never succeed.
|
|
67
|
+
await this.store.remove(name);
|
|
68
|
+
this.abandonedCount += 1;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
async remove(name) {
|
|
74
|
+
await this.store.remove(name);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Record a failed attempt.
|
|
78
|
+
*
|
|
79
|
+
* Returns false when the batch has been abandoned, so the caller knows it is
|
|
80
|
+
* gone rather than merely deferred.
|
|
81
|
+
*/
|
|
82
|
+
async recordFailure(entry) {
|
|
83
|
+
const attempts = entry.attempts + 1;
|
|
84
|
+
if (attempts >= this.maxAttempts) {
|
|
85
|
+
await this.store.remove(entry.name);
|
|
86
|
+
this.abandonedCount += 1;
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
const envelope = { batch: entry.batch, attempts };
|
|
90
|
+
await this.store.write(entry.name, JSON.stringify(envelope));
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
/** Drop oldest batches until the queue is under its ceiling. */
|
|
94
|
+
async prune() {
|
|
95
|
+
const names = (await this.store.list()).sort();
|
|
96
|
+
const excess = names.length - (this.maxBatches - 1);
|
|
97
|
+
for (let i = 0; i < excess; i += 1) {
|
|
98
|
+
const name = names[i];
|
|
99
|
+
if (!name)
|
|
100
|
+
break;
|
|
101
|
+
await this.store.remove(name);
|
|
102
|
+
this.droppedCount += 1;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
package/dist/redact.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-device redaction.
|
|
3
|
+
*
|
|
4
|
+
* Runs before anything enters the buffer (section 36). Data that never leaves
|
|
5
|
+
* the device cannot leak from the backend, so this is the only redaction step
|
|
6
|
+
* that is genuinely reliable — the server-side pass exists as defense in
|
|
7
|
+
* depth against SDKs too old to have current rules.
|
|
8
|
+
*
|
|
9
|
+
* Deliberately over-redacts. A false positive costs one field of debugging
|
|
10
|
+
* context; a false negative puts a credential in someone's log aggregator.
|
|
11
|
+
*/
|
|
12
|
+
export declare const REDACTED = "[redacted]";
|
|
13
|
+
/**
|
|
14
|
+
* Recursively redact sensitive keys.
|
|
15
|
+
*
|
|
16
|
+
* `maskedKeys` comes from remote config, so a project can add its own without
|
|
17
|
+
* shipping a new app build.
|
|
18
|
+
*/
|
|
19
|
+
export declare function redact(value: unknown, maskedKeys?: readonly string[]): unknown;
|
package/dist/redact.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-device redaction.
|
|
3
|
+
*
|
|
4
|
+
* Runs before anything enters the buffer (section 36). Data that never leaves
|
|
5
|
+
* the device cannot leak from the backend, so this is the only redaction step
|
|
6
|
+
* that is genuinely reliable — the server-side pass exists as defense in
|
|
7
|
+
* depth against SDKs too old to have current rules.
|
|
8
|
+
*
|
|
9
|
+
* Deliberately over-redacts. A false positive costs one field of debugging
|
|
10
|
+
* context; a false negative puts a credential in someone's log aggregator.
|
|
11
|
+
*/
|
|
12
|
+
/** Never captured, regardless of configuration. */
|
|
13
|
+
const DENIED_KEYS = new Set([
|
|
14
|
+
'authorization',
|
|
15
|
+
'cookie',
|
|
16
|
+
'set-cookie',
|
|
17
|
+
'proxy-authorization',
|
|
18
|
+
]);
|
|
19
|
+
/** Substring match on the key name, case-insensitive. */
|
|
20
|
+
const DENIED_PATTERN = /token|key|secret|password|passwd|auth|session|credential/i;
|
|
21
|
+
export const REDACTED = '[redacted]';
|
|
22
|
+
/** Guards against pathological nesting; deeper values are dropped. */
|
|
23
|
+
const MAX_DEPTH = 8;
|
|
24
|
+
function isDenied(key, extraKeys) {
|
|
25
|
+
const lower = key.toLowerCase();
|
|
26
|
+
return (DENIED_KEYS.has(lower) || extraKeys.has(lower) || DENIED_PATTERN.test(key));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Recursively redact sensitive keys.
|
|
30
|
+
*
|
|
31
|
+
* `maskedKeys` comes from remote config, so a project can add its own without
|
|
32
|
+
* shipping a new app build.
|
|
33
|
+
*/
|
|
34
|
+
export function redact(value, maskedKeys = []) {
|
|
35
|
+
const extra = new Set(maskedKeys.map((k) => k.toLowerCase()));
|
|
36
|
+
return walk(value, extra, 0, new WeakSet());
|
|
37
|
+
}
|
|
38
|
+
function walk(value, extra, depth, seen) {
|
|
39
|
+
if (value === null || typeof value !== 'object') {
|
|
40
|
+
return value;
|
|
41
|
+
}
|
|
42
|
+
if (depth >= MAX_DEPTH) {
|
|
43
|
+
return REDACTED;
|
|
44
|
+
}
|
|
45
|
+
// A circular reference would otherwise recurse until the stack blows —
|
|
46
|
+
// taking the host app down with it.
|
|
47
|
+
if (seen.has(value)) {
|
|
48
|
+
return REDACTED;
|
|
49
|
+
}
|
|
50
|
+
seen.add(value);
|
|
51
|
+
if (Array.isArray(value)) {
|
|
52
|
+
return value.map((item) => walk(item, extra, depth + 1, seen));
|
|
53
|
+
}
|
|
54
|
+
const out = {};
|
|
55
|
+
for (const [key, item] of Object.entries(value)) {
|
|
56
|
+
out[key] = isDenied(key, extra)
|
|
57
|
+
? REDACTED
|
|
58
|
+
: walk(item, extra, depth + 1, seen);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether the open session records.
|
|
3
|
+
*
|
|
4
|
+
* Shared by both replay packages, and here rather than in either of them
|
|
5
|
+
* because the answer does not depend on whether the recording is screenshots
|
|
6
|
+
* or DOM events. This is the piece worth testing: it got the answer wrong once
|
|
7
|
+
* already, and the symptom was a session that recorded nothing with no error
|
|
8
|
+
* anywhere to explain it.
|
|
9
|
+
*
|
|
10
|
+
* Consulted at session start *and* on every flush tick, for three reasons
|
|
11
|
+
* that all bite:
|
|
12
|
+
*
|
|
13
|
+
* - `installReplay` runs synchronously after `init()`, before the first
|
|
14
|
+
* remote config fetch returns. Deciding once at that moment reads
|
|
15
|
+
* `DEFAULT_CONFIG`, where replay is off — so the first session of every
|
|
16
|
+
* launch recorded nothing, whatever the project had configured.
|
|
17
|
+
* - The kill switch has to reach a session already in progress. That is the
|
|
18
|
+
* entire point of it.
|
|
19
|
+
* - Turning recording on from the dashboard should take effect within a
|
|
20
|
+
* segment, not at the next session.
|
|
21
|
+
*
|
|
22
|
+
* Sampling is still decided once per session: the rate is pinned the first
|
|
23
|
+
* time a real decision is made and ignored thereafter, because a session that
|
|
24
|
+
* starts recording halfway through looks complete and is silently wrong.
|
|
25
|
+
*/
|
|
26
|
+
/** The slice of `RemoteConfig` this needs. Structural, so tests need no core. */
|
|
27
|
+
export interface ReplayConfig {
|
|
28
|
+
enabled: boolean;
|
|
29
|
+
replayEnabled: boolean;
|
|
30
|
+
replaySampleRate: number;
|
|
31
|
+
/** 0 means no config has arrived yet. The server never sends 0. */
|
|
32
|
+
configVersion: number;
|
|
33
|
+
}
|
|
34
|
+
export type GateAction =
|
|
35
|
+
/** No config yet. Not a decision — do nothing, and ask again next tick. */
|
|
36
|
+
{
|
|
37
|
+
kind: 'wait';
|
|
38
|
+
}
|
|
39
|
+
/** Off remotely. Stop, and discard what is already on disk. */
|
|
40
|
+
| {
|
|
41
|
+
kind: 'off';
|
|
42
|
+
}
|
|
43
|
+
/** Decided: this session is not in the sample. */
|
|
44
|
+
| {
|
|
45
|
+
kind: 'skip';
|
|
46
|
+
} | {
|
|
47
|
+
kind: 'record';
|
|
48
|
+
sessionId: string;
|
|
49
|
+
};
|
|
50
|
+
export declare class ReplayGate {
|
|
51
|
+
private readonly sampled;
|
|
52
|
+
private openSession;
|
|
53
|
+
/** The session the rate below was pinned for. */
|
|
54
|
+
private decidedFor;
|
|
55
|
+
private rate;
|
|
56
|
+
private forced;
|
|
57
|
+
constructor(sampled: (sessionId: string, rate: number) => boolean);
|
|
58
|
+
/** A session has begun. Any previous decision belonged to a previous one. */
|
|
59
|
+
open(sessionId: string): void;
|
|
60
|
+
/**
|
|
61
|
+
* Record this session whatever the sampling says.
|
|
62
|
+
*
|
|
63
|
+
* Errors bypass sampling everywhere else in this system; a recording of the
|
|
64
|
+
* seconds before a crash is the case replay exists for.
|
|
65
|
+
*/
|
|
66
|
+
force(sessionId: string): void;
|
|
67
|
+
evaluate(config: ReplayConfig): GateAction;
|
|
68
|
+
reset(): void;
|
|
69
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether the open session records.
|
|
3
|
+
*
|
|
4
|
+
* Shared by both replay packages, and here rather than in either of them
|
|
5
|
+
* because the answer does not depend on whether the recording is screenshots
|
|
6
|
+
* or DOM events. This is the piece worth testing: it got the answer wrong once
|
|
7
|
+
* already, and the symptom was a session that recorded nothing with no error
|
|
8
|
+
* anywhere to explain it.
|
|
9
|
+
*
|
|
10
|
+
* Consulted at session start *and* on every flush tick, for three reasons
|
|
11
|
+
* that all bite:
|
|
12
|
+
*
|
|
13
|
+
* - `installReplay` runs synchronously after `init()`, before the first
|
|
14
|
+
* remote config fetch returns. Deciding once at that moment reads
|
|
15
|
+
* `DEFAULT_CONFIG`, where replay is off — so the first session of every
|
|
16
|
+
* launch recorded nothing, whatever the project had configured.
|
|
17
|
+
* - The kill switch has to reach a session already in progress. That is the
|
|
18
|
+
* entire point of it.
|
|
19
|
+
* - Turning recording on from the dashboard should take effect within a
|
|
20
|
+
* segment, not at the next session.
|
|
21
|
+
*
|
|
22
|
+
* Sampling is still decided once per session: the rate is pinned the first
|
|
23
|
+
* time a real decision is made and ignored thereafter, because a session that
|
|
24
|
+
* starts recording halfway through looks complete and is silently wrong.
|
|
25
|
+
*/
|
|
26
|
+
export class ReplayGate {
|
|
27
|
+
constructor(sampled) {
|
|
28
|
+
this.openSession = null;
|
|
29
|
+
/** The session the rate below was pinned for. */
|
|
30
|
+
this.decidedFor = null;
|
|
31
|
+
this.rate = 0;
|
|
32
|
+
this.forced = false;
|
|
33
|
+
this.sampled = sampled;
|
|
34
|
+
}
|
|
35
|
+
/** A session has begun. Any previous decision belonged to a previous one. */
|
|
36
|
+
open(sessionId) {
|
|
37
|
+
this.openSession = sessionId;
|
|
38
|
+
this.decidedFor = null;
|
|
39
|
+
this.forced = false;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Record this session whatever the sampling says.
|
|
43
|
+
*
|
|
44
|
+
* Errors bypass sampling everywhere else in this system; a recording of the
|
|
45
|
+
* seconds before a crash is the case replay exists for.
|
|
46
|
+
*/
|
|
47
|
+
force(sessionId) {
|
|
48
|
+
if (sessionId !== this.openSession)
|
|
49
|
+
this.open(sessionId);
|
|
50
|
+
this.forced = true;
|
|
51
|
+
}
|
|
52
|
+
evaluate(config) {
|
|
53
|
+
if (!this.openSession)
|
|
54
|
+
return { kind: 'wait' };
|
|
55
|
+
// A kill switch outranks everything, including a forced session: consent
|
|
56
|
+
// withdrawn or replay disabled means stop, whatever just happened.
|
|
57
|
+
if (config.configVersion > 0 && (!config.enabled || !config.replayEnabled)) {
|
|
58
|
+
return { kind: 'off' };
|
|
59
|
+
}
|
|
60
|
+
if (this.forced)
|
|
61
|
+
return { kind: 'record', sessionId: this.openSession };
|
|
62
|
+
if (config.configVersion === 0)
|
|
63
|
+
return { kind: 'wait' };
|
|
64
|
+
if (this.decidedFor !== this.openSession) {
|
|
65
|
+
this.decidedFor = this.openSession;
|
|
66
|
+
this.rate = config.replaySampleRate;
|
|
67
|
+
}
|
|
68
|
+
return this.sampled(this.openSession, this.rate)
|
|
69
|
+
? { kind: 'record', sessionId: this.openSession }
|
|
70
|
+
: { kind: 'skip' };
|
|
71
|
+
}
|
|
72
|
+
reset() {
|
|
73
|
+
this.openSession = null;
|
|
74
|
+
this.decidedFor = null;
|
|
75
|
+
this.rate = 0;
|
|
76
|
+
this.forced = false;
|
|
77
|
+
}
|
|
78
|
+
}
|
package/dist/safe.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crash isolation.
|
|
3
|
+
*
|
|
4
|
+
* This SDK runs inside other people's production apps. A defect here does not
|
|
5
|
+
* degrade a dashboard — it breaks someone's business, and they cannot ship a
|
|
6
|
+
* fix until their next app store release.
|
|
7
|
+
*
|
|
8
|
+
* So every public entry point and every listener callback goes through here.
|
|
9
|
+
* Telemetry that throws into a host render tree is worse than no telemetry.
|
|
10
|
+
*
|
|
11
|
+
* Exists in Phase 1 rather than Phase 2 because retrofitting it means finding
|
|
12
|
+
* every entry point again and missing one.
|
|
13
|
+
*/
|
|
14
|
+
/** True once the SDK has self-disabled after repeated internal errors. */
|
|
15
|
+
export declare function isSelfDisabled(): boolean;
|
|
16
|
+
/** Test-only reset. */
|
|
17
|
+
export declare function resetSafeState(): void;
|
|
18
|
+
/**
|
|
19
|
+
* Wrap a function so it can never throw into the host app.
|
|
20
|
+
*
|
|
21
|
+
* Returns `fallback` when the wrapped function throws or the SDK has
|
|
22
|
+
* self-disabled.
|
|
23
|
+
*/
|
|
24
|
+
export declare function safe<A extends unknown[], R>(fn: (...args: A) => R, fallback: R, label?: string): (...args: A) => R;
|
|
25
|
+
/** Async variant. A rejected promise escaping the SDK is just as damaging. */
|
|
26
|
+
export declare function safeAsync<A extends unknown[], R>(fn: (...args: A) => Promise<R>, fallback: R, label?: string): (...args: A) => Promise<R>;
|
package/dist/safe.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crash isolation.
|
|
3
|
+
*
|
|
4
|
+
* This SDK runs inside other people's production apps. A defect here does not
|
|
5
|
+
* degrade a dashboard — it breaks someone's business, and they cannot ship a
|
|
6
|
+
* fix until their next app store release.
|
|
7
|
+
*
|
|
8
|
+
* So every public entry point and every listener callback goes through here.
|
|
9
|
+
* Telemetry that throws into a host render tree is worse than no telemetry.
|
|
10
|
+
*
|
|
11
|
+
* Exists in Phase 1 rather than Phase 2 because retrofitting it means finding
|
|
12
|
+
* every entry point again and missing one.
|
|
13
|
+
*/
|
|
14
|
+
/** Consecutive internal failures before the SDK stops trying. */
|
|
15
|
+
const FAILURE_THRESHOLD = 5;
|
|
16
|
+
let consecutiveFailures = 0;
|
|
17
|
+
let disabled = false;
|
|
18
|
+
/** True once the SDK has self-disabled after repeated internal errors. */
|
|
19
|
+
export function isSelfDisabled() {
|
|
20
|
+
return disabled;
|
|
21
|
+
}
|
|
22
|
+
/** Test-only reset. */
|
|
23
|
+
export function resetSafeState() {
|
|
24
|
+
consecutiveFailures = 0;
|
|
25
|
+
disabled = false;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Wrap a function so it can never throw into the host app.
|
|
29
|
+
*
|
|
30
|
+
* Returns `fallback` when the wrapped function throws or the SDK has
|
|
31
|
+
* self-disabled.
|
|
32
|
+
*/
|
|
33
|
+
export function safe(fn, fallback, label = 'sdk') {
|
|
34
|
+
return (...args) => {
|
|
35
|
+
if (disabled)
|
|
36
|
+
return fallback;
|
|
37
|
+
try {
|
|
38
|
+
const result = fn(...args);
|
|
39
|
+
consecutiveFailures = 0;
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
recordFailure(label, err);
|
|
44
|
+
return fallback;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** Async variant. A rejected promise escaping the SDK is just as damaging. */
|
|
49
|
+
export function safeAsync(fn, fallback, label = 'sdk') {
|
|
50
|
+
return async (...args) => {
|
|
51
|
+
if (disabled)
|
|
52
|
+
return fallback;
|
|
53
|
+
try {
|
|
54
|
+
const result = await fn(...args);
|
|
55
|
+
consecutiveFailures = 0;
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
catch (err) {
|
|
59
|
+
recordFailure(label, err);
|
|
60
|
+
return fallback;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function recordFailure(label, err) {
|
|
65
|
+
consecutiveFailures += 1;
|
|
66
|
+
if (consecutiveFailures >= FAILURE_THRESHOLD) {
|
|
67
|
+
disabled = true;
|
|
68
|
+
// eslint-disable-next-line no-console
|
|
69
|
+
console.warn(`[session-capture] disabled after ${FAILURE_THRESHOLD} consecutive internal errors (${label})`, err);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
if (isDev()) {
|
|
73
|
+
// eslint-disable-next-line no-console
|
|
74
|
+
console.warn(`[session-capture] internal error in ${label}`, err);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* `__DEV__` is a React Native global. It does not exist in Node, in Jest
|
|
79
|
+
* without the RN preset, or in a web bundle — and referencing an undeclared
|
|
80
|
+
* identifier bare throws ReferenceError rather than yielding undefined.
|
|
81
|
+
*
|
|
82
|
+
* That matters more here than anywhere else in the SDK: this runs inside the
|
|
83
|
+
* failure handler, so a bare reference turns a caught error into an uncaught
|
|
84
|
+
* one and defeats the entire purpose of this module.
|
|
85
|
+
*/
|
|
86
|
+
function isDev() {
|
|
87
|
+
return typeof __DEV__ !== 'undefined' && __DEV__ === true;
|
|
88
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session lifecycle.
|
|
3
|
+
*
|
|
4
|
+
* A session is a run of activity with no gap longer than the timeout. The SDK
|
|
5
|
+
* owns this definition, and the backend's sweeper uses the same timeout to
|
|
6
|
+
* close sessions whose `session_end` never arrived — which is the common case
|
|
7
|
+
* on mobile, since apps get force-quit and OS-killed (section 20).
|
|
8
|
+
*/
|
|
9
|
+
export interface SessionState {
|
|
10
|
+
sessionId: string;
|
|
11
|
+
startedAt: number;
|
|
12
|
+
lastActivityAt: number;
|
|
13
|
+
/** Next sequence number to hand out. */
|
|
14
|
+
sequence: number;
|
|
15
|
+
/**
|
|
16
|
+
* Decided once, at session start. Never re-evaluated — a session that
|
|
17
|
+
* flipped mid-flight would produce a half-captured timeline, which looks
|
|
18
|
+
* complete and is silently wrong (section 35).
|
|
19
|
+
*/
|
|
20
|
+
sampled: boolean;
|
|
21
|
+
screen: string | null;
|
|
22
|
+
}
|
|
23
|
+
export interface SessionManagerOptions {
|
|
24
|
+
/** Idle bound: this long without activity ends the session. */
|
|
25
|
+
timeoutMs: number;
|
|
26
|
+
/**
|
|
27
|
+
* A session already in progress, resumed rather than started.
|
|
28
|
+
*
|
|
29
|
+
* For a platform where the JavaScript context dies while the session does
|
|
30
|
+
* not — a browser tab reloading. `onStart` deliberately does not fire for
|
|
31
|
+
* it: this session already announced itself, and a second `session_start`
|
|
32
|
+
* would give the backend a second device context for the same id.
|
|
33
|
+
*
|
|
34
|
+
* Restoring an expired one is harmless; the next `touch()` rotates it, the
|
|
35
|
+
* same as if it had never left memory.
|
|
36
|
+
*/
|
|
37
|
+
initial?: SessionState | null;
|
|
38
|
+
sampleRate: number;
|
|
39
|
+
now?: () => number;
|
|
40
|
+
/** Called once per session, as it begins. See `start()`. */
|
|
41
|
+
onStart?: (session: SessionState) => void;
|
|
42
|
+
/**
|
|
43
|
+
* Called with the outgoing session, just before it is replaced.
|
|
44
|
+
*
|
|
45
|
+
* Only on rotation — an app that simply stops has no chance to say
|
|
46
|
+
* anything, which is why the backend sweeper exists at all.
|
|
47
|
+
*/
|
|
48
|
+
onEnd?: (session: SessionState) => void;
|
|
49
|
+
}
|
|
50
|
+
export declare class SessionManager {
|
|
51
|
+
private state;
|
|
52
|
+
private options;
|
|
53
|
+
/** True only while `onEnd` runs. See `touch()`. */
|
|
54
|
+
private rotating;
|
|
55
|
+
private readonly now;
|
|
56
|
+
constructor(options: SessionManagerOptions);
|
|
57
|
+
current(): SessionState | null;
|
|
58
|
+
/**
|
|
59
|
+
* Register activity, starting or rotating the session as needed.
|
|
60
|
+
*
|
|
61
|
+
* Returns the session the caller should attribute its event to.
|
|
62
|
+
*/
|
|
63
|
+
touch(): SessionState;
|
|
64
|
+
/** Whether the current session is over after a period with no activity. */
|
|
65
|
+
private expired;
|
|
66
|
+
/**
|
|
67
|
+
* Take the next sequence number for a session already in hand.
|
|
68
|
+
*
|
|
69
|
+
* The caller has already decided which session this event belongs to —
|
|
70
|
+
* `touch()` for anything that keeps a session alive, `current()` for a
|
|
71
|
+
* goodbye. Taking the sequence must not make that decision a second time.
|
|
72
|
+
*/
|
|
73
|
+
takeSequence(session: SessionState): number;
|
|
74
|
+
setScreen(name: string): void;
|
|
75
|
+
/** Explicit end, e.g. on an intentional logout. */
|
|
76
|
+
end(): void;
|
|
77
|
+
/** Apply a new sample rate. Takes effect from the next session onward. */
|
|
78
|
+
setSampleRate(sampleRate: number): void;
|
|
79
|
+
private start;
|
|
80
|
+
}
|
package/dist/session.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session lifecycle.
|
|
3
|
+
*
|
|
4
|
+
* A session is a run of activity with no gap longer than the timeout. The SDK
|
|
5
|
+
* owns this definition, and the backend's sweeper uses the same timeout to
|
|
6
|
+
* close sessions whose `session_end` never arrived — which is the common case
|
|
7
|
+
* on mobile, since apps get force-quit and OS-killed (section 20).
|
|
8
|
+
*/
|
|
9
|
+
import { createId, isSampled } from "./ids.js";
|
|
10
|
+
export class SessionManager {
|
|
11
|
+
// Explicit fields rather than parameter properties: Node's strip-only
|
|
12
|
+
// TypeScript mode rejects the shorthand, and keeping these files runnable
|
|
13
|
+
// without a build step is worth more than the brevity.
|
|
14
|
+
constructor(options) {
|
|
15
|
+
this.state = null;
|
|
16
|
+
/** True only while `onEnd` runs. See `touch()`. */
|
|
17
|
+
this.rotating = false;
|
|
18
|
+
this.options = options;
|
|
19
|
+
this.now = options.now ?? Date.now;
|
|
20
|
+
this.state = options.initial ?? null;
|
|
21
|
+
}
|
|
22
|
+
current() {
|
|
23
|
+
return this.state;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Register activity, starting or rotating the session as needed.
|
|
27
|
+
*
|
|
28
|
+
* Returns the session the caller should attribute its event to.
|
|
29
|
+
*/
|
|
30
|
+
touch() {
|
|
31
|
+
const now = this.now();
|
|
32
|
+
// `rotating` holds the old session in place while `onEnd` runs. That
|
|
33
|
+
// callback captures `session_end`, which comes straight back through here
|
|
34
|
+
// — and without the guard it would find the session expired and rotate
|
|
35
|
+
// again, attributing the end of a session to its successor.
|
|
36
|
+
if (this.state && (this.rotating || !this.expired(now))) {
|
|
37
|
+
this.state.lastActivityAt = now;
|
|
38
|
+
return this.state;
|
|
39
|
+
}
|
|
40
|
+
const ending = this.state;
|
|
41
|
+
if (ending) {
|
|
42
|
+
this.rotating = true;
|
|
43
|
+
try {
|
|
44
|
+
this.options.onEnd?.(ending);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// A listener must not be able to strand the session it was told about.
|
|
48
|
+
}
|
|
49
|
+
finally {
|
|
50
|
+
this.rotating = false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return this.start(now);
|
|
54
|
+
}
|
|
55
|
+
/** Whether the current session is over after a period with no activity. */
|
|
56
|
+
expired(now) {
|
|
57
|
+
if (!this.state)
|
|
58
|
+
return true;
|
|
59
|
+
return now - this.state.lastActivityAt > this.options.timeoutMs;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Take the next sequence number for a session already in hand.
|
|
63
|
+
*
|
|
64
|
+
* The caller has already decided which session this event belongs to —
|
|
65
|
+
* `touch()` for anything that keeps a session alive, `current()` for a
|
|
66
|
+
* goodbye. Taking the sequence must not make that decision a second time.
|
|
67
|
+
*/
|
|
68
|
+
takeSequence(session) {
|
|
69
|
+
const sequence = session.sequence;
|
|
70
|
+
session.sequence += 1;
|
|
71
|
+
return sequence;
|
|
72
|
+
}
|
|
73
|
+
setScreen(name) {
|
|
74
|
+
this.touch().screen = name;
|
|
75
|
+
}
|
|
76
|
+
/** Explicit end, e.g. on an intentional logout. */
|
|
77
|
+
end() {
|
|
78
|
+
this.state = null;
|
|
79
|
+
}
|
|
80
|
+
/** Apply a new sample rate. Takes effect from the next session onward. */
|
|
81
|
+
setSampleRate(sampleRate) {
|
|
82
|
+
this.options = { ...this.options, sampleRate };
|
|
83
|
+
}
|
|
84
|
+
start(now) {
|
|
85
|
+
const sessionId = createId('sess');
|
|
86
|
+
this.state = {
|
|
87
|
+
sessionId,
|
|
88
|
+
startedAt: now,
|
|
89
|
+
lastActivityAt: now,
|
|
90
|
+
// Sequence restarts per session. Ordering is only ever meaningful
|
|
91
|
+
// within one session (section 14).
|
|
92
|
+
sequence: 0,
|
|
93
|
+
sampled: isSampled(sessionId, this.options.sampleRate),
|
|
94
|
+
screen: null,
|
|
95
|
+
};
|
|
96
|
+
// Announced from here rather than from the callers, because this is the
|
|
97
|
+
// only place a session id is ever minted — `touch()` rotates through it
|
|
98
|
+
// on timeout, so a hook anywhere else would miss the sessions that begin
|
|
99
|
+
// in the middle of a `capture()`.
|
|
100
|
+
//
|
|
101
|
+
// `this.state` is already set, so a listener that calls back into the SDK
|
|
102
|
+
// finds a live session and does not recurse into another rotation.
|
|
103
|
+
try {
|
|
104
|
+
this.options.onStart?.(this.state);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
// A listener is someone else's code. Capture continues regardless.
|
|
108
|
+
}
|
|
109
|
+
return this.state;
|
|
110
|
+
}
|
|
111
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable storage boundary.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately tiny — four operations. The queue is written against this, not
|
|
5
|
+
* against `expo-file-system`, so swapping API generations (or dropping to
|
|
6
|
+
* memory when persistence is unavailable) is a one-file change and the queue
|
|
7
|
+
* logic stays testable in Node.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Storage directories.
|
|
11
|
+
*
|
|
12
|
+
* Named here rather than in `store-expo.ts` because that module statically
|
|
13
|
+
* imports `expo-file-system`, which Node cannot load — anything importing it
|
|
14
|
+
* is device-only, tests included.
|
|
15
|
+
*
|
|
16
|
+
* The queue and the config cache must never share a directory:
|
|
17
|
+
* `SendQueue.peek()` treats every file it can see as a queued batch and
|
|
18
|
+
* deletes whatever fails to parse as one.
|
|
19
|
+
*/
|
|
20
|
+
export declare const QUEUE_DIR = "session-capture-queue";
|
|
21
|
+
export declare const CONFIG_DIR = "session-capture-config";
|
|
22
|
+
export interface FileStore {
|
|
23
|
+
/** Names of stored entries, oldest-sortable. */
|
|
24
|
+
list(): Promise<string[]>;
|
|
25
|
+
read(name: string): Promise<string | null>;
|
|
26
|
+
write(name: string, contents: string): Promise<void>;
|
|
27
|
+
remove(name: string): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* In-memory fallback.
|
|
31
|
+
*
|
|
32
|
+
* Used by tests, and on any platform where persistence is unavailable. Losing
|
|
33
|
+
* events on process death is bad; refusing to start is worse, so the SDK
|
|
34
|
+
* degrades rather than throwing (section 24).
|
|
35
|
+
*/
|
|
36
|
+
export declare class MemoryStore implements FileStore {
|
|
37
|
+
private readonly entries;
|
|
38
|
+
list(): Promise<string[]>;
|
|
39
|
+
read(name: string): Promise<string | null>;
|
|
40
|
+
write(name: string, contents: string): Promise<void>;
|
|
41
|
+
remove(name: string): Promise<void>;
|
|
42
|
+
/** Test helper. */
|
|
43
|
+
get size(): number;
|
|
44
|
+
}
|