@shware/analytics 16.3.4 → 16.3.5

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.
Files changed (59) hide show
  1. package/dist/next/index.cjs +2 -1
  2. package/dist/next/index.cjs.map +1 -1
  3. package/dist/next/index.d.cts.map +1 -1
  4. package/dist/next/index.d.mts.map +1 -1
  5. package/dist/next/index.mjs +2 -1
  6. package/dist/next/index.mjs.map +1 -1
  7. package/dist/third-parties/analytics-props.cjs +2 -1
  8. package/dist/third-parties/analytics-props.cjs.map +1 -1
  9. package/dist/third-parties/analytics-props.mjs +2 -1
  10. package/dist/third-parties/analytics-props.mjs.map +1 -1
  11. package/dist/third-parties/index.cjs +1 -0
  12. package/dist/third-parties/index.d.cts +2 -2
  13. package/dist/third-parties/index.d.mts +2 -2
  14. package/dist/third-parties/index.mjs +2 -2
  15. package/dist/third-parties/integration.cjs +31 -0
  16. package/dist/third-parties/integration.cjs.map +1 -1
  17. package/dist/third-parties/integration.d.cts +16 -0
  18. package/dist/third-parties/integration.d.cts.map +1 -1
  19. package/dist/third-parties/integration.d.mts +16 -0
  20. package/dist/third-parties/integration.d.mts.map +1 -1
  21. package/dist/third-parties/integration.mjs +29 -1
  22. package/dist/third-parties/integration.mjs.map +1 -1
  23. package/dist/third-parties/linkedin-insight-tag.cjs +2 -2
  24. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  25. package/dist/third-parties/linkedin-insight-tag.d.cts.map +1 -1
  26. package/dist/third-parties/linkedin-insight-tag.d.mts.map +1 -1
  27. package/dist/third-parties/linkedin-insight-tag.mjs +2 -2
  28. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  29. package/dist/third-parties/meta-pixel.cjs +1 -2
  30. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  31. package/dist/third-parties/meta-pixel.d.cts.map +1 -1
  32. package/dist/third-parties/meta-pixel.d.mts.map +1 -1
  33. package/dist/third-parties/meta-pixel.mjs +2 -3
  34. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  35. package/dist/third-parties/microsoft-uet.cjs +2 -5
  36. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  37. package/dist/third-parties/microsoft-uet.d.cts.map +1 -1
  38. package/dist/third-parties/microsoft-uet.d.mts.map +1 -1
  39. package/dist/third-parties/microsoft-uet.mjs +3 -6
  40. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  41. package/dist/third-parties/openai-pixel.cjs +1 -2
  42. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  43. package/dist/third-parties/openai-pixel.d.cts.map +1 -1
  44. package/dist/third-parties/openai-pixel.d.mts.map +1 -1
  45. package/dist/third-parties/openai-pixel.mjs +2 -3
  46. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  47. package/dist/third-parties/posthog.cjs +2 -2
  48. package/dist/third-parties/posthog.cjs.map +1 -1
  49. package/dist/third-parties/posthog.d.cts.map +1 -1
  50. package/dist/third-parties/posthog.d.mts.map +1 -1
  51. package/dist/third-parties/posthog.mjs +2 -2
  52. package/dist/third-parties/posthog.mjs.map +1 -1
  53. package/dist/third-parties/reddit-pixel.cjs +1 -2
  54. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  55. package/dist/third-parties/reddit-pixel.d.cts.map +1 -1
  56. package/dist/third-parties/reddit-pixel.d.mts.map +1 -1
  57. package/dist/third-parties/reddit-pixel.mjs +2 -3
  58. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  59. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"meta-pixel.mjs","names":[],"sources":["../../src/third-parties/meta-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type FBQ, type PixelId, isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type AdsOptions, type Integration, adEvents, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Meta Pixel script has loaded. */\n fbq?: FBQ['fbq'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n event_id?: string\n) {\n if (typeof window === 'undefined' || !window.fbq) {\n console.warn('fbq 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 options = { eventID: event_id };\n const [type, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n // The two branches are identical on purpose. `fbq` is overloaded per `type` — 'track' takes a\n // standard event name with its typed properties, 'trackCustom' an arbitrary string — and what\n // `mapFBEvent` returns is a union of both shapes. Narrowing `type` is what picks a single\n // overload; collapsing the branches leaves the call matching none of them.\n if (type === 'track') {\n window.fbq(type, fbEventName, fbEventProperties, options);\n } else {\n window.fbq(type, fbEventName, fbEventProperties, options);\n }\n}\n\nexport function setFBUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.fbq) {\n console.warn('fbq has not been initialized');\n return;\n }\n\n const address = getFirst(user_data?.address);\n\n window.fbq('init', pixelId, {\n em: getFirst(user_data?.email),\n fn: address?.first_name,\n ln: address?.last_name,\n ph: getFirst(user_data?.phone_number),\n external_id: user_id,\n ct: address?.city,\n // `st` is Meta's state/province field, not the street address.\n st: address?.region,\n zp: address?.postal_code,\n country: address?.country,\n });\n };\n}\n\n/** Meta Pixel: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`. */\n/** Meta's configuration, shared by `metaAds` in the browser and `metaConversions` on the server. */\nexport interface MetaAdsOptions extends AdsOptions {\n pixelId: PixelId;\n}\n\nexport function metaAds(options: MetaAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),\n setUser: setFBUser(options.pixelId),\n script: {\n id: 'meta-pixel',\n inline: `\n !(function (f, b, e, v, n, t, s) {\n if (f.fbq) return;\n n = f.fbq = function () {\n n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);\n };\n if (!f._fbq) f._fbq = n;\n n.push = n;\n n.loaded = !0;\n n.version = '2.0';\n n.queue = [];\n t = b.createElement(e);\n t.async = !0;\n t.src = v;\n s = b.getElementsByTagName(e)[0];\n s.parentNode.insertBefore(t, s);\n })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');\n fbq('init', ${JSON.stringify(options.pixelId)});\n fbq('track', 'PageView');\n `,\n },\n };\n}\n"],"mappings":";;;;AAaA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,YACd,MACA,YACA,UACA;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,UAAU,EAAE,SAAS,SAAS;CACpC,MAAM,CAAC,MAAM,aAAa,qBAAqB,WAAW,MAAM,UAAU;CAK1E,IAAI,SAAS,SACX,OAAO,IAAI,MAAM,aAAa,mBAAmB,OAAO;MAExD,OAAO,IAAI,MAAM,aAAa,mBAAmB,OAAO;AAE5D;AAEA,SAAgB,UAAU,SAAkB;CAC1C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;GAChD,QAAQ,KAAK,8BAA8B;GAC3C;EACF;EAEA,MAAM,UAAU,SAAS,WAAW,OAAO;EAE3C,OAAO,IAAI,QAAQ,SAAS;GAC1B,IAAI,SAAS,WAAW,KAAK;GAC7B,IAAI,SAAS;GACb,IAAI,SAAS;GACb,IAAI,SAAS,WAAW,YAAY;GACpC,aAAa;GACb,IAAI,SAAS;GAEb,IAAI,SAAS;GACb,IAAI,SAAS;GACb,SAAS,SAAS;EACpB,CAAC;CACH;AACF;AAQA,SAAgB,QAAQ,SAAsC;CAC5D,OAAO;EACL,MAAM;EACN,OAAO,WAAW,aAAa,SAAS,mBAAmB,QAAQ,YAAY,CAAC;EAChF,SAAS,UAAU,QAAQ,OAAO;EAClC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;;;;sBAiBQ,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAGlD;CACF;AACF"}
1
+ {"version":3,"file":"meta-pixel.mjs","names":[],"sources":["../../src/third-parties/meta-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport { type FBQ, type PixelId, isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the Meta Pixel script has loaded. */\n fbq?: FBQ['fbq'];\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendFBEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n event_id?: string\n) {\n if (typeof window === 'undefined' || !window.fbq) {\n console.warn('fbq has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (isLocalHost()) return;\n\n const options = { eventID: event_id };\n const [type, fbEventName, fbEventProperties] = mapFBEvent(name, properties);\n // The two branches are identical on purpose. `fbq` is overloaded per `type` — 'track' takes a\n // standard event name with its typed properties, 'trackCustom' an arbitrary string — and what\n // `mapFBEvent` returns is a union of both shapes. Narrowing `type` is what picks a single\n // overload; collapsing the branches leaves the call matching none of them.\n if (type === 'track') {\n window.fbq(type, fbEventName, fbEventProperties, options);\n } else {\n window.fbq(type, fbEventName, fbEventProperties, options);\n }\n}\n\nexport function setFBUser(pixelId: PixelId) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.fbq) {\n console.warn('fbq has not been initialized');\n return;\n }\n\n const address = getFirst(user_data?.address);\n\n window.fbq('init', pixelId, {\n em: getFirst(user_data?.email),\n fn: address?.first_name,\n ln: address?.last_name,\n ph: getFirst(user_data?.phone_number),\n external_id: user_id,\n ct: address?.city,\n // `st` is Meta's state/province field, not the street address.\n st: address?.region,\n zp: address?.postal_code,\n country: address?.country,\n });\n };\n}\n\n/** Meta Pixel: the events `mapFBEvent` maps to a Meta standard event, and `customEvents`. */\n/** Meta's configuration, shared by `metaAds` in the browser and `metaConversions` on the server. */\nexport interface MetaAdsOptions extends AdsOptions {\n pixelId: PixelId;\n}\n\nexport function metaAds(options: MetaAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendFBEvent, adEvents(isStandardFBEvent, options.customEvents)),\n setUser: setFBUser(options.pixelId),\n script: {\n id: 'meta-pixel',\n inline: `\n !(function (f, b, e, v, n, t, s) {\n if (f.fbq) return;\n n = f.fbq = function () {\n n.callMethod ? n.callMethod.apply(n, arguments) : n.queue.push(arguments);\n };\n if (!f._fbq) f._fbq = n;\n n.push = n;\n n.loaded = !0;\n n.version = '2.0';\n n.queue = [];\n t = b.createElement(e);\n t.async = !0;\n t.src = v;\n s = b.getElementsByTagName(e)[0];\n s.parentNode.insertBefore(t, s);\n })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');\n fbq('init', ${JSON.stringify(options.pixelId)});\n fbq('track', 'PageView');\n `,\n },\n };\n}\n"],"mappings":";;;;AAmBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,YACd,MACA,YACA,UACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;EAChD,QAAQ,KAAK,8BAA8B;EAC3C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,YAAY,GAAG;CAEnB,MAAM,UAAU,EAAE,SAAS,SAAS;CACpC,MAAM,CAAC,MAAM,aAAa,qBAAqB,WAAW,MAAM,UAAU;CAK1E,IAAI,SAAS,SACX,OAAO,IAAI,MAAM,aAAa,mBAAmB,OAAO;MAExD,OAAO,IAAI,MAAM,aAAa,mBAAmB,OAAO;AAE5D;AAEA,SAAgB,UAAU,SAAkB;CAC1C,QAAQ,EAAE,SAAS,gBAAkC;EACnD,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAK;GAChD,QAAQ,KAAK,8BAA8B;GAC3C;EACF;EAEA,MAAM,UAAU,SAAS,WAAW,OAAO;EAE3C,OAAO,IAAI,QAAQ,SAAS;GAC1B,IAAI,SAAS,WAAW,KAAK;GAC7B,IAAI,SAAS;GACb,IAAI,SAAS;GACb,IAAI,SAAS,WAAW,YAAY;GACpC,aAAa;GACb,IAAI,SAAS;GAEb,IAAI,SAAS;GACb,IAAI,SAAS;GACb,SAAS,SAAS;EACpB,CAAC;CACH;AACF;AAQA,SAAgB,QAAQ,SAAsC;CAC5D,OAAO;EACL,MAAM;EACN,OAAO,WAAW,aAAa,SAAS,mBAAmB,QAAQ,YAAY,CAAC;EAChF,SAAS,UAAU,QAAQ,OAAO;EAClC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;;;;sBAiBQ,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAGlD;CACF;AACF"}
@@ -17,9 +17,6 @@ const metrics = [
17
17
  function clean(value) {
18
18
  return JSON.parse(JSON.stringify(value));
19
19
  }
20
- function isLocal() {
21
- return window.location.host.includes("127.0.0.1") || window.location.host.includes("localhost");
22
- }
23
20
  /**
24
21
  * Forward an internal track event to the Microsoft Advertising UET tag.
25
22
  *
@@ -38,7 +35,7 @@ function sendUETEvent(name, properties, eventId) {
38
35
  return false;
39
36
  }
40
37
  if (metrics.includes(name) || name === "page_view") return;
41
- if (isLocal()) return;
38
+ if (require_third_parties_integration.isLocalHost()) return;
42
39
  const [action, params] = require_track_uetq.mapUETEvent(name, properties, eventId);
43
40
  window.uetq.push("event", action, clean(params));
44
41
  }
@@ -119,7 +116,7 @@ async function syncUETVisitor(userId) {
119
116
  }
120
117
  function sendUETIdSync(options) {
121
118
  if (typeof window === "undefined" || typeof Image === "undefined") return;
122
- if (isLocal()) return;
119
+ if (require_third_parties_integration.isLocalHost()) return;
123
120
  const fire = (uid) => {
124
121
  const params = new URLSearchParams({
125
122
  Red3: `BACID_${options.customerId}`,
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-uet.cjs","names":["mapUETEvent","getFirst","visitorId","CONVERSION_EVENTS","adEvents","adsTracker"],"sources":["../../src/third-parties/microsoft-uet.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { type UETConsent, type UETQ, mapUETEvent } from '../track/uetq';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { visitorId } from '../visitor/id';\nimport {\n type AdsOptions,\n CONVERSION_EVENTS,\n type Integration,\n adEvents,\n adsTracker,\n} from './integration';\n\ndeclare global {\n interface Window {\n /**\n * Defined by the UET snippet before `bat.js` loads (as a plain array), so pushes made early\n * are queued rather than lost. Undefined only where the snippet was never installed.\n */\n uetq?: UETQ;\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\n/** Drop `undefined` fields: bat.js validates every key it receives, and `undefined` is a value. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\nfunction isLocal(): boolean {\n return window.location.host.includes('127.0.0.1') || window.location.host.includes('localhost');\n}\n\n/**\n * Forward an internal track event to the Microsoft Advertising UET tag.\n *\n * `eventId` is reused as UET's `event_id` so the browser event deduplicates against the same\n * conversion sent through the Conversions API (`sendMicrosoftEvents`). The action name is the\n * internal name on both channels — see `mapUETEvent`.\n *\n * `page_view` is not forwarded: bat.js turns that action into its page-load beacon, which the\n * snippet already fires on load and, with `enableAutoSpaTracking: true` (the setting in\n * Microsoft's generated snippet), on every history change — forwarding the SDK's own page views\n * would report each page twice. The tag owns page loads; this tracker owns everything else.\n */\nexport function sendUETEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return false;\n }\n if (metrics.includes(name) || name === 'page_view') return;\n if (isLocal()) return;\n\n const [action, params] = mapUETEvent(name, properties, eventId);\n window.uetq.push('event', action, clean(params));\n}\n\n/**\n * Enhanced conversions: hand the tag the visitor's email and phone so Microsoft can match a\n * conversion to an ad click without a third-party cookie. A `set` applies to every event fired\n * from the page afterwards, `pageLoad` included, and the tag fires a `pid` beacon on its own\n * when the page load already went out. Values are sent raw — the tag normalizes and SHA-256\n * hashes them in the browser (bat.js `validatePid`) before anything leaves the page.\n *\n * A setter itself, like `setGAUser`, rather than a factory like `setFBUser(pixelId)`: UET is\n * bound to its tag by the snippet and `set` addresses whichever tag drains `uetq`, so there is\n * nothing to bind first.\n */\nexport function setUETUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return;\n }\n\n // A signed-in user is also the moment the ID Sync pixel can carry a `UID` — see `syncUETVisitor`.\n if (user_id) void syncUETVisitor(user_id);\n\n const em = getFirst(user_data?.email);\n const ph = getFirst(user_data?.phone_number);\n if (!em && !ph) return;\n\n window.uetq.push('set', { pid: clean({ em, ph }) });\n}\n\n/**\n * UET consent mode. Push `default` before the tag loads (the tag processes `consent` early, ahead\n * of the queued events) and `update` when the visitor decides. With `ad_storage: 'denied'` the\n * tag neither writes its cookies nor reads the `msclkid` from the URL.\n * https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\nexport function setUETConsent(mode: 'default' | 'update', consent: UETConsent) {\n if (typeof window === 'undefined') return;\n window.uetq ??= [] as unknown as UETQ;\n window.uetq.push('consent', mode, consent);\n}\n\n/**\n * The Conversions API's client-side ID Sync pixel: ties the visitor id sent server-side as\n * `anonymousId` to Microsoft's own identifier, so server events can be attributed across\n * contexts (view-through, audiences). Microsoft requires it for remarketing built from CAPI\n * events and recommends it for measurement quality; fire it at least once per session, ideally\n * on the first page view. A pixel rather than a fetch on purpose: Microsoft must observe the\n * browser context of the sync, which a server-side call cannot carry.\n *\n * `customerId` is the Microsoft Advertising customer id (`cid` in the UI's URLs) — not the UET\n * tag id. `visitorId` is the SDK visitor id (`visitorId()`), which is what\n * `sendMicrosoftEvents` sends as `anonymousId`; Microsoft requires the two to be equal.\n * `userId` is the raw signed-in user id: it is SHA-256 hashed here, exactly as the server sender\n * hashes it into `externalId`, so the pair matches as well. Hashing is asynchronous, so the\n * pixel fires once the digest resolves; where SubtleCrypto is unavailable (an insecure context)\n * the pixel goes out without `UID` rather than with a raw id.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#id-sync-and-why-it-matters\n */\n/**\n * The Microsoft Advertising customer id the ID Sync pixel reports to, set once by the framework\n * `Analytics` component's `uetCustomerId` prop (or `configureUET`). Unset, nothing syncs.\n */\nlet uetCustomerId: string | undefined;\n\nexport function configureUET(options: { customerId?: string | number }) {\n uetCustomerId = options.customerId === undefined ? undefined : String(options.customerId);\n}\n\n/**\n * Sync the SDK visitor — the `anonymousId` of the events the server sends to the Conversions\n * API — with Microsoft, plus the user's `UID` when one is known. The `Analytics` components run\n * it on mount so every visit syncs at least once, anonymous visitors included (they are who\n * remarketing audiences are built from), and `setUETUser` runs it again on sign-in.\n */\nexport async function syncUETVisitor(userId?: string): Promise<void> {\n if (!uetCustomerId) return;\n sendUETIdSync({ customerId: uetCustomerId, visitorId: visitorId(), userId });\n}\n\nexport function sendUETIdSync(options: {\n customerId: string | number;\n visitorId: string;\n /** The signed-in user's id, raw; hashed before it leaves the page. */\n userId?: string;\n}) {\n if (typeof window === 'undefined' || typeof Image === 'undefined') return;\n if (isLocal()) return;\n\n const fire = (uid?: string) => {\n const params = new URLSearchParams({\n Red3: `BACID_${options.customerId}`,\n VID: options.visitorId,\n });\n if (uid) params.set('UID', uid);\n new Image().src = `https://c.bing.com/c.gif?${params.toString()}`;\n };\n\n if (!options.userId) {\n fire();\n return;\n }\n sha256(options.userId).then(fire, () => fire());\n}\n\n/** What `microsoftAds` returns: an integration that also names the customer id for ID Sync. */\nexport type MicrosoftAdsIntegration = Integration & { readonly uetCustomerId?: `${number}` };\n\n/** The customer id of the `microsoftAds` integration among these, for `useUETIdSync`. */\nexport function uetCustomerIdOf(integrations: readonly Integration[] = []) {\n return integrations.find(\n (integration): integration is MicrosoftAdsIntegration => 'uetCustomerId' in integration\n )?.uetCustomerId;\n}\n\n/**\n * Microsoft Advertising UET. UET has no standard events to map to — a conversion goal is defined\n * on an action name in the ads UI — so it receives an explicit list, the GA4 conversion events\n * by default (`CONVERSION_EVENTS`), plus `customEvents`.\n *\n * Its script is Microsoft's UET snippet with `enableAutoSpaTracking: true` (the tag reports page\n * loads itself), the consent mode default pushed inside it so bat.js reads it before the first\n * page load.\n */\n/** The events UET receives: `events` (the GA4 conversion events by default) and `customEvents`. */\nexport function uetEvents(options: Pick<MicrosoftAdsOptions, 'events' | 'customEvents'>) {\n const events: readonly string[] = options.events ?? CONVERSION_EVENTS;\n return adEvents((name) => events.includes(name), options.customEvents);\n}\n\n/**\n * Microsoft's configuration, shared by `microsoftAds` and `microsoftConversions` on the server.\n */\nexport interface MicrosoftAdsOptions extends AdsOptions {\n tagId: `${number}`;\n /** Microsoft Advertising customer id (`cid` in the ads UI's URLs): enables the ID Sync pixel. */\n customerId?: `${number}`;\n /**\n * The UET consent mode default, `ad_storage: granted` unless given: how the tag behaves\n * without a signal, so Microsoft stops flagging EEA/UK/CH events as missing consent. Sites\n * with a consent banner pass `{ ad_storage: 'denied' }` and send `update` with\n * `setUETConsent`; `false` pushes no default. https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\n consent?: UETConsent | false;\n /** The events UET receives, `CONVERSION_EVENTS` by default; names `track` accepts. */\n events?: readonly TrackName[];\n}\n\nexport function microsoftAds(options: MicrosoftAdsOptions): MicrosoftAdsIntegration {\n const consent = options.consent ?? { ad_storage: 'granted' };\n const defaults = consent ? `w[u].push(\"consent\", \"default\", ${JSON.stringify(consent)});` : '';\n return {\n type: 'ads',\n track: adsTracker(sendUETEvent, uetEvents(options)),\n setUser: setUETUser,\n script: {\n id: 'uet-tag',\n inline: `\n (function (w, d, t, u, o) {\n w[u] = w[u] || [], o.ts = (new Date).getTime();\n ${defaults}\n var n = d.createElement(t);\n n.src = \"https://bat.bing.net/bat.js?ti=\" + o.ti + (\"uetq\" != u ? \"&q=\" + u : \"\"),\n n.async = 1, n.onload = n.onreadystatechange = function() {\n var s = this.readyState;\n s && \"loaded\" !== s && \"complete\" !== s ||\n (o.q = w[u], w[u] = new UET(o), w[u].push(\"pageLoad\"),\n n.onload = n.onreadystatechange = null)\n };\n var i = d.getElementsByTagName(t)[0];\n i.parentNode.insertBefore(n, i);\n })(window, document, \"script\", \"uetq\", {\n ti: ${JSON.stringify(options.tagId)},\n enableAutoSpaTracking: true\n });\n `,\n },\n uetCustomerId: options.customerId,\n };\n}\n"],"mappings":";;;;;;;AAwBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;;AAI1D,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AAEA,SAAS,UAAmB;CAC1B,OAAO,OAAO,SAAS,KAAK,SAAS,WAAW,KAAK,OAAO,SAAS,KAAK,SAAS,WAAW;AAChG;;;;;;;;;;;;;AAcA,SAAgB,aACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,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AAI,KAAK,OAAO,IAAI,OAAO,GAAG;EAC9B,IAAI,MAAM,CAAC,CAAC,MAAM,4BAA4B,OAAO,SAAS;CAChE;CAEA,IAAI,CAAC,QAAQ,QAAQ;EACnB,KAAK;EACL;CACF;CACA,qBAAA,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;AAChD;;AAMA,SAAgB,gBAAgB,eAAuC,CAAC,GAAG;CACzE,OAAO,aAAa,MACjB,gBAAwD,mBAAmB,WAC9E,CAAC,EAAE;AACL;;;;;;;;;;;AAYA,SAAgB,UAAU,SAA+D;CACvF,MAAM,SAA4B,QAAQ,UAAUC,kCAAAA;CACpD,OAAOC,kCAAAA,UAAU,SAAS,OAAO,SAAS,IAAI,GAAG,QAAQ,YAAY;AACvE;AAoBA,SAAgB,aAAa,SAAuD;CAClF,MAAM,UAAU,QAAQ,WAAW,EAAE,YAAY,UAAU;CAC3D,MAAM,WAAW,UAAU,mCAAmC,KAAK,UAAU,OAAO,EAAE,MAAM;CAC5F,OAAO;EACL,MAAM;EACN,OAAOC,kCAAAA,WAAW,cAAc,UAAU,OAAO,CAAC;EAClD,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;YAGF,SAAS;;;;;;;;;;;;gBAYL,KAAK,UAAU,QAAQ,KAAK,EAAE;;;;EAI1C;EACA,eAAe,QAAQ;CACzB;AACF"}
1
+ {"version":3,"file":"microsoft-uet.cjs","names":["isLocalHost","mapUETEvent","getFirst","visitorId","CONVERSION_EVENTS","adEvents","adsTracker"],"sources":["../../src/third-parties/microsoft-uet.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { type UETConsent, type UETQ, mapUETEvent } from '../track/uetq';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { visitorId } from '../visitor/id';\nimport {\n type AdsOptions,\n CONVERSION_EVENTS,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /**\n * Defined by the UET snippet before `bat.js` loads (as a plain array), so pushes made early\n * are queued rather than lost. Undefined only where the snippet was never installed.\n */\n uetq?: UETQ;\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\n/** Drop `undefined` fields: bat.js validates every key it receives, and `undefined` is a value. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the Microsoft Advertising UET tag.\n *\n * `eventId` is reused as UET's `event_id` so the browser event deduplicates against the same\n * conversion sent through the Conversions API (`sendMicrosoftEvents`). The action name is the\n * internal name on both channels — see `mapUETEvent`.\n *\n * `page_view` is not forwarded: bat.js turns that action into its page-load beacon, which the\n * snippet already fires on load and, with `enableAutoSpaTracking: true` (the setting in\n * Microsoft's generated snippet), on every history change — forwarding the SDK's own page views\n * would report each page twice. The tag owns page loads; this tracker owns everything else.\n */\nexport function sendUETEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return false;\n }\n if (metrics.includes(name) || name === 'page_view') return;\n if (isLocalHost()) return;\n\n const [action, params] = mapUETEvent(name, properties, eventId);\n window.uetq.push('event', action, clean(params));\n}\n\n/**\n * Enhanced conversions: hand the tag the visitor's email and phone so Microsoft can match a\n * conversion to an ad click without a third-party cookie. A `set` applies to every event fired\n * from the page afterwards, `pageLoad` included, and the tag fires a `pid` beacon on its own\n * when the page load already went out. Values are sent raw — the tag normalizes and SHA-256\n * hashes them in the browser (bat.js `validatePid`) before anything leaves the page.\n *\n * A setter itself, like `setGAUser`, rather than a factory like `setFBUser(pixelId)`: UET is\n * bound to its tag by the snippet and `set` addresses whichever tag drains `uetq`, so there is\n * nothing to bind first.\n */\nexport function setUETUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return;\n }\n\n // A signed-in user is also the moment the ID Sync pixel can carry a `UID` — see `syncUETVisitor`.\n if (user_id) void syncUETVisitor(user_id);\n\n const em = getFirst(user_data?.email);\n const ph = getFirst(user_data?.phone_number);\n if (!em && !ph) return;\n\n window.uetq.push('set', { pid: clean({ em, ph }) });\n}\n\n/**\n * UET consent mode. Push `default` before the tag loads (the tag processes `consent` early, ahead\n * of the queued events) and `update` when the visitor decides. With `ad_storage: 'denied'` the\n * tag neither writes its cookies nor reads the `msclkid` from the URL.\n * https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\nexport function setUETConsent(mode: 'default' | 'update', consent: UETConsent) {\n if (typeof window === 'undefined') return;\n window.uetq ??= [] as unknown as UETQ;\n window.uetq.push('consent', mode, consent);\n}\n\n/**\n * The Conversions API's client-side ID Sync pixel: ties the visitor id sent server-side as\n * `anonymousId` to Microsoft's own identifier, so server events can be attributed across\n * contexts (view-through, audiences). Microsoft requires it for remarketing built from CAPI\n * events and recommends it for measurement quality; fire it at least once per session, ideally\n * on the first page view. A pixel rather than a fetch on purpose: Microsoft must observe the\n * browser context of the sync, which a server-side call cannot carry.\n *\n * `customerId` is the Microsoft Advertising customer id (`cid` in the UI's URLs) — not the UET\n * tag id. `visitorId` is the SDK visitor id (`visitorId()`), which is what\n * `sendMicrosoftEvents` sends as `anonymousId`; Microsoft requires the two to be equal.\n * `userId` is the raw signed-in user id: it is SHA-256 hashed here, exactly as the server sender\n * hashes it into `externalId`, so the pair matches as well. Hashing is asynchronous, so the\n * pixel fires once the digest resolves; where SubtleCrypto is unavailable (an insecure context)\n * the pixel goes out without `UID` rather than with a raw id.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#id-sync-and-why-it-matters\n */\n/**\n * The Microsoft Advertising customer id the ID Sync pixel reports to, set once by the framework\n * `Analytics` component's `uetCustomerId` prop (or `configureUET`). Unset, nothing syncs.\n */\nlet uetCustomerId: string | undefined;\n\nexport function configureUET(options: { customerId?: string | number }) {\n uetCustomerId = options.customerId === undefined ? undefined : String(options.customerId);\n}\n\n/**\n * Sync the SDK visitor — the `anonymousId` of the events the server sends to the Conversions\n * API — with Microsoft, plus the user's `UID` when one is known. The `Analytics` components run\n * it on mount so every visit syncs at least once, anonymous visitors included (they are who\n * remarketing audiences are built from), and `setUETUser` runs it again on sign-in.\n */\nexport async function syncUETVisitor(userId?: string): Promise<void> {\n if (!uetCustomerId) return;\n sendUETIdSync({ customerId: uetCustomerId, visitorId: visitorId(), userId });\n}\n\nexport function sendUETIdSync(options: {\n customerId: string | number;\n visitorId: string;\n /** The signed-in user's id, raw; hashed before it leaves the page. */\n userId?: string;\n}) {\n if (typeof window === 'undefined' || typeof Image === 'undefined') return;\n if (isLocalHost()) return;\n\n const fire = (uid?: string) => {\n const params = new URLSearchParams({\n Red3: `BACID_${options.customerId}`,\n VID: options.visitorId,\n });\n if (uid) params.set('UID', uid);\n new Image().src = `https://c.bing.com/c.gif?${params.toString()}`;\n };\n\n if (!options.userId) {\n fire();\n return;\n }\n sha256(options.userId).then(fire, () => fire());\n}\n\n/** What `microsoftAds` returns: an integration that also names the customer id for ID Sync. */\nexport type MicrosoftAdsIntegration = Integration & { readonly uetCustomerId?: `${number}` };\n\n/** The customer id of the `microsoftAds` integration among these, for `useUETIdSync`. */\nexport function uetCustomerIdOf(integrations: readonly Integration[] = []) {\n return integrations.find(\n (integration): integration is MicrosoftAdsIntegration => 'uetCustomerId' in integration\n )?.uetCustomerId;\n}\n\n/**\n * Microsoft Advertising UET. UET has no standard events to map to — a conversion goal is defined\n * on an action name in the ads UI — so it receives an explicit list, the GA4 conversion events\n * by default (`CONVERSION_EVENTS`), plus `customEvents`.\n *\n * Its script is Microsoft's UET snippet with `enableAutoSpaTracking: true` (the tag reports page\n * loads itself), the consent mode default pushed inside it so bat.js reads it before the first\n * page load.\n */\n/** The events UET receives: `events` (the GA4 conversion events by default) and `customEvents`. */\nexport function uetEvents(options: Pick<MicrosoftAdsOptions, 'events' | 'customEvents'>) {\n const events: readonly string[] = options.events ?? CONVERSION_EVENTS;\n return adEvents((name) => events.includes(name), options.customEvents);\n}\n\n/**\n * Microsoft's configuration, shared by `microsoftAds` and `microsoftConversions` on the server.\n */\nexport interface MicrosoftAdsOptions extends AdsOptions {\n tagId: `${number}`;\n /** Microsoft Advertising customer id (`cid` in the ads UI's URLs): enables the ID Sync pixel. */\n customerId?: `${number}`;\n /**\n * The UET consent mode default, `ad_storage: granted` unless given: how the tag behaves\n * without a signal, so Microsoft stops flagging EEA/UK/CH events as missing consent. Sites\n * with a consent banner pass `{ ad_storage: 'denied' }` and send `update` with\n * `setUETConsent`; `false` pushes no default. https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\n consent?: UETConsent | false;\n /** The events UET receives, `CONVERSION_EVENTS` by default; names `track` accepts. */\n events?: readonly TrackName[];\n}\n\nexport function microsoftAds(options: MicrosoftAdsOptions): MicrosoftAdsIntegration {\n const consent = options.consent ?? { ad_storage: 'granted' };\n const defaults = consent ? `w[u].push(\"consent\", \"default\", ${JSON.stringify(consent)});` : '';\n return {\n type: 'ads',\n track: adsTracker(sendUETEvent, uetEvents(options)),\n setUser: setUETUser,\n script: {\n id: 'uet-tag',\n inline: `\n (function (w, d, t, u, o) {\n w[u] = w[u] || [], o.ts = (new Date).getTime();\n ${defaults}\n var n = d.createElement(t);\n n.src = \"https://bat.bing.net/bat.js?ti=\" + o.ti + (\"uetq\" != u ? \"&q=\" + u : \"\"),\n n.async = 1, n.onload = n.onreadystatechange = function() {\n var s = this.readyState;\n s && \"loaded\" !== s && \"complete\" !== s ||\n (o.q = w[u], w[u] = new UET(o), w[u].push(\"pageLoad\"),\n n.onload = n.onreadystatechange = null)\n };\n var i = d.getElementsByTagName(t)[0];\n i.parentNode.insertBefore(n, i);\n })(window, document, \"script\", \"uetq\", {\n ti: ${JSON.stringify(options.tagId)},\n enableAutoSp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}
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-uet.d.cts","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"mappings":";;;;QAcQ;YACI;;;;;IAKR,OAAO;;;;;;;;;;;;;;;wBA4BK,aAAa,UAAU,WACrC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;;;;;;wBAwBc,aAAa,SAAS,aAAa;;;;;;;wBAsBnC,cAAc,4BAA4B,SAAS;wBA6BnD,aAAa;EAAW;;;;;;;;wBAUlB,eAAe,kBAAkB;wBAKvC,cAAc;EAC5B;EACA;;EAEA;;;YAsBU,0BAA0B;WAAyB;;;wBAG/C,gBAAgB,wBAAuB;;;;;;;;;;;wBAgBvC,UAAU,SAAS,KAAK,mDAA+C;;;;iBAQtE,4BAA4B;EAC3C;;EAEA;;;;;;;EAOA,UAAU;;EAEV,kBAAkB;;wBAGJ,aAAa,SAAS,sBAAsB"}
1
+ {"version":3,"file":"microsoft-uet.d.cts","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"mappings":";;;;QAeQ;YACI;;;;;IAKR,OAAO;;;;;;;;;;;;;;;wBAwBK,aAAa,UAAU,WACrC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;;;;;;wBAwBc,aAAa,SAAS,aAAa;;;;;;;wBAsBnC,cAAc,4BAA4B,SAAS;wBA6BnD,aAAa;EAAW;;;;;;;;wBAUlB,eAAe,kBAAkB;wBAKvC,cAAc;EAC5B;EACA;;EAEA;;;YAsBU,0BAA0B;WAAyB;;;wBAG/C,gBAAgB,wBAAuB;;;;;;;;;;;wBAgBvC,UAAU,SAAS,KAAK,mDAA+C;;;;iBAQtE,4BAA4B;EAC3C;;EAEA;;;;;;;EAOA,UAAU;;EAEV,kBAAkB;;wBAGJ,aAAa,SAAS,sBAAsB"}
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-uet.d.mts","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"mappings":";;;;QAcQ;YACI;;;;;IAKR,OAAO;;;;;;;;;;;;;;;wBA4BK,aAAa,UAAU,WACrC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;;;;;;wBAwBc,aAAa,SAAS,aAAa;;;;;;;wBAsBnC,cAAc,4BAA4B,SAAS;wBA6BnD,aAAa;EAAW;;;;;;;;wBAUlB,eAAe,kBAAkB;wBAKvC,cAAc;EAC5B;EACA;;EAEA;;;YAsBU,0BAA0B;WAAyB;;;wBAG/C,gBAAgB,wBAAuB;;;;;;;;;;;wBAgBvC,UAAU,SAAS,KAAK,mDAA+C;;;;iBAQtE,4BAA4B;EAC3C;;EAEA;;;;;;;EAOA,UAAU;;EAEV,kBAAkB;;wBAGJ,aAAa,SAAS,sBAAsB"}
1
+ {"version":3,"file":"microsoft-uet.d.mts","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"mappings":";;;;QAeQ;YACI;;;;;IAKR,OAAO;;;;;;;;;;;;;;;wBAwBK,aAAa,UAAU,WACrC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;;;;;;wBAwBc,aAAa,SAAS,aAAa;;;;;;;wBAsBnC,cAAc,4BAA4B,SAAS;wBA6BnD,aAAa;EAAW;;;;;;;;wBAUlB,eAAe,kBAAkB;wBAKvC,cAAc;EAC5B;EACA;;EAEA;;;YAsBU,0BAA0B;WAAyB;;;wBAG/C,gBAAgB,wBAAuB;;;;;;;;;;;wBAgBvC,UAAU,SAAS,KAAK,mDAA+C;;;;iBAQtE,4BAA4B;EAC3C;;EAEA;;;;;;;EAOA,UAAU;;EAEV,kBAAkB;;wBAGJ,aAAa,SAAS,sBAAsB"}
@@ -2,7 +2,7 @@ import { visitorId } from "../visitor/id.mjs";
2
2
  import { mapUETEvent } from "../track/uetq.mjs";
3
3
  import { getFirst } from "../utils/field.mjs";
4
4
  import { sha256 } from "../utils/sha256.mjs";
5
- import { CONVERSION_EVENTS, adEvents, adsTracker } from "./integration.mjs";
5
+ import { CONVERSION_EVENTS, adEvents, adsTracker, isLocalHost } from "./integration.mjs";
6
6
  // src/third-parties/microsoft-uet.ts
7
7
  const metrics = [
8
8
  "CLS",
@@ -16,9 +16,6 @@ const metrics = [
16
16
  function clean(value) {
17
17
  return JSON.parse(JSON.stringify(value));
18
18
  }
19
- function isLocal() {
20
- return window.location.host.includes("127.0.0.1") || window.location.host.includes("localhost");
21
- }
22
19
  /**
23
20
  * Forward an internal track event to the Microsoft Advertising UET tag.
24
21
  *
@@ -37,7 +34,7 @@ function sendUETEvent(name, properties, eventId) {
37
34
  return false;
38
35
  }
39
36
  if (metrics.includes(name) || name === "page_view") return;
40
- if (isLocal()) return;
37
+ if (isLocalHost()) return;
41
38
  const [action, params] = mapUETEvent(name, properties, eventId);
42
39
  window.uetq.push("event", action, clean(params));
43
40
  }
@@ -118,7 +115,7 @@ async function syncUETVisitor(userId) {
118
115
  }
119
116
  function sendUETIdSync(options) {
120
117
  if (typeof window === "undefined" || typeof Image === "undefined") return;
121
- if (isLocal()) return;
118
+ if (isLocalHost()) return;
122
119
  const fire = (uid) => {
123
120
  const params = new URLSearchParams({
124
121
  Red3: `BACID_${options.customerId}`,
@@ -1 +1 @@
1
- {"version":3,"file":"microsoft-uet.mjs","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { type UETConsent, type UETQ, mapUETEvent } from '../track/uetq';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { visitorId } from '../visitor/id';\nimport {\n type AdsOptions,\n CONVERSION_EVENTS,\n type Integration,\n adEvents,\n adsTracker,\n} from './integration';\n\ndeclare global {\n interface Window {\n /**\n * Defined by the UET snippet before `bat.js` loads (as a plain array), so pushes made early\n * are queued rather than lost. Undefined only where the snippet was never installed.\n */\n uetq?: UETQ;\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\n/** Drop `undefined` fields: bat.js validates every key it receives, and `undefined` is a value. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\nfunction isLocal(): boolean {\n return window.location.host.includes('127.0.0.1') || window.location.host.includes('localhost');\n}\n\n/**\n * Forward an internal track event to the Microsoft Advertising UET tag.\n *\n * `eventId` is reused as UET's `event_id` so the browser event deduplicates against the same\n * conversion sent through the Conversions API (`sendMicrosoftEvents`). The action name is the\n * internal name on both channels — see `mapUETEvent`.\n *\n * `page_view` is not forwarded: bat.js turns that action into its page-load beacon, which the\n * snippet already fires on load and, with `enableAutoSpaTracking: true` (the setting in\n * Microsoft's generated snippet), on every history change — forwarding the SDK's own page views\n * would report each page twice. The tag owns page loads; this tracker owns everything else.\n */\nexport function sendUETEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return false;\n }\n if (metrics.includes(name) || name === 'page_view') return;\n if (isLocal()) return;\n\n const [action, params] = mapUETEvent(name, properties, eventId);\n window.uetq.push('event', action, clean(params));\n}\n\n/**\n * Enhanced conversions: hand the tag the visitor's email and phone so Microsoft can match a\n * conversion to an ad click without a third-party cookie. A `set` applies to every event fired\n * from the page afterwards, `pageLoad` included, and the tag fires a `pid` beacon on its own\n * when the page load already went out. Values are sent raw — the tag normalizes and SHA-256\n * hashes them in the browser (bat.js `validatePid`) before anything leaves the page.\n *\n * A setter itself, like `setGAUser`, rather than a factory like `setFBUser(pixelId)`: UET is\n * bound to its tag by the snippet and `set` addresses whichever tag drains `uetq`, so there is\n * nothing to bind first.\n */\nexport function setUETUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return;\n }\n\n // A signed-in user is also the moment the ID Sync pixel can carry a `UID` — see `syncUETVisitor`.\n if (user_id) void syncUETVisitor(user_id);\n\n const em = getFirst(user_data?.email);\n const ph = getFirst(user_data?.phone_number);\n if (!em && !ph) return;\n\n window.uetq.push('set', { pid: clean({ em, ph }) });\n}\n\n/**\n * UET consent mode. Push `default` before the tag loads (the tag processes `consent` early, ahead\n * of the queued events) and `update` when the visitor decides. With `ad_storage: 'denied'` the\n * tag neither writes its cookies nor reads the `msclkid` from the URL.\n * https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\nexport function setUETConsent(mode: 'default' | 'update', consent: UETConsent) {\n if (typeof window === 'undefined') return;\n window.uetq ??= [] as unknown as UETQ;\n window.uetq.push('consent', mode, consent);\n}\n\n/**\n * The Conversions API's client-side ID Sync pixel: ties the visitor id sent server-side as\n * `anonymousId` to Microsoft's own identifier, so server events can be attributed across\n * contexts (view-through, audiences). Microsoft requires it for remarketing built from CAPI\n * events and recommends it for measurement quality; fire it at least once per session, ideally\n * on the first page view. A pixel rather than a fetch on purpose: Microsoft must observe the\n * browser context of the sync, which a server-side call cannot carry.\n *\n * `customerId` is the Microsoft Advertising customer id (`cid` in the UI's URLs) — not the UET\n * tag id. `visitorId` is the SDK visitor id (`visitorId()`), which is what\n * `sendMicrosoftEvents` sends as `anonymousId`; Microsoft requires the two to be equal.\n * `userId` is the raw signed-in user id: it is SHA-256 hashed here, exactly as the server sender\n * hashes it into `externalId`, so the pair matches as well. Hashing is asynchronous, so the\n * pixel fires once the digest resolves; where SubtleCrypto is unavailable (an insecure context)\n * the pixel goes out without `UID` rather than with a raw id.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#id-sync-and-why-it-matters\n */\n/**\n * The Microsoft Advertising customer id the ID Sync pixel reports to, set once by the framework\n * `Analytics` component's `uetCustomerId` prop (or `configureUET`). Unset, nothing syncs.\n */\nlet uetCustomerId: string | undefined;\n\nexport function configureUET(options: { customerId?: string | number }) {\n uetCustomerId = options.customerId === undefined ? undefined : String(options.customerId);\n}\n\n/**\n * Sync the SDK visitor — the `anonymousId` of the events the server sends to the Conversions\n * API — with Microsoft, plus the user's `UID` when one is known. The `Analytics` components run\n * it on mount so every visit syncs at least once, anonymous visitors included (they are who\n * remarketing audiences are built from), and `setUETUser` runs it again on sign-in.\n */\nexport async function syncUETVisitor(userId?: string): Promise<void> {\n if (!uetCustomerId) return;\n sendUETIdSync({ customerId: uetCustomerId, visitorId: visitorId(), userId });\n}\n\nexport function sendUETIdSync(options: {\n customerId: string | number;\n visitorId: string;\n /** The signed-in user's id, raw; hashed before it leaves the page. */\n userId?: string;\n}) {\n if (typeof window === 'undefined' || typeof Image === 'undefined') return;\n if (isLocal()) return;\n\n const fire = (uid?: string) => {\n const params = new URLSearchParams({\n Red3: `BACID_${options.customerId}`,\n VID: options.visitorId,\n });\n if (uid) params.set('UID', uid);\n new Image().src = `https://c.bing.com/c.gif?${params.toString()}`;\n };\n\n if (!options.userId) {\n fire();\n return;\n }\n sha256(options.userId).then(fire, () => fire());\n}\n\n/** What `microsoftAds` returns: an integration that also names the customer id for ID Sync. */\nexport type MicrosoftAdsIntegration = Integration & { readonly uetCustomerId?: `${number}` };\n\n/** The customer id of the `microsoftAds` integration among these, for `useUETIdSync`. */\nexport function uetCustomerIdOf(integrations: readonly Integration[] = []) {\n return integrations.find(\n (integration): integration is MicrosoftAdsIntegration => 'uetCustomerId' in integration\n )?.uetCustomerId;\n}\n\n/**\n * Microsoft Advertising UET. UET has no standard events to map to — a conversion goal is defined\n * on an action name in the ads UI — so it receives an explicit list, the GA4 conversion events\n * by default (`CONVERSION_EVENTS`), plus `customEvents`.\n *\n * Its script is Microsoft's UET snippet with `enableAutoSpaTracking: true` (the tag reports page\n * loads itself), the consent mode default pushed inside it so bat.js reads it before the first\n * page load.\n */\n/** The events UET receives: `events` (the GA4 conversion events by default) and `customEvents`. */\nexport function uetEvents(options: Pick<MicrosoftAdsOptions, 'events' | 'customEvents'>) {\n const events: readonly string[] = options.events ?? CONVERSION_EVENTS;\n return adEvents((name) => events.includes(name), options.customEvents);\n}\n\n/**\n * Microsoft's configuration, shared by `microsoftAds` and `microsoftConversions` on the server.\n */\nexport interface MicrosoftAdsOptions extends AdsOptions {\n tagId: `${number}`;\n /** Microsoft Advertising customer id (`cid` in the ads UI's URLs): enables the ID Sync pixel. */\n customerId?: `${number}`;\n /**\n * The UET consent mode default, `ad_storage: granted` unless given: how the tag behaves\n * without a signal, so Microsoft stops flagging EEA/UK/CH events as missing consent. Sites\n * with a consent banner pass `{ ad_storage: 'denied' }` and send `update` with\n * `setUETConsent`; `false` pushes no default. https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\n consent?: UETConsent | false;\n /** The events UET receives, `CONVERSION_EVENTS` by default; names `track` accepts. */\n events?: readonly TrackName[];\n}\n\nexport function microsoftAds(options: MicrosoftAdsOptions): MicrosoftAdsIntegration {\n const consent = options.consent ?? { ad_storage: 'granted' };\n const defaults = consent ? `w[u].push(\"consent\", \"default\", ${JSON.stringify(consent)});` : '';\n return {\n type: 'ads',\n track: adsTracker(sendUETEvent, uetEvents(options)),\n setUser: setUETUser,\n script: {\n id: 'uet-tag',\n inline: `\n (function (w, d, t, u, o) {\n w[u] = w[u] || [], o.ts = (new Date).getTime();\n ${defaults}\n var n = d.createElement(t);\n n.src = \"https://bat.bing.net/bat.js?ti=\" + o.ti + (\"uetq\" != u ? \"&q=\" + u : \"\"),\n n.async = 1, n.onload = n.onreadystatechange = function() {\n var s = this.readyState;\n s && \"loaded\" !== s && \"complete\" !== s ||\n (o.q = w[u], w[u] = new UET(o), w[u].push(\"pageLoad\"),\n n.onload = n.onreadystatechange = null)\n };\n var i = d.getElementsByTagName(t)[0];\n i.parentNode.insertBefore(n, i);\n })(window, document, \"script\", \"uetq\", {\n ti: ${JSON.stringify(options.tagId)},\n enableAutoSpaTracking: true\n });\n `,\n },\n uetCustomerId: options.customerId,\n };\n}\n"],"mappings":";;;;;;AAwBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;;AAI1D,SAAS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Ac;EAAE,YAAY;EAAe,WAAW,UAAU;EAAG;CAAO,CAAC;AAC7E;AAEA,SAAgB,cAAc,SAK3B;CACD,IAAI,OAAO,WAAW,eAAe,OAAO,UAAU,aAAa;CACnE,IAAI,QAAQ,GAAG;CAEf,MAAM,QAAQ,QAAiB;EAC7B,MAAM,SAAS,IAAI,gBAAgB;GACjC,MAAM,SAAS,QAAQ;GACvB,KAAK,QAAQ;EACf,CAAC;EACD,IAAI,KAAK,OAAO,IAAI,OAAO,GAAG;EAC9B,IAAI,MAAM,CAAC,CAAC,MAAM,4BAA4B,OAAO,SAAS;CAChE;CAEA,IAAI,CAAC,QAAQ,QAAQ;EACnB,KAAK;EACL;CACF;CACA,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,YAAY,KAAK,CAAC;AAChD;;AAMA,SAAgB,gBAAgB,eAAuC,CAAC,GAAG;CACzE,OAAO,aAAa,MACjB,gBAAwD,mBAAmB,WAC9E,CAAC,EAAE;AACL;;;;;;;;;;;AAYA,SAAgB,UAAU,SAA+D;CACvF,MAAM,SAA4B,QAAQ,UAAU;CACpD,OAAO,UAAU,SAAS,OAAO,SAAS,IAAI,GAAG,QAAQ,YAAY;AACvE;AAoBA,SAAgB,aAAa,SAAuD;CAClF,MAAM,UAAU,QAAQ,WAAW,EAAE,YAAY,UAAU;CAC3D,MAAM,WAAW,UAAU,mCAAmC,KAAK,UAAU,OAAO,EAAE,MAAM;CAC5F,OAAO;EACL,MAAM;EACN,OAAO,WAAW,cAAc,UAAU,OAAO,CAAC;EAClD,SAAS;EACT,QAAQ;GACN,IAAI;GACJ,QAAQ;;;YAGF,SAAS;;;;;;;;;;;;gBAYL,KAAK,UAAU,QAAQ,KAAK,EAAE;;;;EAI1C;EACA,eAAe,QAAQ;CACzB;AACF"}
1
+ {"version":3,"file":"microsoft-uet.mjs","names":[],"sources":["../../src/third-parties/microsoft-uet.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { type UETConsent, type UETQ, mapUETEvent } from '../track/uetq';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { visitorId } from '../visitor/id';\nimport {\n type AdsOptions,\n CONVERSION_EVENTS,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /**\n * Defined by the UET snippet before `bat.js` loads (as a plain array), so pushes made early\n * are queued rather than lost. Undefined only where the snippet was never installed.\n */\n uetq?: UETQ;\n }\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\n/** Drop `undefined` fields: bat.js validates every key it receives, and `undefined` is a value. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the Microsoft Advertising UET tag.\n *\n * `eventId` is reused as UET's `event_id` so the browser event deduplicates against the same\n * conversion sent through the Conversions API (`sendMicrosoftEvents`). The action name is the\n * internal name on both channels — see `mapUETEvent`.\n *\n * `page_view` is not forwarded: bat.js turns that action into its page-load beacon, which the\n * snippet already fires on load and, with `enableAutoSpaTracking: true` (the setting in\n * Microsoft's generated snippet), on every history change — forwarding the SDK's own page views\n * would report each page twice. The tag owns page loads; this tracker owns everything else.\n */\nexport function sendUETEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return false;\n }\n if (metrics.includes(name) || name === 'page_view') return;\n if (isLocalHost()) return;\n\n const [action, params] = mapUETEvent(name, properties, eventId);\n window.uetq.push('event', action, clean(params));\n}\n\n/**\n * Enhanced conversions: hand the tag the visitor's email and phone so Microsoft can match a\n * conversion to an ad click without a third-party cookie. A `set` applies to every event fired\n * from the page afterwards, `pageLoad` included, and the tag fires a `pid` beacon on its own\n * when the page load already went out. Values are sent raw — the tag normalizes and SHA-256\n * hashes them in the browser (bat.js `validatePid`) before anything leaves the page.\n *\n * A setter itself, like `setGAUser`, rather than a factory like `setFBUser(pixelId)`: UET is\n * bound to its tag by the snippet and `set` addresses whichever tag drains `uetq`, so there is\n * nothing to bind first.\n */\nexport function setUETUser({ user_id, user_data }: UpdateVisitorDTO) {\n if (typeof window === 'undefined' || !window.uetq) {\n console.warn('uetq has not been initialized');\n return;\n }\n\n // A signed-in user is also the moment the ID Sync pixel can carry a `UID` — see `syncUETVisitor`.\n if (user_id) void syncUETVisitor(user_id);\n\n const em = getFirst(user_data?.email);\n const ph = getFirst(user_data?.phone_number);\n if (!em && !ph) return;\n\n window.uetq.push('set', { pid: clean({ em, ph }) });\n}\n\n/**\n * UET consent mode. Push `default` before the tag loads (the tag processes `consent` early, ahead\n * of the queued events) and `update` when the visitor decides. With `ad_storage: 'denied'` the\n * tag neither writes its cookies nor reads the `msclkid` from the URL.\n * https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\nexport function setUETConsent(mode: 'default' | 'update', consent: UETConsent) {\n if (typeof window === 'undefined') return;\n window.uetq ??= [] as unknown as UETQ;\n window.uetq.push('consent', mode, consent);\n}\n\n/**\n * The Conversions API's client-side ID Sync pixel: ties the visitor id sent server-side as\n * `anonymousId` to Microsoft's own identifier, so server events can be attributed across\n * contexts (view-through, audiences). Microsoft requires it for remarketing built from CAPI\n * events and recommends it for measurement quality; fire it at least once per session, ideally\n * on the first page view. A pixel rather than a fetch on purpose: Microsoft must observe the\n * browser context of the sync, which a server-side call cannot carry.\n *\n * `customerId` is the Microsoft Advertising customer id (`cid` in the UI's URLs) — not the UET\n * tag id. `visitorId` is the SDK visitor id (`visitorId()`), which is what\n * `sendMicrosoftEvents` sends as `anonymousId`; Microsoft requires the two to be equal.\n * `userId` is the raw signed-in user id: it is SHA-256 hashed here, exactly as the server sender\n * hashes it into `externalId`, so the pair matches as well. Hashing is asynchronous, so the\n * pixel fires once the digest resolves; where SubtleCrypto is unavailable (an insecure context)\n * the pixel goes out without `UID` rather than with a raw id.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#id-sync-and-why-it-matters\n */\n/**\n * The Microsoft Advertising customer id the ID Sync pixel reports to, set once by the framework\n * `Analytics` component's `uetCustomerId` prop (or `configureUET`). Unset, nothing syncs.\n */\nlet uetCustomerId: string | undefined;\n\nexport function configureUET(options: { customerId?: string | number }) {\n uetCustomerId = options.customerId === undefined ? undefined : String(options.customerId);\n}\n\n/**\n * Sync the SDK visitor — the `anonymousId` of the events the server sends to the Conversions\n * API — with Microsoft, plus the user's `UID` when one is known. The `Analytics` components run\n * it on mount so every visit syncs at least once, anonymous visitors included (they are who\n * remarketing audiences are built from), and `setUETUser` runs it again on sign-in.\n */\nexport async function syncUETVisitor(userId?: string): Promise<void> {\n if (!uetCustomerId) return;\n sendUETIdSync({ customerId: uetCustomerId, visitorId: visitorId(), userId });\n}\n\nexport function sendUETIdSync(options: {\n customerId: string | number;\n visitorId: string;\n /** The signed-in user's id, raw; hashed before it leaves the page. */\n userId?: string;\n}) {\n if (typeof window === 'undefined' || typeof Image === 'undefined') return;\n if (isLocalHost()) return;\n\n const fire = (uid?: string) => {\n const params = new URLSearchParams({\n Red3: `BACID_${options.customerId}`,\n VID: options.visitorId,\n });\n if (uid) params.set('UID', uid);\n new Image().src = `https://c.bing.com/c.gif?${params.toString()}`;\n };\n\n if (!options.userId) {\n fire();\n return;\n }\n sha256(options.userId).then(fire, () => fire());\n}\n\n/** What `microsoftAds` returns: an integration that also names the customer id for ID Sync. */\nexport type MicrosoftAdsIntegration = Integration & { readonly uetCustomerId?: `${number}` };\n\n/** The customer id of the `microsoftAds` integration among these, for `useUETIdSync`. */\nexport function uetCustomerIdOf(integrations: readonly Integration[] = []) {\n return integrations.find(\n (integration): integration is MicrosoftAdsIntegration => 'uetCustomerId' in integration\n )?.uetCustomerId;\n}\n\n/**\n * Microsoft Advertising UET. UET has no standard events to map to — a conversion goal is defined\n * on an action name in the ads UI — so it receives an explicit list, the GA4 conversion events\n * by default (`CONVERSION_EVENTS`), plus `customEvents`.\n *\n * Its script is Microsoft's UET snippet with `enableAutoSpaTracking: true` (the tag reports page\n * loads itself), the consent mode default pushed inside it so bat.js reads it before the first\n * page load.\n */\n/** The events UET receives: `events` (the GA4 conversion events by default) and `customEvents`. */\nexport function uetEvents(options: Pick<MicrosoftAdsOptions, 'events' | 'customEvents'>) {\n const events: readonly string[] = options.events ?? CONVERSION_EVENTS;\n return adEvents((name) => events.includes(name), options.customEvents);\n}\n\n/**\n * Microsoft's configuration, shared by `microsoftAds` and `microsoftConversions` on the server.\n */\nexport interface MicrosoftAdsOptions extends AdsOptions {\n tagId: `${number}`;\n /** Microsoft Advertising customer id (`cid` in the ads UI's URLs): enables the ID Sync pixel. */\n customerId?: `${number}`;\n /**\n * The UET consent mode default, `ad_storage: granted` unless given: how the tag behaves\n * without a signal, so Microsoft stops flagging EEA/UK/CH events as missing consent. Sites\n * with a consent banner pass `{ ad_storage: 'denied' }` and send `update` with\n * `setUETConsent`; `false` pushes no default. https://help.ads.microsoft.com/#apex/ads/en/60119/1\n */\n consent?: UETConsent | false;\n /** The events UET receives, `CONVERSION_EVENTS` by default; names `track` accepts. */\n events?: readonly TrackName[];\n}\n\nexport function microsoftAds(options: MicrosoftAdsOptions): MicrosoftAdsIntegration {\n const consent = options.consent ?? { ad_storage: 'granted' };\n const defaults = consent ? `w[u].push(\"consent\", \"default\", ${JSON.stringify(consent)});` : '';\n return {\n type: 'ads',\n track: adsTracker(sendUETEvent, uetEvents(options)),\n setUser: setUETUser,\n script: {\n id: 'uet-tag',\n inline: `\n (function (w, d, t, u, o) {\n w[u] = w[u] || [], o.ts = (new Date).getTime();\n ${defaults}\n var n = d.createElement(t);\n n.src = \"https://bat.bing.net/bat.js?ti=\" + o.ti + (\"uetq\" != u ? \"&q=\" + u : \"\"),\n n.async = 1, n.onload = n.onreadystatechange = function() {\n var s = this.readyState;\n s && \"loaded\" !== s && \"complete\" !== s ||\n (o.q = w[u], w[u] = new UET(o), w[u].push(\"pageLoad\"),\n n.onload = n.onreadystatechange = null)\n };\n var i = d.getElementsByTagName(t)[0];\n i.parentNode.insertBefore(n, i);\n })(window, document, \"script\", \"uetq\", {\n ti: ${JSON.stringify(options.tagId)},\n enableAutoSpaTracking: true\n });\n `,\n },\n uetCustomerId: options.customerId,\n };\n}\n"],"mappings":";;;;;;AAyBA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;;AAI1D,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;;;;;;;;AAcA,SAAgB,aACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,KAAK,SAAS,aAAa;CACpD,IAAI,YAAY,GAAG;CAEnB,MAAM,CAAC,QAAQ,UAAU,YAAY,MAAM,YAAY,OAAO;CAC9D,OAAO,KAAK,KAAK,SAAS,QAAQ,MAAM,MAAM,CAAC;AACjD;;;;;;;;;;;;AAaA,SAAgB,WAAW,EAAE,SAAS,aAA+B;CACnE,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C;CACF;CAGA,IAAI,SAAS,eAAoB,OAAO;CAExC,MAAM,KAAK,SAAS,WAAW,KAAK;CACpC,MAAM,KAAK,SAAS,WAAW,YAAY;CAC3C,IAAI,CAAC,MAAM,CAAC,IAAI;CAEhB,OAAO,KAAK,KAAK,OAAO,EAAE,KAAK,MAAM;EAAE;EAAI;CAAG,CAAC,EAAE,CAAC;AACpD;;;;;;;AAQA,SAAgB,cAAc,MAA4B,SAAqB;CAC7E,IAAI,OAAO,WAAW,aAAa;CACnC,OAAO,SAAS,CAAC;CACjB,OAAO,KAAK,KAAK,WAAW,MAAM,OAAO;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;;;;;;;;;gBAYL,KAAK,UAAU,QAAQ,KAAK,EAAE;;;;EAI1C;EACA,eAAe,QAAQ;CACzB;AACF"}
@@ -19,8 +19,7 @@ function sendOpenAIEvent(name, properties, eventId) {
19
19
  return false;
20
20
  }
21
21
  if (require_track_oaiq.NON_AD_EVENTS.includes(name)) return;
22
- if (window.location.host.includes("127.0.0.1")) return;
23
- if (window.location.host.includes("localhost")) return;
22
+ if (require_third_parties_integration.isLocalHost()) return;
24
23
  const { type, data } = require_track_oaiq.mapOAIEvent(name, properties);
25
24
  if (require_track_oaiq.APP_EVENTS.includes(type)) return;
26
25
  if (type === "custom") {
@@ -1 +1 @@
1
- {"version":3,"file":"openai-pixel.cjs","names":["NON_AD_EVENTS","mapOAIEvent","APP_EVENTS","oaiCustomEventName","getFirst","sha256","normalizeOAIPhone","normalizeOAIName","adsTracker","adEvents","isStandardOAIEvent"],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n isStandardOAIEvent,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { type AdsOptions, type Integration, adEvents, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.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, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n\n/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */\n/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */\nexport interface OpenAIAdsOptions extends AdsOptions {\n pixelId: string;\n}\n\nexport function openaiAds(options: OpenAIAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendOpenAIEvent, adEvents(isStandardOAIEvent, options.customEvents)),\n setUser: setOpenAIUser(options.pixelId),\n script: {\n id: 'openai-pixel',\n inline: `\n (function (w, d, s, u) {\n if (w.oaiq) return;\n var q = function () {\n q.q.push(arguments);\n };\n q.q = [];\n w.oaiq = q;\n var js = d.createElement(s);\n js.async = true;\n js.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(js, f);\n })(window, document, \"script\", \"https://bzrcdn.openai.com/sdk/oaiq.min.js\");\n oaiq(\"init\", { pixelId: ${JSON.stringify(options.pixelId)} });\n oaiq(\"measure\", \"page_viewed\", { type: \"contents\" });\n `,\n },\n };\n}\n"],"mappings":";;;;;;;AA0BA,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;AAOA,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAIA,mBAAAA,cAAc,SAAS,IAAI,GAAG;CAClC,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAChD,IAAI,OAAO,SAAS,KAAK,SAAS,WAAW,GAAG;CAEhD,MAAM,EAAE,MAAM,SAASC,mBAAAA,YAAY,MAAM,UAAU;CAEnD,IAAIC,mBAAAA,WAAW,SAAS,IAAa,GAA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AAC,CACC,MAAM,CAAC,cAAc,qBAAqB,oBAAoB,OAAO,UACpE,KAAK;GACH;GACA;GACA;GACA,mBAAmB;GACnB,kBAAkB;EACpB,CAAC,CACH,CAAC,CACA,YAAY,KAAK,CAAC,CAAC,CAAC;CACzB;AACF;AAQA,SAAgB,UAAU,SAAwC;CAChE,OAAO;EACL,MAAM;EACN,OAAOC,kCAAAA,WAAW,iBAAiBC,kCAAAA,SAASC,mBAAAA,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;kCAcoB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAG9D;CACF;AACF"}
1
+ {"version":3,"file":"openai-pixel.cjs","names":["NON_AD_EVENTS","isLocalHost","mapOAIEvent","APP_EVENTS","oaiCustomEventName","getFirst","sha256","normalizeOAIPhone","normalizeOAIName","adsTracker","adEvents","isStandardOAIEvent"],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n isStandardOAIEvent,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.includes(name)) return;\n if (isLocalHost()) return;\n\n const { type, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n\n/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */\n/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */\nexport interface OpenAIAdsOptions extends AdsOptions {\n pixelId: string;\n}\n\nexport function openaiAds(options: OpenAIAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendOpenAIEvent, adEvents(isStandardOAIEvent, options.customEvents)),\n setUser: setOpenAIUser(options.pixelId),\n script: {\n id: 'openai-pixel',\n inline: `\n (function (w, d, s, u) {\n if (w.oaiq) return;\n var q = function () {\n q.q.push(arguments);\n };\n q.q = [];\n w.oaiq = q;\n var js = d.createElement(s);\n js.async = true;\n js.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(js, f);\n })(window, document, \"script\", \"https://bzrcdn.openai.com/sdk/oaiq.min.js\");\n oaiq(\"init\", { pixelId: ${JSON.stringify(options.pixelId)} });\n oaiq(\"measure\", \"page_viewed\", { type: \"contents\" });\n `,\n },\n };\n}\n"],"mappings":";;;;;;;AAgCA,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;AAOA,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAIA,mBAAAA,cAAc,SAAS,IAAI,GAAG;CAClC,IAAIC,kCAAAA,YAAY,GAAG;CAEnB,MAAM,EAAE,MAAM,SAASC,mBAAAA,YAAY,MAAM,UAAU;CAEnD,IAAIC,mBAAAA,WAAW,SAAS,IAAa,GAAG;CACxC,IAAI,SAAS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C,cAAc,qBAAqB,oBAAoB,OAAO,UACpE,KAAK;GACH;GACA;GACA;GACA,mBAAmB;GACnB,kBAAkB;EACpB,CAAC,CACH,CAAC,CACA,YAAY,KAAK,CAAC,CAAC,CAAC;CACzB;AACF;AAQA,SAAgB,UAAU,SAAwC;CAChE,OAAO;EACL,MAAM;EACN,OAAOC,kCAAAA,WAAW,iBAAiBC,kCAAAA,SAASC,mBAAAA,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;kCAcoB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAG9D;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-pixel.d.cts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAiBQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA6Bc,cAAc,qBAAe,SAAA,aACX;;;iBA8CjB,yBAAyB;EACxC;;wBAGc,UAAU,SAAS,mBAAmB"}
1
+ {"version":3,"file":"openai-pixel.d.cts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAuBQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA4Bc,cAAc,qBAAe,SAAA,aACX;;;iBA8CjB,yBAAyB;EACxC;;wBAGc,UAAU,SAAS,mBAAmB"}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-pixel.d.mts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAiBQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA6Bc,cAAc,qBAAe,SAAA,aACX;;;iBA8CjB,yBAAyB;EACxC;;wBAGc,UAAU,SAAS,mBAAmB"}
1
+ {"version":3,"file":"openai-pixel.d.mts","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"mappings":";;;;QAuBQ;YACI;;IAER,OAAO;;;;;;;;wBAeK,gBAAgB,UAAU,WACxC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;;;;;;;wBA4Bc,cAAc,qBAAe,SAAA,aACX;;;iBA8CjB,yBAAyB;EACxC;;wBAGc,UAAU,SAAS,mBAAmB"}
@@ -1,6 +1,6 @@
1
1
  import { getFirst } from "../utils/field.mjs";
2
2
  import { sha256 } from "../utils/sha256.mjs";
3
- import { adEvents, adsTracker } from "./integration.mjs";
3
+ import { adEvents, adsTracker, isLocalHost } from "./integration.mjs";
4
4
  import { APP_EVENTS, NON_AD_EVENTS, isStandardOAIEvent, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
5
5
  // src/third-parties/openai-pixel.ts
6
6
  /** Drop `undefined` fields so the SDK only receives populated values. */
@@ -18,8 +18,7 @@ function sendOpenAIEvent(name, properties, eventId) {
18
18
  return false;
19
19
  }
20
20
  if (NON_AD_EVENTS.includes(name)) return;
21
- if (window.location.host.includes("127.0.0.1")) return;
22
- if (window.location.host.includes("localhost")) return;
21
+ if (isLocalHost()) return;
23
22
  const { type, data } = mapOAIEvent(name, properties);
24
23
  if (APP_EVENTS.includes(type)) return;
25
24
  if (type === "custom") {
@@ -1 +1 @@
1
- {"version":3,"file":"openai-pixel.mjs","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n isStandardOAIEvent,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport { type AdsOptions, type Integration, adEvents, adsTracker } from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.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, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n\n/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */\n/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */\nexport interface OpenAIAdsOptions extends AdsOptions {\n pixelId: string;\n}\n\nexport function openaiAds(options: OpenAIAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendOpenAIEvent, adEvents(isStandardOAIEvent, options.customEvents)),\n setUser: setOpenAIUser(options.pixelId),\n script: {\n id: 'openai-pixel',\n inline: `\n (function (w, d, s, u) {\n if (w.oaiq) return;\n var q = function () {\n q.q.push(arguments);\n };\n q.q = [];\n w.oaiq = q;\n var js = d.createElement(s);\n js.async = true;\n js.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(js, f);\n })(window, document, \"script\", \"https://bzrcdn.openai.com/sdk/oaiq.min.js\");\n oaiq(\"init\", { pixelId: ${JSON.stringify(options.pixelId)} });\n oaiq(\"measure\", \"page_viewed\", { type: \"contents\" });\n `,\n },\n };\n}\n"],"mappings":";;;;;;AA0BA,SAAS,MAAM,OAAqB;CAClC,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;KAAE,GAAG;KAAM,GAAG;IAAO,CAAC;GAAE,CAAC;EAC/D;EAEA,MAAM,QAAQ,UAA+B,QAAQ,OAAO,KAAK,IAAI,KAAA;EACrE,QAAQ,IAAI;GACV,KAAK,KAAK;GACV,KAAK,QAAQ,kBAAkB,KAAK,IAAI,KAAA,CAAS;GACjD,KAAK,SAAS,KAAK,CAAC;GACpB,KAAK,iBAAiB,SAAS,UAAU,CAAC;GAC1C,KAAK,iBAAiB,SAAS,SAAS,CAAC;EAC3C,CAAC,CAAC,CACC,MAAM,CAAC,cAAc,qBAAqB,oBAAoB,OAAO,UACpE,KAAK;GACH;GACA;GACA;GACA,mBAAmB;GACnB,kBAAkB;EACpB,CAAC,CACH,CAAC,CACA,YAAY,KAAK,CAAC,CAAC,CAAC;CACzB;AACF;AAQA,SAAgB,UAAU,SAAwC;CAChE,OAAO;EACL,MAAM;EACN,OAAO,WAAW,iBAAiB,SAAS,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;kCAcoB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAG9D;CACF;AACF"}
1
+ {"version":3,"file":"openai-pixel.mjs","names":[],"sources":["../../src/third-parties/openai-pixel.ts"],"sourcesContent":["import type { UpdateVisitorDTO } from '../schema/index';\nimport {\n APP_EVENTS,\n NON_AD_EVENTS,\n type OAIQ,\n type OAIQUser,\n isStandardOAIEvent,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { sha256 } from '../utils/sha256';\nimport {\n type AdsOptions,\n type Integration,\n adEvents,\n adsTracker,\n isLocalHost,\n} from './integration';\n\ndeclare global {\n interface Window {\n /** Undefined until the OpenAI pixel script has loaded. */\n oaiq?: OAIQ['oaiq'];\n }\n}\n\n/** Drop `undefined` fields so the SDK only receives populated values. */\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction clean(value: unknown): any {\n return JSON.parse(JSON.stringify(value));\n}\n\n/**\n * Forward an internal track event to the OpenAI measurement pixel.\n * `eventId` is reused as the OpenAI `event_id` so browser events deduplicate against the\n * Conversions API. https://developers.openai.com/ads/measurement-pixel\n */\nexport function sendOpenAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n eventId?: string\n) {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return false;\n }\n if (NON_AD_EVENTS.includes(name)) return;\n if (isLocalHost()) return;\n\n const { type, data } = mapOAIEvent(name, properties);\n // OpenAI takes the app events from the Conversions API only.\n if (APP_EVENTS.includes(type as never)) return;\n if (type === 'custom') {\n // Named as the Conversions API names it, so the two deduplicate; skipped when it cannot be.\n const custom_event_name = oaiCustomEventName(name);\n if (!custom_event_name) return;\n window.oaiq('measure', 'custom', clean(data), { event_id: eventId, custom_event_name });\n } else {\n window.oaiq('measure', type, clean(data), { event_id: eventId });\n }\n}\n\n/**\n * Re-initialize the pixel with hashed user identity for better conversion matching. Email, phone,\n * external id and names are normalized as OpenAI documents and hashed client-side; geographic\n * fields are sent raw. Hashing is asynchronous, so the `init` call is deferred until the digests\n * resolve.\n */\nexport function setOpenAIUser(pixelId: string) {\n return ({ user_id, user_data }: UpdateVisitorDTO) => {\n if (typeof window === 'undefined' || !window.oaiq) {\n console.warn('oaiq has not been initialized');\n return;\n }\n // Capture the narrowed reference so the deferred `init` closure keeps it non-optional.\n const oaiq = window.oaiq;\n\n const email = getFirst(user_data?.email)?.trim().toLowerCase() || undefined;\n const phone = getFirst(user_data?.phone_number);\n const address = getFirst(user_data?.address);\n\n const base: OAIQUser = {\n country: address?.country?.trim().toUpperCase(),\n city: address?.city?.trim(),\n region: address?.region?.trim(),\n postal_code: address?.postal_code?.trim(),\n };\n\n const init = (hashed: Partial<OAIQUser>) => {\n oaiq('init', { pixelId, user: clean({ ...base, ...hashed }) });\n };\n\n const hash = (value: string | undefined) => (value ? sha256(value) : undefined);\n Promise.all([\n hash(email),\n hash(phone ? normalizeOAIPhone(phone) : undefined),\n hash(user_id?.trim()),\n hash(normalizeOAIName(address?.first_name)),\n hash(normalizeOAIName(address?.last_name)),\n ])\n .then(([email_sha256, phone_number_sha256, external_id_sha256, first, last]) =>\n init({\n email_sha256,\n phone_number_sha256,\n external_id_sha256,\n first_name_sha256: first,\n last_name_sha256: last,\n })\n )\n .catch(() => init({}));\n };\n}\n\n/** OpenAI measurement pixel: the events `mapOAIEvent` maps to a standard event, and `customEvents`. */\n/** OpenAI's configuration, shared by `openaiAds` and `openaiConversions` on the server. */\nexport interface OpenAIAdsOptions extends AdsOptions {\n pixelId: string;\n}\n\nexport function openaiAds(options: OpenAIAdsOptions): Integration {\n return {\n type: 'ads',\n track: adsTracker(sendOpenAIEvent, adEvents(isStandardOAIEvent, options.customEvents)),\n setUser: setOpenAIUser(options.pixelId),\n script: {\n id: 'openai-pixel',\n inline: `\n (function (w, d, s, u) {\n if (w.oaiq) return;\n var q = function () {\n q.q.push(arguments);\n };\n q.q = [];\n w.oaiq = q;\n var js = d.createElement(s);\n js.async = true;\n js.src = u;\n var f = d.getElementsByTagName(s)[0];\n f.parentNode.insertBefore(js, f);\n })(window, document, \"script\", \"https://bzrcdn.openai.com/sdk/oaiq.min.js\");\n oaiq(\"init\", { pixelId: ${JSON.stringify(options.pixelId)} });\n oaiq(\"measure\", \"page_viewed\", { type: \"contents\" });\n `,\n },\n };\n}\n"],"mappings":";;;;;;AAgCA,SAAS,MAAM,OAAqB;CAClC,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;;;;;;AAOA,SAAgB,gBACd,MACA,YACA,SACA;CACA,IAAI,OAAO,WAAW,eAAe,CAAC,OAAO,MAAM;EACjD,QAAQ,KAAK,+BAA+B;EAC5C,OAAO;CACT;CACA,IAAI,cAAc,SAAS,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,KAAK,iBAAiB,SAAS,SAAS,CAAC;EAC3C,CAAC,CAAC,CACC,MAAM,CAAC,cAAc,qBAAqB,oBAAoB,OAAO,UACpE,KAAK;GACH;GACA;GACA;GACA,mBAAmB;GACnB,kBAAkB;EACpB,CAAC,CACH,CAAC,CACA,YAAY,KAAK,CAAC,CAAC,CAAC;CACzB;AACF;AAQA,SAAgB,UAAU,SAAwC;CAChE,OAAO;EACL,MAAM;EACN,OAAO,WAAW,iBAAiB,SAAS,oBAAoB,QAAQ,YAAY,CAAC;EACrF,SAAS,cAAc,QAAQ,OAAO;EACtC,QAAQ;GACN,IAAI;GACJ,QAAQ;;;;;;;;;;;;;;kCAcoB,KAAK,UAAU,QAAQ,OAAO,EAAE;;;EAG9D;CACF;AACF"}
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_utils_field = require("../utils/field.cjs");
3
+ const require_third_parties_integration = require("./integration.cjs");
3
4
  // src/third-parties/posthog.ts
4
5
  /**
5
6
  * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
@@ -70,8 +71,7 @@ function sendPosthogEvent(name, properties) {
70
71
  return false;
71
72
  }
72
73
  if (metrics.includes(name)) return;
73
- if (window.location.host.includes("127.0.0.1")) return;
74
- if (window.location.host.includes("localhost")) return;
74
+ if (require_third_parties_integration.isLocalHost()) return;
75
75
  posthog.capture(name, properties);
76
76
  }
77
77
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.cjs","names":["getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog 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 posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAAI,SAAe,YAAY;EAC5C,WAAW,SAAS,SAAS;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,SAAS;EAEd,QAAQ,qBAAqB,QAAQ,CAAC;CACxC,CAAC;CACD,O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B,SAYjB;CAGd,MAAM,SAAS,QAAQ,OAAO,SAAS,QAAQ,kBAAkB,uBAAuB;CAIxF,MAAM,QAAQ,UAAmB,KAAK,UAAU,KAAK,CAAC,CAAC,QAAQ,MAAM,SAAS;CAC9E,MAAM,QAAQ,KAAK,UAAU,QAAQ,KAAK;CAC1C,MAAM,EAAE,kBAAkB;CAC1B,IAAI,OAAO,gBAAgB,MAAM,IAAI,KAAK,QAAQ,MAAM,EAAE;CAC1D,IAAI,kBAAkB,KAAA,GAAW;EAC/B,MAAM,WAAW,OAAO,kBAAkB,WAAW,gBAAgB,CAAC;EACtE,MAAM,SAAS;GACb,GAAG,QAAQ;GACX,oBACE,QAAQ,OAAO,uBAAuB,kBAAkB,SAAS,eAAe;EACpF;EACA,MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,SAAS,MAAM;EAC3B,QAAQ;GACN,IAAI;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
1
+ {"version":3,"file":"posthog.cjs","names":["isLocalHost","getFirst"],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type Integration, isLocalHost } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (isLocalHost()) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAAI,SAAe,YAAY;EAC5C,WAAW,SAAS,SAAS;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,SAAS;EAEd,QAAQ,qBAAqB,QAAQ,CAAC;CACxC,CAAC;CACD,OAAO;AACT;AAEA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,iBACd,MACA,YACA;CAIA,I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AAK,UAAU,QAAQ,KAAK;CAC1C,MAAM,EAAE,kBAAkB;CAC1B,IAAI,OAAO,gBAAgB,MAAM,IAAI,KAAK,QAAQ,MAAM,EAAE;CAC1D,IAAI,kBAAkB,KAAA,GAAW;EAC/B,MAAM,WAAW,OAAO,kBAAkB,WAAW,gBAAgB,CAAC;EACtE,MAAM,SAAS;GACb,GAAG,QAAQ;GACX,oBACE,QAAQ,OAAO,uBAAuB,kBAAkB,SAAS,eAAe;EACpF;EACA,MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,SAAS,MAAM;EAC3B,QAAQ;GACN,IAAI;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
1
+ {"version":3,"file":"posthog.d.cts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA2Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA4Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
1
+ {"version":3,"file":"posthog.d.mts","names":["PostHog","PostHogConfig"],"sources":["../../src/third-parties/posthog.ts"],"mappings":";;;;;;;;;;;;;;wBAwBgB,cAAcA;;;;;;;wBAWd,oBAAoBA;;;;;;;;;;;;;;;;;;;wBAyBpB,kBAAkB,qBAAmB;wBAcrC,iBAAiB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB;;;;;;;;;;;wBA2Bf,iBAAiB,SAAS,aAAa,KAAK;;;;;;;;;;wBAsB5C,wBACd,gBACA,aAAa,aACZ;;YAUS,wBAAwB;iBAEnB;;;;;EAKf,wBAAwB;;;;;;;EAOxB,wBAAwB;;;;;;;EAOxB,oBAAoB;;;;;;;;;;;wBA0DN,iBAAiB;EAC/B;EACA,QAAQ,QAAQC;IAAmB;;;;;;;;;;EASnC,0BAA0B;IACxB"}
@@ -1,4 +1,5 @@
1
1
  import { getFirst } from "../utils/field.mjs";
2
+ import { isLocalHost } from "./integration.mjs";
2
3
  // src/third-parties/posthog.ts
3
4
  /**
4
5
  * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):
@@ -69,8 +70,7 @@ function sendPosthogEvent(name, properties) {
69
70
  return false;
70
71
  }
71
72
  if (metrics.includes(name)) return;
72
- if (window.location.host.includes("127.0.0.1")) return;
73
- if (window.location.host.includes("localhost")) return;
73
+ if (isLocalHost()) return;
74
74
  posthog.capture(name, properties);
75
75
  }
76
76
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport type { Integration } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog 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 posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAAI,SAAe,YAAY;EAC5C,WAAW,SAAS,SAAS;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,SAAS;EAEd,QAAQ,qBAAqB,QAAQ,CAAC;CACxC,CAAC;CACD,OAAO;AACT;AAEA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,iBACd,MACA,YACA;CAIA,IAAI,OAAO,aAAa,aAAa;CACrC,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C,OA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B,IAAI,OAAO,gBAAgB,MAAM,IAAI,KAAK,QAAQ,MAAM,EAAE;CAC1D,IAAI,kBAAkB,KAAA,GAAW;EAC/B,MAAM,WAAW,OAAO,kBAAkB,WAAW,gBAAgB,CAAC;EACtE,MAAM,SAAS;GACb,GAAG,QAAQ;GACX,oBACE,QAAQ,OAAO,uBAAuB,kBAAkB,SAAS,eAAe;EACpF;EACA,MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,SAAS,MAAM;EAC3B,QAAQ;GACN,IAAI;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
1
+ {"version":3,"file":"posthog.mjs","names":[],"sources":["../../src/third-parties/posthog.ts"],"sourcesContent":["import type {\n CaptureResult,\n ExceptionAutoCaptureConfig,\n PostHog,\n PostHogConfig,\n Properties,\n} from '@posthog/types';\nimport type { UpdateVisitorDTO } from '../schema/index';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type Integration, isLocalHost } from './integration';\n\nexport type { PostHog, PostHogConfig } from '@posthog/types';\n\n/**\n * `window.posthog`, for calls that return nothing (`capture`, `identify`, `onFeatureFlags`, …):\n * the snippet's stub until the library loads, which queues them and replays them in order once it\n * has. A method that returns a value returns `undefined` on the stub — use `getLoadedPosthog` for\n * those. `undefined` on the server and before the snippet has run.\n *\n * Read off `window` rather than declared on it, so a host that also has `posthog-js`'s own types\n * does not get two conflicting declarations. The types come from `@posthog/types`, PostHog's\n * types-only package for the snippet, so the host installs nothing for them.\n */\nexport function getPosthog(): PostHog | undefined {\n if (typeof document === 'undefined') return undefined;\n return (window as { posthog?: PostHog }).posthog;\n}\n\n/**\n * The PostHog instance once the library has loaded, for the methods that return a value\n * (`getFeatureFlag`, `isFeatureEnabled`, `get_distinct_id`, …); `undefined` while only the stub is\n * there. To act when flags arrive, subscribe with `getPosthog()?.onFeatureFlags` instead, which\n * the stub queues.\n */\nexport function getLoadedPosthog(): PostHog | undefined {\n const posthog = getPosthog();\n return posthog?.__loaded ? posthog : undefined;\n}\n\nlet flagsReady: Promise<void> | undefined;\n\n/**\n * Resolves once PostHog has loaded its feature flags — or after `timeoutMs` (3 s by default),\n * since an ad blocker that stops the library would otherwise hold it forever; read the flags\n * after it with `useFeatureFlagVariantKey` / `getLoadedPosthog`, which are `undefined` in that\n * case. One promise per page, so React's `use()` can suspend on it:\n *\n * ```tsx\n * function Checkout() {\n * use(browser()); // react-dom: the server renders the <Suspense> fallback instead\n * use(posthogFlagsReady());\n * return useFeatureFlagVariantKey('new-checkout') === 'test' ? <NewCheckout /> : <OldCheckout />;\n * }\n * ```\n *\n * Waiting shows the fallback until the flags are in, instead of the default then the variant;\n * with server-evaluated flags in `config.bootstrap` it resolves as soon as the library loads.\n * Browser only: it never resolves on the server.\n */\nexport function posthogFlagsReady(timeoutMs = 3000): Promise<void> {\n if (typeof document === 'undefined') return new Promise(() => {});\n flagsReady ??= new Promise<void>((resolve) => {\n setTimeout(resolve, timeoutMs);\n const posthog = getPosthog();\n if (!posthog) return;\n // Queued on the stub; once loaded, called as soon as flags are (or already were) in.\n posthog.onFeatureFlags(() => resolve());\n });\n return flagsReady;\n}\n\nconst metrics = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'];\n\nexport function sendPosthogEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // `document`, not `window`: React Native defines `window` as an alias of `global`, so a\n // window check would pass there and then throw on `window.location`, which it has no such\n // alias for.\n if (typeof document === 'undefined') return;\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return false;\n }\n if (metrics.includes(name)) return;\n if (isLocalHost()) return;\n\n posthog.capture(name, properties);\n}\n\n/**\n * Identifies the visitor to PostHog as the signed-in user, by the user's id — the server's\n * `distinct_id` for the visitor once someone has signed in on it. Only a user: identifying an\n * anonymous visitor by its own id would make PostHog treat it as an identified person, and\n * PostHog does not merge one identified person into another when the user later signs in, so the\n * pre-sign-in events would stay split off.\n *\n * Without a user it is sign-out (`reset()`): PostHog's identity is reset, so the next person on\n * this page starts anonymous instead of merging into the one who left.\n */\nexport function setPosthogUser({ user_id, user_data }: Omit<UpdateVisitorDTO, 'tags'>) {\n const posthog = getPosthog();\n if (!posthog) {\n console.warn('posthog has not been initialized');\n return;\n }\n if (!user_id) {\n posthog.reset();\n return;\n }\n posthog.identify(user_id, { email: getFirst(user_data?.email) });\n}\n\n/**\n * Sends an error to PostHog's error tracking (`captureException`), as `sendPosthogEvent` does an\n * event: queued on the snippet's stub until the library loads, so it can be called from anywhere\n * at any time — an http client's error hook, a `catch` that recovers but should still be known.\n * Returns the `$exception` event, `undefined` while only the stub is there (or without PostHog).\n *\n * Never throws: reporting an error must not become a second one where it is called. The\n * `errorTracking` filter of `posthogAnalytics` applies, as to every exception.\n */\nexport function capturePosthogException(\n error: unknown,\n properties?: Properties\n): CaptureResult | undefined {\n try {\n return getPosthog()?.captureException(error, properties);\n } catch (e: unknown) {\n console.error('capturePosthogException: the error was not reported', e);\n return undefined;\n }\n}\n\n/** A substring of what it is matched against, or a regular expression tested on it. */\nexport type ErrorPattern = string | RegExp;\n\nexport interface PosthogErrorTrackingOptions {\n /**\n * The library's exception autocapture: window errors and unhandled rejections, on by default.\n * The same as `config.capture_exceptions`, which wins when both are set.\n */\n autocapture?: boolean | ExceptionAutoCaptureConfig;\n /**\n * Exceptions not sent, as Sentry's `ignoreErrors`: matched against `Type: message` and the\n * message alone of each error in the chain (`$exception_list`), e.g. `'UET is not defined'` for an\n * ad blocker stubbing a tag. Errors thrown by browser extensions need no entry: PostHog drops them\n * itself (`error_tracking.captureExtensionExceptions`).\n */\n ignoreErrors?: readonly ErrorPattern[];\n /**\n * Exceptions not sent by where they were thrown, as Sentry's `denyUrls`: matched against the\n * file of the error's innermost frame, e.g. `'/gsi/client'` for Google One Tap's own minified\n * errors, whose messages change with every build. An error of yours that only passed through\n * such a script (a callback it called) is still sent.\n */\n denyUrls?: readonly ErrorPattern[];\n}\n\n/**\n * A pattern as JSON: a regular expression by its source and flags, rebuilt in the snippet. `g`\n * and `y` are dropped: they make `test` resume from the last match, so one rule would match the\n * same message only every other time.\n */\ntype SerializedPattern = string | { source: string; flags: string };\n\nfunction serializePatterns(patterns: readonly ErrorPattern[] = []): SerializedPattern[] {\n return patterns.map((p) =>\n typeof p === 'string' ? p : { source: p.source, flags: p.flags.replace(/[gy]/g, '') }\n );\n}\n\n/**\n * The snippet's `before_send`, as source: `config` goes to `posthog.init` as JSON, which drops\n * functions, so the filter is written into the inline script instead — in place from the first\n * event, with no window before the app's bundle could install it. ES5, as the rest of the snippet.\n * Called with the rules (`off`, `errors`, `urls`); returns the `before_send` function.\n */\nconst EXCEPTION_FILTER = `function(r){\n function compile(ps){var o=[];for(var i=0;i<ps.length;i++){var p=ps[i];o.push(typeof p===\"string\"?p:new RegExp(p.source,p.flags))}return o}\n function any(ps,t){if(!t)return false;for(var i=0;i<ps.length;i++){var p=ps[i];if(typeof p===\"string\"?t.indexOf(p)!==-1:p.test(t))return true}return false}\n var errors=compile(r.errors),urls=compile(r.urls);\n return function(e){\n if(!e||e.event!==\"$exception\")return e;\n if(r.off)return null;\n var l=(e.properties&&e.properties.$exception_list)||[];\n for(var i=0;i<l.length;i++){var x=l[i]||{},v=x.value||\"\";if(any(errors,x.type?x.type+\": \"+v:v)||any(errors,v))return null}\n var f=l[0]&&l[0].stacktrace&&l[0].stacktrace.frames,u=f&&f.length?f[f.length-1].filename:\"\";\n return any(urls,u)?null:e;\n };\n}`;\n\n/**\n * The origin to preconnect to, or none for a relative URL (a reverse proxy on the site's own\n * origin). `new URL` in a try rather than `URL.canParse`, which Safari before 17 and Chrome before\n * 120 lack: this runs while the app sets up its analytics, where a throw takes the page down.\n */\nfunction originOf(url: string): string[] {\n try {\n return [new URL(url).origin];\n } catch {\n return [];\n }\n}\n\n/**\n * PostHog: every event, for behavior analysis. Loaded with PostHog's HTML snippet, which defines\n * a stub `window.posthog` and fetches the library (`array.js`) asynchronously from PostHog's\n * assets host, so it stays out of the app's bundle; calls made before it loads are queued.\n *\n * `config` is serialized into the snippet's `posthog.init` call, so only its JSON survives:\n * `api_host`, `defaults`, `bootstrap` (server-evaluated flags, so an experiment renders its variant\n * without a flicker), and the other plain options — functions such as `loaded` are dropped.\n */\nexport function posthogAnalytics(options: {\n token: `phc_${string}`;\n config: Partial<PostHogConfig> & { api_host: string };\n /**\n * PostHog's error tracking. `true` or options turn on exception autocapture and filter what is\n * sent (`ignoreErrors`, `denyUrls`); `false` sends no exception at all, autocaptured or\n * reported (`capturePosthogException`, `PosthogErrorBoundary`, `setupPosthogReactErrorHandler`) — for\n * local development, which would otherwise fill the production project's issues. Left out, the\n * library's own `config` decides, as before. Each exception carries the session id, so its issue\n * links to the session's replay.\n */\n errorTracking?: boolean | PosthogErrorTrackingOptions;\n}): Integration {\n // Where the snippet loads `array.js` from, by its own rule; a relative `api_host` (a reverse\n // proxy on the site's origin) needs no preconnect.\n const assets = options.config.api_host.replace('.i.posthog.com', '-assets.i.posthog.com');\n // `<` escaped: `config` is arbitrary JSON (a `bootstrap` can carry user data, a pattern any\n // text), and a `</script>` inside it would end this inline script early. `\\u003c` parses back\n // to the same value.\n const json = (value: unknown) => JSON.stringify(value).replace(/</g, '\\\\u003c');\n const token = JSON.stringify(options.token);\n const { errorTracking } = options;\n let init = `posthog.init(${token}, ${json(options.config)});`;\n if (errorTracking !== undefined) {\n const tracking = typeof errorTracking === 'object' ? errorTracking : {};\n const config = {\n ...options.config,\n capture_exceptions:\n options.config.capture_exceptions ?? (errorTracking && (tracking.autocapture ?? true)),\n };\n const rules = {\n off: !errorTracking,\n errors: serializePatterns(tracking.ignoreErrors),\n urls: serializePatterns(tracking.denyUrls),\n };\n // In a function, so `c` does not become a global of this classic script.\n init = `!function(){var c=${json(config)};c.before_send=(${EXCEPTION_FILTER})(${json(rules)});posthog.init(${token}, c)}();`;\n }\n return {\n type: 'analytics',\n track: sendPosthogEvent,\n setUser: setPosthogUser,\n preconnect: originOf(assets),\n script: {\n id: 'posthog-snippet',\n // The stub must exist before hydration, whose effects already track (`page_view`) and\n // identify; it is a few lines, and `array.js` still loads async. PostHog's own Next example\n // does the same. The snippet is PostHog's current one, verbatim\n // (posthog.com/docs/error-tracking/installation/web): it leaves an already loaded library in\n // place, inserts `array.js` once, and retries it on the next `init` if it failed to load.\n strategy: 'beforeInteractive',\n inline: `\n !function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(\".\");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement(\"script\")).type=\"text/javascript\",p.crossOrigin=\"anonymous\",p.async=!0,p.src=s.api_host.replace(\".i.posthog.com\",\"-assets.i.posthog.com\")+\"/static/array.js\",p.onerror=function(){p=null},(r=t.getElementsByTagName(\"script\")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a=\"posthog\",u.people=u.people||[],Object.defineProperty(u,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e=\"posthog\";return\"posthog\"!==a&&(e+=\".\"+a),t||(e+=\" (stub)\"),e}}),Object.defineProperty(u.people,\"toString\",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+\".people (stub)\"}}),o=\"init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug\".split(\" \"),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);\n ${init}\n `,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAgB,aAAkC;CAChD,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAC5C,OAAQ,OAAiC;AAC3C;;;;;;;AAQA,SAAgB,mBAAwC;CACtD,MAAM,UAAU,WAAW;CAC3B,OAAO,SAAS,WAAW,UAAU,KAAA;AACvC;AAEA,IAAI;;;;;;;;;;;;;;;;;;;AAoBJ,SAAgB,kBAAkB,YAAY,KAAqB;CACjE,IAAI,OAAO,aAAa,aAAa,OAAO,IAAI,cAAc,CAAC,CAAC;CAChE,eAAe,IAAI,SAAe,YAAY;EAC5C,WAAW,SAAS,SAAS;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,SAAS;EAEd,QAAQ,qBAAqB,QAAQ,CAAC;CACxC,CAAC;CACD,OAAO;AACT;AAEA,MAAM,UAAU;CAAC;CAAO;CAAO;CAAO;CAAO;CAAO;AAAM;AAE1D,SAAgB,iBACd,MACA,YACA;CAIA,IAAI,OAAO,aAAa,aAAa;CACrC,MAAM,UAAU,WAAW;CAC3B,IAAI,CAAC,SAAS;EACZ,QAAQ,KAAK,kCAAkC;EAC/C,OAAO;CACT;CACA,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,IAAI,YAAY,GAAG;CAEnB,QAAQ,QAAQ,MAAM,UAAU;AAClC;;;;;;;;;;;AAYA,SAAg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AO,uBAAuB,kBAAkB,SAAS,eAAe;EACpF;EACA,MAAM,QAAQ;GACZ,KAAK,CAAC;GACN,QAAQ,kBAAkB,SAAS,YAAY;GAC/C,MAAM,kBAAkB,SAAS,QAAQ;EAC3C;EAEA,OAAO,qBAAqB,KAAK,MAAM,EAAE,kBAAkB,iBAAiB,IAAI,KAAK,KAAK,EAAE,iBAAiB,MAAM;CACrH;CACA,OAAO;EACL,MAAM;EACN,OAAO;EACP,SAAS;EACT,YAAY,SAAS,MAAM;EAC3B,QAAQ;GACN,IAAI;GAMJ,UAAU;GACV,QAAQ;;UAEJ,KAAK;;EAEX;CACF;AACF"}
@@ -17,8 +17,7 @@ function sendRedditEvent(name, properties, eventId) {
17
17
  return false;
18
18
  }
19
19
  if (metrics.includes(name)) return;
20
- if (window.location.host.includes("127.0.0.1")) return;
21
- if (window.location.host.includes("localhost")) return;
20
+ if (require_third_parties_integration.isLocalHost()) return;
22
21
  const [type, params] = require_track_rdt.mapRDTEvent(name, properties, eventId);
23
22
  if (type === "Custom") window.rdt("track", type, JSON.parse(JSON.stringify(params)));
24
23
  else window.rdt("track", type, JSON.parse(JSON.stringify(params)));