@depsmith/depsmith-sdk 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -171,7 +171,8 @@ interface DepsmithSdkEvent {
171
171
  * carry a change; applied against `user_id` when set, else `anonymous_id`.
172
172
  */
173
173
  user_properties?: UserPropertyOps;
174
- platform: 'web';
174
+ /** Where the user is. Always `Web` from this SDK (schema 0.9.1; `web` before). */
175
+ platform: 'Web';
175
176
  sdk_version: string;
176
177
  }
177
178
  interface BatchPayload {
@@ -257,6 +258,15 @@ interface DepsmithSdkConfig {
257
258
  * consent, like deviceFingerprinting. Default false.
258
259
  */
259
260
  geolocation?: boolean;
261
+ /**
262
+ * Opt-in. Strip the fragment and query string from every URL the SDK sends — `context.page`
263
+ * url/referrer/previous_url, `context.referrer`, `$ac_href`, `$ac_form_action`, `$net_*`.
264
+ * `{ keepParams: ['utm_source'] }` keeps the named query parameters. Default false: URLs are
265
+ * sent whole. See API_SPEC §12.
266
+ */
267
+ scrubUrls?: boolean | {
268
+ keepParams?: string[];
269
+ };
260
270
  /** Per-field context suppression, all keys default true. Subtractive only; see API_SPEC §12.2. */
261
271
  trackingOptions?: TrackingOptions;
262
272
  /** Persist identity keys in a cookie scoped to this domain (cross-subdomain identity). */
@@ -321,6 +331,12 @@ interface AutocaptureConfig {
321
331
  * Given as bare names: `['product-id']` captures `data-product-id` as `$ac_attr_product_id`.
322
332
  */
323
333
  attributes?: string[];
334
+ /**
335
+ * `$network_request` for failed `fetch` calls, which wraps `window.fetch`. Default true (on
336
+ * whenever autocapture is); false leaves `fetch` untouched while keeping the rest of
337
+ * autocapture. See API_SPEC §12.6.
338
+ */
339
+ networkErrors?: boolean;
324
340
  }
325
341
 
326
342
  /**
@@ -332,7 +348,7 @@ interface KVStorage {
332
348
  set(key: string, value: string): void;
333
349
  remove(key: string): void;
334
350
  }
335
- 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"];
351
+ 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"];
336
352
  /**
337
353
  * Minimal async key-value backend. Shaped to accept Shopify's `browser.localStorage`
338
354
  * / `browser.sessionStorage` directly (all methods Promise-returning, proxied to the
@@ -440,7 +456,7 @@ declare class DepsmithSdkClient {
440
456
  * Autocapture's unload-time `$page_leave` trigger, when pageview tracking is on.
441
457
  *
442
458
  * The client owns the call site rather than autocapture, because it must run BEFORE the
443
- * teardown drain — see {@link attachLifecycle}. Undefined means no page-leave tracking:
459
+ * teardown drain — see `lifecycle.ts`. Undefined means no page-leave tracking:
444
460
  * autocapture is off, compiled out, or still loading.
445
461
  */
446
462
  private leaveOnUnload?;
@@ -450,13 +466,10 @@ declare class DepsmithSdkClient {
450
466
  private vitalsReported;
451
467
  private queue;
452
468
  private uploader;
453
- private flushTimer;
454
- /**
455
- * Set once a teardown drain has run, so `pagehide` and `visibilitychange`→hidden do not
456
- * both run it on one navigation. Cleared on resume, on `pageshow`, and by any newly
457
- * captured event ({@link enqueueEvent}).
458
- */
459
- private drained;
469
+ /** Timer and page listeners. Undefined under `manualLifecycle`, and in the pixel build. */
470
+ private lifecycle?;
471
+ /** Set by shutdown(); a lazily loaded autocapture chunk checks it before starting. */
472
+ private stopped;
460
473
  private teardownFns;
461
474
  private contextProvider?;
462
475
  /** Resolves once async storage (IndexedDB) is hydrated; uploads gate on this. */
@@ -475,14 +488,14 @@ declare class DepsmithSdkClient {
475
488
  *
476
489
  * Dropping the call is harsh, and it is the lesser harm. `event`, `user_id` and `group_id` are
477
490
  * all capped at 255 in event.schema.json, the collector validates every batch with Ajv, and a
478
- * 400 is non-retryable — so the uploader discards the WHOLE batch as a poison pill. For
479
- * `user_id` and `group_id` that is not a one-batch loss either: both are persisted and ride on
491
+ * 400 is non-retryable — the uploader bisects the batch and drops the event that fails. For
492
+ * `user_id` and `group_id` that is not a one-event loss either: both are persisted and ride on
480
493
  * every subsequent event, so a single over-long id silently destroys everything that user sends
481
494
  * until reset(). A JWT or a concatenated composite key passed as a user id does it.
482
495
  *
483
496
  * Truncating instead would keep the events but silently merge two users sharing a 255-char
484
497
  * prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is
485
- * the rule throughout: such an event would 400 and take the whole batch with it.
498
+ * the rule throughout: such an event would 400 and be dropped at upload, after a bisection.
486
499
  */
487
500
  /** Client traits as sent: `$` keys dropped, then sanitised like event properties. */
488
501
  private traits;
@@ -520,6 +533,8 @@ declare class DepsmithSdkClient {
520
533
  group(groupId: string, traits?: Properties): void;
521
534
  setGroupTraits(traits: Properties): void;
522
535
  setProperty(key: string, value: Properties[string]): void;
536
+ /** The shared tail of setProperty / setOnceProperty: remember it locally, emit the operator. */
537
+ private setUserProp;
523
538
  /**
524
539
  * Sets a property only if this device has not already set it.
525
540
  *
@@ -598,16 +613,21 @@ declare class DepsmithSdkClient {
598
613
  */
599
614
  private persistNow;
600
615
  /**
601
- * Queues an event and re-arms the teardown drain.
602
- *
603
- * `drained` exists only to stop `pagehide` and `visibilitychange`→hidden running the
604
- * same drain twice on one navigation. It must not outlive the work it covered: on
605
- * desktop, `visibilitychange`→hidden fires on an ordinary tab switch, and a backgrounded
606
- * tab keeps capturing (the batch-interval timer, `online`, a host-driven `track()`). If
607
- * that tab is then closed without ever becoming visible again, a latch left set would
608
- * skip both the final `sendBeaconAll()` and the teardown write, losing everything
609
- * captured while hidden — a correctness hole opened by a pure optimisation.
616
+ * Device signals (fingerprint, Client Hints, position) may be read and sent: not COPPA mode,
617
+ * and consent granted — `canUpload()` is false while pending, after opt-out and under DNT.
618
+ * The ONE gate for both the reads below and the emission in `contextOptions()` (#87).
610
619
  */
620
+ private deviceSignals;
621
+ /**
622
+ * Starts the once-per-document device-signal reads (high-entropy Client Hints, and the
623
+ * geolocation permission query + position), off the capture path — only when their results
624
+ * could be sent. Under pending or denied consent, or DNT, nothing is read; `optIn()` calls
625
+ * this again. Defaults are unchanged: this only skips reads whose results would be discarded.
626
+ * The geolocation gate is re-checked before every later read (permission change, stale-fix
627
+ * refresh), so `optOut()` stops those too.
628
+ */
629
+ private primeDeviceSignals;
630
+ /** Queues an event and re-arms the teardown drain — see {@link BrowserLifecycle.rearm}. */
611
631
  private enqueueEvent;
612
632
  /**
613
633
  * The single entry point for starting an upload.
@@ -619,10 +639,12 @@ declare class DepsmithSdkClient {
619
639
  * exists to remove, reappearing in the exact case that matters most (a backed-up queue).
620
640
  */
621
641
  private flushUploads;
642
+ /** Starts an upload when there is something to send and consent allows it. */
643
+ private flushIfQueued;
622
644
  /**
623
- * Fingerprinting is opt-in and privacy-gated: it requires explicit config, granted
624
- * consent (consent.current is 'denied' under DNT and never 'granted' while pending),
625
- * and non-COPPA mode.
645
+ * Fingerprinting is on by default (opt-out via `deviceFingerprinting: false`) and
646
+ * privacy-gated: it requires granted consent (consent.current is 'denied' under DNT and
647
+ * never 'granted' while pending) and non-COPPA mode.
626
648
  */
627
649
  private contextOptions;
628
650
  /**
@@ -648,23 +670,38 @@ declare class DepsmithSdkClient {
648
670
  /**
649
671
  * Config drift (guidelines §12): events queued under a different apiKey belong to
650
672
  * another project — drop them rather than misattribute. Fingerprint, not raw key.
673
+ * The upload pause goes too: a 401 or Retry-After for that key says nothing about this one.
651
674
  */
652
675
  private detectConfigDrift;
676
+ /** The synchronous store. IndexedDB is never returned here — see the constructor. */
653
677
  private pickStorage;
654
- private enqueueSessionEnd;
655
678
  /**
656
- * Announces a session the SDK just observed beginning.
679
+ * `$session_start` / `$session_end`, built in one place: the two envelopes differ only in
680
+ * their name, their timestamp and the fingerprint components the opening one carries.
681
+ */
682
+ private enqueueSessionBoundary;
683
+ /**
684
+ * Stamps session activity and emits the boundary events that revealed. The one place a
685
+ * session is touched, for capture() and for the tab-resume path alike: the resume path used
686
+ * to emit both boundaries with no sample check, so at `sampleRate: 0.1` nine in ten resumed
687
+ * sessions reached the warehouse as a bare `$session_start` with nothing after it.
657
688
  *
658
- * Consent-gated for the same reason as enqueueSessionEnd: the visibilitychange resume
659
- * path reaches this without going through capture(). Under `pending` consent
660
- * canCapture() is true, so it is queued and held — matching capture() exactly.
689
+ * Order is load-bearing (API_SPEC §5): the old session's end precedes the new session's
690
+ * start, and both precede the event that triggered the rotation.
691
+ *
692
+ * Each boundary follows ITS OWN session's sample decision, not the current event's: the
693
+ * ending and starting sessions have different ids and can therefore decide differently, and
694
+ * an exempt $identify must not drag a boundary event into an out-of-sample session.
695
+ */
696
+ private touchSession;
697
+ /**
698
+ * `visibilitychange`→visible: run the session-timeout check.
661
699
  *
662
- * Not emitted by reset()/rotate() (an explicit user action, not an observed boundary)
663
- * nor by peek()'s mint-if-absent branch (analytics from a getter).
700
+ * Not at all while capture is denied. capture() returns before touching the session in that
701
+ * state; this path did not, so every refocus by an opted-out or DNT visitor wrote a session id
702
+ * and an activity timestamp to storage.
664
703
  */
665
- private enqueueSessionStart;
666
- private startFlushTimer;
667
- private attachLifecycle;
704
+ private resumeSession;
668
705
  /** Lazily loads the autocapture engine so the core bundle stays <10KB gz. */
669
706
  private startAutocapture;
670
707
  private guard;
@@ -678,6 +715,7 @@ declare class DepsmithSdkClient {
678
715
  * DepsmithSdk.track('button_clicked', { color: 'red' });
679
716
  *
680
717
  * Re-init with the same apiKey is a no-op; a different apiKey replaces the client (API_SPEC §2).
718
+ * Without a `window` (server rendering) init() does nothing and returns null — see below.
681
719
  */
682
720
  declare const DepsmithSdk: {
683
721
  init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null;
package/dist/index.d.ts CHANGED
@@ -171,7 +171,8 @@ interface DepsmithSdkEvent {
171
171
  * carry a change; applied against `user_id` when set, else `anonymous_id`.
172
172
  */
173
173
  user_properties?: UserPropertyOps;
174
- platform: 'web';
174
+ /** Where the user is. Always `Web` from this SDK (schema 0.9.1; `web` before). */
175
+ platform: 'Web';
175
176
  sdk_version: string;
176
177
  }
177
178
  interface BatchPayload {
@@ -257,6 +258,15 @@ interface DepsmithSdkConfig {
257
258
  * consent, like deviceFingerprinting. Default false.
258
259
  */
259
260
  geolocation?: boolean;
261
+ /**
262
+ * Opt-in. Strip the fragment and query string from every URL the SDK sends — `context.page`
263
+ * url/referrer/previous_url, `context.referrer`, `$ac_href`, `$ac_form_action`, `$net_*`.
264
+ * `{ keepParams: ['utm_source'] }` keeps the named query parameters. Default false: URLs are
265
+ * sent whole. See API_SPEC §12.
266
+ */
267
+ scrubUrls?: boolean | {
268
+ keepParams?: string[];
269
+ };
260
270
  /** Per-field context suppression, all keys default true. Subtractive only; see API_SPEC §12.2. */
261
271
  trackingOptions?: TrackingOptions;
262
272
  /** Persist identity keys in a cookie scoped to this domain (cross-subdomain identity). */
@@ -321,6 +331,12 @@ interface AutocaptureConfig {
321
331
  * Given as bare names: `['product-id']` captures `data-product-id` as `$ac_attr_product_id`.
322
332
  */
323
333
  attributes?: string[];
334
+ /**
335
+ * `$network_request` for failed `fetch` calls, which wraps `window.fetch`. Default true (on
336
+ * whenever autocapture is); false leaves `fetch` untouched while keeping the rest of
337
+ * autocapture. See API_SPEC §12.6.
338
+ */
339
+ networkErrors?: boolean;
324
340
  }
325
341
 
326
342
  /**
@@ -332,7 +348,7 @@ interface KVStorage {
332
348
  set(key: string, value: string): void;
333
349
  remove(key: string): void;
334
350
  }
335
- 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"];
351
+ 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"];
336
352
  /**
337
353
  * Minimal async key-value backend. Shaped to accept Shopify's `browser.localStorage`
338
354
  * / `browser.sessionStorage` directly (all methods Promise-returning, proxied to the
@@ -440,7 +456,7 @@ declare class DepsmithSdkClient {
440
456
  * Autocapture's unload-time `$page_leave` trigger, when pageview tracking is on.
441
457
  *
442
458
  * The client owns the call site rather than autocapture, because it must run BEFORE the
443
- * teardown drain — see {@link attachLifecycle}. Undefined means no page-leave tracking:
459
+ * teardown drain — see `lifecycle.ts`. Undefined means no page-leave tracking:
444
460
  * autocapture is off, compiled out, or still loading.
445
461
  */
446
462
  private leaveOnUnload?;
@@ -450,13 +466,10 @@ declare class DepsmithSdkClient {
450
466
  private vitalsReported;
451
467
  private queue;
452
468
  private uploader;
453
- private flushTimer;
454
- /**
455
- * Set once a teardown drain has run, so `pagehide` and `visibilitychange`→hidden do not
456
- * both run it on one navigation. Cleared on resume, on `pageshow`, and by any newly
457
- * captured event ({@link enqueueEvent}).
458
- */
459
- private drained;
469
+ /** Timer and page listeners. Undefined under `manualLifecycle`, and in the pixel build. */
470
+ private lifecycle?;
471
+ /** Set by shutdown(); a lazily loaded autocapture chunk checks it before starting. */
472
+ private stopped;
460
473
  private teardownFns;
461
474
  private contextProvider?;
462
475
  /** Resolves once async storage (IndexedDB) is hydrated; uploads gate on this. */
@@ -475,14 +488,14 @@ declare class DepsmithSdkClient {
475
488
  *
476
489
  * Dropping the call is harsh, and it is the lesser harm. `event`, `user_id` and `group_id` are
477
490
  * all capped at 255 in event.schema.json, the collector validates every batch with Ajv, and a
478
- * 400 is non-retryable — so the uploader discards the WHOLE batch as a poison pill. For
479
- * `user_id` and `group_id` that is not a one-batch loss either: both are persisted and ride on
491
+ * 400 is non-retryable — the uploader bisects the batch and drops the event that fails. For
492
+ * `user_id` and `group_id` that is not a one-event loss either: both are persisted and ride on
480
493
  * every subsequent event, so a single over-long id silently destroys everything that user sends
481
494
  * until reset(). A JWT or a concatenated composite key passed as a user id does it.
482
495
  *
483
496
  * Truncating instead would keep the events but silently merge two users sharing a 255-char
484
497
  * prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is
485
- * the rule throughout: such an event would 400 and take the whole batch with it.
498
+ * the rule throughout: such an event would 400 and be dropped at upload, after a bisection.
486
499
  */
487
500
  /** Client traits as sent: `$` keys dropped, then sanitised like event properties. */
488
501
  private traits;
@@ -520,6 +533,8 @@ declare class DepsmithSdkClient {
520
533
  group(groupId: string, traits?: Properties): void;
521
534
  setGroupTraits(traits: Properties): void;
522
535
  setProperty(key: string, value: Properties[string]): void;
536
+ /** The shared tail of setProperty / setOnceProperty: remember it locally, emit the operator. */
537
+ private setUserProp;
523
538
  /**
524
539
  * Sets a property only if this device has not already set it.
525
540
  *
@@ -598,16 +613,21 @@ declare class DepsmithSdkClient {
598
613
  */
599
614
  private persistNow;
600
615
  /**
601
- * Queues an event and re-arms the teardown drain.
602
- *
603
- * `drained` exists only to stop `pagehide` and `visibilitychange`→hidden running the
604
- * same drain twice on one navigation. It must not outlive the work it covered: on
605
- * desktop, `visibilitychange`→hidden fires on an ordinary tab switch, and a backgrounded
606
- * tab keeps capturing (the batch-interval timer, `online`, a host-driven `track()`). If
607
- * that tab is then closed without ever becoming visible again, a latch left set would
608
- * skip both the final `sendBeaconAll()` and the teardown write, losing everything
609
- * captured while hidden — a correctness hole opened by a pure optimisation.
616
+ * Device signals (fingerprint, Client Hints, position) may be read and sent: not COPPA mode,
617
+ * and consent granted — `canUpload()` is false while pending, after opt-out and under DNT.
618
+ * The ONE gate for both the reads below and the emission in `contextOptions()` (#87).
610
619
  */
620
+ private deviceSignals;
621
+ /**
622
+ * Starts the once-per-document device-signal reads (high-entropy Client Hints, and the
623
+ * geolocation permission query + position), off the capture path — only when their results
624
+ * could be sent. Under pending or denied consent, or DNT, nothing is read; `optIn()` calls
625
+ * this again. Defaults are unchanged: this only skips reads whose results would be discarded.
626
+ * The geolocation gate is re-checked before every later read (permission change, stale-fix
627
+ * refresh), so `optOut()` stops those too.
628
+ */
629
+ private primeDeviceSignals;
630
+ /** Queues an event and re-arms the teardown drain — see {@link BrowserLifecycle.rearm}. */
611
631
  private enqueueEvent;
612
632
  /**
613
633
  * The single entry point for starting an upload.
@@ -619,10 +639,12 @@ declare class DepsmithSdkClient {
619
639
  * exists to remove, reappearing in the exact case that matters most (a backed-up queue).
620
640
  */
621
641
  private flushUploads;
642
+ /** Starts an upload when there is something to send and consent allows it. */
643
+ private flushIfQueued;
622
644
  /**
623
- * Fingerprinting is opt-in and privacy-gated: it requires explicit config, granted
624
- * consent (consent.current is 'denied' under DNT and never 'granted' while pending),
625
- * and non-COPPA mode.
645
+ * Fingerprinting is on by default (opt-out via `deviceFingerprinting: false`) and
646
+ * privacy-gated: it requires granted consent (consent.current is 'denied' under DNT and
647
+ * never 'granted' while pending) and non-COPPA mode.
626
648
  */
627
649
  private contextOptions;
628
650
  /**
@@ -648,23 +670,38 @@ declare class DepsmithSdkClient {
648
670
  /**
649
671
  * Config drift (guidelines §12): events queued under a different apiKey belong to
650
672
  * another project — drop them rather than misattribute. Fingerprint, not raw key.
673
+ * The upload pause goes too: a 401 or Retry-After for that key says nothing about this one.
651
674
  */
652
675
  private detectConfigDrift;
676
+ /** The synchronous store. IndexedDB is never returned here — see the constructor. */
653
677
  private pickStorage;
654
- private enqueueSessionEnd;
655
678
  /**
656
- * Announces a session the SDK just observed beginning.
679
+ * `$session_start` / `$session_end`, built in one place: the two envelopes differ only in
680
+ * their name, their timestamp and the fingerprint components the opening one carries.
681
+ */
682
+ private enqueueSessionBoundary;
683
+ /**
684
+ * Stamps session activity and emits the boundary events that revealed. The one place a
685
+ * session is touched, for capture() and for the tab-resume path alike: the resume path used
686
+ * to emit both boundaries with no sample check, so at `sampleRate: 0.1` nine in ten resumed
687
+ * sessions reached the warehouse as a bare `$session_start` with nothing after it.
657
688
  *
658
- * Consent-gated for the same reason as enqueueSessionEnd: the visibilitychange resume
659
- * path reaches this without going through capture(). Under `pending` consent
660
- * canCapture() is true, so it is queued and held — matching capture() exactly.
689
+ * Order is load-bearing (API_SPEC §5): the old session's end precedes the new session's
690
+ * start, and both precede the event that triggered the rotation.
691
+ *
692
+ * Each boundary follows ITS OWN session's sample decision, not the current event's: the
693
+ * ending and starting sessions have different ids and can therefore decide differently, and
694
+ * an exempt $identify must not drag a boundary event into an out-of-sample session.
695
+ */
696
+ private touchSession;
697
+ /**
698
+ * `visibilitychange`→visible: run the session-timeout check.
661
699
  *
662
- * Not emitted by reset()/rotate() (an explicit user action, not an observed boundary)
663
- * nor by peek()'s mint-if-absent branch (analytics from a getter).
700
+ * Not at all while capture is denied. capture() returns before touching the session in that
701
+ * state; this path did not, so every refocus by an opted-out or DNT visitor wrote a session id
702
+ * and an activity timestamp to storage.
664
703
  */
665
- private enqueueSessionStart;
666
- private startFlushTimer;
667
- private attachLifecycle;
704
+ private resumeSession;
668
705
  /** Lazily loads the autocapture engine so the core bundle stays <10KB gz. */
669
706
  private startAutocapture;
670
707
  private guard;
@@ -678,6 +715,7 @@ declare class DepsmithSdkClient {
678
715
  * DepsmithSdk.track('button_clicked', { color: 'red' });
679
716
  *
680
717
  * Re-init with the same apiKey is a no-op; a different apiKey replaces the client (API_SPEC §2).
718
+ * Without a `window` (server rendering) init() does nothing and returns null — see below.
681
719
  */
682
720
  declare const DepsmithSdk: {
683
721
  init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null;