@shware/analytics 15.0.1 → 16.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +164 -36
- package/dist/native/fbsdk.cjs +44 -1
- package/dist/native/fbsdk.cjs.map +1 -1
- package/dist/native/fbsdk.d.cts +23 -1
- package/dist/native/fbsdk.d.cts.map +1 -1
- package/dist/native/fbsdk.d.mts +23 -1
- package/dist/native/fbsdk.d.mts.map +1 -1
- package/dist/native/fbsdk.mjs +44 -3
- package/dist/native/fbsdk.mjs.map +1 -1
- package/dist/native/firebase.cjs +27 -0
- package/dist/native/firebase.cjs.map +1 -1
- package/dist/native/firebase.d.cts +11 -0
- package/dist/native/firebase.d.cts.map +1 -1
- package/dist/native/firebase.d.mts +11 -0
- package/dist/native/firebase.d.mts.map +1 -1
- package/dist/native/firebase.mjs +27 -2
- package/dist/native/firebase.mjs.map +1 -1
- package/dist/next/index.cjs +10 -123
- package/dist/next/index.cjs.map +1 -1
- package/dist/next/index.d.cts +2 -31
- package/dist/next/index.d.cts.map +1 -1
- package/dist/next/index.d.mts +2 -31
- package/dist/next/index.d.mts.map +1 -1
- package/dist/next/index.mjs +10 -123
- package/dist/next/index.mjs.map +1 -1
- package/dist/react/index.cjs +45 -0
- package/dist/react/index.cjs.map +1 -0
- package/dist/react/index.d.cts +15 -0
- package/dist/react/index.d.cts.map +1 -0
- package/dist/react/index.d.mts +15 -0
- package/dist/react/index.d.mts.map +1 -0
- package/dist/react/index.mjs +43 -0
- package/dist/react/index.mjs.map +1 -0
- package/dist/react/use-feature-flag.cjs +23 -0
- package/dist/react/use-feature-flag.cjs.map +1 -0
- package/dist/react/use-feature-flag.d.cts +10 -0
- package/dist/react/use-feature-flag.d.cts.map +1 -0
- package/dist/react/use-feature-flag.d.mts +10 -0
- package/dist/react/use-feature-flag.d.mts.map +1 -0
- package/dist/react/use-feature-flag.mjs +22 -0
- package/dist/react/use-feature-flag.mjs.map +1 -0
- package/dist/server/conversions-api-error.cjs +20 -0
- package/dist/server/conversions-api-error.cjs.map +1 -0
- package/dist/server/conversions-api-error.d.cts +17 -0
- package/dist/server/conversions-api-error.d.cts.map +1 -0
- package/dist/server/conversions-api-error.d.mts +17 -0
- package/dist/server/conversions-api-error.d.mts.map +1 -0
- package/dist/server/conversions-api-error.mjs +19 -0
- package/dist/server/conversions-api-error.mjs.map +1 -0
- package/dist/server/google-data-manager.cjs +24 -26
- package/dist/server/google-data-manager.cjs.map +1 -1
- package/dist/server/google-data-manager.d.cts +13 -5
- package/dist/server/google-data-manager.d.cts.map +1 -1
- package/dist/server/google-data-manager.d.mts +13 -5
- package/dist/server/google-data-manager.d.mts.map +1 -1
- package/dist/server/google-data-manager.mjs +24 -27
- package/dist/server/google-data-manager.mjs.map +1 -1
- package/dist/server/index.cjs +11 -0
- package/dist/server/index.d.cts +10 -7
- package/dist/server/index.d.mts +10 -7
- package/dist/server/index.mjs +9 -7
- package/dist/server/linkedin-conversions-api.cjs +29 -23
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.d.cts +7 -2
- package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
- package/dist/server/linkedin-conversions-api.d.mts +7 -2
- package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs +29 -24
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/dist/server/meta-capi.cjs +32 -31
- package/dist/server/meta-capi.cjs.map +1 -1
- package/dist/server/meta-capi.d.cts +12 -3
- package/dist/server/meta-capi.d.cts.map +1 -1
- package/dist/server/meta-capi.d.mts +12 -3
- package/dist/server/meta-capi.d.mts.map +1 -1
- package/dist/server/meta-capi.mjs +33 -33
- package/dist/server/meta-capi.mjs.map +1 -1
- package/dist/server/microsoft-conversions-api.cjs +33 -28
- package/dist/server/microsoft-conversions-api.cjs.map +1 -1
- package/dist/server/microsoft-conversions-api.d.cts +14 -2
- package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
- package/dist/server/microsoft-conversions-api.d.mts +14 -2
- package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
- package/dist/server/microsoft-conversions-api.mjs +33 -29
- package/dist/server/microsoft-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +20 -18
- package/dist/server/openai-conversions-api.cjs.map +1 -1
- package/dist/server/openai-conversions-api.d.cts +7 -0
- package/dist/server/openai-conversions-api.d.cts.map +1 -1
- package/dist/server/openai-conversions-api.d.mts +7 -0
- package/dist/server/openai-conversions-api.d.mts.map +1 -1
- package/dist/server/openai-conversions-api.mjs +21 -20
- package/dist/server/openai-conversions-api.mjs.map +1 -1
- package/dist/server/reddit-conversions-api.cjs +20 -18
- package/dist/server/reddit-conversions-api.cjs.map +1 -1
- package/dist/server/reddit-conversions-api.d.cts +8 -1
- package/dist/server/reddit-conversions-api.d.cts.map +1 -1
- package/dist/server/reddit-conversions-api.d.mts +8 -1
- package/dist/server/reddit-conversions-api.d.mts.map +1 -1
- package/dist/server/reddit-conversions-api.mjs +21 -20
- package/dist/server/reddit-conversions-api.mjs.map +1 -1
- package/dist/server/setup-conversions.cjs +62 -0
- package/dist/server/setup-conversions.cjs.map +1 -0
- package/dist/server/setup-conversions.d.cts +97 -0
- package/dist/server/setup-conversions.d.cts.map +1 -0
- package/dist/server/setup-conversions.d.mts +97 -0
- package/dist/server/setup-conversions.d.mts.map +1 -0
- package/dist/server/setup-conversions.mjs +60 -0
- package/dist/server/setup-conversions.mjs.map +1 -0
- package/dist/setup/index.cjs +4 -4
- package/dist/setup/index.cjs.map +1 -1
- package/dist/setup/index.d.cts +16 -6
- package/dist/setup/index.d.cts.map +1 -1
- package/dist/setup/index.d.mts +16 -6
- package/dist/setup/index.d.mts.map +1 -1
- package/dist/setup/index.mjs +4 -4
- package/dist/setup/index.mjs.map +1 -1
- package/dist/tanstack/index.cjs +0 -2
- package/dist/tanstack/index.d.cts +1 -2
- package/dist/tanstack/index.d.mts +1 -2
- package/dist/tanstack/index.mjs +1 -3
- package/dist/third-parties/analytics-props.cjs +28 -0
- package/dist/third-parties/analytics-props.cjs.map +1 -0
- package/dist/third-parties/analytics-props.d.cts +23 -0
- package/dist/third-parties/analytics-props.d.cts.map +1 -0
- package/dist/third-parties/analytics-props.d.mts +23 -0
- package/dist/third-parties/analytics-props.d.mts.map +1 -0
- package/dist/third-parties/analytics-props.mjs +26 -0
- package/dist/third-parties/analytics-props.mjs.map +1 -0
- package/dist/third-parties/google-analytics.cjs +32 -0
- package/dist/third-parties/google-analytics.cjs.map +1 -1
- package/dist/third-parties/google-analytics.d.cts +11 -1
- package/dist/third-parties/google-analytics.d.cts.map +1 -1
- package/dist/third-parties/google-analytics.d.mts +11 -1
- package/dist/third-parties/google-analytics.d.mts.map +1 -1
- package/dist/third-parties/google-analytics.mjs +32 -1
- package/dist/third-parties/google-analytics.mjs.map +1 -1
- package/dist/third-parties/index.cjs +16 -0
- package/dist/third-parties/index.d.cts +9 -7
- package/dist/third-parties/index.d.mts +9 -7
- package/dist/third-parties/index.mjs +9 -7
- package/dist/third-parties/integration.cjs +46 -0
- package/dist/third-parties/integration.cjs.map +1 -0
- package/dist/third-parties/integration.d.cts +61 -0
- package/dist/third-parties/integration.d.cts.map +1 -0
- package/dist/third-parties/integration.d.mts +61 -0
- package/dist/third-parties/integration.d.mts.map +1 -0
- package/dist/third-parties/integration.mjs +43 -0
- package/dist/third-parties/integration.mjs.map +1 -0
- package/dist/third-parties/linkedin-insight-tag.cjs +29 -0
- package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.cts +14 -8
- package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.mts +14 -8
- package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.mjs +29 -1
- package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
- package/dist/third-parties/meta-pixel.cjs +32 -0
- package/dist/third-parties/meta-pixel.cjs.map +1 -1
- package/dist/third-parties/meta-pixel.d.cts +7 -0
- package/dist/third-parties/meta-pixel.d.cts.map +1 -1
- package/dist/third-parties/meta-pixel.d.mts +7 -0
- package/dist/third-parties/meta-pixel.d.mts.map +1 -1
- package/dist/third-parties/meta-pixel.mjs +33 -2
- package/dist/third-parties/meta-pixel.mjs.map +1 -1
- package/dist/third-parties/microsoft-uet.cjs +54 -0
- package/dist/third-parties/microsoft-uet.cjs.map +1 -1
- package/dist/third-parties/microsoft-uet.d.cts +36 -0
- package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
- package/dist/third-parties/microsoft-uet.d.mts +36 -0
- package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
- package/dist/third-parties/microsoft-uet.mjs +52 -1
- package/dist/third-parties/microsoft-uet.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +29 -0
- package/dist/third-parties/openai-pixel.cjs.map +1 -1
- package/dist/third-parties/openai-pixel.d.cts +7 -0
- package/dist/third-parties/openai-pixel.d.cts.map +1 -1
- package/dist/third-parties/openai-pixel.d.mts +7 -0
- package/dist/third-parties/openai-pixel.d.mts.map +1 -1
- package/dist/third-parties/openai-pixel.mjs +30 -2
- package/dist/third-parties/openai-pixel.mjs.map +1 -1
- package/dist/third-parties/posthog.cjs +97 -4
- package/dist/third-parties/posthog.cjs.map +1 -1
- package/dist/third-parties/posthog.d.cts +56 -1
- package/dist/third-parties/posthog.d.cts.map +1 -1
- package/dist/third-parties/posthog.d.mts +56 -1
- package/dist/third-parties/posthog.d.mts.map +1 -1
- package/dist/third-parties/posthog.mjs +91 -2
- package/dist/third-parties/posthog.mjs.map +1 -1
- package/dist/third-parties/reddit-pixel.cjs +30 -0
- package/dist/third-parties/reddit-pixel.cjs.map +1 -1
- package/dist/third-parties/reddit-pixel.d.cts +7 -0
- package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
- package/dist/third-parties/reddit-pixel.d.mts +7 -0
- package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
- package/dist/third-parties/reddit-pixel.mjs +31 -2
- package/dist/third-parties/reddit-pixel.mjs.map +1 -1
- package/dist/track/fbq.cjs +6 -1
- package/dist/track/fbq.cjs.map +1 -1
- package/dist/track/fbq.d.cts +2 -0
- package/dist/track/fbq.d.cts.map +1 -1
- package/dist/track/fbq.d.mts +2 -0
- package/dist/track/fbq.d.mts.map +1 -1
- package/dist/track/fbq.mjs +6 -2
- package/dist/track/fbq.mjs.map +1 -1
- package/dist/track/index.cjs +7 -7
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.d.cts.map +1 -1
- package/dist/track/index.d.mts.map +1 -1
- package/dist/track/index.mjs +7 -7
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/oaiq.cjs +5 -0
- package/dist/track/oaiq.cjs.map +1 -1
- package/dist/track/oaiq.d.cts +2 -0
- package/dist/track/oaiq.d.cts.map +1 -1
- package/dist/track/oaiq.d.mts +2 -0
- package/dist/track/oaiq.d.mts.map +1 -1
- package/dist/track/oaiq.mjs +5 -1
- package/dist/track/oaiq.mjs.map +1 -1
- package/dist/track/rdt.cjs +5 -0
- package/dist/track/rdt.cjs.map +1 -1
- package/dist/track/rdt.d.cts +2 -0
- package/dist/track/rdt.d.cts.map +1 -1
- package/dist/track/rdt.d.mts +2 -0
- package/dist/track/rdt.d.mts.map +1 -1
- package/dist/track/rdt.mjs +5 -1
- package/dist/track/rdt.mjs.map +1 -1
- package/dist/visitor/index.cjs +3 -3
- package/dist/visitor/index.cjs.map +1 -1
- package/dist/visitor/index.mjs +3 -3
- package/dist/visitor/index.mjs.map +1 -1
- package/package.json +11 -39
- package/dist/react-router/index.cjs +0 -160
- package/dist/react-router/index.cjs.map +0 -1
- package/dist/react-router/index.d.cts +0 -22
- package/dist/react-router/index.d.cts.map +0 -1
- package/dist/react-router/index.d.mts +0 -22
- package/dist/react-router/index.d.mts.map +0 -1
- package/dist/react-router/index.mjs +0 -159
- package/dist/react-router/index.mjs.map +0 -1
- package/dist/server/legacy.cjs +0 -3
- package/dist/server/legacy.d.cts +0 -2
- package/dist/server/legacy.d.mts +0 -2
- package/dist/server/legacy.mjs +0 -1
- package/dist/server/meta-conversions-api.cjs +0 -205
- package/dist/server/meta-conversions-api.cjs.map +0 -1
- package/dist/server/meta-conversions-api.d.cts +0 -8
- package/dist/server/meta-conversions-api.d.cts.map +0 -1
- package/dist/server/meta-conversions-api.d.mts +0 -8
- package/dist/server/meta-conversions-api.d.mts.map +0 -1
- package/dist/server/meta-conversions-api.mjs +0 -201
- package/dist/server/meta-conversions-api.mjs.map +0 -1
- package/dist/tanstack/analytics.cjs +0 -184
- package/dist/tanstack/analytics.cjs.map +0 -1
- package/dist/tanstack/analytics.d.cts +0 -33
- package/dist/tanstack/analytics.d.cts.map +0 -1
- package/dist/tanstack/analytics.d.mts +0 -33
- package/dist/tanstack/analytics.d.mts.map +0 -1
- package/dist/tanstack/analytics.mjs +0 -183
- package/dist/tanstack/analytics.mjs.map +0 -1
package/dist/track/index.mjs
CHANGED
|
@@ -62,16 +62,16 @@ let timer = null;
|
|
|
62
62
|
* either exists by then or the script is blocked.
|
|
63
63
|
*/
|
|
64
64
|
function firePixels({ event, options }) {
|
|
65
|
-
if (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) return;
|
|
66
|
-
const notReady =
|
|
65
|
+
if (options.enableThirdPartyTracking === false || config.excludeFromIntegrations.includes(event.name) || IGNORED_EVENTS.includes(event.name)) return;
|
|
66
|
+
const notReady = callIntegrations(config.integrations, event);
|
|
67
67
|
if (notReady.length === 0) return;
|
|
68
|
-
setTimeout(() =>
|
|
68
|
+
setTimeout(() => callIntegrations(notReady, event), 0);
|
|
69
69
|
}
|
|
70
|
-
/**
|
|
71
|
-
function
|
|
72
|
-
return
|
|
70
|
+
/** Hands the event to each integration; returns the ones that said they were not ready. */
|
|
71
|
+
function callIntegrations(integrations, event) {
|
|
72
|
+
return integrations.filter(({ track }) => {
|
|
73
73
|
try {
|
|
74
|
-
return
|
|
74
|
+
return track(event.name, event.properties, event.id) === false;
|
|
75
75
|
} catch (e) {
|
|
76
76
|
if (e instanceof Error) console.log(e.message);
|
|
77
77
|
return false;
|
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 { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} 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.log(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 (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: TrackEvent): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(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.log(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.log(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.log(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":";;;;;;;AA4BA,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,IAAI,EAAE,OAAO;EAC7C,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,IAAI,QAAQ,6BAA6B,SAAS,eAAe,SAAS,MAAM,IAAI,GAClF;CAEF,MAAM,WAAW,aAAa,OAAO,oBAAoB,KAAK;CAC9D,IAAI,SAAS,WAAW,GAAG;CAC3B,iBAAiB,aAAa,UAAU,KAAK,GAAG,CAAC;AACnD;;AAGA,SAAS,aAAa,UAA+B,OAAwC;CAC3F,OAAO,SAAS,QAAQ,YAAY;EAClC,IAAI;GACF,OAAO,QAAQ,MAAM,MAAM,MAAM,YAAY,MAAM,EAAE,MAAM;EAC7D,SAAS,GAAY;GAEnB,IA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AAI,MAAM;GAAI,QAAQ;EAAK,CAAC,CAAC;CAC3F,CAAC;CACD,IAAI,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.log(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.log(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.log(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.log(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,IAAI,EAAE,OAAO;EAC7C,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,iBAAi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,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,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/oaiq.cjs
CHANGED
|
@@ -228,8 +228,13 @@ function mapOAIEvent(name, properties) {
|
|
|
228
228
|
}
|
|
229
229
|
}
|
|
230
230
|
}
|
|
231
|
+
/** Whether `mapOAIEvent` turns the event into an OpenAI standard event rather than `custom`. */
|
|
232
|
+
function isStandardOAIEvent(name) {
|
|
233
|
+
return mapOAIEvent(name).type !== "custom";
|
|
234
|
+
}
|
|
231
235
|
exports.APP_EVENTS = APP_EVENTS;
|
|
232
236
|
exports.NON_AD_EVENTS = NON_AD_EVENTS;
|
|
237
|
+
exports.isStandardOAIEvent = isStandardOAIEvent;
|
|
233
238
|
exports.mapContents = mapContents;
|
|
234
239
|
exports.mapOAIEvent = mapOAIEvent;
|
|
235
240
|
exports.normalizeOAIName = normalizeOAIName;
|
package/dist/track/oaiq.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oaiq.cjs","names":[],"sources":["../../src/track/oaiq.ts"],"sourcesContent":["import type { Item } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport const NON_AD_EVENTS = [\n // metrics\n 'CLS',\n 'FCP',\n 'FID',\n 'INP',\n 'LCP',\n 'TTFB',\n // promotions\n 'view_promotion',\n 'select_promotion',\n];\n\n/**\n * Content item shared by `contents` and `plan_enrollment` events.\n * https://developers.openai.com/ads/supported-events\n */\nexport type ContentItem = {\n id?: string;\n name?: string;\n content_type?: string;\n quantity?: number;\n /** Per-item monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n};\n\nexport type ContentsData = {\n type: 'contents';\n /** Monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomerActionData = {\n type: 'customer_action';\n amount?: number;\n currency?: string;\n};\n\nexport type PlanEnrollmentData = {\n type: 'plan_enrollment';\n plan_id?: string;\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomEventData = {\n type: 'custom';\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type EventData = ContentsData | CustomerActionData | PlanEnrollmentData | CustomEventData;\n\n/**\n * Standard event names and the `data` shape each one expects.\n * https://developers.openai.com/ads/supported-events\n */\nexport type StandardEvents = {\n app_installed: CustomerActionData;\n app_opened: CustomerActionData;\n appointment_scheduled: CustomerActionData;\n checkout_started: ContentsData;\n contents_viewed: ContentsData;\n items_added: ContentsData;\n lead_created: CustomerActionData;\n order_created: ContentsData;\n page_viewed: ContentsData;\n registration_completed: CustomerActionData;\n subscription_created: PlanEnrollmentData;\n trial_started: PlanEnrollmentData;\n};\n\nexport type StandardEvent = keyof StandardEvents;\n\n/**\n * The app events, which OpenAI takes \"through the Conversions API only\", with `action_source`\n * `mobile_app`: the pixel never sends them, and the server only for an app's events.\n * https://developers.openai.com/ads/supported-events\n */\nexport const APP_EVENTS: readonly StandardEvent[] = ['app_installed', 'app_opened'];\n\nconst STANDARD_EVENTS: readonly string[] = [\n 'app_installed',\n 'app_opened',\n 'appointment_scheduled',\n 'checkout_started',\n 'contents_viewed',\n 'items_added',\n 'lead_created',\n 'order_created',\n 'page_viewed',\n 'registration_completed',\n 'subscription_created',\n 'trial_started',\n] satisfies StandardEvent[];\n\n/**\n * A track name as an OpenAI `custom_event_name`: 1–64 letters, digits, underscores or hyphens,\n * starting and ending with a letter or digit, not a standard event name; the API lowercases it.\n * Anything else becomes an underscore, so `Sign Up.Clicked` is `sign_up_clicked`. Undefined when\n * nothing usable is left — the event is then not sent at all. The pixel and the server both name\n * a custom event through this, so the two still deduplicate.\n * https://developers.openai.com/ads/supported-events\n */\nexport function oaiCustomEventName(name: string): string | undefined {\n const sanitized = name\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, '_')\n .slice(0, 64)\n .replace(/^[_-]+|[_-]+$/g, '');\n if (!sanitized || STANDARD_EVENTS.includes(sanitized)) return undefined;\n return sanitized;\n}\n\n/**\n * Identity fields passed to `oaiq(\"init\", ...)` for conversion matching. Identifiers are\n * normalized, then sent as lowercase 64-char SHA-256 hex strings; geographic values are raw.\n * https://developers.openai.com/ads/measurement-pixel#send-user-data\n */\nexport type OAIQUser = {\n email_sha256?: string;\n /** 8–15 digits with the country code, no leading `+` or zeroes (`normalizeOAIPhone`). */\n phone_number_sha256?: string;\n external_id_sha256?: string;\n /** Lowercase, without whitespace or ASCII punctuation (`normalizeOAIName`). */\n first_name_sha256?: string;\n last_name_sha256?: string;\n /** Two-letter ISO 3166-1 country code (e.g. \"US\"). */\n country?: string;\n /** Max 128 characters; OpenAI trims and lowercases it. */\n city?: string;\n /** State, province or region, max 128 characters. */\n region?: string;\n postal_code?: string;\n};\n\n/**\n * A phone number as OpenAI hashes it: whitespace, parentheses, periods and hyphens removed, then\n * the leading `+` and zeroes; 8–15 digits with the country code, else not a usable number.\n */\nexport function normalizeOAIPhone(phone: string): string | undefined {\n const digits = phone\n .replace(/[\\s().-]/g, '')\n .replace(/^\\+/, '')\n .replace(/^0+/, '');\n return /^\\d{8,15}$/.test(digits) ? digits : undefined;\n}\n\n/** A name as OpenAI hashes it: lowercase, no whitespace or ASCII punctuation, accents kept. */\nexport function normalizeOAIName(name: string | undefined): string | undefined {\n return name?.toLowerCase().replace(/[\\s!-/:-@[-`{-~]/g, '') || undefined;\n}\n\nexport type InitConfig = {\n pixelId: string;\n /** Log SDK activity to the browser console. */\n debug?: boolean;\n user?: OAIQUser;\n};\n\n/**\n * Fourth argument of `oaiq(\"measure\", ...)`. Required for custom events (carries\n * `custom_event_name`); optional for standard events.\n */\nexport type MeasureOptions = {\n /** Shared with the Conversions API to deduplicate the same conversion across browser and server. */\n event_id?: string;\n /** Required for custom events; 1-64 chars of letters, numbers, underscores, or dashes. */\n custom_event_name?: string;\n /** When true, opts the event out of user-level personalization. */\n opt_out?: boolean;\n};\n\nexport interface OAIQ {\n oaiq(command: 'init', config: InitConfig): void;\n oaiq<T extends StandardEvent>(\n command: 'measure',\n event: T,\n data: StandardEvents[T],\n options?: MeasureOptions\n ): void;\n oaiq(\n command: 'measure',\n event: 'custom',\n data: CustomEventData,\n options: MeasureOptions & { custom_event_name: string }\n ): void;\n}\n\n/**\n * Currencies whose minor unit has 0 or 3 decimal places; everything else uses 2.\n * Follows Stripe's zero-decimal convention (e.g., MGA is treated as 0, ISK is included),\n * which can differ from strict ISO 4217 exponents.\n * https://docs.stripe.com/currencies#zero-decimal\n */\nconst ZERO_DECIMAL_CURRENCIES = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n]);\nconst THREE_DECIMAL_CURRENCIES = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND']);\n\n/**\n * Convert a major-unit amount (e.g., 129.99) into ISO 4217 minor units (e.g., 12,999). None\n * without a currency: the minor unit depends on it, and OpenAI requires a `currency` with every\n * `amount` — an amount alone would be invalid, not just imprecise.\n */\nexport function toMinorUnits(value?: number | null, currency?: string): number | undefined {\n if (value === undefined || value === null || Number.isNaN(value)) return undefined;\n const code = currency?.toUpperCase();\n if (!code) return undefined;\n const exponent =\n code && ZERO_DECIMAL_CURRENCIES.has(code)\n ? 0\n : code && THREE_DECIMAL_CURRENCIES.has(code)\n ? 3\n : 2;\n return Math.round(value * 10 ** exponent);\n}\n\nexport function mapContents(items?: Item[], currency?: string): ContentItem[] | undefined {\n if (!items || items.length === 0) return undefined;\n const code = currency?.toUpperCase();\n return items.map((item) => {\n const amount = toMinorUnits(item.price, currency);\n return {\n id: item.item_id,\n name: item.item_name,\n content_type: item.item_category,\n quantity: item.quantity,\n amount,\n currency: amount !== undefined ? code : undefined,\n };\n });\n}\n\n/** Safely read a property off loosely typed track properties without widening to `any`. */\nfunction prop(properties: unknown, key: string): unknown {\n return typeof properties === 'object' && properties !== null\n ? (properties as Record<string, unknown>)[key]\n : undefined;\n}\n\nfunction readValue(properties: unknown): number | undefined {\n const value = prop(properties, 'value');\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction readCurrency(properties: unknown): string | undefined {\n const currency = prop(properties, 'currency');\n return typeof currency === 'string' ? currency : undefined;\n}\n\nfunction readItems(properties: unknown): Item[] | undefined {\n const items = prop(properties, 'items');\n return Array.isArray(items) ? (items as Item[]) : undefined;\n}\n\nfunction contentsData(properties: unknown): ContentsData {\n const currency = readCurrency(properties);\n return {\n type: 'contents',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n };\n}\n\nfunction customerActionData(properties: unknown): CustomerActionData {\n const currency = readCurrency(properties);\n return {\n type: 'customer_action',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n };\n}\n\nfunction planEnrollmentData(properties: unknown): PlanEnrollmentData {\n const currency = readCurrency(properties);\n const items = readItems(properties);\n return {\n type: 'plan_enrollment',\n plan_id: items?.[0]?.item_id,\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(items, currency),\n };\n}\n\nexport type MappedOAIEvent = {\n type: StandardEvent | 'custom';\n data: EventData;\n};\n\n/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */\nexport function mapOAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): MappedOAIEvent {\n switch (name) {\n // The app's first launch, recorded once by the app hook: the closest thing to an install.\n case 'first_open':\n return { type: 'app_installed', data: customerActionData(properties) };\n case 'app_open':\n return { type: 'app_opened', data: customerActionData(properties) };\n case 'page_view':\n return { type: 'page_viewed', data: contentsData(properties) };\n case 'view_item':\n case 'view_item_list':\n return { type: 'contents_viewed', data: contentsData(properties) };\n case 'begin_checkout':\n return { type: 'checkout_started', data: contentsData(properties) };\n case 'add_to_cart':\n return { type: 'items_added', data: contentsData(properties) };\n case 'purchase':\n return { type: 'order_created', data: contentsData(properties) };\n case 'generate_lead':\n case 'qualify_lead':\n return { type: 'lead_created', data: customerActionData(properties) };\n case 'sign_up':\n case 'login':\n return { type: 'registration_completed', data: customerActionData(properties) };\n case 'schedule':\n return { type: 'appointment_scheduled', data: customerActionData(properties) };\n case 'subscribe':\n return { type: 'subscription_created', data: planEnrollmentData(properties) };\n case 'trial_begin':\n return { type: 'trial_started', data: planEnrollmentData(properties) };\n default: {\n const currency = readCurrency(properties);\n return {\n type: 'custom',\n data: {\n type: 'custom',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n },\n };\n }\n }\n}\n"],"mappings":";;AAGA,MAAa,gBAAgB;CAE3B;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;AACF;;;;;;AAyEA,MAAa,aAAuC,CAAC,iBAAiB,YAAY;AAElF,MAAM,kBAAqC;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,SAAgB,mBAAmB,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AACF;;AAQA,SAAgB,YACd,MACA,YACgB;CAChB,QAAQ,MAAR;EAEE,KAAK,cACH,OAAO;GAAE,MAAM;GAAiB,MAAM,mBAAmB,UAAU;EAAE;EACvE,KAAK,YACH,OAAO;GAAE,MAAM;GAAc,MAAM,mBAAmB,UAAU;EAAE;EACpE,KAAK,aACH,OAAO;GAAE,MAAM;GAAe,MAAM,aAAa,UAAU;EAAE;EAC/D,KAAK;EACL,KAAK,kBACH,OAAO;GAAE,MAAM;GAAmB,MAAM,aAAa,UAAU;EAAE;EACnE,KAAK,kBACH,OAAO;GAAE,MAAM;GAAoB,MAAM,aAAa,UAAU;EAAE;EACpE,KAAK,eACH,OAAO;GAAE,MAAM;GAAe,MAAM,aAAa,UAAU;EAAE;EAC/D,KAAK,YACH,OAAO;GAAE,MAAM;GAAiB,MAAM,aAAa,UAAU;EAAE;EACjE,KAAK;EACL,KAAK,gBACH,OAAO;GAAE,MAAM;GAAgB,MAAM,mBAAmB,UAAU;EAAE;EACtE,KAAK;EACL,KAAK,SACH,OAAO;GAAE,MAAM;GAA0B,MAAM,mBAAmB,UAAU;EAAE;EAChF,KAAK,YACH,OAAO;GAAE,MAAM;GAAyB,MAAM,mBAAmB,UAAU;EAAE;EAC/E,KAAK,aACH,OAAO;GAAE,MAAM;GAAwB,MAAM,mBAAmB,UAAU;EAAE;EAC9E,KAAK,eACH,OAAO;GAAE,MAAM;GAAiB,MAAM,mBAAmB,UAAU;EAAE;EACvE,SAAS;GACP,MAAM,WAAW,aAAa,UAAU;GACxC,OAAO;IACL,MAAM;IACN,MAAM;KACJ,MAAM;KACN,QAAQ,aAAa,UAAU,UAAU,GAAG,QAAQ;KACpD,UAAU,UAAU,YAAY;KAChC,UAAU,YAAY,UAAU,UAAU,GAAG,QAAQ;IACvD;GACF;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"oaiq.cjs","names":[],"sources":["../../src/track/oaiq.ts"],"sourcesContent":["import type { Item } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport const NON_AD_EVENTS = [\n // metrics\n 'CLS',\n 'FCP',\n 'FID',\n 'INP',\n 'LCP',\n 'TTFB',\n // promotions\n 'view_promotion',\n 'select_promotion',\n];\n\n/**\n * Content item shared by `contents` and `plan_enrollment` events.\n * https://developers.openai.com/ads/supported-events\n */\nexport type ContentItem = {\n id?: string;\n name?: string;\n content_type?: string;\n quantity?: number;\n /** Per-item monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n};\n\nexport type ContentsData = {\n type: 'contents';\n /** Monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomerActionData = {\n type: 'customer_action';\n amount?: number;\n currency?: string;\n};\n\nexport type PlanEnrollmentData = {\n type: 'plan_enrollment';\n plan_id?: string;\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomEventData = {\n type: 'custom';\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type EventData = ContentsData | CustomerActionData | PlanEnrollmentData | CustomEventData;\n\n/**\n * Standard event names and the `data` shape each one expects.\n * https://developers.openai.com/ads/supported-events\n */\nexport type StandardEvents = {\n app_installed: CustomerActionData;\n app_opened: CustomerActionData;\n appointment_scheduled: CustomerActionData;\n checkout_started: ContentsData;\n contents_viewed: ContentsData;\n items_added: ContentsData;\n lead_created: CustomerActionData;\n order_created: ContentsData;\n page_viewed: ContentsData;\n registration_completed: CustomerActionData;\n subscription_created: PlanEnrollmentData;\n trial_started: PlanEnrollmentData;\n};\n\nexport type StandardEvent = keyof StandardEvents;\n\n/**\n * The app events, which OpenAI takes \"through the Conversions API only\", with `action_source`\n * `mobile_app`: the pixel never sends them, and the server only for an app's events.\n * https://developers.openai.com/ads/supported-events\n */\nexport const APP_EVENTS: readonly StandardEvent[] = ['app_installed', 'app_opened'];\n\nconst STANDARD_EVENTS: readonly string[] = [\n 'app_installed',\n 'app_opened',\n 'appointment_scheduled',\n 'checkout_started',\n 'contents_viewed',\n 'items_added',\n 'lead_created',\n 'order_created',\n 'page_viewed',\n 'registration_completed',\n 'subscription_created',\n 'trial_started',\n] satisfies StandardEvent[];\n\n/**\n * A track name as an OpenAI `custom_event_name`: 1–64 letters, digits, underscores or hyphens,\n * starting and ending with a letter or digit, not a standard event name; the API lowercases it.\n * Anything else becomes an underscore, so `Sign Up.Clicked` is `sign_up_clicked`. Undefined when\n * nothing usable is left — the event is then not sent at all. The pixel and the server both name\n * a custom event through this, so the two still deduplicate.\n * https://developers.openai.com/ads/supported-events\n */\nexport function oaiCustomEventName(name: string): string | undefined {\n const sanitized = name\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, '_')\n .slice(0, 64)\n .replace(/^[_-]+|[_-]+$/g, '');\n if (!sanitized || STANDARD_EVENTS.includes(sanitized)) return undefined;\n return sanitized;\n}\n\n/**\n * Identity fields passed to `oaiq(\"init\", ...)` for conversion matching. Identifiers are\n * normalized, then sent as lowercase 64-char SHA-256 hex strings; geographic values are raw.\n * https://developers.openai.com/ads/measurement-pixel#send-user-data\n */\nexport type OAIQUser = {\n email_sha256?: string;\n /** 8–15 digits with the country code, no leading `+` or zeroes (`normalizeOAIPhone`). */\n phone_number_sha256?: string;\n external_id_sha256?: string;\n /** Lowercase, without whitespace or ASCII punctuation (`normalizeOAIName`). */\n first_name_sha256?: string;\n last_name_sha256?: string;\n /** Two-letter ISO 3166-1 country code (e.g. \"US\"). */\n country?: string;\n /** Max 128 characters; OpenAI trims and lowercases it. */\n city?: string;\n /** State, province or region, max 128 characters. */\n region?: string;\n postal_code?: string;\n};\n\n/**\n * A phone number as OpenAI hashes it: whitespace, parentheses, periods and hyphens removed, then\n * the leading `+` and zeroes; 8–15 digits with the country code, else not a usable number.\n */\nexport function normalizeOAIPhone(phone: string): string | undefined {\n const digits = phone\n .replace(/[\\s().-]/g, '')\n .replace(/^\\+/, '')\n .replace(/^0+/, '');\n return /^\\d{8,15}$/.test(digits) ? digits : undefined;\n}\n\n/** A name as OpenAI hashes it: lowercase, no whitespace or ASCII punctuation, accents kept. */\nexport function normalizeOAIName(name: string | undefined): string | undefined {\n return name?.toLowerCase().replace(/[\\s!-/:-@[-`{-~]/g, '') || undefined;\n}\n\nexport type InitConfig = {\n pixelId: string;\n /** Log SDK activity to the browser console. */\n debug?: boolean;\n user?: OAIQUser;\n};\n\n/**\n * Fourth argument of `oaiq(\"measure\", ...)`. Required for custom events (carries\n * `custom_event_name`); optional for standard events.\n */\nexport type MeasureOptions = {\n /** Shared with the Conversions API to deduplicate the same conversion across browser and server. */\n event_id?: string;\n /** Required for custom events; 1-64 chars of letters, numbers, underscores, or dashes. */\n custom_event_name?: string;\n /** When true, opts the event out of user-level personalization. */\n opt_out?: boolean;\n};\n\nexport interface OAIQ {\n oaiq(command: 'init', config: InitConfig): void;\n oaiq<T extends StandardEvent>(\n command: 'measure',\n event: T,\n data: StandardEvents[T],\n options?: MeasureOptions\n ): void;\n oaiq(\n command: 'measure',\n event: 'custom',\n data: CustomEventData,\n options: MeasureOptions & { custom_event_name: string }\n ): void;\n}\n\n/**\n * Currencies whose minor unit has 0 or 3 decimal places; everything else uses 2.\n * Follows Stripe's zero-decimal convention (e.g., MGA is treated as 0, ISK is included),\n * which can differ from strict ISO 4217 exponents.\n * https://docs.stripe.com/currencies#zero-decimal\n */\nconst ZERO_DECIMAL_CURRENCIES = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n]);\nconst THREE_DECIMAL_CURRENCIES = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND']);\n\n/**\n * Convert a major-unit amount (e.g., 129.99) into ISO 4217 minor units (e.g., 12,999). None\n * without a currency: the minor unit depends on it, and OpenAI requires a `currency` with every\n * `amount` — an amount alone would be invalid, not just imprecise.\n */\nexport function toMinorUnits(value?: number | null, currency?: string): number | undefined {\n if (value === undefined || value === null || Number.isNaN(value)) return undefined;\n const code = currency?.toUpperCase();\n if (!code) return undefined;\n const exponent =\n code && ZERO_DECIMAL_CURRENCIES.has(code)\n ? 0\n : code && THREE_DECIMAL_CURRENCIES.has(code)\n ? 3\n : 2;\n return Math.round(value * 10 ** exponent);\n}\n\nexport function mapContents(items?: Item[], currency?: string): ContentItem[] | undefined {\n if (!items || items.length === 0) return undefined;\n const code = currency?.toUpperCase();\n return items.map((item) => {\n const amount = toMinorUnits(item.price, currency);\n return {\n id: item.item_id,\n name: item.item_name,\n content_type: item.item_category,\n quantity: item.quantity,\n amount,\n currency: amount !== undefined ? code : undefined,\n };\n });\n}\n\n/** Safely read a property off loosely typed track properties without widening to `any`. */\nfunction prop(properties: unknown, key: string): unknown {\n return typeof properties === 'object' && properties !== null\n ? (properties as Record<string, unknown>)[key]\n : undefined;\n}\n\nfunction readValue(properties: unknown): number | undefined {\n const value = prop(properties, 'value');\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction readCurrency(properties: unknown): string | undefined {\n const currency = prop(properties, 'currency');\n return typeof currency === 'string' ? currency : undefined;\n}\n\nfunction readItems(properties: unknown): Item[] | undefined {\n const items = prop(properties, 'items');\n return Array.isArray(items) ? (items as Item[]) : undefined;\n}\n\nfunction contentsData(properties: unknown): ContentsData {\n const currency = readCurrency(properties);\n return {\n type: 'contents',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n };\n}\n\nfunction customerActionData(properties: unknown): CustomerActionData {\n const currency = readCurrency(properties);\n return {\n type: 'customer_action',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n };\n}\n\nfunction planEnrollmentData(properties: unknown): PlanEnrollmentData {\n const currency = readCurrency(properties);\n const items = readItems(properties);\n return {\n type: 'plan_enrollment',\n plan_id: items?.[0]?.item_id,\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(items, currency),\n };\n}\n\nexport type MappedOAIEvent = {\n type: StandardEvent | 'custom';\n data: EventData;\n};\n\n/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */\nexport function mapOAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): MappedOAIEvent {\n switch (name) {\n // The app's first launch, recorded once by the app hook: the closest thing to an install.\n case 'first_open':\n return { type: 'app_installed', data: customerActionData(properties) };\n case 'app_open':\n return { type: 'app_opened', data: customerActionData(properties) };\n case 'page_view':\n return { type: 'page_viewed', data: contentsData(properties) };\n case 'view_item':\n case 'view_item_list':\n return { type: 'contents_viewed', data: contentsData(properties) };\n case 'begin_checkout':\n return { type: 'checkout_started', data: contentsData(properties) };\n case 'add_to_cart':\n return { type: 'items_added', data: contentsData(properties) };\n case 'purchase':\n return { type: 'order_created', data: contentsData(properties) };\n case 'generate_lead':\n case 'qualify_lead':\n return { type: 'lead_created', data: customerActionData(properties) };\n case 'sign_up':\n case 'login':\n return { type: 'registration_completed', data: customerActionData(properties) };\n case 'schedule':\n return { type: 'appointment_scheduled', data: customerActionData(properties) };\n case 'subscribe':\n return { type: 'subscription_created', data: planEnrollmentData(properties) };\n case 'trial_begin':\n return { type: 'trial_started', data: planEnrollmentData(properties) };\n default: {\n const currency = readCurrency(properties);\n return {\n type: 'custom',\n data: {\n type: 'custom',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n },\n };\n }\n }\n}\n\n/** Whether `mapOAIEvent` turns the event into an OpenAI standard event rather than `custom`. */\nexport function isStandardOAIEvent(name: string): boolean {\n return mapOAIEvent(name as TrackName).type !== 'custom';\n}\n"],"mappings":";;AAGA,MAAa,gBAAgB;CAE3B;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;AACF;;;;;;AAyEA,MAAa,a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G,QAAQ;IACvD;GACF;EACF;CACF;AACF;;AAGA,SAAgB,mBAAmB,MAAuB;CACxD,OAAO,YAAY,IAAiB,CAAC,CAAC,SAAS;AACjD"}
|
package/dist/track/oaiq.d.cts
CHANGED
|
@@ -140,4 +140,6 @@ export type MappedOAIEvent = {
|
|
|
140
140
|
};
|
|
141
141
|
/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */
|
|
142
142
|
export declare function mapOAIEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): MappedOAIEvent;
|
|
143
|
+
/** Whether `mapOAIEvent` turns the event into an OpenAI standard event rather than `custom`. */
|
|
144
|
+
export declare function isStandardOAIEvent(name: string): boolean;
|
|
143
145
|
//# sourceMappingURL=oaiq.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oaiq.d.cts","names":[],"sources":["../../src/track/oaiq.ts"],"mappings":";;qBAGa;;;;;YAiBD;EACV;EACA;EACA;EACA;;EAEA;EACA;;YAGU;EACV;;EAEA;EACA;EACA,WAAW;;YAGD;EACV;EACA;EACA;;YAGU;EACV;EACA;EACA;EACA;EACA,WAAW;;YAGD;EACV;EACA;EACA;EACA,WAAW;;YAGD,YAAY,eAAe,qBAAqB,qBAAqB;;;;;YAMrE;EACV,eAAe;EACf,YAAY;EACZ,uBAAuB;EACvB,kBAAkB;EAClB,iBAAiB;EACjB,aAAa;EACb,cAAc;EACd,eAAe;EACf,aAAa;EACb,wBAAwB;EACxB,sBAAsB;EACtB,eAAe;;YAGL,sBAAsB;;;;;;qBAOrB,qBAAqB;;;;;;;;;wBAyBlB,mBAAmB;;;;;;YAevB;EACV;;EAEA;EACA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;;;;;wBAOc,kBAAkB;;wBASlB,iBAAiB;YAIrB;EACV;;EAEA;EACA,OAAO;;;;;;YAOG;;EAEV;;EAEA;;EAEA;;iBAGe;EACf,KAAK,iBAAiB,QAAQ;EAC9B,KAAK,UAAU,eAC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IAChB,aAAa,gBAAgB,KAC5B;;wBA8Ca,mBAAmB"}
|
package/dist/track/oaiq.d.mts
CHANGED
|
@@ -140,4 +140,6 @@ export type MappedOAIEvent = {
|
|
|
140
140
|
};
|
|
141
141
|
/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */
|
|
142
142
|
export declare function mapOAIEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): MappedOAIEvent;
|
|
143
|
+
/** Whether `mapOAIEvent` turns the event into an OpenAI standard event rather than `custom`. */
|
|
144
|
+
export declare function isStandardOAIEvent(name: string): boolean;
|
|
143
145
|
//# sourceMappingURL=oaiq.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oaiq.d.mts","names":[],"sources":["../../src/track/oaiq.ts"],"mappings":";;qBAGa;;;;;YAiBD;EACV;EACA;EACA;EACA;;EAEA;EACA;;YAGU;EACV;;EAEA;EACA;EACA,WAAW;;YAGD;EACV;EACA;EACA;;YAGU;EACV;EACA;EACA;EACA;EACA,WAAW;;YAGD;EACV;EACA;EACA;EACA,WAAW;;YAGD,YAAY,eAAe,qBAAqB,qBAAqB;;;;;YAMrE;EACV,eAAe;EACf,YAAY;EACZ,uBAAuB;EACvB,kBAAkB;EAClB,iBAAiB;EACjB,aAAa;EACb,cAAc;EACd,eAAe;EACf,aAAa;EACb,wBAAwB;EACxB,sBAAsB;EACtB,eAAe;;YAGL,sBAAsB;;;;;;qBAOrB,qBAAqB;;;;;;;;;wBAyBlB,mBAAmB;;;;;;YAevB;EACV;;EAEA;EACA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;;;;;wBAOc,kBAAkB;;wBASlB,iBAAiB;YAIrB;EACV;;EAEA;EACA,OAAO;;;;;;YAOG;;EAEV;;EAEA;;EAEA;;iBAGe;EACf,KAAK,iBAAiB,QAAQ;EAC9B,KAAK,UAAU,eACb,oBACA,OAAO,GACP,MAAM,eAAe,IACrB,UAAU;EAEZ,KACE,oBACA,iBACA,MAAM,iBACN,SAAS;IAAmB;;;;;;;;wBAoChB,aAAa,uBAAuB;wBAapC,YAAY,QAAQ,QAAQ,oBAAoB;YAqEpD;EACV,MAAM;EACN,MAAM;;;wBAIQ,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB,KAC5B"}
|
|
1
|
+
{"version":3,"file":"oaiq.d.mts","names":[],"sources":["../../src/track/oaiq.ts"],"mappings":";;qBAGa;;;;;YAiBD;EACV;EACA;EACA;EACA;;EAEA;EACA;;YAGU;EACV;;EAEA;EACA;EACA,WAAW;;YAGD;EACV;EACA;EACA;;YAGU;EACV;EACA;EACA;EACA;EACA,WAAW;;YAGD;EACV;EACA;EACA;EACA,WAAW;;YAGD,YAAY,eAAe,qBAAqB,qBAAqB;;;;;YAMrE;EACV,eAAe;EACf,YAAY;EACZ,uBAAuB;EACvB,kBAAkB;EAClB,iBAAiB;EACjB,aAAa;EACb,cAAc;EACd,eAAe;EACf,aAAa;EACb,wBAAwB;EACxB,sBAAsB;EACtB,eAAe;;YAGL,sBAAsB;;;;;;qBAOrB,qBAAqB;;;;;;;;;wBAyBlB,mBAAmB;;;;;;YAevB;EACV;;EAEA;EACA;;EAEA;EACA;;EAEA;;EAEA;;EAEA;EACA;;;;;;wBAOc,kBAAkB;;wBASlB,iBAAiB;YAIrB;EACV;;EAEA;EACA,OAAO;;;;;;YAOG;;EAEV;;EAEA;;EAEA;;iBAGe;EACf,KAAK,iBAAiB,QAAQ;EAC9B,KAAK,UAAU,eACb,oBACA,OAAO,GACP,MAAM,eAAe,IACrB,UAAU;EAEZ,KACE,oBACA,iBACA,MAAM,iBACN,SAAS;IAAmB;;;;;;;;wBAoChB,aAAa,uBAAuB;wBAapC,YAAY,QAAQ,QAAQ,oBAAoB;YAqEpD;EACV,MAAM;EACN,MAAM;;;wBAIQ,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB,KAC5B;;wBA8Ca,mBAAmB"}
|
package/dist/track/oaiq.mjs
CHANGED
|
@@ -227,6 +227,10 @@ function mapOAIEvent(name, properties) {
|
|
|
227
227
|
}
|
|
228
228
|
}
|
|
229
229
|
}
|
|
230
|
-
|
|
230
|
+
/** Whether `mapOAIEvent` turns the event into an OpenAI standard event rather than `custom`. */
|
|
231
|
+
function isStandardOAIEvent(name) {
|
|
232
|
+
return mapOAIEvent(name).type !== "custom";
|
|
233
|
+
}
|
|
234
|
+
export { APP_EVENTS, NON_AD_EVENTS, isStandardOAIEvent, mapContents, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName, toMinorUnits };
|
|
231
235
|
|
|
232
236
|
//# sourceMappingURL=oaiq.mjs.map
|
package/dist/track/oaiq.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"oaiq.mjs","names":[],"sources":["../../src/track/oaiq.ts"],"sourcesContent":["import type { Item } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport const NON_AD_EVENTS = [\n // metrics\n 'CLS',\n 'FCP',\n 'FID',\n 'INP',\n 'LCP',\n 'TTFB',\n // promotions\n 'view_promotion',\n 'select_promotion',\n];\n\n/**\n * Content item shared by `contents` and `plan_enrollment` events.\n * https://developers.openai.com/ads/supported-events\n */\nexport type ContentItem = {\n id?: string;\n name?: string;\n content_type?: string;\n quantity?: number;\n /** Per-item monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n};\n\nexport type ContentsData = {\n type: 'contents';\n /** Monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomerActionData = {\n type: 'customer_action';\n amount?: number;\n currency?: string;\n};\n\nexport type PlanEnrollmentData = {\n type: 'plan_enrollment';\n plan_id?: string;\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomEventData = {\n type: 'custom';\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type EventData = ContentsData | CustomerActionData | PlanEnrollmentData | CustomEventData;\n\n/**\n * Standard event names and the `data` shape each one expects.\n * https://developers.openai.com/ads/supported-events\n */\nexport type StandardEvents = {\n app_installed: CustomerActionData;\n app_opened: CustomerActionData;\n appointment_scheduled: CustomerActionData;\n checkout_started: ContentsData;\n contents_viewed: ContentsData;\n items_added: ContentsData;\n lead_created: CustomerActionData;\n order_created: ContentsData;\n page_viewed: ContentsData;\n registration_completed: CustomerActionData;\n subscription_created: PlanEnrollmentData;\n trial_started: PlanEnrollmentData;\n};\n\nexport type StandardEvent = keyof StandardEvents;\n\n/**\n * The app events, which OpenAI takes \"through the Conversions API only\", with `action_source`\n * `mobile_app`: the pixel never sends them, and the server only for an app's events.\n * https://developers.openai.com/ads/supported-events\n */\nexport const APP_EVENTS: readonly StandardEvent[] = ['app_installed', 'app_opened'];\n\nconst STANDARD_EVENTS: readonly string[] = [\n 'app_installed',\n 'app_opened',\n 'appointment_scheduled',\n 'checkout_started',\n 'contents_viewed',\n 'items_added',\n 'lead_created',\n 'order_created',\n 'page_viewed',\n 'registration_completed',\n 'subscription_created',\n 'trial_started',\n] satisfies StandardEvent[];\n\n/**\n * A track name as an OpenAI `custom_event_name`: 1–64 letters, digits, underscores or hyphens,\n * starting and ending with a letter or digit, not a standard event name; the API lowercases it.\n * Anything else becomes an underscore, so `Sign Up.Clicked` is `sign_up_clicked`. Undefined when\n * nothing usable is left — the event is then not sent at all. The pixel and the server both name\n * a custom event through this, so the two still deduplicate.\n * https://developers.openai.com/ads/supported-events\n */\nexport function oaiCustomEventName(name: string): string | undefined {\n const sanitized = name\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, '_')\n .slice(0, 64)\n .replace(/^[_-]+|[_-]+$/g, '');\n if (!sanitized || STANDARD_EVENTS.includes(sanitized)) return undefined;\n return sanitized;\n}\n\n/**\n * Identity fields passed to `oaiq(\"init\", ...)` for conversion matching. Identifiers are\n * normalized, then sent as lowercase 64-char SHA-256 hex strings; geographic values are raw.\n * https://developers.openai.com/ads/measurement-pixel#send-user-data\n */\nexport type OAIQUser = {\n email_sha256?: string;\n /** 8–15 digits with the country code, no leading `+` or zeroes (`normalizeOAIPhone`). */\n phone_number_sha256?: string;\n external_id_sha256?: string;\n /** Lowercase, without whitespace or ASCII punctuation (`normalizeOAIName`). */\n first_name_sha256?: string;\n last_name_sha256?: string;\n /** Two-letter ISO 3166-1 country code (e.g. \"US\"). */\n country?: string;\n /** Max 128 characters; OpenAI trims and lowercases it. */\n city?: string;\n /** State, province or region, max 128 characters. */\n region?: string;\n postal_code?: string;\n};\n\n/**\n * A phone number as OpenAI hashes it: whitespace, parentheses, periods and hyphens removed, then\n * the leading `+` and zeroes; 8–15 digits with the country code, else not a usable number.\n */\nexport function normalizeOAIPhone(phone: string): string | undefined {\n const digits = phone\n .replace(/[\\s().-]/g, '')\n .replace(/^\\+/, '')\n .replace(/^0+/, '');\n return /^\\d{8,15}$/.test(digits) ? digits : undefined;\n}\n\n/** A name as OpenAI hashes it: lowercase, no whitespace or ASCII punctuation, accents kept. */\nexport function normalizeOAIName(name: string | undefined): string | undefined {\n return name?.toLowerCase().replace(/[\\s!-/:-@[-`{-~]/g, '') || undefined;\n}\n\nexport type InitConfig = {\n pixelId: string;\n /** Log SDK activity to the browser console. */\n debug?: boolean;\n user?: OAIQUser;\n};\n\n/**\n * Fourth argument of `oaiq(\"measure\", ...)`. Required for custom events (carries\n * `custom_event_name`); optional for standard events.\n */\nexport type MeasureOptions = {\n /** Shared with the Conversions API to deduplicate the same conversion across browser and server. */\n event_id?: string;\n /** Required for custom events; 1-64 chars of letters, numbers, underscores, or dashes. */\n custom_event_name?: string;\n /** When true, opts the event out of user-level personalization. */\n opt_out?: boolean;\n};\n\nexport interface OAIQ {\n oaiq(command: 'init', config: InitConfig): void;\n oaiq<T extends StandardEvent>(\n command: 'measure',\n event: T,\n data: StandardEvents[T],\n options?: MeasureOptions\n ): void;\n oaiq(\n command: 'measure',\n event: 'custom',\n data: CustomEventData,\n options: MeasureOptions & { custom_event_name: string }\n ): void;\n}\n\n/**\n * Currencies whose minor unit has 0 or 3 decimal places; everything else uses 2.\n * Follows Stripe's zero-decimal convention (e.g., MGA is treated as 0, ISK is included),\n * which can differ from strict ISO 4217 exponents.\n * https://docs.stripe.com/currencies#zero-decimal\n */\nconst ZERO_DECIMAL_CURRENCIES = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n]);\nconst THREE_DECIMAL_CURRENCIES = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND']);\n\n/**\n * Convert a major-unit amount (e.g., 129.99) into ISO 4217 minor units (e.g., 12,999). None\n * without a currency: the minor unit depends on it, and OpenAI requires a `currency` with every\n * `amount` — an amount alone would be invalid, not just imprecise.\n */\nexport function toMinorUnits(value?: number | null, currency?: string): number | undefined {\n if (value === undefined || value === null || Number.isNaN(value)) return undefined;\n const code = currency?.toUpperCase();\n if (!code) return undefined;\n const exponent =\n code && ZERO_DECIMAL_CURRENCIES.has(code)\n ? 0\n : code && THREE_DECIMAL_CURRENCIES.has(code)\n ? 3\n : 2;\n return Math.round(value * 10 ** exponent);\n}\n\nexport function mapContents(items?: Item[], currency?: string): ContentItem[] | undefined {\n if (!items || items.length === 0) return undefined;\n const code = currency?.toUpperCase();\n return items.map((item) => {\n const amount = toMinorUnits(item.price, currency);\n return {\n id: item.item_id,\n name: item.item_name,\n content_type: item.item_category,\n quantity: item.quantity,\n amount,\n currency: amount !== undefined ? code : undefined,\n };\n });\n}\n\n/** Safely read a property off loosely typed track properties without widening to `any`. */\nfunction prop(properties: unknown, key: string): unknown {\n return typeof properties === 'object' && properties !== null\n ? (properties as Record<string, unknown>)[key]\n : undefined;\n}\n\nfunction readValue(properties: unknown): number | undefined {\n const value = prop(properties, 'value');\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction readCurrency(properties: unknown): string | undefined {\n const currency = prop(properties, 'currency');\n return typeof currency === 'string' ? currency : undefined;\n}\n\nfunction readItems(properties: unknown): Item[] | undefined {\n const items = prop(properties, 'items');\n return Array.isArray(items) ? (items as Item[]) : undefined;\n}\n\nfunction contentsData(properties: unknown): ContentsData {\n const currency = readCurrency(properties);\n return {\n type: 'contents',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n };\n}\n\nfunction customerActionData(properties: unknown): CustomerActionData {\n const currency = readCurrency(properties);\n return {\n type: 'customer_action',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n };\n}\n\nfunction planEnrollmentData(properties: unknown): PlanEnrollmentData {\n const currency = readCurrency(properties);\n const items = readItems(properties);\n return {\n type: 'plan_enrollment',\n plan_id: items?.[0]?.item_id,\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(items, currency),\n };\n}\n\nexport type MappedOAIEvent = {\n type: StandardEvent | 'custom';\n data: EventData;\n};\n\n/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */\nexport function mapOAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): MappedOAIEvent {\n switch (name) {\n // The app's first launch, recorded once by the app hook: the closest thing to an install.\n case 'first_open':\n return { type: 'app_installed', data: customerActionData(properties) };\n case 'app_open':\n return { type: 'app_opened', data: customerActionData(properties) };\n case 'page_view':\n return { type: 'page_viewed', data: contentsData(properties) };\n case 'view_item':\n case 'view_item_list':\n return { type: 'contents_viewed', data: contentsData(properties) };\n case 'begin_checkout':\n return { type: 'checkout_started', data: contentsData(properties) };\n case 'add_to_cart':\n return { type: 'items_added', data: contentsData(properties) };\n case 'purchase':\n return { type: 'order_created', data: contentsData(properties) };\n case 'generate_lead':\n case 'qualify_lead':\n return { type: 'lead_created', data: customerActionData(properties) };\n case 'sign_up':\n case 'login':\n return { type: 'registration_completed', data: customerActionData(properties) };\n case 'schedule':\n return { type: 'appointment_scheduled', data: customerActionData(properties) };\n case 'subscribe':\n return { type: 'subscription_created', data: planEnrollmentData(properties) };\n case 'trial_begin':\n return { type: 'trial_started', data: planEnrollmentData(properties) };\n default: {\n const currency = readCurrency(properties);\n return {\n type: 'custom',\n data: {\n type: 'custom',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n },\n };\n }\n }\n}\n"],"mappings":";AAGA,MAAa,gBAAgB;CAE3B;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;AACF;;;;;;AAyEA,MAAa,aAAuC,CAAC,iBAAiB,YAAY;AAElF,MAAM,kBAAqC;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,SAAgB,mBAAmB,MAAkC;CACnE,MAAM,YAAY,KACf,YAAY,CAAC,CACb,QAAQ,iBAAiB,GAAG,CAAC,CAC7B,MAAM,GAAG,EAAE,CAAC,CACZ,QAAQ,kBAAkB,EAAE;CAC/B,IAAI,CAAC,aAAa,gBAAgB,SAAS,SAAS,GAAG,OAAO,KAAA;CAC9D,OAAO;AACT;;;;;AA4BA,SAAgB,kBAAkB,OAAmC;CACnE,MAAM,SAAS,MACZ,QAAQ,aAAa,EAAE,CAAC,CACxB,QAAQ,OAAO,EAAE,CAAC,CAClB,QAAQ,OAAO,EAAE;CACpB,OAAO,aAAa,KAAK,MAAM,IAAI,SAAS,KAAA;AAC9C;;AAGA,SAAgB,iBAAiB,MAA8C;CAC7E,OAAO,MAAM,YAAY,CAAC,CAAC,QAAQ,qBAAqB,EAAE,KAAK,KAAA;AACjE;;;;;;;AA4CA,MAAM,0CAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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AAK,SACH,OAAO;GAAE,MAAM;GAA0B,MAAM,mBAAmB,UAAU;EAAE;EAChF,KAAK,YACH,OAAO;GAAE,MAAM;GAAyB,MAAM,mBAAmB,UAAU;EAAE;EAC/E,KAAK,aACH,OAAO;GAAE,MAAM;GAAwB,MAAM,mBAAmB,UAAU;EAAE;EAC9E,KAAK,eACH,OAAO;GAAE,MAAM;GAAiB,MAAM,mBAAmB,UAAU;EAAE;EACvE,SAAS;GACP,MAAM,WAAW,aAAa,UAAU;GACxC,OAAO;IACL,MAAM;IACN,MAAM;KACJ,MAAM;KACN,QAAQ,aAAa,UAAU,UAAU,GAAG,QAAQ;KACpD,UAAU,UAAU,YAAY;KAChC,UAAU,YAAY,UAAU,UAAU,GAAG,QAAQ;IACvD;GACF;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"oaiq.mjs","names":[],"sources":["../../src/track/oaiq.ts"],"sourcesContent":["import type { Item } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport const NON_AD_EVENTS = [\n // metrics\n 'CLS',\n 'FCP',\n 'FID',\n 'INP',\n 'LCP',\n 'TTFB',\n // promotions\n 'view_promotion',\n 'select_promotion',\n];\n\n/**\n * Content item shared by `contents` and `plan_enrollment` events.\n * https://developers.openai.com/ads/supported-events\n */\nexport type ContentItem = {\n id?: string;\n name?: string;\n content_type?: string;\n quantity?: number;\n /** Per-item monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n};\n\nexport type ContentsData = {\n type: 'contents';\n /** Monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomerActionData = {\n type: 'customer_action';\n amount?: number;\n currency?: string;\n};\n\nexport type PlanEnrollmentData = {\n type: 'plan_enrollment';\n plan_id?: string;\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomEventData = {\n type: 'custom';\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type EventData = ContentsData | CustomerActionData | PlanEnrollmentData | CustomEventData;\n\n/**\n * Standard event names and the `data` shape each one expects.\n * https://developers.openai.com/ads/supported-events\n */\nexport type StandardEvents = {\n app_installed: CustomerActionData;\n app_opened: CustomerActionData;\n appointment_scheduled: CustomerActionData;\n checkout_started: ContentsData;\n contents_viewed: ContentsData;\n items_added: ContentsData;\n lead_created: CustomerActionData;\n order_created: ContentsData;\n page_viewed: ContentsData;\n registration_completed: CustomerActionData;\n subscription_created: PlanEnrollmentData;\n trial_started: PlanEnrollmentData;\n};\n\nexport type StandardEvent = keyof StandardEvents;\n\n/**\n * The app events, which OpenAI takes \"through the Conversions API only\", with `action_source`\n * `mobile_app`: the pixel never sends them, and the server only for an app's events.\n * https://developers.openai.com/ads/supported-events\n */\nexport const APP_EVENTS: readonly StandardEvent[] = ['app_installed', 'app_opened'];\n\nconst STANDARD_EVENTS: readonly string[] = [\n 'app_installed',\n 'app_opened',\n 'appointment_scheduled',\n 'checkout_started',\n 'contents_viewed',\n 'items_added',\n 'lead_created',\n 'order_created',\n 'page_viewed',\n 'registration_completed',\n 'subscription_created',\n 'trial_started',\n] satisfies StandardEvent[];\n\n/**\n * A track name as an OpenAI `custom_event_name`: 1–64 letters, digits, underscores or hyphens,\n * starting and ending with a letter or digit, not a standard event name; the API lowercases it.\n * Anything else becomes an underscore, so `Sign Up.Clicked` is `sign_up_clicked`. Undefined when\n * nothing usable is left — the event is then not sent at all. The pixel and the server both name\n * a custom event through this, so the two still deduplicate.\n * https://developers.openai.com/ads/supported-events\n */\nexport function oaiCustomEventName(name: string): string | undefined {\n const sanitized = name\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, '_')\n .slice(0, 64)\n .replace(/^[_-]+|[_-]+$/g, '');\n if (!sanitized || STANDARD_EVENTS.includes(sanitized)) return undefined;\n return sanitized;\n}\n\n/**\n * Identity fields passed to `oaiq(\"init\", ...)` for conversion matching. Identifiers are\n * normalized, then sent as lowercase 64-char SHA-256 hex strings; geographic values are raw.\n * https://developers.openai.com/ads/measurement-pixel#send-user-data\n */\nexport type OAIQUser = {\n email_sha256?: string;\n /** 8–15 digits with the country code, no leading `+` or zeroes (`normalizeOAIPhone`). */\n phone_number_sha256?: string;\n external_id_sha256?: string;\n /** Lowercase, without whitespace or ASCII punctuation (`normalizeOAIName`). */\n first_name_sha256?: string;\n last_name_sha256?: string;\n /** Two-letter ISO 3166-1 country code (e.g. \"US\"). */\n country?: string;\n /** Max 128 characters; OpenAI trims and lowercases it. */\n city?: string;\n /** State, province or region, max 128 characters. */\n region?: string;\n postal_code?: string;\n};\n\n/**\n * A phone number as OpenAI hashes it: whitespace, parentheses, periods and hyphens removed, then\n * the leading `+` and zeroes; 8–15 digits with the country code, else not a usable number.\n */\nexport function normalizeOAIPhone(phone: string): string | undefined {\n const digits = phone\n .replace(/[\\s().-]/g, '')\n .replace(/^\\+/, '')\n .replace(/^0+/, '');\n return /^\\d{8,15}$/.test(digits) ? digits : undefined;\n}\n\n/** A name as OpenAI hashes it: lowercase, no whitespace or ASCII punctuation, accents kept. */\nexport function normalizeOAIName(name: string | undefined): string | undefined {\n return name?.toLowerCase().replace(/[\\s!-/:-@[-`{-~]/g, '') || undefined;\n}\n\nexport type InitConfig = {\n pixelId: string;\n /** Log SDK activity to the browser console. */\n debug?: boolean;\n user?: OAIQUser;\n};\n\n/**\n * Fourth argument of `oaiq(\"measure\", ...)`. Required for custom events (carries\n * `custom_event_name`); optional for standard events.\n */\nexport type MeasureOptions = {\n /** Shared with the Conversions API to deduplicate the same conversion across browser and server. */\n event_id?: string;\n /** Required for custom events; 1-64 chars of letters, numbers, underscores, or dashes. */\n custom_event_name?: string;\n /** When true, opts the event out of user-level personalization. */\n opt_out?: boolean;\n};\n\nexport interface OAIQ {\n oaiq(command: 'init', config: InitConfig): void;\n oaiq<T extends StandardEvent>(\n command: 'measure',\n event: T,\n data: StandardEvents[T],\n options?: MeasureOptions\n ): void;\n oaiq(\n command: 'measure',\n event: 'custom',\n data: CustomEventData,\n options: MeasureOptions & { custom_event_name: string }\n ): void;\n}\n\n/**\n * Currencies whose minor unit has 0 or 3 decimal places; everything else uses 2.\n * Follows Stripe's zero-decimal convention (e.g., MGA is treated as 0, ISK is included),\n * which can differ from strict ISO 4217 exponents.\n * https://docs.stripe.com/currencies#zero-decimal\n */\nconst ZERO_DECIMAL_CURRENCIES = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n]);\nconst THREE_DECIMAL_CURRENCIES = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND']);\n\n/**\n * Convert a major-unit amount (e.g., 129.99) into ISO 4217 minor units (e.g., 12,999). None\n * without a currency: the minor unit depends on it, and OpenAI requires a `currency` with every\n * `amount` — an amount alone would be invalid, not just imprecise.\n */\nexport function toMinorUnits(value?: number | null, currency?: string): number | undefined {\n if (value === undefined || value === null || Number.isNaN(value)) return undefined;\n const code = currency?.toUpperCase();\n if (!code) return undefined;\n const exponent =\n code && ZERO_DECIMAL_CURRENCIES.has(code)\n ? 0\n : code && THREE_DECIMAL_CURRENCIES.has(code)\n ? 3\n : 2;\n return Math.round(value * 10 ** exponent);\n}\n\nexport function mapContents(items?: Item[], currency?: string): ContentItem[] | undefined {\n if (!items || items.length === 0) return undefined;\n const code = currency?.toUpperCase();\n return items.map((item) => {\n const amount = toMinorUnits(item.price, currency);\n return {\n id: item.item_id,\n name: item.item_name,\n content_type: item.item_category,\n quantity: item.quantity,\n amount,\n currency: amount !== undefined ? code : undefined,\n };\n });\n}\n\n/** Safely read a property off loosely typed track properties without widening to `any`. */\nfunction prop(properties: unknown, key: string): unknown {\n return typeof properties === 'object' && properties !== null\n ? (properties as Record<string, unknown>)[key]\n : undefined;\n}\n\nfunction readValue(properties: unknown): number | undefined {\n const value = prop(properties, 'value');\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction readCurrency(properties: unknown): string | undefined {\n const currency = prop(properties, 'currency');\n return typeof currency === 'string' ? currency : undefined;\n}\n\nfunction readItems(properties: unknown): Item[] | undefined {\n const items = prop(properties, 'items');\n return Array.isArray(items) ? (items as Item[]) : undefined;\n}\n\nfunction contentsData(properties: unknown): ContentsData {\n const currency = readCurrency(properties);\n return {\n type: 'contents',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n };\n}\n\nfunction customerActionData(properties: unknown): CustomerActionData {\n const currency = readCurrency(properties);\n return {\n type: 'customer_action',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n };\n}\n\nfunction planEnrollmentData(properties: unknown): PlanEnrollmentData {\n const currency = readCurrency(properties);\n const items = readItems(properties);\n return {\n type: 'plan_enrollment',\n plan_id: items?.[0]?.item_id,\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(items, currency),\n };\n}\n\nexport type MappedOAIEvent = {\n type: StandardEvent | 'custom';\n data: EventData;\n};\n\n/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */\nexport function mapOAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): MappedOAIEvent {\n switch (name) {\n // The app's first launch, recorded once by the app hook: the closest thing to an install.\n case 'first_open':\n return { type: 'app_installed', data: customerActionData(properties) };\n case 'app_open':\n return { type: 'app_opened', data: customerActionData(properties) };\n case 'page_view':\n return { type: 'page_viewed', data: contentsData(properties) };\n case 'view_item':\n case 'view_item_list':\n return { type: 'contents_viewed', data: contentsData(properties) };\n case 'begin_checkout':\n return { type: 'checkout_started', data: contentsData(properties) };\n case 'add_to_cart':\n return { type: 'items_added', data: contentsData(properties) };\n case 'purchase':\n return { type: 'order_created', data: contentsData(properties) };\n case 'generate_lead':\n case 'qualify_lead':\n return { type: 'lead_created', data: customerActionData(properties) };\n case 'sign_up':\n case 'login':\n return { type: 'registration_completed', data: customerActionData(properties) };\n case 'schedule':\n return { type: 'appointment_scheduled', data: customerActionData(properties) };\n case 'subscribe':\n return { type: 'subscription_created', data: planEnrollmentData(properties) };\n case 'trial_begin':\n return { type: 'trial_started', data: planEnrollmentData(properties) };\n default: {\n const currency = readCurrency(properties);\n return {\n type: 'custom',\n data: {\n type: 'custom',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n },\n };\n }\n }\n}\n\n/** Whether `mapOAIEvent` turns the event into an OpenAI standard event rather than `custom`. */\nexport function isStandardOAIEvent(name: string): boolean {\n return mapOAIEvent(name as TrackName).type !== 'custom';\n}\n"],"mappings":";AAGA,MAAa,gBAAgB;CAE3B;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;AACF;;;;;;AAyEA,MAAa,aAAuC,CAAC,iBAAiB,YAAY;AAElF,MAAM,kBAAqC;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;AAUA,SAAgB,mBAAmB,MAAkC;CACnE,MAAM,YAAY,KACf,YAAY,CAAC,CACb,QAAQ,iBAAiB,GAAG,CAAC,CAC7B,MAAM,GAAG,EAAE,CAAC,CACZ,QAAQ,kBAAkB,EAAE;CAC/B,IAAI,CAAC,aAAa,gBAAgB,SAAS,SAAS,GAAG,OAAO,KAAA;CAC9D,OAAO;AACT;;;;;AA4BA,SAAgB,kBAAkB,OAAmC;CACnE,MAAM,SAAS,MACZ,QAAQ,aAAa,EAAE,CAAC,CACxB,QAAQ,OAAO,EAAE,CAAC,CAClB,QAAQ,OAAO,EAAE;CACpB,OAAO,aAAa,KAAK,MAAM,IAAI,SAAS,KAAA;AAC9C;;AAGA,SAAgB,iBAAiB,MAA8C;CAC7E,OAAO,MAAM,YAAY,CAAC,CAAC,QAAQ,qBAAq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AAE,MAAM;GAAiB,MAAM,aAAa,UAAU;EAAE;EACjE,KAAK;EACL,KAAK,gBACH,OAAO;GAAE,MAAM;GAAgB,MAAM,mBAAmB,UAAU;EAAE;EACtE,KAAK;EACL,KAAK,SACH,OAAO;GAAE,MAAM;GAA0B,MAAM,mBAAmB,UAAU;EAAE;EAChF,KAAK,YACH,OAAO;GAAE,MAAM;GAAyB,MAAM,mBAAmB,UAAU;EAAE;EAC/E,KAAK,aACH,OAAO;GAAE,MAAM;GAAwB,MAAM,mBAAmB,UAAU;EAAE;EAC9E,KAAK,eACH,OAAO;GAAE,MAAM;GAAiB,MAAM,mBAAmB,UAAU;EAAE;EACvE,SAAS;GACP,MAAM,WAAW,aAAa,UAAU;GACxC,OAAO;IACL,MAAM;IACN,MAAM;KACJ,MAAM;KACN,QAAQ,aAAa,UAAU,UAAU,GAAG,QAAQ;KACpD,UAAU,UAAU,YAAY;KAChC,UAAU,YAAY,UAAU,UAAU,GAAG,QAAQ;IACvD;GACF;EACF;CACF;AACF;;AAGA,SAAgB,mBAAmB,MAAuB;CACxD,OAAO,YAAY,IAAiB,CAAC,CAAC,SAAS;AACjD"}
|
package/dist/track/rdt.cjs
CHANGED
|
@@ -65,6 +65,11 @@ function mapServerStandardEvent(name) {
|
|
|
65
65
|
if (name === "Lead") return "LEAD";
|
|
66
66
|
return "SIGN_UP";
|
|
67
67
|
}
|
|
68
|
+
/** Whether `mapRDTEvent` turns the event into a Reddit standard event rather than `Custom`. */
|
|
69
|
+
function isStandardRDTEvent(name) {
|
|
70
|
+
return mapRDTEvent(name)[0] !== "Custom";
|
|
71
|
+
}
|
|
72
|
+
exports.isStandardRDTEvent = isStandardRDTEvent;
|
|
68
73
|
exports.mapItems = mapItems;
|
|
69
74
|
exports.mapRDTEvent = mapRDTEvent;
|
|
70
75
|
exports.mapServerStandardEvent = mapServerStandardEvent;
|
package/dist/track/rdt.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdt.cjs","names":["itemKey"],"sources":["../../src/track/rdt.ts"],"sourcesContent":["import { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\n/** https://business.reddithelp.com/s/article/about-event-metadata */\nexport type Product = {\n /**\n * (Required) Product ID: Either the SKU or GTIN, which represents the variant ID, not the\n * parent ID. If there are no variants, pass the assigned ID for that item.\n */\n id: string;\n\n /** (Optional) Product Category: The group the product belongs to. */\n name?: string;\n\n /** (Optional) Product Name: The title of the product. */\n category?: string;\n};\n\n/**\n * https://business.reddithelp.com/s/article/supported-conversion-events#supported-conversion-events\n * https://business.reddithelp.com/s/article/about-event-metadata\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport type StandardEvents = {\n PageVisit: {\n conversionId?: string;\n products?: Product[];\n };\n ViewContent: {\n conversionId?: string;\n products?: Product[];\n };\n Search: {\n conversionId?: string;\n products?: Product[];\n };\n AddToCart: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n AddToWishlist: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Purchase: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Lead: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n SignUp: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n};\n\nexport type PixelId = `a2_${string}`;\n\nexport type MatchKeys = {\n email?: string;\n phoneNumber?: string;\n externalId?: string;\n idfa?: string;\n aaid?: string;\n};\n\nexport type CustomEventParams<T extends string = string> = {\n customEventName: T;\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n};\n\nexport interface RDT {\n rdt(event: 'init', pixelId: PixelId, matchKeys?: MatchKeys): void;\n\n rdt<T extends keyof StandardEvents>(event: 'track', type: T, params?: StandardEvents[T]): void;\n\n rdt(event: 'track', type: 'Custom', params: CustomEventParams): void;\n}\n\ntype Mapped<F extends keyof StandardEvents> = [F, StandardEvents[F]];\ntype Missed<F extends string> = ['Custom', CustomEventParams<F>];\n\nexport function mapItems(items?: Item[]): undefined | Product[] {\n if (!items || items.length === 0) return undefined;\n return items.map((item) => ({\n id: itemKey(item),\n name: item.item_name,\n category: item.item_category,\n }));\n}\n\nexport function mapRDTEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n // standard events\n if (name === 'page_view') {\n return ['PageVisit', { conversionId: eventId }];\n } else if (name === 'view_item') {\n return ['ViewContent', { conversionId: eventId }];\n } else if (name === 'search') {\n return ['Search', { conversionId: eventId }];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'AddToCart',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'AddToWishlist',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'Purchase',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items?.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return [\n 'Lead',\n { conversionId: eventId, value: p?.value, currency: p?.currency.toUpperCase() },\n ];\n } else if (name === 'sign_up' || name === 'login') {\n return ['SignUp', { conversionId: eventId }];\n } else {\n // custom event\n return [\n 'Custom',\n {\n customEventName: name,\n conversionId: eventId,\n value:\n properties && 'value' in properties && typeof properties.value === 'number'\n ? properties.value\n : undefined,\n currency:\n properties && 'currency' in properties && typeof properties.currency === 'string'\n ? properties.currency.toUpperCase()\n : undefined,\n },\n ];\n }\n}\n\nexport type ServerStandardEvent =\n | 'PAGE_VISIT'\n | 'VIEW_CONTENT'\n | 'SEARCH'\n | 'ADD_TO_CART'\n | 'ADD_TO_WISHLIST'\n | 'PURCHASE'\n | 'LEAD'\n | 'SIGN_UP';\n\nexport function mapServerStandardEvent(name: keyof StandardEvents): ServerStandardEvent {\n if (name === 'PageVisit') return 'PAGE_VISIT';\n if (name === 'ViewContent') return 'VIEW_CONTENT';\n if (name === 'Search') return 'SEARCH';\n if (name === 'AddToCart') return 'ADD_TO_CART';\n if (name === 'AddToWishlist') return 'ADD_TO_WISHLIST';\n if (name === 'Purchase') return 'PURCHASE';\n if (name === 'Lead') return 'LEAD';\n // `name` is narrowed to 'SignUp' here, so the mapping is exhaustive\n return 'SIGN_UP';\n}\n"],"mappings":";;;AAqGA,SAAgB,SAAS,OAAuC;CAC9D,IAAI,CAAC,SAAS,MAAM,WAAW,GAAG,OAAO,KAAA;CACzC,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAIA,mBAAAA,QAAQ,IAAI;EAChB,MAAM,KAAK;EACX,UAAU,KAAK;CACjB,EAAE;AACJ;AAEA,SAAgB,YACd,MACA,YACA,SACqD;CAErD,IAAI,SAAS,aACX,OAAO,CAAC,aAAa,EAAE,cAAc,QAAQ,CAAC;MACzC,IAAI,SAAS,aAClB,OAAO,CAAC,eAAe,EAAE,cAAc,QAAQ,CAAC;MAC3C,IAAI,SAAS,UAClB,OAAO,CAAC,UAAU,EAAE,cAAc,QAAQ,CAAC;MACtC,IAAI,SAAS,eAAe;EACjC,MAAM,IAAI;EACV,OAAO,CACL,aACA;GACE,cAAc;GACd,OAAO,GAAG;GACV,UAAU,GAAG,SAAS,YAAY;GAClC,WA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S,YAAY,OAAO;CAChC,IAAI,SAAS,QAAQ,OAAO;CAE5B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"rdt.cjs","names":["itemKey"],"sources":["../../src/track/rdt.ts"],"sourcesContent":["import { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\n/** https://business.reddithelp.com/s/article/about-event-metadata */\nexport type Product = {\n /**\n * (Required) Product ID: Either the SKU or GTIN, which represents the variant ID, not the\n * parent ID. If there are no variants, pass the assigned ID for that item.\n */\n id: string;\n\n /** (Optional) Product Category: The group the product belongs to. */\n name?: string;\n\n /** (Optional) Product Name: The title of the product. */\n category?: string;\n};\n\n/**\n * https://business.reddithelp.com/s/article/supported-conversion-events#supported-conversion-events\n * https://business.reddithelp.com/s/article/about-event-metadata\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport type StandardEvents = {\n PageVisit: {\n conversionId?: string;\n products?: Product[];\n };\n ViewContent: {\n conversionId?: string;\n products?: Product[];\n };\n Search: {\n conversionId?: string;\n products?: Product[];\n };\n AddToCart: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n AddToWishlist: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Purchase: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Lead: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n SignUp: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n};\n\nexport type PixelId = `a2_${string}`;\n\nexport type MatchKeys = {\n email?: string;\n phoneNumber?: string;\n externalId?: string;\n idfa?: string;\n aaid?: string;\n};\n\nexport type CustomEventParams<T extends string = string> = {\n customEventName: T;\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n};\n\nexport interface RDT {\n rdt(event: 'init', pixelId: PixelId, matchKeys?: MatchKeys): void;\n\n rdt<T extends keyof StandardEvents>(event: 'track', type: T, params?: StandardEvents[T]): void;\n\n rdt(event: 'track', type: 'Custom', params: CustomEventParams): void;\n}\n\ntype Mapped<F extends keyof StandardEvents> = [F, StandardEvents[F]];\ntype Missed<F extends string> = ['Custom', CustomEventParams<F>];\n\nexport function mapItems(items?: Item[]): undefined | Product[] {\n if (!items || items.length === 0) return undefined;\n return items.map((item) => ({\n id: itemKey(item),\n name: item.item_name,\n category: item.item_category,\n }));\n}\n\nexport function mapRDTEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n // standard events\n if (name === 'page_view') {\n return ['PageVisit', { conversionId: eventId }];\n } else if (name === 'view_item') {\n return ['ViewContent', { conversionId: eventId }];\n } else if (name === 'search') {\n return ['Search', { conversionId: eventId }];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'AddToCart',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'AddToWishlist',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'Purchase',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items?.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return [\n 'Lead',\n { conversionId: eventId, value: p?.value, currency: p?.currency.toUpperCase() },\n ];\n } else if (name === 'sign_up' || name === 'login') {\n return ['SignUp', { conversionId: eventId }];\n } else {\n // custom event\n return [\n 'Custom',\n {\n customEventName: name,\n conversionId: eventId,\n value:\n properties && 'value' in properties && typeof properties.value === 'number'\n ? properties.value\n : undefined,\n currency:\n properties && 'currency' in properties && typeof properties.currency === 'string'\n ? properties.currency.toUpperCase()\n : undefined,\n },\n ];\n }\n}\n\nexport type ServerStandardEvent =\n | 'PAGE_VISIT'\n | 'VIEW_CONTENT'\n | 'SEARCH'\n | 'ADD_TO_CART'\n | 'ADD_TO_WISHLIST'\n | 'PURCHASE'\n | 'LEAD'\n | 'SIGN_UP';\n\nexport function mapServerStandardEvent(name: keyof StandardEvents): ServerStandardEvent {\n if (name === 'PageVisit') return 'PAGE_VISIT';\n if (name === 'ViewContent') return 'VIEW_CONTENT';\n if (name === 'Search') return 'SEARCH';\n if (name === 'AddToCart') return 'ADD_TO_CART';\n if (name === 'AddToWishlist') return 'ADD_TO_WISHLIST';\n if (name === 'Purchase') return 'PURCHASE';\n if (name === 'Lead') return 'LEAD';\n // `name` is narrowed to 'SignUp' here, so the mapping is exhaustive\n return 'SIGN_UP';\n}\n\n/** Whether `mapRDTEvent` turns the event into a Reddit standard event rather than `Custom`. */\nexport function isStandardRDTEvent(name: string): boolean {\n return mapRDTEvent(name as TrackName)[0] !== 'Custom';\n}\n"],"mappings":";;;AAqGA,SAAgB,SAAS,OAAuC;CAC9D,IAAI,CAAC,SAAS,MAAM,WAAW,GAAG,OAAO,KAAA;CACzC,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAIA,mBAAAA,QAAQ,IAAI;EAChB,MAAM,KAAK;EACX,UAAU,KAAK;CACjB,EAAE;AACJ;AAEA,SAAgB,YACd,MACA,YACA,SACqD;CAErD,IAAI,SAAS,aACX,OAAO,CAAC,aAAa,EAAE,cAAc,QAAQ,CAAC;MACzC,IAAI,SAAS,aAClB,OAAO,CAAC,eAAe,EAAE,cAA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,CACF;AAEJ;AAYA,SAAgB,uBAAuB,MAAiD;CACtF,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,SAAS,eAAe,OAAO;CACnC,IAAI,SAAS,UAAU,OAAO;CAC9B,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,SAAS,iBAAiB,OAAO;CACrC,IAAI,SAAS,YAAY,OAAO;CAChC,IAAI,SAAS,QAAQ,OAAO;CAE5B,OAAO;AACT;;AAGA,SAAgB,mBAAmB,MAAuB;CACxD,OAAO,YAAY,IAAiB,CAAC,CAAC,OAAO;AAC/C"}
|
package/dist/track/rdt.d.cts
CHANGED
|
@@ -91,5 +91,7 @@ export declare function mapItems(items?: Item[]): undefined | Product[];
|
|
|
91
91
|
export declare function mapRDTEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>, eventId?: string): Mapped<keyof StandardEvents> | Missed<TrackName<T>>;
|
|
92
92
|
export type ServerStandardEvent = 'PAGE_VISIT' | 'VIEW_CONTENT' | 'SEARCH' | 'ADD_TO_CART' | 'ADD_TO_WISHLIST' | 'PURCHASE' | 'LEAD' | 'SIGN_UP';
|
|
93
93
|
export declare function mapServerStandardEvent(name: keyof StandardEvents): ServerStandardEvent;
|
|
94
|
+
/** Whether `mapRDTEvent` turns the event into a Reddit standard event rather than `Custom`. */
|
|
95
|
+
export declare function isStandardRDTEvent(name: string): boolean;
|
|
94
96
|
export {};
|
|
95
97
|
//# sourceMappingURL=rdt.d.cts.map
|
package/dist/track/rdt.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdt.d.cts","names":[],"sources":["../../src/track/rdt.ts"],"mappings":";;;YAIY;;;;;EAKV;;EAGA;;EAGA;;;;;;;YAQU;EACV;IACE;IACA,WAAW;;EAEb;IACE;IACA,WAAW;;EAEb;IACE;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA,WAAW;;;YAIH;YAEA;EACV;EACA;EACA;EACA;EACA;;YAGU,kBAAkB;EAC5B,iBAAiB;EACjB;EACA;EACA;EACA;EACA,WAAW;;iBAGI;EACf,IAAI,eAAe,SAAS,SAAS,YAAY;EAEjD,IAAI,gBAAgB,gBAAgB,gBAAgB,MAAM,GAAG,SAAS,eAAe;EAErF,IAAI,gBAAgB,gBAAgB,QAAQ;;KAGzC,OAAO,gBAAgB,mBAAmB,GAAG,eAAe;KAC5D,OAAO,+BAA+B,kBAAkB;wBAE7C,SAAS,QAAQ,qBAAqB;wBAStC,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,mBACC,aAAa,kBAAkB,OAAO,UAAU;YAwEvC;wBAUI,uBAAuB,YAAY,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"rdt.d.cts","names":[],"sources":["../../src/track/rdt.ts"],"mappings":";;;YAIY;;;;;EAKV;;EAGA;;EAGA;;;;;;;YAQU;EACV;IACE;IACA,WAAW;;EAEb;IACE;IACA,WAAW;;EAEb;IACE;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA,WAAW;;;YAIH;YAEA;EACV;EACA;EACA;EACA;EACA;;YAGU,kBAAkB;EAC5B,iBAAiB;EACjB;EACA;EACA;EACA;EACA,WAAW;;iBAGI;EACf,IAAI,eAAe,SAAS,SAAS,YAAY;EAEjD,IAAI,gBAAgB,gBAAgB,gBAAgB,MAAM,GAAG,SAAS,eAAe;EAErF,IAAI,gBAAgB,gBAAgB,QAAQ;;KAGzC,OAAO,gBAAgB,mBAAmB,GAAG,eAAe;KAC5D,OAAO,+BAA+B,kBAAkB;wBAE7C,SAAS,QAAQ,qBAAqB;wBAStC,YAAY,UAAU,WACpC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,mBACC,aAAa,kBAAkB,OAAO,UAAU;YAwEvC;wBAUI,uBAAuB,YAAY,iBAAiB;;wBAapD,mBAAmB"}
|
package/dist/track/rdt.d.mts
CHANGED
|
@@ -91,5 +91,7 @@ export declare function mapItems(items?: Item[]): undefined | Product[];
|
|
|
91
91
|
export declare function mapRDTEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>, eventId?: string): Mapped<keyof StandardEvents> | Missed<TrackName<T>>;
|
|
92
92
|
export type ServerStandardEvent = 'PAGE_VISIT' | 'VIEW_CONTENT' | 'SEARCH' | 'ADD_TO_CART' | 'ADD_TO_WISHLIST' | 'PURCHASE' | 'LEAD' | 'SIGN_UP';
|
|
93
93
|
export declare function mapServerStandardEvent(name: keyof StandardEvents): ServerStandardEvent;
|
|
94
|
+
/** Whether `mapRDTEvent` turns the event into a Reddit standard event rather than `Custom`. */
|
|
95
|
+
export declare function isStandardRDTEvent(name: string): boolean;
|
|
94
96
|
export {};
|
|
95
97
|
//# sourceMappingURL=rdt.d.mts.map
|
package/dist/track/rdt.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdt.d.mts","names":[],"sources":["../../src/track/rdt.ts"],"mappings":";;;YAIY;;;;;EAKV;;EAGA;;EAGA;;;;;;;YAQU;EACV;IACE;IACA,WAAW;;EAEb;IACE;IACA,WAAW;;EAEb;IACE;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA,WAAW;;EAEb;IACE;IACA;IACA;IACA,WAAW;;;YAIH;YAEA;EACV;EACA;EACA;EACA;EACA;;YAGU,kBAAkB;EAC5B,iBAAiB;EACj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BAAuB,YAAY,iBAAiB;;wBAapD,mBAAmB"}
|
package/dist/track/rdt.mjs
CHANGED
|
@@ -64,6 +64,10 @@ function mapServerStandardEvent(name) {
|
|
|
64
64
|
if (name === "Lead") return "LEAD";
|
|
65
65
|
return "SIGN_UP";
|
|
66
66
|
}
|
|
67
|
-
|
|
67
|
+
/** Whether `mapRDTEvent` turns the event into a Reddit standard event rather than `Custom`. */
|
|
68
|
+
function isStandardRDTEvent(name) {
|
|
69
|
+
return mapRDTEvent(name)[0] !== "Custom";
|
|
70
|
+
}
|
|
71
|
+
export { isStandardRDTEvent, mapItems, mapRDTEvent, mapServerStandardEvent };
|
|
68
72
|
|
|
69
73
|
//# sourceMappingURL=rdt.mjs.map
|
package/dist/track/rdt.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdt.mjs","names":[],"sources":["../../src/track/rdt.ts"],"sourcesContent":["import { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\n/** https://business.reddithelp.com/s/article/about-event-metadata */\nexport type Product = {\n /**\n * (Required) Product ID: Either the SKU or GTIN, which represents the variant ID, not the\n * parent ID. If there are no variants, pass the assigned ID for that item.\n */\n id: string;\n\n /** (Optional) Product Category: The group the product belongs to. */\n name?: string;\n\n /** (Optional) Product Name: The title of the product. */\n category?: string;\n};\n\n/**\n * https://business.reddithelp.com/s/article/supported-conversion-events#supported-conversion-events\n * https://business.reddithelp.com/s/article/about-event-metadata\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport type StandardEvents = {\n PageVisit: {\n conversionId?: string;\n products?: Product[];\n };\n ViewContent: {\n conversionId?: string;\n products?: Product[];\n };\n Search: {\n conversionId?: string;\n products?: Product[];\n };\n AddToCart: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n AddToWishlist: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Purchase: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Lead: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n SignUp: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n};\n\nexport type PixelId = `a2_${string}`;\n\nexport type MatchKeys = {\n email?: string;\n phoneNumber?: string;\n externalId?: string;\n idfa?: string;\n aaid?: string;\n};\n\nexport type CustomEventParams<T extends string = string> = {\n customEventName: T;\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n};\n\nexport interface RDT {\n rdt(event: 'init', pixelId: PixelId, matchKeys?: MatchKeys): void;\n\n rdt<T extends keyof StandardEvents>(event: 'track', type: T, params?: StandardEvents[T]): void;\n\n rdt(event: 'track', type: 'Custom', params: CustomEventParams): void;\n}\n\ntype Mapped<F extends keyof StandardEvents> = [F, StandardEvents[F]];\ntype Missed<F extends string> = ['Custom', CustomEventParams<F>];\n\nexport function mapItems(items?: Item[]): undefined | Product[] {\n if (!items || items.length === 0) return undefined;\n return items.map((item) => ({\n id: itemKey(item),\n name: item.item_name,\n category: item.item_category,\n }));\n}\n\nexport function mapRDTEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n // standard events\n if (name === 'page_view') {\n return ['PageVisit', { conversionId: eventId }];\n } else if (name === 'view_item') {\n return ['ViewContent', { conversionId: eventId }];\n } else if (name === 'search') {\n return ['Search', { conversionId: eventId }];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'AddToCart',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'AddToWishlist',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'Purchase',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items?.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return [\n 'Lead',\n { conversionId: eventId, value: p?.value, currency: p?.currency.toUpperCase() },\n ];\n } else if (name === 'sign_up' || name === 'login') {\n return ['SignUp', { conversionId: eventId }];\n } else {\n // custom event\n return [\n 'Custom',\n {\n customEventName: name,\n conversionId: eventId,\n value:\n properties && 'value' in properties && typeof properties.value === 'number'\n ? properties.value\n : undefined,\n currency:\n properties && 'currency' in properties && typeof properties.currency === 'string'\n ? properties.currency.toUpperCase()\n : undefined,\n },\n ];\n }\n}\n\nexport type ServerStandardEvent =\n | 'PAGE_VISIT'\n | 'VIEW_CONTENT'\n | 'SEARCH'\n | 'ADD_TO_CART'\n | 'ADD_TO_WISHLIST'\n | 'PURCHASE'\n | 'LEAD'\n | 'SIGN_UP';\n\nexport function mapServerStandardEvent(name: keyof StandardEvents): ServerStandardEvent {\n if (name === 'PageVisit') return 'PAGE_VISIT';\n if (name === 'ViewContent') return 'VIEW_CONTENT';\n if (name === 'Search') return 'SEARCH';\n if (name === 'AddToCart') return 'ADD_TO_CART';\n if (name === 'AddToWishlist') return 'ADD_TO_WISHLIST';\n if (name === 'Purchase') return 'PURCHASE';\n if (name === 'Lead') return 'LEAD';\n // `name` is narrowed to 'SignUp' here, so the mapping is exhaustive\n return 'SIGN_UP';\n}\n"],"mappings":";;AAqGA,SAAgB,SAAS,OAAuC;CAC9D,IAAI,CAAC,S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E,CAChF;CACF,OAAO,IAAI,SAAS,aAAa,SAAS,SACxC,OAAO,CAAC,UAAU,EAAE,cAAc,QAAQ,CAAC;MAG3C,OAAO,CACL,UACA;EACE,iBAAiB;EACjB,cAAc;EACd,OACE,cAAc,WAAW,cAAc,OAAO,WAAW,UAAU,WAC/D,WAAW,QACX,KAAA;EACN,UACE,cAAc,cAAc,cAAc,OAAO,WAAW,aAAa,WACrE,WAAW,SAAS,YAAY,IAChC,KAAA;CACR,CACF;AAEJ;AAYA,SAAgB,uBAAuB,MAAiD;CACtF,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,SAAS,eAAe,OAAO;CACnC,IAAI,SAAS,UAAU,OAAO;CAC9B,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,SAAS,iBAAiB,OAAO;CACrC,IAAI,SAAS,YAAY,OAAO;CAChC,IAAI,SAAS,QAAQ,OAAO;CAE5B,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"rdt.mjs","names":[],"sources":["../../src/track/rdt.ts"],"sourcesContent":["import { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\n/** https://business.reddithelp.com/s/article/about-event-metadata */\nexport type Product = {\n /**\n * (Required) Product ID: Either the SKU or GTIN, which represents the variant ID, not the\n * parent ID. If there are no variants, pass the assigned ID for that item.\n */\n id: string;\n\n /** (Optional) Product Category: The group the product belongs to. */\n name?: string;\n\n /** (Optional) Product Name: The title of the product. */\n category?: string;\n};\n\n/**\n * https://business.reddithelp.com/s/article/supported-conversion-events#supported-conversion-events\n * https://business.reddithelp.com/s/article/about-event-metadata\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport type StandardEvents = {\n PageVisit: {\n conversionId?: string;\n products?: Product[];\n };\n ViewContent: {\n conversionId?: string;\n products?: Product[];\n };\n Search: {\n conversionId?: string;\n products?: Product[];\n };\n AddToCart: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n AddToWishlist: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Purchase: {\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n };\n Lead: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n SignUp: {\n value?: number;\n currency?: string;\n conversionId?: string;\n products?: Product[];\n };\n};\n\nexport type PixelId = `a2_${string}`;\n\nexport type MatchKeys = {\n email?: string;\n phoneNumber?: string;\n externalId?: string;\n idfa?: string;\n aaid?: string;\n};\n\nexport type CustomEventParams<T extends string = string> = {\n customEventName: T;\n value?: number;\n currency?: string;\n itemCount?: number;\n conversionId?: string;\n products?: Product[];\n};\n\nexport interface RDT {\n rdt(event: 'init', pixelId: PixelId, matchKeys?: MatchKeys): void;\n\n rdt<T extends keyof StandardEvents>(event: 'track', type: T, params?: StandardEvents[T]): void;\n\n rdt(event: 'track', type: 'Custom', params: CustomEventParams): void;\n}\n\ntype Mapped<F extends keyof StandardEvents> = [F, StandardEvents[F]];\ntype Missed<F extends string> = ['Custom', CustomEventParams<F>];\n\nexport function mapItems(items?: Item[]): undefined | Product[] {\n if (!items || items.length === 0) return undefined;\n return items.map((item) => ({\n id: itemKey(item),\n name: item.item_name,\n category: item.item_category,\n }));\n}\n\nexport function mapRDTEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n // standard events\n if (name === 'page_view') {\n return ['PageVisit', { conversionId: eventId }];\n } else if (name === 'view_item') {\n return ['ViewContent', { conversionId: eventId }];\n } else if (name === 'search') {\n return ['Search', { conversionId: eventId }];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'AddToCart',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'AddToWishlist',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'Purchase',\n {\n conversionId: eventId,\n value: p?.value,\n currency: p?.currency.toUpperCase(),\n itemCount: p?.items?.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n products: mapItems(p?.items),\n },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return [\n 'Lead',\n { conversionId: eventId, value: p?.value, currency: p?.currency.toUpperCase() },\n ];\n } else if (name === 'sign_up' || name === 'login') {\n return ['SignUp', { conversionId: eventId }];\n } else {\n // custom event\n return [\n 'Custom',\n {\n customEventName: name,\n conversionId: eventId,\n value:\n properties && 'value' in properties && typeof properties.value === 'number'\n ? properties.value\n : undefined,\n currency:\n properties && 'currency' in properties && typeof properties.currency === 'string'\n ? properties.currency.toUpperCase()\n : undefined,\n },\n ];\n }\n}\n\nexport type ServerStandardEvent =\n | 'PAGE_VISIT'\n | 'VIEW_CONTENT'\n | 'SEARCH'\n | 'ADD_TO_CART'\n | 'ADD_TO_WISHLIST'\n | 'PURCHASE'\n | 'LEAD'\n | 'SIGN_UP';\n\nexport function mapServerStandardEvent(name: keyof StandardEvents): ServerStandardEvent {\n if (name === 'PageVisit') return 'PAGE_VISIT';\n if (name === 'ViewContent') return 'VIEW_CONTENT';\n if (name === 'Search') return 'SEARCH';\n if (name === 'AddToCart') return 'ADD_TO_CART';\n if (name === 'AddToWishlist') return 'ADD_TO_WISHLIST';\n if (name === 'Purchase') return 'PURCHASE';\n if (name === 'Lead') return 'LEAD';\n // `name` is narrowed to 'SignUp' here, so the mapping is exhaustive\n return 'SIGN_UP';\n}\n\n/** Whether `mapRDTEvent` turns the event into a Reddit standard event rather than `Custom`. */\nexport function isStandardRDTEvent(name: string): boolean {\n return mapRDTEvent(name as TrackName)[0] !== 'Custom';\n}\n"],"mappings":";;AAqGA,SAAgB,SAAS,OAAuC;CAC9D,IAAI,CAAC,SAAS,MAAM,WAAW,GAAG,OAAO,KAAA;CACzC,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAI,QAAQ,IAAI;EAChB,MAAM,KAAK;EACX,UAAU,KAAK;CACjB,EAAE;AACJ;AAEA,SAAgB,YACd,MACA,YACA,SACqD;CAErD,IAAI,SAAS,aACX,OAAO,CAAC,aAAa,EAAE,cAAc,QAAQ,CAAC;MACzC,IAAI,SAAS,aAClB,OAAO,CAAC,eAAe,EAAE,cAAc,QAAQ,CAAC;MAC3C,IAAI,SAAS,UAClB,OAAO,CAAC,UAAU,EAAE,cAAc,QAAQ,CAAC;MACtC,IAAI,SAAS,eAAe;EACjC,MAAM,IAAI;EACV,OAAO,CACL,aACA;GACE,cAAc;GACd,OAAO,GAAG;GACV,UAAU,GAAG,SAAS,YAAY;GAClC,WAAW,GAAG,MAAM,QAAQ,KAAK,MAAM,OAAO,EAAE,YAAY,IAAI,CAAC;GACjE,UAAU,SAAS,GAAG,KAAK;EAC7B,CACF;CACF,OAAO,IAAI,SAAS,mBAAmB;EACrC,MAAM,IAAI;EACV,OAAO,CACL,iBACA;GACE,cAAc;GACd,OAAO,GAAG;GACV,UAAU,GAAG,SAAS,YAAY;GAClC,WAAW,GAAG,MAAM,QAAQ,KAAK,MAAM,OAAO,EAAE,YAAY,IAAI,CAAC;GACjE,UAAU,SAAS,GAAG,KAAK;EAC7B,CACF;CACF,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,IAAI;EACV,OAAO,CACL,YACA;GACE,cAAc;GACd,OAAO,GAAG;GACV,UAAU,GAAG,SAAS,YAAY;GAClC,WAAW,GAAG,OAAO,QAAQ,KAAK,MAAM,OAAO,EAAE,YAAY,IAAI,CAAC;GAClE,UAAU,SAAS,GAAG,KAAK;EAC7B,CACF;CACF,OAAO,IAAI,SAAS,iBAAiB;EACnC,MAAM,IAAI;EACV,OAAO,CACL,QACA;GAAE,cAAc;GAAS,OAAO,GAAG;GAAO,UAAU,GAAG,SAAS,YAAY;EAAE,CAChF;CACF,OAAO,IAAI,SAAS,aAAa,SAAS,SACxC,OAAO,CAAC,UAAU,EAAE,cAAc,QAAQ,CAAC;MAG3C,OAAO,CACL,UACA;EACE,iBAAiB;EACjB,cAAc;EACd,OACE,cAAc,WAAW,cAAc,OAAO,WAAW,UAAU,WAC/D,WAAW,QACX,KAAA;EACN,UACE,cAAc,cAAc,cAAc,OAAO,WAAW,aAAa,WACrE,WAAW,SAAS,YAAY,IAChC,KAAA;CACR,CACF;AAEJ;AAYA,SAAgB,uBAAuB,MAAiD;CACtF,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,SAAS,eAAe,OAAO;CACnC,IAAI,SAAS,UAAU,OAAO;CAC9B,IAAI,SAAS,aAAa,OAAO;CACjC,IAAI,SAAS,iBAAiB,OAAO;CACrC,IAAI,SAAS,YAAY,OAAO;CAChC,IAAI,SAAS,QAAQ,OAAO;CAE5B,OAAO;AACT;;AAGA,SAAgB,mBAAmB,MAAuB;CACxD,OAAO,YAAY,IAAiB,CAAC,CAAC,OAAO;AAC/C"}
|
package/dist/visitor/index.cjs
CHANGED
|
@@ -21,11 +21,11 @@ const IDENTIFY_EVENT = "identify";
|
|
|
21
21
|
* left to sign out — the device's identity, if any, is someone this page has not identified.
|
|
22
22
|
*/
|
|
23
23
|
let identified;
|
|
24
|
-
/** Hands the user to every
|
|
24
|
+
/** Hands the user to every integration's user setter; one that throws does not stop the others. */
|
|
25
25
|
function setUsers(user) {
|
|
26
|
-
require_setup_index.config.
|
|
26
|
+
require_setup_index.config.integrations.forEach(({ setUser }) => {
|
|
27
27
|
try {
|
|
28
|
-
|
|
28
|
+
setUser?.(user);
|
|
29
29
|
} catch (e) {
|
|
30
30
|
if (e instanceof Error) console.log(e.message);
|
|
31
31
|
}
|
|
@@ -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
|
|
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;CAC3D,oBAAA,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;EACA,oBAAA,OAAO,QAAQ,QAAQA,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;EACb,oBAAA,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,OAAOF,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;CACnB,oBAAA,WAAW;CACX,mBAAA,aAAa;CACb,oBAAA,OAAO,QAAQ,QAAQD,0BAAAA,KAAK,SAAS,EAAE;AACzC"}
|
package/dist/visitor/index.mjs
CHANGED
|
@@ -20,11 +20,11 @@ const IDENTIFY_EVENT = "identify";
|
|
|
20
20
|
* left to sign out — the device's identity, if any, is someone this page has not identified.
|
|
21
21
|
*/
|
|
22
22
|
let identified;
|
|
23
|
-
/** Hands the user to every
|
|
23
|
+
/** Hands the user to every integration's user setter; one that throws does not stop the others. */
|
|
24
24
|
function setUsers(user) {
|
|
25
|
-
config.
|
|
25
|
+
config.integrations.forEach(({ setUser }) => {
|
|
26
26
|
try {
|
|
27
|
-
|
|
27
|
+
setUser?.(user);
|
|
28
28
|
} catch (e) {
|
|
29
29
|
if (e instanceof Error) console.log(e.message);
|
|
30
30
|
}
|