@depsmith/depsmith-sdk 0.0.0-stage → 0.6.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/README.md +56 -2
- package/dist/autocapture.js +2 -0
- package/dist/autocapture.js.map +1 -0
- package/dist/depsmith-sdk.global.js +2 -0
- package/dist/depsmith-sdk.global.js.map +1 -0
- package/dist/depsmith-sdk.pixel.global.js +10 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +560 -0
- package/dist/index.d.ts +560 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +72 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* User-property operators (API_SPEC §14).
|
|
3
|
+
*
|
|
4
|
+
* The operators exist because applying them on a client is wrong, not merely inconvenient:
|
|
5
|
+
* `$add` on a device is a read-modify-write race between tabs, and `$append` cannot converge
|
|
6
|
+
* at all. So the SDK's job is to *describe* the change and let the collector apply it.
|
|
7
|
+
*
|
|
8
|
+
* Two invariants are the client's responsibility, and both are here rather than in the
|
|
9
|
+
* collector — the schema's own comment explains why: they are what keep the collector free
|
|
10
|
+
* of operator algebra.
|
|
11
|
+
*
|
|
12
|
+
* 1. A key appears under AT MOST ONE operator per event. Without it, `$set` then `$add` on
|
|
13
|
+
* one key is only resolvable by assuming the value is numeric.
|
|
14
|
+
* 2. `$clear_all` is exclusive. Combining it with anything else makes the result depend on
|
|
15
|
+
* ordering that is otherwise unobservable.
|
|
16
|
+
*
|
|
17
|
+
* Both are enforced by dropping the offending entry with a debug warning, never by throwing:
|
|
18
|
+
* the public API is fire-and-forget and must not break a host page over a analytics call.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The closed operator set, exactly as `event.schema.json` `$defs.userPropertyOps` declares it.
|
|
23
|
+
* Closed on purpose: level 2 is a fixed 10-member enum the collector knows at compile time,
|
|
24
|
+
* which is what lets `user_properties.$add.orders` flatten deterministically into a warehouse
|
|
25
|
+
* column despite being three levels from the root.
|
|
26
|
+
*/
|
|
27
|
+
interface UserPropertyOps {
|
|
28
|
+
$set?: Properties;
|
|
29
|
+
$set_once?: Properties;
|
|
30
|
+
$append?: Properties;
|
|
31
|
+
$prepend?: Properties;
|
|
32
|
+
$pre_insert?: Properties;
|
|
33
|
+
$post_insert?: Properties;
|
|
34
|
+
$remove?: Properties;
|
|
35
|
+
/** Numeric increments. Absent counts as 0; negative is allowed. */
|
|
36
|
+
$add?: Record<string, number>;
|
|
37
|
+
$unset?: string[];
|
|
38
|
+
/** Deletes every user property for this identity. Exclusive. */
|
|
39
|
+
$clear_all?: true;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Canonical types mirroring spec/schema/event.schema.json. */
|
|
43
|
+
|
|
44
|
+
type Scalar = string | number | boolean | null;
|
|
45
|
+
type PropertyValue = Scalar | Scalar[] | Record<string, Scalar>;
|
|
46
|
+
type Properties = Record<string, PropertyValue>;
|
|
47
|
+
type EventType = 'track' | 'page_view' | 'screen' | 'identify' | 'alias' | 'group' | 'autocapture' | 'session_start' | 'session_end';
|
|
48
|
+
type NetworkType = '2g' | '3g' | '4g' | '5g' | 'wifi' | 'ethernet' | 'none' | 'unknown';
|
|
49
|
+
interface EventContext {
|
|
50
|
+
library: {
|
|
51
|
+
name: string;
|
|
52
|
+
version: string;
|
|
53
|
+
};
|
|
54
|
+
page?: {
|
|
55
|
+
url?: string;
|
|
56
|
+
referrer?: string;
|
|
57
|
+
title?: string;
|
|
58
|
+
path?: string;
|
|
59
|
+
};
|
|
60
|
+
screen?: {
|
|
61
|
+
width?: number;
|
|
62
|
+
height?: number;
|
|
63
|
+
density?: number;
|
|
64
|
+
};
|
|
65
|
+
browser?: {
|
|
66
|
+
name?: string;
|
|
67
|
+
version?: string;
|
|
68
|
+
engine?: string;
|
|
69
|
+
};
|
|
70
|
+
/** No `id` — the device fingerprint is the top-level `DepsmithSdkEvent.device_id`. */
|
|
71
|
+
device?: {
|
|
72
|
+
manufacturer?: string;
|
|
73
|
+
model?: string;
|
|
74
|
+
type?: string;
|
|
75
|
+
};
|
|
76
|
+
os?: {
|
|
77
|
+
name?: string;
|
|
78
|
+
version?: string;
|
|
79
|
+
};
|
|
80
|
+
network?: {
|
|
81
|
+
wifi?: boolean;
|
|
82
|
+
cellular?: boolean;
|
|
83
|
+
type?: NetworkType;
|
|
84
|
+
carrier?: string;
|
|
85
|
+
isp?: string;
|
|
86
|
+
vpn?: boolean;
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Coordinates may come from the device (`geolocation: true`, permission already granted);
|
|
90
|
+
* city/region/country are always server-enriched from the request IP. `source` records
|
|
91
|
+
* where the coordinates came from.
|
|
92
|
+
*/
|
|
93
|
+
location?: {
|
|
94
|
+
latitude?: number;
|
|
95
|
+
longitude?: number;
|
|
96
|
+
accuracy?: number;
|
|
97
|
+
source?: 'gps' | 'ip';
|
|
98
|
+
city?: string;
|
|
99
|
+
region?: string;
|
|
100
|
+
country?: string;
|
|
101
|
+
};
|
|
102
|
+
locale?: string;
|
|
103
|
+
timezone?: string;
|
|
104
|
+
user_agent?: string;
|
|
105
|
+
traits?: Properties;
|
|
106
|
+
}
|
|
107
|
+
interface DepsmithSdkEvent {
|
|
108
|
+
event_id: string;
|
|
109
|
+
event: string;
|
|
110
|
+
event_type: EventType;
|
|
111
|
+
properties?: Properties;
|
|
112
|
+
timestamp: string;
|
|
113
|
+
session_id: string;
|
|
114
|
+
/** When the event's session began. Lets session length be computed per row. */
|
|
115
|
+
session_started_at?: string;
|
|
116
|
+
user_id?: string | null;
|
|
117
|
+
anonymous_id: string;
|
|
118
|
+
group_id?: string | null;
|
|
119
|
+
/**
|
|
120
|
+
* Device fingerprint — the third column identity resolution joins on, after `user_id` and
|
|
121
|
+
* `anonymous_id`, and the recovery path when `anonymous_id` has been cleared.
|
|
122
|
+
*
|
|
123
|
+
* Absent (never empty) unless `deviceFingerprinting` is on, `childSafeMode` is off and
|
|
124
|
+
* consent is granted — the same gate that populates the rest of the fingerprint context.
|
|
125
|
+
*/
|
|
126
|
+
device_id?: string;
|
|
127
|
+
context: EventContext;
|
|
128
|
+
/**
|
|
129
|
+
* Server-applied user-property operators (API_SPEC §14). Present only on the events that
|
|
130
|
+
* carry a change; applied against `user_id` when set, else `anonymous_id`.
|
|
131
|
+
*/
|
|
132
|
+
user_properties?: UserPropertyOps;
|
|
133
|
+
platform: 'web';
|
|
134
|
+
sdk_version: string;
|
|
135
|
+
}
|
|
136
|
+
interface BatchPayload {
|
|
137
|
+
batch: DepsmithSdkEvent[];
|
|
138
|
+
api_key: string;
|
|
139
|
+
source: 'sdk';
|
|
140
|
+
sent_at: string;
|
|
141
|
+
anonymize_ip?: boolean;
|
|
142
|
+
}
|
|
143
|
+
type ConsentState = 'pending' | 'granted' | 'denied';
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Per-field suppression of context signals (API_SPEC §12.2).
|
|
147
|
+
*
|
|
148
|
+
* Every key defaults true (collected). This filter is SUBTRACTIVE ONLY — leaving an option
|
|
149
|
+
* true never re-enables a field that `deviceFingerprinting`, `childSafeMode` or consent
|
|
150
|
+
* already suppressed, so the controls compose by intersection and no context field ends up
|
|
151
|
+
* with two sources of truth.
|
|
152
|
+
*/
|
|
153
|
+
interface TrackingOptions {
|
|
154
|
+
/** context.app. Mobile only — web has no app-version concept. */
|
|
155
|
+
appVersion?: boolean;
|
|
156
|
+
/** context.browser. Populated only when deviceFingerprinting is on. */
|
|
157
|
+
browser?: boolean;
|
|
158
|
+
/** context.network.carrier. Implied by `network: false`. */
|
|
159
|
+
carrier?: boolean;
|
|
160
|
+
deviceManufacturer?: boolean;
|
|
161
|
+
deviceModel?: boolean;
|
|
162
|
+
deviceType?: boolean;
|
|
163
|
+
/** context.locale. */
|
|
164
|
+
language?: boolean;
|
|
165
|
+
/** context.network in full. Subsumes carrier. */
|
|
166
|
+
network?: boolean;
|
|
167
|
+
osName?: boolean;
|
|
168
|
+
osVersion?: boolean;
|
|
169
|
+
/** context.page. Not the `name` property on $page_view — that is a property, not context. */
|
|
170
|
+
page?: boolean;
|
|
171
|
+
screen?: boolean;
|
|
172
|
+
timezone?: boolean;
|
|
173
|
+
/** context.user_agent. */
|
|
174
|
+
userAgent?: boolean;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Public config — keys mirror spec/schema/config.schema.json. */
|
|
178
|
+
interface DepsmithSdkConfig {
|
|
179
|
+
apiKey: string;
|
|
180
|
+
endpoint: string;
|
|
181
|
+
batchSize?: number;
|
|
182
|
+
batchIntervalMs?: number;
|
|
183
|
+
maxQueueSize?: number;
|
|
184
|
+
/**
|
|
185
|
+
* Ceiling on the serialised queue, in UTF-16 code units — the unit browsers meter
|
|
186
|
+
* storage quota in. Bounds the bytes DepsmithSdk occupies in an origin-shared `localStorage`,
|
|
187
|
+
* which `maxQueueSize` (a count) cannot. Oldest events are dropped first. Web only.
|
|
188
|
+
*/
|
|
189
|
+
maxQueueBytes?: number;
|
|
190
|
+
sessionTimeoutMs?: number;
|
|
191
|
+
/** Fraction of SESSIONS captured, 0..1. Default 1. Session-sticky; see config.schema.json. */
|
|
192
|
+
sampleRate?: number;
|
|
193
|
+
/** Emit $session_start/$session_end as events, or leave them derivable server-side. Default 'emit'. */
|
|
194
|
+
sessionEvents?: 'emit' | 'derive';
|
|
195
|
+
consentMode?: 'granted' | 'pending';
|
|
196
|
+
respectDnt?: boolean;
|
|
197
|
+
maxRetries?: number;
|
|
198
|
+
debug?: boolean;
|
|
199
|
+
autocapture?: boolean | AutocaptureConfig;
|
|
200
|
+
defaultProperties?: Properties;
|
|
201
|
+
/** Batch upload compression. gzip when CompressionStream exists, transparent fallback otherwise. */
|
|
202
|
+
compression?: 'gzip' | 'none';
|
|
203
|
+
/** COPPA: memory-only identity, identify()/alias() disabled, anonymizeIp forced on. */
|
|
204
|
+
childSafeMode?: boolean;
|
|
205
|
+
/** Ask the server to strip the last IP octet (anonymize_ip on every batch). */
|
|
206
|
+
anonymizeIp?: boolean;
|
|
207
|
+
/** Device fingerprinting (browser/os/device.id/network). **Default true** — opt-OUT, unlike `geolocation`. Suppressed under DNT/childSafeMode/pending consent. */
|
|
208
|
+
deviceFingerprinting?: boolean;
|
|
209
|
+
/**
|
|
210
|
+
* Opt-in device position on context.location (latitude/longitude/accuracy). Never prompts:
|
|
211
|
+
* read only when the site already holds the geolocation permission. City/region/country
|
|
212
|
+
* remain server-resolved from the request IP. Suppressed under DNT/childSafeMode/pending
|
|
213
|
+
* consent, like deviceFingerprinting. Default false.
|
|
214
|
+
*/
|
|
215
|
+
geolocation?: boolean;
|
|
216
|
+
/** Per-field context suppression, all keys default true. Subtractive only; see API_SPEC §12.2. */
|
|
217
|
+
trackingOptions?: TrackingOptions;
|
|
218
|
+
/** Persist identity keys in a cookie scoped to this domain (cross-subdomain identity). */
|
|
219
|
+
cookieDomain?: string;
|
|
220
|
+
/** Queue persistence backend. */
|
|
221
|
+
storage?: 'localstorage' | 'indexeddb' | 'memory';
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Which clicks produce a `$autocapture` event.
|
|
225
|
+
* 'interactive' — only clicks resolving to a link/button/[role=button]/submit control
|
|
226
|
+
* or an explicit [data-depsmith-sdk-capture]. The default.
|
|
227
|
+
* 'all' — every click anywhere on the page, including layout containers.
|
|
228
|
+
* true — alias of 'interactive'; false disables click capture.
|
|
229
|
+
*/
|
|
230
|
+
type ClickCapture = boolean | 'interactive' | 'all';
|
|
231
|
+
interface AutocaptureConfig {
|
|
232
|
+
clicks?: ClickCapture;
|
|
233
|
+
forms?: boolean;
|
|
234
|
+
scrolls?: boolean;
|
|
235
|
+
pageviews?: boolean;
|
|
236
|
+
ignoredSelectors?: string[];
|
|
237
|
+
selectorMaxDepth?: number;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Key-value storage abstraction. localStorage when available (synchronous — safe to
|
|
242
|
+
* write during pagehide), in-memory fallback for SSR / privacy modes that block storage.
|
|
243
|
+
*/
|
|
244
|
+
interface KVStorage {
|
|
245
|
+
get(key: string): string | null;
|
|
246
|
+
set(key: string, value: string): void;
|
|
247
|
+
remove(key: string): void;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Every key DepsmithSdk persists. Single source of truth for hosts that must enumerate
|
|
251
|
+
* them up front — e.g. `AsyncMirrorAdapter`, whose backend has no bulk read.
|
|
252
|
+
* Kept in sync with the `KEY_*` consts in identity/session/consent/queue/depsmith-sdk/breaker.
|
|
253
|
+
*/
|
|
254
|
+
declare const DEPSMITH_SDK_STORAGE_KEYS: readonly ["depsmith_anonymous_id", "depsmith_user_id", "depsmith_group_id", "depsmith_user_props", "depsmith_session", "depsmith_consent", "depsmith_queue", "depsmith_config_fp", "depsmith_net_breaker"];
|
|
255
|
+
/**
|
|
256
|
+
* Minimal async key-value backend. Shaped to accept Shopify's `browser.localStorage`
|
|
257
|
+
* / `browser.sessionStorage` directly (all methods Promise-returning, proxied to the
|
|
258
|
+
* top frame from the web-pixel sandbox).
|
|
259
|
+
*/
|
|
260
|
+
interface AsyncKV {
|
|
261
|
+
getItem(key: string): Promise<string | null | undefined>;
|
|
262
|
+
setItem(key: string, value: string): Promise<unknown>;
|
|
263
|
+
removeItem(key: string): Promise<unknown>;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* Synchronous `KVStorage` over an asynchronous backend: an in-memory mirror serves
|
|
267
|
+
* reads, writes go through to the mirror and are flushed write-behind.
|
|
268
|
+
*
|
|
269
|
+
* `hydrate()` must be awaited **before** constructing a DepsmithSdkClient over this
|
|
270
|
+
* adapter — IdentityManager/SessionManager/EventQueue all read in their constructors,
|
|
271
|
+
* and a cold mirror would mint a fresh anonymousId over a returning visitor's.
|
|
272
|
+
*/
|
|
273
|
+
declare class AsyncMirrorAdapter implements KVStorage {
|
|
274
|
+
private backend;
|
|
275
|
+
private keys;
|
|
276
|
+
private mirror;
|
|
277
|
+
private hydrated;
|
|
278
|
+
constructor(backend: AsyncKV, keys?: readonly string[]);
|
|
279
|
+
/** Bulk-loads `keys` into the mirror. Idempotent; never rejects. */
|
|
280
|
+
hydrate(): Promise<void>;
|
|
281
|
+
get(key: string): string | null;
|
|
282
|
+
set(key: string, value: string): void;
|
|
283
|
+
remove(key: string): void;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Injectable time source — the conformance runner substitutes a controllable clock. */
|
|
287
|
+
interface Clock {
|
|
288
|
+
now(): number;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Deferred work scheduling.
|
|
293
|
+
*
|
|
294
|
+
* Exists so persistence can be moved off the capture task. Writing to `localStorage` is
|
|
295
|
+
* synchronous and blocks the main thread; doing it inside a click handler is what put
|
|
296
|
+
* DepsmithSdk on the critical path of every shopper interaction. Coalescing those writes onto
|
|
297
|
+
* an idle callback keeps the interaction cheap and collapses a burst of events into a
|
|
298
|
+
* single write.
|
|
299
|
+
*/
|
|
300
|
+
type Scheduler = (fn: () => void) => void;
|
|
301
|
+
/**
|
|
302
|
+
* Runs `fn` at the next idle moment, or within {@link IDLE_TIMEOUT_MS} at the latest.
|
|
303
|
+
*
|
|
304
|
+
* Falls back to a macrotask where `requestIdleCallback` is absent — Safari below 16.4 and
|
|
305
|
+
* jsdom. The fallback is still correct, just less considerate about when it lands.
|
|
306
|
+
*/
|
|
307
|
+
declare const idleScheduler: Scheduler;
|
|
308
|
+
/**
|
|
309
|
+
* Runs `fn` immediately, restoring write-through behaviour.
|
|
310
|
+
*
|
|
311
|
+
* The seam tests use to assert persisted state without pumping timers, and the escape
|
|
312
|
+
* hatch for any host that needs durability over latency.
|
|
313
|
+
*/
|
|
314
|
+
declare const syncScheduler: Scheduler;
|
|
315
|
+
|
|
316
|
+
/** Test/conformance seams. Not part of the public API contract. */
|
|
317
|
+
interface InternalOverrides {
|
|
318
|
+
storage?: KVStorage;
|
|
319
|
+
clock?: Clock;
|
|
320
|
+
fetchFn?: typeof fetch;
|
|
321
|
+
isOnline?: () => boolean;
|
|
322
|
+
sleep?: (ms: number) => Promise<void>;
|
|
323
|
+
dnt?: boolean;
|
|
324
|
+
/** Per-attempt upload timeout. Test seam so a hung-request test needn't wait 30s. */
|
|
325
|
+
requestTimeoutMs?: number;
|
|
326
|
+
/** Disable timers/listeners (conformance runners drive flushes explicitly). */
|
|
327
|
+
manualLifecycle?: boolean;
|
|
328
|
+
/**
|
|
329
|
+
* Called at capture time for host-supplied `context` fields, shallow-merged over the
|
|
330
|
+
* derived ones. Used by the Shopify web-pixel adapter, which gets fresh page context
|
|
331
|
+
* on every event and cannot read the real `window`/`document`.
|
|
332
|
+
*/
|
|
333
|
+
contextProvider?: () => Partial<EventContext>;
|
|
334
|
+
/**
|
|
335
|
+
* How queue/session persistence is deferred. Defaults to an idle callback, which is what
|
|
336
|
+
* keeps the blocking `localStorage` write off the capture path. Pass `syncScheduler` to
|
|
337
|
+
* restore write-through — tests do, and so does any host whose storage is already
|
|
338
|
+
* non-blocking (the Shopify pixel's async-mirrored storage).
|
|
339
|
+
*/
|
|
340
|
+
schedule?: Scheduler;
|
|
341
|
+
}
|
|
342
|
+
declare class DepsmithSdkClient {
|
|
343
|
+
private config;
|
|
344
|
+
private logger;
|
|
345
|
+
private storage;
|
|
346
|
+
private clock;
|
|
347
|
+
private identity;
|
|
348
|
+
private session;
|
|
349
|
+
private consent;
|
|
350
|
+
private queue;
|
|
351
|
+
private uploader;
|
|
352
|
+
private flushTimer;
|
|
353
|
+
/**
|
|
354
|
+
* Set once a teardown drain has run, so `pagehide` and `visibilitychange`→hidden do not
|
|
355
|
+
* both run it on one navigation. Cleared on resume, on `pageshow`, and by any newly
|
|
356
|
+
* captured event ({@link enqueueEvent}).
|
|
357
|
+
*/
|
|
358
|
+
private drained;
|
|
359
|
+
private teardownFns;
|
|
360
|
+
private contextProvider?;
|
|
361
|
+
/** Resolves once async storage (IndexedDB) is hydrated; uploads gate on this. */
|
|
362
|
+
private ready;
|
|
363
|
+
constructor(config: DepsmithSdkConfig, overrides?: InternalOverrides);
|
|
364
|
+
track(name: string, properties?: Properties): void;
|
|
365
|
+
/**
|
|
366
|
+
* Rejects an envelope id the collector's schema would refuse, at the point it enters the SDK.
|
|
367
|
+
*
|
|
368
|
+
* Dropping the call is harsh, and it is the lesser harm. `event`, `user_id` and `group_id` are
|
|
369
|
+
* all capped at 255 in event.schema.json, the collector validates every batch with Ajv, and a
|
|
370
|
+
* 400 is non-retryable — so the uploader discards the WHOLE batch as a poison pill. For
|
|
371
|
+
* `user_id` and `group_id` that is not a one-batch loss either: both are persisted and ride on
|
|
372
|
+
* every subsequent event, so a single over-long id silently destroys everything that user sends
|
|
373
|
+
* until reset(). A JWT or a concatenated composite key passed as a user id does it.
|
|
374
|
+
*
|
|
375
|
+
* Truncating instead would keep the events but silently merge two users sharing a 255-char
|
|
376
|
+
* prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is
|
|
377
|
+
* the rule throughout: such an event would 400 and take the whole batch with it.
|
|
378
|
+
*/
|
|
379
|
+
private tooLong;
|
|
380
|
+
page(name?: string, properties?: Properties): void;
|
|
381
|
+
/** Alias of page() — unified mobile naming. */
|
|
382
|
+
screen(name?: string, properties?: Properties): void;
|
|
383
|
+
identify(userId: string, traits?: Properties): void;
|
|
384
|
+
alias(aliasId: string): void;
|
|
385
|
+
reset(): void;
|
|
386
|
+
group(groupId: string, traits?: Properties): void;
|
|
387
|
+
setGroupTraits(traits: Properties): void;
|
|
388
|
+
setProperty(key: string, value: Properties[string]): void;
|
|
389
|
+
/**
|
|
390
|
+
* Sets a property only if this device has not already set it.
|
|
391
|
+
*
|
|
392
|
+
* The local check is the cross-SDK contract (`spec/conformance/fixtures/
|
|
393
|
+
* user_props_set_setonce_unset.json` asserts that a repeat call emits nothing), so it
|
|
394
|
+
* stays. It is an optimisation, not the guarantee: a client can only see THIS device, and
|
|
395
|
+
* a returning visitor on a second browser looks like a first write. `$set_once` closes
|
|
396
|
+
* that, because the collector evaluates it against the stored identity.
|
|
397
|
+
*/
|
|
398
|
+
setOnceProperty(key: string, value: Properties[string]): void;
|
|
399
|
+
unsetProperty(key: string): void;
|
|
400
|
+
/**
|
|
401
|
+
* Applies user-property operators server-side (API_SPEC §14).
|
|
402
|
+
*
|
|
403
|
+
* The whole closed operator set in one call — `$set`, `$set_once`, `$add`, `$append`,
|
|
404
|
+
* `$prepend`, `$pre_insert`, `$post_insert`, `$remove`, `$unset`, `$clear_all` — rather
|
|
405
|
+
* than ten methods, because the set is fixed by the schema and a typed map keeps the
|
|
406
|
+
* public surface proportional to what it buys.
|
|
407
|
+
*
|
|
408
|
+
* `$add` is the reason this exists at all: incrementing on the client is a
|
|
409
|
+
* read-modify-write race between tabs, and no amount of care on one device fixes it.
|
|
410
|
+
*
|
|
411
|
+
* Unlike the three convenience methods above, this sends NO `context.traits`. Those carry
|
|
412
|
+
* traits for compatibility with consumers that read them today; a caller reaching for the
|
|
413
|
+
* operators directly is asking for the server-applied semantics, and duplicating an
|
|
414
|
+
* `$append` into a trait would misreport it as an overwrite.
|
|
415
|
+
*
|
|
416
|
+
* Silently does nothing when nothing survives validation — a key claimed twice, a
|
|
417
|
+
* non-finite `$add`, an empty map — since the schema forbids an empty operator object.
|
|
418
|
+
*/
|
|
419
|
+
setUserProperties(ops: UserPropertyOps): void;
|
|
420
|
+
optIn(): void;
|
|
421
|
+
optOut(): void;
|
|
422
|
+
flush(): Promise<void>;
|
|
423
|
+
/**
|
|
424
|
+
* Autocapture engine entry point ($autocapture events). Not part of the public API —
|
|
425
|
+
* the lazily-loaded engine calls this through its `emit` hook.
|
|
426
|
+
*
|
|
427
|
+
* Named rather than inlined into startAutocapture() so the conformance runner can drive
|
|
428
|
+
* it by reflection, exactly as Android's `autocapture()` and iOS's `autocapture(_:)`
|
|
429
|
+
* already allow. Without a named entry point the whole subsystem is unreachable from a
|
|
430
|
+
* shared fixture, which is why it had none.
|
|
431
|
+
*/
|
|
432
|
+
autocapture(properties: Properties): void;
|
|
433
|
+
/** Conformance/testing: await any in-flight upload (incl. retries) without forcing one. */
|
|
434
|
+
drainInFlight(): Promise<void>;
|
|
435
|
+
getAnonymousId(): string;
|
|
436
|
+
getSessionId(): string;
|
|
437
|
+
/**
|
|
438
|
+
* Adopts an externally supplied session id, so a session can span a web→app handoff or
|
|
439
|
+
* two contexts that do not share storage. Must be a UUIDv7; anything else is a debug-warn
|
|
440
|
+
* no-op rather than a corrupted session. Emits no `$session_start` (API_SPEC §5).
|
|
441
|
+
*/
|
|
442
|
+
setSessionId(sessionId: string, startedAt?: number): void;
|
|
443
|
+
/** Stops timers/listeners. Queued events stay persisted. */
|
|
444
|
+
shutdown(): void;
|
|
445
|
+
/**
|
|
446
|
+
* Forces the write-behind queue and session state to storage now.
|
|
447
|
+
*
|
|
448
|
+
* Persistence is deferred to an idle callback so a captured event does not pay a
|
|
449
|
+
* blocking `localStorage` write on the interaction that produced it. This is the escape
|
|
450
|
+
* hatch for the moments where there may be no later tick: page teardown and shutdown.
|
|
451
|
+
*/
|
|
452
|
+
private persistNow;
|
|
453
|
+
/**
|
|
454
|
+
* Queues an event and re-arms the teardown drain.
|
|
455
|
+
*
|
|
456
|
+
* `drained` exists only to stop `pagehide` and `visibilitychange`→hidden running the
|
|
457
|
+
* same drain twice on one navigation. It must not outlive the work it covered: on
|
|
458
|
+
* desktop, `visibilitychange`→hidden fires on an ordinary tab switch, and a backgrounded
|
|
459
|
+
* tab keeps capturing (the batch-interval timer, `online`, a host-driven `track()`). If
|
|
460
|
+
* that tab is then closed without ever becoming visible again, a latch left set would
|
|
461
|
+
* skip both the final `sendBeaconAll()` and the teardown write, losing everything
|
|
462
|
+
* captured while hidden — a correctness hole opened by a pure optimisation.
|
|
463
|
+
*/
|
|
464
|
+
private enqueueEvent;
|
|
465
|
+
/**
|
|
466
|
+
* The single entry point for starting an upload.
|
|
467
|
+
*
|
|
468
|
+
* Persistence is NOT forced here. API_SPEC §1 step 4 (durable storage before any network
|
|
469
|
+
* attempt) is upheld inside the uploader's drain loop, which persists per batch it is
|
|
470
|
+
* about to send. Forcing it here instead meant a synchronous write on every capture once
|
|
471
|
+
* the queue sat at or above `batchSize` — which is the regression this whole change
|
|
472
|
+
* exists to remove, reappearing in the exact case that matters most (a backed-up queue).
|
|
473
|
+
*/
|
|
474
|
+
private flushUploads;
|
|
475
|
+
/**
|
|
476
|
+
* Fingerprinting is opt-in and privacy-gated: it requires explicit config, granted
|
|
477
|
+
* consent (consent.current is 'denied' under DNT and never 'granted' while pending),
|
|
478
|
+
* and non-COPPA mode.
|
|
479
|
+
*/
|
|
480
|
+
private contextOptions;
|
|
481
|
+
/**
|
|
482
|
+
* Session-sticky sampling.
|
|
483
|
+
*
|
|
484
|
+
* The decision is derived from (apiKey, session_id) rather than drawn at random, so it
|
|
485
|
+
* is stable for the session's whole lifetime and identical across tabs sharing that
|
|
486
|
+
* session. A random draw per event would split sessions in half, which is worse than
|
|
487
|
+
* useless: a funnel built from partial sessions is wrong rather than merely noisy.
|
|
488
|
+
*
|
|
489
|
+
* Salted with the apiKey so a future, independently-configured sampler at the same rate
|
|
490
|
+
* does not select the identical set of sessions.
|
|
491
|
+
*
|
|
492
|
+
* Identity events are NEVER sampled. Dropping $identify for 90% of users would stop
|
|
493
|
+
* their user properties applying at all — that is not less data, it is wrong data.
|
|
494
|
+
* Everything else follows the session: a session is wholly in or wholly out. Scale
|
|
495
|
+
* sampled metrics by 1/sampleRate.
|
|
496
|
+
*/
|
|
497
|
+
private sessionInSample;
|
|
498
|
+
/** Identity events are exempt; everything else follows its session. */
|
|
499
|
+
private inSample;
|
|
500
|
+
private capture;
|
|
501
|
+
/**
|
|
502
|
+
* Config drift (guidelines §12): events queued under a different apiKey belong to
|
|
503
|
+
* another project — drop them rather than misattribute. Fingerprint, not raw key.
|
|
504
|
+
*/
|
|
505
|
+
private detectConfigDrift;
|
|
506
|
+
private pickStorage;
|
|
507
|
+
private enqueueSessionEnd;
|
|
508
|
+
/**
|
|
509
|
+
* Announces a session the SDK just observed beginning.
|
|
510
|
+
*
|
|
511
|
+
* Consent-gated for the same reason as enqueueSessionEnd: the visibilitychange resume
|
|
512
|
+
* path reaches this without going through capture(). Under `pending` consent
|
|
513
|
+
* canCapture() is true, so it is queued and held — matching capture() exactly.
|
|
514
|
+
*
|
|
515
|
+
* Not emitted by reset()/rotate() (an explicit user action, not an observed boundary)
|
|
516
|
+
* nor by peek()'s mint-if-absent branch (analytics from a getter).
|
|
517
|
+
*/
|
|
518
|
+
private enqueueSessionStart;
|
|
519
|
+
private startFlushTimer;
|
|
520
|
+
private attachLifecycle;
|
|
521
|
+
/** Lazily loads the autocapture engine so the core bundle stays <10KB gz. */
|
|
522
|
+
private startAutocapture;
|
|
523
|
+
private guard;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Default singleton facade:
|
|
528
|
+
*
|
|
529
|
+
* import { DepsmithSdk } from '@depsmith/depsmith-sdk';
|
|
530
|
+
* DepsmithSdk.init({ apiKey: '...', endpoint: 'https://collector.example.com' });
|
|
531
|
+
* DepsmithSdk.track('button_clicked', { color: 'red' });
|
|
532
|
+
*
|
|
533
|
+
* Re-init with the same apiKey is a no-op; a different apiKey replaces the client (API_SPEC §2).
|
|
534
|
+
*/
|
|
535
|
+
declare const DepsmithSdk: {
|
|
536
|
+
init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null;
|
|
537
|
+
track: (name: string, properties?: Properties) => void;
|
|
538
|
+
page: (name?: string, properties?: Properties) => void;
|
|
539
|
+
screen: (name?: string, properties?: Properties) => void;
|
|
540
|
+
identify: (userId: string, traits?: Properties) => void;
|
|
541
|
+
alias: (aliasId: string) => void;
|
|
542
|
+
reset: () => void;
|
|
543
|
+
group: (groupId: string, traits?: Properties) => void;
|
|
544
|
+
setGroupTraits: (traits: Properties) => void;
|
|
545
|
+
setProperty: (key: string, value: Properties[string]) => void;
|
|
546
|
+
setOnceProperty: (key: string, value: Properties[string]) => void;
|
|
547
|
+
unsetProperty: (key: string) => void;
|
|
548
|
+
/** Applies the §14 operator set server-side: $set, $add, $append, $unset, $clear_all, … */
|
|
549
|
+
setUserProperties: (ops: UserPropertyOps) => void;
|
|
550
|
+
optIn: () => void;
|
|
551
|
+
optOut: () => void;
|
|
552
|
+
flush: () => Promise<void>;
|
|
553
|
+
getAnonymousId: () => string | undefined;
|
|
554
|
+
getSessionId: () => string | undefined;
|
|
555
|
+
setSessionId: (sessionId: string, startedAt?: number) => void;
|
|
556
|
+
/** Testing/teardown: stop timers and forget the singleton. */
|
|
557
|
+
shutdown(): void;
|
|
558
|
+
};
|
|
559
|
+
|
|
560
|
+
export { type AsyncKV, AsyncMirrorAdapter, type AutocaptureConfig, type BatchPayload, type ConsentState, DEPSMITH_SDK_STORAGE_KEYS, DepsmithSdk, DepsmithSdkClient, type DepsmithSdkConfig, type DepsmithSdkEvent, type EventContext, type EventType, type InternalOverrides, type KVStorage, type Properties, type PropertyValue, type Scheduler, type TrackingOptions, type UserPropertyOps, idleScheduler, syncScheduler };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function ae(){return import("./autocapture.js")}var z=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]],Ke=Object.fromEntries(z.map(([r])=>[r,!0]));function de(r){let e={...Ke};if(!r)return e;for(let[t]of z)r[t]===!1&&(e[t]=!1);return e}function ue(r,e){let t=r;for(let[i,n,s]of z){if(e[i])continue;if(s===void 0){delete t[n];continue}let o={...t[n]};delete o[s],Object.keys(o).length>0?t[n]=o:delete t[n]}return r}var V={clicks:"interactive",forms:!0,scrolls:!0,pageviews:!0,ignoredSelectors:[],selectorMaxDepth:5};function ze(r){return r===void 0?V.clicks:r===!0?"interactive":r}function ce(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=r.autocapture===!0?V:r.autocapture&&typeof r.autocapture=="object"?{...V,...r.autocapture,clicks:ze(r.autocapture.clicks)}:!1;return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:L(r.batchSize??20,1,500),batchIntervalMs:Math.max(r.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(r.maxQueueSize??1e3,1),maxQueueBytes:Math.max(r.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(r.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(r.sampleRate)?L(r.sampleRate,0,1):1,sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:L(r.maxRetries??5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,trackingOptions:de(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage"}}function L(r,e,t){return Math.min(Math.max(r,e),t)}function F(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function pe(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e>>>0}function Le(r){return pe(r).toString(36)}function le(r){return pe(r)/4294967296}function B(r){return F(r)+Le(r)}var j={},he=!1;function ge(){if(!he){he=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{j=e}).catch(()=>{})}catch{}}}function fe(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=je(e,t);i&&(r.browser=i);let n=Xe(e);if(n){let a=Fe(n.name,j.platformVersion);r.os=a?{...n,version:a}:n}let s=Ge(e,t);s&&(r.deviceType=s);let o=Ve(e,n);return o&&(r.device=o),r}function Ve(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=j.model?.trim();return i?t.model=i:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function Fe(r,e){let t=e?.trim();if(t){if(r==="Windows"){let i=Number.parseInt(t.split(".")[0]??"",10);return!Number.isFinite(i)||i===0?void 0:i>=13?"11":"10"}return me(t)}}var Be=[{pattern:/Edg(?:e|A|iOS)?\/([\d.]+)/,name:"Edge",engine:"Blink"},{pattern:/OPR\/([\d.]+)/,name:"Opera",engine:"Blink"},{pattern:/Firefox\/([\d.]+)/,name:"Firefox",engine:"Gecko"},{pattern:/Chrome\/([\d.]+)/,name:"Chrome",engine:"Blink"},{pattern:/Version\/([\d.]+)/,name:"Safari",engine:"WebKit",requires:/Safari/}];function je(r,e){for(let i of Be){if(i.requires&&!i.requires.test(r))continue;let n=r.match(i.pattern);if(n)return{name:i.name,version:n[1],engine:i.engine}}let t=e?.brands?.find(i=>!/not.?a.?brand/i.test(i.brand));if(t)return{name:t.brand,version:t.version}}var Ye=[{pattern:/Windows NT ([\d.]+)/,name:"Windows"},{pattern:/OS ([\d_]+)/,name:"iOS",requires:/iPhone|iPad|iPod/},{pattern:/Android ([\d.]+)/,name:"Android"},{pattern:/Mac OS X ([\d_]+)/,name:"macOS"}];function Xe(r){for(let e of Ye){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:me((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function me(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function Ge(r,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(r))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(r))return"mobile";if(/Android/.test(r))return"tablet";if(typeof navigator<"u"&&r)return"desktop"}var A=null,E=null;function ve(){return E!==null||(E=We()),E}function O(){return A!==null||(A=B(ve().map(r=>r.value).join("|"))),A}function ye(){let r={};for(let e of ve())r[`$fp_${e.name}`]=e.value;return r}function We(){let r=[];try{if(typeof screen<"u"&&r.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;r.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),r.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),r.push({name:"plat",value:`plat:${navigator.platform??""}`}),r.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}r.push({name:"canvas",value:`canvas:${He()}`})}catch{}return r}function He(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),B(r.toDataURL())):""}catch{return""}}function Se(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};switch(r.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(r.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var P=null,ke=0,be=!1,y=!1,we=null;function xe(){if(!be){be=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let r=navigator.permissions;if(typeof r?.query!="function")return;r.query({name:"geolocation"}).then(e=>{we=e,e.state==="granted"&&Y(),e.onchange=()=>{e.state==="granted"?Y():P=null}}).catch(()=>{})}catch{}}}function Y(){if(!y){y=!0;try{navigator.geolocation.getCurrentPosition(r=>{y=!1;let{latitude:e,longitude:t,accuracy:i}=r.coords;if(!Number.isFinite(e)||!Number.isFinite(t))return;let n={latitude:e,longitude:t,source:"gps"};Number.isFinite(i)&&(n.accuracy=i),P=n,ke=Date.now()},()=>{y=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{y=!1}}}function _e(){if(P)return Date.now()-ke>3e5&&we?.state==="granted"&&Y(),{...P}}var G="@depsmith/depsmith-sdk",f="0.6.0",X=null;function Je(){if(X)return X;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),X=r,r}function b(r={}){let e={library:{name:G,version:f}};S(()=>{typeof window<"u"&&window.location&&(e.page={url:window.location.href,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0})}),S(()=>{typeof window<"u"&&window.screen&&(e.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),S(()=>{let t=Je();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),S(()=>{r.fingerprint&&Qe(e)}),S(()=>{if(r.geolocation){let t=_e();t&&(e.location=t)}});try{if(r.overrides){for(let[t,i]of Object.entries(r.overrides))i!==void 0&&(e[t]=i);e.library={name:G,version:f}}}catch{}return r.tracking&&ue(e,r.tracking),e}function Qe(r){let{browser:e,os:t,deviceType:i,device:n}=fe();e&&(r.browser=e),t&&(r.os=t);let s={};i&&(s.type=i),n?.manufacturer&&(s.manufacturer=n.manufacturer),n?.model&&(s.model=n.model),Object.keys(s).length>0&&(r.device=s);let o=Se();o.type&&(r.network={...r.network,type:o.type})}function S(r){try{r()}catch{}}function Ae(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var W="depsmith_consent",C=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(W);this.state=n==="granted"||n==="denied"||n==="pending"?n:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(W,"granted")}optOut(){this.state="denied",this.storage.set(W,"denied")}};var k=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Ze=r=>r();var T="depsmith_queue",et=512*1024,H=2,tt=new Set(["identify","alias","group"]);function rt(r){return tt.has(r?.event_type)}var I=class{constructor(e,t,i,n={}){this.storage=e;this.maxSize=t;this.logger=i;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=n.maxChars??et,this.schedule=n.schedule??k,this.restore()}restore(){try{let e=this.storage.get(T);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let i=t.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string");this.reset(i),i.length!==t.length&&(this.logger.warn("discarded corrupt queued events on restore"),this.markDirty()),this.trimToBudget()&&this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty"),this.reset([]),this.storage.remove(T)}}reset(e){this.events=e,this.sizes=e.map(t=>Ee(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?H:this.sizeSum+(this.events.length-1)+H}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(T,JSON.stringify(this.events)))}prepend(e){let t=new Set(this.events.map(n=>n.event_id)),i=e.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string"&&!t.has(n.event_id));i.length!==0&&(this.reset([...i,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let t=Ee(e);if(t+H>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let i=this.events.length-this.maxSize;this.dropOldest(i),this.logger.warn(`queue cap reached; dropped ${i} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!rt(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e){return this.events.slice(0,e)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let a=this.events[o];if(t.has(a.event_id))continue;let d=this.sizes[o];i.push(a),n.push(d),s+=d}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(T)}};function Ee(r){return JSON.stringify(r).length}function l(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let i=0;i<16;i++)e[i]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=[];for(let i=0;i<16;i++)t.push(e[i].toString(16).padStart(2,"0"));return`${t[0]}${t[1]}${t[2]}${t[3]}-${t[4]}${t[5]}-${t[6]}${t[7]}-${t[8]}${t[9]}-${t[10]}${t[11]}${t[12]}${t[13]}${t[14]}${t[15]}`}function m(r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r))return null;let e=r.slice(0,8)+r.slice(9,13),t=parseInt(e,16);return Number.isFinite(t)?t:null}var Oe=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker"],v=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},J=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},M=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let i of document.cookie.split("; "))if(i.startsWith(t))return decodeURIComponent(i.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",i=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${i}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},it=new Set(["depsmith_anonymous_id"]),$=class{constructor(e,t,i=it){this.primary=e;this.secondary=t;this.mirrored=i}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let i=this.secondary.get(e);if(t===i)return t;if(t===null&&i!==null)return this.primary.set(e,i),i;if(i===null&&t!==null)return this.secondary.set(e,t),t;let n=nt(t,i)??t;return this.primary.set(e,n),this.secondary.set(e,n),n}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}};function nt(r,e){let t=m(r),i=m(e);return t===null||i===null?null:t<=i?r:e}var w=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let i=indexedDB.open(e,1);i.onupgradeneeded=()=>i.result.createObjectStore("kv"),i.onsuccess=()=>{this.db=i.result;let n=this.db.transaction("kv","readonly").objectStore("kv"),s=n.getAllKeys(),o=n.getAll();o.onsuccess=()=>{let a=s.result;o.result.forEach((d,u)=>{let p=a[u];p!==void 0&&(this.snapshot.set(p,d),this.mirror.has(p)||this.mirror.set(p,d))}),t()},o.onerror=()=>t()},i.onerror=()=>t()}catch{t()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(t,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}},Q=class{constructor(e,t=Oe){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};function Pe(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new J(window.localStorage)}}catch{}return new v}var Z="depsmith_anonymous_id",ee="depsmith_user_id",te="depsmith_group_id",R="depsmith_user_props",D=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(Z);return e||(e=l(this.clock.now()),this.storage.set(Z,e)),e}get userId(){return this.storage.get(ee)}get groupId(){return this.storage.get(te)}identify(e){this.storage.set(ee,e)}setGroup(e){this.storage.set(te,e)}getUserProps(){try{return JSON.parse(this.storage.get(R)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(R,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(R,JSON.stringify(t))}reset(){this.storage.remove(ee),this.storage.remove(te),this.storage.remove(R);let e=l(this.clock.now());return this.storage.set(Z,e),e}};var Ce="depsmith_session",N=class{constructor(e,t,i,n=k){this.storage=e;this.clock=t;this.timeoutMs=i;this.pending=null;this.scheduled=!1;this.schedule=n}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(Ce);if(!e)return null;let t=JSON.parse(e);return typeof t.id!="string"||typeof t.lastActivityAt!="number"?null:(typeof t.startedAt!="number"&&(t.startedAt=m(t.id)??t.lastActivityAt),t)}catch{return null}}save(e){this.pending=e,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){let e=this.pending;e&&(this.pending=null,this.storage.set(Ce,JSON.stringify(e)))}mint(e){let t={id:l(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let i=this.mint(e);return{sessionId:i.id,startedAt:e,startedSession:{id:i.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let i=this.mint(e);return{sessionId:i.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:i.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let i=m(e);return i===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:t??i}),!0)}rotate(){return this.mint(this.clock.now()).id}};function h(r,e){if(r==null)return{};if(typeof r!="object"||Array.isArray(r))return e.warn("properties must be an object; ignoring",r),{};let t={},i=0;for(let[n,s]of Object.entries(r)){if(i>=200){e.warn("properties exceed 200 keys; excess dropped");break}let o=st(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function re(r){if(r===null)return null;let e=typeof r;if(e==="string"||e==="boolean")return r;if(e==="number")return Number.isFinite(r)?r:void 0;if(r instanceof Date)return isNaN(r.getTime())?void 0:r.toISOString()}function st(r,e){let t=re(r);if(t!==void 0)return t;if(!(r===void 0||typeof r=="function"||typeof r=="symbol")){if(Array.isArray(r)){let i=[];for(let n of r.slice(0,100)){let s=re(n);i.push(s!==void 0?s:Te(n))}return i}if(typeof r=="object"){let i={},n=0;for(let[s,o]of Object.entries(r)){if(n>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let a=re(o);i[String(s)]=a!==void 0?a:Te(o),n++}return i}}}function Te(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}var ot=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],Ie=50,Me=200;function ie(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let s=Object.keys(r).filter(o=>o!=="$clear_all");return s.length>0&&e.warn(`$clear_all is exclusive; ignored ${s.join(", ")}`),{$clear_all:!0}}let t={},i=new Set,n=(s,o)=>i.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(i.add(s),!0);for(let s of ot){let o=r[s];if(!o||typeof o!="object")continue;let a=h(o,e),d={};for(let[u,p]of Object.entries(a))n(u,s)&&(d[u]=p);Object.keys(d).length>0&&(t[s]=d)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[a,d]of Object.entries(r.$add)){if(o>=Ie){e.debug(`$add over ${Ie} keys; excess dropped`);break}if(typeof d!="number"||!Number.isFinite(d)){e.debug(`$add "${a}" is not finite; dropped`);continue}n(a,"$add")&&(s[a]=d,o++)}Object.keys(s).length>0&&(t.$add=s)}if(Array.isArray(r.$unset)){let s=[];for(let o of r.$unset){if(s.length>=Me){e.debug(`$unset over ${Me} keys; excess dropped`);break}typeof o!="string"||o.length===0||n(o,"$unset")&&s.push(o)}s.length>0&&(t.$unset=s)}return Object.keys(t).length>0?t:void 0}function U(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var $e={now:()=>Date.now()};function g(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function Re(r){return r===0||r===408||r===429||r>=500}var at=1e3,dt=32e3;function De(r,e=Math.random){let t=Math.min(at*2**r,dt);return Math.round(e()*t)}async function ut(r){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new TextEncoder().encode(r)).catch(()=>{}),t.close().catch(()=>{});let i=e.readable.getReader(),n=[];for(;;){let{done:d,value:u}=await i.read();if(d)break;n.push(u)}let s=n.reduce((d,u)=>d+u.length,0),o=new Uint8Array(new ArrayBuffer(s)),a=0;for(let d of n)o.set(d,a),a+=d.length;return o}function Ne(r){let e=[];for(let t of r)e.push(t.event_id);return e}var ct=3e4,pt=6e4,lt=10;function ht(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var q=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("collector unreachable; uploads paused");return}let e=this.queue.peek(this.config.batchSize);this.queue.persistNow();let t=await this.uploadWithRetry(e);if(t==="requeue")return;t==="dropped"&&this.deps.logger.warn(`dropped poison batch of ${e.length}`),this.queue.remove(Ne(e))}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1;for(let n=0;n<=this.config.maxRetries;n++){let s=await this.post(e);if(s!==0&&(i=!0),s>=200&&s<300)return t?.ok(),"sent";if(!Re(s))return t?.ok(),this.deps.logger.warn(`non-retryable ${s}; dropping batch`),"dropped";if(this.deps.logger.debug(`upload attempt ${n+1} failed (${s})`),s===0&&!i&&t?.suspect())break;n<this.config.maxRetries&&await this.deps.sleep(De(n))}return i?t?.ok():t?.fail(),"requeue"}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:g(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s=t,o={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream<"u")try{s=await ut(t),o["Content-Encoding"]="gzip"}catch{s=t}let a=ht(s)<=pt;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let d={method:"POST",headers:o,body:s,keepalive:a};return i&&(d.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,d)).status}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:ct}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<lt;){let t=this.queue.peek(this.config.batchSize),i=this.buildPayload(t);if(!navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(i)],{type:"text/plain"})))return;this.queue.remove(Ne(t)),e++}}catch{}}};var ne="depsmith_net_breaker";function Ue(r,e){let t=!1,i=0,n=0,s=3e5,o=(u,p,_)=>typeof u=="number"&&u===u?Math.min(Math.max(u,p),_):p,a=()=>{if(!t){t=!0;try{let u=JSON.parse(r.get(ne)??"0");if(!Array.isArray(u))return;i=o(u[0],0,3),n=o(u[1],0,e.now()+36e5),s=o(u[2],3e5,36e5)}catch{}}},d=()=>{try{i?r.set(ne,JSON.stringify([i,n,s])):r.remove(ne)}catch{}};return{open:()=>(a(),e.now()<n),suspect:()=>(a(),i>0),fail:()=>{a(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),d()},ok:()=>{a(),i&&(i=n=0,s=3e5,d())}}}var K=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var qe=255,x=class{constructor(e,t={}){this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=ce(e),this.logger=new K(this.config.debug),this.clock=t.clock??$e,this.storage=t.storage??this.pickStorage(),this.contextProvider=t.contextProvider;let i=this.config.childSafeMode?new v:this.config.storage==="memory"?this.storage:new $(this.storage,new M(this.config.cookieDomain||void 0));this.identity=new D(i,this.clock),this.session=new N(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new C(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??Ae())),this.queue=new I(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&ge(),this.config.geolocation&&!this.config.childSafeMode&&xe(),this.storage instanceof w&&(this.ready=this.storage.hydrate().then(n=>{try{let s=n.get("depsmith_queue");s&&this.queue.prepend(JSON.parse(s))}catch{this.logger.warn("persisted queue corrupt; discarded")}})),this.uploader=new q(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...n)=>fetch(...n)),clock:this.clock,logger:this.logger,sleep:t.sleep??(n=>new Promise(s=>setTimeout(s,n))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:Ue(this.storage,this.clock)}),t.manualLifecycle||(this.startFlushTimer(),this.attachLifecycle(),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}if(e.startsWith("$")){this.logger.warn(`track: "$"-prefixed names are reserved; dropped "${e}"`);return}this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}tooLong(e,t){return e.length<=qe?!1:(this.logger.warn(`${t} exceeds ${qe} characters (got ${e.length}); dropped`),!0)}page(e,t){this.guard(()=>{let i=e??(typeof document<"u"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...t,name:i})})}screen(e,t){this.page(e,t)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let i=h(t,this.logger);this.capture("$identify","identify",void 0,i,U("$set",i))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.identity.reset(),this.session.rotate(),this.logger.debug("reset: identity and session rotated")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}this.tooLong(e,"group: groupId")||(this.identity.setGroup(e),this.capture("$group","group",void 0,h(t,this.logger)))})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}this.capture("$group","group",void 0,h(e,this.logger))})}setProperty(e,t){this.guard(()=>{this.identity.setUserProp(e,t);let i=h({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,U("$set",i))})}setOnceProperty(e,t){this.guard(()=>{if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.identity.setUserProp(e,t);let i=h({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,U("$set_once",i))})}unsetProperty(e){this.guard(()=>{this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},ie({$unset:[e]},this.logger))})}setUserProperties(e){this.guard(()=>{let t=ie(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.flushUploads()})}optOut(){this.guard(()=>{this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.flushTimer!==null&&clearInterval(this.flushTimer),this.flushTimer=null;for(let e of this.teardownFns.splice(0))e();this.persistNow()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}enqueueEvent(e){this.queue.enqueue(e),this.drained=!1}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides:e,tracking:this.config.trackingOptions}}sessionInSample(e){return this.config.sampleRate>=1?!0:le(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,i,n,s){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let o=this.session.touch();if(o.endedSession&&this.sessionInSample(o.endedSession.id)&&this.enqueueSessionEnd(o.endedSession),o.startedSession&&this.sessionInSample(o.startedSession.id)&&this.enqueueSessionStart(o.startedSession),!this.inSample(o.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let a=this.clock.now(),d=this.contextOptions(),u={event_id:l(a),event:e,event_type:t,timestamp:g(a),session_id:o.sessionId,session_started_at:g(o.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...b(d),traits:n}:b(d),platform:"web",sdk_version:f};s&&(u.user_properties=s);let p={...this.config.defaultProperties,...h(i,this.logger)};Object.keys(p).length>0&&(u.properties=p);let _=this.identity.userId;_&&(u.user_id=_);let oe=this.identity.groupId;oe&&(u.group_id=oe),d.fingerprint&&(u.device_id=O()),this.enqueueEvent(u),this.logger.debug(`captured ${e}`,u),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",t=F(this.config.apiKey),i=this.storage.get(e);i!==null&&i!==t&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear()),this.storage.set(e,t)}pickStorage(){return this.config.storage==="memory"?new v:this.config.storage==="indexeddb"&&typeof indexedDB<"u"?new w:Pe()}enqueueSessionEnd(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:l(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:g(e.lastActivityAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:b(t),platform:"web",sdk_version:f},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=O()),this.enqueueEvent(i)}enqueueSessionStart(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:l(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:g(e.startedAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:b(t),platform:"web",sdk_version:f},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=O()),t.fingerprint&&(i.properties={...i.properties,...ye()}),this.enqueueEvent(i)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window>"u"||typeof document>"u")return;let e=()=>{this.drained||(this.drained=!0,this.consent.canUpload()&&this.uploader.sendBeaconAll(),this.persistNow())},t=()=>{if(document.visibilityState==="hidden")e();else{this.drained=!1;let s=this.session.touch();s.endedSession&&this.enqueueSessionEnd(s.endedSession),s.startedSession&&this.enqueueSessionStart(s.startedSession)}},i=()=>{this.drained=!1},n=()=>{this.uploader.resetNetworkBreaker(),this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()};window.addEventListener("pagehide",e),window.addEventListener("pageshow",i),document.addEventListener("visibilitychange",t),window.addEventListener("online",n),this.teardownFns.push(()=>{window.removeEventListener("pagehide",e),window.removeEventListener("pageshow",i),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",n)})}startAutocapture(){let e=this.config.autocapture;!e||typeof window>"u"||ae().then(t=>{t&&this.teardownFns.push(t.startAutocapture(e,{emit:i=>this.autocapture(i),page:()=>this.page()}))}).catch(t=>this.logger.debug("autocapture load failed",t))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var c=null,se=null,gr={init(r,e){try{return c&&se===r.apiKey||(c?.shutdown(),c=new x(r,e),se=r.apiKey),c}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>c?.track(r,e),page:(r,e)=>c?.page(r,e),screen:(r,e)=>c?.screen(r,e),identify:(r,e)=>c?.identify(r,e),alias:r=>c?.alias(r),reset:()=>c?.reset(),group:(r,e)=>c?.group(r,e),setGroupTraits:r=>c?.setGroupTraits(r),setProperty:(r,e)=>c?.setProperty(r,e),setOnceProperty:(r,e)=>c?.setOnceProperty(r,e),unsetProperty:r=>c?.unsetProperty(r),setUserProperties:r=>c?.setUserProperties(r),optIn:()=>c?.optIn(),optOut:()=>c?.optOut(),flush:()=>c?.flush()??Promise.resolve(),getAnonymousId:()=>c?.getAnonymousId(),getSessionId:()=>c?.getSessionId(),setSessionId:(r,e)=>c?.setSessionId(r,e),shutdown(){c?.shutdown(),c=null,se=null}};export{Q as AsyncMirrorAdapter,Oe as DEPSMITH_SDK_STORAGE_KEYS,gr as DepsmithSdk,x as DepsmithSdkClient,k as idleScheduler,Ze as syncScheduler};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|