@depsmith/depsmith-sdk 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -2
- package/dist/autocapture.js +2 -0
- package/dist/autocapture.js.map +1 -0
- package/dist/depsmith-sdk.global.js +2 -0
- package/dist/depsmith-sdk.global.js.map +1 -0
- package/dist/depsmith-sdk.pixel.global.js +10 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +560 -0
- package/dist/index.d.ts +560 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/package.json +72 -4
package/README.md
CHANGED
|
@@ -1,3 +1,57 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @depsmith/depsmith-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Web SDK for DepSmith DepSmith SDK event tracking. Core bundle target: **< 10 KB gzipped**.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { DepsmithSdk } from '@depsmith/depsmith-sdk';
|
|
7
|
+
|
|
8
|
+
DepsmithSdk.init({
|
|
9
|
+
apiKey: 'your-key',
|
|
10
|
+
endpoint: 'https://collector.example.com',
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
DepsmithSdk.track('button_clicked', { color: 'red' });
|
|
14
|
+
DepsmithSdk.identify('user-42', { email: 'u@example.com' });
|
|
15
|
+
DepsmithSdk.page('Home');
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## API
|
|
19
|
+
|
|
20
|
+
`track, page, screen, identify, alias, reset, group, setGroupTraits, setProperty, setOnceProperty, unsetProperty, optIn, optOut, flush, getAnonymousId, getSessionId` — semantics defined in [`../spec/api/API_SPEC.md`](../spec/api/API_SPEC.md).
|
|
21
|
+
|
|
22
|
+
Multiple instances: `new DepsmithSdkClient(config)` (the `DepsmithSdk` export is a singleton facade).
|
|
23
|
+
|
|
24
|
+
## Behavior highlights
|
|
25
|
+
|
|
26
|
+
- **Offline-first**: events persist to localStorage before any network attempt; replayed on reconnect / next page load
|
|
27
|
+
- **Batching**: 20 events or 60 s (configurable); `sendBeacon` final flush on `pagehide`
|
|
28
|
+
- **Retry**: exponential backoff 1s→32s + jitter for network/408/429/5xx; other 4xx batches are dropped (poison-pill protection)
|
|
29
|
+
- **Consent**: `consentMode: 'pending'` captures but holds uploads until `optIn()`; `optOut()` drops and blocks; DNT respected by default
|
|
30
|
+
- **Sessions**: 30-min inactivity rotation, persisted across reloads
|
|
31
|
+
- **Never throws**: all public methods are guarded; enable `debug: true` to see internal warnings
|
|
32
|
+
|
|
33
|
+
## Development
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm install
|
|
37
|
+
npm test # unit + conformance (shared spec fixtures)
|
|
38
|
+
npm run build # tsup → dist/
|
|
39
|
+
npm run size # size-limit gate (<10KB gz)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`npm test` runs under jsdom with the network faked, so it cannot see gzip upload, the
|
|
43
|
+
`sendBeacon` unload path, CORS, real localStorage across a navigation, or `depsmith-sdk.global.js`
|
|
44
|
+
loaded over a `<script src>`. [`../e2e/`](../e2e) covers those in a real Chromium against a
|
|
45
|
+
real collector — run it after `npm run build`, since it tests the bundle on disk.
|
|
46
|
+
|
|
47
|
+
Build outputs:
|
|
48
|
+
|
|
49
|
+
| File | Consumer |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `dist/index.js` / `.cjs` / `.d.ts` | npm / bundlers |
|
|
52
|
+
| `dist/depsmith-sdk.global.js` | `<script src>` — e.g. a Shopify theme asset |
|
|
53
|
+
| `dist/depsmith-sdk.pixel.global.js` | Shopify **custom pixel** (checkout + purchase) — see [`examples/shopify/`](./examples/shopify) |
|
|
54
|
+
|
|
55
|
+
Shopify: [integration reference](./examples/shopify/INTEGRATION.md) · [developer guide](./examples/shopify/README.md) · [merchant install guide](./examples/shopify/INSTALL.md)
|
|
56
|
+
|
|
57
|
+
Try it live: build, start `node ../tools/mock-collector/server.js`, then serve `examples/vanilla/` (e.g. `npx serve ../..`).
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function v(e,i){let t=[],r=e;for(;r&&r!==document.documentElement&&t.length<i;){let o=r.tagName.toLowerCase();if(r.id){t.unshift(`${o}#${r.id}`);break}let n=Array.from(r.classList).slice(0,3);n.length&&(o+=`.${n.join(".")}`);let s=r.parentElement;if(s){let c=Array.from(s.children).filter(a=>a.tagName===r.tagName);c.length>1&&(o+=`:nth-of-type(${c.indexOf(r)+1})`)}t.unshift(o),r=s}return t.join(" > ")}function E(e,i){if(e.closest("[data-depsmith-sdk-no-capture]"))return!0;for(let t of i)try{if(e.closest(t))return!0}catch{}return!1}var S=new Set(["password","email","tel","hidden","number"]);function y(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e.closest("[data-depsmith-sdk-mask]"))return;let i=e.textContent?.trim().replace(/\s+/g," ");return i?i.slice(0,255):void 0}function L(e){return e instanceof HTMLInputElement?S.has(e.type)||!!e.closest("[data-depsmith-sdk-mask]"):!1}var A='a, button, [role="button"], input[type="submit"], input[type="button"], [data-depsmith-sdk-capture]';function R(e,i){let t=[],r=[];if(e.clicks&&t.push(H(e,i)),e.forms&&t.push(T(e,i)),e.scrolls){let o=_(i);t.push(o.stop),r.push(o.rearm)}return e.pageviews&&r.push(i.page),r.length>0&&t.push(C(()=>{for(let o of r)o()})),()=>{for(let o of t.splice(0))o()}}function H(e,i){let t=e.clicks!=="all",r=o=>{let n=o.target;if(!(n instanceof Element))return;let s=n.closest(A);if(t&&!s)return;let c=s??n;if(E(c,e.ignoredSelectors))return;let a={$ac_kind:"click",$ac_selector:v(c,e.selectorMaxDepth),$ac_tag:c.tagName.toLowerCase()},m=y(c);m&&(a.$ac_text=m),c instanceof HTMLAnchorElement&&c.href&&(a.$ac_href=c.href),i.emit(a)};return document.documentElement.addEventListener("click",r,{capture:!0,passive:!0}),()=>document.documentElement.removeEventListener("click",r,{capture:!0})}function T(e,i){let t=r=>{let o=r.target;if(!(o instanceof HTMLFormElement)||E(o,e.ignoredSelectors))return;let n=Array.from(o.elements).filter(s=>s instanceof HTMLInputElement&&!L(s)).map(s=>s.name||s.id).filter(Boolean).slice(0,50);i.emit({$ac_kind:"form_submit",$ac_selector:v(o,e.selectorMaxDepth),$ac_form_id:o.id||null,$ac_form_fields:n})};return document.documentElement.addEventListener("submit",t,{capture:!0,passive:!0}),()=>document.documentElement.removeEventListener("submit",t,{capture:!0})}var p=[25,50,75,100],k=240;function _(e){let i=0,t=-1,r=0,o=!1,n,s=()=>{t=n?n.scrollHeight-n.clientHeight:document.documentElement.scrollHeight-window.innerHeight},c=()=>Math.min(100,Math.round((n?n.scrollTop:window.scrollY)/t*100)),a=()=>{if(r=0,t<=0&&s(),t<=0||c()<p[i]||(s(),t<=0))return;let l=c();for(;i<p.length&&l>=p[i];)e.emit({$ac_kind:"scroll_depth",$ac_depth:p[i]}),i++;i>=p.length&&b()},m=l=>{if(n&&!n.isConnected&&(n=void 0),n===null&&t===0&&(n=void 0),n===void 0){let d=l.target;if(!(d instanceof Element)||d===document.documentElement||document.documentElement.scrollHeight>window.innerHeight)n=null;else{let h=d;if(h.scrollHeight-h.clientHeight<k)return;n=h}t=-1,g()}else if(n&&l.target!==n)return;r===0&&(r=x(a))},f=()=>{t=-1},u=null,g=()=>{if(!(typeof ResizeObserver>"u"))try{if(u?.disconnect(),u=new ResizeObserver(f),u.observe(n??document.documentElement),n){let l=n.children;for(let d=0;d<l.length;d++)u.observe(l[d])}}catch{u=null}},w=()=>{o||(o=!0,window.addEventListener("scroll",m,{capture:!0,passive:!0}),window.addEventListener("resize",f,{passive:!0}),window.addEventListener("orientationchange",f,{passive:!0}),g())},b=()=>{o&&(o=!1,window.removeEventListener("scroll",m,{capture:!0}),window.removeEventListener("resize",f),window.removeEventListener("orientationchange",f),u?.disconnect(),u=null)};return w(),{stop:()=>{r!==0&&$(r),r=0,b()},rearm:()=>{i=0,t=-1,n=void 0,w()}}}function x(e){return typeof requestAnimationFrame=="function"?requestAnimationFrame(e):setTimeout(e,16)}function $(e){typeof cancelAnimationFrame=="function"?cancelAnimationFrame(e):clearTimeout(e)}function C(e){let i=location.href,t=()=>{location.href!==i&&(i=location.href,e())},r=history.pushState.bind(history),o=history.replaceState.bind(history);return history.pushState=(...n)=>{r(...n),t()},history.replaceState=(...n)=>{o(...n),t()},window.addEventListener("popstate",t),()=>{history.pushState=r,history.replaceState=o,window.removeEventListener("popstate",t)}}export{R as startAutocapture};
|
|
2
|
+
//# sourceMappingURL=autocapture.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/autocapture/selector.ts","../src/autocapture/index.ts"],"sourcesContent":["/** CSS selector generation for autocaptured elements, capped at a configurable depth. */\nexport function elementSelector(element: Element, maxDepth: number): string {\n const parts: string[] = [];\n let current: Element | null = element;\n\n while (current && current !== document.documentElement && parts.length < maxDepth) {\n let part = current.tagName.toLowerCase();\n if (current.id) {\n parts.unshift(`${part}#${current.id}`);\n break; // ids are unique enough — stop here\n }\n const classes = Array.from(current.classList).slice(0, 3);\n if (classes.length) part += `.${classes.join('.')}`;\n\n const parent: Element | null = current.parentElement;\n if (parent) {\n const siblings = Array.from(parent.children).filter((c) => c.tagName === current!.tagName);\n if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(current) + 1})`;\n }\n parts.unshift(part);\n current = parent;\n }\n\n return parts.join(' > ');\n}\n\n/** True when the element (or an ancestor) opts out of autocapture. */\nexport function isIgnored(element: Element, ignoredSelectors: string[]): boolean {\n if (element.closest('[data-depsmith-sdk-no-capture]')) return true;\n for (const selector of ignoredSelectors) {\n try {\n if (element.closest(selector)) return true;\n } catch {\n // invalid selector in config — skip it\n }\n }\n return false;\n}\n\nconst SENSITIVE_INPUT_TYPES = new Set(['password', 'email', 'tel', 'hidden', 'number']);\n\n/** Element text, aggressively masked: never inputs, never [data-depsmith-sdk-mask], 255-char cap. */\nexport function safeText(element: Element): string | undefined {\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) return undefined;\n if (element.closest('[data-depsmith-sdk-mask]')) return undefined;\n const text = element.textContent?.trim().replace(/\\s+/g, ' ');\n return text ? text.slice(0, 255) : undefined;\n}\n\nexport function isSensitiveField(input: Element): boolean {\n if (!(input instanceof HTMLInputElement)) return false;\n return SENSITIVE_INPUT_TYPES.has(input.type) || !!input.closest('[data-depsmith-sdk-mask]');\n}\n","/**\n * Web autocapture engine — lazily loaded so the core bundle stays under 10KB gz.\n * Clicks (delegation), form submits (values never captured), scroll depth\n * (quartiles), and SPA pageviews (History API patch). See API_SPEC §3 for the\n * reserved $autocapture event.\n */\nimport type { AutocaptureConfig } from '../config';\nimport type { Properties } from '../types';\nimport { elementSelector, isIgnored, isSensitiveField, safeText } from './selector';\n\nexport interface AutocaptureHooks {\n /** Emits a $autocapture event through the client pipeline. */\n emit(properties: Properties): void;\n /** Emits a $page_view through the client pipeline (SPA navigation). */\n page(): void;\n}\n\n/** Elements a click is attributed to when `clicks: 'interactive'`. */\nconst INTERACTIVE_SELECTOR =\n 'a, button, [role=\"button\"], input[type=\"submit\"], input[type=\"button\"], [data-depsmith-sdk-capture]';\n\nexport function startAutocapture(\n config: Required<AutocaptureConfig>,\n hooks: AutocaptureHooks\n): () => void {\n const teardowns: Array<() => void> = [];\n /** Run on SPA navigation, in registration order. */\n const onNavigate: Array<() => void> = [];\n\n if (config.clicks) teardowns.push(captureClicks(config, hooks));\n if (config.forms) teardowns.push(captureForms(config, hooks));\n if (config.scrolls) {\n const scroll = captureScrollDepth(hooks);\n teardowns.push(scroll.stop);\n // Re-arm before the pageview so the new page's quartiles are live by the time it fires.\n onNavigate.push(scroll.rearm);\n }\n if (config.pageviews) onNavigate.push(hooks.page);\n\n // One History patch feeding every navigation-sensitive feature, rather than one per\n // feature. Scroll depth needs the same signal pageviews do — without it, a re-armed\n // quartile set on an SPA route change is unreachable once the listener has detached.\n if (onNavigate.length > 0) {\n teardowns.push(\n observeNavigation(() => {\n for (const fn of onNavigate) fn();\n })\n );\n }\n\n return () => {\n for (const stop of teardowns.splice(0)) stop();\n };\n}\n\nfunction captureClicks(config: Required<AutocaptureConfig>, hooks: AutocaptureHooks): () => void {\n // `true` means \"capture clicks\", not \"capture every click on the page\" — it resolves to\n // the interactive gate like the default does. Emitting a $autocapture for a tap on a\n // product image or a bare layout <div> is a firehose that costs a queue write per event\n // and buries the clicks that carry intent, so it takes an explicit 'all' to ask for it.\n const interactiveOnly = config.clicks !== 'all';\n\n const onClick = (event: MouseEvent): void => {\n const target = event.target;\n if (!(target instanceof Element)) return;\n const interactive = target.closest(INTERACTIVE_SELECTOR);\n if (interactiveOnly && !interactive) return;\n const element = interactive ?? target;\n if (isIgnored(element, config.ignoredSelectors)) return;\n\n const properties: Properties = {\n $ac_kind: 'click',\n $ac_selector: elementSelector(element, config.selectorMaxDepth),\n $ac_tag: element.tagName.toLowerCase(),\n };\n const text = safeText(element);\n if (text) properties.$ac_text = text;\n if (element instanceof HTMLAnchorElement && element.href) properties.$ac_href = element.href;\n\n hooks.emit(properties);\n };\n\n document.documentElement.addEventListener('click', onClick, { capture: true, passive: true });\n return () => document.documentElement.removeEventListener('click', onClick, { capture: true });\n}\n\nfunction captureForms(config: Required<AutocaptureConfig>, hooks: AutocaptureHooks): () => void {\n const onSubmit = (event: Event): void => {\n const form = event.target;\n if (!(form instanceof HTMLFormElement)) return;\n if (isIgnored(form, config.ignoredSelectors)) return;\n\n // Field NAMES only — values are never captured (privacy by construction).\n const fields = Array.from(form.elements)\n .filter((el): el is HTMLInputElement => el instanceof HTMLInputElement && !isSensitiveField(el))\n .map((el) => el.name || el.id)\n .filter(Boolean)\n .slice(0, 50);\n\n hooks.emit({\n $ac_kind: 'form_submit',\n $ac_selector: elementSelector(form, config.selectorMaxDepth),\n $ac_form_id: form.id || null,\n $ac_form_fields: fields,\n });\n };\n\n document.documentElement.addEventListener('submit', onSubmit, { capture: true, passive: true });\n return () => document.documentElement.removeEventListener('submit', onSubmit, { capture: true });\n}\n\nconst QUARTILES = [25, 50, 75, 100] as const;\n\n/**\n * Vertical overflow an element needs before it counts as the page's scroller.\n *\n * Roughly a phone viewport. Below it a box is an in-page control — a size-guide popover, a\n * variant list, a sticky mini-cart — and reporting \"100% scroll depth\" because someone\n * flicked through six shipping options would be worse than reporting nothing.\n */\nconst MIN_HOST_SCROLLABLE_PX = 240;\n\ninterface ScrollTracker {\n stop(): void;\n /** Re-arms the quartiles for a new SPA route, re-attaching if we had detached at 100%. */\n rearm(): void;\n}\n\n/**\n * Scroll-depth quartiles, without a layout read per scroll event.\n *\n * The previous version read `document.documentElement.scrollHeight` inside the scroll\n * handler. That forces a synchronous style + layout flush, and scroll fires at input\n * frequency — so it was a forced reflow per frame, for the life of the page, and the\n * listener stayed attached long after all four quartiles had fired.\n *\n * Three changes make it cheap:\n * - handling is coalesced into one `requestAnimationFrame` callback per frame;\n * - the scrollable height is cached, invalidated whenever the document actually resizes,\n * and otherwise re-measured only when the cached value says we are about to cross a\n * quartile — so a lazily growing page still reports accurately, at ≤4 layout reads;\n * - the listener detaches once 100% is reached, since there is nothing left to report.\n *\n * Depth is measured against whichever box actually scrolls. Listening on `window` only\n * ever sees the viewport, so a theme whose `documentElement` and `body` are both\n * `overflow: hidden` — the content scrolling inside a wrapper instead, which is common on\n * modern Shopify themes — emitted nothing at all, for the life of the page, with no error\n * and no way to tell from the outside that the feature was inert.\n *\n * The document has ABSOLUTE PRECEDENCE in that choice: if the document can scroll at all,\n * depth is the document's, no matter which box happened to scroll first. An in-page\n * scroller is only ever adopted on a page where the document is flat. That ordering is what\n * keeps this strictly additive — every page that reported correctly before still does, and\n * the wrapper themes that reported nothing now report too.\n *\n * Invalidation watches the DOCUMENT, not just the window. `resize` fires for the viewport\n * only, so in-page height changes — a filter removing rows, an accordion collapsing, a\n * dismissed banner — left a stale, too-large `scrollable` behind, and `percent()` then\n * under-reported forever: no further quartile could ever fire. The same staleness made a\n * first measurement of exactly 0 (content one viewport tall, lazy content still to land)\n * permanent, because 0 does not satisfy the `< 0` re-measure guard.\n */\nfunction captureScrollDepth(hooks: AutocaptureHooks): ScrollTracker {\n /** Index into QUARTILES; everything below it has already been emitted. */\n let reached = 0;\n /** Cached scrollable extent of {@link host}. -1 means \"needs measuring\". */\n let scrollable = -1;\n /** Pending frame handle, or 0 when none is scheduled. */\n let frame = 0;\n let attached = false;\n /**\n * What depth is measured against, as a three-state value: `undefined` is \"not resolved\n * yet\", `null` is the viewport, an Element is an in-page scroller.\n *\n * Resolved from the first qualifying scroll event rather than searched for, so a\n * container that only exists after hydration is picked up for free — and so resolution\n * costs one layout read for the life of the page instead of a DOM walk at init.\n */\n let host: Element | null | undefined;\n\n const measure = (): void => {\n scrollable = host\n ? host.scrollHeight - host.clientHeight\n : document.documentElement.scrollHeight - window.innerHeight;\n };\n\n const percent = (): number =>\n Math.min(100, Math.round(((host ? host.scrollTop : window.scrollY) / scrollable) * 100));\n\n const evaluate = (): void => {\n frame = 0;\n // `<= 0`, not `< 0`: a page that measured as unscrollable must be re-measured rather\n // than written off, or content arriving after first paint never becomes reportable.\n // Costs nothing in the steady state — an unscrollable page emits no scroll events.\n if (scrollable <= 0) measure();\n if (scrollable <= 0) return;\n // Cheap path: cached metrics say we have not reached the next quartile, so there is\n // nothing to report and no reason to touch layout.\n if (percent() < QUARTILES[reached]!) return;\n\n // About to emit — confirm against live layout, since the page may have grown since we\n // last measured (lazy images, infinite scroll) and the cached value would over-report.\n measure();\n if (scrollable <= 0) return;\n const depth = percent();\n while (reached < QUARTILES.length && depth >= QUARTILES[reached]!) {\n hooks.emit({ $ac_kind: 'scroll_depth', $ac_depth: QUARTILES[reached]! });\n reached++;\n }\n if (reached >= QUARTILES.length) detach();\n };\n\n const onScroll = (event: Event): void => {\n // Give the host back when it can no longer be the page, and let the next branch resolve\n // again. Two ways that happens:\n //\n // - an ELEMENT host went away. A wrapper re-mounted without a history change — a\n // filter rebuilding the product grid — leaves a detached node whose metrics freeze.\n // - the VIEWPORT was adopted, has since measured as genuinely unscrollable, and\n // something else just scrolled. Only reachable once `evaluate` has measured a real\n // zero, so it costs nothing on a page that scrolls, and it keeps the viewport's\n // precedence below from being a one-way door on a theme that fires a stray window\n // scroll before its wrapper ever moves.\n //\n // `reached` deliberately survives both: still the same route, so quartiles already\n // reported must not report a second time.\n if (host && !host.isConnected) host = undefined;\n if (host === null && scrollable === 0) host = undefined;\n\n if (host === undefined) {\n // Resolved from the first scroll that actually happens, rather than by searching the\n // DOM at init: a wrapper that only exists after hydration is picked up for free, and\n // the layout reads below are paid once for the life of the page, not once per frame.\n const target = event.target;\n // THE PAGE WINS WHENEVER THE PAGE CAN SCROLL AT ALL — whatever fired this event.\n // `scroll_depth` has always meant \"how far down the page\", and on an ordinary page an\n // in-page box (a size-guide modal, a cart drawer, a sticky filter rail) is a control\n // WITHIN the page, not a replacement for it. Resolving by \"whichever box scrolled\n // first\" instead meant a shopper who nudged a modal before reading the page lost page\n // depth for the rest of the route — a page that reported correctly before the in-page\n // path existed. Anchoring on the document means this can only ever ADD coverage.\n //\n // The two tests are ordered so the common case costs nothing: a scroll from the\n // document's own scrollport IS the page and needs no measurement, so the viewport\n // path's layout-read budget is exactly what it was before in-page scrollers existed.\n // Only a scroll from some other box has to ask how far the document can go.\n //\n // No `MIN_HOST_SCROLLABLE_PX` on that second test, on purpose: the threshold exists to\n // tell a page from a control, and the document is never a control. A document with\n // 100px of overflow is still the page, and was always reported as one.\n //\n // The document measurement is not cached: a zero means \"cannot scroll YET\", and a page\n // that starts one viewport tall and grows when lazy content lands has to be able to\n // change that answer without waiting on a resize that may never come.\n //\n // The scrollport test is deliberately NOT `target === window`. A Window identity check\n // is unreliable across realms — under vitest's jsdom the event's Window and the\n // module's `window` are different objects, and the same holds inside an iframe — so it\n // silently failed and every viewport scroll was discarded. Window and Document are the\n // two scroll targets that are not Elements, and `documentElement` is the Element that\n // means the same thing; none of that needs identity. `body` is pointedly excluded: it\n // is a viewport proxy in the standard shape but a scroll container in its own right\n // under `html { overflow: hidden } body { overflow: auto }`, where the viewport\n // metrics it would send us to read are inert — which is how that theme reported\n // nothing. It goes to the element path below and is measured for real.\n if (\n !(target instanceof Element) ||\n target === document.documentElement ||\n document.documentElement.scrollHeight > window.innerHeight\n ) {\n host = null;\n } else {\n // The document cannot scroll and something else did: the wrapper-scroller theme, or\n // the `body { overflow: auto }` variant of it, which lands here too because `body`\n // is a real scroll container in that shape and `body.scrollTop` is the live value.\n //\n // A horizontal carousel has no vertical overflow and is filtered out here, as is a\n // small popover — neither is \"the page\", and reporting depth for a box the shopper\n // barely touched would be worse than reporting nothing. Returning without\n // committing leaves the host unresolved, so a real wrapper can still claim it.\n const box = target as Element;\n if (box.scrollHeight - box.clientHeight < MIN_HOST_SCROLLABLE_PX) return;\n host = box;\n }\n scrollable = -1; // metrics now come from a different box\n observeHost();\n // Not the box we report depth for: a mini-cart drawer scrolled to its end must not\n // read as \"the shopper reached the bottom of the page\".\n //\n // Only an ELEMENT host filters by target. Once the viewport is the host there is\n // nothing to filter against: depth comes from `window.scrollY`, which no in-page box\n // can move, so a stray scroll from a drawer costs one coalesced frame and emits\n // nothing. Not asking also means it no longer matters whether an engine targets\n // `document` or `body` for a page scroll — a distinction that was load-bearing here\n // and is not worth depending on.\n } else if (host && event.target !== host) {\n return;\n }\n if (frame !== 0) return; // a frame is already pending — coalesce into it\n frame = scheduleFrame(evaluate);\n };\n\n // Content height and viewport both change here, so the cache is no longer trustworthy.\n const onResize = (): void => {\n scrollable = -1;\n };\n\n /**\n * Catches content-height changes, which `resize` does not report. Without it a page that\n * SHRINKS keeps a too-large cached height and silently stops reporting quartiles.\n * Absent in older Safari and in jsdom, where the window listeners remain the fallback.\n *\n * Re-pointed at the host once one is resolved: an in-page scroller's content can grow\n * while the document's never changes, so observing the document would miss it entirely.\n *\n * An element host is observed together with its children, because the host's own box is\n * its SCROLLPORT — pinned to the viewport (`height: 100vh`) in every theme that scrolls a\n * wrapper, so it does not resize when the content inside it does. Observing it alone gave\n * the host path none of the shrink protection the document path has a test for: a wrapper\n * primed at 20,000px and then collapsed kept the stale extent, and scrolling to its true\n * bottom read ~16% and emitted nothing further. The children are what actually change\n * height. `documentElement` is no substitute here — in exactly these themes it is pinned\n * to 100vh as well.\n */\n let observer: ResizeObserver | null = null;\n const observeHost = (): void => {\n if (typeof ResizeObserver === 'undefined') return;\n try {\n observer?.disconnect();\n observer = new ResizeObserver(onResize);\n observer.observe(host ?? document.documentElement);\n // Index loop, not `for…of`: HTMLCollection is not iterable under this tsconfig's lib,\n // and a spread would cost an array per resolution for no gain.\n if (host) {\n const content = host.children;\n for (let i = 0; i < content.length; i++) observer.observe(content[i]!);\n }\n } catch {\n observer = null; // never let instrumentation break the page\n }\n };\n\n const attach = (): void => {\n if (attached) return;\n attached = true;\n // CAPTURE phase — that single flag is the whole fix. Scroll events do not bubble, so a\n // plain window listener sees only the viewport, and a theme that scrolls an inner\n // wrapper (documentElement and body both `overflow: hidden`, common on modern Shopify\n // themes) emitted nothing at all, silently, for the life of the page. The capture\n // phase runs from the root down to the target, so it delivers scroll from ANY element\n // even though the event never bubbles back up — one listener, both shapes, no DOM\n // search, and the listener stays on `window` exactly as before.\n window.addEventListener('scroll', onScroll, { capture: true, passive: true });\n window.addEventListener('resize', onResize, { passive: true });\n window.addEventListener('orientationchange', onResize, { passive: true });\n observeHost();\n };\n\n const detach = (): void => {\n if (!attached) return;\n attached = false;\n // The capture flag is part of the listener's identity — omitting it here would leave\n // the listener attached for the life of the page.\n window.removeEventListener('scroll', onScroll, { capture: true });\n window.removeEventListener('resize', onResize);\n window.removeEventListener('orientationchange', onResize);\n observer?.disconnect();\n observer = null;\n };\n\n attach();\n\n return {\n stop: () => {\n if (frame !== 0) cancelFrame(frame);\n frame = 0;\n detach();\n },\n rearm: () => {\n reached = 0;\n scrollable = -1;\n // A new route can scroll a different box — a PDP with a document-level scroll after\n // a collection page that scrolled an inner wrapper. Re-resolve rather than keep\n // measuring the old route's container, which may no longer be in the document.\n host = undefined;\n attach();\n },\n };\n}\n\n/** rAF where available; a macrotask in jsdom and other non-visual hosts. */\nfunction scheduleFrame(fn: () => void): number {\n if (typeof requestAnimationFrame === 'function') return requestAnimationFrame(fn);\n return setTimeout(fn, 16) as unknown as number;\n}\n\nfunction cancelFrame(handle: number): void {\n if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(handle);\n else clearTimeout(handle);\n}\n\n/**\n * Calls `onNavigate` when the History API or a popstate changes the URL.\n * Returns a teardown that restores the original History methods.\n */\nfunction observeNavigation(onNavigate: () => void): () => void {\n let lastUrl = location.href;\n const emitIfChanged = (): void => {\n if (location.href === lastUrl) return;\n lastUrl = location.href;\n onNavigate();\n };\n\n const originalPush = history.pushState.bind(history);\n const originalReplace = history.replaceState.bind(history);\n\n history.pushState = (...args: Parameters<History['pushState']>) => {\n originalPush(...args);\n emitIfChanged();\n };\n history.replaceState = (...args: Parameters<History['replaceState']>) => {\n originalReplace(...args);\n emitIfChanged();\n };\n window.addEventListener('popstate', emitIfChanged);\n\n return () => {\n history.pushState = originalPush;\n history.replaceState = originalReplace;\n window.removeEventListener('popstate', emitIfChanged);\n };\n}\n"],"mappings":"AACO,SAASA,EAAgBC,EAAkBC,EAA0B,CAC1E,IAAMC,EAAkB,CAAC,EACrBC,EAA0BH,EAE9B,KAAOG,GAAWA,IAAY,SAAS,iBAAmBD,EAAM,OAASD,GAAU,CACjF,IAAIG,EAAOD,EAAQ,QAAQ,YAAY,EACvC,GAAIA,EAAQ,GAAI,CACdD,EAAM,QAAQ,GAAGE,CAAI,IAAID,EAAQ,EAAE,EAAE,EACrC,KACF,CACA,IAAME,EAAU,MAAM,KAAKF,EAAQ,SAAS,EAAE,MAAM,EAAG,CAAC,EACpDE,EAAQ,SAAQD,GAAQ,IAAIC,EAAQ,KAAK,GAAG,CAAC,IAEjD,IAAMC,EAAyBH,EAAQ,cACvC,GAAIG,EAAQ,CACV,IAAMC,EAAW,MAAM,KAAKD,EAAO,QAAQ,EA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,EACA,MAAO,IAAM,CACXT,EAAU,EACVC,EAAa,GAIbG,EAAO,OACPc,EAAO,CACT,CACF,CACF,CAGA,SAASL,EAAcjC,EAAwB,CAC7C,OAAI,OAAO,uBAA0B,WAAmB,sBAAsBA,CAAE,EACzE,WAAWA,EAAI,EAAE,CAC1B,CAEA,SAASuC,EAAYC,EAAsB,CACrC,OAAO,sBAAyB,WAAY,qBAAqBA,CAAM,EACtE,aAAaA,CAAM,CAC1B,CAMA,SAASzC,EAAkBL,EAAoC,CAC7D,IAAI+C,EAAU,SAAS,KACjBC,EAAgB,IAAY,CAC5B,SAAS,OAASD,IACtBA,EAAU,SAAS,KACnB/C,EAAW,EACb,EAEMiD,EAAe,QAAQ,UAAU,KAAK,OAAO,EAC7CC,EAAkB,QAAQ,aAAa,KAAK,OAAO,EAEzD,eAAQ,UAAY,IAAIC,IAA2C,CACjEF,EAAa,GAAGE,CAAI,EACpBH,EAAc,CAChB,EACA,QAAQ,aAAe,IAAIG,IAA8C,CACvED,EAAgB,GAAGC,CAAI,EACvBH,EAAc,CAChB,EACA,OAAO,iBAAiB,WAAYA,CAAa,EAE1C,IAAM,CACX,QAAQ,UAAYC,EACpB,QAAQ,aAAeC,EACvB,OAAO,oBAAoB,WAAYF,CAAa,CACtD,CACF","names":["elementSelector","element","maxDepth","parts","current","part","classes","parent","siblings","c","isIgnored","ignoredSelectors","selector","SENSITIVE_INPUT_TYPES","safeText","text","isSensitiveField","input","INTERACTIVE_SELECTOR","startAutocapture","config","hooks","teardowns","onNavigate","captureClicks","captureForms","scroll","captureScrollDepth","observeNavigation","fn","stop","interactiveOnly","onClick","event","target","interactive","element","isIgnored","properties","elementSelector","text","safeText","onSubmit","form","fields","el","isSensitiveField","QUARTILES","MIN_HOST_SCROLLABLE_PX","reached","scrollable","frame","attached","host","measure","percent","evaluate","depth","detach","onScroll","box","observeHost","scheduleFrame","onResize","observer","content","i","attach","cancelFrame","handle","lastUrl","emitIfChanged","originalPush","originalReplace","args"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var DepsmithSdkBundle=(()=>{var H=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var me=(t,e)=>()=>(t&&(e=t(t=0)),e);var ve=(t,e)=>{for(var r in e)H(t,r,{get:e[r],enumerable:!0})},it=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of rt(e))!nt.call(t,i)&&i!==r&&H(t,i,{get:()=>e[i],enumerable:!(n=tt(e,i))||n.enumerable});return t};var ot=t=>it(H({},"__esModule",{value:!0}),t);function j(t,e){let r=[],n=t;for(;n&&n!==document.documentElement&&r.length<e;){let i=n.tagName.toLowerCase();if(n.id){r.unshift(`${i}#${n.id}`);break}let o=Array.from(n.classList).slice(0,3);o.length&&(i+=`.${o.join(".")}`);let s=n.parentElement;if(s){let a=Array.from(s.children).filter(d=>d.tagName===n.tagName);a.length>1&&(i+=`:nth-of-type(${a.indexOf(n)+1})`)}r.unshift(i),n=s}return r.join(" > ")}function Y(t,e){if(t.closest("[data-depsmith-sdk-no-capture]"))return!0;for(let r of e)try{if(t.closest(r))return!0}catch{}return!1}function ye(t){if(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t.closest("[data-depsmith-sdk-mask]"))return;let e=t.textContent?.trim().replace(/\s+/g," ");return e?e.slice(0,255):void 0}function Se(t){return t instanceof HTMLInputElement?st.has(t.type)||!!t.closest("[data-depsmith-sdk-mask]"):!1}var st,be=me(()=>{"use strict";st=new Set(["password","email","tel","hidden","number"])});var ke={};ve(ke,{startAutocapture:()=>dt});function dt(t,e){let r=[],n=[];if(t.clicks&&r.push(ut(t,e)),t.forms&&r.push(ct(t,e)),t.scrolls){let i=lt(e);r.push(i.stop),n.push(i.rearm)}return t.pageviews&&n.push(e.page),n.length>0&&r.push(gt(()=>{for(let i of n)i()})),()=>{for(let i of r.splice(0))i()}}function ut(t,e){let r=t.clicks!=="all",n=i=>{let o=i.target;if(!(o instanceof Element))return;let s=o.closest(at);if(r&&!s)return;let a=s??o;if(Y(a,t.ignoredSelectors))return;let d={$ac_kind:"click",$ac_selector:j(a,t.selectorMaxDepth),$ac_tag:a.tagName.toLowerCase()},u=ye(a);u&&(d.$ac_text=u),a instanceof HTMLAnchorElement&&a.href&&(d.$ac_href=a.href),e.emit(d)};return document.documentElement.addEventListener("click",n,{capture:!0,passive:!0}),()=>document.documentElement.removeEventListener("click",n,{capture:!0})}function ct(t,e){let r=n=>{let i=n.target;if(!(i instanceof HTMLFormElement)||Y(i,t.ignoredSelectors))return;let o=Array.from(i.elements).filter(s=>s instanceof HTMLInputElement&&!Se(s)).map(s=>s.name||s.id).filter(Boolean).slice(0,50);e.emit({$ac_kind:"form_submit",$ac_selector:j(i,t.selectorMaxDepth),$ac_form_id:i.id||null,$ac_form_fields:o})};return document.documentElement.addEventListener("submit",r,{capture:!0,passive:!0}),()=>document.documentElement.removeEventListener("submit",r,{capture:!0})}function lt(t){let e=0,r=-1,n=0,i=!1,o,s=()=>{r=o?o.scrollHeight-o.clientHeight:document.documentElement.scrollHeight-window.innerHeight},a=()=>Math.min(100,Math.round((o?o.scrollTop:window.scrollY)/r*100)),d=()=>{if(n=0,r<=0&&s(),r<=0||a()<x[e]||(s(),r<=0))return;let v=a();for(;e<x.length&&v>=x[e];)t.emit({$ac_kind:"scroll_depth",$ac_depth:x[e]}),e++;e>=x.length&&ge()},u=v=>{if(o&&!o.isConnected&&(o=void 0),o===null&&r===0&&(o=void 0),o===void 0){let y=v.target;if(!(y instanceof Element)||y===document.documentElement||document.documentElement.scrollHeight>window.innerHeight)o=null;else{let B=y;if(B.scrollHeight-B.clientHeight<pt)return;o=B}r=-1,w()}else if(o&&v.target!==o)return;n===0&&(n=ft(d))},p=()=>{r=-1},l=null,w=()=>{if(!(typeof ResizeObserver>"u"))try{if(l?.disconnect(),l=new ResizeObserver(p),l.observe(o??document.documentElement),o){let v=o.children;for(let y=0;y<v.length;y++)l.observe(v[y])}}catch{l=null}},he=()=>{i||(i=!0,window.addEventListener("scroll",u,{capture:!0,passive:!0}),window.addEventListener("resize",p,{passive:!0}),window.addEventListener("orientationchange",p,{passive:!0}),w())},ge=()=>{i&&(i=!1,window.removeEventListener("scroll",u,{capture:!0}),window.removeEventListener("resize",p),window.removeEventListener("orientationchange",p),l?.disconnect(),l=null)};return he(),{stop:()=>{n!==0&&ht(n),n=0,ge()},rearm:()=>{e=0,r=-1,o=void 0,he()}}}function ft(t){return typeof requestAnimationFrame=="function"?requestAnimationFrame(t):setTimeout(t,16)}function ht(t){typeof cancelAnimationFrame=="function"?cancelAnimationFrame(t):clearTimeout(t)}function gt(t){let e=location.href,r=()=>{location.href!==e&&(e=location.href,t())},n=history.pushState.bind(history),i=history.replaceState.bind(history);return history.pushState=(...o)=>{n(...o),r()},history.replaceState=(...o)=>{i(...o),r()},window.addEventListener("popstate",r),()=>{history.pushState=n,history.replaceState=i,window.removeEventListener("popstate",r)}}var at,x,pt,we=me(()=>{"use strict";be();at='a, button, [role="button"], input[type="submit"], input[type="button"], [data-depsmith-sdk-capture]';x=[25,50,75,100],pt=240});var Bt={};ve(Bt,{DepsmithSdk:()=>fe,DepsmithSdkClient:()=>m});function xe(){return Promise.resolve().then(()=>(we(),ke))}var X=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]],mt=Object.fromEntries(X.map(([t])=>[t,!0]));function Ee(t){let e={...mt};if(!t)return e;for(let[r]of X)t[r]===!1&&(e[r]=!1);return e}function _e(t,e){let r=t;for(let[n,i,o]of X){if(e[n])continue;if(o===void 0){delete r[i];continue}let s={...r[i]};delete s[o],Object.keys(s).length>0?r[i]=s:delete r[i]}return t}var W={clicks:"interactive",forms:!0,scrolls:!0,pageviews:!0,ignoredSelectors:[],selectorMaxDepth:5};function vt(t){return t===void 0?W.clicks:t===!0?"interactive":t}function Ae(t){if(!t||typeof t.apiKey!="string"||t.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof t.endpoint!="string"||!/^https?:\/\//.test(t.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=t.autocapture===!0?W:t.autocapture&&typeof t.autocapture=="object"?{...W,...t.autocapture,clicks:vt(t.autocapture.clicks)}:!1;return{apiKey:t.apiKey,endpoint:t.endpoint.replace(/\/+$/,""),batchSize:G(t.batchSize??20,1,500),batchIntervalMs:Math.max(t.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(t.maxQueueSize??1e3,1),maxQueueBytes:Math.max(t.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(t.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(t.sampleRate)?G(t.sampleRate,0,1):1,sessionEvents:t.sessionEvents==="derive"?"derive":"emit",consentMode:t.consentMode??"granted",respectDnt:t.respectDnt??!0,maxRetries:G(t.maxRetries??5,0,10),debug:t.debug??!1,defaultProperties:t.defaultProperties??{},autocapture:e,compression:t.compression??"gzip",childSafeMode:t.childSafeMode??!1,anonymizeIp:(t.anonymizeIp??!1)||(t.childSafeMode??!1),deviceFingerprinting:t.deviceFingerprinting??!0,geolocation:t.geolocation??!1,trackingOptions:Ee(t.trackingOptions),cookieDomain:t.cookieDomain??"",storage:t.storage??"localstorage"}}function G(t,e,r){return Math.min(Math.max(t,e),r)}function J(t){let e=5381;for(let r=0;r<t.length;r++)e=(e<<5)+e+t.charCodeAt(r)>>>0;return e.toString(36)}function Pe(t){let e=2166136261;for(let r=0;r<t.length;r++)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function yt(t){return Pe(t).toString(36)}function Oe(t){return Pe(t)/4294967296}function Q(t){return J(t)+yt(t)}var Z={},Ce=!1;function Te(){if(!Ce){Ce=!0;try{let t=navigator?.userAgentData;if(typeof t?.getHighEntropyValues!="function")return;t.getHighEntropyValues(["model","platformVersion"]).then(e=>{Z=e}).catch(()=>{})}catch{}}}function Ie(){let t={};if(typeof navigator>"u")return t;let e=navigator.userAgent||"",r=navigator.userAgentData,n=wt(e,r);n&&(t.browser=n);let i=Et(e);if(i){let a=bt(i.name,Z.platformVersion);t.os=a?{...i,version:a}:i}let o=_t(e,r);o&&(t.deviceType=o);let s=St(e,i);return s&&(t.device=s),t}function St(t,e){let r={};(e?.name==="iOS"||e?.name==="macOS")&&(r.manufacturer="Apple");let n=Z.model?.trim();return n?r.model=n:/iPhone/.test(t)?r.model="iPhone":/iPad/.test(t)&&(r.model="iPad"),r.manufacturer||r.model?r:void 0}function bt(t,e){let r=e?.trim();if(r){if(t==="Windows"){let n=Number.parseInt(r.split(".")[0]??"",10);return!Number.isFinite(n)||n===0?void 0:n>=13?"11":"10"}return $e(r)}}var kt=[{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 wt(t,e){for(let n of kt){if(n.requires&&!n.requires.test(t))continue;let i=t.match(n.pattern);if(i)return{name:n.name,version:i[1],engine:n.engine}}let r=e?.brands?.find(n=>!/not.?a.?brand/i.test(n.brand));if(r)return{name:r.brand,version:r.version}}var xt=[{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 Et(t){for(let e of xt){if(e.requires&&!e.requires.test(t))continue;let r=t.match(e.pattern);if(r)return{name:e.name,version:$e((r[1]??"").replace(/_/g,"."))}}if(/Linux/.test(t))return{name:"Linux"}}function $e(t){let e=t.replace(/(\.0)+$/,"");return e.length>0?e:t}function _t(t,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(t))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(t))return"mobile";if(/Android/.test(t))return"tablet";if(typeof navigator<"u"&&t)return"desktop"}var O=null,C=null;function Me(){return C!==null||(C=At()),C}function T(){return O!==null||(O=Q(Me().map(t=>t.value).join("|"))),O}function Re(){let t={};for(let e of Me())t[`$fp_${e.name}`]=e.value;return t}function At(){let t=[];try{if(typeof screen<"u"&&t.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;t.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),t.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),t.push({name:"plat",value:`plat:${navigator.platform??""}`}),t.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}t.push({name:"canvas",value:`canvas:${Pt()}`})}catch{}return t}function Pt(){try{if(typeof document>"u")return"";let t=document.createElement("canvas");t.width=240,t.height=60;let e=t.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(),Q(t.toDataURL())):""}catch{return""}}function De(){try{if(typeof navigator>"u")return{};let t=navigator.connection;if(!t)return{};switch(t.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(t.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var I=null,Le=0,Ne=!1,E=!1,Ue=null;function qe(){if(!Ne){Ne=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let t=navigator.permissions;if(typeof t?.query!="function")return;t.query({name:"geolocation"}).then(e=>{Ue=e,e.state==="granted"&&ee(),e.onchange=()=>{e.state==="granted"?ee():I=null}}).catch(()=>{})}catch{}}}function ee(){if(!E){E=!0;try{navigator.geolocation.getCurrentPosition(t=>{E=!1;let{latitude:e,longitude:r,accuracy:n}=t.coords;if(!Number.isFinite(e)||!Number.isFinite(r))return;let i={latitude:e,longitude:r,source:"gps"};Number.isFinite(n)&&(i.accuracy=n),I=i,Le=Date.now()},()=>{E=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{E=!1}}}function ze(){if(I)return Date.now()-Le>3e5&&Ue?.state==="granted"&&ee(),{...I}}var re="@depsmith/depsmith-sdk",S="0.6.0",te=null;function Ot(){if(te)return te;let t={};try{t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(t.locale=navigator.language,t.userAgent=navigator.userAgent),te=t,t}function A(t={}){let e={library:{name:re,version:S}};_(()=>{typeof window<"u"&&window.location&&(e.page={url:window.location.href,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0})}),_(()=>{typeof window<"u"&&window.screen&&(e.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),_(()=>{let r=Ot();r.locale!==void 0&&(e.locale=r.locale),r.userAgent!==void 0&&(e.user_agent=r.userAgent),r.timezone!==void 0&&(e.timezone=r.timezone)}),_(()=>{t.fingerprint&&Ct(e)}),_(()=>{if(t.geolocation){let r=ze();r&&(e.location=r)}});try{if(t.overrides){for(let[r,n]of Object.entries(t.overrides))n!==void 0&&(e[r]=n);e.library={name:re,version:S}}}catch{}return t.tracking&&_e(e,t.tracking),e}function Ct(t){let{browser:e,os:r,deviceType:n,device:i}=Ie();e&&(t.browser=e),r&&(t.os=r);let o={};n&&(o.type=n),i?.manufacturer&&(o.manufacturer=i.manufacturer),i?.model&&(o.model=i.model),Object.keys(o).length>0&&(t.device=o);let s=De();s.type&&(t.network={...t.network,type:s.type})}function _(t){try{t()}catch{}}function Ke(){try{if(typeof navigator>"u")return!1;let t=navigator,e=typeof window<"u"?window:{},r=navigator.doNotTrack??e.doNotTrack??t.msDoNotTrack;return r==="1"||r==="yes"}catch{return!1}}var ne="depsmith_consent",$=class{constructor(e,r,n){this.storage=e;this.dntActive=n;let i=e.get(ne);this.state=i==="granted"||i==="denied"||i==="pending"?i:r}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(ne,"granted")}optOut(){this.state="denied",this.storage.set(ne,"denied")}};var M=t=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(t,{timeout:250});return}setTimeout(t,0)};var R="depsmith_queue",Tt=512*1024,ie=2,It=new Set(["identify","alias","group"]);function $t(t){return It.has(t?.event_type)}var D=class{constructor(e,r,n,i={}){this.storage=e;this.maxSize=r;this.logger=n;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=i.maxChars??Tt,this.schedule=i.schedule??M,this.restore()}restore(){try{let e=this.storage.get(R);if(!e)return;let r=JSON.parse(e);if(!Array.isArray(r))return;let n=r.filter(i=>!!i&&typeof i=="object"&&typeof i.event_id=="string");this.reset(n),n.length!==r.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(R)}}reset(e){this.events=e,this.sizes=e.map(r=>Fe(r)),this.sizeSum=this.sizes.reduce((r,n)=>r+n,0)}serializedLength(){return this.events.length===0?ie:this.sizeSum+(this.events.length-1)+ie}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(R,JSON.stringify(this.events)))}prepend(e){let r=new Set(this.events.map(i=>i.event_id)),n=e.filter(i=>!!i&&typeof i=="object"&&typeof i.event_id=="string"&&!r.has(i.event_id));n.length!==0&&(this.reset([...n,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let r=Fe(e);if(r+ie>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(r),this.sizeSum+=r,this.events.length>this.maxSize){let n=this.events.length-this.maxSize;this.dropOldest(n),this.logger.warn(`queue cap reached; dropped ${n} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!$t(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 r=0;r<e&&this.events.length>0;r++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e){return this.events.slice(0,e)}remove(e){let r=new Set(e),n=[],i=[],o=0;for(let s=0;s<this.events.length;s++){let a=this.events[s];if(r.has(a.event_id))continue;let d=this.sizes[s];n.push(a),i.push(d),o+=d}this.events=n,this.sizes=i,this.sizeSum=o,this.markDirty()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(R)}};function Fe(t){return JSON.stringify(t).length}function f(t){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]=t/2**40&255,e[1]=t/2**32&255,e[2]=t/2**24&255,e[3]=t/2**16&255,e[4]=t/2**8&255,e[5]=t&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;let r=[];for(let n=0;n<16;n++)r.push(e[n].toString(16).padStart(2,"0"));return`${r[0]}${r[1]}${r[2]}${r[3]}-${r[4]}${r[5]}-${r[6]}${r[7]}-${r[8]}${r[9]}-${r[10]}${r[11]}${r[12]}${r[13]}${r[14]}${r[15]}`}function b(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t))return null;let e=t.slice(0,8)+t.slice(9,13),r=parseInt(e,16);return Number.isFinite(r)?r:null}var k=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,r){this.data.set(e,r)}remove(e){this.data.delete(e)}},oe=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,r){try{this.ls.setItem(e,r)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},N=class{constructor(e){this.domain=e}get(e){try{let r=`${encodeURIComponent(e)}=`;for(let n of document.cookie.split("; "))if(n.startsWith(r))return decodeURIComponent(n.slice(r.length))}catch{}return null}attributes(e){let r=this.domain?`; domain=${this.domain}`:"",n=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${r}; path=/; max-age=${e}; SameSite=Lax${n}`}set(e,r){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(r)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},Mt=new Set(["depsmith_anonymous_id"]),L=class{constructor(e,r,n=Mt){this.primary=e;this.secondary=r;this.mirrored=n}get(e){let r=this.primary.get(e);if(!this.mirrored.has(e))return r;let n=this.secondary.get(e);if(r===n)return r;if(r===null&&n!==null)return this.primary.set(e,n),n;if(n===null&&r!==null)return this.secondary.set(e,r),r;let i=Rt(r,n)??r;return this.primary.set(e,i),this.secondary.set(e,i),i}set(e,r){this.primary.set(e,r),this.mirrored.has(e)&&this.secondary.set(e,r)}remove(e){this.primary.remove(e),this.secondary.remove(e)}};function Rt(t,e){let r=b(t),n=b(e);return r===null||n===null?null:r<=n?t:e}var P=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(r=>{try{let n=indexedDB.open(e,1);n.onupgradeneeded=()=>n.result.createObjectStore("kv"),n.onsuccess=()=>{this.db=n.result;let i=this.db.transaction("kv","readonly").objectStore("kv"),o=i.getAllKeys(),s=i.getAll();s.onsuccess=()=>{let a=o.result;s.result.forEach((d,u)=>{let p=a[u];p!==void 0&&(this.snapshot.set(p,d),this.mirror.has(p)||this.mirror.set(p,d))}),r()},s.onerror=()=>r()},n.onerror=()=>r()}catch{r()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,r){this.mirror.set(e,r),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(r,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}};function Ve(){try{if(typeof window<"u"&&window.localStorage){let t="__depsmith_probe__";return window.localStorage.setItem(t,"1"),window.localStorage.removeItem(t),new oe(window.localStorage)}}catch{}return new k}var se="depsmith_anonymous_id",ae="depsmith_user_id",de="depsmith_group_id",U="depsmith_user_props",q=class{constructor(e,r){this.storage=e;this.clock=r}get anonymousId(){let e=this.storage.get(se);return e||(e=f(this.clock.now()),this.storage.set(se,e)),e}get userId(){return this.storage.get(ae)}get groupId(){return this.storage.get(de)}identify(e){this.storage.set(ae,e)}setGroup(e){this.storage.set(de,e)}getUserProps(){try{return JSON.parse(this.storage.get(U)??"{}")}catch{return{}}}setUserProp(e,r){let n=this.getUserProps();n[e]=r,this.storage.set(U,JSON.stringify(n))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let r=this.getUserProps();delete r[e],this.storage.set(U,JSON.stringify(r))}reset(){this.storage.remove(ae),this.storage.remove(de),this.storage.remove(U);let e=f(this.clock.now());return this.storage.set(se,e),e}};var Be="depsmith_session",z=class{constructor(e,r,n,i=M){this.storage=e;this.clock=r;this.timeoutMs=n;this.pending=null;this.scheduled=!1;this.schedule=i}load(){let e=this.readStored(),r=this.pending;return r?!e||r.lastActivityAt>=e.lastActivityAt?r:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(Be);if(!e)return null;let r=JSON.parse(e);return typeof r.id!="string"||typeof r.lastActivityAt!="number"?null:(typeof r.startedAt!="number"&&(r.startedAt=b(r.id)??r.lastActivityAt),r)}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(Be,JSON.stringify(e)))}mint(e){let r={id:f(e),lastActivityAt:e,startedAt:e};return this.save(r),r}touch(){let e=this.clock.now(),r=this.load();if(!r){let n=this.mint(e);return{sessionId:n.id,startedAt:e,startedSession:{id:n.id,startedAt:e}}}if(e-r.lastActivityAt>this.timeoutMs){let n=this.mint(e);return{sessionId:n.id,startedAt:e,endedSession:{id:r.id,lastActivityAt:r.lastActivityAt,startedAt:r.startedAt},startedSession:{id:n.id,startedAt:e}}}return this.save({id:r.id,lastActivityAt:e,startedAt:r.startedAt}),{sessionId:r.id,startedAt:r.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,r){let n=b(e);return n===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:r??n}),!0)}rotate(){return this.mint(this.clock.now()).id}};function h(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return e.warn("properties must be an object; ignoring",t),{};let r={},n=0;for(let[i,o]of Object.entries(t)){if(n>=200){e.warn("properties exceed 200 keys; excess dropped");break}let s=Dt(o,e);if(s===void 0){e.debug(`property "${i}" dropped (unsupported value)`);continue}r[String(i)]=s,n++}return r}function ue(t){if(t===null)return null;let e=typeof t;if(e==="string"||e==="boolean")return t;if(e==="number")return Number.isFinite(t)?t:void 0;if(t instanceof Date)return isNaN(t.getTime())?void 0:t.toISOString()}function Dt(t,e){let r=ue(t);if(r!==void 0)return r;if(!(t===void 0||typeof t=="function"||typeof t=="symbol")){if(Array.isArray(t)){let n=[];for(let i of t.slice(0,100)){let o=ue(i);n.push(o!==void 0?o:He(i))}return n}if(typeof t=="object"){let n={},i=0;for(let[o,s]of Object.entries(t)){if(i>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let a=ue(s);n[String(o)]=a!==void 0?a:He(s),i++}return n}}}function He(t){try{return JSON.stringify(t)??"null"}catch{return String(t)}}var Nt=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],je=50,Ye=200;function ce(t,e){if(!t||typeof t!="object")return;if(t.$clear_all===!0){let o=Object.keys(t).filter(s=>s!=="$clear_all");return o.length>0&&e.warn(`$clear_all is exclusive; ignored ${o.join(", ")}`),{$clear_all:!0}}let r={},n=new Set,i=(o,s)=>n.has(o)?(e.debug(`"${o}" has an operator already; ${s} dropped`),!1):(n.add(o),!0);for(let o of Nt){let s=t[o];if(!s||typeof s!="object")continue;let a=h(s,e),d={};for(let[u,p]of Object.entries(a))i(u,o)&&(d[u]=p);Object.keys(d).length>0&&(r[o]=d)}if(t.$add&&typeof t.$add=="object"){let o={},s=0;for(let[a,d]of Object.entries(t.$add)){if(s>=je){e.debug(`$add over ${je} keys; excess dropped`);break}if(typeof d!="number"||!Number.isFinite(d)){e.debug(`$add "${a}" is not finite; dropped`);continue}i(a,"$add")&&(o[a]=d,s++)}Object.keys(o).length>0&&(r.$add=o)}if(Array.isArray(t.$unset)){let o=[];for(let s of t.$unset){if(o.length>=Ye){e.debug(`$unset over ${Ye} keys; excess dropped`);break}typeof s!="string"||s.length===0||i(s,"$unset")&&o.push(s)}o.length>0&&(r.$unset=o)}return Object.keys(r).length>0?r:void 0}function K(t,e){return Object.keys(e).length>0?{[t]:e}:void 0}var Xe={now:()=>Date.now()};function g(t){return new Date(t).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function Ge(t){return t===0||t===408||t===429||t>=500}var Lt=1e3,Ut=32e3;function We(t,e=Math.random){let r=Math.min(Lt*2**t,Ut);return Math.round(e()*r)}async function qt(t){let e=new CompressionStream("gzip"),r=e.writable.getWriter();r.write(new TextEncoder().encode(t)).catch(()=>{}),r.close().catch(()=>{});let n=e.readable.getReader(),i=[];for(;;){let{done:d,value:u}=await n.read();if(d)break;i.push(u)}let o=i.reduce((d,u)=>d+u.length,0),s=new Uint8Array(new ArrayBuffer(o)),a=0;for(let d of i)s.set(d,a),a+=d.length;return s}function Je(t){let e=[];for(let r of t)e.push(r.event_id);return e}var zt=3e4,Kt=6e4,Ft=10;function Vt(t){return typeof t=="string"?new TextEncoder().encode(t).byteLength:t instanceof Uint8Array?t.byteLength:0}var F=class{constructor(e,r,n){this.queue=e;this.config=r;this.deps=n;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 r=await this.uploadWithRetry(e);if(r==="requeue")return;r==="dropped"&&this.deps.logger.warn(`dropped poison batch of ${e.length}`),this.queue.remove(Je(e))}}async uploadWithRetry(e){let r=this.deps.breaker,n=!1;for(let i=0;i<=this.config.maxRetries;i++){let o=await this.post(e);if(o!==0&&(n=!0),o>=200&&o<300)return r?.ok(),"sent";if(!Ge(o))return r?.ok(),this.deps.logger.warn(`non-retryable ${o}; dropping batch`),"dropped";if(this.deps.logger.debug(`upload attempt ${i+1} failed (${o})`),o===0&&!n&&r?.suspect())break;i<this.config.maxRetries&&await this.deps.sleep(We(i))}return n?r?.ok():r?.fail(),"requeue"}buildPayload(e){let r={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:g(this.deps.clock.now())};return this.config.anonymizeIp&&(r.anonymize_ip=!0),r}async post(e){let r=JSON.stringify(this.buildPayload(e)),n=typeof AbortController<"u"?new AbortController:null,i=null;try{let o=r,s={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream<"u")try{o=await qt(r),s["Content-Encoding"]="gzip"}catch{o=r}let a=Vt(o)<=Kt;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let d={method:"POST",headers:s,body:o,keepalive:a};return n&&(d.signal=n.signal,i=setTimeout(()=>n.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,d)).status}catch{return 0}finally{i!==null&&clearTimeout(i)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:zt}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<Ft;){let r=this.queue.peek(this.config.batchSize),n=this.buildPayload(r);if(!navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(n)],{type:"text/plain"})))return;this.queue.remove(Je(r)),e++}}catch{}}};var pe="depsmith_net_breaker";function Qe(t,e){let r=!1,n=0,i=0,o=3e5,s=(u,p,l)=>typeof u=="number"&&u===u?Math.min(Math.max(u,p),l):p,a=()=>{if(!r){r=!0;try{let u=JSON.parse(t.get(pe)??"0");if(!Array.isArray(u))return;n=s(u[0],0,3),i=s(u[1],0,e.now()+36e5),o=s(u[2],3e5,36e5)}catch{}}},d=()=>{try{n?t.set(pe,JSON.stringify([n,i,o])):t.remove(pe)}catch{}};return{open:()=>(a(),e.now()<i),suspect:()=>(a(),n>0),fail:()=>{a(),++n>=3&&(i=e.now()+o,o=Math.min(o*2,36e5),n=3),d()},ok:()=>{a(),n&&(n=i=0,o=3e5,d())}}}var V=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 Ze=255,m=class{constructor(e,r={}){this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=Ae(e),this.logger=new V(this.config.debug),this.clock=r.clock??Xe,this.storage=r.storage??this.pickStorage(),this.contextProvider=r.contextProvider;let n=this.config.childSafeMode?new k:this.config.storage==="memory"?this.storage:new L(this.storage,new N(this.config.cookieDomain||void 0));this.identity=new q(n,this.clock),this.session=new z(this.storage,this.clock,this.config.sessionTimeoutMs,r.schedule),this.consent=new $(this.storage,this.config.consentMode,this.config.respectDnt&&(r.dnt??Ke())),this.queue=new D(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:r.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&Te(),this.config.geolocation&&!this.config.childSafeMode&&qe(),this.storage instanceof P&&(this.ready=this.storage.hydrate().then(i=>{try{let o=i.get("depsmith_queue");o&&this.queue.prepend(JSON.parse(o))}catch{this.logger.warn("persisted queue corrupt; discarded")}})),this.uploader=new F(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:r.requestTimeoutMs},{fetchFn:r.fetchFn??((...i)=>fetch(...i)),clock:this.clock,logger:this.logger,sleep:r.sleep??(i=>new Promise(o=>setTimeout(o,i))),isOnline:r.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:Qe(this.storage,this.clock)}),r.manualLifecycle||(this.startFlushTimer(),this.attachLifecycle(),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,r){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",r)})}tooLong(e,r){return e.length<=Ze?!1:(this.logger.warn(`${r} exceeds ${Ze} characters (got ${e.length}); dropped`),!0)}page(e,r){this.guard(()=>{let n=e??(typeof document<"u"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...r,name:n})})}screen(e,r){this.page(e,r)}identify(e,r){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 n=h(r,this.logger);this.capture("$identify","identify",void 0,n,K("$set",n))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.identity.reset(),this.session.rotate(),this.logger.debug("reset: identity and session rotated")})}group(e,r){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}this.tooLong(e,"group: groupId")||(this.identity.setGroup(e),this.capture("$group","group",void 0,h(r,this.logger)))})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}this.capture("$group","group",void 0,h(e,this.logger))})}setProperty(e,r){this.guard(()=>{this.identity.setUserProp(e,r);let n=h({[e]:r},this.logger);this.capture("$identify","identify",void 0,n,K("$set",n))})}setOnceProperty(e,r){this.guard(()=>{if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.identity.setUserProp(e,r);let n=h({[e]:r},this.logger);this.capture("$identify","identify",void 0,n,K("$set_once",n))})}unsetProperty(e){this.guard(()=>{this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},ce({$unset:[e]},this.logger))})}setUserProperties(e){this.guard(()=>{let r=ce(e,this.logger);r&&this.capture("$identify","identify",void 0,void 0,r)})}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,r){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,r))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.flushTimer!==null&&clearInterval(this.flushTimer),this.flushTimer=null;for(let e of this.teardownFns.splice(0))e();this.persistNow()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}enqueueEvent(e){this.queue.enqueue(e),this.drained=!1}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides:e,tracking:this.config.trackingOptions}}sessionInSample(e){return this.config.sampleRate>=1?!0:Oe(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,r){return r==="identify"||r==="alias"||r==="group"?!0:this.sessionInSample(e)}capture(e,r,n,i,o){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let s=this.session.touch();if(s.endedSession&&this.sessionInSample(s.endedSession.id)&&this.enqueueSessionEnd(s.endedSession),s.startedSession&&this.sessionInSample(s.startedSession.id)&&this.enqueueSessionStart(s.startedSession),!this.inSample(s.sessionId,r)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let a=this.clock.now(),d=this.contextOptions(),u={event_id:f(a),event:e,event_type:r,timestamp:g(a),session_id:s.sessionId,session_started_at:g(s.startedAt),anonymous_id:this.identity.anonymousId,context:i?{...A(d),traits:i}:A(d),platform:"web",sdk_version:S};o&&(u.user_properties=o);let p={...this.config.defaultProperties,...h(n,this.logger)};Object.keys(p).length>0&&(u.properties=p);let l=this.identity.userId;l&&(u.user_id=l);let w=this.identity.groupId;w&&(u.group_id=w),d.fingerprint&&(u.device_id=T()),this.enqueueEvent(u),this.logger.debug(`captured ${e}`,u),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",r=J(this.config.apiKey),n=this.storage.get(e);n!==null&&n!==r&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear()),this.storage.set(e,r)}pickStorage(){return this.config.storage==="memory"?new k:this.config.storage==="indexeddb"&&typeof indexedDB<"u"?new P:Ve()}enqueueSessionEnd(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}let r=this.contextOptions(),n={event_id:f(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:g(e.lastActivityAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:A(r),platform:"web",sdk_version:S},i=this.identity.userId;i&&(n.user_id=i),r.fingerprint&&(n.device_id=T()),this.enqueueEvent(n)}enqueueSessionStart(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}let r=this.contextOptions(),n={event_id:f(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:g(e.startedAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:A(r),platform:"web",sdk_version:S},i=this.identity.userId;i&&(n.user_id=i),r.fingerprint&&(n.device_id=T()),r.fingerprint&&(n.properties={...n.properties,...Re()}),this.enqueueEvent(n)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window>"u"||typeof document>"u")return;let e=()=>{this.drained||(this.drained=!0,this.consent.canUpload()&&this.uploader.sendBeaconAll(),this.persistNow())},r=()=>{if(document.visibilityState==="hidden")e();else{this.drained=!1;let o=this.session.touch();o.endedSession&&this.enqueueSessionEnd(o.endedSession),o.startedSession&&this.enqueueSessionStart(o.startedSession)}},n=()=>{this.drained=!1},i=()=>{this.uploader.resetNetworkBreaker(),this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()};window.addEventListener("pagehide",e),window.addEventListener("pageshow",n),document.addEventListener("visibilitychange",r),window.addEventListener("online",i),this.teardownFns.push(()=>{window.removeEventListener("pagehide",e),window.removeEventListener("pageshow",n),document.removeEventListener("visibilitychange",r),window.removeEventListener("online",i)})}startAutocapture(){let e=this.config.autocapture;!e||typeof window>"u"||xe().then(r=>{r&&this.teardownFns.push(r.startAutocapture(e,{emit:n=>this.autocapture(n),page:()=>this.page()}))}).catch(r=>this.logger.debug("autocapture load failed",r))}guard(e){try{e()}catch(r){this.logger.error("internal error",r)}}};var c=null,le=null,fe={init(t,e){try{return c&&le===t.apiKey||(c?.shutdown(),c=new m(t,e),le=t.apiKey),c}catch(r){return t?.debug&&console.error("[depsmith-sdk] init failed:",r),null}},track:(t,e)=>c?.track(t,e),page:(t,e)=>c?.page(t,e),screen:(t,e)=>c?.screen(t,e),identify:(t,e)=>c?.identify(t,e),alias:t=>c?.alias(t),reset:()=>c?.reset(),group:(t,e)=>c?.group(t,e),setGroupTraits:t=>c?.setGroupTraits(t),setProperty:(t,e)=>c?.setProperty(t,e),setOnceProperty:(t,e)=>c?.setOnceProperty(t,e),unsetProperty:t=>c?.unsetProperty(t),setUserProperties:t=>c?.setUserProperties(t),optIn:()=>c?.optIn(),optOut:()=>c?.optOut(),flush:()=>c?.flush()??Promise.resolve(),getAnonymousId:()=>c?.getAnonymousId(),getSessionId:()=>c?.getSessionId(),setSessionId:(t,e)=>c?.setSessionId(t,e),shutdown(){c?.shutdown(),c=null,le=null}};var et=globalThis;et.DepsmithSdk=fe;et.DepsmithSdkClient=m;return ot(Bt);})();
|
|
2
|
+
//# sourceMappingURL=depsmith-sdk.global.js.map
|