@shware/analytics 16.5.0 → 16.5.2
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/_virtual/_rolldown/runtime.cjs +0 -2
- package/dist/ads/google.d.cts +13 -0
- package/dist/ads/google.d.cts.map +1 -1
- package/dist/ads/google.d.mts +13 -0
- package/dist/ads/google.d.mts.map +1 -1
- package/dist/ads/index.cjs +1 -1
- package/dist/ads/index.d.cts +1 -1
- package/dist/ads/index.d.mts +1 -1
- package/dist/ads/index.mjs +1 -1
- package/dist/ads/meta.cjs.map +1 -1
- package/dist/ads/meta.mjs.map +1 -1
- package/dist/ads/types.d.cts +1 -0
- package/dist/ads/types.d.cts.map +1 -1
- package/dist/attribution/index.cjs +1 -1
- package/dist/attribution/index.d.cts +1 -1
- package/dist/attribution/index.d.mts +1 -1
- package/dist/attribution/index.mjs +1 -1
- package/dist/click-id/index.cjs.map +1 -1
- package/dist/hooks/use-app-analytics.cjs +1 -1
- package/dist/hooks/use-app-analytics.cjs.map +1 -1
- package/dist/hooks/use-app-analytics.mjs +1 -1
- package/dist/hooks/use-outbound-click-analytics.cjs.map +1 -1
- package/dist/hooks/use-report-web-vitals.cjs.map +1 -1
- package/dist/hooks/use-track-impression.cjs.map +1 -1
- package/dist/hooks/use-uet-id-sync.cjs.map +1 -1
- package/dist/hooks/use-uet-id-sync.mjs.map +1 -1
- package/dist/hooks/use-web-analytics.cjs +2 -2
- package/dist/hooks/use-web-analytics.cjs.map +1 -1
- package/dist/hooks/use-web-analytics.mjs +2 -2
- package/dist/index.d.cts +7 -7
- package/dist/index.d.mts +7 -7
- package/dist/link/index.cjs.map +1 -1
- package/dist/link/index.d.cts +12 -1
- package/dist/link/index.d.cts.map +1 -1
- package/dist/link/index.d.mts +12 -1
- package/dist/link/index.d.mts.map +1 -1
- package/dist/link/index.mjs.map +1 -1
- package/dist/native/deep-link.cjs.map +1 -1
- package/dist/native/fbsdk.cjs +1 -1
- package/dist/native/fbsdk.cjs.map +1 -1
- package/dist/native/fbsdk.d.cts +1 -1
- package/dist/native/fbsdk.d.mts +1 -1
- package/dist/native/fbsdk.mjs +1 -1
- package/dist/native/firebase.cjs.map +1 -1
- package/dist/native/firebase.d.cts +1 -1
- package/dist/native/firebase.d.mts +1 -1
- package/dist/native/index.cjs +2 -2
- package/dist/native/index.d.cts +2 -2
- package/dist/native/index.d.mts +2 -2
- package/dist/native/index.mjs +2 -2
- package/dist/native/setup.cjs +1 -1
- package/dist/native/setup.cjs.map +1 -1
- package/dist/native/setup.d.cts +1 -2
- package/dist/native/setup.d.cts.map +1 -1
- package/dist/native/setup.d.mts +1 -1
- package/dist/native/setup.mjs +1 -1
- package/dist/next/index.cjs +2 -2
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.mjs +2 -2
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.cjs +2157 -0
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.cjs.map +1 -0
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.mjs +2152 -0
- package/dist/node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.mjs.map +1 -0
- package/dist/react/index.cjs +2 -2
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.mjs +2 -2
- package/dist/react/posthog-error-boundary.cjs.map +1 -1
- package/dist/react/posthog-error-boundary.mjs.map +1 -1
- package/dist/server/conversions-api-error.cjs.map +1 -1
- package/dist/server/conversions-api-error.mjs.map +1 -1
- package/dist/server/index.cjs +4 -4
- package/dist/server/index.d.cts +6 -6
- package/dist/server/index.d.mts +6 -6
- package/dist/server/index.mjs +4 -4
- package/dist/server/linkedin-conversions-api.d.cts +1 -1
- package/dist/server/linkedin-conversions-api.d.mts +1 -1
- package/dist/server/meta-capi.cjs +1 -1
- package/dist/server/meta-capi.d.cts +1 -1
- package/dist/server/meta-capi.d.mts +1 -1
- package/dist/server/meta-capi.mjs +1 -1
- package/dist/server/microsoft-conversions-api.cjs +3 -3
- package/dist/server/microsoft-conversions-api.d.cts +1 -1
- package/dist/server/microsoft-conversions-api.d.mts +1 -1
- package/dist/server/microsoft-conversions-api.mjs +3 -3
- package/dist/server/openai-conversions-api.cjs +2 -2
- package/dist/server/openai-conversions-api.d.cts +2 -2
- package/dist/server/openai-conversions-api.d.mts +2 -2
- package/dist/server/openai-conversions-api.mjs +2 -2
- package/dist/server/reddit-conversions-api.cjs +3 -3
- package/dist/server/reddit-conversions-api.d.cts +2 -2
- package/dist/server/reddit-conversions-api.d.mts +2 -2
- package/dist/server/reddit-conversions-api.mjs +3 -3
- package/dist/setup/index.d.cts +1 -1
- package/dist/setup/index.d.mts +1 -1
- package/dist/setup/session.cjs +1 -1
- package/dist/setup/session.cjs.map +1 -1
- package/dist/setup/session.mjs +1 -1
- package/dist/test/setup.cjs +1 -1
- package/dist/test/setup.cjs.map +1 -1
- package/dist/test/setup.mjs +1 -1
- package/dist/test/setup.mjs.map +1 -1
- package/dist/third-parties/google-analytics.d.cts +1 -1
- package/dist/third-parties/google-analytics.d.mts +1 -1
- package/dist/third-parties/index.cjs +3 -3
- package/dist/third-parties/index.d.cts +5 -5
- package/dist/third-parties/index.d.mts +5 -5
- package/dist/third-parties/index.mjs +3 -3
- package/dist/third-parties/linkedin-insight-tag.d.cts +2 -2
- package/dist/third-parties/linkedin-insight-tag.d.mts +2 -2
- package/dist/third-parties/meta-pixel.cjs +1 -1
- package/dist/third-parties/meta-pixel.d.cts +2 -2
- package/dist/third-parties/meta-pixel.d.mts +2 -2
- package/dist/third-parties/meta-pixel.mjs +1 -1
- package/dist/third-parties/microsoft-uet.cjs +1 -1
- package/dist/third-parties/microsoft-uet.cjs.map +1 -1
- package/dist/third-parties/microsoft-uet.d.cts +2 -2
- package/dist/third-parties/microsoft-uet.d.mts +2 -2
- package/dist/third-parties/microsoft-uet.mjs +1 -1
- package/dist/third-parties/microsoft-uet.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +1 -1
- package/dist/third-parties/openai-pixel.d.cts +2 -2
- package/dist/third-parties/openai-pixel.d.mts +2 -2
- package/dist/third-parties/openai-pixel.mjs +1 -1
- package/dist/third-parties/posthog.d.cts +1 -1
- package/dist/third-parties/posthog.d.mts +1 -1
- package/dist/third-parties/reddit-pixel.cjs +1 -1
- package/dist/third-parties/reddit-pixel.d.cts +2 -2
- package/dist/third-parties/reddit-pixel.d.mts +2 -2
- package/dist/third-parties/reddit-pixel.mjs +1 -1
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/once.cjs.map +1 -1
- package/dist/track/once.d.cts +1 -1
- package/dist/track/once.d.mts +1 -1
- package/dist/visitor/id.cjs +1 -1
- package/dist/visitor/id.cjs.map +1 -1
- package/dist/visitor/id.mjs +1 -1
- package/dist/visitor/index.cjs +2 -2
- package/dist/visitor/index.cjs.map +1 -1
- package/dist/visitor/index.mjs +2 -2
- package/dist/web/index.cjs +3 -5
- package/dist/web/index.cjs.map +1 -1
- package/dist/web/index.d.cts +1 -1
- package/dist/web/index.d.mts +1 -1
- package/dist/web/index.mjs +3 -5
- package/dist/web/index.mjs.map +1 -1
- package/package.json +11 -11
- package/dist/_virtual/_rolldown/runtime.mjs +0 -23
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.cjs +0 -1724
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.cjs.map +0 -1
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.mjs +0 -1721
- package/dist/node_modules/.pnpm/bowser@2.14.1/node_modules/bowser/es5.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"microsoft-uet.mjs","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { type UETConsent, type UETQ, mapUETEvent } from '../track/uetq';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { visitorId } from '../visitor/id';\nimport {\n type AdsOptions,\n CONVERSION_EVENTS,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /**\n * Defined by the UET snippet before `bat.js` loads (as a plain array), so pushes made early\n * are queued rather than lost. Undefined only where the snippet was never installed.\n */\n uetq?: UETQ;\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\n/** Drop `undefined` fields: bat.js validates every key it receives, and `undefined` is a value. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the Microsoft Advertising UET tag.\n *\n * `eventId` is reused as UET's `event_id` so the browser event deduplicates against the same\n * conversion sent through the Conversions API (`sendMicrosoftEvents`). The action name is the\n * internal name on both channels — see `mapUETEvent`.\n *\n * `page_view` is not forwarded: bat.js turns that action into its page-load beacon, which the\n * snippet already fires on load and, with `enableAutoSpaTracking: true` (the setting in\n * Microsoft's generated snippet), on every history change — forwarding the SDK's own page views\n * would report each page twice. The tag owns page loads; this tracker owns everything else.\n */\nexport function sendUETEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return false;\n }\n if (metrics.includes(name) || name === 'page_view') return;\n if (isLocalHost()) return;\n\n const [action, params] = mapUETEvent(name, properties, eventId);\n window.uetq.push('event', action, clean(params));\n}\n\n/**\n * Enhanced conversions: hand the tag the visitor's email and phone so Microsoft can match a\n * conversion to an ad click without a third-party cookie. A `set` applies to every event fired\n * from the page afterwards, `pageLoad` included, and the tag fires a `pid` beacon on its own\n * when the page load already went out. Values are sent raw — the tag normalizes and SHA-256\n * hashes them in the browser (bat.js `validatePid`) before anything leaves the page.\n *\n * A setter itself, like `setGAUser`, rather than a factory like `setFBUser(pixelId)`: UET is\n * bound to its tag by the snippet and `set` addresses whichever tag drains `uetq`, so there is\n * nothing to bind first.\n */\nexport function setUETUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return;\n }\n\n // A signed-in user is also the moment the ID Sync pixel can carry a `UID` — see `syncUETVisitor`.\n if (user_id) void syncUETVisitor(user_id);\n\n const em = getFirst(user_data?.email);\n const ph = getFirst(user_data?.phone_number);\n if (!em && !ph) return;\n\n window.uetq.push('set', { pid: clean({ em, ph }) });\n}\n\n/**\n * UET consent mode. Push `default` before the tag loads (the tag processes `consent` early, ahead\n * of the queued events) and `update` when the visitor decides. With `ad_storage: 'denied'` the\n * tag neither writes its cookies nor reads the `msclkid` from the URL.\n * https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\nexport function setUETConsent(mode: 'default' | 'update', consent: UETConsent) {\n if (typeof window === 'undefined') return;\n window.uetq ??= [] as unknown as UETQ;\n window.uetq.push('consent', mode, consent);\n}\n\n/**\n * The Conversions API's client-side ID Sync pixel: ties the visitor id sent server-side as\n * `anonymousId` to Microsoft's own identifier, so server events can be attributed across\n * contexts (view-through, audiences). Microsoft requires it for remarketing built from CAPI\n * events and recommends it for measurement quality; fire it at least once per session, ideally\n * on the first page view. A pixel rather than a fetch on purpose: Microsoft must observe the\n * browser context of the sync, which a server-side call cannot carry.\n *\n * `customerId` is the Microsoft Advertising customer id (`cid` in the UI's URLs) — not the UET\n * tag id. `visitorId` is the SDK visitor id (`visitorId()`), which is what\n * `sendMicrosoftEvents` sends as `anonymousId`; Microsoft requires the two to be equal.\n * `userId` is the raw signed-in user id: it is SHA-256 hashed here, exactly as the server sender\n * hashes it into `externalId`, so the pair matches as well. Hashing is asynchronous, so the\n * pixel fires once the digest resolves; where SubtleCrypto is unavailable (an insecure context)\n * the pixel goes out without `UID` rather than with a raw id.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#id-sync-and-why-it-matters\n */\n/**\n * The Microsoft Advertising customer id the ID Sync pixel reports to, set once by the framework\n * `Analytics` component's `uetCustomerId` prop (or `configureUET`). Unset, nothing syncs.\n */\nlet uetCustomerId: string | undefined;\n\nexport function configureUET(options: { customerId?: string | number }) {\n uetCustomerId = options.customerId === undefined ? undefined : String(options.customerId);\n}\n\n/**\n * Sync the SDK visitor — the `anonymousId` of the events the server sends to the Conversions\n * API — with Microsoft, plus the user's `UID` when one is known. The `Analytics` components run\n * it on mount so every visit syncs at least once, anonymous visitors included (they are who\n * remarketing audiences are built from), and `setUETUser` runs it again on sign-in.\n */\nexport async function syncUETVisitor(userId?: string): Promise<void> {\n if (!uetCustomerId) return;\n sendUETIdSync({ customerId: uetCustomerId, visitorId: visitorId(), userId });\n}\n\nexport function sendUETIdSync(options: {\n customerId: string | number;\n visitorId: string;\n /** The signed-in user's id, raw; hashed before it leaves the page. */\n userId?: string;\n}) {\n if (typeof window === 'undefined' || typeof Image === 'undefined') return;\n if (isLocalHost()) return;\n\n const fire = (uid?: string) => {\n const params = new URLSearchParams({\n Red3: `BACID_${options.customerId}`,\n VID: options.visitorId,\n });\n if (uid) params.set('UID', uid);\n new Image().src = `https://c.bing.com/c.gif?${params.toString()}`;\n };\n\n if (!options.userId) {\n fire();\n return;\n }\n sha256(options.userId).then(fire, () => fire());\n}\n\n/** What `microsoftAds` returns: an integration that also names the customer id for ID Sync. */\nexport type MicrosoftAdsIntegration = Integration & { readonly uetCustomerId?: `${number}` };\n\n/** The customer id of the `microsoftAds` integration among these, for `useUETIdSync`. */\nexport function uetCustomerIdOf(integrations: readonly Integration[] = []) {\n return integrations.find(\n (integration): integration is MicrosoftAdsIntegration => 'uetCustomerId' in integration\n )?.uetCustomerId;\n}\n\n/**\n * Microsoft Advertising UET. UET has no standard events to map to — a conversion goal is defined\n * on an action name in the ads UI — so it receives an explicit list, the GA4 conversion events\n * by default (`CONVERSION_EVENTS`), plus `customEvents`.\n *\n * Its script is Microsoft's UET snippet with `enableAutoSpaTracking: true` (the tag reports page\n * loads itself), the consent mode default pushed inside it so bat.js reads it before the first\n * page load.\n */\n/** The events UET receives: `events` (the GA4 conversion events by default) and `customEvents`. */\nexport function uetEvents(options: Pick<MicrosoftAdsOptions, 'events' | 'customEvents'>) {\n const events: readonly string[] = options.events ?? CONVERSION_EVENTS;\n return adEvents((name) => events.includes(name), options.customEvents);\n}\n\n/**\n * Microsoft's configuration, shared by `microsoftAds` and `microsoftConversions` on the server.\n */\nexport interface MicrosoftAdsOptions extends AdsOptions {\n tagId: `${number}`;\n /** Microsoft Advertising customer id (`cid` in the ads UI's URLs): enables the ID Sync pixel. */\n customerId?: `${number}`;\n /**\n * The UET consent mode default, `ad_storage: granted` unless given: how the tag behaves\n * without a signal, so Microsoft stops flagging EEA/UK/CH events as missing consent. Sites\n * with a consent banner pass `{ ad_storage: 'denied' }` and send `update` with\n * `setUETConsent`; `false` pushes no default. https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\n consent?: UETConsent | false;\n /** The events UET receives, `CONVERSION_EVENTS` by default; names `track` accepts. */\n events?: readonly TrackName[];\n}\n\nexport function microsoftAds(options: MicrosoftAdsOptions): MicrosoftAdsIntegration {\n const consent = options.consent ?? { ad_storage: 'granted' };\n const defaults = consent ? `w[u].push(\"consent\", \"default\", ${JSON.stringify(consent)});` : '';\n return {\n type: 'ads',\n track: adsTracker(sendUETEvent, uetEvents(options)),\n setUser: setUETUser,\n script: {\n id: 'uet-tag',\n inline: `\n (function (w, d, t, u, o) {\n w[u] = w[u] || [], o.ts = (new Date).getTime();\n ${defaults}\n var n = d.createElement(t);\n n.src = \"https://bat.bing.net/bat.js?ti=\" + o.ti + (\"uetq\" != u ? \"&q=\" + u : \"\"),\n n.async = 1, n.onload = n.onreadystatechange = function() {\n var s = this.readyState;\n s && \"loaded\" !== s && \"complete\" !== s ||\n (o.q = w[u], w[u] = new UET(o), w[u].push(\"pageLoad\"),\n n.onload = n.onreadystatechange = null)\n };\n var i = d.getElementsByTagName(t)[0];\n i.parentNode.insertBefore(n, i);\n })(window, document, \"script\", \"uetq\", {\n ti: ${JSON.stringify(options.tagId)},\n enableAutoSpaTracking: true\n });\n `,\n },\n uetCustomerId: options.customerId,\n };\n}\n"],"mappings":";;;;;;AAyBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;;AAI1D,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;;;;;;;;AAcA,SAAgB,aACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,KAAK,SAAS,aAAa;CACpD,IAAI,YAAY,GAAG;CAEnB,MAAM,CAAC,QAAQ,UAAU,YAAY,MAAM,YAAY,OAAO;CAC9D,OAAO,KAAK,KAAK,SAAS,QAAQ,MAAM,MAAM,CAAC;AACjD;;;;;;;;;;;;AAaA,SAAgB,WAAW,EAAE,SAAS,aAA+B;CACnE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C;CACF;CAGA,IAAI,SAAS,eAAoB,OAAO;CAExC,MAAM,KAAK,SAAS,WAAW,KAAK;CACpC,MAAM,KAAK,SAAS,WAAW,YAAY;CAC3C,IAAI,CAAC,MAAM,CAAC,IAAI;CAEhB,OAAO,KAAK,KAAK,OAAO,EAAE,KAAK,MAAM;EAAE;EAAI;CAAG,CAAC,EAAE,CAAC;AACpD;;;;;;;AAQA,SAAgB,cAAc,MAA4B,SAAqB;CAC7E,IAAI,OAAO,WAAW,aAAa;CACnC,OAAO,SAAS,CAAC;CACjB,OAAO,KAAK,KAAK,WAAW,MAAM,OAAO;AAC3C;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAI;AAEJ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;EAI1C;EACA,eAAe,QAAQ;CACzB;AACF"}
|
|
1
|
+
{"version":3,"file":"microsoft-uet.mjs","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { type UETConsent, type UETQ, mapUETEvent } from '../track/uetq';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { visitorId } from '../visitor/id';\nimport {\n type AdsOptions,\n CONVERSION_EVENTS,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /**\n * Defined by the UET snippet before `bat.js` loads (as a plain array), so pushes made early\n * are queued rather than lost. Undefined only where the snippet was never installed.\n */\n uetq?: UETQ;\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\n/** Drop `undefined` fields: bat.js validates every key it receives, and `undefined` is a value. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the Microsoft Advertising UET tag.\n *\n * `eventId` is reused as UET's `event_id` so the browser event deduplicates against the same\n * conversion sent through the Conversions API (`sendMicrosoftEvents`). The action name is the\n * internal name on both channels — see `mapUETEvent`.\n *\n * `page_view` is not forwarded: bat.js turns that action into its page-load beacon, which the\n * snippet already fires on load and, with `enableAutoSpaTracking: true` (the setting in\n * Microsoft's generated snippet), on every history change — forwarding the SDK's own page views\n * would report each page twice. The tag owns page loads; this tracker owns everything else.\n */\nexport function sendUETEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return false;\n }\n if (metrics.includes(name) || name === 'page_view') return;\n if (isLocalHost()) return;\n\n const [action, params] = mapUETEvent(name, properties, eventId);\n window.uetq.push('event', action, clean(params));\n}\n\n/**\n * Enhanced conversions: hand the tag the visitor's email and phone so Microsoft can match a\n * conversion to an ad click without a third-party cookie. A `set` applies to every event fired\n * from the page afterwards, `pageLoad` included, and the tag fires a `pid` beacon on its own\n * when the page load already went out. Values are sent raw — the tag normalizes and SHA-256\n * hashes them in the browser (bat.js `validatePid`) before anything leaves the page.\n *\n * A setter itself, like `setGAUser`, rather than a factory like `setFBUser(pixelId)`: UET is\n * bound to its tag by the snippet and `set` addresses whichever tag drains `uetq`, so there is\n * nothing to bind first.\n */\nexport function setUETUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return;\n }\n\n // A signed-in user is also the moment the ID Sync pixel can carry a `UID` — see `syncUETVisitor`.\n if (user_id) void syncUETVisitor(user_id);\n\n const em = getFirst(user_data?.email);\n const ph = getFirst(user_data?.phone_number);\n if (!em && !ph) return;\n\n window.uetq.push('set', { pid: clean({ em, ph }) });\n}\n\n/**\n * UET consent mode. Push `default` before the tag loads (the tag processes `consent` early, ahead\n * of the queued events) and `update` when the visitor decides. With `ad_storage: 'denied'` the\n * tag neither writes its cookies nor reads the `msclkid` from the URL.\n * https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\nexport function setUETConsent(mode: 'default' | 'update', consent: UETConsent) {\n if (typeof window === 'undefined') return;\n window.uetq ??= [] as unknown as UETQ;\n window.uetq.push('consent', mode, consent);\n}\n\n/**\n * The Conversions API's client-side ID Sync pixel: ties the visitor id sent server-side as\n * `anonymousId` to Microsoft's own identifier, so server events can be attributed across\n * contexts (view-through, audiences). Microsoft requires it for remarketing built from CAPI\n * events and recommends it for measurement quality; fire it at least once per session, ideally\n * on the first page view. A pixel rather than a fetch on purpose: Microsoft must observe the\n * browser context of the sync, which a server-side call cannot carry.\n *\n * `customerId` is the Microsoft Advertising customer id (`cid` in the UI's URLs) — not the UET\n * tag id. `visitorId` is the SDK visitor id (`visitorId()`), which is what\n * `sendMicrosoftEvents` sends as `anonymousId`; Microsoft requires the two to be equal.\n * `userId` is the raw signed-in user id: it is SHA-256 hashed here, exactly as the server sender\n * hashes it into `externalId`, so the pair matches as well. Hashing is asynchronous, so the\n * pixel fires once the digest resolves; where SubtleCrypto is unavailable (an insecure context)\n * the pixel goes out without `UID` rather than with a raw id.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#id-sync-and-why-it-matters\n */\n/**\n * The Microsoft Advertising customer id the ID Sync pixel reports to, set once by the framework\n * `Analytics` component's `uetCustomerId` prop (or `configureUET`). Unset, nothing syncs.\n */\nlet uetCustomerId: string | undefined;\n\nexport function configureUET(options: { customerId?: string | number }) {\n uetCustomerId = options.customerId === undefined ? undefined : String(options.customerId);\n}\n\n/**\n * Sync the SDK visitor — the `anonymousId` of the events the server sends to the Conversions\n * API — with Microsoft, plus the user's `UID` when one is known. The `Analytics` components run\n * it on mount so every visit syncs at least once, anonymous visitors included (they are who\n * remarketing audiences are built from), and `setUETUser` runs it again on sign-in.\n */\nexport async function syncUETVisitor(userId?: string): Promise<void> {\n if (!uetCustomerId) return;\n sendUETIdSync({ customerId: uetCustomerId, visitorId: visitorId(), userId });\n}\n\nexport function sendUETIdSync(options: {\n customerId: string | number;\n visitorId: string;\n /** The signed-in user's id, raw; hashed before it leaves the page. */\n userId?: string;\n}) {\n if (typeof window === 'undefined' || typeof Image === 'undefined') return;\n if (isLocalHost()) return;\n\n const fire = (uid?: string) => {\n const params = new URLSearchParams({\n Red3: `BACID_${options.customerId}`,\n VID: options.visitorId,\n });\n if (uid) params.set('UID', uid);\n new Image().src = `https://c.bing.com/c.gif?${params.toString()}`;\n };\n\n if (!options.userId) {\n fire();\n return;\n }\n sha256(options.userId).then(fire, () => fire());\n}\n\n/** What `microsoftAds` returns: an integration that also names the customer id for ID Sync. */\nexport type MicrosoftAdsIntegration = Integration & { readonly uetCustomerId?: `${number}` };\n\n/** The customer id of the `microsoftAds` integration among these, for `useUETIdSync`. */\nexport function uetCustomerIdOf(integrations: readonly Integration[] = []) {\n return integrations.find(\n (integration): integration is MicrosoftAdsIntegration => 'uetCustomerId' in integration\n )?.uetCustomerId;\n}\n\n/**\n * Microsoft Advertising UET. UET has no standard events to map to — a conversion goal is defined\n * on an action name in the ads UI — so it receives an explicit list, the GA4 conversion events\n * by default (`CONVERSION_EVENTS`), plus `customEvents`.\n *\n * Its script is Microsoft's UET snippet with `enableAutoSpaTracking: true` (the tag reports page\n * loads itself), the consent mode default pushed inside it so bat.js reads it before the first\n * page load.\n */\n/** The events UET receives: `events` (the GA4 conversion events by default) and `customEvents`. */\nexport function uetEvents(options: Pick<MicrosoftAdsOptions, 'events' | 'customEvents'>) {\n const events: readonly string[] = options.events ?? CONVERSION_EVENTS;\n return adEvents((name) => events.includes(name), options.customEvents);\n}\n\n/**\n * Microsoft's configuration, shared by `microsoftAds` and `microsoftConversions` on the server.\n */\nexport interface MicrosoftAdsOptions extends AdsOptions {\n tagId: `${number}`;\n /** Microsoft Advertising customer id (`cid` in the ads UI's URLs): enables the ID Sync pixel. */\n customerId?: `${number}`;\n /**\n * The UET consent mode default, `ad_storage: granted` unless given: how the tag behaves\n * without a signal, so Microsoft stops flagging EEA/UK/CH events as missing consent. Sites\n * with a consent banner pass `{ ad_storage: 'denied' }` and send `update` with\n * `setUETConsent`; `false` pushes no default. https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\n consent?: UETConsent | false;\n /** The events UET receives, `CONVERSION_EVENTS` by default; names `track` accepts. */\n events?: readonly TrackName[];\n}\n\nexport function microsoftAds(options: MicrosoftAdsOptions): MicrosoftAdsIntegration {\n const consent = options.consent ?? { ad_storage: 'granted' };\n const defaults = consent ? `w[u].push(\"consent\", \"default\", ${JSON.stringify(consent)});` : '';\n return {\n type: 'ads',\n track: adsTracker(sendUETEvent, uetEvents(options)),\n setUser: setUETUser,\n script: {\n id: 'uet-tag',\n inline: `\n (function (w, d, t, u, o) {\n w[u] = w[u] || [], o.ts = (new Date).getTime();\n ${defaults}\n var n = d.createElement(t);\n n.src = \"https://bat.bing.net/bat.js?ti=\" + o.ti + (\"uetq\" != u ? \"&q=\" + u : \"\"),\n n.async = 1, n.onload = n.onreadystatechange = function() {\n var s = this.readyState;\n s && \"loaded\" !== s && \"complete\" !== s ||\n (o.q = w[u], w[u] = new UET(o), w[u].push(\"pageLoad\"),\n n.onload = n.onreadystatechange = null)\n };\n var i = d.getElementsByTagName(t)[0];\n i.parentNode.insertBefore(n, i);\n })(window, document, \"script\", \"uetq\", {\n ti: ${JSON.stringify(options.tagId)},\n enableAutoSpaTracking: true\n });\n `,\n },\n uetCustomerId: options.customerId,\n };\n}\n"],"mappings":";;;;;;AAyBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;;AAI1D,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;;;;;;;;AAcA,SAAgB,aACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,KAAK,SAAS,aAAa;CACpD,IAAI,YAAY,GAAG;CAEnB,MAAM,CAAC,QAAQ,UAAU,YAAY,MAAM,YAAY,OAAO;CAC9D,OAAO,KAAK,KAAK,SAAS,QAAQ,MAAM,MAAM,CAAC;AACjD;;;;;;;;;;;;AAaA,SAAgB,WAAW,EAAE,SAAS,aAA+B;CACnE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C;CACF;CAGA,IAAI,SAAc,eAAe,OAAO;CAExC,MAAM,KAAK,SAAS,WAAW,KAAK;CACpC,MAAM,KAAK,SAAS,WAAW,YAAY;CAC3C,IAAI,CAAC,MAAM,CAAC,IAAI;CAEhB,OAAO,KAAK,KAAK,OAAO,EAAE,KAAK,MAAM;EAAE;EA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AU,mCAAmC,KAAK,UAAU,OAAO,EAAE,MAAM;CAC5F,OAAO;EACL,MAAM;EACN,OAAO,WAAW,cAAc,UAAU,OAAO,CAAC;EAClD,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;YAGF,SAAS;;;;;;;;;;;;gBAYL,KAAK,UAAU,QAAQ,KAAK,EAAE;;;;EAI1C;EACA,eAAe,QAAQ;CACzB;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_track_oaiq = require("../track/oaiq.cjs");
|
|
2
3
|
const require_utils_field = require("../utils/field.cjs");
|
|
3
4
|
const require_utils_sha256 = require("../utils/sha256.cjs");
|
|
4
5
|
const require_third_parties_integration = require("./integration.cjs");
|
|
5
|
-
const require_track_oaiq = require("../track/oaiq.cjs");
|
|
6
6
|
// src/third-parties/openai-pixel.ts
|
|
7
7
|
/** Drop `undefined` fields so the SDK only receives populated values. */
|
|
8
8
|
function clean(value) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
2
1
|
import { UpdateVisitorDTO } from "../schema/index.cjs";
|
|
3
|
-
import { AdsOptions, Integration } from "./integration.cjs";
|
|
4
2
|
import { OAIQ } from "../track/oaiq.cjs";
|
|
3
|
+
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
4
|
+
import { AdsOptions, Integration } from "./integration.cjs";
|
|
5
5
|
declare global {
|
|
6
6
|
interface Window {
|
|
7
7
|
/** Undefined until the OpenAI pixel script has loaded. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
2
1
|
import { UpdateVisitorDTO } from "../schema/index.mjs";
|
|
3
|
-
import { AdsOptions, Integration } from "./integration.mjs";
|
|
4
2
|
import { OAIQ } from "../track/oaiq.mjs";
|
|
3
|
+
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
4
|
+
import { AdsOptions, Integration } from "./integration.mjs";
|
|
5
5
|
declare global {
|
|
6
6
|
interface Window {
|
|
7
7
|
/** Undefined until the OpenAI pixel script has loaded. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { APP_EVENTS, NON_AD_EVENTS, isStandardOAIEvent, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
|
|
1
2
|
import { getFirst } from "../utils/field.mjs";
|
|
2
3
|
import { sha256 } from "../utils/sha256.mjs";
|
|
3
4
|
import { adEvents, adsTracker, isLocalHost } from "./integration.mjs";
|
|
4
|
-
import { APP_EVENTS, NON_AD_EVENTS, isStandardOAIEvent, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
|
|
5
5
|
// src/third-parties/openai-pixel.ts
|
|
6
6
|
/** Drop `undefined` fields so the SDK only receives populated values. */
|
|
7
7
|
function clean(value) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
2
1
|
import { UpdateVisitorDTO } from "../schema/index.cjs";
|
|
2
|
+
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
3
3
|
import { Integration } from "./integration.cjs";
|
|
4
4
|
import { CaptureResult, ExceptionAutoCaptureConfig, PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1, Properties } from "@posthog/types";
|
|
5
5
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
2
1
|
import { UpdateVisitorDTO } from "../schema/index.mjs";
|
|
2
|
+
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
3
3
|
import { Integration } from "./integration.mjs";
|
|
4
4
|
import { CaptureResult, ExceptionAutoCaptureConfig, PostHog, PostHog as PostHog$1, PostHogConfig, PostHogConfig as PostHogConfig$1, Properties } from "@posthog/types";
|
|
5
5
|
/**
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_track_rdt = require("../track/rdt.cjs");
|
|
2
3
|
const require_utils_field = require("../utils/field.cjs");
|
|
3
4
|
const require_third_parties_integration = require("./integration.cjs");
|
|
4
|
-
const require_track_rdt = require("../track/rdt.cjs");
|
|
5
5
|
// src/third-parties/reddit-pixel.ts
|
|
6
6
|
const metrics = [
|
|
7
7
|
"CLS",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
2
1
|
import { UpdateVisitorDTO } from "../schema/index.cjs";
|
|
3
|
-
import { AdsOptions, Integration } from "./integration.cjs";
|
|
4
2
|
import { PixelId, RDT } from "../track/rdt.cjs";
|
|
3
|
+
import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
|
|
4
|
+
import { AdsOptions, Integration } from "./integration.cjs";
|
|
5
5
|
declare global {
|
|
6
6
|
interface Window {
|
|
7
7
|
/** Undefined until the Reddit Pixel script has loaded. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
2
1
|
import { UpdateVisitorDTO } from "../schema/index.mjs";
|
|
3
|
-
import { AdsOptions, Integration } from "./integration.mjs";
|
|
4
2
|
import { PixelId, RDT } from "../track/rdt.mjs";
|
|
3
|
+
import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
|
|
4
|
+
import { AdsOptions, Integration } from "./integration.mjs";
|
|
5
5
|
declare global {
|
|
6
6
|
interface Window {
|
|
7
7
|
/** Undefined until the Reddit Pixel script has loaded. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { isStandardRDTEvent, mapRDTEvent } from "../track/rdt.mjs";
|
|
1
2
|
import { getFirst } from "../utils/field.mjs";
|
|
2
3
|
import { adEvents, adsTracker, isLocalHost } from "./integration.mjs";
|
|
3
|
-
import { isStandardRDTEvent, mapRDTEvent } from "../track/rdt.mjs";
|
|
4
4
|
// src/third-parties/reddit-pixel.ts
|
|
5
5
|
const metrics = [
|
|
6
6
|
"CLS",
|
package/dist/track/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","visitorId","getSession","uuidv7","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels({ event, options }: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.warn(e.message);\n return false;\n }\n });\n}\n\n/**\n * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.warn(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,KAAK,EAAE,OAAO;EAC9C,OAAOC,oBAAAA,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,EAAE,OAAO,WAAiB;CAG5C,IACE,QAAQ,6BAA6B,SACrCD,oBAAAA,OAAO,wBAAwB,SAAS,MAAM,IAAI,KAClDE,qCAAAA,eAAe,SAAS,MAAM,IAAI,GAElC;CAEF,MAAM,WAAW,iBAAiBF,oBAAAA,OAAO,cAAc,KAAK;CAC5D,IAAI,SAAS,WAAW,GAAG;CAC3B,iBAAiB,iBAAiB,UAAU,KAAK,GAAG,CA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;AAC/D;;;;;;;;;;;;;AAcA,SAAgB,oBAAoB;CAClC,IAAI,KAAK,WAAW,GAAG;CACvB,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,UAAU;EAC3C,IAAI,CAAC,OAAO,MAAM,KAAK,SAAS,KAAK,KAAK,CAAC,GAAG;GAC5C,KAAK,KAAK,GAAG,KAAK;GAClB;EACF;EACA,MAAM,SAAS,EAAE,OAAO,cAAc,QAAQ,YAAY;GAAE,IAAI,MAAM;GAAI,QAAQ;EAAK,CAAC,CAAC;CAC3F,CAAC;CACD,IAAI,KAAK,SAAS,GAAG,MAAW;AAClC;AAEA,SAAgB,WACd,MACA,YACA;CAGA,MAAM,aAAaI,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAIjB,IAAI,OAAO,CAAC;EAAE,GAAG,QAAQ,UAAU;EAAG,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EAAG;EAAM;CAAW,CAAC,CAAC,GAAG;CAC1E,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","visitorId","getSession","uuidv7","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels({ event, options }: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.warn(e.message);\n return false;\n }\n });\n}\n\n/**\n * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.warn(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAA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,UAAU;AACxD"}
|
package/dist/track/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels({ event, options }: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.warn(e.message);\n return false;\n }\n });\n}\n\n/**\n * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.warn(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,KAAK,EAAE,OAAO;EAC9C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,EAAE,OAAO,WAAiB;CAG5C,IACE,QAAQ,6BAA6B,SACrC,OAAO,wBAAwB,SAAS,MAAM,IAAI,KAClD,eAAe,SAAS,MAAM,IAAI,GAElC;CAEF,MAAM,WAAW,iBAAiB,OAAO,cAAc,KAAK;CAC5D,IAAI,SAAS,WAAW,GAAG;CAC3B,iBAAiB,iBAAiB,UAAU,KAAK,GAAG,CAAC;AACvD;;AAGA,SAAS,iBAAiB,cAAsC,OAAkC;CAChG,OAAO,aAAa,QAAQ,EAAE,YAAY;EACxC,IAAI;GACF,OAAO,MAAM,MAAM,MAAM,MAAM,YAAY,MAAM,EAAE,MAAM;EAC3D,SAAS,GAAY;GAEnB,IAAI,aAAa,OAAO,QAAQ,KAAK,EAAE,OAAO;GAC9C,OAAO;EACT;CACF,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I,KAAK,SAAS,GAAG,MAAW;AAClC;AAEA,SAAgB,WACd,MACA,YACA;CAGA,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAIjB,IAAI,OAAO,CAAC;EAAE,GAAG,QAAQ,UAAU;EAAG,IAAIA,GAAO;EAAG;EAAM;CAAW,CAAC,CAAC,GAAG;CAC1E,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels({ event, options }: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.warn(e.message);\n return false;\n }\n });\n}\n\n/**\n * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.warn(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,KAAK,EAAE,OAAO;EAC9C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,EAAE,OAAO,WAAiB;CAG5C,IACE,QAAQ,6BAA6B,SACrC,OAAO,wBAAwB,SAAS,MAAM,IAAI,KAClD,eAAe,SAAS,MAAM,IAAI,GAElC;CAEF,MAAM,WAAW,iBAAiB,OAAO,cAAc,KAAK;CAC5D,IAAI,SAAS,WAAW,GAAG;CAC3B,iBAAiB,iBAAiB,UAAU,KAAK,GAAG,CAAC;AACvD;;AAGA,SAAS,iBAA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AI,CAAC,OAAO,MAAM,KAAK,SAAS,KAAK,KAAK,CAAC,GAAG;GAC5C,KAAK,KAAK,GAAG,KAAK;GAClB;EACF;EACA,MAAM,SAAS,EAAE,OAAO,cAAc,QAAQ,YAAY;GAAE,IAAI,MAAM;GAAI,QAAQ;EAAK,CAAC,CAAC;CAC3F,CAAC;CACD,IAAI,KAAK,SAAS,GAAQ,MAAM;AAClC;AAEA,SAAgB,WACd,MACA,YACA;CAGA,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAIjB,IAAI,OAAO,CAAC;EAAE,GAAG,QAAQ,UAAU;EAAG,IAAIA,GAAO;EAAG;EAAM;CAAW,CAAC,CAAC,GAAG;CAC1E,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
package/dist/track/once.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"once.cjs","names":["config","uuidv7"],"sources":["../../src/track/once.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice.\n *\n * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked\n * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry\n * stays unsent with its id. The next call for the key — the result page opened again — sends the\n * event once more under that id and without pixels, which the server ignores when the beacon did\n * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n // A beacon was only queued by the browser: the entry stays unsent, so a later call\n // sends it again under the same id.\n if (response?.beacon) {\n options.onSucceed?.(response);\n return;\n }\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,SAAS,WAAW,MAAc;CAChC,OAAO,cAAc;AACvB;;AAGA,SAAS,KAAK,MAAuB;CACnC,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQ,WAAW,IAAI,CAAC;CACnD,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,QAAQ;EACN,OAAO,CAAC;CACV;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO,CAAC;CAC3D,MAAM,EAAE,GAAG,YAAY;CACvB,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;CACrC,IAAI,MAAM,GACR,OAAO,QAAQ,SAAS,UAAmB;EACzC,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;EACnC,MAAM,CAAC,KAAK,aAAa;EACzB,IAAI,OAAO,QAAQ,YAAY,OAAO,cAAc,UAAU,OAAO,CAAC;EAEtE,OAAO,CAAC;GAAE;GAAK,IAAI;GAAI;GAAW,MAAM;EAAK,CAAC;CAChD,CAAC;CAEH,IAAI,MAAM,SAAS,OAAO,CAAC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id';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice.\n *\n * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked\n * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry\n * stays unsent with its id. The next call for the key — the result page opened again — sends the\n * event once more under that id and without pixels, which the server ignores when the beacon did\n * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n // A beacon was only queued by the browser: the entry stays unsent, so a later call\n // sends it again under the same id.\n if (response?.beacon) {\n options.onSucceed?.(response);\n return;\n }\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,SAAS,WAAW,MAAc;CAChC,OAAO,cAAc;AACvB;;AAGA,SAAS,KAAK,MAAuB;CACnC,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQ,WAAW,I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AQ;IAC5B;GACF;GACA,IAAI;IAEF,MAAM,MAAM,CAAC,GADG,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,QAAQ,UAAU,MAAM,QAAQ,GACvD,GAAG;KAAE;KAAK;KAAI,WAAW,KAAK,IAAI,IAAI;KAAK,MAAM;IAAK,CAAC,CAAC;GAChF,SAAS,GAAY;IACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;GAC/C;GACA,QAAQ,YAAY,QAAQ;EAC9B;EACA,UAAU,UAAU;GAElB,aAAa,MAAM,GAAG;GACtB,QAAQ,UAAU,KAAK;EACzB;CACF,GACA,UAAU;EAAE;EAAI,QAAQ;CAAM,IAAI,EAAE,GAAG,CACzC;CACA,OAAO;AACT"}
|
package/dist/track/once.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "./types.cjs";
|
|
2
1
|
import { TrackOptions } from "./index.cjs";
|
|
2
|
+
import { EventName, TrackName, TrackProperties } from "./types.cjs";
|
|
3
3
|
export interface TrackOnceOptions extends TrackOptions {
|
|
4
4
|
/**
|
|
5
5
|
* What makes this occurrence the same one again: a checkout session id for `purchase`, an order
|
package/dist/track/once.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { EventName, TrackName, TrackProperties } from "./types.mjs";
|
|
2
1
|
import { TrackOptions } from "./index.mjs";
|
|
2
|
+
import { EventName, TrackName, TrackProperties } from "./types.mjs";
|
|
3
3
|
export interface TrackOnceOptions extends TrackOptions {
|
|
4
4
|
/**
|
|
5
5
|
* What makes this occurrence the same one again: a checkout session id for `purchase`, an order
|
package/dist/visitor/id.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_setup_index = require("../setup/index.cjs");
|
|
3
2
|
const require_constants_storage = require("../constants/storage.cjs");
|
|
3
|
+
const require_setup_index = require("../setup/index.cjs");
|
|
4
4
|
let uuid = require("uuid");
|
|
5
5
|
// src/visitor/id.ts
|
|
6
6
|
/**
|
package/dist/visitor/id.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"id.cjs","names":["config","keys","validate","version","uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7, validate, version } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.\n * Anything else stored there is replaced, because the server rejects every batch carrying it:\n * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the\n * visitor when the server refused it; without that round trip the id would never change.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // Also covers the string 'undefined' an old client stored for an unset id. Replacing it below\n // writes the new id back, which clears the bad value from storage for good.\n if (stored && validate(stored) && version(stored) === 7) return stored;\n return newVisitorId();\n}\n\n/** Starts a new visitor on this device — `reset()` — and returns its id. */\nexport function newVisitorId(): string {\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,SAAgB,YAAoB;CAClC,MAAM,SAASA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,UAAU;CAGrD,IAAI,WAAA,GAAUC,KAAAA,SAAAA,CAAS,MAAM,MAAA,GAAKC,KAAAA,QAAAA,CAAQ,MAAM,MAAM,GAAG,OAAO;CAChE,OAAO,aAAa;AACtB;;AAGA,SAAgB,eAAuB;CACrC,MAAM,MAAA,GAAKC,KAAAA,GAAAA,CAAO;
|
|
1
|
+
{"version":3,"file":"id.cjs","names":["config","keys","validate","version","uuidv7"],"sources":["../../src/visitor/id.ts"],"sourcesContent":["import { v7 as uuidv7, validate, version } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\n\n/**\n * This visitor's id: generated here on the first visit (uuidv7) and kept in `config.storage`, so\n * it exists the moment the page loads. The first events, and the beacon of a visit left within a\n * second, go out without waiting for a round trip; the server creates the visitor from its first\n * events. A uuidv7 a server issued to an older client is kept as it is: the visitor continues.\n * Anything else stored there is replaced, because the server rejects every batch carrying it:\n * clients before 11.0 kept the int64 id older servers issued, and healed it by recreating the\n * visitor when the server refused it; without that round trip the id would never change.\n *\n * Needs a server that creates visitors from events (see the README, \"Visitors\"); one that still\n * only creates them on `POST /visitors` rejects the events of a new visitor.\n */\nexport function visitorId(): string {\n const stored = config.storage.getItem(keys.visitor_id);\n // Also covers the string 'undefined' an old client stored for an unset id. Replacing it below\n // writes the new id back, which clears the bad value from storage for good.\n if (stored && validate(stored) && version(stored) === 7) return stored;\n return newVisitorId();\n}\n\n/** Starts a new visitor on this device — `reset()` — and returns its id. */\nexport function newVisitorId(): string {\n const id = uuidv7();\n config.storage.setItem(keys.visitor_id, id);\n return id;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgBA,SAAgB,YAAoB;CAClC,MAAM,SAASA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,UAAU;CAGrD,IAAI,WAAA,GAAUC,KAAAA,SAAAA,CAAS,MAAM,MAAA,GAAKC,KAAAA,QAAAA,CAAQ,MAAM,MAAM,GAAG,OAAO;CAChE,OAAO,aAAa;AACtB;;AAGA,SAAgB,eAAuB;CACrC,MAAM,MAAA,GAAKC,KAAAA,GAAAA,CAAO;CAClBJ,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,YAAY,EAAE;CAC1C,OAAO;AACT"}
|
package/dist/visitor/id.mjs
CHANGED
package/dist/visitor/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_setup_index = require("../setup/index.cjs");
|
|
3
2
|
const require_constants_storage = require("../constants/storage.cjs");
|
|
4
|
-
const
|
|
3
|
+
const require_setup_index = require("../setup/index.cjs");
|
|
5
4
|
const require_track_index = require("../track/index.cjs");
|
|
5
|
+
const require_visitor_id = require("./id.cjs");
|
|
6
6
|
// src/visitor/index.ts
|
|
7
7
|
/**
|
|
8
8
|
* The event that binds the visitor to the user who signed in on it: the server sets the visitor's
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["config","keys","visitorId"],"sources":["../../src/visitor/index.ts"],"sourcesContent":["import { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { endSession, track } from '../track/index';\nimport type { UserProvidedData } from '../track/types';\nimport { newVisitorId, visitorId } from './id';\nimport type { ThirdPartyUserSetter } from './types';\n\nexport { visitorId } from './id';\n\n/**\n * The event that binds the visitor to the user who signed in on it: the server sets the visitor's\n * `user_id` and `distinct_id` from its `user_id` property, in the transaction that stores the\n * batch — which also creates the visitor when it is new, so the binding can never arrive before it.\n */\nexport const IDENTIFY_EVENT = 'identify';\n\n/**\n * The visitor and user this page last identified, as `<visitor>:<user>`: identify once per binding\n * per page, not per call. The visitor is part of it because the storage is shared: another tab's\n * `reset()` replaces the visitor under this page, and the same user here must then bind the new\n * one too.\n *\n * `undefined` until this page identifies anyone; `null` once it has signed out (`reset()`), so the\n * same user signing back in is identified again, and a later `reset()` here knows it has nothing\n * left to sign out — the device's identity, if any, is someone this page has not identified.\n */\nlet identified: string | null | undefined;\n\n/** Hands the user to every integration's user setter; one that throws does not stop the others. */\nfunction setUsers(user: Parameters<ThirdPartyUserSetter>[0]) {\n config.integrations.forEach(({ setUser }) => {\n try {\n setUser?.(user);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n });\n}\n\n/**\n * Hands the signed-in user to the analytics: the third-party user setters (gtag, the pixels) now,\n * and the server through an `identify` event, sent when the user differs from the one this page\n * last identified — a host calls this on every page load once someone is signed in. Like any\n * event it goes with the next batch or the page-hide beacon; `userData` is handed to the setters\n * only, never stored with the event.\n *\n * The visitor's sessions so far — those before the sign-in included — become this user's. So a\n * different user than the one last identified on this device (an expired session, a sign-out the\n * host never reported) is `reset()` first: the previous user's visitor stays theirs, and this one\n * starts on a new visitor.\n *\n * Synchronous and never throws: sign-in must not fail on analytics.\n */\nexport function identify(userId: string, userData?: UserProvidedData) {\n let visitor = '';\n try {\n const previous = config.storage.getItem(keys.user_id);\n if (previous && previous !== userId) {\n // Another user is on the device: start over whatever this page last identified.\n startOver();\n setUsers({});\n }\n config.storage.setItem(keys.user_id, userId);\n visitor = visitorId();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n\n const binding = `${visitor}:${userId}`;\n if (binding !== identified) {\n identified = binding;\n track(IDENTIFY_EVENT, { user_id: userId }, { enableThirdPartyTracking: false });\n }\n\n setUsers({ user_id: userId, user_data: userData });\n}\n\n/**\n * Signs the visitor out, as PostHog's `reset()` does: call it on sign-out, after\n * `track('logout')`, so that event still belongs to the user leaving.\n *\n * - The current session ends: what it accrued goes out as a `user_engagement`\n * (`trigger: 'reset'`), as when the page is closed, and the queue is sent under the visitor\n * and session its events happened in.\n * - A new visitor starts, and the next event opens a new session on it. Everything until the next\n * sign-in is anonymous, and becomes whoever's signs in next; the visitor that is left stays the\n * previous user's, with its history.\n * - The third-party setters drop the user (PostHog resets its identity, GA clears its user_id).\n *\n * The device id and the first visit or first open stay: they describe the device, not the person.\n *\n * Only the sign-out this page knows of: the session and visitor are replaced while the device's\n * identity (`keys.user_id` and the visitor, shared by every tab) is still the one this page last\n * identified, or the page has neither identified nor signed out anyone (a host that identifies at\n * sign-in only, on a page loaded since). Every tab of a site sees a sign-out and calls this,\n * some of them late — a tab frozen in the background handles it on resuming, after another tab\n * may have signed out and in again. A call that finds no user, or someone else's binding, is\n * stale: replacing that would cut the new anonymous visitor off from the next sign-in, or end the\n * next user's session and leave their pages on a visitor nobody identified. It only clears this\n * page: its setters are still told, since GA holds the user per page.\n *\n * Synchronous and never throws: sign-out must not fail on analytics.\n */\nexport function reset() {\n let current = false;\n try {\n const user = config.storage.getItem(keys.user_id);\n current = !!user && (identified === undefined || identified === `${visitorId()}:${user}`);\n if (current) startOver();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n if (current || identified) setUsers({});\n identified = null;\n}\n\n/**\n * Ends the device's session and starts a new visitor with no user: `reset()` for the sign-out it\n * knows of, `identify` for a user signing in over another.\n */\nfunction startOver() {\n endSession();\n newVisitorId();\n config.storage.setItem(keys.user_id, '');\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,iBAAiB;;;;;;;;;;;AAY9B,IAAI;;AAGJ,SAAS,SAAS,MAA2C;
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["config","keys","visitorId","track","endSession","newVisitorId"],"sources":["../../src/visitor/index.ts"],"sourcesContent":["import { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { endSession, track } from '../track/index';\nimport type { UserProvidedData } from '../track/types';\nimport { newVisitorId, visitorId } from './id';\nimport type { ThirdPartyUserSetter } from './types';\n\nexport { visitorId } from './id';\n\n/**\n * The event that binds the visitor to the user who signed in on it: the server sets the visitor's\n * `user_id` and `distinct_id` from its `user_id` property, in the transaction that stores the\n * batch — which also creates the visitor when it is new, so the binding can never arrive before it.\n */\nexport const IDENTIFY_EVENT = 'identify';\n\n/**\n * The visitor and user this page last identified, as `<visitor>:<user>`: identify once per binding\n * per page, not per call. The visitor is part of it because the storage is shared: another tab's\n * `reset()` replaces the visitor under this page, and the same user here must then bind the new\n * one too.\n *\n * `undefined` until this page identifies anyone; `null` once it has signed out (`reset()`), so the\n * same user signing back in is identified again, and a later `reset()` here knows it has nothing\n * left to sign out — the device's identity, if any, is someone this page has not identified.\n */\nlet identified: string | null | undefined;\n\n/** Hands the user to every integration's user setter; one that throws does not stop the others. */\nfunction setUsers(user: Parameters<ThirdPartyUserSetter>[0]) {\n config.integrations.forEach(({ setUser }) => {\n try {\n setUser?.(user);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n });\n}\n\n/**\n * Hands the signed-in user to the analytics: the third-party user setters (gtag, the pixels) now,\n * and the server through an `identify` event, sent when the user differs from the one this page\n * last identified — a host calls this on every page load once someone is signed in. Like any\n * event it goes with the next batch or the page-hide beacon; `userData` is handed to the setters\n * only, never stored with the event.\n *\n * The visitor's sessions so far — those before the sign-in included — become this user's. So a\n * different user than the one last identified on this device (an expired session, a sign-out the\n * host never reported) is `reset()` first: the previous user's visitor stays theirs, and this one\n * starts on a new visitor.\n *\n * Synchronous and never throws: sign-in must not fail on analytics.\n */\nexport function identify(userId: string, userData?: UserProvidedData) {\n let visitor = '';\n try {\n const previous = config.storage.getItem(keys.user_id);\n if (previous && previous !== userId) {\n // Another user is on the device: start over whatever this page last identified.\n startOver();\n setUsers({});\n }\n config.storage.setItem(keys.user_id, userId);\n visitor = visitorId();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n\n const binding = `${visitor}:${userId}`;\n if (binding !== identified) {\n identified = binding;\n track(IDENTIFY_EVENT, { user_id: userId }, { enableThirdPartyTracking: false });\n }\n\n setUsers({ user_id: userId, user_data: userData });\n}\n\n/**\n * Signs the visitor out, as PostHog's `reset()` does: call it on sign-out, after\n * `track('logout')`, so that event still belongs to the user leaving.\n *\n * - The current session ends: what it accrued goes out as a `user_engagement`\n * (`trigger: 'reset'`), as when the page is closed, and the queue is sent under the visitor\n * and session its events happened in.\n * - A new visitor starts, and the next event opens a new session on it. Everything until the next\n * sign-in is anonymous, and becomes whoever's signs in next; the visitor that is left stays the\n * previous user's, with its history.\n * - The third-party setters drop the user (PostHog resets its identity, GA clears its user_id).\n *\n * The device id and the first visit or first open stay: they describe the device, not the person.\n *\n * Only the sign-out this page knows of: the session and visitor are replaced while the device's\n * identity (`keys.user_id` and the visitor, shared by every tab) is still the one this page last\n * identified, or the page has neither identified nor signed out anyone (a host that identifies at\n * sign-in only, on a page loaded since). Every tab of a site sees a sign-out and calls this,\n * some of them late — a tab frozen in the background handles it on resuming, after another tab\n * may have signed out and in again. A call that finds no user, or someone else's binding, is\n * stale: replacing that would cut the new anonymous visitor off from the next sign-in, or end the\n * next user's session and leave their pages on a visitor nobody identified. It only clears this\n * page: its setters are still told, since GA holds the user per page.\n *\n * Synchronous and never throws: sign-out must not fail on analytics.\n */\nexport function reset() {\n let current = false;\n try {\n const user = config.storage.getItem(keys.user_id);\n current = !!user && (identified === undefined || identified === `${visitorId()}:${user}`);\n if (current) startOver();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n if (current || identified) setUsers({});\n identified = null;\n}\n\n/**\n * Ends the device's session and starts a new visitor with no user: `reset()` for the sign-out it\n * knows of, `identify` for a user signing in over another.\n */\nfunction startOver() {\n endSession();\n newVisitorId();\n config.storage.setItem(keys.user_id, '');\n}\n"],"mappings":";;;;;;;;;;;AAcA,MAAa,iBAAiB;;;;;;;;;;;AAY9B,IAAI;;AAGJ,SAAS,SAAS,MAA2C;CAC3DA,oBAAAA,OAAO,aAAa,SAAS,EAAE,cAAc;EAC3C,IAAI;GACF,UAAU,IAAI;EAChB,SAAS,GAAY;GACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC/C;CACF,CAAC;AACH;;;;;;;;;;;;;;;AAgBA,SAAgB,SAAS,QAAgB,UAA6B;CACpE,IAAI,UAAU;CACd,IAAI;EACF,MAAM,WAAWA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,OAAO;EACpD,IAAI,YAAY,aAAa,QAAQ;GAEnC,UAAU;GACV,SAAS,CAAC,CAAC;EACb;EACAD,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,SAAS,MAAM;EAC3C,UAAUC,mBAAAA,UAAU;CACtB,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;CAC/C;CAEA,MAAM,UAAU,GAAG,QAAQ,GAAG;CAC9B,IAAI,YAAY,YAAY;EAC1B,aAAa;EACbC,oBAAAA,MAAM,gBAAgB,EAAE,SAAS,OAAO,GAAG,EAAE,0BAA0B,MAAM,CAAC;CAChF;CAEA,SAAS;EAAE,SAAS;EAAQ,WAAW;CAAS,CAAC;AACnD;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,QAAQ;CACtB,IAAI,UAAU;CACd,IAAI;EACF,MAAM,OAAOH,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,OAAO;EAChD,UAAU,CAAC,CAAC,SAAS,eAAe,KAAA,KAAa,eAAe,GAAGC,mBAAAA,UAAU,EAAE,GAAG;EAClF,IAAI,SAAS,UAAU;CACzB,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;CAC/C;CACA,IAAI,WAAW,YAAY,SAAS,CAAC,CAAC;CACtC,aAAa;AACf;;;;;AAMA,SAAS,YAAY;CACnBE,oBAAAA,WAAW;CACXC,mBAAAA,aAAa;CACbL,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,SAAS,EAAE;AACzC"}
|
package/dist/visitor/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { config } from "../setup/index.mjs";
|
|
2
1
|
import { keys } from "../constants/storage.mjs";
|
|
3
|
-
import {
|
|
2
|
+
import { config } from "../setup/index.mjs";
|
|
4
3
|
import { endSession, track } from "../track/index.mjs";
|
|
4
|
+
import { newVisitorId, visitorId } from "./id.mjs";
|
|
5
5
|
// src/visitor/index.ts
|
|
6
6
|
/**
|
|
7
7
|
* The event that binds the visitor to the user who signed in on it: the server sets the visitor's
|
package/dist/web/index.cjs
CHANGED
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const
|
|
3
|
-
const require_setup_index = require("../setup/index.cjs");
|
|
2
|
+
const require_bowser = require("../node_modules/.pnpm/bowser@2.15.0/node_modules/bowser/bowser.cjs");
|
|
4
3
|
const require_constants_storage = require("../constants/storage.cjs");
|
|
5
4
|
const require_link_index = require("../link/index.cjs");
|
|
6
|
-
const
|
|
5
|
+
const require_setup_index = require("../setup/index.cjs");
|
|
7
6
|
const require_utils_redact_url = require("../utils/redact-url.cjs");
|
|
8
7
|
const require_web_page_key = require("./page-key.cjs");
|
|
9
8
|
let uuid = require("uuid");
|
|
10
9
|
let cookie = require("cookie");
|
|
11
10
|
// src/web/index.ts
|
|
12
|
-
var import_es5 = /* @__PURE__ */ require_runtime.__toESM(require_es5$1.default, 1);
|
|
13
11
|
function randomUUID() {
|
|
14
12
|
return crypto.randomUUID ? crypto.randomUUID() : (0, uuid.v4)();
|
|
15
13
|
}
|
|
@@ -89,7 +87,7 @@ async function getTags() {
|
|
|
89
87
|
const page_location = require_utils_redact_url.redactUrl(window.location.href);
|
|
90
88
|
const { id: page_load_id, referrer: page_referrer } = currentPage();
|
|
91
89
|
const page_title = document.title;
|
|
92
|
-
parser ??=
|
|
90
|
+
parser ??= require_bowser.getParser(window.navigator.userAgent);
|
|
93
91
|
const params = new URLSearchParams(window.location.search);
|
|
94
92
|
const os = parser.getOS();
|
|
95
93
|
const browser = parser.getBrowser();
|