@shware/analytics 9.0.1 → 9.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/google-data-manager.cjs +3 -3
- package/dist/server/google-data-manager.cjs.map +1 -1
- package/dist/server/google-data-manager.d.cts +15 -2
- package/dist/server/google-data-manager.d.cts.map +1 -1
- package/dist/server/google-data-manager.d.mts +15 -2
- package/dist/server/google-data-manager.d.mts.map +1 -1
- package/dist/server/google-data-manager.mjs +3 -3
- package/dist/server/google-data-manager.mjs.map +1 -1
- package/dist/server/index.d.cts +2 -2
- package/dist/server/index.d.mts +2 -2
- package/dist/server/linkedin-conversions-api.cjs +6 -1
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
- package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs +6 -1
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/dist/server/meta-capi.cjs +7 -1
- package/dist/server/meta-capi.cjs.map +1 -1
- package/dist/server/meta-capi.d.cts.map +1 -1
- package/dist/server/meta-capi.d.mts.map +1 -1
- package/dist/server/meta-capi.mjs +7 -1
- package/dist/server/meta-capi.mjs.map +1 -1
- package/dist/server/meta-conversions-api.cjs +3 -1
- package/dist/server/meta-conversions-api.cjs.map +1 -1
- package/dist/server/meta-conversions-api.d.cts.map +1 -1
- package/dist/server/meta-conversions-api.d.mts.map +1 -1
- package/dist/server/meta-conversions-api.mjs +3 -1
- package/dist/server/meta-conversions-api.mjs.map +1 -1
- package/dist/server/microsoft-conversions-api.cjs +3 -1
- package/dist/server/microsoft-conversions-api.cjs.map +1 -1
- package/dist/server/microsoft-conversions-api.d.cts.map +1 -1
- package/dist/server/microsoft-conversions-api.d.mts.map +1 -1
- package/dist/server/microsoft-conversions-api.mjs +3 -1
- package/dist/server/microsoft-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +13 -12
- package/dist/server/openai-conversions-api.cjs.map +1 -1
- package/dist/server/openai-conversions-api.d.cts.map +1 -1
- package/dist/server/openai-conversions-api.d.mts.map +1 -1
- package/dist/server/openai-conversions-api.mjs +14 -13
- package/dist/server/openai-conversions-api.mjs.map +1 -1
- package/dist/server/reddit-conversions-api.cjs +6 -2
- package/dist/server/reddit-conversions-api.cjs.map +1 -1
- package/dist/server/reddit-conversions-api.d.cts +10 -1
- package/dist/server/reddit-conversions-api.d.cts.map +1 -1
- package/dist/server/reddit-conversions-api.d.mts +10 -1
- package/dist/server/reddit-conversions-api.d.mts.map +1 -1
- package/dist/server/reddit-conversions-api.mjs +6 -2
- package/dist/server/reddit-conversions-api.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +29 -13
- package/dist/third-parties/openai-pixel.cjs.map +1 -1
- package/dist/third-parties/openai-pixel.d.cts +4 -3
- package/dist/third-parties/openai-pixel.d.cts.map +1 -1
- package/dist/third-parties/openai-pixel.d.mts +4 -3
- package/dist/third-parties/openai-pixel.d.mts.map +1 -1
- package/dist/third-parties/openai-pixel.mjs +30 -14
- package/dist/third-parties/openai-pixel.mjs.map +1 -1
- package/dist/track/oaiq.cjs +57 -9
- package/dist/track/oaiq.cjs.map +1 -1
- package/dist/track/oaiq.d.cts +33 -7
- package/dist/track/oaiq.d.cts.map +1 -1
- package/dist/track/oaiq.d.mts +33 -7
- package/dist/track/oaiq.d.mts.map +1 -1
- package/dist/track/oaiq.mjs +55 -10
- package/dist/track/oaiq.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"microsoft-conversions-api.cjs","names":["createHash","microsoftMsclkid","formatMsclkid","mapUETEvent","pageLocation","IGNORED_EVENTS","chunk","fetch"],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws\n * `sendEvents`, the token in a header and never in a URL or a log line.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. Never throws: an HTTP\n * or network failure is logged (without the token) and yields no response for that request.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n try {\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is\n // the one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Microsoft conversion, network error: ${message}`);\n }\n }\n return responses;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,WAAW;;AAGjB,MAAM,yBAAyB;AAE/B,MAAM,SAAS;AAEf,MAAM,UAAU,WAAA,GAAkBA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;;;AAQjF,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,KAAK,CAAC,CAAC,YAAY;CACvC,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CAEtB,OAAO,GADM,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GACxD,GAAG,MAAM,MAAM,KAAK,CAAC;AACtC;AAEA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,OAAO,OAAO,KAAK,KAAK,IAAI,QAAQ,OAAO,eAAe,KAAK,CAAC;AAClE;;;;;;AAOA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,OAAO,KAAK,KAAK,GAAG,OAAO;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;CAErC,MAAM,YAA4C,CAAC;CACnD,KAAK,MAAM,UAAA,GAASC,cAAAA,MAAAA,CAAM,YAAY,sBAAsB,GAAG;EAC7D,MAAM,OAAO,QAAQ;GAAE,MAAM;GAAO;GAA2B;EAAa,CAAC;EAC7E,IAAI;GACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CAAM,GAAG,SAAS,GAAG,MAAM,UAAU;IAC1D,QAAQ;IACR,SAAS;KACP,gBAAgB;KAChB,QAAQ;KACR,eAAe,UAAU;IAC3B;IACA,MAAM,KAAK,UAAU,IAAI;GAC3B,CAAC;GACD,IAAI,SAAS,IAAI;IACf,MAAM,SAAU,MAAM,SAAS,KAAK;IAIpC,IAAI,OAAO,OAAO,SAAS,QACzB,QAAQ,KACN,yDAAyD,KAAK,UAAU,OAAO,MAAM,OAAO,GAC9F;IAEF,UAAU,KAAK,MAAM;IACrB;GACF;GACA,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,SAAS,KAAK;GACpC,QAAQ,MAAM,gDAAgD,OAAO,UAAU,SAAS;EAC1F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,uDAAuD,SAAS;EAChF;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"microsoft-conversions-api.cjs","names":["createHash","microsoftMsclkid","formatMsclkid","mapUETEvent","pageLocation","IGNORED_EVENTS","chunk","fetch"],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws\n * `sendEvents`, the token in a header and never in a URL or a log line.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** `eventTime` must be \"within the last 7 days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. Never throws: an HTTP\n * or network failure is logged (without the token) and yields no response for that request.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n try {\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is\n // the one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Microsoft conversion, network error: ${message}`);\n }\n }\n return responses;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,WAAW;;AAGjB,MAAM,yBAAyB;AAE/B,MAAM,SAAS;AAEf,MAAM,UAAU,WAAA,GAAkBA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;;;AAQjF,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,MAAM,KAAK,CAAC,CAAC,YAAY;CACvC,MAAM,KAAK,MAAM,YAAY,GAAG;CAChC,IAAI,OAAO,IAAI,OAAO;CAEtB,OAAO,GADM,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,QAAQ,OAAO,EAAE,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,MAAM,GACxD,GAAG,MAAM,MAAM,KAAK,CAAC;AACtC;AAEA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,OAAO,OAAO,KAAK,KAAK,IAAI,QAAQ,OAAO,eAAe,KAAK,CAAC;AAClE;;;;;;AAOA,SAAS,UAAU,OAA+C;CAChE,MAAM,QAAQ,OAAO,KAAK,CAAC,CAAC,YAAY;CACxC,IAAI,CAAC,OAAO,OAAO,KAAA;CACnB,IAAI,OAAO,KAAK,KAAK,GAAG,OAAO;CAC/B,MAAM,QAAQ,MA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Q,UAAU,MAAM,cAAc,cAAc,MAAM,cAAc;CAC3E,IAAI,WAAW,WAAW,GAAG,OAAO,CAAC;CAErC,MAAM,YAA4C,CAAC;CACnD,KAAK,MAAM,UAAA,GAASC,cAAAA,MAAAA,CAAM,YAAY,sBAAsB,GAAG;EAC7D,MAAM,OAAO,QAAQ;GAAE,MAAM;GAAO;GAA2B;EAAa,CAAC;EAC7E,IAAI;GACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CAAM,GAAG,SAAS,GAAG,MAAM,UAAU;IAC1D,QAAQ;IACR,SAAS;KACP,gBAAgB;KAChB,QAAQ;KACR,eAAe,UAAU;IAC3B;IACA,MAAM,KAAK,UAAU,IAAI;GAC3B,CAAC;GACD,IAAI,SAAS,IAAI;IACf,MAAM,SAAU,MAAM,SAAS,KAAK;IAIpC,IAAI,OAAO,OAAO,SAAS,QACzB,QAAQ,KACN,yDAAyD,KAAK,UAAU,OAAO,MAAM,OAAO,GAC9F;IAEF,UAAU,KAAK,MAAM;IACrB;GACF;GACA,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,SAAS,KAAK;GACpC,QAAQ,MAAM,gDAAgD,OAAO,UAAU,SAAS;EAC1F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,uDAAuD,SAAS;EAChF;CACF;CACA,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"microsoft-conversions-api.d.cts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;;wBAyCgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM,kBAEN;;AAAA,UAAS,wBAAwB,mCAChC;;;;;;
|
|
1
|
+
{"version":3,"file":"microsoft-conversions-api.d.cts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;;wBAyCgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM,kBAEN;;AAAA,UAAS,wBAAwB,mCAChC;;;;;;wBAkCmB,WACpB,eACA,wBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"microsoft-conversions-api.d.mts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;;wBAyCgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM,kBAEN;;AAAA,UAAS,wBAAwB,mCAChC;;;;;;
|
|
1
|
+
{"version":3,"file":"microsoft-conversions-api.d.mts","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"mappings":";;;;;;;;wBAyCgB,eAAe;iBA2Bd;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;EACA;;;iBAIe;EACf;EACA;;EAEA;;EAEA;EACA;;EAEA;EACA;EACA;;EAEA;EACA,UAAU;EACV,aAAa;;iBAGE;;;;;EAKf;;;;;;;;;;;;EAYA;;EAEA;;;;;;EAMA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;IAAU;IAAe;IAAkB,UAAU;;;;;;;;YA4D3C,wBAAwB,KAAK;wBAEzB,eAEd,OAAO,iBACP,OAAM,kBAEN;;AAAA,UAAS,wBAAwB,mCAChC;;;;;;wBAkCmB,WACpB,eACA,wBAEA,QAAQ,mBACR,OAAM,kBACN,UAAS,8BACR,QAAQ"}
|
|
@@ -119,6 +119,8 @@ function getServerEvent(event, data = {}, options = {}) {
|
|
|
119
119
|
function compact(value) {
|
|
120
120
|
return JSON.parse(JSON.stringify(value));
|
|
121
121
|
}
|
|
122
|
+
/** `eventTime` must be "within the last 7 days"; a minute's margin for the trip. */
|
|
123
|
+
const MAX_EVENT_AGE_MS = 60474e4;
|
|
122
124
|
/**
|
|
123
125
|
* Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split
|
|
124
126
|
* into consecutive requests; one response is returned per request made. Never throws: an HTTP
|
|
@@ -126,7 +128,7 @@ function compact(value) {
|
|
|
126
128
|
*/
|
|
127
129
|
async function sendEvents(token, tagId, events, data = {}, options = {}) {
|
|
128
130
|
const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;
|
|
129
|
-
const capiEvents = events.filter((event) => pageLoads && event.name === "page_view" || !IGNORED_EVENTS.includes(event.name)).map((event) => getServerEvent(event, data, {
|
|
131
|
+
const capiEvents = events.filter((event) => pageLoads && event.name === "page_view" || !IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).map((event) => getServerEvent(event, data, {
|
|
130
132
|
consent,
|
|
131
133
|
pageLoads
|
|
132
134
|
})).filter((event) => event.eventType !== "pageLoad" || event.eventSourceUrl);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"microsoft-conversions-api.mjs","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws\n * `sendEvents`, the token in a header and never in a URL or a log line.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. Never throws: an HTTP\n * or network failure is logged (without the token) and yields no response for that request.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n try {\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is\n // the one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Microsoft conversion, network error: ${message}`);\n }\n }\n return responses;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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O,GAC9F;IAEF,UAAU,KAAK,MAAM;IACrB;GACF;GACA,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,SAAS,KAAK;GACpC,QAAQ,MAAM,gDAAgD,OAAO,UAAU,SAAS;EAC1F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,uDAAuD,SAAS;EAChF;CACF;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"microsoft-conversions-api.mjs","names":[],"sources":["../../src/server/microsoft-conversions-api.ts"],"sourcesContent":["/**\n * Microsoft Advertising Conversions API (CAPI) sender — the server-side counterpart of the UET\n * tag, in the same shape as the other senders here: a pure per-event builder, a never-throws\n * `sendEvents`, the token in a header and never in a URL or a log line.\n *\n * Microsoft's recommended deployment is hybrid: keep the UET JavaScript on the page and send the\n * same conversions here too, deduplicated by (`tagId`, `eventName`, `eventId`). Both channels in\n * this SDK are fed from the same `track()` call — the browser sends the internal name as the UET\n * action with the event id as `event_id`, and this builder sends the same name as `eventName`\n * with the same id — so the pair agrees by construction.\n *\n * The token comes from the UET tag's \"Use Conversions API\" setup step, or from the Campaign\n * Management API's `UetTagAuthKey/Query`. Access is provisioned per customer account: an account\n * whose tag setup has no \"Use Conversions API\" option has to ask Microsoft Advertising support.\n *\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration\n */\nimport { createHash } from 'node:crypto';\nimport { chunk, fetch } from '@shware/utils';\nimport { formatMsclkid } from '../click-id/index';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { mapUETEvent } from '../track/uetq';\nimport { microsoftMsclkid } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://capi.uet.microsoft.com/v1';\n\n/** The API's hard limit per request. */\nconst MAX_EVENTS_PER_REQUEST = 1000;\n\nconst SHA256 = /^[a-f0-9]{64}$/;\n\nconst sha256 = (value: string) => createHash('sha256').update(value).digest('hex');\n\n/**\n * Microsoft's email normalization: trim, drop the dots and any `+alias` from the user part —\n * for EVERY domain, unlike Google's gmail-only rule — lowercase, SHA-256. A value that is\n * already a SHA-256 hex digest passes through.\n * https://learn.microsoft.com/en-us/advertising/guides/uet-conversion-api-integration#hashed-identifiers\n */\nexport function normalizeEmail(input: string): string {\n const email = input.trim().toLowerCase();\n const at = email.lastIndexOf('@');\n if (at === -1) return email;\n const user = email.slice(0, at).replace(/\\./g, '').split('+', 1)[0] ?? '';\n return `${user}@${email.slice(at + 1)}`;\n}\n\nfunction hashEmail(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n return SHA256.test(value) ? value : sha256(normalizeEmail(value));\n}\n\n/**\n * Phones are E.164 by the schema (`+` then 11–15 digits, the range bat.js validates too); the\n * separators bat.js tolerates are stripped, and anything else is dropped rather than guessed —\n * a number with no country code hashed under an assumed one can never match.\n */\nfunction hashPhone(input: string | undefined): string | undefined {\n const value = input?.trim().toLowerCase();\n if (!value) return undefined;\n if (SHA256.test(value)) return value;\n const phone = value.replace(/[-() \\t]/g, '');\n return /^\\+\\d{11,15}$/.test(phone) ? sha256(phone) : undefined;\n}\n\nexport interface MicrosoftUserData {\n /** Microsoft click id, as a dashed UUID. */\n msclkid?: string;\n /** SHA-256 of the normalized email. */\n em?: string;\n /** SHA-256 of the E.164 phone number. */\n ph?: string;\n /** The SDK visitor id — what the client-side ID Sync pixel (`sendUETIdSync`) sends as `VID`. */\n anonymousId?: string;\n /** SHA-256 of the signed-in user id — what `sendUETIdSync` sends as `UID`. */\n externalId?: string;\n clientUserAgent?: string;\n clientIpAddress?: string;\n idfa?: string;\n gaid?: string;\n}\n\nexport interface MicrosoftItem {\n id?: string;\n name?: string;\n price?: number;\n quantity?: number;\n}\n\nexport interface MicrosoftCustomData {\n eventCategory?: string;\n eventLabel?: string;\n eventValue?: number;\n searchTerm?: string;\n transactionId?: string;\n value?: number;\n currency?: string;\n items?: MicrosoftItem[];\n itemIds?: string[];\n pageType?: string;\n ecommTotalValue?: number;\n ecommCategory?: string;\n}\n\n/** One entry of the `data` array POSTed to `/v1/{tagId}/events`. */\nexport interface MicrosoftEvent {\n eventType: 'custom' | 'pageLoad';\n eventId: string;\n /** The UET action; absent on `pageLoad` events. */\n eventName?: string;\n /** UNIX seconds, UTC; the API rejects anything older than 7 days. */\n eventTime: number;\n eventSourceUrl?: string;\n /** Links a `custom` event to its `pageLoad` event; a v4 UUID (the SDK's `page_load_id` tag). */\n pageLoadId?: string;\n referrerUrl?: string;\n pageTitle?: string;\n /** `G` granted, `D` denied. Absent means granted. */\n adStorageConsent?: 'G' | 'D';\n userData: MicrosoftUserData;\n customData?: MicrosoftCustomData;\n}\n\nexport interface MicrosoftConversionsOptions {\n /**\n * EEA/UK/CH consent for the whole batch. `denied` events are accepted but used for nothing —\n * no attribution, no audiences. Absent means granted, which is also the API's default.\n */\n consent?: 'granted' | 'denied';\n /**\n * Also send `page_view` events, as CAPI `pageLoad` events, and link every custom event to the\n * page load it happened on (`pageLoadId`, from the `page_load_id` tag). Off by default because\n * the UET JavaScript already reports every page load and the two would double-count\n * destination-URL goals; turn it on for a CAPI-only site with no tag on the page. Off, no\n * `pageLoadId` is sent either: it would point at a page load Microsoft only saw from the tag,\n * under the tag's own id.\n *\n * Not yet modelled: the revenue-only custom event a `pageLoad` needs for a destination goal\n * with variable revenue.\n */\n pageLoads?: boolean;\n /** Identifies a third-party sender in Microsoft's monitoring; leave unset for a first-party build. */\n dataProvider?: string;\n /**\n * Process the valid events of a batch and report the invalid ones, instead of the API's default\n * all-or-nothing rejection. On by default — one malformed event should cost itself, not the\n * batch it travelled with.\n */\n continueOnValidationError?: boolean;\n}\n\nexport interface MicrosoftValidationDetail {\n index?: number;\n propertyName?: string;\n attemptedValue?: unknown;\n errorMessage?: string;\n errorCode?: string;\n isWarning?: boolean;\n}\n\nexport interface MicrosoftConversionsResponse {\n eventsReceived?: number;\n error?: { code?: string; message?: string; details?: MicrosoftValidationDetail[] };\n}\n\nfunction getUserData(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): MicrosoftUserData {\n const { tags, platform, visitor_id } = event;\n const email = Array.isArray(data.email) ? data.email[0] : data.email;\n const phone = Array.isArray(data.phone_number) ? data.phone_number[0] : data.phone_number;\n const msclkid = microsoftMsclkid(tags);\n\n return {\n msclkid: msclkid ? formatMsclkid(msclkid) : undefined,\n em: hashEmail(email),\n ph: hashPhone(phone),\n // Microsoft requires this to equal the `VID` of the client-side ID Sync pixel; both sides use\n // the SDK visitor id, which every event carries and the client can always read.\n anonymousId: visitor_id || undefined,\n // Microsoft asks for an anonymized id and never a real one. SHA-256, the same digest\n // `sendUETIdSync` applies client-side, so `externalId` and the pixel's `UID` agree too.\n externalId: data.user_id ? sha256(data.user_id) : undefined,\n clientUserAgent: data.user_agent,\n clientIpAddress:\n typeof tags.ip_address === 'string' && tags.ip_address ? tags.ip_address : data.ip_address,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n gaid: platform === 'android' ? tags.advertising_id : undefined,\n };\n}\n\n// oxlint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getCustomData(event: TrackEvent<any>): MicrosoftCustomData | undefined {\n const [, params] = mapUETEvent(event.name, event.properties);\n const customData: MicrosoftCustomData = {\n eventCategory: params.event_category,\n eventLabel: params.event_label,\n eventValue: params.event_value,\n searchTerm: params.search_term,\n transactionId: params.transaction_id,\n value: params.revenue_value,\n currency: params.currency,\n items: params.items?.map(({ id, name, price, quantity }) => ({ id, name, price, quantity })),\n itemIds: Array.isArray(params.ecomm_prodid)\n ? params.ecomm_prodid\n : params.ecomm_prodid\n ? [params.ecomm_prodid]\n : undefined,\n pageType: params.ecomm_pagetype,\n ecommTotalValue: params.ecomm_totalvalue,\n ecommCategory: params.ecomm_category,\n };\n return Object.values(customData).some((value) => value !== undefined) ? customData : undefined;\n}\n\n/**\n * Build one CAPI event. `page_view` becomes a `pageLoad` event (the caller decides whether to\n * send those, see `MicrosoftConversionsOptions.pageLoads`); everything else is a `custom` event\n * named after the track event, which is also the UET action the browser sent.\n */\nexport type MicrosoftEventOptions = Pick<MicrosoftConversionsOptions, 'consent' | 'pageLoads'>;\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData = {},\n /** Options, or — the 8.3.0 signature, still accepted — the bare consent value. */\n options: MicrosoftEventOptions | MicrosoftEventOptions['consent'] = {}\n): MicrosoftEvent {\n const { consent, pageLoads = false } =\n typeof options === 'string' ? { consent: options } : options;\n const { id, name, tags, created_at } = event;\n const isPageLoad = name === 'page_view';\n\n return {\n eventType: isPageLoad ? 'pageLoad' : 'custom',\n eventId: tags.idempotency_key ?? id,\n eventName: isPageLoad ? undefined : name,\n eventTime: Math.round(new Date(created_at).getTime() / 1000),\n eventSourceUrl: pageLocation(tags),\n pageLoadId: pageLoads ? tags.page_load_id : undefined,\n referrerUrl: tags.page_referrer,\n pageTitle: tags.page_title,\n adStorageConsent: consent === 'granted' ? 'G' : consent === 'denied' ? 'D' : undefined,\n userData: getUserData(event, data),\n customData: isPageLoad ? undefined : getCustomData(event),\n };\n}\n\n/** Strip undefined fields so the wire payload carries only what was set. */\nfunction compact<T>(value: T): T {\n return JSON.parse(JSON.stringify(value)) as T;\n}\n\n/** `eventTime` must be \"within the last 7 days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\n\n/**\n * Send events to `POST /v1/{tagId}/events`. Batches above the API's 1,000-event limit are split\n * into consecutive requests; one response is returned per request made. Never throws: an HTTP\n * or network failure is logged (without the token) and yields no response for that request.\n */\nexport async function sendEvents(\n token: string,\n tagId: string | number,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n options: MicrosoftConversionsOptions = {}\n): Promise<MicrosoftConversionsResponse[]> {\n const { consent, pageLoads = false, dataProvider, continueOnValidationError = true } = options;\n\n const capiEvents = events\n .filter(\n (event) => (pageLoads && event.name === 'page_view') || !IGNORED_EVENTS.includes(event.name)\n )\n .filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS)\n .map((event) => getServerEvent(event, data, { consent, pageLoads }))\n // A pageLoad without a URL is rejected by the API, and a page-less event has nothing to say.\n .filter((event) => event.eventType !== 'pageLoad' || event.eventSourceUrl);\n if (capiEvents.length === 0) return [];\n\n const responses: MicrosoftConversionsResponse[] = [];\n for (const batch of chunk(capiEvents, MAX_EVENTS_PER_REQUEST)) {\n const body = compact({ data: batch, continueOnValidationError, dataProvider });\n try {\n const response = await fetch(`${ENDPOINT}/${tagId}/events`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n });\n if (response.ok) {\n const result = (await response.json()) as MicrosoftConversionsResponse;\n // A 200 can still carry field-level warnings (the field was removed) and, with\n // `continueOnValidationError`, skipped events. Surface them: silent partial data loss is\n // the one failure mode the caller cannot see from the status code.\n if (result.error?.details?.length) {\n console.warn(\n `Microsoft conversion accepted with validation issues: ${JSON.stringify(result.error.details)}`\n );\n }\n responses.push(result);\n continue;\n }\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Microsoft conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(`Failed to send Microsoft conversion, network error: ${message}`);\n }\n }\n return responses;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,WAAW;;AAGjB,MAAM,yBAAyB;AAE/B,MAAM,SAAS;AAEf,MAAM,UAAU,UAAkB,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;;;;;;;AAQjF,SAAgB,eAAe,OAAuB;CACpD,MAAM,QAAQ,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KAAK;GACpC,QAAQ,MAAM,gDAAgD,OAAO,UAAU,SAAS;EAC1F,SAAS,OAAO;GACd,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACrE,QAAQ,MAAM,uDAAuD,SAAS;EAChF;CACF;CACA,OAAO;AACT"}
|
|
@@ -33,23 +33,16 @@ function values(items) {
|
|
|
33
33
|
const result = [...new Set(items.filter((item) => !!item))];
|
|
34
34
|
return result.length > 0 ? result : void 0;
|
|
35
35
|
}
|
|
36
|
-
function normalizePhone(phone) {
|
|
37
|
-
const digits = phone.replace(/[\s().-]/g, "").replace(/^\+/, "").replace(/^0+/, "");
|
|
38
|
-
return /^\d{8,15}$/.test(digits) ? digits : void 0;
|
|
39
|
-
}
|
|
40
|
-
function normalizeName(name) {
|
|
41
|
-
return name?.toLowerCase().replace(/[\s!-/:-@[-`{-~]/g, "") || void 0;
|
|
42
|
-
}
|
|
43
36
|
function getUser(event, data) {
|
|
44
37
|
const hashed = (items) => values(items)?.map(sha256);
|
|
45
38
|
const addresses = list(data.address);
|
|
46
39
|
const user = {
|
|
47
40
|
obref: event.tags.__obref,
|
|
48
41
|
emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),
|
|
49
|
-
phone_numbers_sha256: hashed(list(data.phone_number).map(
|
|
42
|
+
phone_numbers_sha256: hashed(list(data.phone_number).map(require_track_oaiq.normalizeOAIPhone)),
|
|
50
43
|
external_ids_sha256: hashed([data.user_id?.trim()]),
|
|
51
|
-
first_names_sha256: hashed(addresses.map((a) =>
|
|
52
|
-
last_names_sha256: hashed(addresses.map((a) =>
|
|
44
|
+
first_names_sha256: hashed(addresses.map((a) => require_track_oaiq.normalizeOAIName(a.first_name))),
|
|
45
|
+
last_names_sha256: hashed(addresses.map((a) => require_track_oaiq.normalizeOAIName(a.last_name))),
|
|
53
46
|
regions: values(addresses.map((a) => a.region?.trim())),
|
|
54
47
|
postal_codes: values(addresses.map((a) => a.postal_code?.trim())),
|
|
55
48
|
cities: values(addresses.map((a) => a.city?.trim())),
|
|
@@ -65,7 +58,7 @@ function getServerEvent(event, data, actionSource) {
|
|
|
65
58
|
return {
|
|
66
59
|
id: event.tags.idempotency_key ?? event.id,
|
|
67
60
|
type,
|
|
68
|
-
custom_event_name: type === "custom" ? event.name : void 0,
|
|
61
|
+
custom_event_name: type === "custom" ? require_track_oaiq.oaiCustomEventName(event.name) : void 0,
|
|
69
62
|
timestamp_ms: new Date(event.created_at).getTime(),
|
|
70
63
|
source_url: require_server_page_location.pageLocation(event.tags),
|
|
71
64
|
oppref: require_server_click_ids.openaiOppref(event.tags),
|
|
@@ -74,10 +67,18 @@ function getServerEvent(event, data, actionSource) {
|
|
|
74
67
|
data: eventData
|
|
75
68
|
};
|
|
76
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* `timestamp_ms` "must be within the last 7 days and no more than 10 minutes in the future", or
|
|
72
|
+
* the request fails; such an event is left out, with a minute's margin for the trip.
|
|
73
|
+
*/
|
|
74
|
+
const MAX_EVENT_AGE_MS = 60474e4;
|
|
77
75
|
async function sendEvents(apiKey, pixelId, events, data = {}, validateOnly = false, actionSource) {
|
|
78
76
|
const dto = {
|
|
79
77
|
validate_only: validateOnly,
|
|
80
|
-
events: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).filter((event) => !require_track_oaiq.NON_AD_EVENTS.includes(event.name)).
|
|
78
|
+
events: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).filter((event) => !require_track_oaiq.NON_AD_EVENTS.includes(event.name)).filter((event) => {
|
|
79
|
+
const age = Date.now() - Date.parse(event.created_at);
|
|
80
|
+
return age <= MAX_EVENT_AGE_MS && age >= -6e5;
|
|
81
|
+
}).map((event) => getServerEvent(event, data, actionSource)).filter((event) => event.type !== "custom" || event.custom_event_name !== void 0)
|
|
81
82
|
};
|
|
82
83
|
if (dto.events.length === 0) return;
|
|
83
84
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-conversions-api.cjs","names":["createHash","resolveActionSource","mapOAIEvent","pageLocation","openaiOppref","IGNORED_EVENTS","NON_AD_EVENTS","fetch"],"sources":["../../src/server/openai-conversions-api.ts"],"sourcesContent":["/**\n * OpenAI Conversions API\n * https://developers.openai.com/ads/conversions-api\n * https://developers.openai.com/ads/supported-events\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type EventData, NON_AD_EVENTS, mapOAIEvent } from '../track/oaiq';\nimport type { Platform, TrackEvent, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { openaiOppref } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://bzr.openai.com/v1/events';\n\ntype ActionSource =\n | 'web'\n | 'mobile_app'\n | 'offline'\n | 'physical_store'\n | 'phone_call'\n | 'email'\n | 'other';\n\n/**\n * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase\n * 64-char SHA-256 hex strings; geographic values are raw. Of each list the API uses the first\n * three valid, unique values.\n * ref: https://developers.openai.com/ads/conversions-api#send-user-data\n */\nexport interface OpenAIUser {\n /** The pixel's `__obref` cookie, unhashed; ties the server event to the pixel's browser. */\n obref?: string;\n emails_sha256?: string[];\n /** 8–15 digits with the country code, no leading `+` or zeroes. */\n phone_numbers_sha256?: string[];\n external_ids_sha256?: string[];\n first_names_sha256?: string[];\n last_names_sha256?: string[];\n regions?: string[];\n postal_codes?: string[];\n cities?: string[];\n /** Two-letter ISO 3166-1 country codes (e.g. \"US\"). */\n countries?: string[];\n /** Android GAID only; IDFA is not supported. */\n android_advertising_id?: string;\n ip_address?: string;\n user_agent?: string;\n}\n\nexport interface OpenAIEvent {\n /** Unique event id; combined with `type` for deduplication against pixel events. */\n id: string;\n /** Standard event name or `custom`. */\n type: string;\n /** Required when `type` is `custom`. */\n custom_event_name?: string;\n /** Event timestamp in ms; must be within 7 days and no more than 10 minutes in the future. */\n timestamp_ms: number;\n /** Required for `action_source: \"web\"`. */\n source_url?: string;\n action_source?: ActionSource;\n /** OpenAI-provided privacy-preserving identifier. */\n oppref?: string;\n /** When true, opts the event out of personalization. */\n opt_out?: boolean;\n user?: OpenAIUser;\n data: EventData;\n}\n\nexport interface CreateOpenAIEventsDTO {\n /** When true, validates the events without persisting them. */\n validate_only?: boolean;\n events: OpenAIEvent[];\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction mapActionSource(\n platform: Platform,\n actionSource?: EventActionSource\n): ActionSource | undefined {\n switch (resolveActionSource(platform, actionSource)) {\n case 'web':\n return 'web';\n case 'app':\n return 'mobile_app';\n case 'offline':\n return 'offline';\n default:\n return undefined;\n }\n}\n\nfunction list<T>(field: T | T[] | undefined): T[] {\n if (!field) return [];\n return Array.isArray(field) ? field : [field];\n}\n\n/** The distinct non-empty values, or undefined when there are none. */\nfunction values(items: (string | undefined)[]): string[] | undefined {\n const result = [...new Set(items.filter((item): item is string => !!item))];\n return result.length > 0 ? result : undefined;\n}\n\nfunction normalizePhone(phone: string): string | undefined {\n const digits = phone\n .replace(/[\\s().-]/g, '')\n .replace(/^\\+/, '')\n .replace(/^0+/, '');\n return /^\\d{8,15}$/.test(digits) ? digits : undefined;\n}\n\n// Lowercase, without whitespace or ASCII punctuation; other characters (accents) are kept.\nfunction normalizeName(name: string | undefined): string | undefined {\n return name?.toLowerCase().replace(/[\\s!-/:-@[-`{-~]/g, '') || undefined;\n}\n\nfunction getUser(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): OpenAIUser | undefined {\n const hashed = (items: (string | undefined)[]) => values(items)?.map(sha256);\n const addresses = list(data.address);\n\n const user: OpenAIUser = {\n obref: event.tags.__obref,\n emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),\n phone_numbers_sha256: hashed(list(data.phone_number).map(normalizePhone)),\n external_ids_sha256: hashed([data.user_id?.trim()]),\n first_names_sha256: hashed(addresses.map((a) => normalizeName(a.first_name))),\n last_names_sha256: hashed(addresses.map((a) => normalizeName(a.last_name))),\n regions: values(addresses.map((a) => a.region?.trim())),\n postal_codes: values(addresses.map((a) => a.postal_code?.trim())),\n cities: values(addresses.map((a) => a.city?.trim())),\n countries: values(addresses.map((a) => a.country?.trim().toUpperCase())),\n android_advertising_id:\n event.platform === 'android' ? event.tags.advertising_id || undefined : undefined,\n ip_address: data.ip_address,\n user_agent: data.user_agent,\n };\n\n return Object.values(user).some((value) => value !== undefined) ? user : undefined;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): OpenAIEvent {\n const { type, data: eventData } = mapOAIEvent(event.name, event.properties);\n\n return {\n id: event.tags.idempotency_key ?? event.id,\n type,\n // For custom events the original track name is the OpenAI custom_event_name; this matches\n // the browser pixel so the two deduplicate. Standard events omit it.\n custom_event_name: type === 'custom' ? event.name : undefined,\n timestamp_ms: new Date(event.created_at).getTime(),\n source_url: pageLocation(event.tags),\n // The click id OpenAI appends to an ad's landing URL; what ties the conversion to the click.\n oppref: openaiOppref(event.tags),\n action_source: mapActionSource(event.platform, actionSource),\n user: getUser(event, data),\n data: eventData,\n };\n}\n\nexport async function sendEvents(\n apiKey: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n validateOnly = false,\n actionSource?: EventActionSource\n) {\n const dto: CreateOpenAIEventsDTO = {\n validate_only: validateOnly,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => !NON_AD_EVENTS.includes(event.name))\n .map((event) => getServerEvent(event, data, actionSource)),\n };\n\n if (dto.events.length === 0) return;\n\n try {\n const response = await fetch(`${ENDPOINT}?pid=${pixelId}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(dto),\n });\n\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send OpenAI conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send OpenAI conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAM,WAAW;AA+DjB,SAAS,OAAO,OAAuB;CACrC,QAAA,GAAOA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,gBACP,UACA,cAC0B;CAC1B,QAAQC,6BAAAA,oBAAoB,UAAU,YAAY,GAAlD;EACE,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE;CACJ;AACF;AAEA,SAAS,KAAQ,OAAiC;CAChD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC9C;;AAGA,SAAS,OAAO,OAAqD;CACnE,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,SAAyB,CAAC,CAAC,IAAI,CAAC,CAAC;CAC1E,OAAO,OAAO,SAAS,IAAI,SAAS,KAAA;AACtC;AAEA,SAAS,eAAe,OAAmC;CACzD,MAAM,SAAS,MACZ,QAAQ,aAAa,EAAE,CAAC,CACxB,QAAQ,OAAO,EAAE,CAAC,CAClB,QAAQ,OAAO,EAAE;CACpB,OAAO,aAAa,KAAK,MAAM,IAAI,SAAS,KAAA;AAC9C;AAGA,SAAS,cAAc,MAA8C;CACnE,OAAO,MAAM,YAAY,CAAC,CAAC,QAAQ,qBAAqB,EAAE,KAAK,KAAA;AACjE;AAEA,SAAS,QAEP,OACA,MACwB;CACxB,MAAM,UAAU,UAAkC,OAAO,KAAK,CAAC,EAAE,IAAI,MAAM;CAC3E,MA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IAAI;EAEnC,QAAQC,yBAAAA,aAAa,MAAM,IAAI;EAC/B,eAAe,gBAAgB,MAAM,UAAU,YAAY;EAC3D,MAAM,QAAQ,OAAO,IAAI;EACzB,MAAM;CACR;AACF;AAEA,eAAsB,WACpB,QACA,SAEA,QACA,OAAyB,CAAC,GAC1B,eAAe,OACf,cACA;CACA,MAAM,MAA6B;EACjC,eAAe;EACf,QAAQ,OACL,QAAQ,UAAU,CAACC,qCAAAA,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CACvD,QAAQ,UAAU,CAACC,mBAAAA,cAAc,SAAS,MAAM,IAAI,CAAC,CAAC,CACtD,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC;CAC7D;CAEA,IAAI,IAAI,OAAO,WAAW,GAAG;CAE7B,IAAI;EACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CAAM,GAAG,SAAS,OAAO,WAAW;GACzD,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CAAC;EAED,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,6CAA6C,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
|
|
1
|
+
{"version":3,"file":"openai-conversions-api.cjs","names":["createHash","resolveActionSource","normalizeOAIPhone","normalizeOAIName","mapOAIEvent","oaiCustomEventName","pageLocation","openaiOppref","IGNORED_EVENTS","NON_AD_EVENTS","fetch"],"sources":["../../src/server/openai-conversions-api.ts"],"sourcesContent":["/**\n * OpenAI Conversions API\n * https://developers.openai.com/ads/conversions-api\n * https://developers.openai.com/ads/supported-events\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport {\n type EventData,\n NON_AD_EVENTS,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { Platform, TrackEvent, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { openaiOppref } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://bzr.openai.com/v1/events';\n\ntype ActionSource =\n | 'web'\n | 'mobile_app'\n | 'offline'\n | 'physical_store'\n | 'phone_call'\n | 'email'\n | 'other';\n\n/**\n * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase\n * 64-char SHA-256 hex strings; geographic values are raw. Of each list the API uses the first\n * three valid, unique values.\n * ref: https://developers.openai.com/ads/conversions-api#send-user-data\n */\nexport interface OpenAIUser {\n /** The pixel's `__obref` cookie, unhashed; ties the server event to the pixel's browser. */\n obref?: string;\n emails_sha256?: string[];\n /** 8–15 digits with the country code, no leading `+` or zeroes. */\n phone_numbers_sha256?: string[];\n external_ids_sha256?: string[];\n first_names_sha256?: string[];\n last_names_sha256?: string[];\n regions?: string[];\n postal_codes?: string[];\n cities?: string[];\n /** Two-letter ISO 3166-1 country codes (e.g. \"US\"). */\n countries?: string[];\n /** Android GAID only; IDFA is not supported. */\n android_advertising_id?: string;\n ip_address?: string;\n user_agent?: string;\n}\n\nexport interface OpenAIEvent {\n /** Unique event id; combined with `type` for deduplication against pixel events. */\n id: string;\n /** Standard event name or `custom`. */\n type: string;\n /** Required when `type` is `custom`. */\n custom_event_name?: string;\n /** Event timestamp in ms; must be within 7 days and no more than 10 minutes in the future. */\n timestamp_ms: number;\n /** Required for `action_source: \"web\"`. */\n source_url?: string;\n action_source?: ActionSource;\n /** OpenAI-provided privacy-preserving identifier. */\n oppref?: string;\n /** When true, opts the event out of personalization. */\n opt_out?: boolean;\n user?: OpenAIUser;\n data: EventData;\n}\n\nexport interface CreateOpenAIEventsDTO {\n /** When true, validates the events without persisting them. */\n validate_only?: boolean;\n events: OpenAIEvent[];\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction mapActionSource(\n platform: Platform,\n actionSource?: EventActionSource\n): ActionSource | undefined {\n switch (resolveActionSource(platform, actionSource)) {\n case 'web':\n return 'web';\n case 'app':\n return 'mobile_app';\n case 'offline':\n return 'offline';\n default:\n return undefined;\n }\n}\n\nfunction list<T>(field: T | T[] | undefined): T[] {\n if (!field) return [];\n return Array.isArray(field) ? field : [field];\n}\n\n/** The distinct non-empty values, or undefined when there are none. */\nfunction values(items: (string | undefined)[]): string[] | undefined {\n const result = [...new Set(items.filter((item): item is string => !!item))];\n return result.length > 0 ? result : undefined;\n}\n\nfunction getUser(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): OpenAIUser | undefined {\n const hashed = (items: (string | undefined)[]) => values(items)?.map(sha256);\n const addresses = list(data.address);\n\n const user: OpenAIUser = {\n obref: event.tags.__obref,\n emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),\n phone_numbers_sha256: hashed(list(data.phone_number).map(normalizeOAIPhone)),\n external_ids_sha256: hashed([data.user_id?.trim()]),\n first_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.first_name))),\n last_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.last_name))),\n regions: values(addresses.map((a) => a.region?.trim())),\n postal_codes: values(addresses.map((a) => a.postal_code?.trim())),\n cities: values(addresses.map((a) => a.city?.trim())),\n countries: values(addresses.map((a) => a.country?.trim().toUpperCase())),\n android_advertising_id:\n event.platform === 'android' ? event.tags.advertising_id || undefined : undefined,\n ip_address: data.ip_address,\n user_agent: data.user_agent,\n };\n\n return Object.values(user).some((value) => value !== undefined) ? user : undefined;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): OpenAIEvent {\n const { type, data: eventData } = mapOAIEvent(event.name, event.properties);\n\n return {\n id: event.tags.idempotency_key ?? event.id,\n type,\n // For custom events the track name, made valid (`oaiCustomEventName`); the browser pixel\n // names it the same way, so the two deduplicate. Standard events omit it.\n custom_event_name: type === 'custom' ? oaiCustomEventName(event.name) : undefined,\n timestamp_ms: new Date(event.created_at).getTime(),\n source_url: pageLocation(event.tags),\n // The click id OpenAI appends to an ad's landing URL; what ties the conversion to the click.\n oppref: openaiOppref(event.tags),\n action_source: mapActionSource(event.platform, actionSource),\n user: getUser(event, data),\n data: eventData,\n };\n}\n\n/**\n * `timestamp_ms` \"must be within the last 7 days and no more than 10 minutes in the future\", or\n * the request fails; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\nconst MAX_EVENT_AHEAD_MS = 10 * 60 * 1000;\n\nexport async function sendEvents(\n apiKey: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n validateOnly = false,\n actionSource?: EventActionSource\n) {\n const dto: CreateOpenAIEventsDTO = {\n validate_only: validateOnly,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => !NON_AD_EVENTS.includes(event.name))\n .filter((event) => {\n const age = Date.now() - Date.parse(event.created_at);\n return age <= MAX_EVENT_AGE_MS && age >= -MAX_EVENT_AHEAD_MS;\n })\n .map((event) => getServerEvent(event, data, actionSource))\n // A custom event whose name cannot be made valid would fail the whole request.\n .filter((event) => event.type !== 'custom' || event.custom_event_name !== undefined),\n };\n\n if (dto.events.length === 0) return;\n\n try {\n const response = await fetch(`${ENDPOINT}?pid=${pixelId}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(dto),\n });\n\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send OpenAI conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send OpenAI conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAM,WAAW;AA+DjB,SAAS,OAAO,OAAuB;CACrC,QAAA,GAAOA,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,gBACP,UACA,cAC0B;CAC1B,QAAQC,6BAAAA,oBAAoB,UAAU,YAAY,GAAlD;EACE,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE;CACJ;AACF;AAEA,SAAS,KAAQ,OAAiC;CAChD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC9C;;AAGA,SAAS,OAAO,OAAqD;CACnE,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,SAAyB,CAAC,CAAC,IAAI,CAAC,CAAC;CAC1E,OAAO,OAAO,SAAS,IAAI,SAAS,KAAA;AACtC;AAEA,SAAS,QAEP,OACA,MACwB;CACxB,MAAM,UAAU,UAAkC,OAAO,KAAK,CAAC,EAAE,IAAI,MAAM;CAC3E,MAAM,YAAY,KAAK,KAAK,OAAO;CAEnC,MAAM,OAAmB;EACvB,OAAO,MAAM,KAAK;EAClB,eAAe,OAAO,KAAK,KAAK,KAAK,CAAC,CAAC,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC;EACjF,sBAAsB,OAAO,KAAK,KAAK,YAAY,CAAC,CAAC,IAAIC,mBAAAA,iBAAiB,CAAC;EAC3E,qBAAqB,OAAO,CAAC,KAAK,SAAS,KAAK,CAAC,CAAC;EAClD,oBAAoB,OAAO,UAAU,KAAK,MAAMC,mBAAAA,iBAAiB,EAAE,UAAU,CAAC,CAAC;EAC/E,mBAAmB,OAAO,UAAU,KA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UAAU,CAACC,mBAAAA,cAAc,SAAS,MAAM,IAAI,CAAC,CAAC,CACtD,QAAQ,UAAU;GACjB,MAAM,MAAM,KAAK,IAAI,IAAI,KAAK,MAAM,MAAM,UAAU;GACpD,OAAO,OAAO,oBAAoB,OAAO;EAC3C,CAAC,CAAC,CACD,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC,CAAC,CAEzD,QAAQ,UAAU,MAAM,SAAS,YAAY,MAAM,sBAAsB,KAAA,CAAS;CACvF;CAEA,IAAI,IAAI,OAAO,WAAW,GAAG;CAE7B,IAAI;EACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CAAM,GAAG,SAAS,OAAO,WAAW;GACzD,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CAAC;EAED,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,6CAA6C,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-conversions-api.d.cts","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"openai-conversions-api.d.cts","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"mappings":";;;;KAuBK;;;;;;;iBAeY;;EAEf;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;iBAGe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA,gBAAgB;;EAEhB;;EAEA;EACA,OAAO;EACP,MAAM;;iBAGS;;EAEf;EACA,QAAQ;;wBA8DM,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBA0BmB,WACpB,gBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,wBACA,eAAe,oBAAiB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-conversions-api.d.mts","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"openai-conversions-api.d.mts","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"mappings":";;;;KAuBK;;;;;;;iBAeY;;EAEf;EACA;;EAEA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;iBAGe;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;EACA,gBAAgB;;EAEhB;;EAEA;EACA,OAAO;EACP,MAAM;;iBAGS;;EAEf;EACA,QAAQ;;wBA8DM,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBA0BmB,WACpB,gBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,wBACA,eAAe,oBAAiB"}
|
|
@@ -2,7 +2,7 @@ import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
|
|
|
2
2
|
import { resolveActionSource } from "./action-source.mjs";
|
|
3
3
|
import { openaiOppref } from "./click-ids.mjs";
|
|
4
4
|
import { pageLocation } from "./page-location.mjs";
|
|
5
|
-
import { NON_AD_EVENTS, mapOAIEvent } from "../track/oaiq.mjs";
|
|
5
|
+
import { NON_AD_EVENTS, mapOAIEvent, normalizeOAIName, normalizeOAIPhone, oaiCustomEventName } from "../track/oaiq.mjs";
|
|
6
6
|
import { fetch } from "@shware/utils";
|
|
7
7
|
import { createHash } from "node:crypto";
|
|
8
8
|
//#region src/server/openai-conversions-api.ts
|
|
@@ -32,23 +32,16 @@ function values(items) {
|
|
|
32
32
|
const result = [...new Set(items.filter((item) => !!item))];
|
|
33
33
|
return result.length > 0 ? result : void 0;
|
|
34
34
|
}
|
|
35
|
-
function normalizePhone(phone) {
|
|
36
|
-
const digits = phone.replace(/[\s().-]/g, "").replace(/^\+/, "").replace(/^0+/, "");
|
|
37
|
-
return /^\d{8,15}$/.test(digits) ? digits : void 0;
|
|
38
|
-
}
|
|
39
|
-
function normalizeName(name) {
|
|
40
|
-
return name?.toLowerCase().replace(/[\s!-/:-@[-`{-~]/g, "") || void 0;
|
|
41
|
-
}
|
|
42
35
|
function getUser(event, data) {
|
|
43
36
|
const hashed = (items) => values(items)?.map(sha256);
|
|
44
37
|
const addresses = list(data.address);
|
|
45
38
|
const user = {
|
|
46
39
|
obref: event.tags.__obref,
|
|
47
40
|
emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),
|
|
48
|
-
phone_numbers_sha256: hashed(list(data.phone_number).map(
|
|
41
|
+
phone_numbers_sha256: hashed(list(data.phone_number).map(normalizeOAIPhone)),
|
|
49
42
|
external_ids_sha256: hashed([data.user_id?.trim()]),
|
|
50
|
-
first_names_sha256: hashed(addresses.map((a) =>
|
|
51
|
-
last_names_sha256: hashed(addresses.map((a) =>
|
|
43
|
+
first_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.first_name))),
|
|
44
|
+
last_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.last_name))),
|
|
52
45
|
regions: values(addresses.map((a) => a.region?.trim())),
|
|
53
46
|
postal_codes: values(addresses.map((a) => a.postal_code?.trim())),
|
|
54
47
|
cities: values(addresses.map((a) => a.city?.trim())),
|
|
@@ -64,7 +57,7 @@ function getServerEvent(event, data, actionSource) {
|
|
|
64
57
|
return {
|
|
65
58
|
id: event.tags.idempotency_key ?? event.id,
|
|
66
59
|
type,
|
|
67
|
-
custom_event_name: type === "custom" ? event.name : void 0,
|
|
60
|
+
custom_event_name: type === "custom" ? oaiCustomEventName(event.name) : void 0,
|
|
68
61
|
timestamp_ms: new Date(event.created_at).getTime(),
|
|
69
62
|
source_url: pageLocation(event.tags),
|
|
70
63
|
oppref: openaiOppref(event.tags),
|
|
@@ -73,10 +66,18 @@ function getServerEvent(event, data, actionSource) {
|
|
|
73
66
|
data: eventData
|
|
74
67
|
};
|
|
75
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* `timestamp_ms` "must be within the last 7 days and no more than 10 minutes in the future", or
|
|
71
|
+
* the request fails; such an event is left out, with a minute's margin for the trip.
|
|
72
|
+
*/
|
|
73
|
+
const MAX_EVENT_AGE_MS = 60474e4;
|
|
76
74
|
async function sendEvents(apiKey, pixelId, events, data = {}, validateOnly = false, actionSource) {
|
|
77
75
|
const dto = {
|
|
78
76
|
validate_only: validateOnly,
|
|
79
|
-
events: events.filter((event) => !IGNORED_EVENTS.includes(event.name)).filter((event) => !NON_AD_EVENTS.includes(event.name)).
|
|
77
|
+
events: events.filter((event) => !IGNORED_EVENTS.includes(event.name)).filter((event) => !NON_AD_EVENTS.includes(event.name)).filter((event) => {
|
|
78
|
+
const age = Date.now() - Date.parse(event.created_at);
|
|
79
|
+
return age <= MAX_EVENT_AGE_MS && age >= -6e5;
|
|
80
|
+
}).map((event) => getServerEvent(event, data, actionSource)).filter((event) => event.type !== "custom" || event.custom_event_name !== void 0)
|
|
80
81
|
};
|
|
81
82
|
if (dto.events.length === 0) return;
|
|
82
83
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-conversions-api.mjs","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"sourcesContent":["/**\n * OpenAI Conversions API\n * https://developers.openai.com/ads/conversions-api\n * https://developers.openai.com/ads/supported-events\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type EventData, NON_AD_EVENTS, mapOAIEvent } from '../track/oaiq';\nimport type { Platform, TrackEvent, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { openaiOppref } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://bzr.openai.com/v1/events';\n\ntype ActionSource =\n | 'web'\n | 'mobile_app'\n | 'offline'\n | 'physical_store'\n | 'phone_call'\n | 'email'\n | 'other';\n\n/**\n * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase\n * 64-char SHA-256 hex strings; geographic values are raw. Of each list the API uses the first\n * three valid, unique values.\n * ref: https://developers.openai.com/ads/conversions-api#send-user-data\n */\nexport interface OpenAIUser {\n /** The pixel's `__obref` cookie, unhashed; ties the server event to the pixel's browser. */\n obref?: string;\n emails_sha256?: string[];\n /** 8–15 digits with the country code, no leading `+` or zeroes. */\n phone_numbers_sha256?: string[];\n external_ids_sha256?: string[];\n first_names_sha256?: string[];\n last_names_sha256?: string[];\n regions?: string[];\n postal_codes?: string[];\n cities?: string[];\n /** Two-letter ISO 3166-1 country codes (e.g. \"US\"). */\n countries?: string[];\n /** Android GAID only; IDFA is not supported. */\n android_advertising_id?: string;\n ip_address?: string;\n user_agent?: string;\n}\n\nexport interface OpenAIEvent {\n /** Unique event id; combined with `type` for deduplication against pixel events. */\n id: string;\n /** Standard event name or `custom`. */\n type: string;\n /** Required when `type` is `custom`. */\n custom_event_name?: string;\n /** Event timestamp in ms; must be within 7 days and no more than 10 minutes in the future. */\n timestamp_ms: number;\n /** Required for `action_source: \"web\"`. */\n source_url?: string;\n action_source?: ActionSource;\n /** OpenAI-provided privacy-preserving identifier. */\n oppref?: string;\n /** When true, opts the event out of personalization. */\n opt_out?: boolean;\n user?: OpenAIUser;\n data: EventData;\n}\n\nexport interface CreateOpenAIEventsDTO {\n /** When true, validates the events without persisting them. */\n validate_only?: boolean;\n events: OpenAIEvent[];\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction mapActionSource(\n platform: Platform,\n actionSource?: EventActionSource\n): ActionSource | undefined {\n switch (resolveActionSource(platform, actionSource)) {\n case 'web':\n return 'web';\n case 'app':\n return 'mobile_app';\n case 'offline':\n return 'offline';\n default:\n return undefined;\n }\n}\n\nfunction list<T>(field: T | T[] | undefined): T[] {\n if (!field) return [];\n return Array.isArray(field) ? field : [field];\n}\n\n/** The distinct non-empty values, or undefined when there are none. */\nfunction values(items: (string | undefined)[]): string[] | undefined {\n const result = [...new Set(items.filter((item): item is string => !!item))];\n return result.length > 0 ? result : undefined;\n}\n\nfunction normalizePhone(phone: string): string | undefined {\n const digits = phone\n .replace(/[\\s().-]/g, '')\n .replace(/^\\+/, '')\n .replace(/^0+/, '');\n return /^\\d{8,15}$/.test(digits) ? digits : undefined;\n}\n\n// Lowercase, without whitespace or ASCII punctuation; other characters (accents) are kept.\nfunction normalizeName(name: string | undefined): string | undefined {\n return name?.toLowerCase().replace(/[\\s!-/:-@[-`{-~]/g, '') || undefined;\n}\n\nfunction getUser(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): OpenAIUser | undefined {\n const hashed = (items: (string | undefined)[]) => values(items)?.map(sha256);\n const addresses = list(data.address);\n\n const user: OpenAIUser = {\n obref: event.tags.__obref,\n emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),\n phone_numbers_sha256: hashed(list(data.phone_number).map(normalizePhone)),\n external_ids_sha256: hashed([data.user_id?.trim()]),\n first_names_sha256: hashed(addresses.map((a) => normalizeName(a.first_name))),\n last_names_sha256: hashed(addresses.map((a) => normalizeName(a.last_name))),\n regions: values(addresses.map((a) => a.region?.trim())),\n postal_codes: values(addresses.map((a) => a.postal_code?.trim())),\n cities: values(addresses.map((a) => a.city?.trim())),\n countries: values(addresses.map((a) => a.country?.trim().toUpperCase())),\n android_advertising_id:\n event.platform === 'android' ? event.tags.advertising_id || undefined : undefined,\n ip_address: data.ip_address,\n user_agent: data.user_agent,\n };\n\n return Object.values(user).some((value) => value !== undefined) ? user : undefined;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): OpenAIEvent {\n const { type, data: eventData } = mapOAIEvent(event.name, event.properties);\n\n return {\n id: event.tags.idempotency_key ?? event.id,\n type,\n // For custom events the original track name is the OpenAI custom_event_name; this matches\n // the browser pixel so the two deduplicate. Standard events omit it.\n custom_event_name: type === 'custom' ? event.name : undefined,\n timestamp_ms: new Date(event.created_at).getTime(),\n source_url: pageLocation(event.tags),\n // The click id OpenAI appends to an ad's landing URL; what ties the conversion to the click.\n oppref: openaiOppref(event.tags),\n action_source: mapActionSource(event.platform, actionSource),\n user: getUser(event, data),\n data: eventData,\n };\n}\n\nexport async function sendEvents(\n apiKey: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n validateOnly = false,\n actionSource?: EventActionSource\n) {\n const dto: CreateOpenAIEventsDTO = {\n validate_only: validateOnly,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => !NON_AD_EVENTS.includes(event.name))\n .map((event) => getServerEvent(event, data, actionSource)),\n };\n\n if (dto.events.length === 0) return;\n\n try {\n const response = await fetch(`${ENDPOINT}?pid=${pixelId}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(dto),\n });\n\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send OpenAI conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send OpenAI conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAM,WAAW;AA+DjB,SAAS,OAAO,OAAuB;CACrC,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,gBACP,UACA,cAC0B;CAC1B,QAAQ,oBAAoB,UAAU,YAAY,GAAlD;EACE,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE;CACJ;AACF;AAEA,SAAS,KAAQ,OAAiC;CAChD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,OAAO,MA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IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,6CAA6C,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
|
|
1
|
+
{"version":3,"file":"openai-conversions-api.mjs","names":[],"sources":["../../src/server/openai-conversions-api.ts"],"sourcesContent":["/**\n * OpenAI Conversions API\n * https://developers.openai.com/ads/conversions-api\n * https://developers.openai.com/ads/supported-events\n */\nimport { createHash } from 'node:crypto';\nimport { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport {\n type EventData,\n NON_AD_EVENTS,\n mapOAIEvent,\n normalizeOAIName,\n normalizeOAIPhone,\n oaiCustomEventName,\n} from '../track/oaiq';\nimport type { Platform, TrackEvent, UserProvidedData } from '../track/types';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { openaiOppref } from './click-ids';\nimport { pageLocation } from './page-location';\n\nconst ENDPOINT = 'https://bzr.openai.com/v1/events';\n\ntype ActionSource =\n | 'web'\n | 'mobile_app'\n | 'offline'\n | 'physical_store'\n | 'phone_call'\n | 'email'\n | 'other';\n\n/**\n * Conversion-matching fields, all optional. Identifiers are normalized, then sent as lowercase\n * 64-char SHA-256 hex strings; geographic values are raw. Of each list the API uses the first\n * three valid, unique values.\n * ref: https://developers.openai.com/ads/conversions-api#send-user-data\n */\nexport interface OpenAIUser {\n /** The pixel's `__obref` cookie, unhashed; ties the server event to the pixel's browser. */\n obref?: string;\n emails_sha256?: string[];\n /** 8–15 digits with the country code, no leading `+` or zeroes. */\n phone_numbers_sha256?: string[];\n external_ids_sha256?: string[];\n first_names_sha256?: string[];\n last_names_sha256?: string[];\n regions?: string[];\n postal_codes?: string[];\n cities?: string[];\n /** Two-letter ISO 3166-1 country codes (e.g. \"US\"). */\n countries?: string[];\n /** Android GAID only; IDFA is not supported. */\n android_advertising_id?: string;\n ip_address?: string;\n user_agent?: string;\n}\n\nexport interface OpenAIEvent {\n /** Unique event id; combined with `type` for deduplication against pixel events. */\n id: string;\n /** Standard event name or `custom`. */\n type: string;\n /** Required when `type` is `custom`. */\n custom_event_name?: string;\n /** Event timestamp in ms; must be within 7 days and no more than 10 minutes in the future. */\n timestamp_ms: number;\n /** Required for `action_source: \"web\"`. */\n source_url?: string;\n action_source?: ActionSource;\n /** OpenAI-provided privacy-preserving identifier. */\n oppref?: string;\n /** When true, opts the event out of personalization. */\n opt_out?: boolean;\n user?: OpenAIUser;\n data: EventData;\n}\n\nexport interface CreateOpenAIEventsDTO {\n /** When true, validates the events without persisting them. */\n validate_only?: boolean;\n events: OpenAIEvent[];\n}\n\nfunction sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction mapActionSource(\n platform: Platform,\n actionSource?: EventActionSource\n): ActionSource | undefined {\n switch (resolveActionSource(platform, actionSource)) {\n case 'web':\n return 'web';\n case 'app':\n return 'mobile_app';\n case 'offline':\n return 'offline';\n default:\n return undefined;\n }\n}\n\nfunction list<T>(field: T | T[] | undefined): T[] {\n if (!field) return [];\n return Array.isArray(field) ? field : [field];\n}\n\n/** The distinct non-empty values, or undefined when there are none. */\nfunction values(items: (string | undefined)[]): string[] | undefined {\n const result = [...new Set(items.filter((item): item is string => !!item))];\n return result.length > 0 ? result : undefined;\n}\n\nfunction getUser(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData\n): OpenAIUser | undefined {\n const hashed = (items: (string | undefined)[]) => values(items)?.map(sha256);\n const addresses = list(data.address);\n\n const user: OpenAIUser = {\n obref: event.tags.__obref,\n emails_sha256: hashed(list(data.email).map((email) => email.trim().toLowerCase())),\n phone_numbers_sha256: hashed(list(data.phone_number).map(normalizeOAIPhone)),\n external_ids_sha256: hashed([data.user_id?.trim()]),\n first_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.first_name))),\n last_names_sha256: hashed(addresses.map((a) => normalizeOAIName(a.last_name))),\n regions: values(addresses.map((a) => a.region?.trim())),\n postal_codes: values(addresses.map((a) => a.postal_code?.trim())),\n cities: values(addresses.map((a) => a.city?.trim())),\n countries: values(addresses.map((a) => a.country?.trim().toUpperCase())),\n android_advertising_id:\n event.platform === 'android' ? event.tags.advertising_id || undefined : undefined,\n ip_address: data.ip_address,\n user_agent: data.user_agent,\n };\n\n return Object.values(user).some((value) => value !== undefined) ? user : undefined;\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): OpenAIEvent {\n const { type, data: eventData } = mapOAIEvent(event.name, event.properties);\n\n return {\n id: event.tags.idempotency_key ?? event.id,\n type,\n // For custom events the track name, made valid (`oaiCustomEventName`); the browser pixel\n // names it the same way, so the two deduplicate. Standard events omit it.\n custom_event_name: type === 'custom' ? oaiCustomEventName(event.name) : undefined,\n timestamp_ms: new Date(event.created_at).getTime(),\n source_url: pageLocation(event.tags),\n // The click id OpenAI appends to an ad's landing URL; what ties the conversion to the click.\n oppref: openaiOppref(event.tags),\n action_source: mapActionSource(event.platform, actionSource),\n user: getUser(event, data),\n data: eventData,\n };\n}\n\n/**\n * `timestamp_ms` \"must be within the last 7 days and no more than 10 minutes in the future\", or\n * the request fails; such an event is left out, with a minute's margin for the trip.\n */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\nconst MAX_EVENT_AHEAD_MS = 10 * 60 * 1000;\n\nexport async function sendEvents(\n apiKey: string,\n pixelId: string,\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n events: TrackEvent<any>[],\n data: UserProvidedData = {},\n validateOnly = false,\n actionSource?: EventActionSource\n) {\n const dto: CreateOpenAIEventsDTO = {\n validate_only: validateOnly,\n events: events\n .filter((event) => !IGNORED_EVENTS.includes(event.name))\n .filter((event) => !NON_AD_EVENTS.includes(event.name))\n .filter((event) => {\n const age = Date.now() - Date.parse(event.created_at);\n return age <= MAX_EVENT_AGE_MS && age >= -MAX_EVENT_AHEAD_MS;\n })\n .map((event) => getServerEvent(event, data, actionSource))\n // A custom event whose name cannot be made valid would fail the whole request.\n .filter((event) => event.type !== 'custom' || event.custom_event_name !== undefined),\n };\n\n if (dto.events.length === 0) return;\n\n try {\n const response = await fetch(`${ENDPOINT}?pid=${pixelId}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(dto),\n });\n\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send OpenAI conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send OpenAI conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,MAAM,WAAW;AA+DjB,SAAS,OAAO,OAAuB;CACrC,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,KAAK;AACxD;AAEA,SAAS,gBACP,UACA,cAC0B;CAC1B,QAAQ,oBAAoB,UAAU,YAAY,GAAlD;EACE,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE;CACJ;AACF;AAEA,SAAS,KAAQ,OAAiC;CAChD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AAC9C;;AAGA,SAAS,OAAO,OAAqD;CACnE,MAAM,SAAS,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,SAAyB,CAAC,CAAC,IAAI,CAAC,CAAC;CAC1E,OAAO,OAAO,SAAS,IAAI,SAAS,KAAA;AACtC;AAEA,SAAS,QAEP,OACA,MACwB;CACxB,MAAM,UAAU,UAAkC,OAAO,KAAK,CAAC,EAAE,IAAI,MAAM;CAC3E,MAAM,YAAY,KAAK,KAAK,OAAO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Aa,MAAM,IAAI;EAC/B,eAAe,gBAAgB,MAAM,UAAU,YAAY;EAC3D,MAAM,QAAQ,OAAO,IAAI;EACzB,MAAM;CACR;AACF;;;;;AAMA,MAAM,mBAAmB;AAGzB,eAAsB,WACpB,QACA,SAEA,QACA,OAAyB,CAAC,GAC1B,eAAe,OACf,cACA;CACA,MAAM,MAA6B;EACjC,eAAe;EACf,QAAQ,OACL,QAAQ,UAAU,CAAC,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CACvD,QAAQ,UAAU,CAAC,cAAc,SAAS,MAAM,IAAI,CAAC,CAAC,CACtD,QAAQ,UAAU;GACjB,MAAM,MAAM,KAAK,IAAI,IAAI,KAAK,MAAM,MAAM,UAAU;GACpD,OAAO,OAAO,oBAAoB,OAAO;EAC3C,CAAC,CAAC,CACD,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC,CAAC,CAEzD,QAAQ,UAAU,MAAM,SAAS,YAAY,MAAM,sBAAsB,KAAA,CAAS;CACvF;CAEA,IAAI,IAAI,OAAO,WAAW,GAAG;CAE7B,IAAI;EACF,MAAM,WAAW,MAAM,MAAM,GAAG,SAAS,OAAO,WAAW;GACzD,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CAAC;EAED,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,6CAA6C,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
|
|
@@ -3,6 +3,7 @@ const require_third_parties_ignored_events = require("../third-parties/ignored-e
|
|
|
3
3
|
const require_utils_field = require("../utils/field.cjs");
|
|
4
4
|
const require_server_action_source = require("./action-source.cjs");
|
|
5
5
|
const require_server_click_ids = require("./click-ids.cjs");
|
|
6
|
+
const require_server_page_location = require("./page-location.cjs");
|
|
6
7
|
const require_track_rdt = require("../track/rdt.cjs");
|
|
7
8
|
let _shware_utils = require("@shware/utils");
|
|
8
9
|
//#region src/server/reddit-conversions-api.ts
|
|
@@ -13,7 +14,8 @@ function getServerEvent(event, data, actionSource) {
|
|
|
13
14
|
return {
|
|
14
15
|
click_id: require_server_click_ids.redditClickId(tags),
|
|
15
16
|
event_at: new Date(created_at).getTime(),
|
|
16
|
-
action_source: source === "web" ? "WEBSITE" : source === "app" ? "APP" : "
|
|
17
|
+
action_source: source === "web" ? "WEBSITE" : source === "app" ? "APP" : "OTHER",
|
|
18
|
+
event_source_url: source === "web" ? require_server_page_location.pageLocation(tags) : void 0,
|
|
17
19
|
type: {
|
|
18
20
|
tracking_type: type === "Custom" ? "CUSTOM" : require_track_rdt.mapServerStandardEvent(type),
|
|
19
21
|
custom_event_name: type === "Custom" ? params.customEventName : void 0
|
|
@@ -41,10 +43,12 @@ function getServerEvent(event, data, actionSource) {
|
|
|
41
43
|
}
|
|
42
44
|
};
|
|
43
45
|
}
|
|
46
|
+
/** `event_at` "can't be older than seven days"; a minute's margin for the trip. */
|
|
47
|
+
const MAX_EVENT_AGE_MS = 60474e4;
|
|
44
48
|
async function sendEvents(accessToken, pixelId, events, data = {}, testId, actionSource) {
|
|
45
49
|
const dto = { data: {
|
|
46
50
|
test_id: testId,
|
|
47
|
-
events: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).map((event) => getServerEvent(event, data, actionSource))
|
|
51
|
+
events: events.filter((event) => !require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)).filter((event) => Date.now() - Date.parse(event.created_at) <= MAX_EVENT_AGE_MS).map((event) => getServerEvent(event, data, actionSource))
|
|
48
52
|
} };
|
|
49
53
|
if (dto.data.events.length === 0) return;
|
|
50
54
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.cjs","names":["mapRDTEvent","resolveActionSource","redditClickId","mapServerStandardEvent","getFirst","redditUuid","IGNORED_EVENTS","fetch"],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent, mapRDTEvent, mapServerStandardEvent } from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n action_source: 'WEBSITE' | 'APP' |
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.cjs","names":["mapRDTEvent","resolveActionSource","redditClickId","pageLocation","mapServerStandardEvent","getFirst","redditUuid","IGNORED_EVENTS","fetch"],"sources":["../../src/server/reddit-conversions-api.ts"],"sourcesContent":["import { fetch } from '@shware/utils';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { type ServerStandardEvent, mapRDTEvent, mapServerStandardEvent } from '../track/rdt';\nimport type { TrackEvent, UserProvidedData } from '../track/types';\nimport { getFirst } from '../utils/field';\nimport { type EventActionSource, resolveActionSource } from './action-source';\nimport { redditClickId, redditUuid } from './click-ids';\nimport { pageLocation } from './page-location';\n\n/**\n * https://ads-api.reddit.com/docs/v3/operations/Post%20Conversion%20Events\n * https://business.reddithelp.com/s/article/map-a-catalog-to-a-signal-source\n */\nexport interface RedditEvent {\n /** Match keys: Share user identifiers to match conversions to a Reddit ad engagement. */\n click_id?: string;\n\n /** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */\n event_at: number;\n\n /**\n * Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.\n * https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels\n */\n action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';\n\n /**\n * The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the\n * click id when `click_id` is missing.\n */\n event_source_url?: string;\n\n type: {\n tracking_type: ServerStandardEvent | 'CUSTOM';\n custom_event_name?: string;\n };\n\n /**\n * Event metadata\n * Share as much additional information about your conversion event as you'd like. If you're\n * using the Conversions API with the pixel, conversion_id is required for deduplication.\n */\n metadata?: {\n conversion_id?: string;\n currency?: string; // ISO 4217 3-letter currency code\n item_count?: number;\n value?: number;\n products?: { id: string; name?: string; category?: string }[];\n };\n\n user?: {\n email?: string;\n external_id?: string;\n ip_address?: string;\n phone_number?: string;\n user_agent?: string;\n\n /** The Identifier for Advertisers (IDFA) of the user's Apple device. */\n idfa?: string;\n\n /** The Android Advertising ID (AAID) of the user's Android device. */\n aaid?: string;\n /**\n * The value from the first-party Pixel _rdt_uuid cookie on your domain. Note that it is in\n * the {timestamp}.{uuid} format. You may use the full value or just the UUID portion.\n * Example: 1684189007728.7c73f2ae-a433-4d7b-9838-f467da98f48e\n */\n uuid?: string;\n\n screen_dimensions?: { width: number; height: number };\n\n /**\n * A structure of data processing options to specify the processing type for the event\n * https://business.reddithelp.com/s/article/Limited-Data-Use\n */\n data_processing_options?: {\n country: string;\n region: string;\n modes: string[] | ['LDU'];\n };\n };\n}\n\nexport interface CreateRedditEventDTO {\n data: { test_id?: string; events: RedditEvent[] };\n}\n\nexport function getServerEvent(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n event: TrackEvent<any>,\n data: UserProvidedData,\n actionSource?: EventActionSource\n): RedditEvent {\n const { id, name, properties, tags, platform, created_at } = event;\n const [type, params] = mapRDTEvent(name, properties, id);\n // An offline conversion — in store, from a CRM, over the phone — is `OTHER` rather than\n // `PHYSICAL_STORE`, which only one of those is; so is an undeterminable platform.\n const source = resolveActionSource(platform, actionSource);\n\n return {\n click_id: redditClickId(tags),\n event_at: new Date(created_at).getTime(),\n action_source: source === 'web' ? 'WEBSITE' : source === 'app' ? 'APP' : 'OTHER',\n event_source_url: source === 'web' ? pageLocation(tags) : undefined,\n type: {\n tracking_type: type === 'Custom' ? 'CUSTOM' : mapServerStandardEvent(type),\n custom_event_name: type === 'Custom' ? params.customEventName : undefined,\n },\n metadata: {\n conversion_id: id,\n currency:\n 'currency' in params && typeof params.currency === 'string'\n ? params.currency.toUpperCase()\n : undefined,\n item_count:\n 'itemCount' in params && typeof params.itemCount === 'number'\n ? params.itemCount\n : undefined,\n value: 'value' in params && typeof params.value === 'number' ? params.value : undefined,\n products:\n 'products' in params && Array.isArray(params.products) && params.products.length > 0\n ? params.products\n : undefined,\n },\n user: {\n email: getFirst(data.email),\n external_id: data.user_id,\n ip_address: data.ip_address,\n phone_number: getFirst(data.phone_number),\n user_agent: data.user_agent,\n idfa: platform === 'ios' ? tags.advertising_id : undefined,\n aaid: platform === 'android' ? tags.advertising_id : undefined,\n uuid: redditUuid(tags),\n screen_dimensions:\n tags.screen_width && tags.screen_height\n ? { width: tags.screen_width, height: tags.screen_height }\n : undefined,\n },\n };\n}\n\n/** `event_at` \"can't be older than seven days\"; a minute's margin for the trip. */\nconst MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000 - 60 * 1000;\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 testId?: string,\n actionSource?: EventActionSource\n) {\n const dto: CreateRedditEventDTO = {\n data: {\n test_id: testId,\n events: 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) => getServerEvent(event, data, actionSource)),\n },\n };\n\n if (dto.data.events.length === 0) return;\n\n try {\n const response = await fetch(\n `https://ads-api.reddit.com/api/v3/pixels/${pixelId}/conversion_events`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(dto),\n }\n );\n if (response.ok) return;\n const { status } = response;\n const message = await response.text();\n console.error(`Failed to send Reddit conversion, status: ${status}, body: ${message}`);\n } catch (error) {\n console.error('Failed to send Reddit conversion, network error:', error);\n }\n}\n"],"mappings":";;;;;;;;;AAuFA,SAAgB,eAEd,OACA,MACA,cACa;CACb,MAAM,EAAE,IAAI,MAAM,YAAY,MAAM,UAAU,eAAe;CAC7D,MAAM,CAAC,MAAM,UAAUA,kBAAAA,YAAY,MAAM,YAAY,EAAE;CAGvD,MAAM,SAASC,6BAAAA,oBAAoB,UAAU,YAAY;CAEzD,OAAO;EACL,UAAUC,yBAAAA,cAAc,IAAI;EAC5B,UAAU,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ;EACvC,eAAe,WAAW,QAAQ,YAAY,WAAW,QAAQ,QAAQ;EACzE,kBAAkB,WAAW,QAAQC,6BAAAA,aAAa,IAAI,IAAI,KAAA;EAC1D,MAAM;GACJ,eAAe,SAAS,WAAW,WAAWC,kBAAAA,uBAAuB,IAAI;GACzE,mBAAmB,SAAS,WAAW,OAAO,kBAAkB,KAAA;EAClE;EACA,UAAU;GACR,eAAe;GACf,UACE,cAAc,UAAU,OAAO,OAAO,aAAa,WAC/C,OAAO,SAAS,YAAY,IAC5B,KAAA;GACN,YACE,eAAe,UAAU,OAAO,OAAO,cAAc,WACjD,OAAO,YACP,KAAA;GACN,OAAO,WAAW,UAAU,OAAO,OAAO,UAAU,WAAW,OAAO,QAAQ,KAAA;GAC9E,UACE,cAAc,UAAU,MAAM,QAAQ,OAAO,QAAQ,KAAK,OAAO,SAAS,SAAS,IAC/E,OAAO,WACP,KAAA;EACR;EACA,MAAM;GACJ,OAAOC,oBAAAA,SAAS,KAAK,KAAK;GAC1B,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,cAAcA,oBAAAA,SAAS,KAAK,YAAY;GACxC,YAAY,KAAK;GACjB,MAAM,aAAa,QAAQ,KAAK,iBAAiB,KAAA;GACjD,MAAM,aAAa,YAAY,KAAK,iBAAiB,KAAA;GACrD,MAAMC,yBAAAA,WAAW,IAAI;GACrB,mBACE,KAAK,gBAAgB,KAAK,gBACtB;IAAE,OAAO,KAAK;IAAc,QAAQ,KAAK;GAAc,IACvD,KAAA;EACR;CACF;AACF;;AAGA,MAAM,mBAAmB;AAEzB,eAAsB,WACpB,aACA,SAEA,QACA,OAAyB,CAAC,GAC1B,QACA,cACA;CACA,MAAM,MAA4B,EAChC,MAAM;EACJ,SAAS;EACT,QAAQ,OACL,QAAQ,UAAU,CAACC,qCAAAA,eAAe,SAAS,MAAM,IAAI,CAAC,CAAC,CACvD,QAAQ,UAAU,KAAK,IAAI,IAAI,KAAK,MAAM,MAAM,UAAU,KAAK,gBAAgB,CAAC,CAChF,KAAK,UAAU,eAAe,OAAO,MAAM,YAAY,CAAC;CAC7D,EACF;CAEA,IAAI,IAAI,KAAK,OAAO,WAAW,GAAG;CAElC,IAAI;EACF,MAAM,WAAW,OAAA,GAAMC,cAAAA,MAAAA,CACrB,4CAA4C,QAAQ,qBACpD;GACE,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,QAAQ;IACR,eAAe,UAAU;GAC3B;GACA,MAAM,KAAK,UAAU,GAAG;EAC1B,CACF;EACA,IAAI,SAAS,IAAI;EACjB,MAAM,EAAE,WAAW;EACnB,MAAM,UAAU,MAAM,SAAS,KAAK;EACpC,QAAQ,MAAM,6CAA6C,OAAO,UAAU,SAAS;CACvF,SAAS,OAAO;EACd,QAAQ,MAAM,oDAAoD,KAAK;CACzE;AACF"}
|
|
@@ -11,7 +11,16 @@ export interface RedditEvent {
|
|
|
11
11
|
click_id?: string;
|
|
12
12
|
/** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */
|
|
13
13
|
event_at: number;
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.
|
|
16
|
+
* https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels
|
|
17
|
+
*/
|
|
18
|
+
action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';
|
|
19
|
+
/**
|
|
20
|
+
* The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the
|
|
21
|
+
* click id when `click_id` is missing.
|
|
22
|
+
*/
|
|
23
|
+
event_source_url?: string;
|
|
15
24
|
type: {
|
|
16
25
|
tracking_type: ServerStandardEvent | 'CUSTOM';
|
|
17
26
|
custom_event_name?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.d.cts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.d.cts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;iBAaiB;;EAEf;;EAGA;;;;;EAMA;;;;;EAMA;EAEA;IACE,eAAe;IACf;;;;;;;EAQF;IACE;IACA;IACA;IACA;IACA;MAAa;MAAY;MAAe;;;EAG1C;IACE;IACA;IACA;IACA;IACA;;IAGA;;IAGA;;;;;;IAMA;IAEA;MAAsB;MAAe;;;;;;IAMrC;MACE;MACA;MACA;;;;iBAKW;EACf;IAAQ;IAAkB,QAAQ;;;wBAGpB,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBAoDmB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,iBACA,eAAe,oBAAiB"}
|
|
@@ -11,7 +11,16 @@ export interface RedditEvent {
|
|
|
11
11
|
click_id?: string;
|
|
12
12
|
/** Unix epoch timestamp in milliseconds, event_at can't be older than seven days. */
|
|
13
13
|
event_at: number;
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Where the conversion happened. Pixel events are deduplicated only against `WEBSITE` ones.
|
|
16
|
+
* https://business.reddithelp.com/s/article/Conversions-API#measure-impact-across-channels
|
|
17
|
+
*/
|
|
18
|
+
action_source: 'WEBSITE' | 'APP' | 'PHYSICAL_STORE' | 'OTHER';
|
|
19
|
+
/**
|
|
20
|
+
* The page the event happened on, for `WEBSITE` events: Reddit reads the domain from it, and the
|
|
21
|
+
* click id when `click_id` is missing.
|
|
22
|
+
*/
|
|
23
|
+
event_source_url?: string;
|
|
15
24
|
type: {
|
|
16
25
|
tracking_type: ServerStandardEvent | 'CUSTOM';
|
|
17
26
|
custom_event_name?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reddit-conversions-api.d.mts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"reddit-conversions-api.d.mts","names":[],"sources":["../../src/server/reddit-conversions-api.ts"],"mappings":";;;;;;;;iBAaiB;;EAEf;;EAGA;;;;;EAMA;;;;;EAMA;EAEA;IACE,eAAe;IACf;;;;;;;EAQF;IACE;IACA;IACA;IACA;IACA;MAAa;MAAY;MAAe;;;EAG1C;IACE;IACA;IACA;IACA;IACA;;IAGA;;IAGA;;;;;;IAMA;IAEA;MAAsB;MAAe;;;;;;IAMrC;MACE;MACA;MACA;;;;iBAKW;EACf;IAAQ;IAAkB,QAAQ;;;wBAGpB,eAEd,OAAO,iBACP,MAAM,kBACN,eAAe,oBACd;wBAoDmB,WACpB,qBACA,iBAEA,QAAQ,mBACR,OAAM,kBACN,iBACA,eAAe,oBAAiB"}
|