@shware/analytics 16.3.6 → 16.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +10 -4
  2. package/dist/native/fingerprint.cjs +6 -1
  3. package/dist/native/fingerprint.cjs.map +1 -1
  4. package/dist/native/fingerprint.d.cts +5 -0
  5. package/dist/native/fingerprint.d.cts.map +1 -1
  6. package/dist/native/fingerprint.d.mts +5 -0
  7. package/dist/native/fingerprint.d.mts.map +1 -1
  8. package/dist/native/fingerprint.mjs +6 -1
  9. package/dist/native/fingerprint.mjs.map +1 -1
  10. package/dist/native/setup.cjs +2 -2
  11. package/dist/native/setup.cjs.map +1 -1
  12. package/dist/native/setup.mjs +2 -2
  13. package/dist/native/setup.mjs.map +1 -1
  14. package/dist/server/linkedin-conversions-api.cjs +9 -3
  15. package/dist/server/linkedin-conversions-api.cjs.map +1 -1
  16. package/dist/server/linkedin-conversions-api.d.cts +3 -1
  17. package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
  18. package/dist/server/linkedin-conversions-api.d.mts +3 -1
  19. package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
  20. package/dist/server/linkedin-conversions-api.mjs +9 -3
  21. package/dist/server/linkedin-conversions-api.mjs.map +1 -1
  22. package/dist/server/meta-capi.cjs +5 -1
  23. package/dist/server/meta-capi.cjs.map +1 -1
  24. package/dist/server/meta-capi.d.cts.map +1 -1
  25. package/dist/server/meta-capi.d.mts.map +1 -1
  26. package/dist/server/meta-capi.mjs +5 -1
  27. package/dist/server/meta-capi.mjs.map +1 -1
  28. package/dist/server/setup-conversions.cjs +1 -1
  29. package/dist/server/setup-conversions.cjs.map +1 -1
  30. package/dist/server/setup-conversions.d.cts +19 -3
  31. package/dist/server/setup-conversions.d.cts.map +1 -1
  32. package/dist/server/setup-conversions.d.mts +19 -3
  33. package/dist/server/setup-conversions.d.mts.map +1 -1
  34. package/dist/server/setup-conversions.mjs +1 -1
  35. package/dist/server/setup-conversions.mjs.map +1 -1
  36. package/dist/track/index.cjs +4 -4
  37. package/dist/track/index.cjs.map +1 -1
  38. package/dist/track/index.mjs +4 -4
  39. package/dist/track/index.mjs.map +1 -1
  40. package/dist/web/index.cjs +2 -2
  41. package/dist/web/index.cjs.map +1 -1
  42. package/dist/web/index.mjs +2 -2
  43. package/dist/web/index.mjs.map +1 -1
  44. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"meta-capi.cjs","names":["ParamBuilder","createHash","PII_DATA_TYPE","metaFbc","metaFbp","mapFBEvent","eventTimeMs","resolveActionSource","pageLocation","IGNORED_EVENTS","fetch","ConversionsApiError","conversionDestination","adEvents","isStandardFBEvent"],"sources":["../../src/server/meta-capi.ts"],"sourcesContent":["/**\n * Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, which\n * replaced the sender built on the 31MB `facebook-nodejs-business-sdk`, since removed, with\n * ~0.5MB of parameter building.\n *\n * The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`\n * produces — enforced by a differential test that runs both builders over the same events.\n * Where the two libraries normalize differently (the business SDK keeps punctuation in names,\n * spaces in multi-word last names, accents in cities; the param builder strips them per the\n * current documented rules), this module follows the business SDK so that switching senders\n * cannot change a single hash Meta receives. The param builder is used where the two provably\n * agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)\n * is stripped for the same reason.\n *\n * Two deliberate behavior differences from the business SDK, both on invalid input only:\n * an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from\n * user_data instead of throwing inside `execute()` and costing the whole batch; an invalid\n * currency is uppercased and forwarded instead of rejected. Valid input is unaffected.\n *\n * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { PII_DATA_TYPE, ParamBuilder } from 'capi-param-builder-nodejs';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { MetaAdsOptions } from '../third-parties/meta-pixel';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { metaFbc, metaFbp } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { eventTimeMs } from './event-time';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/** Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). */\nconst API_VERSION = 'v24.0';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\n/**\n * Lazy for the same reason as the session and the token bucket (see setup/session.ts):\n * Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.\n */\nlet paramBuilder: ParamBuilder | undefined;\n\n/**\n * Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the\n * business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's\n * endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as\n * it does in the business SDK.\n */\nfunction pii(value: string | undefined, dataType: string): string | undefined {\n if (!value) return undefined;\n const built = (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType);\n return built?.split('.').at(0) ?? undefined;\n}\n\nconst SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;\n\n/**\n * The business SDK's `normalizeAndHash` for the fields where the param builder normalizes\n * differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,\n * apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the\n * differential test can hold the outputs equal.\n */\nfunction hashed(\n input: string | undefined,\n rule: (lowered: string) => string | undefined\n): string | undefined {\n if (!input) return undefined;\n const lowered = input.trim().toLowerCase();\n if (!lowered) return undefined;\n if (SHA256_OR_MD5.test(lowered)) return lowered;\n const normalized = rule(lowered);\n if (normalized === undefined) return undefined;\n return createHash('sha256').update(normalized).digest('hex');\n}\n\nconst nameRule = (v: string) => v;\nconst f5Rule = (v: string) => (v.length <= 5 ? v : v.slice(0, 5));\nconst cityStateRule = (v: string) => v.replace(/[0-9\\s().-]/g, '');\nconst zipRule = (v: string) => {\n const zip = v.replace(/\\s/g, '').split('-', 1)[0];\n return zip.length < 2 ? undefined : zip;\n};\n\n/**\n * Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each\n * through `dedupArray` (a Set), `external_id` included.\n */\nconst dedupe = (hashes: (string | undefined)[]) =>\n Array.from(new Set(hashes.filter((hash): hash is string => hash !== undefined)));\n\nconst list = (hashes: (string | undefined)[]) => {\n const deduped = dedupe(hashes);\n return deduped.length > 0 ? deduped : undefined;\n};\n\ninterface CapiUserData {\n em?: string[];\n ph?: string[];\n ge?: string[];\n fn?: string[];\n ln?: string[];\n ct?: string[];\n st?: string[];\n zp?: string[];\n country?: string[];\n external_id?: string[];\n client_ip_address?: string;\n client_user_agent?: string;\n fbc?: string;\n fbp?: string;\n fb_login_id?: string;\n page_id?: string;\n f5first?: string;\n f5last?: string;\n dobd?: string;\n dobm?: string;\n doby?: string;\n madid?: string;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number): CapiUserData {\n const userData: CapiUserData = {};\n\n if (data.email) {\n const emails = Array.isArray(data.email) ? data.email : [data.email];\n userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));\n }\n if (data.phone_number) {\n const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];\n userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));\n }\n if (data.gender === 'female' || data.gender === 'male') {\n userData.ge = list([pii(data.gender === 'female' ? 'f' : 'm', PII_DATA_TYPE.GENDER)]);\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n // The SDK sets these lists unconditionally in the multi-address branch, so an all-empty\n // column still goes out as `[]` — kept for byte-equality with the current sender.\n userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));\n userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));\n userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));\n userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));\n userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));\n userData.country = dedupe(\n data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY))\n );\n } else {\n userData.fn = list([hashed(data.address.first_name, nameRule)]);\n userData.ln = list([hashed(data.address.last_name, nameRule)]);\n userData.ct = list([hashed(data.address.city, cityStateRule)]);\n userData.st = list([hashed(data.address.region, cityStateRule)]);\n userData.zp = list([hashed(data.address.postal_code, zipRule)]);\n userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);\n // The 5-character prefixes, exactly as the current sender builds them: sliced first, then\n // normalized. Only the single-address branch sets them, as before.\n userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);\n userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);\n }\n }\n if (data.birthday) {\n const { year, month, day } = data.birthday;\n if (/^\\d{4}$/.test(year.toString())) {\n userData.doby = createHash('sha256').update(year.toString()).digest('hex');\n }\n if (month >= 1 && month <= 12) {\n userData.dobm = createHash('sha256').update(month.toString().padStart(2, '0')).digest('hex');\n }\n if (day >= 1 && day <= 31) {\n userData.dobd = createHash('sha256').update(day.toString().padStart(2, '0')).digest('hex');\n }\n }\n if (data.user_id && data.user_id.length !== 0) {\n // Unhashed, as the business SDK sends it. Meta documents hashing as recommended, not\n // required; changing it here would break continuity with every event sent so far.\n userData.external_id = [data.user_id];\n }\n if (data.ip_address) {\n userData.client_ip_address = data.ip_address;\n }\n if (data.user_agent) {\n userData.client_user_agent = data.user_agent;\n }\n if (data.fb_login_id) {\n userData.fb_login_id = data.fb_login_id;\n }\n if (data.fb_page_id) {\n userData.page_id = data.fb_page_id;\n }\n\n const fbc = metaFbc(tags, eventTimeMs);\n if (fbc) {\n userData.fbc = fbc;\n }\n const fbp = metaFbp(tags);\n if (fbp) {\n userData.fbp = fbp;\n }\n if (tags.advertising_id) {\n userData.madid = tags.advertising_id;\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.client_ip_address = tags.ip_address;\n }\n\n return userData;\n}\n\nconst DELIVERY_CATEGORIES = ['in_store', 'curbside', 'home_delivery'];\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>): Record<string, unknown> {\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n predicted_ltv,\n num_items,\n search_string,\n status,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n\n const customData: Record<string, unknown> = {};\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null && Number.isFinite(Number.parseFloat(String(value)))) {\n customData.value = Number.parseFloat(String(value));\n }\n if (currency) {\n // The business SDK also validates against the ISO 4217 list and throws; here an unknown\n // code is forwarded uppercased rather than costing the batch.\n customData.currency = currency\n .trim()\n .toUpperCase()\n .replace(/[^A-Z]/g, '');\n }\n if (content_name) customData.content_name = content_name;\n if (content_category) customData.content_category = content_category;\n if (content_ids) customData.content_ids = content_ids;\n if (contents) {\n customData.contents = contents.map((c) => {\n const content: Record<string, unknown> = {};\n if (c.id) content.id = c.id;\n if (c.quantity) content.quantity = c.quantity;\n if (c.item_price) content.item_price = c.item_price;\n if (c.title) content.title = c.title;\n if (c.description) content.description = c.description;\n if (c.brand) content.brand = c.brand;\n if (c.category) content.category = c.category;\n const delivery = c.delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;\n return content;\n });\n }\n if (content_type) customData.content_type = content_type;\n if (predicted_ltv) customData.predicted_ltv = predicted_ltv;\n if (num_items) customData.num_items = num_items;\n if (search_string) customData.search_string = search_string;\n if (status) customData.status = status.toString();\n const delivery = delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;\n\n return { ...customData, ...custom_properties };\n}\n\n/**\n * `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset\n * indexes out when it serializes; the documented 16-element array is what the Graph endpoint\n * decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS\n * version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.\n */\n/**\n * The `extinfo` version of an app event's OS — `i2` for iOS, `a2` for Android, the only two Meta\n * documents. Undefined for any other OS (a desktop app): such an event cannot carry the\n * `app_data` an app event requires, and is sent as `other`.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/app-events\n */\nexport function metaExtinfoVersion(tags: TrackTags): 'i2' | 'a2' | undefined {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') return 'i2';\n if (tags.os_name === 'Android') return 'a2';\n return undefined;\n}\n\nfunction getAppData(\n tags: TrackTags,\n appPackageName: string,\n version: 'i2' | 'a2'\n): Record<string, unknown> {\n const extinfo: Record<number, string | number> = {};\n extinfo[0] = version;\n extinfo[1] = appPackageName;\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) extinfo[2] = shortVersion;\n if (tags.release) extinfo[3] = tags.release;\n if (tags.os_version) extinfo[4] = tags.os_version;\n if (tags.device_model_id) extinfo[5] = tags.device_model_id;\n if (tags.language) extinfo[6] = tags.language;\n if (tags.screen_width) extinfo[9] = tags.screen_width;\n if (tags.screen_height) extinfo[10] = tags.screen_height;\n if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();\n\n // Required on every app event. An advertising id is only readable once the user allowed\n // tracking (ATT on iOS, the ad id setting on Android), so its presence is the answer.\n const appData: Record<string, unknown> = {\n extinfo,\n advertiser_tracking_enabled: !!tags.advertising_id,\n };\n if (tags.install_referrer) appData.install_referrer = tags.install_referrer;\n return appData;\n}\n\n/** One entry of the `data` array POSTed to `/{pixel_id}/events`. */\nexport interface CapiEvent {\n event_name: string;\n event_time: number;\n event_id: string;\n event_source_url?: string;\n action_source: 'app' | 'website' | 'other';\n user_data: CapiUserData;\n custom_data: Record<string, unknown>;\n app_data?: Record<string, unknown>;\n}\n\n/**\n * `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a\n * website, and everything else — including a backend-built offline conversion, which should\n * declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK\n * sender put an explicit `'offline'` too.\n */\nexport function getCapiEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string\n): CapiEvent {\n const eventTime = eventTimeMs(event.created_at);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const source = resolveActionSource(event.platform);\n const version = metaExtinfoVersion(event.tags);\n const app =\n source === 'app' && appPackageName && version\n ? { packageName: appPackageName, version }\n : undefined;\n\n const capiEvent: CapiEvent = {\n event_name: eventName,\n event_time: Math.round(eventTime / 1000),\n event_id: event.tags.idempotency_key ?? event.id,\n // `action_source` is required; an offline conversion and an undeterminable platform both\n // land in Meta's catch-all, exactly as in the business-SDK sender. So does an app event that\n // cannot carry the `app_data` Meta requires of one: no package name, or a desktop OS.\n action_source: app ? 'app' : source === 'web' ? 'website' : 'other',\n user_data: getUserData(event.tags, data, eventTime),\n custom_data: getCustomData(event),\n };\n if (app) {\n capiEvent.app_data = getAppData(event.tags, app.packageName, app.version);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n capiEvent.event_source_url = eventSourceUrl;\n }\n return capiEvent;\n}\n\nexport interface MetaConversionsOptions {\n /** Attaches `app_data`/extinfo to events whose platform resolves to an app. */\n appPackageName?: string;\n /** Routes the batch to Events Manager's Test Events tab instead of production. */\n testEventCode?: string;\n /** Graph API version, e.g. 'v24.0'. */\n apiVersion?: string;\n}\n\nexport interface MetaConversionsResponse {\n events_received?: number;\n messages?: string[];\n fbtrace_id?: string;\n}\n\n/**\n * An `event_time` over 7 days old fails the whole request — \"we return an error for the entire\n * request and process no events\" — so such an event is left out; a minute's margin for the trip.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Sends the events to Meta's Conversions API. Rejects on a failed request — a\n * `ConversionsApiError`, or the fetch error — for the caller to handle. The token travels in the\n * JSON body, never in the URL, and is in neither error.\n */\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MetaConversionsOptions = {}\n): Promise<MetaConversionsResponse | undefined> {\n const capiEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getCapiEvent(event, data, options.appPackageName));\n if (capiEvents.length === 0) return undefined;\n // \"The client_user_agent is required for website events\" — sent from `data.user_agent`.\n if (!data.user_agent && capiEvents.some((event) => event.action_source === 'website')) {\n console.warn(\n 'Meta conversion: website events sent without client_user_agent (data.user_agent)'\n );\n }\n\n const version = options.apiVersion ?? API_VERSION;\n const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({\n data: capiEvents,\n test_event_code: options.testEventCode,\n access_token: accessToken,\n }),\n });\n if (response.ok) return (await response.json()) as MetaConversionsResponse;\n throw new ConversionsApiError('meta', response.status, await response.text());\n}\n\n/**\n * Meta's Conversions API, sent the same events as `metaAds` in the browser: the ones Meta maps to\n * a standard event, and `customEvents`.\n */\nexport function metaConversions(\n options: MetaAdsOptions & MetaConversionsOptions & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardFBEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,cAAc;AAEpB,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY;CACxD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,wBAAwB,SAAS,OAAO,IAAI,KAAA,IAAY;AACjE;;;;;AAMA,IAAI;;;;;;;AAQJ,SAAS,IAAI,OAA2B,UAAsC;CAC5E,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,QADe,iBAAiB,IAAIA,0BAAAA,aAAa,EAAA,CAAG,0BAA0B,OAAO,QAC1E,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,KAAA;AACpC;AAEA,MAAM,gBAAgB;;;;;;;AAQtB,SAAS,OACP,OACA,MACoB;CACpB,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY;CACzC,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,cAAc,KAAK,OAAO,GAAG,OAAO;CACxC,MAAM,aAAa,KAAK,OAAO;CAC/B,IAAI,eAAe,KAAA,GAAW,OAAO,KAAA;CACrC,QAAA,GAAOC,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK;AAC7D;AAEA,MAAM,YAAY,MAAc;AAChC,MAAM,UAAU,MAAe,EAAE,UAAU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AA,mBAAmB,QAAQ,YAAY,IAAI,QAAQ,SACvF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,OAAO,CACxE;AACF"}
1
+ {"version":3,"file":"meta-capi.cjs","names":["ParamBuilder","createHash","PII_DATA_TYPE","metaFbc","metaFbp","mapFBEvent","eventTimeMs","resolveActionSource","pageLocation","IGNORED_EVENTS","fetch","ConversionsApiError","conversionDestination","adEvents","isStandardFBEvent"],"sources":["../../src/server/meta-capi.ts"],"sourcesContent":["/**\n * Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, which\n * replaced the sender built on the 31MB `facebook-nodejs-business-sdk`, since removed, with\n * ~0.5MB of parameter building.\n *\n * The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`\n * produces — enforced by a differential test that runs both builders over the same events.\n * Where the two libraries normalize differently (the business SDK keeps punctuation in names,\n * spaces in multi-word last names, accents in cities; the param builder strips them per the\n * current documented rules), this module follows the business SDK so that switching senders\n * cannot change a single hash Meta receives. The param builder is used where the two provably\n * agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)\n * is stripped for the same reason.\n *\n * Two deliberate behavior differences from the business SDK, both on invalid input only:\n * an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from\n * user_data instead of throwing inside `execute()` and costing the whole batch; an invalid\n * currency is uppercased and forwarded instead of rejected. Valid input is unaffected.\n *\n * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { PII_DATA_TYPE, ParamBuilder } from 'capi-param-builder-nodejs';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { MetaAdsOptions } from '../third-parties/meta-pixel';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { metaFbc, metaFbp } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { eventTimeMs } from './event-time';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/**\n * Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). Meta\n * keeps each Graph API version for about two years from its release, then requests to it fail,\n * so this must be bumped with each release (or overridden through `apiVersion`).\n */\nconst API_VERSION = 'v24.0';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\n/**\n * Lazy for the same reason as the session and the token bucket (see setup/session.ts):\n * Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.\n */\nlet paramBuilder: ParamBuilder | undefined;\n\n/**\n * Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the\n * business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's\n * endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as\n * it does in the business SDK.\n */\nfunction pii(value: string | undefined, dataType: string): string | undefined {\n if (!value) return undefined;\n const built = (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType);\n return built?.split('.').at(0) ?? undefined;\n}\n\nconst SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;\n\n/**\n * The business SDK's `normalizeAndHash` for the fields where the param builder normalizes\n * differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,\n * apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the\n * differential test can hold the outputs equal.\n */\nfunction hashed(\n input: string | undefined,\n rule: (lowered: string) => string | undefined\n): string | undefined {\n if (!input) return undefined;\n const lowered = input.trim().toLowerCase();\n if (!lowered) return undefined;\n if (SHA256_OR_MD5.test(lowered)) return lowered;\n const normalized = rule(lowered);\n if (normalized === undefined) return undefined;\n return createHash('sha256').update(normalized).digest('hex');\n}\n\nconst nameRule = (v: string) => v;\nconst f5Rule = (v: string) => (v.length <= 5 ? v : v.slice(0, 5));\nconst cityStateRule = (v: string) => v.replace(/[0-9\\s().-]/g, '');\nconst zipRule = (v: string) => {\n const zip = v.replace(/\\s/g, '').split('-', 1)[0];\n return zip.length < 2 ? undefined : zip;\n};\n\n/**\n * Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each\n * through `dedupArray` (a Set), `external_id` included.\n */\nconst dedupe = (hashes: (string | undefined)[]) =>\n Array.from(new Set(hashes.filter((hash): hash is string => hash !== undefined)));\n\nconst list = (hashes: (string | undefined)[]) => {\n const deduped = dedupe(hashes);\n return deduped.length > 0 ? deduped : undefined;\n};\n\ninterface CapiUserData {\n em?: string[];\n ph?: string[];\n ge?: string[];\n fn?: string[];\n ln?: string[];\n ct?: string[];\n st?: string[];\n zp?: string[];\n country?: string[];\n external_id?: string[];\n client_ip_address?: string;\n client_user_agent?: string;\n fbc?: string;\n fbp?: string;\n fb_login_id?: string;\n page_id?: string;\n f5first?: string;\n f5last?: string;\n dobd?: string;\n dobm?: string;\n doby?: string;\n madid?: string;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number): CapiUserData {\n const userData: CapiUserData = {};\n\n if (data.email) {\n const emails = Array.isArray(data.email) ? data.email : [data.email];\n userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));\n }\n if (data.phone_number) {\n const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];\n userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));\n }\n if (data.gender === 'female' || data.gender === 'male') {\n userData.ge = list([pii(data.gender === 'female' ? 'f' : 'm', PII_DATA_TYPE.GENDER)]);\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n // The SDK sets these lists unconditionally in the multi-address branch, so an all-empty\n // column still goes out as `[]` — kept for byte-equality with the current sender.\n userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));\n userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));\n userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));\n userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));\n userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));\n userData.country = dedupe(\n data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY))\n );\n } else {\n userData.fn = list([hashed(data.address.first_name, nameRule)]);\n userData.ln = list([hashed(data.address.last_name, nameRule)]);\n userData.ct = list([hashed(data.address.city, cityStateRule)]);\n userData.st = list([hashed(data.address.region, cityStateRule)]);\n userData.zp = list([hashed(data.address.postal_code, zipRule)]);\n userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);\n // The 5-character prefixes, exactly as the current sender builds them: sliced first, then\n // normalized. Only the single-address branch sets them, as before.\n userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);\n userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);\n }\n }\n if (data.birthday) {\n const { year, month, day } = data.birthday;\n if (/^\\d{4}$/.test(year.toString())) {\n userData.doby = createHash('sha256').update(year.toString()).digest('hex');\n }\n if (month >= 1 && month <= 12) {\n userData.dobm = createHash('sha256').update(month.toString().padStart(2, '0')).digest('hex');\n }\n if (day >= 1 && day <= 31) {\n userData.dobd = createHash('sha256').update(day.toString().padStart(2, '0')).digest('hex');\n }\n }\n if (data.user_id && data.user_id.length !== 0) {\n // Unhashed, as the business SDK sends it. Meta documents hashing as recommended, not\n // required; changing it here would break continuity with every event sent so far.\n userData.external_id = [data.user_id];\n }\n if (data.ip_address) {\n userData.client_ip_address = data.ip_address;\n }\n if (data.user_agent) {\n userData.client_user_agent = data.user_agent;\n }\n if (data.fb_login_id) {\n userData.fb_login_id = data.fb_login_id;\n }\n if (data.fb_page_id) {\n userData.page_id = data.fb_page_id;\n }\n\n const fbc = metaFbc(tags, eventTimeMs);\n if (fbc) {\n userData.fbc = fbc;\n }\n const fbp = metaFbp(tags);\n if (fbp) {\n userData.fbp = fbp;\n }\n if (tags.advertising_id) {\n userData.madid = tags.advertising_id;\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.client_ip_address = tags.ip_address;\n }\n\n return userData;\n}\n\nconst DELIVERY_CATEGORIES = ['in_store', 'curbside', 'home_delivery'];\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>): Record<string, unknown> {\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n predicted_ltv,\n num_items,\n search_string,\n status,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n\n const customData: Record<string, unknown> = {};\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null && Number.isFinite(Number.parseFloat(String(value)))) {\n customData.value = Number.parseFloat(String(value));\n }\n if (currency) {\n // The business SDK also validates against the ISO 4217 list and throws; here an unknown\n // code is forwarded uppercased rather than costing the batch.\n customData.currency = currency\n .trim()\n .toUpperCase()\n .replace(/[^A-Z]/g, '');\n }\n if (content_name) customData.content_name = content_name;\n if (content_category) customData.content_category = content_category;\n if (content_ids) customData.content_ids = content_ids;\n if (contents) {\n customData.contents = contents.map((c) => {\n const content: Record<string, unknown> = {};\n if (c.id) content.id = c.id;\n if (c.quantity) content.quantity = c.quantity;\n if (c.item_price) content.item_price = c.item_price;\n if (c.title) content.title = c.title;\n if (c.description) content.description = c.description;\n if (c.brand) content.brand = c.brand;\n if (c.category) content.category = c.category;\n const delivery = c.delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;\n return content;\n });\n }\n if (content_type) customData.content_type = content_type;\n if (predicted_ltv) customData.predicted_ltv = predicted_ltv;\n if (num_items) customData.num_items = num_items;\n if (search_string) customData.search_string = search_string;\n if (status) customData.status = status.toString();\n const delivery = delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;\n\n return { ...customData, ...custom_properties };\n}\n\n/**\n * `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset\n * indexes out when it serializes; the documented 16-element array is what the Graph endpoint\n * decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS\n * version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.\n */\n/**\n * The `extinfo` version of an app event's OS — `i2` for iOS, `a2` for Android, the only two Meta\n * documents. Undefined for any other OS (a desktop app): such an event cannot carry the\n * `app_data` an app event requires, and is sent as `other`.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/app-events\n */\nexport function metaExtinfoVersion(tags: TrackTags): 'i2' | 'a2' | undefined {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') return 'i2';\n if (tags.os_name === 'Android') return 'a2';\n return undefined;\n}\n\nfunction getAppData(\n tags: TrackTags,\n appPackageName: string,\n version: 'i2' | 'a2'\n): Record<string, unknown> {\n const extinfo: Record<number, string | number> = {};\n extinfo[0] = version;\n extinfo[1] = appPackageName;\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) extinfo[2] = shortVersion;\n if (tags.release) extinfo[3] = tags.release;\n if (tags.os_version) extinfo[4] = tags.os_version;\n if (tags.device_model_id) extinfo[5] = tags.device_model_id;\n if (tags.language) extinfo[6] = tags.language;\n if (tags.screen_width) extinfo[9] = tags.screen_width;\n if (tags.screen_height) extinfo[10] = tags.screen_height;\n if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();\n\n // Required on every app event. An advertising id is only readable once the user allowed\n // tracking (ATT on iOS, the ad id setting on Android), so its presence is the answer.\n const appData: Record<string, unknown> = {\n extinfo,\n advertiser_tracking_enabled: !!tags.advertising_id,\n };\n if (tags.install_referrer) appData.install_referrer = tags.install_referrer;\n return appData;\n}\n\n/** One entry of the `data` array POSTed to `/{pixel_id}/events`. */\nexport interface CapiEvent {\n event_name: string;\n event_time: number;\n event_id: string;\n event_source_url?: string;\n action_source: 'app' | 'website' | 'other';\n user_data: CapiUserData;\n custom_data: Record<string, unknown>;\n app_data?: Record<string, unknown>;\n}\n\n/**\n * `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a\n * website, and everything else — including a backend-built offline conversion, which should\n * declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK\n * sender put an explicit `'offline'` too.\n */\nexport function getCapiEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string\n): CapiEvent {\n const eventTime = eventTimeMs(event.created_at);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const source = resolveActionSource(event.platform);\n const version = metaExtinfoVersion(event.tags);\n const app =\n source === 'app' && appPackageName && version\n ? { packageName: appPackageName, version }\n : undefined;\n\n const capiEvent: CapiEvent = {\n event_name: eventName,\n event_time: Math.round(eventTime / 1000),\n event_id: event.tags.idempotency_key ?? event.id,\n // `action_source` is required; an offline conversion and an undeterminable platform both\n // land in Meta's catch-all, exactly as in the business-SDK sender. So does an app event that\n // cannot carry the `app_data` Meta requires of one: no package name, or a desktop OS.\n action_source: app ? 'app' : source === 'web' ? 'website' : 'other',\n user_data: getUserData(event.tags, data, eventTime),\n custom_data: getCustomData(event),\n };\n if (app) {\n capiEvent.app_data = getAppData(event.tags, app.packageName, app.version);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n capiEvent.event_source_url = eventSourceUrl;\n }\n return capiEvent;\n}\n\nexport interface MetaConversionsOptions {\n /** Attaches `app_data`/extinfo to events whose platform resolves to an app. */\n appPackageName?: string;\n /** Routes the batch to Events Manager's Test Events tab instead of production. */\n testEventCode?: string;\n /** Graph API version, e.g. 'v24.0'. */\n apiVersion?: string;\n}\n\nexport interface MetaConversionsResponse {\n events_received?: number;\n messages?: string[];\n fbtrace_id?: string;\n}\n\n/**\n * An `event_time` over 7 days old fails the whole request — \"we return an error for the entire\n * request and process no events\" — so such an event is left out; a minute's margin for the trip.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Sends the events to Meta's Conversions API. Rejects on a failed request — a\n * `ConversionsApiError`, or the fetch error — for the caller to handle. The token travels in the\n * JSON body, never in the URL, and is in neither error.\n */\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MetaConversionsOptions = {}\n): Promise<MetaConversionsResponse | undefined> {\n const capiEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getCapiEvent(event, data, options.appPackageName));\n if (capiEvents.length === 0) return undefined;\n // \"The client_user_agent is required for website events\" — sent from `data.user_agent`.\n if (!data.user_agent && capiEvents.some((event) => event.action_source === 'website')) {\n console.warn(\n 'Meta conversion: website events sent without client_user_agent (data.user_agent)'\n );\n }\n\n const version = options.apiVersion ?? API_VERSION;\n const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({\n data: capiEvents,\n test_event_code: options.testEventCode,\n access_token: accessToken,\n }),\n });\n if (response.ok) return (await response.json()) as MetaConversionsResponse;\n throw new ConversionsApiError('meta', response.status, await response.text());\n}\n\n/**\n * Meta's Conversions API, sent the same events as `metaAds` in the browser: the ones Meta maps to\n * a standard event, and `customEvents`.\n */\nexport function metaConversions(\n options: MetaAdsOptions & MetaConversionsOptions & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardFBEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,cAAc;AAEpB,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY;CACxD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,wBAAwB,SAAS,OAAO,IAAI,KAAA,IAAY;AACjE;;;;;AAMA,IAAI;;;;;;;AAQJ,SAAS,IAAI,OAA2B,UAAsC;CAC5E,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,QADe,iBAAiB,IAAIA,0BAAAA,aAAa,EAAA,CAAG,0BAA0B,OAAO,QAC1E,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,KAAA;AACpC;AAEA,MAAM,gBAAgB;;;;;;;AAQtB,SAAS,OACP,OACA,MACoB;CACpB,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,MAAM,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY;CACzC,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,cAAc,KAAK,OAAO,GAAG,OAAO;CACxC,MAAM,aAAa,KAAK,OAAO;CAC/B,IAAI,eAAe,KAAA,GAAW,OAAO,KAAA;CACrC,QAAA,GAAOC,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK;AAC7D;AAEA,MAAM,YAAY,MAAc;AAChC,MAAM,UAAU,MAAe,EAAE,UAAU,IAAI,IAAI,EAAE,MAAM,GAAG,CAAC;AAC/D,MAAM,iBAAiB,MAAc,EAAE,QAAQ,gBAAgB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AAM,OAAO,CACxE;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"meta-capi.d.cts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UA0GU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}
1
+ {"version":3,"file":"meta-capi.d.cts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UA8GU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}
@@ -1 +1 @@
1
- {"version":3,"file":"meta-capi.d.mts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UA0GU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}
1
+ {"version":3,"file":"meta-capi.d.mts","names":[],"sources":["../../src/server/meta-capi.ts"],"mappings":";;;UA8GU;EACR;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;wBAqKc,mBAAmB,MAAM;;iBAmCxB;EACf;EACA;EACA;EACA;EACA;EACA,WAAW;EACX,aAAa;EACb,WAAW;;;;;;;;wBASG,aAEd,OAAO,iBACP,MAAM,kBACN,0BACC;iBA+Bc;;EAEf;;EAEA;;EAEA;;iBAGe;EACf;EACA;EACA;;;;;;;wBAeoB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,yBACR,QAAQ;;;;;wBAiCK,gBACd,SAAS,iBAAiB;EAA2B;IACpD"}
@@ -33,7 +33,11 @@ import { PII_DATA_TYPE, ParamBuilder } from "capi-param-builder-nodejs";
33
33
  * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api
34
34
  * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters
35
35
  */
36
- /** Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). */
36
+ /**
37
+ * Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). Meta
38
+ * keeps each Graph API version for about two years from its release, then requests to it fail,
39
+ * so this must be bumped with each release (or overridden through `apiVersion`).
40
+ */
37
41
  const API_VERSION = "v24.0";
38
42
  const USER_ASSIGNED_COUNTRIES = ["xk"];
39
43
  function normalizeCountry(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"meta-capi.mjs","names":[],"sources":["../../src/server/meta-capi.ts"],"sourcesContent":["/**\n * Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, which\n * replaced the sender built on the 31MB `facebook-nodejs-business-sdk`, since removed, with\n * ~0.5MB of parameter building.\n *\n * The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`\n * produces — enforced by a differential test that runs both builders over the same events.\n * Where the two libraries normalize differently (the business SDK keeps punctuation in names,\n * spaces in multi-word last names, accents in cities; the param builder strips them per the\n * current documented rules), this module follows the business SDK so that switching senders\n * cannot change a single hash Meta receives. The param builder is used where the two provably\n * agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)\n * is stripped for the same reason.\n *\n * Two deliberate behavior differences from the business SDK, both on invalid input only:\n * an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from\n * user_data instead of throwing inside `execute()` and costing the whole batch; an invalid\n * currency is uppercased and forwarded instead of rejected. Valid input is unaffected.\n *\n * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { PII_DATA_TYPE, ParamBuilder } from 'capi-param-builder-nodejs';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { MetaAdsOptions } from '../third-parties/meta-pixel';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { metaFbc, metaFbp } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { eventTimeMs } from './event-time';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/** Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). */\nconst API_VERSION = 'v24.0';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\n/**\n * Lazy for the same reason as the session and the token bucket (see setup/session.ts):\n * Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.\n */\nlet paramBuilder: ParamBuilder | undefined;\n\n/**\n * Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the\n * business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's\n * endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as\n * it does in the business SDK.\n */\nfunction pii(value: string | undefined, dataType: string): string | undefined {\n if (!value) return undefined;\n const built = (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType);\n return built?.split('.').at(0) ?? undefined;\n}\n\nconst SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;\n\n/**\n * The business SDK's `normalizeAndHash` for the fields where the param builder normalizes\n * differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,\n * apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the\n * differential test can hold the outputs equal.\n */\nfunction hashed(\n input: string | undefined,\n rule: (lowered: string) => string | undefined\n): string | undefined {\n if (!input) return undefined;\n const lowered = input.trim().toLowerCase();\n if (!lowered) return undefined;\n if (SHA256_OR_MD5.test(lowered)) return lowered;\n const normalized = rule(lowered);\n if (normalized === undefined) return undefined;\n return createHash('sha256').update(normalized).digest('hex');\n}\n\nconst nameRule = (v: string) => v;\nconst f5Rule = (v: string) => (v.length <= 5 ? v : v.slice(0, 5));\nconst cityStateRule = (v: string) => v.replace(/[0-9\\s().-]/g, '');\nconst zipRule = (v: string) => {\n const zip = v.replace(/\\s/g, '').split('-', 1)[0];\n return zip.length < 2 ? undefined : zip;\n};\n\n/**\n * Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each\n * through `dedupArray` (a Set), `external_id` included.\n */\nconst dedupe = (hashes: (string | undefined)[]) =>\n Array.from(new Set(hashes.filter((hash): hash is string => hash !== undefined)));\n\nconst list = (hashes: (string | undefined)[]) => {\n const deduped = dedupe(hashes);\n return deduped.length > 0 ? deduped : undefined;\n};\n\ninterface CapiUserData {\n em?: string[];\n ph?: string[];\n ge?: string[];\n fn?: string[];\n ln?: string[];\n ct?: string[];\n st?: string[];\n zp?: string[];\n country?: string[];\n external_id?: string[];\n client_ip_address?: string;\n client_user_agent?: string;\n fbc?: string;\n fbp?: string;\n fb_login_id?: string;\n page_id?: string;\n f5first?: string;\n f5last?: string;\n dobd?: string;\n dobm?: string;\n doby?: string;\n madid?: string;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number): CapiUserData {\n const userData: CapiUserData = {};\n\n if (data.email) {\n const emails = Array.isArray(data.email) ? data.email : [data.email];\n userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));\n }\n if (data.phone_number) {\n const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];\n userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));\n }\n if (data.gender === 'female' || data.gender === 'male') {\n userData.ge = list([pii(data.gender === 'female' ? 'f' : 'm', PII_DATA_TYPE.GENDER)]);\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n // The SDK sets these lists unconditionally in the multi-address branch, so an all-empty\n // column still goes out as `[]` — kept for byte-equality with the current sender.\n userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));\n userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));\n userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));\n userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));\n userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));\n userData.country = dedupe(\n data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY))\n );\n } else {\n userData.fn = list([hashed(data.address.first_name, nameRule)]);\n userData.ln = list([hashed(data.address.last_name, nameRule)]);\n userData.ct = list([hashed(data.address.city, cityStateRule)]);\n userData.st = list([hashed(data.address.region, cityStateRule)]);\n userData.zp = list([hashed(data.address.postal_code, zipRule)]);\n userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);\n // The 5-character prefixes, exactly as the current sender builds them: sliced first, then\n // normalized. Only the single-address branch sets them, as before.\n userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);\n userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);\n }\n }\n if (data.birthday) {\n const { year, month, day } = data.birthday;\n if (/^\\d{4}$/.test(year.toString())) {\n userData.doby = createHash('sha256').update(year.toString()).digest('hex');\n }\n if (month >= 1 && month <= 12) {\n userData.dobm = createHash('sha256').update(month.toString().padStart(2, '0')).digest('hex');\n }\n if (day >= 1 && day <= 31) {\n userData.dobd = createHash('sha256').update(day.toString().padStart(2, '0')).digest('hex');\n }\n }\n if (data.user_id && data.user_id.length !== 0) {\n // Unhashed, as the business SDK sends it. Meta documents hashing as recommended, not\n // required; changing it here would break continuity with every event sent so far.\n userData.external_id = [data.user_id];\n }\n if (data.ip_address) {\n userData.client_ip_address = data.ip_address;\n }\n if (data.user_agent) {\n userData.client_user_agent = data.user_agent;\n }\n if (data.fb_login_id) {\n userData.fb_login_id = data.fb_login_id;\n }\n if (data.fb_page_id) {\n userData.page_id = data.fb_page_id;\n }\n\n const fbc = metaFbc(tags, eventTimeMs);\n if (fbc) {\n userData.fbc = fbc;\n }\n const fbp = metaFbp(tags);\n if (fbp) {\n userData.fbp = fbp;\n }\n if (tags.advertising_id) {\n userData.madid = tags.advertising_id;\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.client_ip_address = tags.ip_address;\n }\n\n return userData;\n}\n\nconst DELIVERY_CATEGORIES = ['in_store', 'curbside', 'home_delivery'];\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>): Record<string, unknown> {\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n predicted_ltv,\n num_items,\n search_string,\n status,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n\n const customData: Record<string, unknown> = {};\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null && Number.isFinite(Number.parseFloat(String(value)))) {\n customData.value = Number.parseFloat(String(value));\n }\n if (currency) {\n // The business SDK also validates against the ISO 4217 list and throws; here an unknown\n // code is forwarded uppercased rather than costing the batch.\n customData.currency = currency\n .trim()\n .toUpperCase()\n .replace(/[^A-Z]/g, '');\n }\n if (content_name) customData.content_name = content_name;\n if (content_category) customData.content_category = content_category;\n if (content_ids) customData.content_ids = content_ids;\n if (contents) {\n customData.contents = contents.map((c) => {\n const content: Record<string, unknown> = {};\n if (c.id) content.id = c.id;\n if (c.quantity) content.quantity = c.quantity;\n if (c.item_price) content.item_price = c.item_price;\n if (c.title) content.title = c.title;\n if (c.description) content.description = c.description;\n if (c.brand) content.brand = c.brand;\n if (c.category) content.category = c.category;\n const delivery = c.delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;\n return content;\n });\n }\n if (content_type) customData.content_type = content_type;\n if (predicted_ltv) customData.predicted_ltv = predicted_ltv;\n if (num_items) customData.num_items = num_items;\n if (search_string) customData.search_string = search_string;\n if (status) customData.status = status.toString();\n const delivery = delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;\n\n return { ...customData, ...custom_properties };\n}\n\n/**\n * `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset\n * indexes out when it serializes; the documented 16-element array is what the Graph endpoint\n * decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS\n * version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.\n */\n/**\n * The `extinfo` version of an app event's OS — `i2` for iOS, `a2` for Android, the only two Meta\n * documents. Undefined for any other OS (a desktop app): such an event cannot carry the\n * `app_data` an app event requires, and is sent as `other`.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/app-events\n */\nexport function metaExtinfoVersion(tags: TrackTags): 'i2' | 'a2' | undefined {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') return 'i2';\n if (tags.os_name === 'Android') return 'a2';\n return undefined;\n}\n\nfunction getAppData(\n tags: TrackTags,\n appPackageName: string,\n version: 'i2' | 'a2'\n): Record<string, unknown> {\n const extinfo: Record<number, string | number> = {};\n extinfo[0] = version;\n extinfo[1] = appPackageName;\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) extinfo[2] = shortVersion;\n if (tags.release) extinfo[3] = tags.release;\n if (tags.os_version) extinfo[4] = tags.os_version;\n if (tags.device_model_id) extinfo[5] = tags.device_model_id;\n if (tags.language) extinfo[6] = tags.language;\n if (tags.screen_width) extinfo[9] = tags.screen_width;\n if (tags.screen_height) extinfo[10] = tags.screen_height;\n if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();\n\n // Required on every app event. An advertising id is only readable once the user allowed\n // tracking (ATT on iOS, the ad id setting on Android), so its presence is the answer.\n const appData: Record<string, unknown> = {\n extinfo,\n advertiser_tracking_enabled: !!tags.advertising_id,\n };\n if (tags.install_referrer) appData.install_referrer = tags.install_referrer;\n return appData;\n}\n\n/** One entry of the `data` array POSTed to `/{pixel_id}/events`. */\nexport interface CapiEvent {\n event_name: string;\n event_time: number;\n event_id: string;\n event_source_url?: string;\n action_source: 'app' | 'website' | 'other';\n user_data: CapiUserData;\n custom_data: Record<string, unknown>;\n app_data?: Record<string, unknown>;\n}\n\n/**\n * `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a\n * website, and everything else — including a backend-built offline conversion, which should\n * declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK\n * sender put an explicit `'offline'` too.\n */\nexport function getCapiEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string\n): CapiEvent {\n const eventTime = eventTimeMs(event.created_at);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const source = resolveActionSource(event.platform);\n const version = metaExtinfoVersion(event.tags);\n const app =\n source === 'app' && appPackageName && version\n ? { packageName: appPackageName, version }\n : undefined;\n\n const capiEvent: CapiEvent = {\n event_name: eventName,\n event_time: Math.round(eventTime / 1000),\n event_id: event.tags.idempotency_key ?? event.id,\n // `action_source` is required; an offline conversion and an undeterminable platform both\n // land in Meta's catch-all, exactly as in the business-SDK sender. So does an app event that\n // cannot carry the `app_data` Meta requires of one: no package name, or a desktop OS.\n action_source: app ? 'app' : source === 'web' ? 'website' : 'other',\n user_data: getUserData(event.tags, data, eventTime),\n custom_data: getCustomData(event),\n };\n if (app) {\n capiEvent.app_data = getAppData(event.tags, app.packageName, app.version);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n capiEvent.event_source_url = eventSourceUrl;\n }\n return capiEvent;\n}\n\nexport interface MetaConversionsOptions {\n /** Attaches `app_data`/extinfo to events whose platform resolves to an app. */\n appPackageName?: string;\n /** Routes the batch to Events Manager's Test Events tab instead of production. */\n testEventCode?: string;\n /** Graph API version, e.g. 'v24.0'. */\n apiVersion?: string;\n}\n\nexport interface MetaConversionsResponse {\n events_received?: number;\n messages?: string[];\n fbtrace_id?: string;\n}\n\n/**\n * An `event_time` over 7 days old fails the whole request — \"we return an error for the entire\n * request and process no events\" — so such an event is left out; a minute's margin for the trip.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Sends the events to Meta's Conversions API. Rejects on a failed request — a\n * `ConversionsApiError`, or the fetch error — for the caller to handle. The token travels in the\n * JSON body, never in the URL, and is in neither error.\n */\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MetaConversionsOptions = {}\n): Promise<MetaConversionsResponse | undefined> {\n const capiEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getCapiEvent(event, data, options.appPackageName));\n if (capiEvents.length === 0) return undefined;\n // \"The client_user_agent is required for website events\" — sent from `data.user_agent`.\n if (!data.user_agent && capiEvents.some((event) => event.action_source === 'website')) {\n console.warn(\n 'Meta conversion: website events sent without client_user_agent (data.user_agent)'\n );\n }\n\n const version = options.apiVersion ?? API_VERSION;\n const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({\n data: capiEvents,\n test_event_code: options.testEventCode,\n access_token: accessToken,\n }),\n });\n if (response.ok) return (await response.json()) as MetaConversionsResponse;\n throw new ConversionsApiError('meta', response.status, await response.text());\n}\n\n/**\n * Meta's Conversions API, sent the same events as `metaAds` in the browser: the ones Meta maps to\n * a standard event, and `customEvents`.\n */\nexport function metaConversions(\n options: MetaAdsOptions & MetaConversionsOptions & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardFBEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;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IAAI,IAAI,KAAK,MAAM,MAAM,UAAU,KAAK,gBAAgB,CAAC,CAChF,KAAK,UAAU,aAAa,OAAO,MAAM,QAAQ,cAAc,CAAC;CACnE,IAAI,WAAW,WAAW,GAAG,OAAO,KAAA;CAEpC,IAAI,CAAC,KAAK,cAAc,WAAW,MAAM,UAAU,MAAM,kBAAkB,SAAS,GAClF,QAAQ,KACN,kFACF;CAGF,MAAM,UAAU,QAAQ,cAAc;CACtC,MAAM,WAAW,MAAM,MAAM,8BAA8B,QAAQ,GAAG,QAAQ,UAAU;EACtF,QAAQ;EAER,SAAS;EACT,SAAS;GAAE,gBAAgB;GAAoB,QAAQ;EAAmB;EAC1E,MAAM,KAAK,UAAU;GACnB,MAAM;GACN,iBAAiB,QAAQ;GACzB,cAAc;EAChB,CAAC;CACH,CAAC;CACD,IAAI,SAAS,IAAI,OAAQ,MAAM,SAAS,KAAK;CAC7C,MAAM,IAAI,oBAAoB,QAAQ,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;AAC9E;;;;;AAMA,SAAgB,gBACd,SACuB;CACvB,OAAO,sBAAsB,SAAS,mBAAmB,QAAQ,YAAY,IAAI,QAAQ,SACvF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,OAAO,CACxE;AACF"}
1
+ {"version":3,"file":"meta-capi.mjs","names":[],"sources":["../../src/server/meta-capi.ts"],"sourcesContent":["/**\n * Meta Conversions API sender built on `capi-param-builder-nodejs` and plain `fetch`, which\n * replaced the sender built on the 31MB `facebook-nodejs-business-sdk`, since removed, with\n * ~0.5MB of parameter building.\n *\n * The wire payload is byte-identical to what the business SDK's `ServerEvent.normalize()`\n * produces — enforced by a differential test that runs both builders over the same events.\n * Where the two libraries normalize differently (the business SDK keeps punctuation in names,\n * spaces in multi-word last names, accents in cities; the param builder strips them per the\n * current documented rules), this module follows the business SDK so that switching senders\n * cannot change a single hash Meta receives. The param builder is used where the two provably\n * agree — email, phone, gender, country — and its adoption-tracking appendix (`<hash>.<token>`)\n * is stripped for the same reason.\n *\n * Two deliberate behavior differences from the business SDK, both on invalid input only:\n * an invalid field (malformed email, non-ISO country, letters in a phone) is dropped from\n * user_data instead of throwing inside `execute()` and costing the whole batch; an invalid\n * currency is uppercased and forwarded instead of rejected. Valid input is unaffected.\n *\n * https://developers.facebook.com/docs/marketing-api/conversions-api/using-the-api\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { PII_DATA_TYPE, ParamBuilder } from 'capi-param-builder-nodejs';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { adEvents } from '../third-parties/integration';\nimport type { MetaAdsOptions } from '../third-parties/meta-pixel';\nimport { isStandardFBEvent, mapFBEvent } from '../track/fbq';\nimport type { TrackEvent, TrackTags, UserProvidedData } from '../track/types';\nimport { resolveActionSource } from './action-source';\nimport { metaFbc, metaFbp } from './click-ids';\nimport { ConversionsApiError } from './conversions-api-error';\nimport { eventTimeMs } from './event-time';\nimport { pageLocation } from './page-location';\nimport { type ConversionDestination, conversionDestination } from './setup-conversions';\n\n/**\n * Matches the Graph API version the pinned business SDK speaks (`FacebookAdsApi.VERSION`). Meta\n * keeps each Graph API version for about two years from its release, then requests to it fail,\n * so this must be bumped with each release (or overridden through `apiVersion`).\n */\nconst API_VERSION = 'v24.0';\n\nconst USER_ASSIGNED_COUNTRIES: string[] = ['xk'];\nfunction normalizeCountry(input: string | undefined): string | undefined {\n const country = input?.split(/[-_]/).at(0)?.toLowerCase();\n if (!country) return undefined;\n return USER_ASSIGNED_COUNTRIES.includes(country) ? undefined : country;\n}\n\n/**\n * Lazy for the same reason as the session and the token bucket (see setup/session.ts):\n * Cloudflare Workers refuse some work in module scope, and nothing here is per-request state.\n */\nlet paramBuilder: ParamBuilder | undefined;\n\n/**\n * Normalize and hash one PII value through the param builder, stripped to the bare SHA-256 the\n * business SDK sends: the builder appends a `.<language-token>` adoption marker that Meta's\n * endpoint tolerates but the business SDK never produced. Pre-hashed input passes through, as\n * it does in the business SDK.\n */\nfunction pii(value: string | undefined, dataType: string): string | undefined {\n if (!value) return undefined;\n const built = (paramBuilder ??= new ParamBuilder()).getNormalizedAndHashedPII(value, dataType);\n return built?.split('.').at(0) ?? undefined;\n}\n\nconst SHA256_OR_MD5 = /^[a-f0-9]{64}$|^[a-f0-9]{32}$/;\n\n/**\n * The business SDK's `normalizeAndHash` for the fields where the param builder normalizes\n * differently (names, city, state, zip): trim + lowercase, pass a pre-hashed value through,\n * apply the field rule, SHA-256. Field rules are copied from `ServerSideUtils` verbatim so the\n * differential test can hold the outputs equal.\n */\nfunction hashed(\n input: string | undefined,\n rule: (lowered: string) => string | undefined\n): string | undefined {\n if (!input) return undefined;\n const lowered = input.trim().toLowerCase();\n if (!lowered) return undefined;\n if (SHA256_OR_MD5.test(lowered)) return lowered;\n const normalized = rule(lowered);\n if (normalized === undefined) return undefined;\n return createHash('sha256').update(normalized).digest('hex');\n}\n\nconst nameRule = (v: string) => v;\nconst f5Rule = (v: string) => (v.length <= 5 ? v : v.slice(0, 5));\nconst cityStateRule = (v: string) => v.replace(/[0-9\\s().-]/g, '');\nconst zipRule = (v: string) => {\n const zip = v.replace(/\\s/g, '').split('-', 1)[0];\n return zip.length < 2 ? undefined : zip;\n};\n\n/**\n * Every multi-value field is deduplicated after hashing, order preserved — the SDK runs each\n * through `dedupArray` (a Set), `external_id` included.\n */\nconst dedupe = (hashes: (string | undefined)[]) =>\n Array.from(new Set(hashes.filter((hash): hash is string => hash !== undefined)));\n\nconst list = (hashes: (string | undefined)[]) => {\n const deduped = dedupe(hashes);\n return deduped.length > 0 ? deduped : undefined;\n};\n\ninterface CapiUserData {\n em?: string[];\n ph?: string[];\n ge?: string[];\n fn?: string[];\n ln?: string[];\n ct?: string[];\n st?: string[];\n zp?: string[];\n country?: string[];\n external_id?: string[];\n client_ip_address?: string;\n client_user_agent?: string;\n fbc?: string;\n fbp?: string;\n fb_login_id?: string;\n page_id?: string;\n f5first?: string;\n f5last?: string;\n dobd?: string;\n dobm?: string;\n doby?: string;\n madid?: string;\n}\n\nfunction getUserData(tags: TrackTags, data: UserProvidedData, eventTimeMs: number): CapiUserData {\n const userData: CapiUserData = {};\n\n if (data.email) {\n const emails = Array.isArray(data.email) ? data.email : [data.email];\n userData.em = list(emails.map((email) => pii(email, PII_DATA_TYPE.EMAIL)));\n }\n if (data.phone_number) {\n const phones = Array.isArray(data.phone_number) ? data.phone_number : [data.phone_number];\n userData.ph = list(phones.map((phone) => pii(phone, PII_DATA_TYPE.PHONE)));\n }\n if (data.gender === 'female' || data.gender === 'male') {\n userData.ge = list([pii(data.gender === 'female' ? 'f' : 'm', PII_DATA_TYPE.GENDER)]);\n }\n if (data.address) {\n if (Array.isArray(data.address)) {\n // The SDK sets these lists unconditionally in the multi-address branch, so an all-empty\n // column still goes out as `[]` — kept for byte-equality with the current sender.\n userData.fn = dedupe(data.address.map((a) => hashed(a.first_name, nameRule)));\n userData.ln = dedupe(data.address.map((a) => hashed(a.last_name, nameRule)));\n userData.ct = dedupe(data.address.map((a) => hashed(a.city, cityStateRule)));\n userData.st = dedupe(data.address.map((a) => hashed(a.region, cityStateRule)));\n userData.zp = dedupe(data.address.map((a) => hashed(a.postal_code, zipRule)));\n userData.country = dedupe(\n data.address.map((a) => pii(normalizeCountry(a.country), PII_DATA_TYPE.COUNTRY))\n );\n } else {\n userData.fn = list([hashed(data.address.first_name, nameRule)]);\n userData.ln = list([hashed(data.address.last_name, nameRule)]);\n userData.ct = list([hashed(data.address.city, cityStateRule)]);\n userData.st = list([hashed(data.address.region, cityStateRule)]);\n userData.zp = list([hashed(data.address.postal_code, zipRule)]);\n userData.country = list([pii(normalizeCountry(data.address.country), PII_DATA_TYPE.COUNTRY)]);\n // The 5-character prefixes, exactly as the current sender builds them: sliced first, then\n // normalized. Only the single-address branch sets them, as before.\n userData.f5first = hashed(data.address.first_name?.slice(0, 5), f5Rule);\n userData.f5last = hashed(data.address.last_name?.slice(0, 5), f5Rule);\n }\n }\n if (data.birthday) {\n const { year, month, day } = data.birthday;\n if (/^\\d{4}$/.test(year.toString())) {\n userData.doby = createHash('sha256').update(year.toString()).digest('hex');\n }\n if (month >= 1 && month <= 12) {\n userData.dobm = createHash('sha256').update(month.toString().padStart(2, '0')).digest('hex');\n }\n if (day >= 1 && day <= 31) {\n userData.dobd = createHash('sha256').update(day.toString().padStart(2, '0')).digest('hex');\n }\n }\n if (data.user_id && data.user_id.length !== 0) {\n // Unhashed, as the business SDK sends it. Meta documents hashing as recommended, not\n // required; changing it here would break continuity with every event sent so far.\n userData.external_id = [data.user_id];\n }\n if (data.ip_address) {\n userData.client_ip_address = data.ip_address;\n }\n if (data.user_agent) {\n userData.client_user_agent = data.user_agent;\n }\n if (data.fb_login_id) {\n userData.fb_login_id = data.fb_login_id;\n }\n if (data.fb_page_id) {\n userData.page_id = data.fb_page_id;\n }\n\n const fbc = metaFbc(tags, eventTimeMs);\n if (fbc) {\n userData.fbc = fbc;\n }\n const fbp = metaFbp(tags);\n if (fbp) {\n userData.fbp = fbp;\n }\n if (tags.advertising_id) {\n userData.madid = tags.advertising_id;\n }\n if (tags.ip_address && typeof tags.ip_address === 'string') {\n userData.client_ip_address = tags.ip_address;\n }\n\n return userData;\n}\n\nconst DELIVERY_CATEGORIES = ['in_store', 'curbside', 'home_delivery'];\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData({ name, properties }: TrackEvent<any>): Record<string, unknown> {\n const [_, _name, fbEventProperties] = mapFBEvent(name, properties);\n const {\n value,\n currency,\n content_name,\n content_category,\n content_ids,\n contents,\n content_type,\n predicted_ltv,\n num_items,\n search_string,\n status,\n delivery_category,\n ...custom_properties\n } = fbEventProperties;\n\n const customData: Record<string, unknown> = {};\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- custom event properties may carry `value: null` at runtime despite the declared type\n if (value !== undefined && value !== null && Number.isFinite(Number.parseFloat(String(value)))) {\n customData.value = Number.parseFloat(String(value));\n }\n if (currency) {\n // The business SDK also validates against the ISO 4217 list and throws; here an unknown\n // code is forwarded uppercased rather than costing the batch.\n customData.currency = currency\n .trim()\n .toUpperCase()\n .replace(/[^A-Z]/g, '');\n }\n if (content_name) customData.content_name = content_name;\n if (content_category) customData.content_category = content_category;\n if (content_ids) customData.content_ids = content_ids;\n if (contents) {\n customData.contents = contents.map((c) => {\n const content: Record<string, unknown> = {};\n if (c.id) content.id = c.id;\n if (c.quantity) content.quantity = c.quantity;\n if (c.item_price) content.item_price = c.item_price;\n if (c.title) content.title = c.title;\n if (c.description) content.description = c.description;\n if (c.brand) content.brand = c.brand;\n if (c.category) content.category = c.category;\n const delivery = c.delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) content.delivery_category = delivery;\n return content;\n });\n }\n if (content_type) customData.content_type = content_type;\n if (predicted_ltv) customData.predicted_ltv = predicted_ltv;\n if (num_items) customData.num_items = num_items;\n if (search_string) customData.search_string = search_string;\n if (status) customData.status = status.toString();\n const delivery = delivery_category?.trim().toLowerCase();\n if (delivery && DELIVERY_CATEGORIES.includes(delivery)) customData.delivery_category = delivery;\n\n return { ...customData, ...custom_properties };\n}\n\n/**\n * `extinfo` is keyed by field index. The business SDK builds the same object and leaves unset\n * indexes out when it serializes; the documented 16-element array is what the Graph endpoint\n * decodes this into. Indexes: 0 version, 1 package, 2 short version, 3 long version, 4 OS\n * version, 5 device model, 6 locale, 9 screen width, 10 height, 11 density.\n */\n/**\n * The `extinfo` version of an app event's OS — `i2` for iOS, `a2` for Android, the only two Meta\n * documents. Undefined for any other OS (a desktop app): such an event cannot carry the\n * `app_data` an app event requires, and is sent as `other`.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/app-events\n */\nexport function metaExtinfoVersion(tags: TrackTags): 'i2' | 'a2' | undefined {\n if (tags.os_name === 'iOS' || tags.os_name === 'iPadOS') return 'i2';\n if (tags.os_name === 'Android') return 'a2';\n return undefined;\n}\n\nfunction getAppData(\n tags: TrackTags,\n appPackageName: string,\n version: 'i2' | 'a2'\n): Record<string, unknown> {\n const extinfo: Record<number, string | number> = {};\n extinfo[0] = version;\n extinfo[1] = appPackageName;\n const shortVersion = tags.release?.split('.').at(0);\n if (shortVersion) extinfo[2] = shortVersion;\n if (tags.release) extinfo[3] = tags.release;\n if (tags.os_version) extinfo[4] = tags.os_version;\n if (tags.device_model_id) extinfo[5] = tags.device_model_id;\n if (tags.language) extinfo[6] = tags.language;\n if (tags.screen_width) extinfo[9] = tags.screen_width;\n if (tags.screen_height) extinfo[10] = tags.screen_height;\n if (tags.device_pixel_ratio) extinfo[11] = tags.device_pixel_ratio.toString();\n\n // Required on every app event. An advertising id is only readable once the user allowed\n // tracking (ATT on iOS, the ad id setting on Android), so its presence is the answer.\n const appData: Record<string, unknown> = {\n extinfo,\n advertiser_tracking_enabled: !!tags.advertising_id,\n };\n if (tags.install_referrer) appData.install_referrer = tags.install_referrer;\n return appData;\n}\n\n/** One entry of the `data` array POSTed to `/{pixel_id}/events`. */\nexport interface CapiEvent {\n event_name: string;\n event_time: number;\n event_id: string;\n event_source_url?: string;\n action_source: 'app' | 'website' | 'other';\n user_data: CapiUserData;\n custom_data: Record<string, unknown>;\n app_data?: Record<string, unknown>;\n}\n\n/**\n * `action_source` is derived from `event.platform` alone: an OS platform is an app, `web` is a\n * website, and everything else — including a backend-built offline conversion, which should\n * declare `platform: 'unknown'` — lands in Meta's `other`, exactly where the business-SDK\n * sender put an explicit `'offline'` too.\n */\nexport function getCapiEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n appPackageName?: string\n): CapiEvent {\n const eventTime = eventTimeMs(event.created_at);\n const [_, eventName] = mapFBEvent(event.name, event.properties);\n const source = resolveActionSource(event.platform);\n const version = metaExtinfoVersion(event.tags);\n const app =\n source === 'app' && appPackageName && version\n ? { packageName: appPackageName, version }\n : undefined;\n\n const capiEvent: CapiEvent = {\n event_name: eventName,\n event_time: Math.round(eventTime / 1000),\n event_id: event.tags.idempotency_key ?? event.id,\n // `action_source` is required; an offline conversion and an undeterminable platform both\n // land in Meta's catch-all, exactly as in the business-SDK sender. So does an app event that\n // cannot carry the `app_data` Meta requires of one: no package name, or a desktop OS.\n action_source: app ? 'app' : source === 'web' ? 'website' : 'other',\n user_data: getUserData(event.tags, data, eventTime),\n custom_data: getCustomData(event),\n };\n if (app) {\n capiEvent.app_data = getAppData(event.tags, app.packageName, app.version);\n }\n const eventSourceUrl = pageLocation(event.tags);\n if (eventSourceUrl) {\n capiEvent.event_source_url = eventSourceUrl;\n }\n return capiEvent;\n}\n\nexport interface MetaConversionsOptions {\n /** Attaches `app_data`/extinfo to events whose platform resolves to an app. */\n appPackageName?: string;\n /** Routes the batch to Events Manager's Test Events tab instead of production. */\n testEventCode?: string;\n /** Graph API version, e.g. 'v24.0'. */\n apiVersion?: string;\n}\n\nexport interface MetaConversionsResponse {\n events_received?: number;\n messages?: string[];\n fbtrace_id?: string;\n}\n\n/**\n * An `event_time` over 7 days old fails the whole request — \"we return an error for the entire\n * request and process no events\" — so such an event is left out; a minute's margin for the trip.\n * https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/server-event\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Sends the events to Meta's Conversions API. Rejects on a failed request — a\n * `ConversionsApiError`, or the fetch error — for the caller to handle. The token travels in the\n * JSON body, never in the URL, and is in neither error.\n */\nexport async function sendEvents(\n accessToken: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MetaConversionsOptions = {}\n): Promise<MetaConversionsResponse | undefined> {\n const capiEvents = events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getCapiEvent(event, data, options.appPackageName));\n if (capiEvents.length === 0) return undefined;\n // \"The client_user_agent is required for website events\" — sent from `data.user_agent`.\n if (!data.user_agent && capiEvents.some((event) => event.action_source === 'website')) {\n console.warn(\n 'Meta conversion: website events sent without client_user_agent (data.user_agent)'\n );\n }\n\n const version = options.apiVersion ?? API_VERSION;\n const response = await fetch(`https://graph.facebook.com/${version}/${pixelId}/events`, {\n method: 'POST',\n // Retried although a POST: the platform deduplicates on the `event_id` each event carries.\n retries: 3,\n headers: { 'Content-Type': 'application/json', Accept: 'application/json' },\n body: JSON.stringify({\n data: capiEvents,\n test_event_code: options.testEventCode,\n access_token: accessToken,\n }),\n });\n if (response.ok) return (await response.json()) as MetaConversionsResponse;\n throw new ConversionsApiError('meta', response.status, await response.text());\n}\n\n/**\n * Meta's Conversions API, sent the same events as `metaAds` in the browser: the ones Meta maps to\n * a standard event, and `customEvents`.\n */\nexport function metaConversions(\n options: MetaAdsOptions & MetaConversionsOptions & { accessToken: string }\n): ConversionDestination {\n return conversionDestination(adEvents(isStandardFBEvent, options.customEvents), (events, data) =>\n sendEvents(options.accessToken, options.pixelId, events, data, options)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,cAAc;AAEpB,MAAM,0BAAoC,CAAC,IAAI;AAC/C,SAAS,iBAAiB,OAA+C;CACvE,MAAM,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY;CACxD,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,OAAO,wBAAwB,SAAS,OAAO,IAAI,KAAA,IAAY;AACjE;;;;;AAMA,IAAI;;;;;;;AAQJ,SAAS,IAAI,OAA2B,UAAsC;CAC5E,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,QADe,iBAAiB,IAAI,aAAa,EAAA,CAAG,0BAA0B,OAAO,QAC1E,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,KAAK,KAAA;AACp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H,CAAC;CACD,IAAI,SAAS,IAAI,OAAQ,MAAM,SAAS,KAAK;CAC7C,MAAM,IAAI,oBAAoB,QAAQ,SAAS,QAAQ,MAAM,SAAS,KAAK,CAAC;AAC9E;;;;;AAMA,SAAgB,gBACd,SACuB;CACvB,OAAO,sBAAsB,SAAS,mBAAmB,QAAQ,YAAY,IAAI,QAAQ,SACvF,WAAW,QAAQ,aAAa,QAAQ,SAAS,QAAQ,MAAM,OAAO,CACxE;AACF"}
@@ -26,7 +26,7 @@ function setupConversions(options) {
26
26
  */
27
27
  async function track({ resolveUser, store }, input) {
28
28
  try {
29
- const user = await resolveUser(input.userId);
29
+ const user = await resolveUser(input.userId, input);
30
30
  if (!user) {
31
31
  console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);
32
32
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"setup-conversions.cjs","names":[],"sources":["../../src/server/setup-conversions.ts"],"sourcesContent":["import type {\n Environment,\n EventName,\n Platform,\n TrackEvent,\n TrackName,\n TrackProperties,\n TrackTags,\n UserProvidedData,\n} from '../track/types';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTrackEvent = TrackEvent<any>;\n\n/**\n * Where `setupConversions` sends events: an ad platform's conversions API, from its factory\n * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a\n * CRM, its own workflows).\n *\n * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,\n * with the events' ids, and still sends to the others.\n */\nexport interface ConversionDestination {\n readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;\n}\n\n/**\n * A destination that sends only the events `accepts` lets through, and makes no request when none\n * is left: what each conversions API's factory (`metaConversions`, …) is built on.\n */\nexport function conversionDestination(\n accepts: (name: string) => boolean,\n send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>\n): ConversionDestination {\n return {\n send: async (events, data) => {\n const accepted = events.filter((event) => accepts(event.name));\n if (accepted.length > 0) await send(accepted, data);\n },\n };\n}\n\n/**\n * Who a server-only event is from, as the host knows them: what the ad platforms match a client\n * event on, read from the host's own records.\n *\n * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page\n * and user agent), with the click ids of the touch the conversion is attributed to over them.\n * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides\n * each platform's action source (website or app), as for a client event.\n * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.\n */\nexport interface ConversionUser {\n tags: TrackTags;\n visitor_id: string;\n session_id: string;\n platform: Platform;\n environment: Environment;\n data: UserProvidedData;\n}\n\n/**\n * An event the server reports on its own, with no client behind it: a webhook's purchase,\n * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from\n * being reported twice, and the platforms pair it with a browser event under the same id.\n */\nexport interface ServerEvent<T extends EventName = EventName> {\n id: string;\n name: TrackName<T>;\n /** The user it belongs to, handed to `track.resolveUser`. */\n userId: string;\n properties?: TrackProperties<T>;\n /** When it happened, as an ISO 8601 string. */\n createdAt: string;\n}\n\nexport interface ConversionsOptions {\n destinations: readonly ConversionDestination[];\n /**\n * How `track` completes and stores a server-only event. Without it `setupConversions` returns\n * only `forward`, for a host that only forwards client events.\n */\n track?: {\n /**\n * The user behind the event, read from the host's records (see `ConversionUser`);\n * `undefined` for one the host has no session of, whose event is then dropped.\n */\n resolveUser: (userId: string) => Promise<ConversionUser | undefined>;\n /**\n * Stores the event, e.g. in the events table, returning whether it was new: `track` sends\n * only an event it stored, so a webhook delivered again (its handler failed on something\n * else) is not reported twice — not every platform deduplicates a server event sent twice.\n */\n store: (event: AnyTrackEvent) => Promise<boolean>;\n };\n}\n\n/**\n * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured\n * once, with the same per-platform options as the browser integrations, so the conversions API\n * and the tag report the same events.\n *\n * - `forward(events, data)`: the events a client sent, as stored, on to every destination.\n * - `track(event)`: an event the server reports on its own (a webhook's), completed by\n * `track.resolveUser`, stored with `track.store`, then forwarded.\n *\n * Neither throws, so reporting a conversion can never fail the request it runs in — a payment\n * webhook least of all, which its provider would then deliver again and again. A failure is\n * logged with the ids of the events it lost, for them to be found and sent later: a missed\n * conversion costs less than a duplicate one, or a webhook that keeps failing.\n */\nexport function setupConversions(\n options: ConversionsOptions & { track: NonNullable<ConversionsOptions['track']> }\n): {\n forward: Forward;\n track: Track;\n};\nexport function setupConversions(options: ConversionsOptions): { forward: Forward };\nexport function setupConversions(options: ConversionsOptions) {\n const { destinations, track: trackOptions } = options;\n\n async function forward(events: AnyTrackEvent[], data: UserProvidedData = {}) {\n if (events.length === 0) return;\n // Called inside a promise: a `send` that throws synchronously rejects there instead of\n // stopping the destinations after it.\n const settled = await Promise.allSettled(\n destinations.map((d) => Promise.resolve().then(() => d.send(events, data)))\n );\n const ids = events.map((event) => event.id).join(', ');\n settled.forEach((outcome) => {\n if (outcome.status === 'rejected') {\n console.error(`Conversions not sent, events: ${ids}`, outcome.reason);\n }\n });\n }\n\n /**\n * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a\n * user with no session, an event `store` had already stored, or a failure, which is logged.\n */\n async function track<T extends EventName>(\n { resolveUser, store }: NonNullable<ConversionsOptions['track']>,\n input: ServerEvent<T>\n ): Promise<TrackEvent<T> | undefined> {\n try {\n const user = await resolveUser(input.userId);\n if (!user) {\n console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);\n return undefined;\n }\n const event: TrackEvent<T> = {\n id: input.id,\n name: input.name,\n properties: input.properties,\n tags: user.tags,\n visitor_id: user.visitor_id,\n session_id: user.session_id,\n platform: user.platform,\n environment: user.environment,\n created_at: input.createdAt,\n };\n if (!(await store(event))) return undefined;\n await forward([event], user.data);\n return event;\n } catch (e: unknown) {\n console.error(`Conversion not reported, event: ${input.id}`, e);\n return undefined;\n }\n }\n\n if (!trackOptions) return { forward };\n return { forward, track: (input: ServerEvent) => track(trackOptions, input) };\n}\n\ntype Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;\ntype Track = <T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AO;EACT,SAAS,GAAY;GACnB,QAAQ,MAAM,mCAAmC,MAAM,MAAM,CAAC;GAC9D;EACF;CACF;CAEA,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ;CACpC,OAAO;EAAE;EAAS,QAAQ,UAAuB,MAAM,cAAc,KAAK;CAAE;AAC9E"}
1
+ {"version":3,"file":"setup-conversions.cjs","names":[],"sources":["../../src/server/setup-conversions.ts"],"sourcesContent":["import type {\n Environment,\n EventName,\n Platform,\n TrackEvent,\n TrackName,\n TrackProperties,\n TrackTags,\n UserProvidedData,\n} from '../track/types';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTrackEvent = TrackEvent<any>;\n\n/**\n * Where `setupConversions` sends events: an ad platform's conversions API, from its factory\n * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a\n * CRM, its own workflows).\n *\n * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,\n * with the events' ids, and still sends to the others.\n */\nexport interface ConversionDestination {\n readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;\n}\n\n/**\n * A destination that sends only the events `accepts` lets through, and makes no request when none\n * is left: what each conversions API's factory (`metaConversions`, …) is built on.\n */\nexport function conversionDestination(\n accepts: (name: string) => boolean,\n send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>\n): ConversionDestination {\n return {\n send: async (events, data) => {\n const accepted = events.filter((event) => accepts(event.name));\n if (accepted.length > 0) await send(accepted, data);\n },\n };\n}\n\n/**\n * Who a server-only event is from, as the host knows them: what the ad platforms match a client\n * event on, read from the host's own records.\n *\n * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page\n * and user agent), with the click ids of the touch the conversion is attributed to over them.\n * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides\n * each platform's action source (website or app), as for a client event.\n * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.\n */\nexport interface ConversionUser {\n tags: TrackTags;\n visitor_id: string;\n session_id: string;\n platform: Platform;\n environment: Environment;\n data: UserProvidedData;\n}\n\n/**\n * An event the server reports on its own, with no client behind it: a webhook's purchase,\n * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from\n * being reported twice, and the platforms pair it with a browser event under the same id.\n */\nexport interface ServerEvent<T extends EventName = EventName> {\n id: string;\n name: TrackName<T>;\n /** The user it belongs to, handed to `track.resolveUser`. */\n userId: string;\n properties?: TrackProperties<T>;\n /** When it happened, as an ISO 8601 string. */\n createdAt: string;\n /**\n * Where it happened, when the server knows better than any session: a Stripe payment is `web`,\n * an App Store one `ios`. Read by `resolveUser`, which answers the event's `platform` (it\n * decides each platform's action source): a session of this platform when the user has one,\n * or something else for a user with no session at all, such as `unknown` when there is no user\n * agent to send with a website event.\n */\n platform?: Platform;\n /**\n * Whether it was real, when the server knows: a store's sandbox purchase is `development` even\n * in a production deployment. Read by `resolveUser`, which answers the event's `environment`.\n */\n environment?: Environment;\n}\n\nexport interface ConversionsOptions {\n destinations: readonly ConversionDestination[];\n /**\n * How `track` completes and stores a server-only event. Without it `setupConversions` returns\n * only `forward`, for a host that only forwards client events.\n */\n track?: {\n /**\n * The user behind the event, read from the host's records (see `ConversionUser`), given the\n * event so a session of its `platform` can be preferred and its `platform` / `environment`\n * answered; what it returns is what the event is sent with. `undefined` drops the event. A user\n * with no session at all can still be matched by the platforms on `data` alone (a hashed\n * email), so a host may answer with empty `tags` and ids of its own rather than drop it.\n */\n resolveUser: (userId: string, event: ServerEvent) => Promise<ConversionUser | undefined>;\n /**\n * Stores the event, e.g. in the events table, returning whether it was new: `track` sends\n * only an event it stored, so a webhook delivered again (its handler failed on something\n * else) is not reported twice — not every platform deduplicates a server event sent twice.\n */\n store: (event: AnyTrackEvent) => Promise<boolean>;\n };\n}\n\n/**\n * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured\n * once, with the same per-platform options as the browser integrations, so the conversions API\n * and the tag report the same events.\n *\n * - `forward(events, data)`: the events a client sent, as stored, on to every destination.\n * - `track(event)`: an event the server reports on its own (a webhook's), completed by\n * `track.resolveUser`, stored with `track.store`, then forwarded.\n *\n * Neither throws, so reporting a conversion can never fail the request it runs in — a payment\n * webhook least of all, which its provider would then deliver again and again. A failure is\n * logged with the ids of the events it lost, for them to be found and sent later: a missed\n * conversion costs less than a duplicate one, or a webhook that keeps failing.\n */\nexport function setupConversions(\n options: ConversionsOptions & { track: NonNullable<ConversionsOptions['track']> }\n): {\n forward: Forward;\n track: Track;\n};\nexport function setupConversions(options: ConversionsOptions): { forward: Forward };\nexport function setupConversions(options: ConversionsOptions) {\n const { destinations, track: trackOptions } = options;\n\n async function forward(events: AnyTrackEvent[], data: UserProvidedData = {}) {\n if (events.length === 0) return;\n // Called inside a promise: a `send` that throws synchronously rejects there instead of\n // stopping the destinations after it.\n const settled = await Promise.allSettled(\n destinations.map((d) => Promise.resolve().then(() => d.send(events, data)))\n );\n const ids = events.map((event) => event.id).join(', ');\n settled.forEach((outcome) => {\n if (outcome.status === 'rejected') {\n console.error(`Conversions not sent, events: ${ids}`, outcome.reason);\n }\n });\n }\n\n /**\n * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a\n * user with no session, an event `store` had already stored, or a failure, which is logged.\n */\n async function track<T extends EventName>(\n { resolveUser, store }: NonNullable<ConversionsOptions['track']>,\n input: ServerEvent<T>\n ): Promise<TrackEvent<T> | undefined> {\n try {\n const user = await resolveUser(input.userId, input);\n if (!user) {\n console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);\n return undefined;\n }\n const event: TrackEvent<T> = {\n id: input.id,\n name: input.name,\n properties: input.properties,\n tags: user.tags,\n visitor_id: user.visitor_id,\n session_id: user.session_id,\n platform: user.platform,\n environment: user.environment,\n created_at: input.createdAt,\n };\n if (!(await store(event))) return undefined;\n await forward([event], user.data);\n return event;\n } catch (e: unknown) {\n console.error(`Conversion not reported, event: ${input.id}`, e);\n return undefined;\n }\n }\n\n if (!trackOptions) return { forward };\n return { forward, track: (input: ServerEvent) => track(trackOptions, input) };\n}\n\ntype Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;\ntype Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;\n"],"mappings":";;;;;;AA8BA,SAAgB,sBACd,SACA,MACuB;CACvB,OAAO,EACL,MAAM,OAAO,QAAQ,SAAS;EAC5B,MAAM,WAAW,OAAO,QAAQ,UAAU,QAAQ,MAAM,IAAI,CAAC;EAC7D,IAAI,SAAS,SAAS,GAAG,MAAM,KAAK,UAAU,IAAI;CACpD,EACF;AACF;AA8FA,SAAgB,iBAAiB,SAA6B;CAC5D,MAAM,EAAE,cAAc,OAAO,iBAAiB;CAE9C,eAAe,QAAQ,QAAyB,OAAyB,CAAC,GAAG;EAC3E,IAAI,OAAO,WAAW,GAAG;EAGzB,MAAM,UAAU,MAAM,QAAQ,WAC5B,aAAa,KAAK,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,CAC5E;EACA,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI;EACrD,QAAQ,SAAS,YAAY;GAC3B,IAAI,QAAQ,WAAW,YACrB,QAAQ,MAAM,iCAAiC,OAAO,QAAQ,MAAM;EAExE,CAAC;CACH;;;;;CAMA,eAAe,MACb,EAAE,aAAa,SACf,OACoC;EACpC,IAAI;GACF,MAAM,OAAO,MAAM,YAAY,MAAM,QAAQ,KAAK;GAClD,IAAI,CAAC,MAAM;IACT,QAAQ,KAAK,mCAAmC,MAAM,GAAG,mBAAmB,MAAM,QAAQ;IAC1F;GACF;GACA,MAAM,QAAuB;IAC3B,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,MAAM,KAAK;IACX,YAAY,KAAK;IACjB,YAAY,KAAK;IACjB,UAAU,KAAK;IACf,aAAa,KAAK;IAClB,YAAY,MAAM;GACpB;GACA,IAAI,CAAE,MAAM,MAAM,KAAK,GAAI,OAAO,KAAA;GAClC,MAAM,QAAQ,CAAC,KAAK,GAAG,KAAK,IAAI;GAChC,OAAO;EACT,SAAS,GAAY;GACnB,QAAQ,MAAM,mCAAmC,MAAM,MAAM,CAAC;GAC9D;EACF;CACF;CAEA,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ;CACpC,OAAO;EAAE;EAAS,QAAQ,UAAuB,MAAM,cAAc,KAAK;CAAE;AAC9E"}
@@ -47,6 +47,19 @@ export interface ServerEvent<T extends EventName = EventName> {
47
47
  properties?: TrackProperties<T>;
48
48
  /** When it happened, as an ISO 8601 string. */
49
49
  createdAt: string;
50
+ /**
51
+ * Where it happened, when the server knows better than any session: a Stripe payment is `web`,
52
+ * an App Store one `ios`. Read by `resolveUser`, which answers the event's `platform` (it
53
+ * decides each platform's action source): a session of this platform when the user has one,
54
+ * or something else for a user with no session at all, such as `unknown` when there is no user
55
+ * agent to send with a website event.
56
+ */
57
+ platform?: Platform;
58
+ /**
59
+ * Whether it was real, when the server knows: a store's sandbox purchase is `development` even
60
+ * in a production deployment. Read by `resolveUser`, which answers the event's `environment`.
61
+ */
62
+ environment?: Environment;
50
63
  }
51
64
  export interface ConversionsOptions {
52
65
  destinations: readonly ConversionDestination[];
@@ -56,10 +69,13 @@ export interface ConversionsOptions {
56
69
  */
57
70
  track?: {
58
71
  /**
59
- * The user behind the event, read from the host's records (see `ConversionUser`);
60
- * `undefined` for one the host has no session of, whose event is then dropped.
72
+ * The user behind the event, read from the host's records (see `ConversionUser`), given the
73
+ * event so a session of its `platform` can be preferred and its `platform` / `environment`
74
+ * answered; what it returns is what the event is sent with. `undefined` drops the event. A user
75
+ * with no session at all can still be matched by the platforms on `data` alone (a hashed
76
+ * email), so a host may answer with empty `tags` and ids of its own rather than drop it.
61
77
  */
62
- resolveUser: (userId: string) => Promise<ConversionUser | undefined>;
78
+ resolveUser: (userId: string, event: ServerEvent) => Promise<ConversionUser | undefined>;
63
79
  /**
64
80
  * Stores the event, e.g. in the events table, returning whether it was new: `track` sends
65
81
  * only an event it stored, so a webhook delivered again (its handler failed on something
@@ -1 +1 @@
1
- {"version":3,"file":"setup-conversions.d.cts","names":[],"sources":["../../src/server/setup-conversions.ts"],"mappings":";KAYK,gBAAgB;;;;;;;;;iBAUJ;WACN,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB;;;;;;wBAOtD,sBACd,UAAU,0BACV,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB,mBAC1D;;;;;;;;;;;iBAmBc;EACf,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,MAAM;;;;;;;iBAQS,YAAY,UAAU,YAAY;EACjD;EACA,MAAM,UAAU;;EAEhB;EACA,aAAa,gBAAgB;;EAE7B;;iBAGe;EACf,uBAAuB;;;;;EAKvB;;;;;IAKE,cAAc,mBAAmB,QAAQ;;;;;;IAMzC,QAAQ,OAAO,kBAAkB;;;;;;;;;;;;;;;;;wBAkBrB,iBACd,SAAS;EAAuB,OAAO,YAAY;;EAEnD,SAAS;EACT,OAAO;;wBAEO,iBAAiB,SAAS;EAAuB,SAAS;;KAyDrE,WAAW,QAAQ,iBAAiB,OAAO,qBAAqB;KAChE,SAAS,UAAU,WAAW,OAAO,YAAY,OAAO,QAAQ,WAAW"}
1
+ {"version":3,"file":"setup-conversions.d.cts","names":[],"sources":["../../src/server/setup-conversions.ts"],"mappings":";KAYK,gBAAgB;;;;;;;;;iBAUJ;WACN,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB;;;;;;wBAOtD,sBACd,UAAU,0BACV,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB,mBAC1D;;;;;;;;;;;iBAmBc;EACf,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,MAAM;;;;;;;iBAQS,YAAY,UAAU,YAAY;EACjD;EACA,MAAM,UAAU;;EAEhB;EACA,aAAa,gBAAgB;;EAE7B;;;;;;;;EAQA,WAAW;;;;;EAKX,cAAc;;iBAGC;EACf,uBAAuB;;;;;EAKvB;;;;;;;;IAQE,cAAc,gBAAgB,OAAO,gBAAgB,QAAQ;;;;;;IAM7D,QAAQ,OAAO,kBAAkB;;;;;;;;;;;;;;;;;wBAkBrB,iBACd,SAAS;EAAuB,OAAO,YAAY;;EAEnD,SAAS;EACT,OAAO;;wBAEO,iBAAiB,SAAS;EAAuB,SAAS;;KAyDrE,WAAW,QAAQ,iBAAiB,OAAO,qBAAqB;KAChE,SAAS,UAAU,WAAW,OAAO,YAAY,OAAO,QAAQ,WAAW"}
@@ -47,6 +47,19 @@ export interface ServerEvent<T extends EventName = EventName> {
47
47
  properties?: TrackProperties<T>;
48
48
  /** When it happened, as an ISO 8601 string. */
49
49
  createdAt: string;
50
+ /**
51
+ * Where it happened, when the server knows better than any session: a Stripe payment is `web`,
52
+ * an App Store one `ios`. Read by `resolveUser`, which answers the event's `platform` (it
53
+ * decides each platform's action source): a session of this platform when the user has one,
54
+ * or something else for a user with no session at all, such as `unknown` when there is no user
55
+ * agent to send with a website event.
56
+ */
57
+ platform?: Platform;
58
+ /**
59
+ * Whether it was real, when the server knows: a store's sandbox purchase is `development` even
60
+ * in a production deployment. Read by `resolveUser`, which answers the event's `environment`.
61
+ */
62
+ environment?: Environment;
50
63
  }
51
64
  export interface ConversionsOptions {
52
65
  destinations: readonly ConversionDestination[];
@@ -56,10 +69,13 @@ export interface ConversionsOptions {
56
69
  */
57
70
  track?: {
58
71
  /**
59
- * The user behind the event, read from the host's records (see `ConversionUser`);
60
- * `undefined` for one the host has no session of, whose event is then dropped.
72
+ * The user behind the event, read from the host's records (see `ConversionUser`), given the
73
+ * event so a session of its `platform` can be preferred and its `platform` / `environment`
74
+ * answered; what it returns is what the event is sent with. `undefined` drops the event. A user
75
+ * with no session at all can still be matched by the platforms on `data` alone (a hashed
76
+ * email), so a host may answer with empty `tags` and ids of its own rather than drop it.
61
77
  */
62
- resolveUser: (userId: string) => Promise<ConversionUser | undefined>;
78
+ resolveUser: (userId: string, event: ServerEvent) => Promise<ConversionUser | undefined>;
63
79
  /**
64
80
  * Stores the event, e.g. in the events table, returning whether it was new: `track` sends
65
81
  * only an event it stored, so a webhook delivered again (its handler failed on something
@@ -1 +1 @@
1
- {"version":3,"file":"setup-conversions.d.mts","names":[],"sources":["../../src/server/setup-conversions.ts"],"mappings":";KAYK,gBAAgB;;;;;;;;;iBAUJ;WACN,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB;;;;;;wBAOtD,sBACd,UAAU,0BACV,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB,mBAC1D;;;;;;;;;;;iBAmBc;EACf,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,MAAM;;;;;;;iBAQS,YAAY,UAAU,YAAY;EACjD;EACA,MAAM,UAAU;;EAEhB;EACA,aAAa,gBAAgB;;EAE7B;;iBAGe;EACf,uBAAuB;;;;;EAKvB;;;;;IAKE,cAAc,mBAAmB,QAAQ;;;;;;IAMzC,QAAQ,OAAO,kBAAkB;;;;;;;;;;;;;;;;;wBAkBrB,iBACd,SAAS;EAAuB,OAAO,YAAY;;EAEnD,SAAS;EACT,OAAO;;wBAEO,iBAAiB,SAAS;EAAuB,SAAS;;KAyDrE,WAAW,QAAQ,iBAAiB,OAAO,qBAAqB;KAChE,SAAS,UAAU,WAAW,OAAO,YAAY,OAAO,QAAQ,WAAW"}
1
+ {"version":3,"file":"setup-conversions.d.mts","names":[],"sources":["../../src/server/setup-conversions.ts"],"mappings":";KAYK,gBAAgB;;;;;;;;;iBAUJ;WACN,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB;;;;;;wBAOtD,sBACd,UAAU,0BACV,OAAO,QAAQ,iBAAiB,MAAM,qBAAqB,mBAC1D;;;;;;;;;;;iBAmBc;EACf,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,MAAM;;;;;;;iBAQS,YAAY,UAAU,YAAY;EACjD;EACA,MAAM,UAAU;;EAEhB;EACA,aAAa,gBAAgB;;EAE7B;;;;;;;;EAQA,WAAW;;;;;EAKX,cAAc;;iBAGC;EACf,uBAAuB;;;;;EAKvB;;;;;;;;IAQE,cAAc,gBAAgB,OAAO,gBAAgB,QAAQ;;;;;;IAM7D,QAAQ,OAAO,kBAAkB;;;;;;;;;;;;;;;;;wBAkBrB,iBACd,SAAS;EAAuB,OAAO,YAAY;;EAEnD,SAAS;EACT,OAAO;;wBAEO,iBAAiB,SAAS;EAAuB,SAAS;;KAyDrE,WAAW,QAAQ,iBAAiB,OAAO,qBAAqB;KAChE,SAAS,UAAU,WAAW,OAAO,YAAY,OAAO,QAAQ,WAAW"}
@@ -25,7 +25,7 @@ function setupConversions(options) {
25
25
  */
26
26
  async function track({ resolveUser, store }, input) {
27
27
  try {
28
- const user = await resolveUser(input.userId);
28
+ const user = await resolveUser(input.userId, input);
29
29
  if (!user) {
30
30
  console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);
31
31
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"setup-conversions.mjs","names":[],"sources":["../../src/server/setup-conversions.ts"],"sourcesContent":["import type {\n Environment,\n EventName,\n Platform,\n TrackEvent,\n TrackName,\n TrackProperties,\n TrackTags,\n UserProvidedData,\n} from '../track/types';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTrackEvent = TrackEvent<any>;\n\n/**\n * Where `setupConversions` sends events: an ad platform's conversions API, from its factory\n * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a\n * CRM, its own workflows).\n *\n * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,\n * with the events' ids, and still sends to the others.\n */\nexport interface ConversionDestination {\n readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;\n}\n\n/**\n * A destination that sends only the events `accepts` lets through, and makes no request when none\n * is left: what each conversions API's factory (`metaConversions`, …) is built on.\n */\nexport function conversionDestination(\n accepts: (name: string) => boolean,\n send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>\n): ConversionDestination {\n return {\n send: async (events, data) => {\n const accepted = events.filter((event) => accepts(event.name));\n if (accepted.length > 0) await send(accepted, data);\n },\n };\n}\n\n/**\n * Who a server-only event is from, as the host knows them: what the ad platforms match a client\n * event on, read from the host's own records.\n *\n * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page\n * and user agent), with the click ids of the touch the conversion is attributed to over them.\n * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides\n * each platform's action source (website or app), as for a client event.\n * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.\n */\nexport interface ConversionUser {\n tags: TrackTags;\n visitor_id: string;\n session_id: string;\n platform: Platform;\n environment: Environment;\n data: UserProvidedData;\n}\n\n/**\n * An event the server reports on its own, with no client behind it: a webhook's purchase,\n * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from\n * being reported twice, and the platforms pair it with a browser event under the same id.\n */\nexport interface ServerEvent<T extends EventName = EventName> {\n id: string;\n name: TrackName<T>;\n /** The user it belongs to, handed to `track.resolveUser`. */\n userId: string;\n properties?: TrackProperties<T>;\n /** When it happened, as an ISO 8601 string. */\n createdAt: string;\n}\n\nexport interface ConversionsOptions {\n destinations: readonly ConversionDestination[];\n /**\n * How `track` completes and stores a server-only event. Without it `setupConversions` returns\n * only `forward`, for a host that only forwards client events.\n */\n track?: {\n /**\n * The user behind the event, read from the host's records (see `ConversionUser`);\n * `undefined` for one the host has no session of, whose event is then dropped.\n */\n resolveUser: (userId: string) => Promise<ConversionUser | undefined>;\n /**\n * Stores the event, e.g. in the events table, returning whether it was new: `track` sends\n * only an event it stored, so a webhook delivered again (its handler failed on something\n * else) is not reported twice — not every platform deduplicates a server event sent twice.\n */\n store: (event: AnyTrackEvent) => Promise<boolean>;\n };\n}\n\n/**\n * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured\n * once, with the same per-platform options as the browser integrations, so the conversions API\n * and the tag report the same events.\n *\n * - `forward(events, data)`: the events a client sent, as stored, on to every destination.\n * - `track(event)`: an event the server reports on its own (a webhook's), completed by\n * `track.resolveUser`, stored with `track.store`, then forwarded.\n *\n * Neither throws, so reporting a conversion can never fail the request it runs in — a payment\n * webhook least of all, which its provider would then deliver again and again. A failure is\n * logged with the ids of the events it lost, for them to be found and sent later: a missed\n * conversion costs less than a duplicate one, or a webhook that keeps failing.\n */\nexport function setupConversions(\n options: ConversionsOptions & { track: NonNullable<ConversionsOptions['track']> }\n): {\n forward: Forward;\n track: Track;\n};\nexport function setupConversions(options: ConversionsOptions): { forward: Forward };\nexport function setupConversions(options: ConversionsOptions) {\n const { destinations, track: trackOptions } = options;\n\n async function forward(events: AnyTrackEvent[], data: UserProvidedData = {}) {\n if (events.length === 0) return;\n // Called inside a promise: a `send` that throws synchronously rejects there instead of\n // stopping the destinations after it.\n const settled = await Promise.allSettled(\n destinations.map((d) => Promise.resolve().then(() => d.send(events, data)))\n );\n const ids = events.map((event) => event.id).join(', ');\n settled.forEach((outcome) => {\n if (outcome.status === 'rejected') {\n console.error(`Conversions not sent, events: ${ids}`, outcome.reason);\n }\n });\n }\n\n /**\n * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a\n * user with no session, an event `store` had already stored, or a failure, which is logged.\n */\n async function track<T extends EventName>(\n { resolveUser, store }: NonNullable<ConversionsOptions['track']>,\n input: ServerEvent<T>\n ): Promise<TrackEvent<T> | undefined> {\n try {\n const user = await resolveUser(input.userId);\n if (!user) {\n console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);\n return undefined;\n }\n const event: TrackEvent<T> = {\n id: input.id,\n name: input.name,\n properties: input.properties,\n tags: user.tags,\n visitor_id: user.visitor_id,\n session_id: user.session_id,\n platform: user.platform,\n environment: user.environment,\n created_at: input.createdAt,\n };\n if (!(await store(event))) return undefined;\n await forward([event], user.data);\n return event;\n } catch (e: unknown) {\n console.error(`Conversion not reported, event: ${input.id}`, e);\n return undefined;\n }\n }\n\n if (!trackOptions) return { forward };\n return { forward, track: (input: ServerEvent) => track(trackOptions, input) };\n}\n\ntype Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;\ntype Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;\n"],"mappings":";;;;;AA8BA,SAAgB,sBACd,SACA,MACuB;CACvB,OAAO,EACL,MAAM,OAAO,QAAQ,SAAS;EAC5B,MAAM,WAAW,OAAO,QAAQ,UAAU,QAAQ,MAAM,IAAI,CAAC;EAC7D,IAAI,SAAS,SAAS,GAAG,MAAM,KAAK,UAAU,IAAI;CACpD,EACF;AACF;AA8EA,SAAgB,iBAAiB,SAA6B;CAC5D,MAAM,EAAE,cAAc,OAAO,iBAAiB;CAE9C,eAAe,QAAQ,QAAyB,OAAyB,CAAC,GAAG;EAC3E,IAAI,OAAO,WAAW,GAAG;EAGzB,MAAM,UAAU,MAAM,QAAQ,WAC5B,aAAa,KAAK,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,CAC5E;EACA,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI;EACrD,QAAQ,SAAS,YAAY;GAC3B,IAAI,QAAQ,WAAW,YACrB,QAAQ,MAAM,iCAAiC,OAAO,QAAQ,MAAM;EAExE,CAAC;CACH;;;;;CAMA,eAAe,MACb,EAAE,aAAa,SACf,OACoC;EACpC,IAAI;GACF,MAAM,OAAO,MAAM,YAAY,MAAM,MAAM;GAC3C,IAAI,CAAC,MAAM;IACT,QAAQ,KAAK,mCAAmC,MAAM,GAAG,mBAAmB,MAAM,QAAQ;IAC1F;GACF;GACA,MAAM,QAAuB;IAC3B,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,MAAM,KAAK;IACX,YAAY,KAAK;IACjB,YAAY,KAAK;IACjB,UAAU,KAAK;IACf,aAAa,KAAK;IAClB,YAAY,MAAM;GACpB;GACA,IAAI,CAAE,MAAM,MAAM,KAAK,GAAI,OAAO,KAAA;GAClC,MAAM,QAAQ,CAAC,KAAK,GAAG,KAAK,IAAI;GAChC,OAAO;EACT,SAAS,GAAY;GACnB,QAAQ,MAAM,mCAAmC,MAAM,MAAM,CAAC;GAC9D;EACF;CACF;CAEA,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ;CACpC,OAAO;EAAE;EAAS,QAAQ,UAAuB,MAAM,cAAc,KAAK;CAAE;AAC9E"}
1
+ {"version":3,"file":"setup-conversions.mjs","names":[],"sources":["../../src/server/setup-conversions.ts"],"sourcesContent":["import type {\n Environment,\n EventName,\n Platform,\n TrackEvent,\n TrackName,\n TrackProperties,\n TrackTags,\n UserProvidedData,\n} from '../track/types';\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTrackEvent = TrackEvent<any>;\n\n/**\n * Where `setupConversions` sends events: an ad platform's conversions API, from its factory\n * (`metaConversions`, … next to each sender), or anything else the host forwards events to (a\n * CRM, its own workflows).\n *\n * `send` rejects when it fails, as the SDK's senders do: `setupConversions` logs the failure,\n * with the events' ids, and still sends to the others.\n */\nexport interface ConversionDestination {\n readonly send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>;\n}\n\n/**\n * A destination that sends only the events `accepts` lets through, and makes no request when none\n * is left: what each conversions API's factory (`metaConversions`, …) is built on.\n */\nexport function conversionDestination(\n accepts: (name: string) => boolean,\n send: (events: AnyTrackEvent[], data: UserProvidedData) => Promise<unknown>\n): ConversionDestination {\n return {\n send: async (events, data) => {\n const accepted = events.filter((event) => accepts(event.name));\n if (accepted.length > 0) await send(accepted, data);\n },\n };\n}\n\n/**\n * Who a server-only event is from, as the host knows them: what the ad platforms match a client\n * event on, read from the host's own records.\n *\n * - `tags`: the user's latest session's tags (their cookies — `_fbp`, `_rdt_uuid`, … — page\n * and user agent), with the click ids of the touch the conversion is attributed to over them.\n * - `visitor_id`, `session_id`, `platform`, `environment`: from that session. `platform` decides\n * each platform's action source (website or app), as for a client event.\n * - `data`: the user's identity (`email`, `user_id`, …), hashed by each sender.\n */\nexport interface ConversionUser {\n tags: TrackTags;\n visitor_id: string;\n session_id: string;\n platform: Platform;\n environment: Environment;\n data: UserProvidedData;\n}\n\n/**\n * An event the server reports on its own, with no client behind it: a webhook's purchase,\n * renewal or refund. `id` is the transaction id: `track.store` keeps a redelivered webhook from\n * being reported twice, and the platforms pair it with a browser event under the same id.\n */\nexport interface ServerEvent<T extends EventName = EventName> {\n id: string;\n name: TrackName<T>;\n /** The user it belongs to, handed to `track.resolveUser`. */\n userId: string;\n properties?: TrackProperties<T>;\n /** When it happened, as an ISO 8601 string. */\n createdAt: string;\n /**\n * Where it happened, when the server knows better than any session: a Stripe payment is `web`,\n * an App Store one `ios`. Read by `resolveUser`, which answers the event's `platform` (it\n * decides each platform's action source): a session of this platform when the user has one,\n * or something else for a user with no session at all, such as `unknown` when there is no user\n * agent to send with a website event.\n */\n platform?: Platform;\n /**\n * Whether it was real, when the server knows: a store's sandbox purchase is `development` even\n * in a production deployment. Read by `resolveUser`, which answers the event's `environment`.\n */\n environment?: Environment;\n}\n\nexport interface ConversionsOptions {\n destinations: readonly ConversionDestination[];\n /**\n * How `track` completes and stores a server-only event. Without it `setupConversions` returns\n * only `forward`, for a host that only forwards client events.\n */\n track?: {\n /**\n * The user behind the event, read from the host's records (see `ConversionUser`), given the\n * event so a session of its `platform` can be preferred and its `platform` / `environment`\n * answered; what it returns is what the event is sent with. `undefined` drops the event. A user\n * with no session at all can still be matched by the platforms on `data` alone (a hashed\n * email), so a host may answer with empty `tags` and ids of its own rather than drop it.\n */\n resolveUser: (userId: string, event: ServerEvent) => Promise<ConversionUser | undefined>;\n /**\n * Stores the event, e.g. in the events table, returning whether it was new: `track` sends\n * only an event it stored, so a webhook delivered again (its handler failed on something\n * else) is not reported twice — not every platform deduplicates a server event sent twice.\n */\n store: (event: AnyTrackEvent) => Promise<boolean>;\n };\n}\n\n/**\n * The server's counterpart of `setupAnalytics({ integrations })`: every destination configured\n * once, with the same per-platform options as the browser integrations, so the conversions API\n * and the tag report the same events.\n *\n * - `forward(events, data)`: the events a client sent, as stored, on to every destination.\n * - `track(event)`: an event the server reports on its own (a webhook's), completed by\n * `track.resolveUser`, stored with `track.store`, then forwarded.\n *\n * Neither throws, so reporting a conversion can never fail the request it runs in — a payment\n * webhook least of all, which its provider would then deliver again and again. A failure is\n * logged with the ids of the events it lost, for them to be found and sent later: a missed\n * conversion costs less than a duplicate one, or a webhook that keeps failing.\n */\nexport function setupConversions(\n options: ConversionsOptions & { track: NonNullable<ConversionsOptions['track']> }\n): {\n forward: Forward;\n track: Track;\n};\nexport function setupConversions(options: ConversionsOptions): { forward: Forward };\nexport function setupConversions(options: ConversionsOptions) {\n const { destinations, track: trackOptions } = options;\n\n async function forward(events: AnyTrackEvent[], data: UserProvidedData = {}) {\n if (events.length === 0) return;\n // Called inside a promise: a `send` that throws synchronously rejects there instead of\n // stopping the destinations after it.\n const settled = await Promise.allSettled(\n destinations.map((d) => Promise.resolve().then(() => d.send(events, data)))\n );\n const ids = events.map((event) => event.id).join(', ');\n settled.forEach((outcome) => {\n if (outcome.status === 'rejected') {\n console.error(`Conversions not sent, events: ${ids}`, outcome.reason);\n }\n });\n }\n\n /**\n * Reports a server-only event; resolves with it as sent, or `undefined` when it was not: a\n * user with no session, an event `store` had already stored, or a failure, which is logged.\n */\n async function track<T extends EventName>(\n { resolveUser, store }: NonNullable<ConversionsOptions['track']>,\n input: ServerEvent<T>\n ): Promise<TrackEvent<T> | undefined> {\n try {\n const user = await resolveUser(input.userId, input);\n if (!user) {\n console.warn(`Conversion not reported, event: ${input.id}: no session for ${input.userId}`);\n return undefined;\n }\n const event: TrackEvent<T> = {\n id: input.id,\n name: input.name,\n properties: input.properties,\n tags: user.tags,\n visitor_id: user.visitor_id,\n session_id: user.session_id,\n platform: user.platform,\n environment: user.environment,\n created_at: input.createdAt,\n };\n if (!(await store(event))) return undefined;\n await forward([event], user.data);\n return event;\n } catch (e: unknown) {\n console.error(`Conversion not reported, event: ${input.id}`, e);\n return undefined;\n }\n }\n\n if (!trackOptions) return { forward };\n return { forward, track: (input: ServerEvent) => track(trackOptions, input) };\n}\n\ntype Forward = (events: AnyTrackEvent[], data?: UserProvidedData) => Promise<void>;\ntype Track = <T extends EventName>(input: ServerEvent<T>) => Promise<TrackEvent<T> | undefined>;\n"],"mappings":";;;;;AA8BA,SAAgB,sBACd,SACA,MACuB;CACvB,OAAO,EACL,MAAM,OAAO,QAAQ,SAAS;EAC5B,MAAM,WAAW,OAAO,QAAQ,UAAU,QAAQ,MAAM,IAAI,CAAC;EAC7D,IAAI,SAAS,SAAS,GAAG,MAAM,KAAK,UAAU,IAAI;CACpD,EACF;AACF;AA8FA,SAAgB,iBAAiB,SAA6B;CAC5D,MAAM,EAAE,cAAc,OAAO,iBAAiB;CAE9C,eAAe,QAAQ,QAAyB,OAAyB,CAAC,GAAG;EAC3E,IAAI,OAAO,WAAW,GAAG;EAGzB,MAAM,UAAU,MAAM,QAAQ,WAC5B,aAAa,KAAK,MAAM,QAAQ,QAAQ,CAAC,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,CAAC,CAC5E;EACA,MAAM,MAAM,OAAO,KAAK,UAAU,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI;EACrD,QAAQ,SAAS,YAAY;GAC3B,IAAI,QAAQ,WAAW,YACrB,QAAQ,MAAM,iCAAiC,OAAO,QAAQ,MAAM;EAExE,CAAC;CACH;;;;;CAMA,eAAe,MACb,EAAE,aAAa,SACf,OACoC;EACpC,IAAI;GACF,MAAM,OAAO,MAAM,YAAY,MAAM,QAAQ,KAAK;GAClD,IAAI,CAAC,MAAM;IACT,QAAQ,KAAK,mCAAmC,MAAM,GAAG,mBAAmB,MAAM,QAAQ;IAC1F;GACF;GACA,MAAM,QAAuB;IAC3B,IAAI,MAAM;IACV,MAAM,MAAM;IACZ,YAAY,MAAM;IAClB,MAAM,KAAK;IACX,YAAY,KAAK;IACjB,YAAY,KAAK;IACjB,UAAU,KAAK;IACf,aAAa,KAAK;IAClB,YAAY,MAAM;GACpB;GACA,IAAI,CAAE,MAAM,MAAM,KAAK,GAAI,OAAO,KAAA;GAClC,MAAM,QAAQ,CAAC,KAAK,GAAG,KAAK,IAAI;GAChC,OAAO;EACT,SAAS,GAAY;GACnB,QAAQ,MAAM,mCAAmC,MAAM,MAAM,CAAC;GAC9D;EACF;CACF;CAEA,IAAI,CAAC,cAAc,OAAO,EAAE,QAAQ;CACpC,OAAO;EAAE;EAAS,QAAQ,UAAuB,MAAM,cAAc,KAAK;CAAE;AAC9E"}
@@ -34,7 +34,7 @@ async function captureTags() {
34
34
  try {
35
35
  return await require_setup_index.config.getTags();
36
36
  } catch (e) {
37
- if (e instanceof Error) console.log(e.message);
37
+ if (e instanceof Error) console.warn(e.message);
38
38
  return require_setup_index.cache.tags ?? {};
39
39
  }
40
40
  }
@@ -74,7 +74,7 @@ function callIntegrations(integrations, event) {
74
74
  try {
75
75
  return track(event.name, event.properties, event.id) === false;
76
76
  } catch (e) {
77
- if (e instanceof Error) console.log(e.message);
77
+ if (e instanceof Error) console.warn(e.message);
78
78
  return false;
79
79
  }
80
80
  });
@@ -175,7 +175,7 @@ async function flush() {
175
175
  headers = await require_setup_index.config.getHeaders();
176
176
  await Promise.all(list.map((item) => item.tagged));
177
177
  } catch (e) {
178
- if (e instanceof Error) console.log(e.message);
178
+ if (e instanceof Error) console.warn(e.message);
179
179
  return;
180
180
  }
181
181
  await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));
@@ -207,7 +207,7 @@ async function send(items, headers) {
207
207
  if (!response.ok) throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);
208
208
  items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));
209
209
  } catch (e) {
210
- if (e instanceof Error) console.log(e.message);
210
+ if (e instanceof Error) console.warn(e.message);
211
211
  fail(items, e);
212
212
  }
213
213
  }