@temps-sdk/analytics-core 0.0.6 → 0.0.7-beta.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,130 @@
1
+ import type { JsonValue } from "./types";
2
+ /** Why a flag has the value it has. Mirrors the server's reason. */
3
+ export interface FlagReason {
4
+ kind: "FLAG_NOT_FOUND" | "DISABLED" | "RULE_MATCH" | "PERCENTAGE_ROLLOUT" | "ENVIRONMENT_VALUE" | "DEFAULT" | "ERROR";
5
+ index?: number;
6
+ }
7
+ /** One flag as the server evaluated it for this visitor. */
8
+ export interface FlagEvaluation {
9
+ key: string;
10
+ value: unknown;
11
+ variant: string | null;
12
+ reason: FlagReason;
13
+ /** Whether reads of this flag should be recorded as exposures. */
14
+ record_exposure: boolean;
15
+ }
16
+ /** Targeting context sent with the request. */
17
+ export interface FlagContext {
18
+ /**
19
+ * Bucketing subject, e.g. a signed-in user id. Defaults, on the server, to
20
+ * the Temps visitor cookie.
21
+ */
22
+ key?: string;
23
+ /** Targeting attributes, e.g. `{ plan: "pro" }`. */
24
+ attributes?: Record<string, string | number | boolean>;
25
+ }
26
+ /** What a `flag_exposure` event carries. */
27
+ export interface FlagExposure {
28
+ flag_key: string;
29
+ variant: string;
30
+ reason: string;
31
+ }
32
+ export interface FeatureFlagsOptions extends FlagContext {
33
+ /** Where the Temps endpoints live. Defaults to `/api/_temps`. */
34
+ basePath?: string;
35
+ /**
36
+ * Values rendered on the server (e.g. from the Node SDK), served until the
37
+ * browser's own request completes, so the page never flashes the wrong
38
+ * variant.
39
+ */
40
+ bootstrap?: Record<string, unknown>;
41
+ /** Called on the first read of each exposure-recorded flag variant. */
42
+ onExposure?: (exposure: FlagExposure) => void;
43
+ /** Called when the flags request fails. Defaults to `console.warn`. */
44
+ onError?: (error: Error) => void;
45
+ /** Never fetch; serve bootstrap values and fallbacks only. */
46
+ disabled?: boolean;
47
+ /** Test seam. Defaults to the global `fetch`. */
48
+ fetch?: typeof fetch;
49
+ /** How long the flags request may take, body included. Defaults to 10 s;
50
+ * past it the request fails like any other (bootstrap values stay). */
51
+ timeoutMs?: number;
52
+ }
53
+ export type FlagsStatus = "idle" | "loading" | "ready" | "error";
54
+ export declare class FeatureFlags {
55
+ private readonly basePath;
56
+ private readonly onExposure?;
57
+ private readonly onError;
58
+ private readonly fetchImpl?;
59
+ private readonly timeoutMs;
60
+ private disabled;
61
+ private context;
62
+ private results;
63
+ private bootstrap;
64
+ private inflight;
65
+ private exposed;
66
+ private listeners;
67
+ private currentStatus;
68
+ private revision;
69
+ private generation;
70
+ constructor(options?: FeatureFlagsOptions);
71
+ /** `idle` until the first read, then `loading`, `ready` or `error`. */
72
+ get status(): FlagsStatus;
73
+ /** Changes whenever the served flags change. For `useSyncExternalStore`. */
74
+ get version(): number;
75
+ /**
76
+ * The value served for `key`, or `fallback` until flags arrive, when the
77
+ * flag does not exist (or is not client-visible), or when the served value
78
+ * is not of the fallback's type.
79
+ */
80
+ get<T>(key: string, fallback: T): T;
81
+ /**
82
+ * What `get` would return, without starting the request or recording an
83
+ * exposure. For render phases that must stay free of side effects; pair it
84
+ * with a `get` after commit.
85
+ */
86
+ peek<T>(key: string, fallback: T): T;
87
+ /** What `getVariant` would return, without side effects. */
88
+ peekVariant(key: string): string | null;
89
+ /** The variant served for `key`, or `null`. */
90
+ getVariant(key: string): string | null;
91
+ /**
92
+ * Replace the evaluation context (unlike `reload`, attributes are not
93
+ * merged). Re-fetches only if flags were already requested, so an unread
94
+ * client stays lazy.
95
+ */
96
+ setContext(context: FlagContext): void;
97
+ /**
98
+ * Turn fetching off or on. Disabling drops any request in flight; enabling
99
+ * fetches on the next read.
100
+ */
101
+ setDisabled(disabled: boolean): void;
102
+ /** The full evaluation for `key`, for debugging. Records no exposure. */
103
+ getEvaluation(key: string): FlagEvaluation | undefined;
104
+ /** Every served flag. Records no exposure. */
105
+ all(): FlagEvaluation[];
106
+ /** Resolves once the first request has finished (successfully or not). */
107
+ ready(): Promise<void>;
108
+ /**
109
+ * Re-evaluate with a new context, e.g. after sign-in. Merges `attributes`
110
+ * over the previous ones; pass `key` to change the bucketing subject.
111
+ */
112
+ reload(context?: FlagContext): Promise<void>;
113
+ subscribe(listener: () => void): () => void;
114
+ /**
115
+ * Values evaluated for another subject or other attributes must not be
116
+ * read under the new ones: after a sign-out they would be the previous
117
+ * user's, and would stay if the new request failed. A change therefore
118
+ * drops the results, the bootstrap values (rendered for the old context)
119
+ * and the exposures already recorded; an unchanged context keeps the last
120
+ * good values while it refreshes.
121
+ */
122
+ private replaceContext;
123
+ private ensureLoaded;
124
+ private load;
125
+ private notify;
126
+ private recordExposure;
127
+ }
128
+ /** Event data for a `flag_exposure` analytics event. */
129
+ export declare function exposureEventData(exposure: FlagExposure): Record<string, JsonValue>;
130
+ //# sourceMappingURL=FeatureFlags.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FeatureFlags.d.ts","sourceRoot":"","sources":["../src/FeatureFlags.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEzC,oEAAoE;AACpE,MAAM,WAAW,UAAU;IACzB,IAAI,EACA,gBAAgB,GAChB,UAAU,GACV,YAAY,GACZ,oBAAoB,GACpB,mBAAmB,GACnB,SAAS,GACT,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,4DAA4D;AAC5D,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,OAAO,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,UAAU,CAAC;IACnB,kEAAkE;IAClE,eAAe,EAAE,OAAO,CAAC;CAC1B;AAED,+CAA+C;AAC/C,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oDAAoD;IACpD,UAAU,CAAC,EAAE,MAAM,CA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wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAEnF"}
@@ -0,0 +1,271 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ /**
4
+ * Feature flags in the browser.
5
+ *
6
+ * Reads `client_visible` flags, already evaluated by the server, from the
7
+ * same-origin `POST {basePath}/flags` endpoint. The browser never sees rules,
8
+ * salts or server-only flags; it receives a value, a variant and a reason per
9
+ * flag, for the visitor making the request.
10
+ *
11
+ * - **Lazy**: nothing is fetched until the app first reads a flag (or calls
12
+ * `ready()` / `reload()`), so a site that never uses flags pays nothing.
13
+ * - **Synchronous reads**: `get()` returns the fallback until the flags have
14
+ * arrived, then the served value. Subscribe (`subscribe`, or the framework
15
+ * hooks) to re-render when they arrive.
16
+ * - **Never throws**: a failed request keeps the last good set (or the
17
+ * fallbacks) and is reported to `onError`.
18
+ * - **Exposure**: when the server marks a flag for exposure recording (opt-in
19
+ * per flag, sampled per visitor), the first read of each served variant on a
20
+ * page reports a `flag_exposure` event through `onExposure`.
21
+ */
22
+ import { postJson, REQUEST_TIMEOUT_MS } from "./request";
23
+ export class FeatureFlags {
24
+ constructor(options = {}) {
25
+ this.results = new Map();
26
+ this.inflight = null;
27
+ this.exposed = new Set();
28
+ this.listeners = new Set();
29
+ this.currentStatus = "idle";
30
+ this.revision = 0;
31
+ this.generation = 0;
32
+ this.basePath = options.basePath ?? "/api/_temps";
33
+ this.context = { key: options.key, attributes: options.attributes };
34
+ this.bootstrap = new Map(Object.entries(options.bootstrap ?? {}));
35
+ this.onExposure = options.onExposure;
36
+ this.onError =
37
+ options.onError ??
38
+ ((error) => {
39
+ // eslint-disable-next-line no-console
40
+ console.warn("[temps-flags] serving fallbacks:", error.message);
41
+ });
42
+ this.fetchImpl = options.fetch;
43
+ this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
44
+ this.disabled = options.disabled ?? false;
45
+ }
46
+ /** `idle` until the first read, then `loading`, `ready` or `error`. */
47
+ get status() {
48
+ return this.currentStatus;
49
+ }
50
+ /** Changes whenever the served flags change. For `useSyncExternalStore`. */
51
+ get version() {
52
+ return this.revision;
53
+ }
54
+ /**
55
+ * The value served for `key`, or `fallback` until flags arrive, when the
56
+ * flag does not exist (or is not client-visible), or when the served value
57
+ * is not of the fallback's type.
58
+ */
59
+ get(key, fallback) {
60
+ this.ensureLoaded();
61
+ const evaluation = this.results.get(key);
62
+ if (evaluation && compatible(evaluation.value, fallback))
63
+ this.recordExposure(evaluation);
64
+ return this.peek(key, fallback);
65
+ }
66
+ /**
67
+ * What `get` would return, without starting the request or recording an
68
+ * exposure. For render phases that must stay free of side effects; pair it
69
+ * with a `get` after commit.
70
+ */
71
+ peek(key, fallback) {
72
+ const evaluation = this.results.get(key);
73
+ if (!evaluation) {
74
+ return this.bootstrap.has(key) ? sameType(this.bootstrap.get(key), fallback) : fallback;
75
+ }
76
+ return sameType(evaluation.value, fallback);
77
+ }
78
+ /** What `getVariant` would return, without side effects. */
79
+ peekVariant(key) {
80
+ return this.results.get(key)?.variant ?? null;
81
+ }
82
+ /** The variant served for `key`, or `null`. */
83
+ getVariant(key) {
84
+ this.ensureLoaded();
85
+ const evaluation = this.results.get(key);
86
+ if (!evaluation)
87
+ return null;
88
+ this.recordExposure(evaluation);
89
+ return evaluation.variant;
90
+ }
91
+ /**
92
+ * Replace the evaluation context (unlike `reload`, attributes are not
93
+ * merged). Re-fetches only if flags were already requested, so an unread
94
+ * client stays lazy.
95
+ */
96
+ setContext(context) {
97
+ this.replaceContext({ key: context.key, attributes: context.attributes });
98
+ if (this.currentStatus !== "idle")
99
+ void this.load();
100
+ }
101
+ /**
102
+ * Turn fetching off or on. Disabling drops any request in flight; enabling
103
+ * fetches on the next read.
104
+ */
105
+ setDisabled(disabled) {
106
+ if (disabled === this.disabled)
107
+ return;
108
+ this.disabled = disabled;
109
+ if (disabled) {
110
+ // A disabled client serves bootstrap values and fallbacks only, so
111
+ // what an earlier request fetched is dropped too.
112
+ this.results = new Map();
113
+ this.generation += 1;
114
+ this.inflight = null;
115
+ if (this.currentStatus === "loading")
116
+ this.currentStatus = "idle";
117
+ }
118
+ else if (this.currentStatus !== "idle") {
119
+ void this.load();
120
+ return;
121
+ }
122
+ this.notify();
123
+ }
124
+ /** The full evaluation for `key`, for debugging. Records no exposure. */
125
+ getEvaluation(key) {
126
+ this.ensureLoaded();
127
+ return this.results.get(key);
128
+ }
129
+ /** Every served flag. Records no exposure. */
130
+ all() {
131
+ this.ensureLoaded();
132
+ return [...this.results.values()];
133
+ }
134
+ /** Resolves once the first request has finished (successfully or not). */
135
+ ready() {
136
+ this.ensureLoaded();
137
+ return this.inflight ?? Promise.resolve();
138
+ }
139
+ /**
140
+ * Re-evaluate with a new context, e.g. after sign-in. Merges `attributes`
141
+ * over the previous ones; pass `key` to change the bucketing subject.
142
+ */
143
+ reload(context = {}) {
144
+ this.replaceContext({
145
+ key: context.key ?? this.context.key,
146
+ attributes: { ...this.context.attributes, ...context.attributes },
147
+ });
148
+ return this.load();
149
+ }
150
+ subscribe(listener) {
151
+ this.listeners.add(listener);
152
+ return () => {
153
+ this.listeners.delete(listener);
154
+ };
155
+ }
156
+ /**
157
+ * Values evaluated for another subject or other attributes must not be
158
+ * read under the new ones: after a sign-out they would be the previous
159
+ * user's, and would stay if the new request failed. A change therefore
160
+ * drops the results, the bootstrap values (rendered for the old context)
161
+ * and the exposures already recorded; an unchanged context keeps the last
162
+ * good values while it refreshes.
163
+ */
164
+ replaceContext(next) {
165
+ const changed = contextKey(next) !== contextKey(this.context);
166
+ this.context = next;
167
+ if (!changed)
168
+ return;
169
+ this.results = new Map();
170
+ this.bootstrap.clear();
171
+ this.exposed.clear();
172
+ this.notify();
173
+ }
174
+ ensureLoaded() {
175
+ if (this.currentStatus === "idle")
176
+ void this.load();
177
+ }
178
+ load() {
179
+ if (this.disabled)
180
+ return Promise.resolve();
181
+ const fetchImpl = this.fetchImpl ?? (typeof fetch === "function" ? fetch : undefined);
182
+ if (!fetchImpl) {
183
+ this.currentStatus = "error";
184
+ return Promise.resolve();
185
+ }
186
+ // A newer request supersedes an older one: a reload after sign-in must
187
+ // not be overwritten by the anonymous request still in flight.
188
+ const generation = ++this.generation;
189
+ this.currentStatus = "loading";
190
+ // Subscribers re-render on `version`, so the loading state is visible.
191
+ // Deferred: a read during render can start this load, and notifying a
192
+ // store's subscribers synchronously from inside a render is not allowed.
193
+ void Promise.resolve().then(() => {
194
+ if (generation === this.generation && this.currentStatus === "loading")
195
+ this.notify();
196
+ });
197
+ const body = JSON.stringify({ key: this.context.key, attributes: this.context.attributes ?? {} });
198
+ const request = (async () => {
199
+ try {
200
+ const parsed = await postJson(fetchImpl, `${this.basePath}/flags`, body, this.timeoutMs);
201
+ if (generation !== this.generation)
202
+ return;
203
+ this.results = new Map((parsed.flags ?? []).map((flag) => [flag.key, flag]));
204
+ // The response is authoritative: a bootstrapped flag it omits was
205
+ // removed, archived or made server-only, so it now serves the
206
+ // fallback. A failed request keeps the bootstrap values.
207
+ this.bootstrap.clear();
208
+ this.currentStatus = "ready";
209
+ }
210
+ catch (error) {
211
+ if (generation !== this.generation)
212
+ return;
213
+ this.currentStatus = "error";
214
+ this.onError(error instanceof Error ? error : new Error(String(error)));
215
+ }
216
+ this.notify();
217
+ })();
218
+ this.inflight = request;
219
+ return request;
220
+ }
221
+ notify() {
222
+ this.revision += 1;
223
+ for (const listener of [...this.listeners]) {
224
+ try {
225
+ listener();
226
+ }
227
+ catch {
228
+ // A failing subscriber must not stop the others.
229
+ }
230
+ }
231
+ }
232
+ recordExposure(evaluation) {
233
+ if (!evaluation.record_exposure || !this.onExposure)
234
+ return;
235
+ const variant = evaluation.variant ?? "";
236
+ const marker = `${evaluation.key}\u0000${variant}`;
237
+ if (this.exposed.has(marker))
238
+ return;
239
+ this.exposed.add(marker);
240
+ try {
241
+ this.onExposure({ flag_key: evaluation.key, variant, reason: evaluation.reason.kind });
242
+ }
243
+ catch {
244
+ // Exposure reporting is best effort.
245
+ }
246
+ }
247
+ }
248
+ /** Serve `value` only if it has the fallback's shape, so a typed call site
249
+ * never receives a string where it expected a boolean. */
250
+ function sameType(value, fallback) {
251
+ return compatible(value, fallback) ? value : fallback;
252
+ }
253
+ /** Whether `value` can be served where `fallback`'s type is expected. */
254
+ function compatible(value, fallback) {
255
+ if (fallback === null || fallback === undefined)
256
+ return true;
257
+ if (value === null || value === undefined)
258
+ return false;
259
+ if (typeof value !== typeof fallback)
260
+ return false;
261
+ return Array.isArray(fallback) === Array.isArray(value);
262
+ }
263
+ /** Event data for a `flag_exposure` analytics event. */
264
+ export function exposureEventData(exposure) {
265
+ return { flag_key: exposure.flag_key, variant: exposure.variant, reason: exposure.reason };
266
+ }
267
+ /** A context as a value: attributes compared by content, not key order. */
268
+ function contextKey(context) {
269
+ const attributes = Object.entries(context.attributes ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
270
+ return JSON.stringify([context.key ?? null, attributes]);
271
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * `identify()` and `reset()` for the browser (ADR 109 D4).
3
+ *
4
+ * `identify` labels the visitor the request already resolves to: the
5
+ * proxy's `_temps_visitor_id` cookie on a site Temps serves, or the
6
+ * tracker's stored id on a keyed site. The browser never names any other
7
+ * visitor. In cookieless mode nothing is sent at all: a user id on a daily
8
+ * visitor would link its days together, which is what cookieless rules out.
9
+ */
10
+ import type { IdentifyResult, JsonValue } from "./types";
11
+ export declare const IDENTIFY_ENDPOINT = "identify";
12
+ export declare const RESET_ENDPOINT = "reset";
13
+ export interface IdentifyVisitorOptions {
14
+ basePath: string;
15
+ ingestKey?: string;
16
+ userId: string;
17
+ traits?: Record<string, JsonValue>;
18
+ /**
19
+ * Resolves once the page view that creates the visitor has been sent. A
20
+ * first visit's visitor only exists after its first event.
21
+ */
22
+ ready?: Promise<unknown>;
23
+ }
24
+ /** Thrown by `resetVisitor` when the server did not confirm the reset. */
25
+ export declare class ResetFailedError extends Error {
26
+ readonly cause?: unknown | undefined;
27
+ constructor(message: string, cause?: unknown | undefined);
28
+ }
29
+ /**
30
+ * Send `identify` for the current visitor. Resolves to the server's answer,
31
+ * or to a local one when nothing was sent (`cookieless_project`,
32
+ * `already_sent`, `invalid_user_id`, `network_error`, `reset`). Never
33
+ * throws.
34
+ */
35
+ export declare function identifyVisitor(options: IdentifyVisitorOptions): Promise<IdentifyResult>;
36
+ /**
37
+ * Forget who this browser belongs to, for a sign-out: deletes the stored
38
+ * visitor and session ids and the identify memo, and asks the server to
39
+ * expire its tracking cookies. The next event starts a new, anonymous
40
+ * visitor.
41
+ *
42
+ * Rejects with `ResetFailedError` when the server did not confirm the
43
+ * reset (offline, or an error status): on a site Temps serves, its tracking
44
+ * cookie still names the signed-out visitor until the reset reaches it, so
45
+ * the caller should retry. The local ids are cleared either way.
46
+ */
47
+ export declare function resetVisitor(options: {
48
+ basePath: string;
49
+ ingestKey?: string;
50
+ }): Promise<void>;
51
+ //# sourceMappingURL=Identify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Identify.d.ts","sourceRoot":"","sources":["../src/Identify.ts"],"names":[],"mappings":"AAGA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAOzD,eAAO,MAAM,iBAAiB,aAAa,CAAC;AAC5C,eAAO,MAAM,cAAc,UAAU,CAAC;AAKtC,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;IACnC;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;CAC1B;AASD,0EAA0E;AAC1E,qBAAa,gBAAiB,SAAQ,KAAK;IACZ,QAAQ,CAAC,KAAK,CAAC,EAAE,OAAO;gBAAzC,OAAO,EAAE,MAAM,EAAW,KAAK,CAAC,EAAE,OAAO,YAAA;CAItD;AAwBD;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,OAAO,CAAC,cAAc,CAAC,CA2D9F;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,YAAY,CAAC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CA0BnG"}
@@ -0,0 +1,154 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ import { ingestKeyHeaders } from "./utils";
4
+ import { clearStoredIdentity, getOrCreateVisitorId, isCookielessIdentity, notifyIdentityReset } from "./identity";
5
+ /** Remembers the last identify that was applied, so repeats are not resent. */
6
+ const IDENTIFIED_KEY = "temps_identified";
7
+ export const IDENTIFY_ENDPOINT = "identify";
8
+ export const RESET_ENDPOINT = "reset";
9
+ /** Server outcomes that mean the label is on the visitor now. */
10
+ const APPLIED_OUTCOMES = new Set(["updated", "unchanged"]);
11
+ /**
12
+ * Bumped by every `reset()`. An identify that was waiting for its page view
13
+ * when the visitor reset belongs to the signed-out user: it must not label
14
+ * the next visitor, nor restore the memo the reset cleared.
15
+ */
16
+ let identityGeneration = 0;
17
+ /** Thrown by `resetVisitor` when the server did not confirm the reset. */
18
+ export class ResetFailedError extends Error {
19
+ constructor(message, cause) {
20
+ super(message);
21
+ this.cause = cause;
22
+ this.name = "ResetFailedError";
23
+ }
24
+ }
25
+ function memoFor(userId, traits) {
26
+ return JSON.stringify([userId, traits ?? null]);
27
+ }
28
+ function readMemo() {
29
+ try {
30
+ return typeof localStorage === "undefined" ? null : localStorage.getItem(IDENTIFIED_KEY);
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ function writeMemo(value) {
37
+ try {
38
+ if (typeof localStorage === "undefined")
39
+ return;
40
+ if (value === null)
41
+ localStorage.removeItem(IDENTIFIED_KEY);
42
+ else
43
+ localStorage.setItem(IDENTIFIED_KEY, value);
44
+ }
45
+ catch {
46
+ // Storage unusable: the next identify is sent again, which is harmless.
47
+ }
48
+ }
49
+ /**
50
+ * Send `identify` for the current visitor. Resolves to the server's answer,
51
+ * or to a local one when nothing was sent (`cookieless_project`,
52
+ * `already_sent`, `invalid_user_id`, `network_error`, `reset`). Never
53
+ * throws.
54
+ */
55
+ export async function identifyVisitor(options) {
56
+ const { basePath, ingestKey, userId, traits, ready } = options;
57
+ if (isCookielessIdentity()) {
58
+ return {
59
+ applied: false,
60
+ outcome: "cookieless_project",
61
+ message: "Identify stores nothing in cookieless mode.",
62
+ };
63
+ }
64
+ if (typeof userId !== "string" || userId.trim() === "") {
65
+ return { applied: false, outcome: "invalid_user_id", message: "identify() needs a non-empty user id." };
66
+ }
67
+ const memo = memoFor(userId, traits);
68
+ if (readMemo() === memo) {
69
+ return { applied: true, outcome: "already_sent", message: "This visitor already has this identity." };
70
+ }
71
+ const generation = identityGeneration;
72
+ try {
73
+ await ready;
74
+ }
75
+ catch {
76
+ // A failed page view does not stop identify; the server says if the
77
+ // visitor is missing.
78
+ }
79
+ // Rechecked after the wait: the page may have signed out or switched to
80
+ // cookieless mode meanwhile.
81
+ if (generation !== identityGeneration) {
82
+ return {
83
+ applied: false,
84
+ outcome: "reset",
85
+ message: "reset() ran while identify was waiting; nothing was sent.",
86
+ };
87
+ }
88
+ if (isCookielessIdentity()) {
89
+ return {
90
+ applied: false,
91
+ outcome: "cookieless_project",
92
+ message: "Identify stores nothing in cookieless mode.",
93
+ };
94
+ }
95
+ try {
96
+ const response = await fetch(`${basePath}/${IDENTIFY_ENDPOINT}`, {
97
+ method: "POST",
98
+ headers: { "Content-Type": "application/json", ...ingestKeyHeaders(ingestKey) },
99
+ body: JSON.stringify({ user_id: userId, traits, visitor_id: getOrCreateVisitorId() }),
100
+ });
101
+ const body = (await response.json().catch(() => null));
102
+ const result = {
103
+ applied: Boolean(body?.applied),
104
+ outcome: typeof body?.outcome === "string" ? body.outcome : `http_${response.status}`,
105
+ message: typeof body?.message === "string" ? body.message : response.statusText,
106
+ };
107
+ const stillCurrent = generation === identityGeneration && !isCookielessIdentity();
108
+ if (response.ok && APPLIED_OUTCOMES.has(result.outcome) && stillCurrent)
109
+ writeMemo(memo);
110
+ return result;
111
+ }
112
+ catch (error) {
113
+ // eslint-disable-next-line no-console
114
+ console.error("Failed to send identify:", error);
115
+ return { applied: false, outcome: "network_error", message: String(error) };
116
+ }
117
+ }
118
+ /**
119
+ * Forget who this browser belongs to, for a sign-out: deletes the stored
120
+ * visitor and session ids and the identify memo, and asks the server to
121
+ * expire its tracking cookies. The next event starts a new, anonymous
122
+ * visitor.
123
+ *
124
+ * Rejects with `ResetFailedError` when the server did not confirm the
125
+ * reset (offline, or an error status): on a site Temps serves, its tracking
126
+ * cookie still names the signed-out visitor until the reset reaches it, so
127
+ * the caller should retry. The local ids are cleared either way.
128
+ */
129
+ export async function resetVisitor(options) {
130
+ identityGeneration += 1;
131
+ writeMemo(null);
132
+ clearStoredIdentity();
133
+ // A replay in progress belongs to the previous visitor; end it now. The
134
+ // next one starts once the server has expired the cookie naming it.
135
+ notifyIdentityReset("started");
136
+ if (isCookielessIdentity()) {
137
+ notifyIdentityReset("confirmed");
138
+ return;
139
+ }
140
+ let response;
141
+ try {
142
+ response = await fetch(`${options.basePath}/${RESET_ENDPOINT}`, {
143
+ method: "POST",
144
+ headers: ingestKeyHeaders(options.ingestKey),
145
+ });
146
+ }
147
+ catch (error) {
148
+ throw new ResetFailedError(`Could not reach ${options.basePath}/${RESET_ENDPOINT} to reset the visitor`, error);
149
+ }
150
+ if (!response.ok) {
151
+ throw new ResetFailedError(`${options.basePath}/${RESET_ENDPOINT} answered ${response.status}; the visitor was not reset on the server`);
152
+ }
153
+ notifyIdentityReset("confirmed");
154
+ }
@@ -77,6 +77,8 @@ export declare class SessionRecorder {
77
77
  private paused;
78
78
  private lastActivityAt;
79
79
  private droppedEvents;
80
+ /** Set by `endForReset()` when it stopped a recording. */
81
+ private resumeAfterResetPending;
80
82
  /**
81
83
  * Sampling verdict for this recorder, decided once. Re-rolling per call (the
82
84
  * previous behaviour) let a recorded session flip itself off on any later
@@ -114,7 +116,13 @@ export declare class SessionRecorder {
114
116
  private startIdleTimer;
115
117
  private stopIdleTimer;
116
118
  private startRecording;
117
- /** Forget the server session and any client state pointing at it. */
119
+ /**
120
+ * Forget the server session and any client state pointing at it, including
121
+ * events not delivered yet: they belong to that session, and a later one
122
+ * must never send them under its own id (another visitor's replay after a
123
+ * `reset()`). The final upload `stopRecording` starts has already built its
124
+ * payload with the old id, so it still reaches the old replay.
125
+ */
118
126
  private clearSession;
119
127
  private detachRecorder;
120
128
  /**
@@ -134,8 +142,32 @@ export declare class SessionRecorder {
134
142
  private handlePopState;
135
143
  private checkPath;
136
144
  start(): void;
145
+ /**
146
+ * Stop recording at the app's request (an opt-out, an unmount, a destroy).
147
+ * This also cancels the new replay a pending `reset()` would start, so a
148
+ * visitor who withdraws consent while the reset waits for the server is
149
+ * not recorded again once it succeeds.
150
+ */
137
151
  stop(): void;
152
+ private halt;
138
153
  destroy(): void;
154
+ /**
155
+ * Stop for good and drop every event not uploaded yet, without sending a
156
+ * final batch: the page switched to cookieless mode, which keeps no replay.
157
+ */
158
+ discard(): void;
159
+ /**
160
+ * `reset()` started (a sign-out): end the current replay, sending what it
161
+ * has to that replay, and remember whether recording was on so
162
+ * `resumeAfterReset()` can start a new one.
163
+ */
164
+ endForReset(): void;
165
+ /**
166
+ * The server confirmed the reset: start a new session if `endForReset()`
167
+ * stopped a recording. Until then nothing is recorded, so activity after a
168
+ * sign-out never joins the previous visitor's replay.
169
+ */
170
+ resumeAfterReset(): void;
139
171
  getSessionId(): string | null;
140
172
  /** Events discarded because the buffer hit `maxBufferedEvents`. */
141
173
  getDroppedEventCount(): number;