@depsmith/depsmith-sdk 0.7.0 → 0.9.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/dist/index.d.ts CHANGED
@@ -44,6 +44,11 @@ interface UserPropertyOps {
44
44
  type Scalar = string | number | boolean | null;
45
45
  type PropertyValue = Scalar | Scalar[] | Record<string, Scalar>;
46
46
  type Properties = Record<string, PropertyValue>;
47
+ /** The third argument of `page()` / `screen()`. */
48
+ interface PageOptions {
49
+ /** The kind of page (`product`, `collection`, `cart`, …), sent as `$page_type`. */
50
+ type?: string;
51
+ }
47
52
  type EventType = 'track' | 'page_view' | 'page_leave' | 'screen' | 'identify' | 'alias' | 'group' | 'autocapture' | 'session_start' | 'session_end';
48
53
  type NetworkType = '2g' | '3g' | '4g' | '5g' | 'wifi' | 'ethernet' | 'none' | 'unknown';
49
54
  interface EventContext {
@@ -93,7 +98,7 @@ interface EventContext {
93
98
  initial_url?: string;
94
99
  initial_domain?: string;
95
100
  };
96
- screen?: {
101
+ screen_size?: {
97
102
  width?: number;
98
103
  height?: number;
99
104
  density?: number;
@@ -204,9 +209,10 @@ interface TrackingOptions {
204
209
  network?: boolean;
205
210
  osName?: boolean;
206
211
  osVersion?: boolean;
207
- /** context.page. Not the `name` property on $page_view — that is a property, not context. */
212
+ /** context.page. Not `$page_name` on $page_view — that is a property, not context. */
208
213
  page?: boolean;
209
- screen?: boolean;
214
+ /** context.screen_size: display width, height and density. */
215
+ screenSize?: boolean;
210
216
  timezone?: boolean;
211
217
  /** context.user_agent. */
212
218
  userAgent?: boolean;
@@ -251,13 +257,37 @@ interface DepsmithSdkConfig {
251
257
  * consent, like deviceFingerprinting. Default false.
252
258
  */
253
259
  geolocation?: boolean;
260
+ /**
261
+ * Opt-in. Strip the fragment and query string from every URL the SDK sends — `context.page`
262
+ * url/referrer/previous_url, `context.referrer`, `$ac_href`, `$ac_form_action`, `$net_*`.
263
+ * `{ keepParams: ['utm_source'] }` keeps the named query parameters. Default false: URLs are
264
+ * sent whole. See API_SPEC §12.
265
+ */
266
+ scrubUrls?: boolean | {
267
+ keepParams?: string[];
268
+ };
254
269
  /** Per-field context suppression, all keys default true. Subtractive only; see API_SPEC §12.2. */
255
270
  trackingOptions?: TrackingOptions;
256
271
  /** Persist identity keys in a cookie scoped to this domain (cross-subdomain identity). */
257
272
  cookieDomain?: string;
258
273
  /** Queue persistence backend. */
259
274
  storage?: 'localstorage' | 'indexeddb' | 'memory';
275
+ /**
276
+ * Readable `$page_name`s for automatic page views, and for `page()` calls made without a name.
277
+ * A name passed to `page()` always wins; with no match the name falls back to the title.
278
+ *
279
+ * - **Patterns:** `{ '/products/*': 'Product', '/': 'Home' }`. `*` is one path segment, `**` the
280
+ * rest of the path. The first match wins, in insertion order, so put specific patterns
281
+ * before broad ones (or use the `[pattern, name]` array form). A pattern match also sets
282
+ * `$page_type` to its name.
283
+ * - **Function:** `(location) => string | undefined`, called per view. Sets the name only.
284
+ * Web-only; config.schema.json can describe the object form alone.
285
+ */
286
+ pageNames?: PageNames;
260
287
  }
288
+ /** What a `pageNames` function is handed: `window.location`, or a URL with the same fields. */
289
+ type PageLocation = Pick<Location, 'href' | 'pathname' | 'search' | 'hash' | 'host'>;
290
+ type PageNames = Record<string, string> | ReadonlyArray<readonly [pattern: string, name: string]> | ((location: PageLocation) => string | undefined);
261
291
  /**
262
292
  * Which clicks produce a `$autocapture` event.
263
293
  * 'interactive' — only clicks resolving to a link/button/[role=button]/submit control
@@ -266,13 +296,28 @@ interface DepsmithSdkConfig {
266
296
  * true — alias of 'interactive'; false disables click capture.
267
297
  */
268
298
  type ClickCapture = boolean | 'interactive' | 'all';
299
+ /**
300
+ * When an automatic `$page_view` (and its `$page_leave`) is sent.
301
+ * 'path' — when `location.pathname` changes. The default: a query-string or `#` change is
302
+ * filters, sort order, pagination or an in-page anchor, not a new page.
303
+ * 'all' — when anything in the URL changes, query and `#` included (the pre-0.8 behaviour).
304
+ * true — alias of 'path'; false sends none automatically.
305
+ */
306
+ type PageViewCapture = boolean | 'path' | 'all';
269
307
  interface AutocaptureConfig {
270
308
  clicks?: ClickCapture;
271
309
  forms?: boolean;
272
310
  scrolls?: boolean;
273
- pageviews?: boolean;
311
+ pageviews?: PageViewCapture;
274
312
  ignoredSelectors?: string[];
275
313
  selectorMaxDepth?: number;
314
+ /**
315
+ * Extra patterns for ids, classes and test-attribute values that `$ac_selector` should skip as
316
+ * generated, on top of the built-in rules (CSS-in-JS and CSS-module hashes, utility classes,
317
+ * long digit runs). Regex sources, e.g. `['^theme-', '^js-']`; an invalid one is skipped with
318
+ * a debug warning.
319
+ */
320
+ selectorIgnore?: string[];
276
321
  /**
277
322
  * `data-*` attribute names to attach to click and change events as `$ac_attr_<name>`.
278
323
  *
@@ -285,6 +330,12 @@ interface AutocaptureConfig {
285
330
  * Given as bare names: `['product-id']` captures `data-product-id` as `$ac_attr_product_id`.
286
331
  */
287
332
  attributes?: string[];
333
+ /**
334
+ * `$network_request` for failed `fetch` calls, which wraps `window.fetch`. Default true (on
335
+ * whenever autocapture is); false leaves `fetch` untouched while keeping the rest of
336
+ * autocapture. See API_SPEC §12.6.
337
+ */
338
+ networkErrors?: boolean;
288
339
  }
289
340
 
290
341
  /**
@@ -296,7 +347,7 @@ interface KVStorage {
296
347
  set(key: string, value: string): void;
297
348
  remove(key: string): void;
298
349
  }
299
- 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", "depsmith_campaign", "depsmith_referrer"];
350
+ declare const DEPSMITH_SDK_STORAGE_KEYS: readonly ["depsmith_anonymous_id", "depsmith_anon_reset_at", "depsmith_user_id", "depsmith_group_id", "depsmith_user_props", "depsmith_session", "depsmith_consent", "depsmith_queue", "depsmith_config_fp", "depsmith_net_breaker", "depsmith_campaign", "depsmith_referrer", "depsmith_super_props"];
300
351
  /**
301
352
  * Minimal async key-value backend. Shaped to accept Shopify's `browser.localStorage`
302
353
  * / `browser.sessionStorage` directly (all methods Promise-returning, proxied to the
@@ -404,7 +455,7 @@ declare class DepsmithSdkClient {
404
455
  * Autocapture's unload-time `$page_leave` trigger, when pageview tracking is on.
405
456
  *
406
457
  * The client owns the call site rather than autocapture, because it must run BEFORE the
407
- * teardown drain — see {@link attachLifecycle}. Undefined means no page-leave tracking:
458
+ * teardown drain — see `lifecycle.ts`. Undefined means no page-leave tracking:
408
459
  * autocapture is off, compiled out, or still loading.
409
460
  */
410
461
  private leaveOnUnload?;
@@ -414,35 +465,53 @@ declare class DepsmithSdkClient {
414
465
  private vitalsReported;
415
466
  private queue;
416
467
  private uploader;
417
- private flushTimer;
418
- /**
419
- * Set once a teardown drain has run, so `pagehide` and `visibilitychange`→hidden do not
420
- * both run it on one navigation. Cleared on resume, on `pageshow`, and by any newly
421
- * captured event ({@link enqueueEvent}).
422
- */
423
- private drained;
468
+ /** Timer and page listeners. Undefined under `manualLifecycle`, and in the pixel build. */
469
+ private lifecycle?;
470
+ /** Set by shutdown(); a lazily loaded autocapture chunk checks it before starting. */
471
+ private stopped;
424
472
  private teardownFns;
425
473
  private contextProvider?;
426
474
  /** Resolves once async storage (IndexedDB) is hydrated; uploads gate on this. */
427
475
  private ready;
428
476
  constructor(config: DepsmithSdkConfig, overrides?: InternalOverrides);
429
477
  track(name: string, properties?: Properties): void;
478
+ /**
479
+ * `track()` without the `$`-key check on properties, for the SDK's own integrations. Not part
480
+ * of the public API: the Shopify pixel needs it because it stamps `$shopify_client_id` on every
481
+ * event it maps, which a public `track()` would now drop as reserved. Event names are checked
482
+ * exactly as in `track()`.
483
+ */
484
+ trackInternal(name: string, properties?: Properties): void;
430
485
  /**
431
486
  * Rejects an envelope id the collector's schema would refuse, at the point it enters the SDK.
432
487
  *
433
488
  * Dropping the call is harsh, and it is the lesser harm. `event`, `user_id` and `group_id` are
434
489
  * all capped at 255 in event.schema.json, the collector validates every batch with Ajv, and a
435
- * 400 is non-retryable — so the uploader discards the WHOLE batch as a poison pill. For
436
- * `user_id` and `group_id` that is not a one-batch loss either: both are persisted and ride on
490
+ * 400 is non-retryable — the uploader bisects the batch and drops the event that fails. For
491
+ * `user_id` and `group_id` that is not a one-event loss either: both are persisted and ride on
437
492
  * every subsequent event, so a single over-long id silently destroys everything that user sends
438
493
  * until reset(). A JWT or a concatenated composite key passed as a user id does it.
439
494
  *
440
495
  * Truncating instead would keep the events but silently merge two users sharing a 255-char
441
496
  * prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is
442
- * the rule throughout: such an event would 400 and take the whole batch with it.
497
+ * the rule throughout: such an event would 400 and be dropped at upload, after a bisection.
443
498
  */
499
+ /** Client traits as sent: `$` keys dropped, then sanitised like event properties. */
500
+ private traits;
444
501
  private tooLong;
445
- page(name?: string, properties?: Properties): void;
502
+ /** `options.type` is sent as `$page_type` (API_SPEC §2). */
503
+ page(name?: string, properties?: Properties, options?: PageOptions): void;
504
+ /**
505
+ * `page()` without the `$`-key check, for the SDK's own integrations. Not part of the public
506
+ * API: the Shopify pixel sends checkout page views with `$checkout_step` and
507
+ * `$shopify_client_id`, which a public `page()` would now drop as reserved. Still a manual
508
+ * view — it is a call, not autocapture.
509
+ *
510
+ * Advances navigation state even for an explicit call, so an app that drives pageviews by hand
511
+ * (no autocapture) still gets previous_url and counter — and claims the URL so autocapture
512
+ * cannot emit a second view for the same page.
513
+ */
514
+ pageInternal(name?: string, properties?: Properties, options?: PageOptions): void;
446
515
  /**
447
516
  * `$web_vitals`, once per page, on the first time the tab is hidden.
448
517
  *
@@ -456,13 +525,15 @@ declare class DepsmithSdkClient {
456
525
  */
457
526
  private emitWebVitals;
458
527
  /** Alias of page() — unified mobile naming. */
459
- screen(name?: string, properties?: Properties): void;
528
+ screen(name?: string, properties?: Properties, options?: PageOptions): void;
460
529
  identify(userId: string, traits?: Properties): void;
461
530
  alias(aliasId: string): void;
462
531
  reset(): void;
463
532
  group(groupId: string, traits?: Properties): void;
464
533
  setGroupTraits(traits: Properties): void;
465
534
  setProperty(key: string, value: Properties[string]): void;
535
+ /** The shared tail of setProperty / setOnceProperty: remember it locally, emit the operator. */
536
+ private setUserProp;
466
537
  /**
467
538
  * Sets a property only if this device has not already set it.
468
539
  *
@@ -541,16 +612,21 @@ declare class DepsmithSdkClient {
541
612
  */
542
613
  private persistNow;
543
614
  /**
544
- * Queues an event and re-arms the teardown drain.
545
- *
546
- * `drained` exists only to stop `pagehide` and `visibilitychange`→hidden running the
547
- * same drain twice on one navigation. It must not outlive the work it covered: on
548
- * desktop, `visibilitychange`→hidden fires on an ordinary tab switch, and a backgrounded
549
- * tab keeps capturing (the batch-interval timer, `online`, a host-driven `track()`). If
550
- * that tab is then closed without ever becoming visible again, a latch left set would
551
- * skip both the final `sendBeaconAll()` and the teardown write, losing everything
552
- * captured while hidden — a correctness hole opened by a pure optimisation.
615
+ * Device signals (fingerprint, Client Hints, position) may be read and sent: not COPPA mode,
616
+ * and consent granted — `canUpload()` is false while pending, after opt-out and under DNT.
617
+ * The ONE gate for both the reads below and the emission in `contextOptions()` (#87).
553
618
  */
619
+ private deviceSignals;
620
+ /**
621
+ * Starts the once-per-document device-signal reads (high-entropy Client Hints, and the
622
+ * geolocation permission query + position), off the capture path — only when their results
623
+ * could be sent. Under pending or denied consent, or DNT, nothing is read; `optIn()` calls
624
+ * this again. Defaults are unchanged: this only skips reads whose results would be discarded.
625
+ * The geolocation gate is re-checked before every later read (permission change, stale-fix
626
+ * refresh), so `optOut()` stops those too.
627
+ */
628
+ private primeDeviceSignals;
629
+ /** Queues an event and re-arms the teardown drain — see {@link BrowserLifecycle.rearm}. */
554
630
  private enqueueEvent;
555
631
  /**
556
632
  * The single entry point for starting an upload.
@@ -562,10 +638,12 @@ declare class DepsmithSdkClient {
562
638
  * exists to remove, reappearing in the exact case that matters most (a backed-up queue).
563
639
  */
564
640
  private flushUploads;
641
+ /** Starts an upload when there is something to send and consent allows it. */
642
+ private flushIfQueued;
565
643
  /**
566
- * Fingerprinting is opt-in and privacy-gated: it requires explicit config, granted
567
- * consent (consent.current is 'denied' under DNT and never 'granted' while pending),
568
- * and non-COPPA mode.
644
+ * Fingerprinting is on by default (opt-out via `deviceFingerprinting: false`) and
645
+ * privacy-gated: it requires granted consent (consent.current is 'denied' under DNT and
646
+ * never 'granted' while pending) and non-COPPA mode.
569
647
  */
570
648
  private contextOptions;
571
649
  /**
@@ -591,23 +669,46 @@ declare class DepsmithSdkClient {
591
669
  /**
592
670
  * Config drift (guidelines §12): events queued under a different apiKey belong to
593
671
  * another project — drop them rather than misattribute. Fingerprint, not raw key.
672
+ * The upload pause goes too: a 401 or Retry-After for that key says nothing about this one.
594
673
  */
595
674
  private detectConfigDrift;
675
+ /** The synchronous store. IndexedDB is never returned here — see the constructor. */
596
676
  private pickStorage;
597
677
  private enqueueSessionEnd;
598
678
  /**
599
679
  * Announces a session the SDK just observed beginning.
600
680
  *
601
- * Consent-gated for the same reason as enqueueSessionEnd: the visibilitychange resume
602
- * path reaches this without going through capture(). Under `pending` consent
603
- * canCapture() is true, so it is queued and held — matching capture() exactly.
604
- *
605
681
  * Not emitted by reset()/rotate() (an explicit user action, not an observed boundary)
606
682
  * nor by peek()'s mint-if-absent branch (analytics from a getter).
607
683
  */
608
684
  private enqueueSessionStart;
609
- private startFlushTimer;
610
- private attachLifecycle;
685
+ /**
686
+ * `$session_start` / `$session_end`, built in one place: the two envelopes differ only in
687
+ * their name, their timestamp and the fingerprint components the opening one carries.
688
+ */
689
+ private enqueueSessionBoundary;
690
+ /**
691
+ * Stamps session activity and emits the boundary events that revealed. The one place a
692
+ * session is touched, for capture() and for the tab-resume path alike: the resume path used
693
+ * to emit both boundaries with no sample check, so at `sampleRate: 0.1` nine in ten resumed
694
+ * sessions reached the warehouse as a bare `$session_start` with nothing after it.
695
+ *
696
+ * Order is load-bearing (API_SPEC §5): the old session's end precedes the new session's
697
+ * start, and both precede the event that triggered the rotation.
698
+ *
699
+ * Each boundary follows ITS OWN session's sample decision, not the current event's: the
700
+ * ending and starting sessions have different ids and can therefore decide differently, and
701
+ * an exempt $identify must not drag a boundary event into an out-of-sample session.
702
+ */
703
+ private touchSession;
704
+ /**
705
+ * `visibilitychange`→visible: run the session-timeout check.
706
+ *
707
+ * Not at all while capture is denied. capture() returns before touching the session in that
708
+ * state; this path did not, so every refocus by an opted-out or DNT visitor wrote a session id
709
+ * and an activity timestamp to storage.
710
+ */
711
+ private resumeSession;
611
712
  /** Lazily loads the autocapture engine so the core bundle stays <10KB gz. */
612
713
  private startAutocapture;
613
714
  private guard;
@@ -621,12 +722,13 @@ declare class DepsmithSdkClient {
621
722
  * DepsmithSdk.track('button_clicked', { color: 'red' });
622
723
  *
623
724
  * Re-init with the same apiKey is a no-op; a different apiKey replaces the client (API_SPEC §2).
725
+ * Without a `window` (server rendering) init() does nothing and returns null — see below.
624
726
  */
625
727
  declare const DepsmithSdk: {
626
728
  init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null;
627
729
  track: (name: string, properties?: Properties) => void;
628
- page: (name?: string, properties?: Properties) => void;
629
- screen: (name?: string, properties?: Properties) => void;
730
+ page: (name?: string, properties?: Properties, options?: PageOptions) => void;
731
+ screen: (name?: string, properties?: Properties, options?: PageOptions) => void;
630
732
  identify: (userId: string, traits?: Properties) => void;
631
733
  alias: (aliasId: string) => void;
632
734
  reset: () => void;
@@ -652,4 +754,4 @@ declare const DepsmithSdk: {
652
754
  shutdown(): void;
653
755
  };
654
756
 
655
- 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 };
757
+ 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 PageLocation, type PageNames, type PageOptions, type Properties, type PropertyValue, type Scheduler, type TrackingOptions, type UserPropertyOps, idleScheduler, syncScheduler };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var tt=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],F="depsmith_campaign",j="depsmith_referrer";function rt(r){try{return new URL(r).host||void 0}catch{return}}var P=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(F)??{},this.referrer=this.read(j)??{}}read(e){try{let t=this.storage.get(e);if(!t)return null;let i=JSON.parse(t);return i&&typeof i=="object"?i:null}catch{return null}}write(e,t){try{this.storage.set(e,JSON.stringify(t))}catch{}}recordLanding(e,t){let i,n;try{let d=new URL(e);i=d.searchParams,n=d.host}catch{return}let s={};for(let[d,c]of tt){let l=i.get(d);l&&(s[c]=l)}Object.keys(s).length>0&&(this.campaign=s,this.write(F,s));let o=t?rt(t):void 0,u=!!o&&o!==n,a=!1;u&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=u?o:"$direct",u&&(this.referrer.initial_url=t),a=!0),a&&this.write(j,this.referrer)}campaignBlock(){return Object.keys(this.campaign).length>0?{...this.campaign}:void 0}referrerBlock(){return Object.keys(this.referrer).length>0?{...this.referrer}:void 0}clear(){this.campaign={},this.referrer={};try{this.storage.remove(F),this.storage.remove(j)}catch{}}};var X=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=be(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=be(this.currentUrl,e)?"internal":"external"),this.currentUrl=e,this.counter+=1,!0)}tracking(){let e={};return this.previousUrl!==void 0&&(e.previous_url=this.previousUrl),this.previousType!==void 0&&(e.previous_type=this.previousType),this.counter>0&&(e.counter=this.counter),e}get pageCount(){return this.counter}get current(){return this.currentUrl}resetForNewSession(){this.counter=this.currentUrl===void 0?0:1}},A=class{constructor(e){this.sink=e;this.pages=new X;this.enteredAt=0}start(e,t){this.pages.recordPage(e,t),this.enteredAt=this.sink.now()}get pageCount(){return this.pages.pageCount}recordExplicit(){this.record(),this.lastViewed=Y()}autoPageView(){this.record();let e=Y();if(e!==void 0&&e===this.lastViewed)return;this.lastViewed=e;let t=typeof document<"u"?document.title:"";this.sink.capture("$page_view","page_view",{name:t||"Unknown",$page_counter:this.pages.pageCount})}leave(e){let t=this.pages.current;if(t===void 0)return;let i={$page_duration_ms:Math.max(0,this.sink.now()-this.enteredAt)};e!==void 0&&(i.$page_max_scroll=e),this.leaving=t;try{this.sink.capture("$page_leave","page_leave",i)}finally{this.leaving=void 0}}restored(e){e&&(this.enteredAt=this.sink.now())}newSession(){this.pages.resetForNewSession()}tracking(){let e=this.pages.tracking();return this.leaving===void 0?e:{...e,url:this.leaving,path:it(this.leaving),domain:G(this.leaving),url_base:W(this.leaving)}}record(){let e=Y();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now())}};function Y(){if(!(typeof window>"u"||!window.location))return window.location.href}function be(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function it(r){try{return new URL(r).pathname||void 0}catch{return}}function G(r){try{return new URL(r).host||void 0}catch{return}}function W(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}function Se(){return import("./autocapture.js")}var H=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["idfv","device","idfv"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]],nt=Object.fromEntries(H.map(([r])=>[r,!0]));function we(r){let e={...nt};if(!r)return e;for(let[t]of H)r[t]===!1&&(e[t]=!1);return e}function ke(r,e){let t=r;for(let[i,n,s]of H){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 Q={clicks:"interactive",forms:!0,scrolls:!0,pageviews:!0,ignoredSelectors:[],selectorMaxDepth:5,attributes:[]};function st(r){return r===void 0?Q.clicks:r===!0?"interactive":r}function _e(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?Q:r.autocapture&&typeof r.autocapture=="object"?{...Q,...r.autocapture,clicks:st(r.autocapture.clicks)}:!1;return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:J(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)?J(r.sampleRate,0,1):1,sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:J(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:we(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage"}}function J(r,e,t){return Math.min(Math.max(r,e),t)}function Z(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 xe(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 ot(r){return xe(r).toString(36)}function Pe(r){return xe(r)/4294967296}function ee(r){return Z(r)+ot(r)}var te={},Ae=!1;function Ee(){if(!Ae){Ae=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{te=e}).catch(()=>{})}catch{}}}function re(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=ct(e,t);i&&(r.browser=i);let n=lt(e);if(n){let u=dt(n.name,te.platformVersion);r.os=u?{...n,version:u}:n}let s=ft(e,t);s&&(r.deviceType=s);let o=at(e,n);return o&&(r.device=o),r}function at(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=te.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 dt(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 Oe(t)}}var ut=[{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 ct(r,e){for(let i of ut){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 pt=[{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 lt(r){for(let e of pt){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Oe((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Oe(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function ft(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 E=null,O=null;function Ce(){return O!==null||(O=gt()),O}function C(){return E!==null||(E=ee(Ce().map(r=>r.value).join("|"))),E}function Te(){let r={};for(let e of Ce())r[`$fp_${e.name}`]=e.value;return r}function gt(){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:${ht()}`})}catch{}return r}function ht(){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(),ee(r.toDataURL())):""}catch{return""}}function $e(){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 T=null,Re=0,Ie=!1,S=!1,Me=null;function Ue(){if(!Ie){Ie=!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=>{Me=e,e.state==="granted"&&ie(),e.onchange=()=>{e.state==="granted"?ie():T=null}}).catch(()=>{})}catch{}}}function ie(){if(!S){S=!0;try{navigator.geolocation.getCurrentPosition(r=>{S=!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),T=n,Re=Date.now()},()=>{S=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{S=!1}}}function De(){if(T)return Date.now()-Re>3e5&&Me?.state==="granted"&&ie(),{...T}}var se="@depsmith/depsmith-sdk",y="0.7.0",ne=null;function mt(){if(ne)return ne;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ne=r,r}function w(r={}){let e={library:{name:se,version:y}};m(()=>{if(typeof window<"u"&&window.location){let t=window.location.href;e.page={url:t,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,domain:G(t),url_base:W(t),...r.page??{}}}}),m(()=>{typeof window<"u"&&window.screen&&(e.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),m(()=>{let t=mt();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)}),m(()=>{let{deviceType:t}=re();t&&(e.device={...e.device,type:t})}),m(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),m(()=>{r.fingerprint&&vt(e)}),m(()=>{if(r.geolocation){let t=De();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:se,version:y}}}catch{}return r.tracking&&ke(e,r.tracking),e}function vt(r){let{browser:e,os:t,deviceType:i,device:n}=re();e&&(r.browser=e),t&&(r.os=t);let s={...r.device};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=$e();o.type&&(r.network={...r.network,type:o.type})}function m(r){try{r()}catch{}}function Ne(){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 oe="depsmith_consent",$=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(oe);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(oe,"granted")}optOut(){this.state="denied",this.storage.set(oe,"denied")}};var k=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},yt=r=>r();var I="depsmith_queue",bt=512*1024,ae=2,St=new Set(["identify","alias","group"]);function wt(r){return St.has(r?.event_type)}var R=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??bt,this.schedule=n.schedule??k,this.restore()}restore(){try{let e=this.storage.get(I);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(I)}}reset(e){this.events=e,this.sizes=e.map(t=>Le(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?ae:this.sizeSum+(this.events.length-1)+ae}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(I,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=Le(e);if(t+ae>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(!wt(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 u=this.events[o];if(t.has(u.event_id))continue;let a=this.sizes[o];i.push(u),n.push(a),s+=a}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(I)}};function Le(r){return JSON.stringify(r).length}function f(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 b(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 qe=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer"],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)}},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{}}},kt=new Set(["depsmith_anonymous_id"]),U=class{constructor(e,t,i=kt){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=_t(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 _t(r,e){let t=b(r),i=b(e);return t===null||i===null?null:t<=i?r:e}var de=class{constructor(e,t=qe){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(()=>{})}};var ue=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{}}},_=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 u=s.result;o.result.forEach((a,d)=>{let c=u[d];c!==void 0&&(this.snapshot.set(c,a),this.mirror.has(c)||this.mirror.set(c,a))}),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{}})}};function Ke(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new ue(window.localStorage)}}catch{}return new v}var ce="depsmith_anonymous_id",pe="depsmith_user_id",le="depsmith_group_id",D="depsmith_user_props",N=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(ce);return e||(e=f(this.clock.now()),this.storage.set(ce,e)),e}get userId(){return this.storage.get(pe)}get groupId(){return this.storage.get(le)}identify(e){this.storage.set(pe,e)}setGroup(e){this.storage.set(le,e)}getUserProps(){try{return JSON.parse(this.storage.get(D)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(D,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(D,JSON.stringify(t))}reset(){this.storage.remove(pe),this.storage.remove(le),this.storage.remove(D);let e=f(this.clock.now());return this.storage.set(ce,e),e}};var Ve="depsmith_session",L=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(Ve);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=b(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(Ve,JSON.stringify(e)))}mint(e){let t={id:f(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=b(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 g(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=xt(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function fe(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 xt(r,e){let t=fe(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=fe(n);i.push(s!==void 0?s:Be(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 u=fe(o);i[String(s)]=u!==void 0?u:Be(o),n++}return i}}}function Be(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function Pt(r){return r>=500}function ze(r){let e={};try{let t=new URL(r,typeof location<"u"?location.href:void 0);e.$net_url=`${t.origin}${t.pathname}`,t.search.length>1&&(e.$net_query=t.search.slice(1)),t.hash.length>1&&(e.$net_fragment=t.hash.slice(1))}catch{e.$net_url=r.slice(0,255)}return e}function At(r){try{let e=r?.get("content-length");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}catch{return}}function Fe(r,e){if(typeof fetch!="function")return{stop:()=>{}};let t=fetch,i=r.replace(/\/+$/,""),n=async(s,o)=>{let u=Date.now(),a=typeof s=="string"?s:s instanceof URL?s.href:s.url,d=o?.method??(typeof s=="object"&&"method"in s?s.method:"GET");if(a.startsWith(i))return t(s,o);try{let c=await t(s,o);return Pt(c.status)&&e({...ze(a),$net_method:String(d).toUpperCase(),$net_status:c.status,$net_start:u,$net_end:Date.now(),$net_duration_ms:Date.now()-u,...Et(o,c)}),c}catch(c){throw e({...ze(a),$net_method:String(d).toUpperCase(),$net_error_message:c instanceof Error?c.message.slice(0,255):"network error",$net_start:u,$net_end:Date.now(),$net_duration_ms:Date.now()-u}),c}};return globalThis.fetch=n,{stop:()=>{globalThis.fetch===n&&(globalThis.fetch=t)}}}function Et(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=At(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function q(r){return Math.round(r)}function je(){let r,e,t,i=0,n=!1,s,o=[],u=(a,d)=>{try{let c=new PerformanceObserver(l=>d(l.getEntries()));c.observe({type:a,buffered:!0}),o.push(c)}catch{}};u("largest-contentful-paint",a=>{let d=a[a.length-1];d&&(r=q(d.startTime))}),u("paint",a=>{for(let d of a)d.name==="first-contentful-paint"&&(e=q(d.startTime))}),u("layout-shift",a=>{for(let d of a)d.hadRecentInput||(i+=d.value??0,n=!0)}),u("event",a=>{for(let d of a){let c=q(d.duration);(t===void 0||c>t)&&(t=c)}});try{let[a]=performance.getEntriesByType("navigation"),d=a;d?.responseStart!==void 0&&d.responseStart>0&&(s=q(d.responseStart))}catch{}return{snapshot(){let a={};return r!==void 0&&(a.$wv_lcp=r),e!==void 0&&(a.$wv_fcp=e),t!==void 0&&(a.$wv_inp=t),n&&(a.$wv_cls=Math.round(i*1e3)/1e3),s!==void 0&&(a.$wv_ttfb=s),a},hasAny(){return r!==void 0||e!==void 0||t!==void 0||n||s!==void 0},stop(){for(let a of o.splice(0))try{a.disconnect()}catch{}}}}var ge="depsmith_super_props";function Ye(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):r.startsWith("$")?(e.warn(`register: "$"-prefixed keys are reserved; ignored "${r}"`),!1):!0}var K=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(ge);if(i){let n=JSON.parse(i);n&&typeof n=="object"&&!Array.isArray(n)&&(this.properties=n)}}catch{}}register(e){let t=!1;for(let[i,n]of Object.entries(e))Ye(i,this.logger)&&(this.properties[i]=n,t=!0);t&&this.persist()}registerOnce(e){let t=!1;for(let[i,n]of Object.entries(e))Ye(i,this.logger)&&(Object.prototype.hasOwnProperty.call(this.properties,i)||(this.properties[i]=n,t=!0));t&&this.persist()}unregister(e){Object.prototype.hasOwnProperty.call(this.properties,e)&&(delete this.properties[e],this.persist())}clear(){if(Object.keys(this.properties).length!==0){this.properties={};try{this.storage.remove(ge)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(ge,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var Ot=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],Xe=50,Ge=200;function he(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 u=g(o,e),a={};for(let[d,c]of Object.entries(u))n(d,s)&&(a[d]=c);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[u,a]of Object.entries(r.$add)){if(o>=Xe){e.debug(`$add over ${Xe} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${u}" is not finite; dropped`);continue}n(u,"$add")&&(s[u]=a,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>=Ge){e.debug(`$unset over ${Ge} 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 V(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var We={now:()=>Date.now()};function h(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function He(r){return r===0||r===408||r===429||r>=500}var Ct=1e3,Tt=32e3;function Je(r,e=Math.random){let t=Math.min(Ct*2**r,Tt);return Math.round(e()*t)}async function $t(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:a,value:d}=await i.read();if(a)break;n.push(d)}let s=n.reduce((a,d)=>a+d.length,0),o=new Uint8Array(new ArrayBuffer(s)),u=0;for(let a of n)o.set(a,u),u+=a.length;return o}function Qe(r){let e=[];for(let t of r)e.push(t.event_id);return e}var It=3e4,Rt=6e4,Mt=10;function Ut(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var B=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(Qe(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(!He(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(Je(n))}return i?t?.ok():t?.fail(),"requeue"}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:h(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 $t(t),o["Content-Encoding"]="gzip"}catch{s=t}let u=Ut(s)<=Rt;u||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let a={method:"POST",headers:o,body:s,keepalive:u};return i&&(a.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,a)).status}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:It}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<Mt;){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(Qe(t)),e++}}catch{}}};var me="depsmith_net_breaker";function Ze(r,e){let t=!1,i=0,n=0,s=3e5,o=(d,c,l)=>typeof d=="number"&&d===d?Math.min(Math.max(d,c),l):c,u=()=>{if(!t){t=!0;try{let d=JSON.parse(r.get(me)??"0");if(!Array.isArray(d))return;i=o(d[0],0,3),n=o(d[1],0,e.now()+36e5),s=o(d[2],3e5,36e5)}catch{}}},a=()=>{try{i?r.set(me,JSON.stringify([i,n,s])):r.remove(me)}catch{}};return{open:()=>(u(),e.now()<n),suspect:()=>(u(),i>0),fail:()=>{u(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),a()},ok:()=>{u(),i&&(i=n=0,s=3e5,a())}}}var z=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 et=255,x=class{constructor(e,t={}){this.pageLife=new A({now:()=>this.clock.now(),capture:(e,t,i)=>this.capture(e,t,i)});this.vitalsReported=!1;this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=_e(e),this.logger=new z(this.config.debug),this.clock=t.clock??We,this.storage=t.storage??this.pickStorage(),this.contextProvider=t.contextProvider;let i=this.config.childSafeMode?new v:this.config.storage==="memory"?this.storage:new U(this.storage,new M(this.config.cookieDomain||void 0));this.identity=new N(i,this.clock),this.session=new L(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new $(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??Ne())),this.attribution=new P(i),this.superProperties=new K(this.storage,this.logger),!this.contextProvider&&typeof window<"u"&&window.location&&(this.attribution.recordLanding(window.location.href,typeof document<"u"?document.referrer:""),this.pageLife.start(window.location.href,typeof document<"u"?document.referrer:"")),this.queue=new R(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&Ee(),this.config.geolocation&&!this.config.childSafeMode&&Ue(),this.storage instanceof _&&(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 B(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:Ze(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<=et?!1:(this.logger.warn(`${t} exceeds ${et} characters (got ${e.length}); dropped`),!0)}page(e,t){this.guard(()=>{this.pageLife.recordExplicit();let i=e??(typeof document<"u"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...t,name:i,$page_counter:this.pageLife.pageCount})})}emitWebVitals(){this.vitalsReported||!this.vitals?.hasAny()||(this.vitalsReported=!0,this.capture("$web_vitals","track",this.vitals.snapshot()))}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=g(t,this.logger);this.capture("$identify","identify",void 0,i,V("$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.attribution.clear(),this.superProperties.clear(),this.logger.debug("reset: identity, session and attribution cleared")})}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,g(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,g(e,this.logger))})}setProperty(e,t){this.guard(()=>{this.identity.setUserProp(e,t);let i=g({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,V("$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=g({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,V("$set_once",i))})}unsetProperty(e){this.guard(()=>{this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},he({$unset:[e]},this.logger))})}register(e){this.guard(()=>this.superProperties.register(e))}registerOnce(e){this.guard(()=>this.superProperties.registerOnce(e))}unregister(e){this.guard(()=>this.superProperties.unregister(e))}setUserProperties(e){this.guard(()=>{let t=he(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,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:Pe(`${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.startedSession&&this.pageLife.newSession(),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 u=this.clock.now(),a=this.contextOptions(),d={event_id:f(u),event:e,event_type:t,timestamp:h(u),session_id:o.sessionId,session_started_at:h(o.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...w(a),traits:n}:w(a),platform:"web",sdk_version:y};s&&(d.user_properties=s);let c={...this.config.defaultProperties,...this.superProperties.current(),...g(i,this.logger)};Object.keys(c).length>0&&(d.properties=c);let l=this.identity.userId;l&&(d.user_id=l);let ye=this.identity.groupId;ye&&(d.group_id=ye),a.fingerprint&&(d.device_id=C()),this.enqueueEvent(d),this.logger.debug(`captured ${e}`,d),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",t=Z(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 _:Ke()}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:f(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:h(e.lastActivityAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:w(t),platform:"web",sdk_version:y},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=C()),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:f(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:h(e.startedAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:w(t),platform:"web",sdk_version:y},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=C()),t.fingerprint&&(i.properties={...i.properties,...Te()}),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.guard(()=>this.emitWebVitals()),this.guard(()=>this.leaveOnUnload?.()),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.pageLife.newSession(),this.enqueueSessionStart(s.startedSession))}},i=s=>{this.drained=!1,this.pageLife.restored(s.persisted)},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;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=je(),this.teardownFns.push(()=>this.vitals?.stop()));let t=Fe(this.config.endpoint,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),Se().then(i=>{i&&(this.teardownFns.push(i.startAutocapture(e,{emit:n=>this.autocapture(n),page:()=>this.guard(()=>this.pageLife.autoPageView()),pageLeave:n=>this.guard(()=>this.pageLife.leave(n)),armUnloadLeave:n=>{this.leaveOnUnload=n}})),this.teardownFns.push(()=>{this.leaveOnUnload=void 0}))}).catch(i=>this.logger.debug("autocapture load failed",i))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var p=null,ve=null,Hr={init(r,e){try{return p&&ve===r.apiKey||(p?.shutdown(),p=new x(r,e),ve=r.apiKey),p}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>p?.track(r,e),page:(r,e)=>p?.page(r,e),screen:(r,e)=>p?.screen(r,e),identify:(r,e)=>p?.identify(r,e),alias:r=>p?.alias(r),reset:()=>p?.reset(),group:(r,e)=>p?.group(r,e),setGroupTraits:r=>p?.setGroupTraits(r),setProperty:(r,e)=>p?.setProperty(r,e),setOnceProperty:(r,e)=>p?.setOnceProperty(r,e),unsetProperty:r=>p?.unsetProperty(r),setUserProperties:r=>p?.setUserProperties(r),register:r=>p?.register(r),registerOnce:r=>p?.registerOnce(r),unregister:r=>p?.unregister(r),optIn:()=>p?.optIn(),optOut:()=>p?.optOut(),flush:()=>p?.flush()??Promise.resolve(),getAnonymousId:()=>p?.getAnonymousId(),getSessionId:()=>p?.getSessionId(),setSessionId:(r,e)=>p?.setSessionId(r,e),shutdown(){p?.shutdown(),p=null,ve=null}};export{de as AsyncMirrorAdapter,qe as DEPSMITH_SDK_STORAGE_KEYS,Hr as DepsmithSdk,x as DepsmithSdkClient,k as idleScheduler,yt as syncScheduler};
1
+ var Ct=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],ne="depsmith_campaign",se="depsmith_referrer";function Tt(r){try{return new URL(r).host||void 0}catch{return}}var N=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(ne)??{},this.referrer=this.read(se)??{}}read(e){try{let t=this.storage.get(e);if(!t)return null;let i=JSON.parse(t);return i&&typeof i=="object"?i:null}catch{return null}}write(e,t){try{this.storage.set(e,JSON.stringify(t))}catch{}}recordLanding(e,t){let i,n;try{let d=new URL(e);i=d.searchParams,n=d.host}catch{return}let s={};for(let[d,p]of Ct){let c=i.get(d);c&&(s[p]=c)}Object.keys(s).length>0&&(this.campaign=s,this.write(ne,s));let o=t?Tt(t):void 0,u=!!o&&o!==n,a=!1;u&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=u?o:"$direct",u&&(this.referrer.initial_url=t),a=!0),a&&this.write(se,this.referrer)}campaignBlock(){return Object.keys(this.campaign).length>0?{...this.campaign}:void 0}referrerBlock(){return Object.keys(this.referrer).length>0?{...this.referrer}:void 0}clear(){this.campaign={},this.referrer={};try{this.storage.remove(ne),this.storage.remove(se)}catch{}}};var oe=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=Ne(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=Ne(this.currentUrl,e)?"internal":"external"),this.currentUrl=e,this.counter+=1,!0)}tracking(){let e={};return this.previousUrl!==void 0&&(e.previous_url=this.previousUrl),this.previousType!==void 0&&(e.previous_type=this.previousType),this.counter>0&&(e.counter=this.counter),e}get pageCount(){return this.counter}get current(){return this.currentUrl}resetForNewSession(){this.counter=this.currentUrl===void 0?0:1}},M=class{constructor(e,t={autocapture:!1}){this.sink=e;this.pages=new oe;this.enteredAt=0;this.left=!1;this.rules=$t(t.pageNames),this.byHref=!!t.autocapture&&t.autocapture.pageviews==="all"}start(e,t){this.pages.recordPage(e,t),this.enteredAt=this.sink.now()}get pageCount(){return this.pages.pageCount}recordExplicit(){this.record(),this.lastViewed=this.pageKey(),this.autoViewed=void 0}manual(e,t,i){let n=this.pending;if(n&&this.keyOf(n.location)===this.pageKey())this.discardPending();else{this.flushPending();let s=this.autoViewed;if(this.autoViewed=void 0,s&&s.url===Ie()&&this.sink.now()-s.at<=Rt)return}this.recordExplicit(),this.sink.capture("$page_view","page_view",{...t,...$e({source:"manual",name:e,type:i},this.rules),$page_counter:this.pages.pageCount})}autoPageView(e){this.flushPending(),this.record();let t=this.pageKey();if(t!==void 0&&t===this.lastViewed)return;this.lastViewed=t;let i=this.pages.pageCount;if(!e){this.emitView(location,i);return}let n=location.href,s={at:this.sink.now(),counter:i,location:new URL(n),page:{url:n,path:location.pathname,referrer:document.referrer,domain:D(n),url_base:U(n),...this.pages.tracking()},cancel:()=>{}};this.pending=s,s.cancel=e(document.title,()=>this.flushPending())}flushPending(){let e=this.pending;e&&(this.pending=void 0,e.cancel(),this.emitView(e.location,e.counter,e))}discardPending(){this.pending?.cancel(),this.pending=void 0}emitView(e,t,i){let n=document.title;this.autoViewed={url:e.href,at:this.sink.now()},this.sink.capture("$page_view","page_view",{...$e({source:"auto",location:e,title:n},this.rules),$page_counter:t},i?.at,i&&{...i.page,title:n})}leave(e){this.flushPending();let t=this.pages.current;if(t===void 0||this.left)return;this.left=!0;let i={$page_duration_ms:Math.max(0,this.sink.now()-this.enteredAt)};e!==void 0&&(i.$page_max_scroll=e),this.leaving=t;try{this.sink.capture("$page_leave","page_leave",i)}finally{this.leaving=void 0}}restored(e){e&&(this.left=!1,this.enteredAt=this.sink.now())}newSession(){this.pages.resetForNewSession()}tracking(){let e=this.pages.tracking();return this.leaving===void 0?e:{...e,url:this.leaving,path:Nt(this.leaving),domain:D(this.leaving),url_base:U(this.leaving)}}pageKey(){let e=globalThis.location;return e&&this.keyOf(e)}keyOf(e){return this.byHref?e.href:e.pathname}record(){let e=Ie();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now(),this.left=!1)}},Rt=2e3;function $e({source:r,name:e,type:t,location:i=globalThis.location,title:n=globalThis.document?.title},s){let o=i&&s?.(i),u=t?.trim()||o?.type;return{$page_name:e?.trim()||o?.name.trim()||n?.trim()||i?.pathname||"Unknown",...u?{$page_type:u}:{},$page_source:r}}function $t(r){if(typeof r=="function")return t=>{try{let i=r(t);return typeof i=="string"?{name:i}:void 0}catch{return}};if(!r||typeof r!="object")return;let e=(Array.isArray(r)?r:Object.entries(r)).map(([t,i])=>[typeof t=="string"&&typeof i=="string"&&It(t),i]);return t=>{let i=Me(t.pathname);for(let[n,s]of e)if(n&&n.test(i))return{name:s,type:s}}}function It(r){let e=Me(r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\*|\*\*?/g,t=>t==="*"?"[^/]+":t==="**"?".*":"(?:/.*)?");return new RegExp(`^${e}$`)}function Me(r){return r.replace(/(.)\/$/,"$1")}function Ie(){if(!(typeof window>"u"||!window.location))return window.location.href}function Ne(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function Nt(r){try{return new URL(r).pathname||void 0}catch{return}}function D(r){try{return new URL(r).host||void 0}catch{return}}function U(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}function De(r){if(typeof window>"u"||typeof document>"u")return;let e=setInterval(()=>r.flushIfQueued(),r.intervalMs);e.unref?.();let t=!1,i,n=()=>{let a=i;clearTimeout(a),i=void 0,r.guard(()=>r.vitals()),r.guard(()=>r.leave()),!(t&&!a)&&(t=!0,r.beacon(),r.persistNow())},s=()=>{if(document.visibilityState==="hidden"){if(t)return;r.guard(()=>r.vitals()),t=!0,r.persistNow(),i=setTimeout(()=>{i=void 0,r.flushIfQueued()},0)}else clearTimeout(i),t=!1,r.resume()},o=a=>{t=!1,r.restored(a.persisted)},u=()=>r.online();return window.addEventListener("pagehide",n),window.addEventListener("pageshow",o),document.addEventListener("visibilitychange",s),window.addEventListener("online",u),{rearm:()=>{t=!1},stop:()=>{clearInterval(e),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",o),document.removeEventListener("visibilitychange",s),window.removeEventListener("online",u),clearTimeout(i)}}}function Ue(){return import("./autocapture.js")}var ae=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["idfv","device","idfv"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screenSize","screen_size"],["timezone","timezone"],["userAgent","user_agent"]],Mt=Object.fromEntries(ae.map(([r])=>[r,!0]));function Le(r){let e={...Mt};if(!r)return e;for(let[t]of ae)r[t]===!1&&(e[t]=!1);return e}function Ve(r,e){let t=r;for(let[i,n,s]of ae){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 Ke={clicks:"interactive",forms:!0,scrolls:!1,pageviews:"path",ignoredSelectors:[],selectorMaxDepth:5,selectorIgnore:[],attributes:[]};function Be(r){if(r===!0)return Ke;if(!r||typeof r!="object")return!1;let e={...Ke};for(let[n,s]of Object.entries(r))s!==void 0&&(e[n]=s);let{clicks:t,pageviews:i}=e;return e.clicks=t==="all"?"all":t?"interactive":!1,e.pageviews=i==="all"?"all":i?"path":!1,e}function qe(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=Be(r.autocapture);return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:P(r.batchSize,20,1,500),batchIntervalMs:P(r.batchIntervalMs,6e4,1e3,2**31-1),maxQueueSize:P(r.maxQueueSize,1e3,1),maxQueueBytes:P(r.maxQueueBytes,512*1024,4096),sessionTimeoutMs:P(r.sessionTimeoutMs,18e5,6e4),sampleRate:ze(r.sampleRate,1,0,1),sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:P(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,scrubUrls:r.scrubUrls??!1,trackingOptions:Le(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage",pageNames:r.pageNames}}function ze(r,e,t,i=1/0){return Math.min(Math.max(Number.isFinite(r)?r:e,t),i)}function P(r,e,t,i){return Math.floor(ze(r,e,t,i))}function ue(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 Fe(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 Dt(r){return Fe(r).toString(36)}function je(r){return Fe(r)/4294967296}function de(r){return ue(r)+Dt(r)}var pe={},Ye=!1;function Xe(){if(!Ye){Ye=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{pe=e}).catch(()=>{})}catch{}}}function ce(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=Kt(e,t);i&&(r.browser=i);let n=qt(e);if(n){let u=Lt(n.name,pe.platformVersion);r.os=u?{...n,version:u}:n}let s=zt(e,t);s&&(r.deviceType=s);let o=Ut(e,n);return o&&(r.device=o),r}function Ut(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=pe.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 Lt(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 We(t)}}var Vt=[{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 Kt(r,e){for(let i of Vt){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 Bt=[{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 qt(r){for(let e of Bt){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:We((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function We(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function zt(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 L=null,V=null;function He(){return V!==null||(V=Ft()),V}function le(){return L!==null||(L=de(He().map(r=>r.value).join("|"))),L}function Qe(){let r={};for(let e of He())r[`$fp_${e.name}`]=e.value;return r}function Ft(){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:${jt()}`})}catch{}return r}function jt(){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(),de(r.toDataURL())):""}catch{return""}}function Ge(){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 A=null,Ze=0,Je=!1,E=!1,et=null,K=()=>!0;function tt(r=K){if(K=r,!Je){Je=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let e=navigator.permissions;if(typeof e?.query!="function")return;e.query({name:"geolocation"}).then(t=>{et=t,t.state==="granted"&&fe(),t.onchange=()=>{t.state==="granted"?fe():A=null}}).catch(()=>{})}catch{}}}function fe(){if(!(E||!K())){E=!0;try{navigator.geolocation.getCurrentPosition(r=>{E=!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),A=n,Ze=Date.now()},()=>{E=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{E=!1}}}function rt(){if(K()||(A=null),!!A)return Date.now()-Ze>3e5&&et?.state==="granted"&&fe(),{...A}}var he="@depsmith/depsmith-sdk",O="0.9.0",ge=null;function Yt(){if(ge)return ge;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ge=r,r}function B(r={}){let e={library:{name:he,version:O}};S(()=>{if(typeof window<"u"&&window.location){let t=window.location.href;e.page={url:t,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,domain:D(t),url_base:U(t),...r.page??{}}}}),S(()=>{typeof window<"u"&&window.screen&&(e.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),S(()=>{let t=Yt();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(()=>{let{deviceType:t}=ce();t&&(e.device={...e.device,type:t})}),S(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),S(()=>{r.fingerprint&&Xt(e)}),S(()=>{if(r.geolocation){let t=rt();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:he,version:O}}}catch{}return r.tracking&&Ve(e,r.tracking),e}function Xt(r){let{browser:e,os:t,deviceType:i,device:n}=ce();e&&(r.browser=e),t&&(r.os=t);let s={...r.device};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=Ge();o.type&&(r.network={...r.network,type:o.type})}function S(r){try{r()}catch{}}function it(){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 me="depsmith_consent",q=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(me);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(me,"granted")}optOut(){this.state="denied",this.storage.set(me,"denied")}};var C=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Wt=r=>r();var v="depsmith_queue",Ht=512*1024,ve=2,Qt=new Set(["identify","alias","group"]);function Gt(r){return Qt.has(r?.event_type)}var z=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??Ht,this.schedule=n.schedule??C,this.restore()}restore(){try{let e=this.storage.get(v);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(v)}}reset(e){this.events=e,this.sizes=e.map(t=>nt(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?ve:this.sizeSum+(this.events.length-1)+ve}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(v,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=nt(e);if(t+ve>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(!Gt(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,t=1/0,i=0){let n=i;for(let s=0;n<this.events.length&&n-i<e&&(s+=this.sizes[n]+1,!(n>i&&s>t));n++);return this.events.slice(i,n)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let u=this.events[o];if(t.has(u.event_id))continue;let a=this.sizes[o];i.push(u),n.push(a),s+=a}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}close(){}clear(){this.reset([]),this.dirty=!1,this.storage.remove(v)}};function nt(r){return JSON.stringify(r).length}var ye=-1,be=0,Jt=67108863;function y(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let n=0;n<16;n++)e[n]=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;let t=(e[6]&7)<<22|e[7]<<14|(e[8]&63)<<8|e[9];r===ye?t=be=be+1&Jt:r>ye&&(ye=r,be=t),e[6]=112|t>>>22,e[7]=t>>>14&255,e[8]=128|t>>>8&63,e[9]=t&255;let i="";for(let n=0;n<16;n++)i+=(e[n]+256).toString(16).slice(1);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function x(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 st=["depsmith_anonymous_id","depsmith_anon_reset_at","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer","depsmith_super_props"],w=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)}},F=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{}}},T="depsmith_anon_reset_at",Zt=new Set(["depsmith_anonymous_id",T]),j=class{constructor(e,t,i=Zt){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=this.pick(t,i);return this.primary.set(e,n),this.secondary.set(e,n),n}pick(e,t){let i=x(e),n=x(t);if(i===null||n===null)return e;let s=[this.primary,this.secondary],o=Math.max(...s.map(a=>Number(a.get(T))||0));o&&s.forEach(a=>a.set(T,`${o}`));let u=i>=o;return u!==n>=o?u?e:t:i<=n?e:t}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)}},Se=class{constructor(e,t=st){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(()=>{})}};var R=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{}}},Y=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 u=s.result;o.result.forEach((a,d)=>{let p=u[d];p!==void 0&&(this.snapshot.set(p,a),this.mirror.has(p)||this.mirror.set(p,a))}),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{}})}};function ot(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new R(window.localStorage)}}catch{}return new w}function at(r,e){return r==="indexeddb"&&typeof indexedDB<"u"?new Y:e}function ut(r,e,t,i,n,s){return r instanceof Y?r.hydrate().then(o=>{try{let u="depsmith_consent";if(o.get(u)==="denied"&&!e.get(u)&&t.optOut(),n||!t.canCapture()){i.clear();return}let a=o.get("depsmith_queue");a&&i.prepend(JSON.parse(a))}catch{s.warn("persisted queue corrupt; discarded")}}):Promise.resolve()}function dt(r){try{let e=JSON.parse(r||"[]");return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.event_id=="string"):null}catch{return null}}var X=class extends z{constructor(...t){super(...t);this.known=new Set(this.ids());this.removed=new Set;this.area=null;this.onStorage=t=>{if(t.key!==v||t.storageArea!==this.area)return;let i=dt(t.newValue);if(!i)return;let n=new Set;for(let o of i)n.add(o.event_id);let s=[];if(this.known.forEach(o=>{n.has(o)||s.push(o)}),s.length!==0){for(let o of s)this.known.delete(o),this.removed.add(o);this.remove(s)}};if(this.storage instanceof R){this.area=this.storage.ls;try{typeof window<"u"&&window.addEventListener("storage",this.onStorage)}catch{}}}ids(){let t=[];for(let i of this.events)t.push(i.event_id);return t}persistNow(){if(!this.dirty)return;this.dirty=!1;let t=new Set(this.ids());this.known.forEach(s=>{t.has(s)||this.removed.add(s)});let i=[],n=new Set;for(let s of dt(this.storage.get(v))??[])n.add(s.event_id),!t.has(s.event_id)&&!this.removed.has(s.event_id)&&i.push(s);this.storage.set(v,JSON.stringify(this.bounded(i).concat(this.events))),this.known=t,this.removed.forEach(s=>{n.has(s)||this.removed.delete(s)})}bounded(t){if(t.length===0)return t;let i=this.maxSize-this.events.length,n=this.maxChars-this.serializedLength(),s=[];for(let o=t.length-1;o>=0&&i>0;o--){let u=JSON.stringify(t[o]).length+1;if(u>n)break;n-=u,i--,s.push(t[o])}return s.reverse()}clear(){super.clear(),this.known.clear(),this.removed.clear()}close(){try{typeof window<"u"&&window.removeEventListener("storage",this.onStorage)}catch{}}};var we="depsmith_anonymous_id",ke="depsmith_user_id",_e="depsmith_group_id",W="depsmith_user_props",H=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(we);return e||(e=y(this.clock.now()),this.storage.set(we,e)),e}get userId(){return this.storage.get(ke)}get groupId(){return this.storage.get(_e)}identify(e){this.storage.set(ke,e)}setGroup(e){this.storage.set(_e,e)}getUserProps(){try{return JSON.parse(this.storage.get(W)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(W,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(W,JSON.stringify(t))}reset(){this.storage.remove(ke),this.storage.remove(_e),this.storage.remove(W);let e=this.clock.now();this.storage.set(T,`${e}`);let t=y(e);return this.storage.set(we,t),t}};var pt="depsmith_session",Q=class{constructor(e,t,i,n=C){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(pt);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=x(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(pt,JSON.stringify(e)))}mint(e){let t={id:y(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=x(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 k(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=er(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function Pe(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 er(r,e){let t=Pe(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=Pe(n);i.push(s!==void 0?s:ct(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 u=Pe(o);i[String(s)]=u!==void 0?u:ct(o),n++}return i}}}function ct(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function G(r,e,t){let i={...r},n;for(let s in i)m(s,e,t)&&(n=delete i[s]);return n?i:r}function m(r,e,t){return r?.[0]!=="$"?!1:(t.warn(`${e}: "$"-prefixed keys are reserved; ignored "${r}"`),!0)}function tr(r,e){let t=r?.name;return t==="AbortError"||t!=="TimeoutError"&&!!e?.aborted}function rr(r){let e=r?.message;return typeof e=="string"&&e?e.slice(0,255):"network error"}function ir(r){return r>=500}function lt(r){let e={};try{let t=new URL(r,typeof location<"u"?location.href:void 0);e.$net_url=`${t.origin}${t.pathname}`,t.search.length>1&&(e.$net_query=t.search.slice(1)),t.hash.length>1&&(e.$net_fragment=t.hash.slice(1))}catch{e.$net_url=r.slice(0,255)}return e}function nr(r){try{let e=r?.get("content-length");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}catch{return}}function sr(r,e){let t=Object.prototype.toString.call(r)==="[object Request]"?r:void 0;return{raw:String(t?t.url:r),method:String(e?.method??t?.method??"GET").toUpperCase(),signal:e?.signal??t?.signal}}function ft(r,e){if(r.autocapture&&r.autocapture.networkErrors===!1||typeof fetch!="function")return{stop:()=>{}};let i=fetch,n=r.endpoint.replace(/\/+$/,""),s=!1,o=0,u=new Set,a=c=>{let f=Date.now();return f-o>=6e4&&(o=f,u=new Set),u.size>=10||u.has(c)?!1:(u.add(c),!0)},d=(c,f)=>{try{let g=f();a(`${String(g.$net_method)} ${String(g.$net_url)} ${c}`)&&e(g)}catch{}},p=function(...c){let f=Date.now(),g=i.apply(this,c);if(s||typeof g?.then!="function")return g;let b,ie,Re;try{if({raw:b,method:ie,signal:Re}=sr(c[0],c[1]),b.startsWith(n))return g}catch{return g}let Ot=c[1];return g.then(h=>(ir(h.status)&&d(h.status,()=>({...lt(b),$net_method:ie,$net_status:h.status,$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f,...or(Ot,h)})),h),h=>{throw typeof navigator<"u"&&navigator.onLine===!1||tr(h,Re)||d("error",()=>({...lt(b),$net_method:ie,$net_error_message:rr(h),$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f})),h})};return globalThis.fetch=p,{stop:()=>{s=!0,globalThis.fetch===p&&(globalThis.fetch=i)}}}function or(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=nr(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function J(r){return Math.round(r)}function gt(){let r,e,t,i=0,n=!1,s,o=[],u=(a,d)=>{try{let p=new PerformanceObserver(c=>d(c.getEntries()));p.observe({type:a,buffered:!0}),o.push(p)}catch{}};u("largest-contentful-paint",a=>{let d=a[a.length-1];d&&(r=J(d.startTime))}),u("paint",a=>{for(let d of a)d.name==="first-contentful-paint"&&(e=J(d.startTime))}),u("layout-shift",a=>{for(let d of a)d.hadRecentInput||(i+=d.value??0,n=!0)}),u("event",a=>{for(let d of a){let p=J(d.duration);(t===void 0||p>t)&&(t=p)}});try{let[a]=performance.getEntriesByType("navigation"),d=a;d?.responseStart!==void 0&&d.responseStart>0&&(s=J(d.responseStart))}catch{}return{snapshot(){let a={};return r!==void 0&&(a.$wv_lcp=r),e!==void 0&&(a.$wv_fcp=e),t!==void 0&&(a.$wv_inp=t),n&&(a.$wv_cls=Math.round(i*1e3)/1e3),s!==void 0&&(a.$wv_ttfb=s),a},hasAny(){return r!==void 0||e!==void 0||t!==void 0||n||s!==void 0},stop(){for(let a of o.splice(0))try{a.disconnect()}catch{}}}}var xe="depsmith_super_props";function ht(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):!m(r,"register",e)}var Z=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(xe);if(i){let n=JSON.parse(i);n&&typeof n=="object"&&!Array.isArray(n)&&(this.properties=n)}}catch{}}register(e){let t=!1;for(let[i,n]of Object.entries(e))ht(i,this.logger)&&(this.properties[i]=n,t=!0);t&&this.persist()}registerOnce(e){let t=!1;for(let[i,n]of Object.entries(e))ht(i,this.logger)&&(Object.prototype.hasOwnProperty.call(this.properties,i)||(this.properties[i]=n,t=!0));t&&this.persist()}unregister(e){Object.prototype.hasOwnProperty.call(this.properties,e)&&(delete this.properties[e],this.persist())}clear(){if(Object.keys(this.properties).length!==0){this.properties={};try{this.storage.remove(xe)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(xe,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var ar=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],mt=50,vt=200;function Ee(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)=>m(s,o,e)?!1:i.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(i.add(s),!0);for(let s of ar){let o=r[s];if(!o||typeof o!="object")continue;let u=k(o,e),a={};for(let[d,p]of Object.entries(u))n(d,s)&&(a[d]=p);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[u,a]of Object.entries(r.$add)){if(o>=mt){e.debug(`$add over ${mt} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${u}" is not finite; dropped`);continue}n(u,"$add")&&(s[u]=a,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>=vt){e.debug(`$unset over ${vt} 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 Ae(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var yt={now:()=>Date.now()};function _(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function ee(r){return r===0||r===408||r===429||r>=500}var ur=1e3,dr=32e3;function bt(r,e=Math.random){let t=Math.min(ur*2**r,dr);return Math.round(e()*t)}function St(r,e){if(!r)return 0;let t=Number(r),i=t===t?t*1e3:Date.parse(r)-e;return i>0?i:0}async function pr(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:a,value:d}=await i.read();if(a)break;n.push(d)}let s=n.reduce((a,d)=>a+d.length,0),o=new Uint8Array(new ArrayBuffer(s)),u=0;for(let a of n)o.set(a,u),u+=a.length;return o}async function wt(r,e){if(e==="none"||typeof CompressionStream>"u")return null;try{return await pr(r)}catch{return null}}function kt(r,e,t,i,n){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let s=t.breaker;if(!t.isOnline()||s?.open()||s?.suspect())return;let o=i;for(let u=0;u<10;u++){let a=r.peek(e.batchSize,48e3,o);if(!a.length)return;let d=n(a);if(navigator.sendBeacon(`${e.endpoint}/e/`,new Blob([JSON.stringify(d)],{type:"text/plain"})))r.remove(a.map(c=>c.event_id));else{if(a.length>1)return;o++}}}catch{}}function cr(r){let e=[];for(let t of r)e.push(t.event_id);return e}var lr=3e4,fr=6e4,gr=256e3;function hr(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var mr=399;function Oe(r){return r>299&&r<400||r===401||r===403}var vr=3e4,yr=60*6e4,te=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null;this.uploading=0;this.limit=0;this.strikes=0;this.wait=0}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.limit=0;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("uploads paused");return}let e=this.config.batchSize,t=this.queue.peek(this.limit||e,gr);this.queue.persistNow(),this.uploading=t.length;let i=await this.uploadWithRetry(t);if(this.uploading=0,Oe(i)||ee(i))return;if(i===400||i===413){if(t.length>1){this.limit=t.length>>1;continue}this.limit=0}if(i>299&&this.deps.logger.notice(`collector answered ${i}; dropped ${t.length} event(s)`),this.queue.remove(cr(t)),i===400)return}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1,n=0;for(let s=0;s<=this.config.maxRetries&&!(s&&(this.deps.canUpload?.()===!1||this.queue.peek(1)[0]?.event_id!==e[0].event_id)||(n=await this.post(e),n&&(i=!0),!ee(n)||this.wait)||(this.deps.logger.debug(`upload attempt ${s+1} failed (${n})`),!i&&t?.suspect()));s++)s<this.config.maxRetries&&await this.deps.sleep(bt(s));return i?(t?.ok(),n>199&&n<300?this.strikes=0:(Oe(n)||ee(n))&&(Oe(n)&&this.deps.logger.notice(`collector refused uploads (${n}); paused`),t?.hold(this.wait||Math.min(vr*2**this.strikes++,yr)))):t?.fail(),n}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:_(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){this.wait=0;let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s={"Content-Type":"application/json"},o=await wt(t,this.config.compression);o&&(s["Content-Encoding"]="gzip");let u=o??t,a=hr(u)<=fr;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let d={method:"POST",headers:s,body:u,keepalive:a};i&&(d.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs()));let p=await this.deps.fetchFn(`${this.config.endpoint}/e/`,d);return p.redirected?mr:(this.wait=St(p.headers?.get("Retry-After"),this.deps.clock.now()),p.status)}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:lr}sendBeaconAll(){kt(this.queue,this.config,this.deps,this.uploading,e=>this.buildPayload(e))}};var $="depsmith_net_breaker";function _t(r,e){let t=!1,i=0,n=0,s=3e5,o=(d,p,c)=>typeof d=="number"&&d===d?Math.min(Math.max(d,p),c):p,u=()=>{if(!t){t=!0;try{let d=JSON.parse(r.get($)??"0");if(!Array.isArray(d))return;i=o(d[0],0,3),n=o(d[1],0,e.now()+36e5),s=o(d[2],3e5,36e5)}catch{}}},a=()=>{try{i||n>e.now()?r.set($,JSON.stringify([i,n,s])):r.remove($)}catch{}};return{open:()=>(u(),e.now()<(n=Math.min(n,e.now()+36e5))),suspect:()=>(u(),i>0),fail:()=>{u(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),a()},ok:()=>{u(),i&&(i=n=0,s=3e5,a())},hold:d=>{u(),n=Math.max(n,e.now()+Math.min(d,36e5)),a()}}}var re=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)}notice(...e){console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var Pt=["url","referrer","previous_url","initial_url"],br=["$ac_href","$ac_form_action","$net_url","$fr_error_file"];function xt(r,e){let t=r.split("#")[0],i=t.indexOf("?");if(i<0)return t;let n=t.slice(i+1).split("&").filter(s=>e.has(Sr(s)));return t.slice(0,i)+(n.length?`?${n.join("&")}`:"")}function Sr(r){let e=r.split("=")[0].replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}function Et(r,e){if(e)try{let t=e.keepParams,i=new Set(Array.isArray(t)?t:[]),n=[[r.context.page,Pt],[r.context.referrer,Pt],[r.properties,br]];for(let[o,u]of n)for(let a of u){let d=o?.[a];typeof d=="string"&&(o[a]=xt(d,i))}let s=r.properties;if(!s)return;if(delete s.$net_fragment,typeof s.$net_query=="string"){let o=xt(`?${s.$net_query}`,i).slice(1);o?s.$net_query=o:delete s.$net_query}}catch{}}var Ce="depsmith_config_fp",At=255,I=class{constructor(e,t={}){this.vitalsReported=!1;this.stopped=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=qe(e),this.logger=new re(this.config.debug),this.clock=t.clock??yt,this.storage=t.storage??this.pickStorage();let i=t.storage?this.storage:at(this.config.storage,this.storage);this.contextProvider=t.contextProvider,this.pageLife=new M({now:()=>this.clock.now(),capture:(a,d,p,c,f)=>this.capture(a,d,p,void 0,void 0,c,f)},this.config);let n=this.config.childSafeMode?new w:this.config.storage==="memory"?this.storage:new j(this.storage,new F(this.config.cookieDomain||void 0));this.identity=new H(n,this.clock),this.session=new Q(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new q(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??it())),this.attribution=new N(n),this.superProperties=new Z(this.storage,this.logger),!this.contextProvider&&typeof window<"u"&&window.location&&(this.attribution.recordLanding(window.location.href,typeof document<"u"?document.referrer:""),this.pageLife.start(window.location.href,typeof document<"u"?document.referrer:""));let s=ue(this.config.apiKey),o={get:a=>i.get(a),set:(a,d)=>{this.storage.get(Ce)===s&&i.set(a,d)},remove:a=>i.remove(a)};this.queue=new X(o,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule});let u=this.detectConfigDrift(s);this.primeDeviceSignals(),this.ready=ut(i,this.storage,this.consent,this.queue,u,this.logger),this.uploader=new te(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??((...a)=>fetch(...a)),clock:this.clock,logger:this.logger,sleep:t.sleep??(a=>new Promise(d=>setTimeout(d,a))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:_t(this.storage,this.clock),canUpload:()=>this.consent.canUpload()}),t.manualLifecycle||(this.lifecycle=De({intervalMs:this.config.batchIntervalMs,guard:a=>this.guard(a),vitals:()=>this.emitWebVitals(),leave:()=>this.leaveOnUnload?.(),restored:a=>this.pageLife.restored(a),resume:()=>this.resumeSession(),flushIfQueued:()=>this.flushIfQueued(),persistNow:()=>this.persistNow(),beacon:()=>{this.consent.canUpload()&&this.uploader.sendBeaconAll()},online:()=>{this.uploader.resetNetworkBreaker(),this.flushIfQueued()}}),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.trackInternal(e,G(t,"track",this.logger))}trackInternal(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}m(e,"track",this.logger)||this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}traits(e,t){return k(G(e,t,this.logger),this.logger)}tooLong(e,t){return e.length<=At?!1:(this.logger.warn(`${t} exceeds ${At} characters (got ${e.length}); dropped`),!0)}page(e,t,i){this.pageInternal(e,G(t,"page",this.logger),i)}pageInternal(e,t,i){this.guard(()=>this.pageLife.manual(e,t,i?.type))}emitWebVitals(){this.vitalsReported||!this.vitals?.hasAny()||(this.vitalsReported=!0,this.capture("$web_vitals","track",this.vitals.snapshot()))}screen(e,t,i){this.page(e,t,i)}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=this.traits(t,"identify");this.capture("$identify","identify",void 0,i,Ae("$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.pageLife.flushPending(),this.identity.reset(),this.session.rotate(),this.attribution.clear(),this.superProperties.clear(),this.logger.debug("reset: identity, session and attribution cleared")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(e,"group: groupId"))return;this.identity.setGroup(e);let i=this.traits(t,"group");this.capture("$group","group",void 0,i)})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}let t=this.traits(e,"setGroupTraits");this.capture("$group","group",void 0,t)})}setProperty(e,t){this.guard(()=>{m(e,"setProperty",this.logger)||this.setUserProp(e,t,"$set")})}setUserProp(e,t,i){this.identity.setUserProp(e,t);let n=k({[e]:t},this.logger);this.capture("$identify","identify",void 0,n,Ae(i,n))}setOnceProperty(e,t){this.guard(()=>{if(!m(e,"setOnceProperty",this.logger)){if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.setUserProp(e,t,"$set_once")}})}unsetProperty(e){this.guard(()=>{m(e,"unsetProperty",this.logger)||(this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},Ee({$unset:[e]},this.logger)))})}register(e){this.guard(()=>this.superProperties.register(e))}registerOnce(e){this.guard(()=>this.superProperties.registerOnce(e))}unregister(e){this.guard(()=>this.superProperties.unregister(e))}setUserProperties(e){this.guard(()=>{let t=Ee(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.primeDeviceSignals(),this.flushUploads()})}optOut(){this.guard(()=>{this.pageLife.discardPending(),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.guard(()=>this.pageLife.flushPending()),this.stopped=!0,this.lifecycle?.stop();for(let e of this.teardownFns.splice(0))e();this.persistNow(),this.queue.close()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}deviceSignals(){return!this.config.childSafeMode&&this.consent.canUpload()}primeDeviceSignals(){this.deviceSignals()&&(this.config.deviceFingerprinting&&Xe(),this.config.geolocation&&tt(()=>this.deviceSignals()))}enqueueEvent(e){Et(e,this.config.scrubUrls),this.queue.enqueue(e),this.lifecycle?.rearm()}flushUploads(){return this.ready.then(()=>this.uploader.flush())}flushIfQueued(){this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}let t=this.deviceSignals();return{fingerprint:this.config.deviceFingerprinting&&t,geolocation:this.config.geolocation&&t,overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:je(`${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,o,u){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let a=this.touchSession();if(!this.inSample(a.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let d=o??this.clock.now(),p=this.contextOptions();u&&(p.page=u);let c={event_id:y(d),event:e,event_type:t,timestamp:_(d),session_id:a.sessionId,session_started_at:_(a.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...B(p),traits:n}:B(p),platform:"web",sdk_version:O};s&&(c.user_properties=s);let f=k({...this.config.defaultProperties,...this.superProperties.current(),...k(i,this.logger)},this.logger);Object.keys(f).length>0&&(c.properties=f);let g=this.identity.userId;g&&(c.user_id=g);let b=this.identity.groupId;b&&(c.group_id=b),p.fingerprint&&(c.device_id=le()),this.enqueueEvent(c),this.logger.debug(`captured ${e}`,c),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(e){let t=this.storage.get(Ce),i=t!==null&&t!==e;return i&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear(),this.storage.remove($)),this.storage.set(Ce,e),i}pickStorage(){return this.config.storage==="memory"?new w:ot()}enqueueSessionEnd(e){this.enqueueSessionBoundary("end",e.id,e.lastActivityAt,e.startedAt)}enqueueSessionStart(e){this.enqueueSessionBoundary("start",e.id,e.startedAt,e.startedAt)}enqueueSessionBoundary(e,t,i,n){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug(`session_${e} dropped (consent denied)`);return}let s=this.contextOptions(),o={event_id:y(this.clock.now()),event:`$session_${e}`,event_type:`session_${e}`,timestamp:_(i),session_id:t,session_started_at:_(n),anonymous_id:this.identity.anonymousId,context:B(s),platform:"web",sdk_version:O},u=this.identity.userId;u&&(o.user_id=u),s.fingerprint&&(o.device_id=le(),e==="start"&&(o.properties=Qe())),this.enqueueEvent(o)}touchSession(){let e=this.session.touch();return e.startedSession&&this.pageLife.newSession(),e.endedSession&&this.sessionInSample(e.endedSession.id)&&this.enqueueSessionEnd(e.endedSession),e.startedSession&&this.sessionInSample(e.startedSession.id)&&this.enqueueSessionStart(e.startedSession),e}resumeSession(){this.consent.canCapture()&&this.touchSession()}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=gt(),this.teardownFns.push(()=>this.vitals?.stop()));let t=ft(this.config,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),Ue().then(i=>{i&&(this.stopped||(this.teardownFns.push(i.startAutocapture(e,{emit:n=>this.autocapture(n),page:n=>this.guard(()=>this.pageLife.autoPageView(n)),pageLeave:n=>this.guard(()=>this.pageLife.leave(n)),warn:n=>this.logger.warn(n),armUnloadLeave:n=>{this.leaveOnUnload=n}})),this.teardownFns.push(()=>{this.leaveOnUnload=void 0})))}).catch(i=>this.logger.debug("autocapture load failed",i))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var l=null,Te=null,en={init(r,e){try{return l&&Te===r.apiKey?l:typeof window>"u"&&r.storage!=="memory"&&!e?.storage?(r.debug&&console.warn("[depsmith-sdk] init skipped: no window"),null):(l?.shutdown(),l=new I(r,e),Te=r.apiKey,l)}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>l?.track(r,e),page:(r,e,t)=>l?.page(r,e,t),screen:(r,e,t)=>l?.screen(r,e,t),identify:(r,e)=>l?.identify(r,e),alias:r=>l?.alias(r),reset:()=>l?.reset(),group:(r,e)=>l?.group(r,e),setGroupTraits:r=>l?.setGroupTraits(r),setProperty:(r,e)=>l?.setProperty(r,e),setOnceProperty:(r,e)=>l?.setOnceProperty(r,e),unsetProperty:r=>l?.unsetProperty(r),setUserProperties:r=>l?.setUserProperties(r),register:r=>l?.register(r),registerOnce:r=>l?.registerOnce(r),unregister:r=>l?.unregister(r),optIn:()=>l?.optIn(),optOut:()=>l?.optOut(),flush:()=>l?.flush()??Promise.resolve(),getAnonymousId:()=>l?.getAnonymousId(),getSessionId:()=>l?.getSessionId(),setSessionId:(r,e)=>l?.setSessionId(r,e),shutdown(){l?.shutdown(),l=null,Te=null}};export{Se as AsyncMirrorAdapter,st as DEPSMITH_SDK_STORAGE_KEYS,en as DepsmithSdk,I as DepsmithSdkClient,C as idleScheduler,Wt as syncScheduler};
2
2
  //# sourceMappingURL=index.js.map