@shware/analytics 15.0.0 → 16.0.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 +90 -37
- package/dist/native/fbsdk.cjs +45 -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 -2
- 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/reddit-conversions-api.d.cts +1 -1
- package/dist/server/reddit-conversions-api.d.mts +1 -1
- 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 +39 -0
- package/dist/third-parties/integration.cjs.map +1 -0
- package/dist/third-parties/integration.d.cts +57 -0
- package/dist/third-parties/integration.d.cts.map +1 -0
- package/dist/third-parties/integration.d.mts +57 -0
- package/dist/third-parties/integration.d.mts.map +1 -0
- package/dist/third-parties/integration.mjs +37 -0
- package/dist/third-parties/integration.mjs.map +1 -0
- package/dist/third-parties/linkedin-insight-tag.cjs +33 -0
- package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.cts +12 -8
- package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.d.mts +12 -8
- package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.mjs +33 -1
- package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
- package/dist/third-parties/meta-pixel.cjs +34 -0
- package/dist/third-parties/meta-pixel.cjs.map +1 -1
- package/dist/third-parties/meta-pixel.d.cts +5 -0
- package/dist/third-parties/meta-pixel.d.cts.map +1 -1
- package/dist/third-parties/meta-pixel.d.mts +5 -0
- package/dist/third-parties/meta-pixel.d.mts.map +1 -1
- package/dist/third-parties/meta-pixel.mjs +34 -1
- package/dist/third-parties/meta-pixel.mjs.map +1 -1
- package/dist/third-parties/microsoft-uet.cjs +49 -0
- package/dist/third-parties/microsoft-uet.cjs.map +1 -1
- package/dist/third-parties/microsoft-uet.d.cts +29 -0
- package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
- package/dist/third-parties/microsoft-uet.d.mts +29 -0
- package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
- package/dist/third-parties/microsoft-uet.mjs +48 -1
- package/dist/third-parties/microsoft-uet.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +31 -0
- package/dist/third-parties/openai-pixel.cjs.map +1 -1
- package/dist/third-parties/openai-pixel.d.cts +5 -0
- package/dist/third-parties/openai-pixel.d.cts.map +1 -1
- package/dist/third-parties/openai-pixel.d.mts +5 -0
- package/dist/third-parties/openai-pixel.d.mts.map +1 -1
- package/dist/third-parties/openai-pixel.mjs +31 -1
- 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 +32 -0
- package/dist/third-parties/reddit-pixel.cjs.map +1 -1
- package/dist/third-parties/reddit-pixel.d.cts +5 -0
- package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
- package/dist/third-parties/reddit-pixel.d.mts +5 -0
- package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
- package/dist/third-parties/reddit-pixel.mjs +32 -1
- package/dist/third-parties/reddit-pixel.mjs.map +1 -1
- package/dist/track/fbq.cjs +1 -1
- package/dist/track/fbq.cjs.map +1 -1
- package/dist/track/fbq.mjs +1 -1
- 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/visitor/index.cjs +36 -20
- package/dist/visitor/index.cjs.map +1 -1
- package/dist/visitor/index.d.cts +9 -6
- package/dist/visitor/index.d.cts.map +1 -1
- package/dist/visitor/index.d.mts +9 -6
- package/dist/visitor/index.d.mts.map +1 -1
- package/dist/visitor/index.mjs +36 -20
- package/dist/visitor/index.mjs.map +1 -1
- package/package.json +11 -24
- 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/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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getFirst } from "../utils/field.mjs";
|
|
2
|
+
import { adsTracker } from "./integration.mjs";
|
|
2
3
|
import { mapRDTEvent } from "../track/rdt.mjs";
|
|
3
4
|
// src/third-parties/reddit-pixel.ts
|
|
4
5
|
const metrics = [
|
|
@@ -34,6 +35,36 @@ function setRedditUser(pixelId) {
|
|
|
34
35
|
});
|
|
35
36
|
};
|
|
36
37
|
}
|
|
37
|
-
|
|
38
|
+
/** Reddit Pixel: the events `mapRDTEvent` maps to a Reddit standard event, and `customEvents`. */
|
|
39
|
+
function redditAds(options) {
|
|
40
|
+
const isStandard = (name) => mapRDTEvent(name)[0] !== "Custom";
|
|
41
|
+
const src = `https://www.redditstatic.com/ads/pixel.js?pixel_id=${encodeURIComponent(options.pixelId)}`;
|
|
42
|
+
return {
|
|
43
|
+
type: "ads",
|
|
44
|
+
track: adsTracker(sendRedditEvent, isStandard, options.customEvents ?? []),
|
|
45
|
+
setUser: setRedditUser(options.pixelId),
|
|
46
|
+
script: {
|
|
47
|
+
id: "reddit-pixel",
|
|
48
|
+
inline: `
|
|
49
|
+
!function(w,d) {
|
|
50
|
+
if(!w.rdt) {
|
|
51
|
+
var p = w.rdt = function() {
|
|
52
|
+
p.sendEvent ? p.sendEvent.apply(p,arguments) : p.callQueue.push(arguments)
|
|
53
|
+
};
|
|
54
|
+
p.callQueue = [];
|
|
55
|
+
var t = d.createElement("script");
|
|
56
|
+
t.src = ${JSON.stringify(src)};
|
|
57
|
+
t.async = !0;
|
|
58
|
+
var s = d.getElementsByTagName("script")[0];
|
|
59
|
+
s.parentNode.insertBefore(t,s)
|
|
60
|
+
}
|
|
61
|
+
}(window, document);
|
|
62
|
+
rdt('init', ${JSON.stringify(options.pixelId)});
|
|
63
|
+
rdt('track', 'PageVisit');
|
|
64
|
+
`
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export { redditAds, sendRedditEvent, setRedditUser };
|
|
38
69
|
|
|
39
70
|
//# sourceMappingURL=reddit-pixel.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-pixel.mjs","names":[],"sources":["../../src/third-parties/reddit-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type PixelId, type RDT, mapRDTEvent } from '../track/rdt';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\n\ndeclare global {\n interface Window {\n /** Undefined until the Reddit Pixel script has loaded. */\n rdt?: RDT['rdt'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendRedditEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const [type, params] = mapRDTEvent(name, properties, eventId);\n // The two branches are identical on purpose: `rdt('track', ...)` is overloaded — a standard\n // event name carries its own params type, 'Custom' carries `CustomEventParams` — and what\n // `mapRDTEvent` returns is a union of both. Narrowing `type` is what picks a single overload.\n if (type === 'Custom') {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n } else {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n }\n}\n\nexport function setRedditUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return;\n }\n\n window.rdt('init', pixelId, {\n email: getFirst(user_data?.email),\n phoneNumber: getFirst(user_data?.phone_number),\n externalId: user_id,\n });\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"reddit-pixel.mjs","names":[],"sources":["../../src/third-parties/reddit-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type PixelId, type RDT, mapRDTEvent } from '../track/rdt';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type AdsOptions, type Integration, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Reddit Pixel script has loaded. */\n rdt?: RDT['rdt'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendRedditEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (window.location.host.includes('127.0.0.1')) return;\n if (window.location.host.includes('localhost')) return;\n\n const [type, params] = mapRDTEvent(name, properties, eventId);\n // The two branches are identical on purpose: `rdt('track', ...)` is overloaded — a standard\n // event name carries its own params type, 'Custom' carries `CustomEventParams` — and what\n // `mapRDTEvent` returns is a union of both. Narrowing `type` is what picks a single overload.\n if (type === 'Custom') {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n } else {\n window.rdt('track', type, JSON.parse(JSON.stringify(params)));\n }\n}\n\nexport function setRedditUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.rdt) {\n console.warn('rdt has not been initialized');\n return;\n }\n\n window.rdt('init', pixelId, {\n email: getFirst(user_data?.email),\n phoneNumber: getFirst(user_data?.phone_number),\n externalId: user_id,\n });\n };\n}\n\n/** Reddit Pixel: the events `mapRDTEvent` maps to a Reddit standard event, and `customEvents`. */\nexport function redditAds(options: { pixelId: PixelId } & AdsOptions): Integration {\n const isStandard = (name: string) => mapRDTEvent(name as TrackName)[0] !== 'Custom';\n // As the Ads console's tag: the pixel loads with its id.\n const src = `https://www.redditstatic.com/ads/pixel.js?pixel_id=${encodeURIComponent(options.pixelId)}`;\n return {\n type: 'ads',\n track: adsTracker(sendRedditEvent, isStandard, options.customEvents ?? []),\n setUser: setRedditUser(options.pixelId),\n script: {\n id: 'reddit-pixel',\n inline: `\n !function(w,d) {\n if(!w.rdt) {\n var p = w.rdt = function() {\n p.sendEvent ? p.sendEvent.apply(p,arguments) : p.callQueue.push(arguments)\n };\n p.callQueue = [];\n var t = d.createElement(\"script\");\n t.src = ${JSON.stringify(src)};\n t.async = !0;\n var s = d.getElementsByTagName(\"script\")[0];\n s.parentNode.insertBefore(t,s)\n }\n }(window, document);\n rdt('init', ${JSON.stringify(options.pixelId)});\n rdt('track', 'PageVisit');\n `,\n },\n };\n}\n"],"mappings":";;;;AAaA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;EAChD,QAAQ,KAAK,8BAA8B;EAC3C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,MAAM,CAAC,MAAM,UAAU,YAAY,MAAM,YAAY,OAAO;CAI5D,IAAI,SAAS,UACX,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;MAE5D,OAAO,IAAI,SAAS,MAAM,KAAK,MAAM,KAAK,UAAU,MAAM,CAAC,CAAC;AAEhE;AAEA,SAAgB,cAAc,SAAkB;CAC9C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;GAChD,QAAQ,KAAK,8BAA8B;GAC3C;EACF;EAEA,OAAO,IAAI,QAAQ,SAAS;GAC1B,OAAO,SAAS,WAAW,KAAK;GAChC,aAAa,SAAS,WAAW,YAAY;GAC7C,YAAY;EACd,CAAC;CACH;AACF;;AAGA,SAAgB,UAAU,SAAyD;CACjF,MAAM,cAAc,SAAiB,YAAY,IAAiB,CAAC,CAAC,OAAO;CAE3E,MAAM,MAAM,sDAAsD,mBAAmB,QAAQ,OAAO;CACpG,OAAO;EACL,MAAM;EACN,OAAO,WAAW,iBAAiB,YAAY,QAAQ,gBAAgB,CAAC,CAAC;EACzE,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;sBAQQ,KAAK,UAAU,GAAG,EAAE;;;;;;sBAMpB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAGlD;CACF;AACF"}
|
package/dist/track/fbq.cjs
CHANGED
package/dist/track/fbq.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fbq.cjs","names":["itemKey","p"],"sources":["../../src/track/fbq.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport type Content = {\n id: string;\n quantity: number;\n item_price?: number;\n title?: string;\n description?: string;\n brand?: string;\n category?: string;\n delivery_category?: string;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/advanced/advanced-matching\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport type MatchingParameters = {\n /** Email: Unhashed lowercase or hashed SHA-256 */\n em?: string;\n\n /** First Name: Lowercase letters */\n fn?: string;\n\n /** Last Name: Lowercase letters */\n ln?: string;\n\n /** Phone Number: Digits only including country code and area code */\n ph?: string;\n\n /**\n * External ID: Any unique ID from the advertiser, such as loyalty membership ID, user ID, and\n * external cookie ID.\n */\n external_id?: string;\n\n /** Gender: Single lowercase letter, f or m, if unknown, leave blank */\n ge?: 'f' | 'm' | '';\n\n /** Birthdate: Digits only with birth year, month, then day, YYYYMMDD */\n db?: number;\n\n /** City: Lowercase with any spaces removed, e.g. \"menlopark\" */\n ct?: string;\n\n /** State or Province: Lowercase two-letter state or province code, e.g. \"ca\" */\n st?: string;\n\n /** Zip or Postal Code: String */\n zp?: string;\n\n /** Country: Lowercase two-letter country code, e.g. \"us\" */\n country?: string;\n\n /** Client IP Address: Do not hash. */\n client_ip_address?: string;\n\n /** Client User Agent: Do not hash. */\n client_user_agent?: string;\n\n /**\n * Click ID: Do not hash.\n * The Facebook click ID value is stored in the _fbc browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value or generate this value from a fbclid\n * query parameter.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${fbclid}.\n */\n fbc?: string;\n\n /**\n * Browser ID: Do not hash.\n * The Facebook browser ID value is stored in the _fbp browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${random_number}.\n */\n fbp?: string;\n\n /**\n * Subscription ID: Do not hash.\n * The subscription ID for the user in this transaction; it is similar to the order ID for an\n * individual product.\n */\n subscription_id?: string;\n\n /**\n * Facebook Login ID: Do not hash.\n * The ID issued by Meta when a person first logs into an instance of an app. This is also known\n * as App-Scoped ID.\n */\n fb_login_id?: number;\n\n /**\n * Lead ID: Do not hash.\n * The ID associated with a lead generated by [Meta's Lead Ads](https://developers.facebook.com/docs/marketing-api/guides/lead-ads).\n */\n lead_id?: number;\n\n /**\n * Install ID: Do not hash.\n * Your install ID. This field represents unique application installation instances.\n * Note: This parameter is for app events only.\n */\n anon_id?: string;\n\n /**\n * Your mobile advertiser ID, the advertising ID from an Android device or the Advertising\n * Identifier (IDFA) from an Apple device.\n */\n madid?: string;\n\n /**\n * Page ID: Do not hash.\n * Your Page ID. Specifies the page ID associated with the event. Use the Facebook page ID of the\n * page associated with the bot.\n */\n page_id?: string;\n\n /**\n * Page Scoped User ID: Do not hash.\n * Specifies the page-scoped user ID associated with the messenger bot that logs the event. Use\n * the page-scoped user ID provided to your webhook.\n */\n page_scoped_user_id?: string;\n\n /**\n * Do not hash.\n * Click ID generated by Meta for ads that click to WhatsApp.\n */\n ctwa_clid?: string;\n\n /**\n * Do not hash.\n * Instagram Account ID that is associated with the business.\n */\n ig_account_id?: string;\n\n /**\n * Do not hash.\n * Users who interact with Instagram are identified by Instagram-Scoped User IDs (IGSID). IGSID\n * can be obtained from this webhook.\n */\n ig_sid?: string;\n};\n\n/**\n * You can include the following predefined object properties with any custom events, and any\n * standard events that support them. Format your parameter object data using JSON. Learn more about\n * event parameters with Blueprint.\n */\nexport type ObjectProperties = {\n content_category?: string;\n content_ids?: string[];\n content_name?: string;\n\n /**\n * Either product or product_group based on the content_ids or contents being passed. If the IDs\n * being passed in content_ids or contents parameter are IDs of products, then the value should be\n * product. If product group IDs are being passed, then the value should be product_group.\n *\n * If no content_type is provided, Meta will match the event to every item that has the same ID,\n * independent of its type.\n */\n content_type?: 'product' | 'product_group' | (string & {});\n contents?: Content[];\n delivery_category?: 'in_store' | 'curbside' | 'home_delivery';\n currency?: string;\n num_items?: number;\n predicted_ltv?: number;\n search_string?: string;\n\n /** Used with the CompleteRegistration event, to show the status of the registration. */\n status?: boolean;\n value?: number;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/payload-helper\n */\nexport type StandardEvents = {\n AddPaymentInfo: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n AddToCart: {\n content_ids?: string[];\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents\n currency?: string;\n value?: number;\n };\n AddToWishlist: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n CompleteRegistration: {\n currency?: string;\n value?: number;\n method?: string;\n };\n Contact: {};\n CustomizeProduct: {};\n Donate: {};\n FindLocation: {};\n InitiateCheckout: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n num_items?: number;\n value?: number;\n };\n Lead: {\n currency?: string;\n value?: number;\n };\n Purchase: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency: string; // required\n num_items?: number;\n value: number; // required\n };\n Schedule: {};\n Search: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n search_string?: string;\n value?: number;\n };\n StartTrial: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n SubmitApplication: {};\n Subscribe: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n ViewContent: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n value?: number;\n };\n};\n\ntype JSONValue =\n | null\n | string\n | number\n | boolean\n | Array<JSONValue>\n | { [value: string]: JSONValue };\n\nexport type PixelId = `${number}`;\nexport type Options = { eventID?: string };\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/reference#standard-events\n *\n * We determine if events are identical based on their ID and name. So, for an event to be deduplicated:\n * - In corresponding events, a Meta Pixel's eventID must match the Conversion API's event_id.\n * - In corresponding events, a Meta Pixel's event must match the Conversion API's event_name.\n *\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport interface FBQ {\n /**\n * reference: https://stackoverflow.com/questions/62304291/sending-user-data-parameters-via-pixel\n *\n * Call init the normal default way first:\n * `fbq('init', 'XXXXX')`\n *\n * And at a later point in time, when you have obtained additional user data, you can call init\n * again basically enriching the already running fbq instance with additional data:\n * `fbq('init', 'XXXXX', { external_id: 1234, em: 'abc@abc.com' } )`\n *\n * Only caveat is that you have to send an event after this additional init call, otherwise the\n * provided data will not be sent to Facebook.\n */\n fbq(type: 'init', pixelId: PixelId, parameters?: MatchingParameters): void;\n\n /** Enable Manual Only mode. (value = false) */\n fbq(type: 'set', key: 'autoConfig', value: boolean, pixelId: PixelId): void;\n\n fbq<T extends keyof StandardEvents>(\n type: 'track',\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n fbq(\n type: 'trackCustom',\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq<T extends keyof StandardEvents>(\n type: 'trackSingle',\n pixelId: PixelId,\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq(\n type: 'trackSingleCustom',\n pixelId: PixelId,\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n}\n\n/**\n * Please download this CSV filefor examples of properly normalized and hashed data for the\n * parameters below.\n */\nexport function normalize(parameters: MatchingParameters): MatchingParameters {\n return {\n ...parameters,\n em: parameters.em?.toLowerCase().trim(),\n ph: parameters.ph?.replace(/[-+()\\s]/g, '').replace(/^0+/, ''),\n zp: parameters.zp?.split('-').at(0)?.trim(),\n fn: parameters.fn?.toLowerCase().trim(),\n ln: parameters.ln?.toLowerCase().trim(),\n ct: parameters.ct?.toLowerCase().replace(/[\\s/-]/g, ''),\n st: parameters.st?.toLowerCase().replace(/[\\s/,.-]/g, ''),\n country: parameters.country?.toLowerCase().replace(/[\\s/-]/g, ''),\n };\n}\n\nexport function mapItems(items?: Item[]): ObjectProperties {\n if (!items) return {};\n const categories = Array.from(new Set(items.map((i) => i.item_category).filter(Boolean)));\n const contents: Content[] = items.map((item) => {\n const { quantity, price, item_name, item_brand, item_category } = item;\n return {\n id: itemKey(item),\n quantity: quantity ?? 1,\n item_price: price,\n title: item_name,\n brand: item_brand,\n category: item_category,\n };\n });\n\n return {\n content_category: categories.length === 1 ? categories.at(0) : undefined,\n contents,\n content_ids: contents.map((c) => c.id),\n num_items: items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n };\n}\n\ntype Mapped<F extends keyof StandardEvents> = ['track', F, StandardEvents[F] & ObjectProperties];\ntype Missed<F extends string> = ['trackCustom', F, Record<string, JSONValue> & ObjectProperties];\n\nexport function mapFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n if (name === 'add_payment_info') {\n const p = properties as TrackProperties<'add_payment_info'> | undefined;\n return [\n 'track',\n 'AddPaymentInfo',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'track',\n 'AddToCart',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'track',\n 'AddToWishlist',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'login') {\n const p = properties as TrackProperties<'login'> | undefined;\n return ['track', 'CompleteRegistration', { method: p?.method }];\n } else if (name === 'contact') {\n return ['track', 'Contact', {}];\n } else if (name === 'customize_product') {\n return ['track', 'CustomizeProduct', {}];\n } else if (name === 'donate') {\n return ['track', 'Donate', {}];\n } else if (name === 'find_location') {\n return ['track', 'FindLocation', {}];\n } else if (name === 'begin_checkout') {\n const p = properties as TrackProperties<'begin_checkout'> | undefined;\n return [\n 'track',\n 'InitiateCheckout',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return ['track', 'Lead', { currency: p?.currency, value: p?.value }];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'track',\n 'Purchase',\n { currency: p?.currency ?? 'USD', value: p?.value ?? 0, ...mapItems(p?.items) },\n ];\n } else if (name === 'schedule') {\n return ['track', 'Schedule', {}];\n } else if (name === 'search') {\n const p = properties as TrackProperties<'search'> | undefined;\n return ['track', 'Search', { search_string: p?.search_term }];\n } else if (name === 'trial_begin') {\n const p = properties as TrackProperties<'trial_begin'> | undefined;\n return ['track', 'StartTrial', { currency: p?.currency, value: p?.value }];\n } else if (name === 'submit_application') {\n return ['track', 'SubmitApplication', {}];\n } else if (name === 'subscribe') {\n const p = properties as TrackProperties<'subscribe'> | undefined;\n return ['track', 'Subscribe', { currency: p?.currency, value: p?.value }];\n } else if (name === 'view_item') {\n const p = properties as TrackProperties<'view_item'> | undefined;\n return [\n 'track',\n 'ViewContent',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else {\n return ['trackCustom', name, properties ?? {}];\n }\n}\n"],"mappings":";;;;;;;AA+UA,SAAgB,UAAU,YAAoD;CAC5E,OAAO;EACL,GAAG;EACH,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,IAAI,QAAQ,aAAa,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE;EAC7D,IAAI,WAAW,IAAI,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK;EAC1C,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,QAAQ,WAAW,EAAE;EACtD,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,QAAQ,aAAa,EAAE;EACxD,SAAS,WAAW,SAAS,YAAY,CAAC,CAAC,QAAQ,WAAW,EAAE;CAClE;AACF;AAEA,SAAgB,SAAS,OAAkC;CACzD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,MAAM,aAAa,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,MAAM,EAAE,aA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-disable @typescript-eslint/no-empty-object-type */\nimport { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport type Content = {\n id: string;\n quantity: number;\n item_price?: number;\n title?: string;\n description?: string;\n brand?: string;\n category?: string;\n delivery_category?: string;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/advanced/advanced-matching\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport type MatchingParameters = {\n /** Email: Unhashed lowercase or hashed SHA-256 */\n em?: string;\n\n /** First Name: Lowercase letters */\n fn?: string;\n\n /** Last Name: Lowercase letters */\n ln?: string;\n\n /** Phone Number: Digits only including country code and area code */\n ph?: string;\n\n /**\n * External ID: Any unique ID from the advertiser, such as loyalty membership ID, user ID, and\n * external cookie ID.\n */\n external_id?: string;\n\n /** Gender: Single lowercase letter, f or m, if unknown, leave blank */\n ge?: 'f' | 'm' | '';\n\n /** Birthdate: Digits only with birth year, month, then day, YYYYMMDD */\n db?: number;\n\n /** City: Lowercase with any spaces removed, e.g. \"menlopark\" */\n ct?: string;\n\n /** State or Province: Lowercase two-letter state or province code, e.g. \"ca\" */\n st?: string;\n\n /** Zip or Postal Code: String */\n zp?: string;\n\n /** Country: Lowercase two-letter country code, e.g. \"us\" */\n country?: string;\n\n /** Client IP Address: Do not hash. */\n client_ip_address?: string;\n\n /** Client User Agent: Do not hash. */\n client_user_agent?: string;\n\n /**\n * Click ID: Do not hash.\n * The Facebook click ID value is stored in the _fbc browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value or generate this value from a fbclid\n * query parameter.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${fbclid}.\n */\n fbc?: string;\n\n /**\n * Browser ID: Do not hash.\n * The Facebook browser ID value is stored in the _fbp browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${random_number}.\n */\n fbp?: string;\n\n /**\n * Subscription ID: Do not hash.\n * The subscription ID for the user in this transaction; it is similar to the order ID for an\n * individual product.\n */\n subscription_id?: string;\n\n /**\n * Facebook Login ID: Do not hash.\n * The ID issued by Meta when a person first logs into an instance of an app. This is also known\n * as App-Scoped ID.\n */\n fb_login_id?: number;\n\n /**\n * Lead ID: Do not hash.\n * The ID associated with a lead generated by [Meta's Lead Ads](https://developers.facebook.com/docs/marketing-api/guides/lead-ads).\n */\n lead_id?: number;\n\n /**\n * Install ID: Do not hash.\n * Your install ID. This field represents unique application installation instances.\n * Note: This parameter is for app events only.\n */\n anon_id?: string;\n\n /**\n * Your mobile advertiser ID, the advertising ID from an Android device or the Advertising\n * Identifier (IDFA) from an Apple device.\n */\n madid?: string;\n\n /**\n * Page ID: Do not hash.\n * Your Page ID. Specifies the page ID associated with the event. Use the Facebook page ID of the\n * page associated with the bot.\n */\n page_id?: string;\n\n /**\n * Page Scoped User ID: Do not hash.\n * Specifies the page-scoped user ID associated with the messenger bot that logs the event. Use\n * the page-scoped user ID provided to your webhook.\n */\n page_scoped_user_id?: string;\n\n /**\n * Do not hash.\n * Click ID generated by Meta for ads that click to WhatsApp.\n */\n ctwa_clid?: string;\n\n /**\n * Do not hash.\n * Instagram Account ID that is associated with the business.\n */\n ig_account_id?: string;\n\n /**\n * Do not hash.\n * Users who interact with Instagram are identified by Instagram-Scoped User IDs (IGSID). IGSID\n * can be obtained from this webhook.\n */\n ig_sid?: string;\n};\n\n/**\n * You can include the following predefined object properties with any custom events, and any\n * standard events that support them. Format your parameter object data using JSON. Learn more about\n * event parameters with Blueprint.\n */\nexport type ObjectProperties = {\n content_category?: string;\n content_ids?: string[];\n content_name?: string;\n\n /**\n * Either product or product_group based on the content_ids or contents being passed. If the IDs\n * being passed in content_ids or contents parameter are IDs of products, then the value should be\n * product. If product group IDs are being passed, then the value should be product_group.\n *\n * If no content_type is provided, Meta will match the event to every item that has the same ID,\n * independent of its type.\n */\n content_type?: 'product' | 'product_group' | (string & {});\n contents?: Content[];\n delivery_category?: 'in_store' | 'curbside' | 'home_delivery';\n currency?: string;\n num_items?: number;\n predicted_ltv?: number;\n search_string?: string;\n\n /** Used with the CompleteRegistration event, to show the status of the registration. */\n status?: boolean;\n value?: number;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/payload-helper\n */\nexport type StandardEvents = {\n AddPaymentInfo: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n AddToCart: {\n content_ids?: string[];\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents\n currency?: string;\n value?: number;\n };\n AddToWishlist: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n CompleteRegistration: {\n currency?: string;\n value?: number;\n method?: string;\n };\n Contact: {};\n CustomizeProduct: {};\n Donate: {};\n FindLocation: {};\n InitiateCheckout: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n num_items?: number;\n value?: number;\n };\n Lead: {\n currency?: string;\n value?: number;\n };\n Purchase: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency: string; // required\n num_items?: number;\n value: number; // required\n };\n Schedule: {};\n Search: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n search_string?: string;\n value?: number;\n };\n StartTrial: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n SubmitApplication: {};\n Subscribe: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n ViewContent: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n value?: number;\n };\n};\n\ntype JSONValue =\n | null\n | string\n | number\n | boolean\n | Array<JSONValue>\n | { [value: string]: JSONValue };\n\nexport type PixelId = `${number}`;\nexport type Options = { eventID?: string };\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/reference#standard-events\n *\n * We determine if events are identical based on their ID and name. So, for an event to be deduplicated:\n * - In corresponding events, a Meta Pixel's eventID must match the Conversion API's event_id.\n * - In corresponding events, a Meta Pixel's event must match the Conversion API's event_name.\n *\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport interface FBQ {\n /**\n * reference: https://stackoverflow.com/questions/62304291/sending-user-data-parameters-via-pixel\n *\n * Call init the normal default way first:\n * `fbq('init', 'XXXXX')`\n *\n * And at a later point in time, when you have obtained additional user data, you can call init\n * again basically enriching the already running fbq instance with additional data:\n * `fbq('init', 'XXXXX', { external_id: 1234, em: 'abc@abc.com' } )`\n *\n * Only caveat is that you have to send an event after this additional init call, otherwise the\n * provided data will not be sent to Facebook.\n */\n fbq(type: 'init', pixelId: PixelId, parameters?: MatchingParameters): void;\n\n /** Enable Manual Only mode. (value = false) */\n fbq(type: 'set', key: 'autoConfig', value: boolean, pixelId: PixelId): void;\n\n fbq<T extends keyof StandardEvents>(\n type: 'track',\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n fbq(\n type: 'trackCustom',\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq<T extends keyof StandardEvents>(\n type: 'trackSingle',\n pixelId: PixelId,\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq(\n type: 'trackSingleCustom',\n pixelId: PixelId,\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n}\n\n/**\n * Please download this CSV filefor examples of properly normalized and hashed data for the\n * parameters below.\n */\nexport function normalize(parameters: MatchingParameters): MatchingParameters {\n return {\n ...parameters,\n em: parameters.em?.toLowerCase().trim(),\n ph: parameters.ph?.replace(/[-+()\\s]/g, '').replace(/^0+/, ''),\n zp: parameters.zp?.split('-').at(0)?.trim(),\n fn: parameters.fn?.toLowerCase().trim(),\n ln: parameters.ln?.toLowerCase().trim(),\n ct: parameters.ct?.toLowerCase().replace(/[\\s/-]/g, ''),\n st: parameters.st?.toLowerCase().replace(/[\\s/,.-]/g, ''),\n country: parameters.country?.toLowerCase().replace(/[\\s/-]/g, ''),\n };\n}\n\nexport function mapItems(items?: Item[]): ObjectProperties {\n if (!items) return {};\n const categories = Array.from(new Set(items.map((i) => i.item_category).filter(Boolean)));\n const contents: Content[] = items.map((item) => {\n const { quantity, price, item_name, item_brand, item_category } = item;\n return {\n id: itemKey(item),\n quantity: quantity ?? 1,\n item_price: price,\n title: item_name,\n brand: item_brand,\n category: item_category,\n };\n });\n\n return {\n content_category: categories.length === 1 ? categories.at(0) : undefined,\n contents,\n content_ids: contents.map((c) => c.id),\n num_items: items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n };\n}\n\ntype Mapped<F extends keyof StandardEvents> = ['track', F, StandardEvents[F] & ObjectProperties];\ntype Missed<F extends string> = ['trackCustom', F, Record<string, JSONValue> & ObjectProperties];\n\nexport function mapFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n if (name === 'add_payment_info') {\n const p = properties as TrackProperties<'add_payment_info'> | undefined;\n return [\n 'track',\n 'AddPaymentInfo',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'track',\n 'AddToCart',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'track',\n 'AddToWishlist',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'sign_up' || name === 'login') {\n const p = properties as TrackProperties<'sign_up' | 'login'> | undefined;\n return ['track', 'CompleteRegistration', { method: p?.method }];\n } else if (name === 'contact') {\n return ['track', 'Contact', {}];\n } else if (name === 'customize_product') {\n return ['track', 'CustomizeProduct', {}];\n } else if (name === 'donate') {\n return ['track', 'Donate', {}];\n } else if (name === 'find_location') {\n return ['track', 'FindLocation', {}];\n } else if (name === 'begin_checkout') {\n const p = properties as TrackProperties<'begin_checkout'> | undefined;\n return [\n 'track',\n 'InitiateCheckout',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return ['track', 'Lead', { currency: p?.currency, value: p?.value }];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'track',\n 'Purchase',\n { currency: p?.currency ?? 'USD', value: p?.value ?? 0, ...mapItems(p?.items) },\n ];\n } else if (name === 'schedule') {\n return ['track', 'Schedule', {}];\n } else if (name === 'search') {\n const p = properties as TrackProperties<'search'> | undefined;\n return ['track', 'Search', { search_string: p?.search_term }];\n } else if (name === 'trial_begin') {\n const p = properties as TrackProperties<'trial_begin'> | undefined;\n return ['track', 'StartTrial', { currency: p?.currency, value: p?.value }];\n } else if (name === 'submit_application') {\n return ['track', 'SubmitApplication', {}];\n } else if (name === 'subscribe') {\n const p = properties as TrackProperties<'subscribe'> | undefined;\n return ['track', 'Subscribe', { currency: p?.currency, value: p?.value }];\n } else if (name === 'view_item') {\n const p = properties as TrackProperties<'view_item'> | undefined;\n return [\n 'track',\n 'ViewContent',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else {\n return ['trackCustom', name, properties ?? {}];\n }\n}\n"],"mappings":";;;;;;;AA+UA,SAAgB,UAAU,YAAoD;CAC5E,OAAO;EACL,GAAG;EACH,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,I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;EACV,OAAO;GAAC;GAAS;GAAc;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;GAAM;EAAC;CAC3E,OAAO,IAAI,SAAS,sBAClB,OAAO;EAAC;EAAS;EAAqB,CAAC;CAAC;MACnC,IAAI,SAAS,aAAa;EAC/B,MAAM,IAAI;EACV,OAAO;GAAC;GAAS;GAAa;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;GAAM;EAAC;CAC1E,OAAO,IAAI,SAAS,aAAa;EAC/B,MAAM,IAAI;EACV,OAAO;GACL;GACA;GACA;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;IAAO,GAAG,SAAS,GAAG,KAAK;GAAE;EAClE;CACF,OACE,OAAO;EAAC;EAAe;EAAM,cAAc,CAAC;CAAC;AAEjD"}
|
package/dist/track/fbq.mjs
CHANGED
package/dist/track/fbq.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fbq.mjs","names":["p"],"sources":["../../src/track/fbq.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport type Content = {\n id: string;\n quantity: number;\n item_price?: number;\n title?: string;\n description?: string;\n brand?: string;\n category?: string;\n delivery_category?: string;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/advanced/advanced-matching\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport type MatchingParameters = {\n /** Email: Unhashed lowercase or hashed SHA-256 */\n em?: string;\n\n /** First Name: Lowercase letters */\n fn?: string;\n\n /** Last Name: Lowercase letters */\n ln?: string;\n\n /** Phone Number: Digits only including country code and area code */\n ph?: string;\n\n /**\n * External ID: Any unique ID from the advertiser, such as loyalty membership ID, user ID, and\n * external cookie ID.\n */\n external_id?: string;\n\n /** Gender: Single lowercase letter, f or m, if unknown, leave blank */\n ge?: 'f' | 'm' | '';\n\n /** Birthdate: Digits only with birth year, month, then day, YYYYMMDD */\n db?: number;\n\n /** City: Lowercase with any spaces removed, e.g. \"menlopark\" */\n ct?: string;\n\n /** State or Province: Lowercase two-letter state or province code, e.g. \"ca\" */\n st?: string;\n\n /** Zip or Postal Code: String */\n zp?: string;\n\n /** Country: Lowercase two-letter country code, e.g. \"us\" */\n country?: string;\n\n /** Client IP Address: Do not hash. */\n client_ip_address?: string;\n\n /** Client User Agent: Do not hash. */\n client_user_agent?: string;\n\n /**\n * Click ID: Do not hash.\n * The Facebook click ID value is stored in the _fbc browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value or generate this value from a fbclid\n * query parameter.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${fbclid}.\n */\n fbc?: string;\n\n /**\n * Browser ID: Do not hash.\n * The Facebook browser ID value is stored in the _fbp browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${random_number}.\n */\n fbp?: string;\n\n /**\n * Subscription ID: Do not hash.\n * The subscription ID for the user in this transaction; it is similar to the order ID for an\n * individual product.\n */\n subscription_id?: string;\n\n /**\n * Facebook Login ID: Do not hash.\n * The ID issued by Meta when a person first logs into an instance of an app. This is also known\n * as App-Scoped ID.\n */\n fb_login_id?: number;\n\n /**\n * Lead ID: Do not hash.\n * The ID associated with a lead generated by [Meta's Lead Ads](https://developers.facebook.com/docs/marketing-api/guides/lead-ads).\n */\n lead_id?: number;\n\n /**\n * Install ID: Do not hash.\n * Your install ID. This field represents unique application installation instances.\n * Note: This parameter is for app events only.\n */\n anon_id?: string;\n\n /**\n * Your mobile advertiser ID, the advertising ID from an Android device or the Advertising\n * Identifier (IDFA) from an Apple device.\n */\n madid?: string;\n\n /**\n * Page ID: Do not hash.\n * Your Page ID. Specifies the page ID associated with the event. Use the Facebook page ID of the\n * page associated with the bot.\n */\n page_id?: string;\n\n /**\n * Page Scoped User ID: Do not hash.\n * Specifies the page-scoped user ID associated with the messenger bot that logs the event. Use\n * the page-scoped user ID provided to your webhook.\n */\n page_scoped_user_id?: string;\n\n /**\n * Do not hash.\n * Click ID generated by Meta for ads that click to WhatsApp.\n */\n ctwa_clid?: string;\n\n /**\n * Do not hash.\n * Instagram Account ID that is associated with the business.\n */\n ig_account_id?: string;\n\n /**\n * Do not hash.\n * Users who interact with Instagram are identified by Instagram-Scoped User IDs (IGSID). IGSID\n * can be obtained from this webhook.\n */\n ig_sid?: string;\n};\n\n/**\n * You can include the following predefined object properties with any custom events, and any\n * standard events that support them. Format your parameter object data using JSON. Learn more about\n * event parameters with Blueprint.\n */\nexport type ObjectProperties = {\n content_category?: string;\n content_ids?: string[];\n content_name?: string;\n\n /**\n * Either product or product_group based on the content_ids or contents being passed. If the IDs\n * being passed in content_ids or contents parameter are IDs of products, then the value should be\n * product. If product group IDs are being passed, then the value should be product_group.\n *\n * If no content_type is provided, Meta will match the event to every item that has the same ID,\n * independent of its type.\n */\n content_type?: 'product' | 'product_group' | (string & {});\n contents?: Content[];\n delivery_category?: 'in_store' | 'curbside' | 'home_delivery';\n currency?: string;\n num_items?: number;\n predicted_ltv?: number;\n search_string?: string;\n\n /** Used with the CompleteRegistration event, to show the status of the registration. */\n status?: boolean;\n value?: number;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/payload-helper\n */\nexport type StandardEvents = {\n AddPaymentInfo: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n AddToCart: {\n content_ids?: string[];\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents\n currency?: string;\n value?: number;\n };\n AddToWishlist: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n CompleteRegistration: {\n currency?: string;\n value?: number;\n method?: string;\n };\n Contact: {};\n CustomizeProduct: {};\n Donate: {};\n FindLocation: {};\n InitiateCheckout: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n num_items?: number;\n value?: number;\n };\n Lead: {\n currency?: string;\n value?: number;\n };\n Purchase: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency: string; // required\n num_items?: number;\n value: number; // required\n };\n Schedule: {};\n Search: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n search_string?: string;\n value?: number;\n };\n StartTrial: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n SubmitApplication: {};\n Subscribe: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n ViewContent: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n value?: number;\n };\n};\n\ntype JSONValue =\n | null\n | string\n | number\n | boolean\n | Array<JSONValue>\n | { [value: string]: JSONValue };\n\nexport type PixelId = `${number}`;\nexport type Options = { eventID?: string };\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/reference#standard-events\n *\n * We determine if events are identical based on their ID and name. So, for an event to be deduplicated:\n * - In corresponding events, a Meta Pixel's eventID must match the Conversion API's event_id.\n * - In corresponding events, a Meta Pixel's event must match the Conversion API's event_name.\n *\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport interface FBQ {\n /**\n * reference: https://stackoverflow.com/questions/62304291/sending-user-data-parameters-via-pixel\n *\n * Call init the normal default way first:\n * `fbq('init', 'XXXXX')`\n *\n * And at a later point in time, when you have obtained additional user data, you can call init\n * again basically enriching the already running fbq instance with additional data:\n * `fbq('init', 'XXXXX', { external_id: 1234, em: 'abc@abc.com' } )`\n *\n * Only caveat is that you have to send an event after this additional init call, otherwise the\n * provided data will not be sent to Facebook.\n */\n fbq(type: 'init', pixelId: PixelId, parameters?: MatchingParameters): void;\n\n /** Enable Manual Only mode. (value = false) */\n fbq(type: 'set', key: 'autoConfig', value: boolean, pixelId: PixelId): void;\n\n fbq<T extends keyof StandardEvents>(\n type: 'track',\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n fbq(\n type: 'trackCustom',\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq<T extends keyof StandardEvents>(\n type: 'trackSingle',\n pixelId: PixelId,\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq(\n type: 'trackSingleCustom',\n pixelId: PixelId,\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n}\n\n/**\n * Please download this CSV filefor examples of properly normalized and hashed data for the\n * parameters below.\n */\nexport function normalize(parameters: MatchingParameters): MatchingParameters {\n return {\n ...parameters,\n em: parameters.em?.toLowerCase().trim(),\n ph: parameters.ph?.replace(/[-+()\\s]/g, '').replace(/^0+/, ''),\n zp: parameters.zp?.split('-').at(0)?.trim(),\n fn: parameters.fn?.toLowerCase().trim(),\n ln: parameters.ln?.toLowerCase().trim(),\n ct: parameters.ct?.toLowerCase().replace(/[\\s/-]/g, ''),\n st: parameters.st?.toLowerCase().replace(/[\\s/,.-]/g, ''),\n country: parameters.country?.toLowerCase().replace(/[\\s/-]/g, ''),\n };\n}\n\nexport function mapItems(items?: Item[]): ObjectProperties {\n if (!items) return {};\n const categories = Array.from(new Set(items.map((i) => i.item_category).filter(Boolean)));\n const contents: Content[] = items.map((item) => {\n const { quantity, price, item_name, item_brand, item_category } = item;\n return {\n id: itemKey(item),\n quantity: quantity ?? 1,\n item_price: price,\n title: item_name,\n brand: item_brand,\n category: item_category,\n };\n });\n\n return {\n content_category: categories.length === 1 ? categories.at(0) : undefined,\n contents,\n content_ids: contents.map((c) => c.id),\n num_items: items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n };\n}\n\ntype Mapped<F extends keyof StandardEvents> = ['track', F, StandardEvents[F] & ObjectProperties];\ntype Missed<F extends string> = ['trackCustom', F, Record<string, JSONValue> & ObjectProperties];\n\nexport function mapFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n if (name === 'add_payment_info') {\n const p = properties as TrackProperties<'add_payment_info'> | undefined;\n return [\n 'track',\n 'AddPaymentInfo',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'track',\n 'AddToCart',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'track',\n 'AddToWishlist',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'login') {\n const p = properties as TrackProperties<'login'> | undefined;\n return ['track', 'CompleteRegistration', { method: p?.method }];\n } else if (name === 'contact') {\n return ['track', 'Contact', {}];\n } else if (name === 'customize_product') {\n return ['track', 'CustomizeProduct', {}];\n } else if (name === 'donate') {\n return ['track', 'Donate', {}];\n } else if (name === 'find_location') {\n return ['track', 'FindLocation', {}];\n } else if (name === 'begin_checkout') {\n const p = properties as TrackProperties<'begin_checkout'> | undefined;\n return [\n 'track',\n 'InitiateCheckout',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return ['track', 'Lead', { currency: p?.currency, value: p?.value }];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'track',\n 'Purchase',\n { currency: p?.currency ?? 'USD', value: p?.value ?? 0, ...mapItems(p?.items) },\n ];\n } else if (name === 'schedule') {\n return ['track', 'Schedule', {}];\n } else if (name === 'search') {\n const p = properties as TrackProperties<'search'> | undefined;\n return ['track', 'Search', { search_string: p?.search_term }];\n } else if (name === 'trial_begin') {\n const p = properties as TrackProperties<'trial_begin'> | undefined;\n return ['track', 'StartTrial', { currency: p?.currency, value: p?.value }];\n } else if (name === 'submit_application') {\n return ['track', 'SubmitApplication', {}];\n } else if (name === 'subscribe') {\n const p = properties as TrackProperties<'subscribe'> | undefined;\n return ['track', 'Subscribe', { currency: p?.currency, value: p?.value }];\n } else if (name === 'view_item') {\n const p = properties as TrackProperties<'view_item'> | undefined;\n return [\n 'track',\n 'ViewContent',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else {\n return ['trackCustom', name, properties ?? {}];\n }\n}\n"],"mappings":";;;;;;AA+UA,SAAgB,UAAU,YAAoD;CAC5E,OAAO;EACL,GAAG;EACH,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,IAAI,QAAQ,aAAa,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE;EAC7D,IAAI,WAAW,IAAI,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK;EAC1C,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,QAAQ,WAAW,EAAE;EACtD,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,QAAQ,aAAa,EAAE;EACxD,SAAS,WAAW,SAAS,YAAY,CAAC,CAAC,QAAQ,WAAW,EAAE;CAClE;AACF;AAEA,SAAgB,SAAS,OAAkC;CACzD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,MAAM,aAAa,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,MAAM,EAAE,aAAa,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;CACxF,MAAM,WAAsB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MAAM,IAAI;EACV,OAAO;GACL;GACA;GACA;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;IAAO,GAAG,SAAS,GAAG,KAAK;GAAE;EAClE;CACF,OAAO,IAAI,SAAS,iBAAiB;EACnC,MAAM,IAAI;EACV,OAAO;GAAC;GAAS;GAAQ;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;GAAM;EAAC;CACrE,OAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,IAAI;EACV,OAAO;GACL;GACA;GACA;IAAE,UAAU,GAAG,YAAY;IAAO,OAAO,GAAG,SAAS;IAAG,GAAG,SAAS,GAAG,KAAK;GAAE;EAChF;CACF,OAAO,IAAI,SAAS,YAClB,OAAO;EAAC;EAAS;EAAY,CAAC;CAAC;MAC1B,IAAI,SAAS,UAElB,OAAO;EAAC;EAAS;EAAU,EAAE,eAAeA,YAAG,YAAY;CAAC;MACvD,IAAI,SAAS,eAAe;EACjC,MAAM,IAAI;EACV,OAAO;GAAC;GAAS;GAAc;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;GAAM;EAAC;CAC3E,OAAO,IAAI,SAAS,sBAClB,OAAO;EAAC;EAAS;EAAqB,CAAC;CAAC;MACnC,IAAI,SAAS,aAAa;EAC/B,MAAM,IAAI;EACV,OAAO;GAAC;GAAS;GAAa;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;GAAM;EAAC;CAC1E,OAAO,IAAI,SAAS,aAAa;EAC/B,MAAM,IAAI;EACV,OAAO;GACL;GACA;GACA;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;IAAO,GAAG,SAAS,GAAG,KAAK;GAAE;EAClE;CACF,OACE,OAAO;EAAC;EAAe;EAAM,cAAc,CAAC;CAAC;AAEjD"}
|
|
1
|
+
{"version":3,"file":"fbq.mjs","names":["p"],"sources":["../../src/track/fbq.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-empty-object-type */\nimport { type Item, itemKey } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport type Content = {\n id: string;\n quantity: number;\n item_price?: number;\n title?: string;\n description?: string;\n brand?: string;\n category?: string;\n delivery_category?: string;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/advanced/advanced-matching\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport type MatchingParameters = {\n /** Email: Unhashed lowercase or hashed SHA-256 */\n em?: string;\n\n /** First Name: Lowercase letters */\n fn?: string;\n\n /** Last Name: Lowercase letters */\n ln?: string;\n\n /** Phone Number: Digits only including country code and area code */\n ph?: string;\n\n /**\n * External ID: Any unique ID from the advertiser, such as loyalty membership ID, user ID, and\n * external cookie ID.\n */\n external_id?: string;\n\n /** Gender: Single lowercase letter, f or m, if unknown, leave blank */\n ge?: 'f' | 'm' | '';\n\n /** Birthdate: Digits only with birth year, month, then day, YYYYMMDD */\n db?: number;\n\n /** City: Lowercase with any spaces removed, e.g. \"menlopark\" */\n ct?: string;\n\n /** State or Province: Lowercase two-letter state or province code, e.g. \"ca\" */\n st?: string;\n\n /** Zip or Postal Code: String */\n zp?: string;\n\n /** Country: Lowercase two-letter country code, e.g. \"us\" */\n country?: string;\n\n /** Client IP Address: Do not hash. */\n client_ip_address?: string;\n\n /** Client User Agent: Do not hash. */\n client_user_agent?: string;\n\n /**\n * Click ID: Do not hash.\n * The Facebook click ID value is stored in the _fbc browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value or generate this value from a fbclid\n * query parameter.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${fbclid}.\n */\n fbc?: string;\n\n /**\n * Browser ID: Do not hash.\n * The Facebook browser ID value is stored in the _fbp browser cookie under your domain. See\n * Managing fbc and fbp Parameters for how to get this value.\n *\n * The format is fb.${subdomain_index}.${creation_time}.${random_number}.\n */\n fbp?: string;\n\n /**\n * Subscription ID: Do not hash.\n * The subscription ID for the user in this transaction; it is similar to the order ID for an\n * individual product.\n */\n subscription_id?: string;\n\n /**\n * Facebook Login ID: Do not hash.\n * The ID issued by Meta when a person first logs into an instance of an app. This is also known\n * as App-Scoped ID.\n */\n fb_login_id?: number;\n\n /**\n * Lead ID: Do not hash.\n * The ID associated with a lead generated by [Meta's Lead Ads](https://developers.facebook.com/docs/marketing-api/guides/lead-ads).\n */\n lead_id?: number;\n\n /**\n * Install ID: Do not hash.\n * Your install ID. This field represents unique application installation instances.\n * Note: This parameter is for app events only.\n */\n anon_id?: string;\n\n /**\n * Your mobile advertiser ID, the advertising ID from an Android device or the Advertising\n * Identifier (IDFA) from an Apple device.\n */\n madid?: string;\n\n /**\n * Page ID: Do not hash.\n * Your Page ID. Specifies the page ID associated with the event. Use the Facebook page ID of the\n * page associated with the bot.\n */\n page_id?: string;\n\n /**\n * Page Scoped User ID: Do not hash.\n * Specifies the page-scoped user ID associated with the messenger bot that logs the event. Use\n * the page-scoped user ID provided to your webhook.\n */\n page_scoped_user_id?: string;\n\n /**\n * Do not hash.\n * Click ID generated by Meta for ads that click to WhatsApp.\n */\n ctwa_clid?: string;\n\n /**\n * Do not hash.\n * Instagram Account ID that is associated with the business.\n */\n ig_account_id?: string;\n\n /**\n * Do not hash.\n * Users who interact with Instagram are identified by Instagram-Scoped User IDs (IGSID). IGSID\n * can be obtained from this webhook.\n */\n ig_sid?: string;\n};\n\n/**\n * You can include the following predefined object properties with any custom events, and any\n * standard events that support them. Format your parameter object data using JSON. Learn more about\n * event parameters with Blueprint.\n */\nexport type ObjectProperties = {\n content_category?: string;\n content_ids?: string[];\n content_name?: string;\n\n /**\n * Either product or product_group based on the content_ids or contents being passed. If the IDs\n * being passed in content_ids or contents parameter are IDs of products, then the value should be\n * product. If product group IDs are being passed, then the value should be product_group.\n *\n * If no content_type is provided, Meta will match the event to every item that has the same ID,\n * independent of its type.\n */\n content_type?: 'product' | 'product_group' | (string & {});\n contents?: Content[];\n delivery_category?: 'in_store' | 'curbside' | 'home_delivery';\n currency?: string;\n num_items?: number;\n predicted_ltv?: number;\n search_string?: string;\n\n /** Used with the CompleteRegistration event, to show the status of the registration. */\n status?: boolean;\n value?: number;\n};\n\n/**\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/payload-helper\n */\nexport type StandardEvents = {\n AddPaymentInfo: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n AddToCart: {\n content_ids?: string[];\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents\n currency?: string;\n value?: number;\n };\n AddToWishlist: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n value?: number;\n };\n CompleteRegistration: {\n currency?: string;\n value?: number;\n method?: string;\n };\n Contact: {};\n CustomizeProduct: {};\n Donate: {};\n FindLocation: {};\n InitiateCheckout: {\n content_ids?: string[];\n contents?: Content[];\n currency?: string;\n num_items?: number;\n value?: number;\n };\n Lead: {\n currency?: string;\n value?: number;\n };\n Purchase: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency: string; // required\n num_items?: number;\n value: number; // required\n };\n Schedule: {};\n Search: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n search_string?: string;\n value?: number;\n };\n StartTrial: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n SubmitApplication: {};\n Subscribe: {\n currency?: string;\n predicted_ltv?: number;\n value?: number;\n };\n ViewContent: {\n content_ids?: string[]; // Required for Advantage+ catalog ads: contents or content_ids\n content_type?: string;\n contents?: Content[]; // Required for Advantage+ catalog ads: contents or content_ids\n currency?: string;\n value?: number;\n };\n};\n\ntype JSONValue =\n | null\n | string\n | number\n | boolean\n | Array<JSONValue>\n | { [value: string]: JSONValue };\n\nexport type PixelId = `${number}`;\nexport type Options = { eventID?: string };\n\n/**\n * reference: https://developers.facebook.com/docs/meta-pixel/reference#standard-events\n *\n * We determine if events are identical based on their ID and name. So, for an event to be deduplicated:\n * - In corresponding events, a Meta Pixel's eventID must match the Conversion API's event_id.\n * - In corresponding events, a Meta Pixel's event must match the Conversion API's event_name.\n *\n * reference: https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nexport interface FBQ {\n /**\n * reference: https://stackoverflow.com/questions/62304291/sending-user-data-parameters-via-pixel\n *\n * Call init the normal default way first:\n * `fbq('init', 'XXXXX')`\n *\n * And at a later point in time, when you have obtained additional user data, you can call init\n * again basically enriching the already running fbq instance with additional data:\n * `fbq('init', 'XXXXX', { external_id: 1234, em: 'abc@abc.com' } )`\n *\n * Only caveat is that you have to send an event after this additional init call, otherwise the\n * provided data will not be sent to Facebook.\n */\n fbq(type: 'init', pixelId: PixelId, parameters?: MatchingParameters): void;\n\n /** Enable Manual Only mode. (value = false) */\n fbq(type: 'set', key: 'autoConfig', value: boolean, pixelId: PixelId): void;\n\n fbq<T extends keyof StandardEvents>(\n type: 'track',\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n fbq(\n type: 'trackCustom',\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq<T extends keyof StandardEvents>(\n type: 'trackSingle',\n pixelId: PixelId,\n event: T,\n properties?: StandardEvents[T] & ObjectProperties,\n options?: Options\n ): void;\n\n /** https://developers.facebook.com/docs/meta-pixel/guides/track-multiple-events/ */\n fbq(\n type: 'trackSingleCustom',\n pixelId: PixelId,\n event: string,\n properties?: Record<string, JSONValue> & ObjectProperties,\n options?: Options\n ): void;\n}\n\n/**\n * Please download this CSV filefor examples of properly normalized and hashed data for the\n * parameters below.\n */\nexport function normalize(parameters: MatchingParameters): MatchingParameters {\n return {\n ...parameters,\n em: parameters.em?.toLowerCase().trim(),\n ph: parameters.ph?.replace(/[-+()\\s]/g, '').replace(/^0+/, ''),\n zp: parameters.zp?.split('-').at(0)?.trim(),\n fn: parameters.fn?.toLowerCase().trim(),\n ln: parameters.ln?.toLowerCase().trim(),\n ct: parameters.ct?.toLowerCase().replace(/[\\s/-]/g, ''),\n st: parameters.st?.toLowerCase().replace(/[\\s/,.-]/g, ''),\n country: parameters.country?.toLowerCase().replace(/[\\s/-]/g, ''),\n };\n}\n\nexport function mapItems(items?: Item[]): ObjectProperties {\n if (!items) return {};\n const categories = Array.from(new Set(items.map((i) => i.item_category).filter(Boolean)));\n const contents: Content[] = items.map((item) => {\n const { quantity, price, item_name, item_brand, item_category } = item;\n return {\n id: itemKey(item),\n quantity: quantity ?? 1,\n item_price: price,\n title: item_name,\n brand: item_brand,\n category: item_category,\n };\n });\n\n return {\n content_category: categories.length === 1 ? categories.at(0) : undefined,\n contents,\n content_ids: contents.map((c) => c.id),\n num_items: items.reduce((acc, i) => acc + (i.quantity ?? 1), 0),\n };\n}\n\ntype Mapped<F extends keyof StandardEvents> = ['track', F, StandardEvents[F] & ObjectProperties];\ntype Missed<F extends string> = ['trackCustom', F, Record<string, JSONValue> & ObjectProperties];\n\nexport function mapFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): Mapped<keyof StandardEvents> | Missed<TrackName<T>> {\n if (name === 'add_payment_info') {\n const p = properties as TrackProperties<'add_payment_info'> | undefined;\n return [\n 'track',\n 'AddPaymentInfo',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_cart') {\n const p = properties as TrackProperties<'add_to_cart'> | undefined;\n return [\n 'track',\n 'AddToCart',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'add_to_wishlist') {\n const p = properties as TrackProperties<'add_to_wishlist'> | undefined;\n return [\n 'track',\n 'AddToWishlist',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'sign_up' || name === 'login') {\n const p = properties as TrackProperties<'sign_up' | 'login'> | undefined;\n return ['track', 'CompleteRegistration', { method: p?.method }];\n } else if (name === 'contact') {\n return ['track', 'Contact', {}];\n } else if (name === 'customize_product') {\n return ['track', 'CustomizeProduct', {}];\n } else if (name === 'donate') {\n return ['track', 'Donate', {}];\n } else if (name === 'find_location') {\n return ['track', 'FindLocation', {}];\n } else if (name === 'begin_checkout') {\n const p = properties as TrackProperties<'begin_checkout'> | undefined;\n return [\n 'track',\n 'InitiateCheckout',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else if (name === 'generate_lead') {\n const p = properties as TrackProperties<'generate_lead'> | undefined;\n return ['track', 'Lead', { currency: p?.currency, value: p?.value }];\n } else if (name === 'purchase') {\n const p = properties as TrackProperties<'purchase'> | undefined;\n return [\n 'track',\n 'Purchase',\n { currency: p?.currency ?? 'USD', value: p?.value ?? 0, ...mapItems(p?.items) },\n ];\n } else if (name === 'schedule') {\n return ['track', 'Schedule', {}];\n } else if (name === 'search') {\n const p = properties as TrackProperties<'search'> | undefined;\n return ['track', 'Search', { search_string: p?.search_term }];\n } else if (name === 'trial_begin') {\n const p = properties as TrackProperties<'trial_begin'> | undefined;\n return ['track', 'StartTrial', { currency: p?.currency, value: p?.value }];\n } else if (name === 'submit_application') {\n return ['track', 'SubmitApplication', {}];\n } else if (name === 'subscribe') {\n const p = properties as TrackProperties<'subscribe'> | undefined;\n return ['track', 'Subscribe', { currency: p?.currency, value: p?.value }];\n } else if (name === 'view_item') {\n const p = properties as TrackProperties<'view_item'> | undefined;\n return [\n 'track',\n 'ViewContent',\n { currency: p?.currency, value: p?.value, ...mapItems(p?.items) },\n ];\n } else {\n return ['trackCustom', name, properties ?? {}];\n }\n}\n"],"mappings":";;;;;;AA+UA,SAAgB,UAAU,YAAoD;CAC5E,OAAO;EACL,GAAG;EACH,IAAI,WAAW,IAAI,YAAY,CAAC,CAAC,KAAK;EACtC,IAAI,WAAW,IAAI,QAAQ,aAAa,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE;EAC7D,IAAI,WAAW,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,OAAO,IAAI,SAAS,sBAClB,OAAO;EAAC;EAAS;EAAqB,CAAC;CAAC;MACnC,IAAI,SAAS,aAAa;EAC/B,MAAM,IAAI;EACV,OAAO;GAAC;GAAS;GAAa;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;GAAM;EAAC;CAC1E,OAAO,IAAI,SAAS,aAAa;EAC/B,MAAM,IAAI;EACV,OAAO;GACL;GACA;GACA;IAAE,UAAU,GAAG;IAAU,OAAO,GAAG;IAAO,GAAG,SAAS,GAAG,KAAK;GAAE;EAClE;CACF,OACE,OAAO;EAAC;EAAe;EAAM,cAAc,CAAC;CAAC;AAEjD"}
|
package/dist/track/index.cjs
CHANGED
|
@@ -63,16 +63,16 @@ let timer = null;
|
|
|
63
63
|
* either exists by then or the script is blocked.
|
|
64
64
|
*/
|
|
65
65
|
function firePixels({ event, options }) {
|
|
66
|
-
if (options.enableThirdPartyTracking === false || require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)) return;
|
|
67
|
-
const notReady =
|
|
66
|
+
if (options.enableThirdPartyTracking === false || require_setup_index.config.excludeFromIntegrations.includes(event.name) || require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)) return;
|
|
67
|
+
const notReady = callIntegrations(require_setup_index.config.integrations, event);
|
|
68
68
|
if (notReady.length === 0) return;
|
|
69
|
-
setTimeout(() =>
|
|
69
|
+
setTimeout(() => callIntegrations(notReady, event), 0);
|
|
70
70
|
}
|
|
71
|
-
/**
|
|
72
|
-
function
|
|
73
|
-
return
|
|
71
|
+
/** Hands the event to each integration; returns the ones that said they were not ready. */
|
|
72
|
+
function callIntegrations(integrations, event) {
|
|
73
|
+
return integrations.filter(({ track }) => {
|
|
74
74
|
try {
|
|
75
|
-
return
|
|
75
|
+
return track(event.name, event.properties, event.id) === false;
|
|
76
76
|
} catch (e) {
|
|
77
77
|
if (e instanceof Error) console.log(e.message);
|
|
78
78
|
return false;
|
package/dist/track/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","visitorId","getSession","uuidv7","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { 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,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAOC,oBAAAA,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,EAAE,OAAO,WAAiB;CAG5C,IAAI,QAAQ,6BAA6B,SAASC,qCAAAA,eAAe,SAAS,MAAM,IAAI,GAClF;CAEF,MAAM,WAAW,aAAaF,oBAAAA,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,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;GAC7C,OAAO;EACT;CACF,CAAC;AACH;;;;;AAMA,SAAS,QAAQ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AAK;GAClB;EACF;EACA,MAAM,SAAS,EAAE,OAAO,cAAc,QAAQ,YAAY;GAAE,IAAI,MAAM;GAAI,QAAQ;EAAK,CAAC,CAAC;CAC3F,CAAC;CACD,IAAI,KAAK,SAAS,GAAG,MAAW;AAClC;AAEA,SAAgB,WACd,MACA,YACA;CAGA,MAAM,aAAaI,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAIjB,IAAI,OAAO,CAAC;EAAE,GAAG,QAAQ,UAAU;EAAG,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EAAG;EAAM;CAAW,CAAC,CAAC,GAAG;CAC1E,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","visitorId","getSession","uuidv7","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.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,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAOC,oBAAAA,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,EAAE,OAAO,WAAiB;CAG5C,IACE,QAAQ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,SAAS,OAAO,KAAmC;CAEjD,IAAI,OAAO,cAAc,eAAe,EAAE,gBAAgB,YAAY,OAAO;CAI7E,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,2BAA2B,CAAC;CACjF,OAAO,UAAU,WAAW,GAAGA,oBAAAA,OAAO,SAAS,UAAU,IAAI;AAC/D;;;;;;;;;;;;;AAcA,SAAgB,oBAAoB;CAClC,IAAI,KAAK,WAAW,GAAG;CACvB,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,UAAU;EAC3C,IAAI,CAAC,OAAO,MAAM,KAAK,SAAS,KAAK,KAAK,CAAC,GAAG;GAC5C,KAAK,KAAK,GAAG,KAAK;GAClB;EACF;EACA,MAAM,SAAS,EAAE,OAAO,cAAc,QAAQ,YAAY;GAAE,IAAI,MAAM;GAAI,QAAQ;EAAK,CAAC,CAAC;CAC3F,CAAC;CACD,IAAI,KAAK,SAAS,GAAG,MAAW;AAClC;AAEA,SAAgB,WACd,MACA,YACA;CAGA,MAAM,aAAaI,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAIjB,IAAI,OAAO,CAAC;EAAE,GAAG,QAAQ,UAAU;EAAG,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EAAG;EAAM;CAAW,CAAC,CAAC,GAAG;CAC1E,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";iBAUiB;EACf;;;;;;;EAOA,aAAa,WAAW;IAA+B;;EACvD,WAAW;;;;;;;iBAkDI;EACf;EACA;;;;;;;wBAqIc;;wBAsGA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;;wBA2BK;wBAgBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";iBAUiB;EACf;;;;;;;EAOA,aAAa,WAAW;IAA+B;;EACvD,WAAW;;;;;;;iBAkDI;EACf;EACA;;;;;;;wBAqIc;;wBAsGA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;;wBA2BK;wBAgBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
|
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;C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AAK,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"}
|
|
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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