tracklane 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -92,7 +92,7 @@ build, so it is never ahead of the library.
92
92
  | GA4 | Measurement Protocol | shipped |
93
93
  | Meta | Conversions API | shipped |
94
94
  | LinkedIn | Conversions API | next |
95
- | PostHog | Capture API | next |
95
+ | PostHog | Capture API | shipped |
96
96
  | X | Conversions API | next |
97
97
 
98
98
  <!-- providers:end -->
@@ -100,6 +100,65 @@ interface MetaServerConfig {
100
100
  */
101
101
  declare function meta$1(credentials: MetaServerCredentials, config?: MetaServerConfig): ServerProvider;
102
102
  //#endregion
103
+ //#region src/providers/posthog.server.d.ts
104
+ /** Credentials for PostHog's Capture API. */
105
+ interface PosthogServerCredentials {
106
+ /** The project API key, the same one the browser SDK is initialised with (`phc_...`). */
107
+ apiKey: string;
108
+ /**
109
+ * Where this project ingests events, when it is not PostHog's default US
110
+ * Cloud instance — `https://eu.i.posthog.com` for the EU Cloud, or a
111
+ * self-hosted deployment's own origin. Defaults to `https://us.i.posthog.com`.
112
+ */
113
+ host?: string;
114
+ }
115
+ /** Optional configuration for the PostHog server provider. */
116
+ interface PosthogServerConfig {
117
+ /**
118
+ * How this project spells each canonical event. Rarely needed: `capture()`
119
+ * accepts any string, so the canonical vocabulary already is PostHog's.
120
+ */
121
+ events?: Record<string, EventBinding<string>>;
122
+ }
123
+ /**
124
+ * PostHog on the server, through the Capture API.
125
+ *
126
+ * **Deduplicating a retried webhook takes two things, not one.** `dedupId`
127
+ * becomes PostHog's `uuid`, and PostHog collapses events sharing `uuid`, event
128
+ * name, timestamp and `distinct_id` — so a `timestamp` left to default to the
129
+ * clock differs on the retry and nothing is deduplicated. Pin it to a value
130
+ * derived from the order, as below. The `dedupId` itself must be a UUID:
131
+ * anything else is reported through `onError` and sent without the field,
132
+ * because PostHog rejects other shapes rather than ignoring them.
133
+ *
134
+ * Deduplication is also eventual, happening during a background merge, so both
135
+ * rows are visible for a while and a test that counts immediately will fail.
136
+ *
137
+ * @param credentials - The project API key, and the ingestion host for
138
+ * anything other than PostHog's default US Cloud instance.
139
+ * @param config - Rarely needed event name overrides.
140
+ * @returns A provider for `createTracking` from `tracklane/server`.
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * import { createTracking, posthog } from 'tracklane/server';
145
+ *
146
+ * const { track } = createTracking({
147
+ * providers: [posthog({ apiKey: process.env.POSTHOG_API_KEY! })],
148
+ * });
149
+ *
150
+ * // Both fields come from the order, so the payment provider's second
151
+ * // delivery of the same webhook produces the same event.
152
+ * await track('purchase', order, {
153
+ * user: { userId: order.userId },
154
+ * cookies: request.headers.get('cookie'),
155
+ * dedupId: order.eventId, // a UUID your checkout minted with the order
156
+ * timestamp: order.paidAt,
157
+ * });
158
+ * ```
159
+ */
160
+ declare function posthog$1(credentials: PosthogServerCredentials, config?: PosthogServerConfig): ServerProvider;
161
+ //#endregion
103
162
  //#region src/vocabulary.d.ts
104
163
  /**
105
164
  * The vocabulary shared by the browser and server libraries.
@@ -459,6 +518,38 @@ interface MetaBrowserConfig {
459
518
  */
460
519
  declare function meta(config?: MetaBrowserConfig): BrowserProvider;
461
520
  //#endregion
521
+ //#region src/providers/posthog.browser.d.ts
522
+ /** Optional configuration for the PostHog browser provider. */
523
+ interface PosthogBrowserConfig {
524
+ /**
525
+ * How this project spells each canonical event. Rarely needed: `capture()`
526
+ * accepts any string, so the canonical vocabulary already is PostHog's.
527
+ */
528
+ events?: Record<string, EventBinding<string>>;
529
+ }
530
+ /**
531
+ * PostHog in the browser, through `posthog-js`.
532
+ *
533
+ * **This provider does not load PostHog's snippet.** It belongs on the page,
534
+ * installed the way PostHog documents it: a snippet in the HTML, or a tag
535
+ * manager. This library talks to the instance that is already there; it
536
+ * never injects a third-party script into your page.
537
+ *
538
+ * @param config - Rarely needed event name overrides.
539
+ * @returns A provider for `createTracking` from `tracklane/browser`.
540
+ *
541
+ * @example
542
+ * ```ts
543
+ * import { createTracking, posthog } from 'tracklane/browser';
544
+ *
545
+ * // PostHog's own snippet is already in the page.
546
+ * const { track } = createTracking({ providers: [posthog()] });
547
+ *
548
+ * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
549
+ * ```
550
+ */
551
+ declare function posthog(config?: PosthogBrowserConfig): BrowserProvider;
552
+ //#endregion
462
553
  //#region src/browser.d.ts
463
554
  /**
464
555
  * Everything the browser needs beyond the event itself.
@@ -548,5 +639,5 @@ interface BrowserTracking {
548
639
  */
549
640
  declare function createTracking(options: BrowserTrackingOptions): BrowserTracking;
550
641
  //#endregion
551
- export { UserData as C, Ga4ServerConfig as D, meta$1 as E, Ga4ServerCredentials as O, TrackingError as S, MetaServerCredentials as T, ConsentState as _, createTracking as a, EventItem as b, Ga4BrowserConfig as c, ResolvedContext as d, ServerProvider as f, ActionSource as g, createTracking$1 as h, TrackOptions as i, ga4$1 as k, ga4 as l, ServerTrackingOptions as m, BrowserTracking as n, MetaBrowserConfig as o, ServerTracking as p, BrowserTrackingOptions as r, meta as s, BrowserProvider as t, EventContext as u, EventBinding as v, MetaServerConfig as w, ProviderDefault as x, EventData as y };
552
- //# sourceMappingURL=browser-DmJeRMFB.d.ts.map
642
+ export { MetaServerCredentials as A, ProviderDefault as C, PosthogServerCredentials as D, PosthogServerConfig as E, Ga4ServerConfig as M, Ga4ServerCredentials as N, posthog$1 as O, ga4$1 as P, EventItem as S, UserData as T, createTracking$1 as _, createTracking as a, EventBinding as b, MetaBrowserConfig as c, ga4 as d, EventContext as f, ServerTrackingOptions as g, ServerTracking as h, TrackOptions as i, meta$1 as j, MetaServerConfig as k, meta as l, ServerProvider as m, BrowserTracking as n, PosthogBrowserConfig as o, ResolvedContext as p, BrowserTrackingOptions as r, posthog as s, BrowserProvider as t, Ga4BrowserConfig as u, ActionSource as v, TrackingError as w, EventData as x, ConsentState as y };
643
+ //# sourceMappingURL=browser-CddkJdvX.d.ts.map
package/dist/browser.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as createTracking, c as Ga4BrowserConfig, i as TrackOptions, l as ga4, n as BrowserTracking, o as MetaBrowserConfig, r as BrowserTrackingOptions, s as meta, t as BrowserProvider } from "./browser-DmJeRMFB.js";
2
- export { BrowserProvider, BrowserTracking, BrowserTrackingOptions, type Ga4BrowserConfig, type MetaBrowserConfig, TrackOptions, createTracking, ga4, meta };
1
+ import { a as createTracking, c as MetaBrowserConfig, d as ga4, i as TrackOptions, l as meta, n as BrowserTracking, o as PosthogBrowserConfig, r as BrowserTrackingOptions, s as posthog, t as BrowserProvider, u as Ga4BrowserConfig } from "./browser-CddkJdvX.js";
2
+ export { BrowserProvider, BrowserTracking, BrowserTrackingOptions, type Ga4BrowserConfig, type MetaBrowserConfig, type PosthogBrowserConfig, TrackOptions, createTracking, ga4, meta, posthog };
package/dist/browser.js CHANGED
@@ -264,6 +264,64 @@ function meta(config = {}) {
264
264
  };
265
265
  }
266
266
  //#endregion
267
+ //#region src/providers/posthog.browser.ts
268
+ function posthogWindow() {
269
+ return typeof window === "undefined" ? void 0 : window;
270
+ }
271
+ /**
272
+ * Returns the vendor SDK, or fails the way a hand-written call would.
273
+ *
274
+ * Calling `posthog.capture(...)` on a page without PostHog's snippet throws,
275
+ * and this library replicates that rather than swallowing it: a silent no-op
276
+ * is how a host ends up believing it is measuring something.
277
+ */
278
+ function sdk() {
279
+ const instance = posthogWindow()?.posthog;
280
+ if (!instance) throw new Error("posthog: window.posthog is not defined. Add PostHog's snippet to the page before creating tracking.");
281
+ return instance;
282
+ }
283
+ /**
284
+ * PostHog in the browser, through `posthog-js`.
285
+ *
286
+ * **This provider does not load PostHog's snippet.** It belongs on the page,
287
+ * installed the way PostHog documents it: a snippet in the HTML, or a tag
288
+ * manager. This library talks to the instance that is already there; it
289
+ * never injects a third-party script into your page.
290
+ *
291
+ * @param config - Rarely needed event name overrides.
292
+ * @returns A provider for `createTracking` from `tracklane/browser`.
293
+ *
294
+ * @example
295
+ * ```ts
296
+ * import { createTracking, posthog } from 'tracklane/browser';
297
+ *
298
+ * // PostHog's own snippet is already in the page.
299
+ * const { track } = createTracking({ providers: [posthog()] });
300
+ *
301
+ * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
302
+ * ```
303
+ */
304
+ function posthog(config = {}) {
305
+ const { events } = config;
306
+ return {
307
+ name: "posthog",
308
+ default: "passthrough",
309
+ ...events ? { events } : {},
310
+ track(name, data, _options) {
311
+ sdk().capture(name, data);
312
+ },
313
+ identify(user, traits) {
314
+ if (user.userId !== void 0) sdk().identify(user.userId);
315
+ if (traits) sdk().setPersonProperties(traits);
316
+ },
317
+ consent(_command, state) {
318
+ const { analytics_storage } = state;
319
+ if (analytics_storage === "denied") sdk().opt_out_capturing();
320
+ else if (analytics_storage === "granted") sdk().opt_in_capturing();
321
+ }
322
+ };
323
+ }
324
+ //#endregion
267
325
  //#region src/browser.ts
268
326
  /**
269
327
  * Creates the browser tracking surface.
@@ -334,6 +392,6 @@ function createTracking(options) {
334
392
  };
335
393
  }
336
394
  //#endregion
337
- export { createTracking, ga4, meta };
395
+ export { createTracking, ga4, meta, posthog };
338
396
 
339
397
  //# sourceMappingURL=browser.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"browser.js","names":["push"],"sources":["../src/providers/ga4.browser.ts","../src/providers/meta.browser.ts","../src/browser.ts"],"sourcesContent":["// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n BrowserProvider,\n ConsentState,\n EventBinding,\n EventData,\n TrackOptions,\n UserData,\n} from '../index.js';\n\ninterface GtagWindow {\n gtag?: (...args: unknown[]) => void;\n}\n\n/** Optional configuration for the GA4 browser provider. */\nexport interface Ga4BrowserConfig {\n /**\n * How this property spells each canonical event. Rarely needed: the\n * canonical vocabulary already is GA4's.\n */\n events?: Record<string, EventBinding<string>>;\n}\n\n// Server rendering reaches this module with no browser at all, where\n// `window` is a ReferenceError rather than `undefined`.\nfunction gtagWindow(): GtagWindow | undefined {\n return typeof window === 'undefined' ? undefined : (window as unknown as GtagWindow);\n}\n\n/**\n * Sends a command, or fails the way a hand-written call would.\n *\n * Writing `gtag(…)` on a page without Google's snippet throws, and this\n * library replicates that rather than swallowing it: a silent no-op is how a\n * host ends up believing it is measuring something.\n */\nfunction push(...args: unknown[]): void {\n const gtag = gtagWindow()?.gtag;\n\n if (!gtag) {\n throw new Error(\n \"ga4: window.gtag is not defined. Add Google's tag to the page before creating tracking.\",\n );\n }\n\n gtag(...args);\n}\n\n/**\n * Google Analytics 4 in the browser, through `gtag.js`.\n *\n * **This provider does not load Google's tag.** The tag belongs on the page,\n * installed the way Google documents it: a snippet in the HTML, or a tag\n * manager. This library talks to the tag that is already there; it never\n * injects a third-party script into your page, and it never issues the\n * property configuration that would emit a second page view.\n *\n * Which also means the initial consent declaration is not ours to make:\n * Google requires it before the property is configured, and the snippet that\n * configures the property is yours. Use {@link ConsentState} through\n * `consent()` for changes after that.\n *\n * @param measurementId - The `G-` id of the data stream, matching the tag on\n * the page.\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/browser`.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/browser';\n *\n * // Google's own snippet is already in the page.\n * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });\n *\n * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });\n * ```\n */\nexport function ga4(measurementId: string, config: Ga4BrowserConfig = {}): BrowserProvider {\n const { events } = config;\n\n return {\n name: 'ga4',\n // The canonical names already are GA4's, so every event passes through\n // under its own name unless the host says otherwise.\n default: 'passthrough',\n ...(events ? { events } : {}),\n\n track(name: string, data: EventData, _options: TrackOptions): void {\n // GA4 documents no browser-to-server deduplication, so `dedupId` maps\n // to nothing here. That is the exact translation of \"this concept does\n // not exist in this vendor\". Inventing a param would imply a merge\n // the platform never performs.\n //\n // `send_to` is written after the host's data on purpose: without it,\n // gtag sends to every configured property on the page, so the\n // addressing is the adapter's to own and not the host's to override.\n push('event', name, { ...data, send_to: measurementId });\n },\n\n identify(user: UserData, traits?: Record<string, unknown>): void {\n // GA4 documents no browser slot for email, phone or names. They map to\n // nothing, which is what \"this concept does not exist here\" means.\n if (user.userId !== undefined) push('set', { user_id: user.userId });\n if (traits) push('set', 'user_properties', traits);\n },\n\n consent(command: 'default' | 'update', state: ConsentState): void {\n // Verbatim: the library's consent vocabulary is Google's own spelling,\n // so there is nothing to translate and no chance to expand a signal\n // the host did not declare.\n push('consent', command, state);\n },\n };\n}\n","// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n BrowserProvider,\n ConsentState,\n EventBinding,\n EventData,\n EventItem,\n TrackOptions,\n} from '../index.js';\n\ninterface FbqWindow {\n fbq?: (...args: unknown[]) => void;\n}\n\n/**\n * The names Meta accepts through `fbq('track')`. Anything else is a custom\n * event and goes through `trackCustom`, which is a different command rather\n * than a different argument.\n *\n * Seventeen standard events plus `PageView`, which Meta documents separately\n * from the seventeen and which the base snippet fires by itself.\n */\nconst STANDARD_EVENTS: readonly string[] = [\n 'AddPaymentInfo',\n 'AddToCart',\n 'AddToWishlist',\n 'CompleteRegistration',\n 'Contact',\n 'CustomizeProduct',\n 'Donate',\n 'FindLocation',\n 'InitiateCheckout',\n 'Lead',\n 'PageView',\n 'Purchase',\n 'Schedule',\n 'Search',\n 'StartTrial',\n 'SubmitApplication',\n 'Subscribe',\n 'ViewContent',\n];\n\n/**\n * How Meta spells the canonical vocabulary, which is GA4's.\n *\n * Only canonical names appear here. Meta has eight more standard events with\n * no GA4 counterpart (`Subscribe`, `StartTrial`, `Schedule`, `Contact`,\n * `Donate`, `FindLocation`, `CustomizeProduct`, `SubmitApplication`), and\n * inventing canonical names for them would make this library the author of a\n * vocabulary it deliberately borrows. A host that fires those maps its own\n * event name to them through `events`.\n *\n * A canonical event with no standard counterpart is **not** dropped: it goes\n * to `trackCustom` under its own name, because by hand that event would have\n * been sent.\n */\nconst CANONICAL_EVENTS: Record<string, EventBinding<string>> = {\n page_view: 'PageView',\n view_item: 'ViewContent',\n search: 'Search',\n add_to_cart: 'AddToCart',\n add_to_wishlist: 'AddToWishlist',\n begin_checkout: 'InitiateCheckout',\n add_payment_info: 'AddPaymentInfo',\n purchase: 'Purchase',\n sign_up: 'CompleteRegistration',\n generate_lead: 'Lead',\n};\n\n/** Optional configuration for the Meta browser provider. */\nexport interface MetaBrowserConfig {\n /**\n * How this pixel spells each canonical event, merged over the built-in map.\n *\n * This is how the eight standard events with no GA4 counterpart are\n * reached, and how an event is kept out of Meta entirely with `null`.\n */\n events?: Record<string, EventBinding<string>>;\n}\n\n// Server rendering reaches this module with no browser at all, where\n// `window` is a ReferenceError rather than `undefined`.\nfunction fbqWindow(): FbqWindow | undefined {\n return typeof window === 'undefined' ? undefined : (window as unknown as FbqWindow);\n}\n\n/**\n * Sends a command, or fails the way a hand-written call would.\n *\n * Writing `fbq(…)` on a page without Meta's snippet throws, and this library\n * replicates that rather than swallowing it: a silent no-op is how a host\n * ends up believing it is measuring something.\n */\nfunction push(...args: unknown[]): void {\n const fbq = fbqWindow()?.fbq;\n\n if (!fbq) {\n throw new Error(\n \"meta: window.fbq is not defined. Add Meta's pixel to the page before creating tracking.\",\n );\n }\n\n fbq(...args);\n}\n\n/**\n * GA4's `items` become Meta's `contents`, which is a closed shape: `id`,\n * `quantity`, `item_price` and `delivery_category`, and nothing else.\n *\n * The rest of a GA4 item, `item_name` and `item_brand`, is dropped rather than\n * forwarded, because a key Meta does not read inside `contents` looks mapped\n * and arrives nowhere. That is the failure mode this project keeps finding.\n */\nfunction contents(items: readonly EventItem[]): Record<string, unknown>[] {\n return items.map((item) => {\n const content: Record<string, unknown> = {};\n\n if (item.item_id !== undefined) content.id = item.item_id;\n if (item.quantity !== undefined) content.quantity = item.quantity;\n if (item.price !== undefined) content.item_price = item.price;\n\n return content;\n });\n}\n\n/**\n * `value` and `currency` are spelled identically by both vendors, so they\n * pass through untouched. Everything the host named itself passes through\n * too: Meta keeps unknown keys as custom properties, which is exactly what a\n * hand-written call would have produced.\n *\n * `transaction_id` stays under its own name here. Meta's pixel documents no\n * order id among its object properties. `order_id` exists on the Conversions\n * API and not on this surface, so translating it would be inventing a slot.\n */\nfunction pixelParams(data: EventData): Record<string, unknown> {\n const { items, ...rest } = data;\n const params: Record<string, unknown> = { ...rest };\n\n if (items) params.contents = contents(items);\n\n return params;\n}\n\n/**\n * Meta's pixel has one consent switch where this library carries Google's\n * four signals, so the four are collapsed into it.\n *\n * The collapse is the strictest declared answer: any `denied` produces\n * `revoke`, and `grant` needs every declared signal to be `granted`. There is\n * no field to partition, so this is the only reduction that cannot widen a\n * denial, and widening is the one thing a projection must never do.\n *\n * A host that wants Meta to follow only its advertising category, and not its\n * analytics one, decides that before `createTracking` by leaving this\n * provider out, which is what `@tracklane/consent` exists to do.\n */\nfunction collapse(state: ConsentState): 'grant' | 'revoke' | undefined {\n const signals = [\n state.ad_storage,\n state.analytics_storage,\n state.ad_user_data,\n state.ad_personalization,\n ].filter((signal) => signal !== undefined);\n\n // Nothing declared produces no command. Reading silence as either answer\n // puts words in the visitor's mouth.\n if (signals.length === 0) return undefined;\n\n return signals.every((signal) => signal === 'granted') ? 'grant' : 'revoke';\n}\n\n/**\n * The Meta pixel in the browser, through `fbq`.\n *\n * **This provider does not load Meta's pixel.** The base code belongs on the\n * page, installed the way\n * [Meta documents it](https://developers.facebook.com/docs/meta-pixel/get-started):\n * a snippet in the HTML, or a tag manager. This library talks to the pixel\n * that is already there; it never injects a third-party script and never\n * issues `fbq('init')`.\n *\n * Three consequences follow from that, and all three are Meta's rules rather\n * than ours:\n *\n * - **There is no `identify` here.** Meta accepts advanced matching only in\n * the base code (\"be sure to place advanced matching parameters in the\n * pixel base code or the values will not be treated as manual advanced\n * matching values\"), and the base code is yours. Put `em`, `ph`, `fn`, `ln`\n * in your own `fbq('init')`, where the pixel normalises and hashes them for\n * you. On the server, where there is no snippet, the same identity travels\n * in `context.user` and is hashed by the adapter.\n * - **The initial consent declaration is not ours.** Meta wants\n * `fbq('consent', 'revoke')` before `init`, and by the time you hold what\n * `createTracking` returns that moment has passed. Ours is every\n * declaration after it, through `consent()`.\n * - **Limited Data Use is not ours either.** `fbq('dataProcessingOptions', …)`\n * is documented as running before `init`. It belongs in your snippet. The\n * server half, which has no snippet, carries it on its factory.\n *\n * **There is no pixel id here**, and that is deliberate rather than an\n * omission. `fbq('track')` reaches every pixel the page initialised, so an id\n * passed in would address nothing and the parameter would promise something\n * this adapter cannot deliver. Which pixels exist is declared by your snippet,\n * in `fbq('init')`.\n *\n * @param config - Event name overrides, merged over the built-in map.\n * @returns A provider for `createTracking` from `tracklane/browser`.\n *\n * @example\n * ```ts\n * import { createTracking, meta } from 'tracklane/browser';\n *\n * // Meta's own base code is already in the page, and it named the pixel.\n * const { track } = createTracking({ providers: [meta()] });\n *\n * // fbq('track', 'Purchase', { value: 49.9, currency: 'BRL' }, { eventID: 'T-1' })\n * track('purchase', { value: 49.9, currency: 'BRL' }, { dedupId: 'T-1' });\n * ```\n */\nexport function meta(config: MetaBrowserConfig = {}): BrowserProvider {\n return {\n name: 'meta',\n // An event Meta has no standard name for is still an event Meta accepts,\n // through `trackCustom`. Nothing is silently dropped.\n default: 'passthrough',\n events: { ...CANONICAL_EVENTS, ...config.events },\n\n track(name: string, data: EventData, options: TrackOptions): void {\n // `track`, which is what a hand-written call is, and the only form Meta\n // documents the deduplication object for.\n //\n // `trackSingle` exists and would address one pixel, the way GA4's\n // `send_to` does. It was used here and then abandoned: Meta publishes no\n // signature for `trackSingle` carrying `{ eventID }`, so the placement\n // that deduplication depends on had no contract behind it. It worked when\n // verified against a real pixel, and an undocumented shape that works\n // today can stop working with no error and no visible symptom — the\n // browser and server hits would simply both count.\n //\n // The cost is Meta's own: on a page with two pixels initialised, `track`\n // reaches both. That is what `fbq('track')` does by hand, so this\n // replicates it rather than deciding otherwise on the host's behalf.\n const command = STANDARD_EVENTS.includes(name) ? 'track' : 'trackCustom';\n const args: unknown[] = [command, name, pixelParams(data)];\n\n // Meta's key is `eventID` here and `event_id` on the Conversions API,\n // matched together with the event name. The library never invents the\n // value: only one the host already owns can match on both sides.\n if (options.dedupId !== undefined) args.push({ eventID: options.dedupId });\n\n push(...args);\n },\n\n consent(_command: 'default' | 'update', state: ConsentState): void {\n // Meta has one consent command and no equivalent of Google's\n // default/update split, so the command maps to nothing. What is\n // declared is the state, and that is what is forwarded.\n const answer = collapse(state);\n if (answer) push('consent', answer);\n },\n };\n}\n","import { assertUniqueProviders, makeReporter, messageOf, resolveEvent } from './dispatch.js';\n\nexport { type Ga4BrowserConfig, ga4 } from './providers/ga4.browser.js';\nexport { type MetaBrowserConfig, meta } from './providers/meta.browser.js';\n\nimport type {\n ConsentState,\n EventBinding,\n EventData,\n ProviderDefault,\n TrackingError,\n UserData,\n} from './vocabulary.js';\n\n/**\n * Everything the browser needs beyond the event itself.\n *\n * There is one field, and that is the point: in the browser each vendor tag\n * reads its own cookies and holds its own session, so the only thing left\n * for the host to supply is the value that ties this hit to a server-side\n * one.\n */\nexport interface TrackOptions {\n /**\n * The value that lets a vendor recognise this hit and a server-side hit as\n * one event. The library never invents it: the browser and the server do\n * not share a process, so only a value the host already owns (an order id)\n * can match on both sides.\n */\n dedupId?: string;\n}\n\n/**\n * A destination for browser events.\n *\n * This is the whole contract. A provider written outside this package\n * implements it exactly as the providers shipped here do.\n */\nexport interface BrowserProvider<Target = string> {\n /** The vendor's fixed name. Registering one twice is an error. */\n name: string;\n /** What happens to a canonical event this vendor has no binding for. */\n default: ProviderDefault;\n /** How this vendor spells each canonical event. */\n events?: Record<string, EventBinding<Target>>;\n /**\n * Loads the vendor tag, at creation.\n *\n * **Make it idempotent.** A host that rebuilds its tracking, as\n * `@tracklane/consent` does on every consent answer, creates again and\n * installs again, including providers that were already there.\n */\n install?(): void | Promise<void>;\n /** Sends one event to this vendor. Throwing here reaches `onError`, not the caller. */\n track(name: Target, data: EventData, options: TrackOptions): void;\n /** Absent where the vendor keeps no user of its own. */\n identify?(user: UserData, traits?: Record<string, unknown>): void;\n /** Absent where the vendor documents no consent command. */\n consent?(command: 'default' | 'update', state: ConsentState): void;\n}\n\n/** Options accepted by {@link createTracking}. */\nexport interface BrowserTrackingOptions {\n /** The vendors to send every event to. Registering the same `name` twice throws. */\n providers: readonly BrowserProvider[];\n /**\n * The one diagnostic channel. Without it the library is silent, exactly as\n * a hand-written vendor call is.\n */\n onError?: (error: TrackingError) => void;\n}\n\n/** What {@link createTracking} returns. */\nexport interface BrowserTracking {\n /** Sends one event to every configured vendor. Never throws. */\n track(name: string, data?: EventData, options?: TrackOptions): void;\n /** Forwards the user to the vendors that hold one, and to nobody else. */\n identify(user: UserData, traits?: Record<string, unknown>): void;\n /**\n * Forwards a consent declaration to every vendor that documents a command\n * for it. It never decides, stores or withholds anything.\n */\n consent(command: 'default' | 'update', state: ConsentState): void;\n}\n\n/**\n * Creates the browser tracking surface.\n *\n * Providers install eagerly, which is what pasting a vendor snippet does and\n * what lets each vendor record its own initial page view. Every vendor\n * shipped here queues its own commands until its script lands, so nothing is\n * lost to loading and this library needs no queue of its own.\n *\n * @param options - The providers to send to, and an optional error channel.\n * @returns The `track`, `identify` and `consent` calls.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/browser';\n *\n * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });\n * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });\n * ```\n */\nexport function createTracking(options: BrowserTrackingOptions): BrowserTracking {\n const { providers } = options;\n assertUniqueProviders(providers);\n\n const report = makeReporter(options.onError);\n\n const fail = (provider: string, event: string, cause: unknown): void => {\n report({ provider, event, severity: 'error', message: messageOf(cause), cause });\n };\n\n for (const provider of providers) {\n try {\n const installing = provider.install?.();\n // An async loader that rejects would otherwise become an unhandled\n // rejection, the silent failure this channel exists to prevent.\n void Promise.resolve(installing).catch((cause: unknown) => {\n fail(provider.name, 'install', cause);\n });\n } catch (cause) {\n fail(provider.name, 'install', cause);\n }\n }\n\n return {\n track(name, data = {}, trackOptions = {}) {\n for (const provider of providers) {\n const target = resolveEvent(provider, name);\n if (target === undefined) continue;\n\n try {\n provider.track(target, data, trackOptions);\n } catch (cause) {\n fail(provider.name, name, cause);\n }\n }\n },\n\n identify(user, traits) {\n for (const provider of providers) {\n try {\n provider.identify?.(user, traits);\n } catch (cause) {\n fail(provider.name, 'identify', cause);\n }\n }\n },\n\n consent(command, state) {\n for (const provider of providers) {\n try {\n provider.consent?.(command, state);\n } catch (cause) {\n fail(provider.name, 'consent', cause);\n }\n }\n },\n };\n}\n"],"mappings":";;AA4BA,SAAS,aAAqC;CAC5C,OAAO,OAAO,WAAW,cAAc,KAAA,IAAa;AACtD;;;;;;;;AASA,SAASA,OAAK,GAAG,MAAuB;CACtC,MAAM,OAAO,WAAW,CAAC,EAAE;CAE3B,IAAI,CAAC,MACH,MAAM,IAAI,MACR,yFACF;CAGF,KAAK,GAAG,IAAI;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,IAAI,eAAuB,SAA2B,CAAC,GAAoB;CACzF,MAAM,EAAE,WAAW;CAEnB,OAAO;EACL,MAAM;EAGN,SAAS;EACT,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAE3B,MAAM,MAAc,MAAiB,UAA8B;GASjE,OAAK,SAAS,MAAM;IAAE,GAAG;IAAM,SAAS;GAAc,CAAC;EACzD;EAEA,SAAS,MAAgB,QAAwC;GAG/D,IAAI,KAAK,WAAW,KAAA,GAAW,OAAK,OAAO,EAAE,SAAS,KAAK,OAAO,CAAC;GACnE,IAAI,QAAQ,OAAK,OAAO,mBAAmB,MAAM;EACnD;EAEA,QAAQ,SAA+B,OAA2B;GAIhE,OAAK,WAAW,SAAS,KAAK;EAChC;CACF;AACF;;;;;;;;;;;AC3FA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AK,SAAS,MAAM,MAAM,KAAK;IACjC;GACF;EACF;EAEA,SAAS,MAAM,QAAQ;GACrB,KAAK,MAAM,YAAY,WACrB,IAAI;IACF,SAAS,WAAW,MAAM,MAAM;GAClC,SAAS,OAAO;IACd,KAAK,SAAS,MAAM,YAAY,KAAK;GACvC;EAEJ;EAEA,QAAQ,SAAS,OAAO;GACtB,KAAK,MAAM,YAAY,WACrB,IAAI;IACF,SAAS,UAAU,SAAS,KAAK;GACnC,SAAS,OAAO;IACd,KAAK,SAAS,MAAM,WAAW,KAAK;GACtC;EAEJ;CACF;AACF"}
1
+ {"version":3,"file":"browser.js","names":["push"],"sources":["../src/providers/ga4.browser.ts","../src/providers/meta.browser.ts","../src/providers/posthog.browser.ts","../src/browser.ts"],"sourcesContent":["// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n BrowserProvider,\n ConsentState,\n EventBinding,\n EventData,\n TrackOptions,\n UserData,\n} from '../index.js';\n\ninterface GtagWindow {\n gtag?: (...args: unknown[]) => void;\n}\n\n/** Optional configuration for the GA4 browser provider. */\nexport interface Ga4BrowserConfig {\n /**\n * How this property spells each canonical event. Rarely needed: the\n * canonical vocabulary already is GA4's.\n */\n events?: Record<string, EventBinding<string>>;\n}\n\n// Server rendering reaches this module with no browser at all, where\n// `window` is a ReferenceError rather than `undefined`.\nfunction gtagWindow(): GtagWindow | undefined {\n return typeof window === 'undefined' ? undefined : (window as unknown as GtagWindow);\n}\n\n/**\n * Sends a command, or fails the way a hand-written call would.\n *\n * Writing `gtag(…)` on a page without Google's snippet throws, and this\n * library replicates that rather than swallowing it: a silent no-op is how a\n * host ends up believing it is measuring something.\n */\nfunction push(...args: unknown[]): void {\n const gtag = gtagWindow()?.gtag;\n\n if (!gtag) {\n throw new Error(\n \"ga4: window.gtag is not defined. Add Google's tag to the page before creating tracking.\",\n );\n }\n\n gtag(...args);\n}\n\n/**\n * Google Analytics 4 in the browser, through `gtag.js`.\n *\n * **This provider does not load Google's tag.** The tag belongs on the page,\n * installed the way Google documents it: a snippet in the HTML, or a tag\n * manager. This library talks to the tag that is already there; it never\n * injects a third-party script into your page, and it never issues the\n * property configuration that would emit a second page view.\n *\n * Which also means the initial consent declaration is not ours to make:\n * Google requires it before the property is configured, and the snippet that\n * configures the property is yours. Use {@link ConsentState} through\n * `consent()` for changes after that.\n *\n * @param measurementId - The `G-` id of the data stream, matching the tag on\n * the page.\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/browser`.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/browser';\n *\n * // Google's own snippet is already in the page.\n * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });\n *\n * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });\n * ```\n */\nexport function ga4(measurementId: string, config: Ga4BrowserConfig = {}): BrowserProvider {\n const { events } = config;\n\n return {\n name: 'ga4',\n // The canonical names already are GA4's, so every event passes through\n // under its own name unless the host says otherwise.\n default: 'passthrough',\n ...(events ? { events } : {}),\n\n track(name: string, data: EventData, _options: TrackOptions): void {\n // GA4 documents no browser-to-server deduplication, so `dedupId` maps\n // to nothing here. That is the exact translation of \"this concept does\n // not exist in this vendor\". Inventing a param would imply a merge\n // the platform never performs.\n //\n // `send_to` is written after the host's data on purpose: without it,\n // gtag sends to every configured property on the page, so the\n // addressing is the adapter's to own and not the host's to override.\n push('event', name, { ...data, send_to: measurementId });\n },\n\n identify(user: UserData, traits?: Record<string, unknown>): void {\n // GA4 documents no browser slot for email, phone or names. They map to\n // nothing, which is what \"this concept does not exist here\" means.\n if (user.userId !== undefined) push('set', { user_id: user.userId });\n if (traits) push('set', 'user_properties', traits);\n },\n\n consent(command: 'default' | 'update', state: ConsentState): void {\n // Verbatim: the library's consent vocabulary is Google's own spelling,\n // so there is nothing to translate and no chance to expand a signal\n // the host did not declare.\n push('consent', command, state);\n },\n };\n}\n","// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n BrowserProvider,\n ConsentState,\n EventBinding,\n EventData,\n EventItem,\n TrackOptions,\n} from '../index.js';\n\ninterface FbqWindow {\n fbq?: (...args: unknown[]) => void;\n}\n\n/**\n * The names Meta accepts through `fbq('track')`. Anything else is a custom\n * event and goes through `trackCustom`, which is a different command rather\n * than a different argument.\n *\n * Seventeen standard events plus `PageView`, which Meta documents separately\n * from the seventeen and which the base snippet fires by itself.\n */\nconst STANDARD_EVENTS: readonly string[] = [\n 'AddPaymentInfo',\n 'AddToCart',\n 'AddToWishlist',\n 'CompleteRegistration',\n 'Contact',\n 'CustomizeProduct',\n 'Donate',\n 'FindLocation',\n 'InitiateCheckout',\n 'Lead',\n 'PageView',\n 'Purchase',\n 'Schedule',\n 'Search',\n 'StartTrial',\n 'SubmitApplication',\n 'Subscribe',\n 'ViewContent',\n];\n\n/**\n * How Meta spells the canonical vocabulary, which is GA4's.\n *\n * Only canonical names appear here. Meta has eight more standard events with\n * no GA4 counterpart (`Subscribe`, `StartTrial`, `Schedule`, `Contact`,\n * `Donate`, `FindLocation`, `CustomizeProduct`, `SubmitApplication`), and\n * inventing canonical names for them would make this library the author of a\n * vocabulary it deliberately borrows. A host that fires those maps its own\n * event name to them through `events`.\n *\n * A canonical event with no standard counterpart is **not** dropped: it goes\n * to `trackCustom` under its own name, because by hand that event would have\n * been sent.\n */\nconst CANONICAL_EVENTS: Record<string, EventBinding<string>> = {\n page_view: 'PageView',\n view_item: 'ViewContent',\n search: 'Search',\n add_to_cart: 'AddToCart',\n add_to_wishlist: 'AddToWishlist',\n begin_checkout: 'InitiateCheckout',\n add_payment_info: 'AddPaymentInfo',\n purchase: 'Purchase',\n sign_up: 'CompleteRegistration',\n generate_lead: 'Lead',\n};\n\n/** Optional configuration for the Meta browser provider. */\nexport interface MetaBrowserConfig {\n /**\n * How this pixel spells each canonical event, merged over the built-in map.\n *\n * This is how the eight standard events with no GA4 counterpart are\n * reached, and how an event is kept out of Meta entirely with `null`.\n */\n events?: Record<string, EventBinding<string>>;\n}\n\n// Server rendering reaches this module with no browser at all, where\n// `window` is a ReferenceError rather than `undefined`.\nfunction fbqWindow(): FbqWindow | undefined {\n return typeof window === 'undefined' ? undefined : (window as unknown as FbqWindow);\n}\n\n/**\n * Sends a command, or fails the way a hand-written call would.\n *\n * Writing `fbq(…)` on a page without Meta's snippet throws, and this library\n * replicates that rather than swallowing it: a silent no-op is how a host\n * ends up believing it is measuring something.\n */\nfunction push(...args: unknown[]): void {\n const fbq = fbqWindow()?.fbq;\n\n if (!fbq) {\n throw new Error(\n \"meta: window.fbq is not defined. Add Meta's pixel to the page before creating tracking.\",\n );\n }\n\n fbq(...args);\n}\n\n/**\n * GA4's `items` become Meta's `contents`, which is a closed shape: `id`,\n * `quantity`, `item_price` and `delivery_category`, and nothing else.\n *\n * The rest of a GA4 item, `item_name` and `item_brand`, is dropped rather than\n * forwarded, because a key Meta does not read inside `contents` looks mapped\n * and arrives nowhere. That is the failure mode this project keeps finding.\n */\nfunction contents(items: readonly EventItem[]): Record<string, unknown>[] {\n return items.map((item) => {\n const content: Record<string, unknown> = {};\n\n if (item.item_id !== undefined) content.id = item.item_id;\n if (item.quantity !== undefined) content.quantity = item.quantity;\n if (item.price !== undefined) content.item_price = item.price;\n\n return content;\n });\n}\n\n/**\n * `value` and `currency` are spelled identically by both vendors, so they\n * pass through untouched. Everything the host named itself passes through\n * too: Meta keeps unknown keys as custom properties, which is exactly what a\n * hand-written call would have produced.\n *\n * `transaction_id` stays under its own name here. Meta's pixel documents no\n * order id among its object properties. `order_id` exists on the Conversions\n * API and not on this surface, so translating it would be inventing a slot.\n */\nfunction pixelParams(data: EventData): Record<string, unknown> {\n const { items, ...rest } = data;\n const params: Record<string, unknown> = { ...rest };\n\n if (items) params.contents = contents(items);\n\n return params;\n}\n\n/**\n * Meta's pixel has one consent switch where this library carries Google's\n * four signals, so the four are collapsed into it.\n *\n * The collapse is the strictest declared answer: any `denied` produces\n * `revoke`, and `grant` needs every declared signal to be `granted`. There is\n * no field to partition, so this is the only reduction that cannot widen a\n * denial, and widening is the one thing a projection must never do.\n *\n * A host that wants Meta to follow only its advertising category, and not its\n * analytics one, decides that before `createTracking` by leaving this\n * provider out, which is what `@tracklane/consent` exists to do.\n */\nfunction collapse(state: ConsentState): 'grant' | 'revoke' | undefined {\n const signals = [\n state.ad_storage,\n state.analytics_storage,\n state.ad_user_data,\n state.ad_personalization,\n ].filter((signal) => signal !== undefined);\n\n // Nothing declared produces no command. Reading silence as either answer\n // puts words in the visitor's mouth.\n if (signals.length === 0) return undefined;\n\n return signals.every((signal) => signal === 'granted') ? 'grant' : 'revoke';\n}\n\n/**\n * The Meta pixel in the browser, through `fbq`.\n *\n * **This provider does not load Meta's pixel.** The base code belongs on the\n * page, installed the way\n * [Meta documents it](https://developers.facebook.com/docs/meta-pixel/get-started):\n * a snippet in the HTML, or a tag manager. This library talks to the pixel\n * that is already there; it never injects a third-party script and never\n * issues `fbq('init')`.\n *\n * Three consequences follow from that, and all three are Meta's rules rather\n * than ours:\n *\n * - **There is no `identify` here.** Meta accepts advanced matching only in\n * the base code (\"be sure to place advanced matching parameters in the\n * pixel base code or the values will not be treated as manual advanced\n * matching values\"), and the base code is yours. Put `em`, `ph`, `fn`, `ln`\n * in your own `fbq('init')`, where the pixel normalises and hashes them for\n * you. On the server, where there is no snippet, the same identity travels\n * in `context.user` and is hashed by the adapter.\n * - **The initial consent declaration is not ours.** Meta wants\n * `fbq('consent', 'revoke')` before `init`, and by the time you hold what\n * `createTracking` returns that moment has passed. Ours is every\n * declaration after it, through `consent()`.\n * - **Limited Data Use is not ours either.** `fbq('dataProcessingOptions', …)`\n * is documented as running before `init`. It belongs in your snippet. The\n * server half, which has no snippet, carries it on its factory.\n *\n * **There is no pixel id here**, and that is deliberate rather than an\n * omission. `fbq('track')` reaches every pixel the page initialised, so an id\n * passed in would address nothing and the parameter would promise something\n * this adapter cannot deliver. Which pixels exist is declared by your snippet,\n * in `fbq('init')`.\n *\n * @param config - Event name overrides, merged over the built-in map.\n * @returns A provider for `createTracking` from `tracklane/browser`.\n *\n * @example\n * ```ts\n * import { createTracking, meta } from 'tracklane/browser';\n *\n * // Meta's own base code is already in the page, and it named the pixel.\n * const { track } = createTracking({ providers: [meta()] });\n *\n * // fbq('track', 'Purchase', { value: 49.9, currency: 'BRL' }, { eventID: 'T-1' })\n * track('purchase', { value: 49.9, currency: 'BRL' }, { dedupId: 'T-1' });\n * ```\n */\nexport function meta(config: MetaBrowserConfig = {}): BrowserProvider {\n return {\n name: 'meta',\n // An event Meta has no standard name for is still an event Meta accepts,\n // through `trackCustom`. Nothing is silently dropped.\n default: 'passthrough',\n events: { ...CANONICAL_EVENTS, ...config.events },\n\n track(name: string, data: EventData, options: TrackOptions): void {\n // `track`, which is what a hand-written call is, and the only form Meta\n // documents the deduplication object for.\n //\n // `trackSingle` exists and would address one pixel, the way GA4's\n // `send_to` does. It was used here and then abandoned: Meta publishes no\n // signature for `trackSingle` carrying `{ eventID }`, so the placement\n // that deduplication depends on had no contract behind it. It worked when\n // verified against a real pixel, and an undocumented shape that works\n // today can stop working with no error and no visible symptom — the\n // browser and server hits would simply both count.\n //\n // The cost is Meta's own: on a page with two pixels initialised, `track`\n // reaches both. That is what `fbq('track')` does by hand, so this\n // replicates it rather than deciding otherwise on the host's behalf.\n const command = STANDARD_EVENTS.includes(name) ? 'track' : 'trackCustom';\n const args: unknown[] = [command, name, pixelParams(data)];\n\n // Meta's key is `eventID` here and `event_id` on the Conversions API,\n // matched together with the event name. The library never invents the\n // value: only one the host already owns can match on both sides.\n if (options.dedupId !== undefined) args.push({ eventID: options.dedupId });\n\n push(...args);\n },\n\n consent(_command: 'default' | 'update', state: ConsentState): void {\n // Meta has one consent command and no equivalent of Google's\n // default/update split, so the command maps to nothing. What is\n // declared is the state, and that is what is forwarded.\n const answer = collapse(state);\n if (answer) push('consent', answer);\n },\n };\n}\n","// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n BrowserProvider,\n ConsentState,\n EventBinding,\n EventData,\n TrackOptions,\n UserData,\n} from '../index.js';\n\n/** The slice of `posthog-js` this adapter calls. */\ninterface PosthogSdk {\n capture: (event: string, properties?: EventData) => void;\n identify: (distinctId: string) => void;\n setPersonProperties: (properties: Record<string, unknown>) => void;\n opt_in_capturing: () => void;\n opt_out_capturing: () => void;\n}\n\ninterface PosthogWindow {\n posthog?: PosthogSdk;\n}\n\n/** Optional configuration for the PostHog browser provider. */\nexport interface PosthogBrowserConfig {\n /**\n * How this project spells each canonical event. Rarely needed: `capture()`\n * accepts any string, so the canonical vocabulary already is PostHog's.\n */\n events?: Record<string, EventBinding<string>>;\n}\n\n// Server rendering reaches this module with no browser at all, where\n// `window` is a ReferenceError rather than `undefined`.\nfunction posthogWindow(): PosthogWindow | undefined {\n return typeof window === 'undefined' ? undefined : (window as unknown as PosthogWindow);\n}\n\n/**\n * Returns the vendor SDK, or fails the way a hand-written call would.\n *\n * Calling `posthog.capture(...)` on a page without PostHog's snippet throws,\n * and this library replicates that rather than swallowing it: a silent no-op\n * is how a host ends up believing it is measuring something.\n */\nfunction sdk(): PosthogSdk {\n const instance = posthogWindow()?.posthog;\n\n if (!instance) {\n throw new Error(\n \"posthog: window.posthog is not defined. Add PostHog's snippet to the page before creating tracking.\",\n );\n }\n\n return instance;\n}\n\n/**\n * PostHog in the browser, through `posthog-js`.\n *\n * **This provider does not load PostHog's snippet.** It belongs on the page,\n * installed the way PostHog documents it: a snippet in the HTML, or a tag\n * manager. This library talks to the instance that is already there; it\n * never injects a third-party script into your page.\n *\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/browser`.\n *\n * @example\n * ```ts\n * import { createTracking, posthog } from 'tracklane/browser';\n *\n * // PostHog's own snippet is already in the page.\n * const { track } = createTracking({ providers: [posthog()] });\n *\n * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });\n * ```\n */\nexport function posthog(config: PosthogBrowserConfig = {}): BrowserProvider {\n const { events } = config;\n\n return {\n name: 'posthog',\n default: 'passthrough',\n ...(events ? { events } : {}),\n\n track(name: string, data: EventData, _options: TrackOptions): void {\n // capture() accepts any string as the event name and documents no\n // browser-to-server deduplication key, so dedupId maps nowhere — the\n // same gap GA4 has, for the same reason: there is no field to put it\n // in.\n sdk().capture(name, data);\n },\n\n identify(user: UserData, traits?: Record<string, unknown>): void {\n // distinct_id is PostHog's only identity slot. email, phone and names\n // have no separate slot the way Meta's user_data has one for each —\n // they map to nothing here, exactly the gap GA4 has for the same\n // fields.\n if (user.userId !== undefined) sdk().identify(user.userId);\n // setPersonProperties works against whichever identity is already\n // current, so it needs no id of its own — the same shape as GA4's\n // separate `set user_properties` push.\n if (traits) sdk().setPersonProperties(traits);\n },\n\n consent(_command: 'default' | 'update', state: ConsentState): void {\n // opt_in_capturing/opt_out_capturing is one binary switch, local SDK\n // state, not a per-signal API — nothing like Google's four commands.\n // analytics_storage is the one signal that actually describes what\n // this toggle governs (whether PostHog stores and sends analytics\n // events at all), so it is the one signal this collapses onto. The\n // other three have no honest PostHog equivalent; folding them in too\n // would risk an ad-only denial silently switching off analytics\n // capture the visitor never objected to, so they are left alone.\n const { analytics_storage } = state;\n\n if (analytics_storage === 'denied') {\n sdk().opt_out_capturing();\n } else if (analytics_storage === 'granted') {\n sdk().opt_in_capturing();\n }\n // Absent: no command fires. Whatever posture the page's own PostHog\n // snippet already set — opted in by default, or opted out through\n // `opt_out_capturing_by_default` — stands, rather than being guessed at.\n },\n };\n}\n","import { assertUniqueProviders, makeReporter, messageOf, resolveEvent } from './dispatch.js';\n\nexport { type Ga4BrowserConfig, ga4 } from './providers/ga4.browser.js';\nexport { type MetaBrowserConfig, meta } from './providers/meta.browser.js';\nexport { type PosthogBrowserConfig, posthog } from './providers/posthog.browser.js';\n\nimport type {\n ConsentState,\n EventBinding,\n EventData,\n ProviderDefault,\n TrackingError,\n UserData,\n} from './vocabulary.js';\n\n/**\n * Everything the browser needs beyond the event itself.\n *\n * There is one field, and that is the point: in the browser each vendor tag\n * reads its own cookies and holds its own session, so the only thing left\n * for the host to supply is the value that ties this hit to a server-side\n * one.\n */\nexport interface TrackOptions {\n /**\n * The value that lets a vendor recognise this hit and a server-side hit as\n * one event. The library never invents it: the browser and the server do\n * not share a process, so only a value the host already owns (an order id)\n * can match on both sides.\n */\n dedupId?: string;\n}\n\n/**\n * A destination for browser events.\n *\n * This is the whole contract. A provider written outside this package\n * implements it exactly as the providers shipped here do.\n */\nexport interface BrowserProvider<Target = string> {\n /** The vendor's fixed name. Registering one twice is an error. */\n name: string;\n /** What happens to a canonical event this vendor has no binding for. */\n default: ProviderDefault;\n /** How this vendor spells each canonical event. */\n events?: Record<string, EventBinding<Target>>;\n /**\n * Loads the vendor tag, at creation.\n *\n * **Make it idempotent.** A host that rebuilds its tracking, as\n * `@tracklane/consent` does on every consent answer, creates again and\n * installs again, including providers that were already there.\n */\n install?(): void | Promise<void>;\n /** Sends one event to this vendor. Throwing here reaches `onError`, not the caller. */\n track(name: Target, data: EventData, options: TrackOptions): void;\n /** Absent where the vendor keeps no user of its own. */\n identify?(user: UserData, traits?: Record<string, unknown>): void;\n /** Absent where the vendor documents no consent command. */\n consent?(command: 'default' | 'update', state: ConsentState): void;\n}\n\n/** Options accepted by {@link createTracking}. */\nexport interface BrowserTrackingOptions {\n /** The vendors to send every event to. Registering the same `name` twice throws. */\n providers: readonly BrowserProvider[];\n /**\n * The one diagnostic channel. Without it the library is silent, exactly as\n * a hand-written vendor call is.\n */\n onError?: (error: TrackingError) => void;\n}\n\n/** What {@link createTracking} returns. */\nexport interface BrowserTracking {\n /** Sends one event to every configured vendor. Never throws. */\n track(name: string, data?: EventData, options?: TrackOptions): void;\n /** Forwards the user to the vendors that hold one, and to nobody else. */\n identify(user: UserData, traits?: Record<string, unknown>): void;\n /**\n * Forwards a consent declaration to every vendor that documents a command\n * for it. It never decides, stores or withholds anything.\n */\n consent(command: 'default' | 'update', state: ConsentState): void;\n}\n\n/**\n * Creates the browser tracking surface.\n *\n * Providers install eagerly, which is what pasting a vendor snippet does and\n * what lets each vendor record its own initial page view. Every vendor\n * shipped here queues its own commands until its script lands, so nothing is\n * lost to loading and this library needs no queue of its own.\n *\n * @param options - The providers to send to, and an optional error channel.\n * @returns The `track`, `identify` and `consent` calls.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/browser';\n *\n * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });\n * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });\n * ```\n */\nexport function createTracking(options: BrowserTrackingOptions): BrowserTracking {\n const { providers } = options;\n assertUniqueProviders(providers);\n\n const report = makeReporter(options.onError);\n\n const fail = (provider: string, event: string, cause: unknown): void => {\n report({ provider, event, severity: 'error', message: messageOf(cause), cause });\n };\n\n for (const provider of providers) {\n try {\n const installing = provider.install?.();\n // An async loader that rejects would otherwise become an unhandled\n // rejection, the silent failure this channel exists to prevent.\n void Promise.resolve(installing).catch((cause: unknown) => {\n fail(provider.name, 'install', cause);\n });\n } catch (cause) {\n fail(provider.name, 'install', cause);\n }\n }\n\n return {\n track(name, data = {}, trackOptions = {}) {\n for (const provider of providers) {\n const target = resolveEvent(provider, name);\n if (target === undefined) continue;\n\n try {\n provider.track(target, data, trackOptions);\n } catch (cause) {\n fail(provider.name, name, cause);\n }\n }\n },\n\n identify(user, traits) {\n for (const provider of providers) {\n try {\n provider.identify?.(user, traits);\n } catch (cause) {\n fail(provider.name, 'identify', cause);\n }\n }\n },\n\n consent(command, state) {\n for (const provider of providers) {\n try {\n provider.consent?.(command, state);\n } catch (cause) {\n fail(provider.name, 'consent', cause);\n }\n }\n },\n };\n}\n"],"mappings":";;AA4BA,SAAS,aAAqC;CAC5C,OAAO,OAAO,WAA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K,SAAS,MAAM,WAAW,KAAK;CACtC;CAGF,OAAO;EACL,MAAM,MAAM,OAAO,CAAC,GAAG,eAAe,CAAC,GAAG;GACxC,KAAK,MAAM,YAAY,WAAW;IAChC,MAAM,SAAS,aAAa,UAAU,IAAI;IAC1C,IAAI,WAAW,KAAA,GAAW;IAE1B,IAAI;KACF,SAAS,MAAM,QAAQ,MAAM,YAAY;IAC3C,SAAS,OAAO;KACd,KAAK,SAAS,MAAM,MAAM,KAAK;IACjC;GACF;EACF;EAEA,SAAS,MAAM,QAAQ;GACrB,KAAK,MAAM,YAAY,WACrB,IAAI;IACF,SAAS,WAAW,MAAM,MAAM;GAClC,SAAS,OAAO;IACd,KAAK,SAAS,MAAM,YAAY,KAAK;GACvC;EAEJ;EAEA,QAAQ,SAAS,OAAO;GACtB,KAAK,MAAM,YAAY,WACrB,IAAI;IACF,SAAS,UAAU,SAAS,KAAK;GACnC,SAAS,OAAO;IACd,KAAK,SAAS,MAAM,WAAW,KAAK;GACtC;EAEJ;CACF;AACF"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { C as UserData, S as TrackingError, _ as ConsentState, b as EventItem, d as ResolvedContext, f as ServerProvider, g as ActionSource, i as TrackOptions, m as ServerTrackingOptions, n as BrowserTracking, p as ServerTracking, r as BrowserTrackingOptions, t as BrowserProvider, u as EventContext, v as EventBinding, x as ProviderDefault, y as EventData } from "./browser-DmJeRMFB.js";
1
+ import { C as ProviderDefault, S as EventItem, T as UserData, b as EventBinding, f as EventContext, g as ServerTrackingOptions, h as ServerTracking, i as TrackOptions, m as ServerProvider, n as BrowserTracking, p as ResolvedContext, r as BrowserTrackingOptions, t as BrowserProvider, v as ActionSource, w as TrackingError, x as EventData, y as ConsentState } from "./browser-CddkJdvX.js";
2
2
  export type { ActionSource, BrowserProvider, BrowserTracking, BrowserTrackingOptions, ConsentState, EventBinding, EventContext, EventData, EventItem, ProviderDefault, ResolvedContext, ServerProvider, ServerTracking, ServerTrackingOptions, TrackOptions, TrackingError, UserData };
package/dist/server.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { D as Ga4ServerConfig, E as meta, O as Ga4ServerCredentials, T as MetaServerCredentials, d as ResolvedContext, f as ServerProvider, h as createTracking, k as ga4, m as ServerTrackingOptions, p as ServerTracking, u as EventContext, w as MetaServerConfig } from "./browser-DmJeRMFB.js";
2
- export { EventContext, type Ga4ServerConfig, type Ga4ServerCredentials, type MetaServerConfig, type MetaServerCredentials, ResolvedContext, ServerProvider, ServerTracking, ServerTrackingOptions, createTracking, ga4, meta };
1
+ import { A as MetaServerCredentials, D as PosthogServerCredentials, E as PosthogServerConfig, M as Ga4ServerConfig, N as Ga4ServerCredentials, O as posthog, P as ga4, _ as createTracking, f as EventContext, g as ServerTrackingOptions, h as ServerTracking, j as meta, k as MetaServerConfig, m as ServerProvider, p as ResolvedContext } from "./browser-CddkJdvX.js";
2
+ export { EventContext, type Ga4ServerConfig, type Ga4ServerCredentials, type MetaServerConfig, type MetaServerCredentials, type PosthogServerConfig, type PosthogServerCredentials, ResolvedContext, ServerProvider, ServerTracking, ServerTrackingOptions, createTracking, ga4, meta, posthog };
package/dist/server.js CHANGED
@@ -319,6 +319,114 @@ function meta(credentials, config = {}) {
319
319
  };
320
320
  }
321
321
  //#endregion
322
+ //#region src/providers/posthog.server.ts
323
+ const DEFAULT_HOST = "https://us.i.posthog.com";
324
+ /**
325
+ * The distinct_id lives inside a cookie posthog-js writes by default, named
326
+ * after this project's own api key: `ph_<api_key>_posthog`. Its value is
327
+ * `encodeURIComponent(JSON.stringify({ distinct_id, ... }))`, so it has to be
328
+ * decoded before it parses as JSON.
329
+ *
330
+ * Verified against a live project rather than read off the SDK's source: the
331
+ * cookie was percent-encoded, held `distinct_id` alongside `$device_id` and
332
+ * `$user_state`, and the id parsed out of it matched what the page's own
333
+ * `posthog.get_distinct_id()` returned. A server event sent with it landed on
334
+ * the same person the browser had created, which is the whole point.
335
+ *
336
+ * This is only the anonymous fallback. It is not read when the caller already
337
+ * knows who the visitor is; see the comment in `track` for why.
338
+ */
339
+ function anonymousId(cookies, apiKey) {
340
+ const raw = cookies[`ph_${apiKey}_posthog`];
341
+ if (!raw) return void 0;
342
+ try {
343
+ const parsed = JSON.parse(decodeURIComponent(raw));
344
+ return typeof parsed.distinct_id === "string" ? parsed.distinct_id : void 0;
345
+ } catch {
346
+ return;
347
+ }
348
+ }
349
+ /**
350
+ * PostHog deduplicates on `uuid`, and the field holds a UUID rather than any
351
+ * string: an invalid one is documented as dropped on ingestion, and has been
352
+ * reported answering 400 instead. Since `dedupId` is whatever the host chose
353
+ * — Meta's `event_id` takes anything, and this library's own example is an
354
+ * order id — forwarding it unchecked would turn a duplicated purchase into no
355
+ * purchase at all.
356
+ *
357
+ * Accepts any RFC 4122 layout rather than v4 alone, because v7 is what a
358
+ * system minting ids today tends to produce.
359
+ */
360
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
361
+ /**
362
+ * PostHog on the server, through the Capture API.
363
+ *
364
+ * **Deduplicating a retried webhook takes two things, not one.** `dedupId`
365
+ * becomes PostHog's `uuid`, and PostHog collapses events sharing `uuid`, event
366
+ * name, timestamp and `distinct_id` — so a `timestamp` left to default to the
367
+ * clock differs on the retry and nothing is deduplicated. Pin it to a value
368
+ * derived from the order, as below. The `dedupId` itself must be a UUID:
369
+ * anything else is reported through `onError` and sent without the field,
370
+ * because PostHog rejects other shapes rather than ignoring them.
371
+ *
372
+ * Deduplication is also eventual, happening during a background merge, so both
373
+ * rows are visible for a while and a test that counts immediately will fail.
374
+ *
375
+ * @param credentials - The project API key, and the ingestion host for
376
+ * anything other than PostHog's default US Cloud instance.
377
+ * @param config - Rarely needed event name overrides.
378
+ * @returns A provider for `createTracking` from `tracklane/server`.
379
+ *
380
+ * @example
381
+ * ```ts
382
+ * import { createTracking, posthog } from 'tracklane/server';
383
+ *
384
+ * const { track } = createTracking({
385
+ * providers: [posthog({ apiKey: process.env.POSTHOG_API_KEY! })],
386
+ * });
387
+ *
388
+ * // Both fields come from the order, so the payment provider's second
389
+ * // delivery of the same webhook produces the same event.
390
+ * await track('purchase', order, {
391
+ * user: { userId: order.userId },
392
+ * cookies: request.headers.get('cookie'),
393
+ * dedupId: order.eventId, // a UUID your checkout minted with the order
394
+ * timestamp: order.paidAt,
395
+ * });
396
+ * ```
397
+ */
398
+ function posthog(credentials, config = {}) {
399
+ const { apiKey, host = DEFAULT_HOST } = credentials;
400
+ return {
401
+ name: "posthog",
402
+ default: "passthrough",
403
+ ...config.events ? { events: config.events } : {},
404
+ async track(name, data, context, report) {
405
+ const id = context.user?.userId ?? anonymousId(context.cookies, apiKey);
406
+ if (!id) throw new Error("posthog: cannot resolve distinct_id — no user.userId in context and no ph_<api_key>_posthog cookie among the cookies passed in context. Pass user.userId once the visitor is known, or ensure PostHog's browser tag has set its cookie first.");
407
+ const properties = { ...data };
408
+ if (context.traits) properties.$set = context.traits;
409
+ const dedup = {};
410
+ if (context.dedupId !== void 0) if (UUID.test(context.dedupId)) dedup.uuid = context.dedupId;
411
+ else report("dedupId is not a UUID, so it was not forwarded as uuid: PostHog deduplicates on that field and rejects other shapes, so this event can duplicate on a retry");
412
+ const body = {
413
+ api_key: apiKey,
414
+ event: name,
415
+ distinct_id: id,
416
+ ...dedup,
417
+ properties,
418
+ timestamp: new Date(context.timestamp).toISOString()
419
+ };
420
+ const response = await fetch(`${host}/i/v0/e/`, {
421
+ method: "POST",
422
+ headers: { "content-type": "application/json" },
423
+ body: JSON.stringify(body)
424
+ });
425
+ if (!response.ok) throw new Error(`posthog: the capture endpoint answered ${response.status}`);
426
+ }
427
+ };
428
+ }
429
+ //#endregion
322
430
  //#region src/server.ts
323
431
  /** `name=value; name=value`, the shape of a `Cookie` header. */
324
432
  function parseCookies(cookies) {
@@ -396,6 +504,6 @@ function createTracking(options) {
396
504
  } };
397
505
  }
398
506
  //#endregion
399
- export { createTracking, ga4, meta };
507
+ export { createTracking, ga4, meta, posthog };
400
508
 
401
509
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","names":[],"sources":["../src/providers/ga4.server.ts","../src/providers/meta.server.ts","../src/server.ts"],"sourcesContent":["// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n ConsentState,\n EventBinding,\n EventData,\n ResolvedContext,\n ServerProvider,\n} from '../index.js';\n\nconst ENDPOINT = 'https://www.google-analytics.com/mp/collect';\n\n/** Credentials for the GA4 Measurement Protocol. */\nexport interface Ga4ServerCredentials {\n /** The `G-` id of the data stream. */\n measurementId: string;\n /** Created under Admin → Data Streams → Measurement Protocol. */\n apiSecret: string;\n}\n\n/** Optional configuration for the GA4 server provider. */\nexport interface Ga4ServerConfig {\n events?: Record<string, EventBinding<string>>;\n}\n\n/**\n * The visitor cookie holds `GA1.<depth>.<client_id>`, and the client id\n * itself contains a dot, so the identifier is the last two segments, which\n * is what survives Google's varying prefix depth.\n *\n * The value must be the cookie as the browser wrote it. A host passing a\n * parsed map passes cookie values, not values it took apart itself.\n */\nfunction visitorId(cookies: Record<string, string>): string | undefined {\n const raw = cookies._ga;\n if (!raw) return undefined;\n\n const parts = raw.split('.');\n if (parts.length < 4) return undefined;\n\n return parts.slice(-2).join('.');\n}\n\n/**\n * The per-container cookie carries the session, in one of two layouts.\n *\n * Verified against Google's live tag on 2026-07-31 rather than assumed:\n *\n * - `GS2.1.s1785511401$o1$g0$t1785511401$j60$l0$h0`, the current one. The\n * third dot-segment packs several fields joined by `$`, and the session is\n * the first of them, prefixed with `s`.\n * - `GS1.1.1785511401.1.1.…`, the older one, where the third dot-segment is\n * the session on its own.\n *\n * Reading the third segment blindly works for the old layout and returns the\n * whole `s…$o1$g0$…` blob for the new one, which the vendor would accept and\n * silently fail to match. Hence the two shapes, and hence `undefined` rather\n * than a guess when neither fits.\n */\nfunction sessionId(cookies: Record<string, string>, measurementId: string): string | undefined {\n // Scoped to *this* property's cookie. A page with two GA4 properties has two\n // `_ga_*` cookies, and taking whichever came first would attach another\n // property's session to our event, which Google accepts and never matches.\n const value = cookies[`_ga_${measurementId.replace(/^G-/, '')}`];\n const segment = value?.split('.')[2];\n if (!segment) return undefined;\n\n const packed = /^s(\\d+)/.exec(segment);\n if (packed) return packed[1];\n\n // The older layout: a bare session id, nothing packed around it.\n return /^\\d+$/.test(segment) ? segment : undefined;\n}\n\n/**\n * The Measurement Protocol documents exactly two consent fields, and spells\n * their values in upper case where the browser spells them in lower, one of\n * the small asymmetries an adapter absorbs so nobody else has to.\n */\nfunction consentBody(state: ConsentState | undefined): Record<string, string> | undefined {\n if (!state) return undefined;\n\n const body: Record<string, string> = {};\n if (state.ad_user_data) body.ad_user_data = state.ad_user_data.toUpperCase();\n if (state.ad_personalization) body.ad_personalization = state.ad_personalization.toUpperCase();\n\n return Object.keys(body).length > 0 ? body : undefined;\n}\n\n/**\n * Google Analytics 4 on the server, through the Measurement Protocol.\n *\n * @param credentials - The measurement id and API secret.\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/server`.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret: process.env.GA4_SECRET! })],\n * });\n *\n * await track('purchase', order, { cookies: request.headers.get('cookie') });\n * ```\n */\nexport function ga4(\n credentials: Ga4ServerCredentials,\n config: Ga4ServerConfig = {},\n): ServerProvider {\n const { measurementId, apiSecret } = credentials;\n\n return {\n name: 'ga4',\n default: 'passthrough',\n ...(config.events ? { events: config.events } : {}),\n\n async track(\n name: string,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void> {\n const clientId = visitorId(context.cookies);\n if (!clientId) {\n // Not withholding on policy grounds: the protocol requires this and\n // it cannot be invented. The endpoint answers success even to\n // invalid payloads, so sending anyway would look like it worked.\n // Naming the vendor's own field, so that searching Google's docs\n // for the error leads somewhere.\n throw new Error(\n \"ga4: cannot build client_id, no _ga cookie among the cookies passed in context. Ensure GA4's browser tag has set it first.\",\n );\n }\n\n const session = sessionId(context.cookies, measurementId);\n if (!session) {\n report(\n 'no session cookie (_ga_<container>): Google will accept this event and it will not appear in any report',\n );\n }\n\n const params: Record<string, unknown> = { ...data };\n if (session) {\n params.session_id = session;\n // Google drops sessions with no engagement from its reports, so the\n // event would arrive and still be invisible without this.\n params.engagement_time_msec = 1;\n }\n\n // The dedup id maps nowhere: GA4 documents no browser-to-server\n // deduplication. `transaction_id` (business data) travels in params\n // and is the duplicate control this vendor does have.\n const body: Record<string, unknown> = {\n client_id: clientId,\n timestamp_micros: context.timestamp * 1000,\n events: [{ name, params }],\n };\n\n if (context.user?.userId !== undefined) body.user_id = context.user.userId;\n\n if (context.traits) {\n // Each property is an object with a `value` key here, where the\n // browser takes the bare value. Sending the bare value is rejected\n // by Google's validation endpoint and **accepted with 204 by the\n // collection endpoint**, which then drops it, verified on\n // 2026-07-31. One of several places where this vendor fails by\n // accepting.\n body.user_properties = Object.fromEntries(\n Object.entries(context.traits).map(([name, value]) => [name, { value }]),\n );\n }\n\n const consent = consentBody(context.consent);\n if (consent) body.consent = consent;\n\n // Credentials go in the query because the protocol offers no\n // alternative. Query strings land in proxy and APM logs; that\n // exposure is Google's design, not a choice made here.\n const url = `${ENDPOINT}?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n // The status only. The event carries raw personal data, and no\n // library-owned surface re-emits it into a host's logs.\n throw new Error(`ga4: the Measurement Protocol answered ${response.status}`);\n }\n },\n };\n}\n","// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n ActionSource,\n EventBinding,\n EventData,\n EventItem,\n ResolvedContext,\n ServerProvider,\n} from '../index.js';\n\nconst GRAPH = 'https://graph.facebook.com';\n\n/**\n * Pinned on purpose. A Graph URL with no version resolves to the *oldest*\n * version still available, which silently changes what the endpoint accepts\n * the day Meta drops it.\n */\nconst DEFAULT_API_VERSION = 'v25.0';\n\n/**\n * How Meta spells the canonical vocabulary, which is GA4's. Kept in step with\n * `meta.browser.ts` by hand: the two halves are two libraries, and neither\n * imports the other.\n */\nconst CANONICAL_EVENTS: Record<string, EventBinding<string>> = {\n page_view: 'PageView',\n view_item: 'ViewContent',\n search: 'Search',\n add_to_cart: 'AddToCart',\n add_to_wishlist: 'AddToWishlist',\n begin_checkout: 'InitiateCheckout',\n add_payment_info: 'AddPaymentInfo',\n purchase: 'Purchase',\n sign_up: 'CompleteRegistration',\n generate_lead: 'Lead',\n};\n\n/** Credentials for Meta's Conversions API. */\nexport interface MetaServerCredentials {\n /** The pixel (dataset) id events are posted to. */\n pixelId: string;\n /** A system user or page access token with `ads_management`. It is a credential. */\n accessToken: string;\n}\n\n/** Optional configuration for the Meta server provider. */\nexport interface MetaServerConfig {\n /** How this pixel spells each canonical event, merged over the built-in map. */\n events?: Record<string, EventBinding<string>>;\n /**\n * Where conversions happen by default. Meta requires `action_source` on\n * every event, so there is always a value; `context.source` overrides it\n * per call, which is what a webhook and a checkout need.\n */\n actionSource?: ActionSource;\n /** The Graph API version in the URL. Defaults to a pinned one. */\n apiVersion?: string;\n /**\n * Routes events to the Test Events tab in Events Manager instead of the\n * live dataset. **Testing only**: Meta says to remove it before\n * production, and it is the only instrument that shows what a payload\n * actually became.\n */\n testEventCode?: string;\n /**\n * Meta's Limited Data Use marking, forwarded verbatim: `['LDU']` to enable\n * it, `[]` to disable it.\n *\n * This is a processing marking that some US state laws require, not a\n * consent declaration, which is why it is configuration on this factory and\n * not a reading of `context.consent`. The browser half has no equivalent:\n * `fbq('dataProcessingOptions', …)` is documented as running before\n * `fbq('init')`, and the snippet is the host's.\n */\n dataProcessingOptions?: readonly string[];\n /** `0` lets Meta geolocate. Meaningless without `dataProcessingOptions`. */\n dataProcessingOptionsCountry?: number;\n /** `0` lets Meta geolocate. Meaningless without `dataProcessingOptions`. */\n dataProcessingOptionsState?: number;\n}\n\n/**\n * Web Crypto rather than `node:crypto`, so the built server bundle stays\n * platform-neutral: this adapter is called from Cloudflare Workers, Deno and\n * Vercel's edge runtime as often as from a Node process, and a `node:` import\n * would rule those out for no gain.\n */\nasync function sha256(value: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));\n\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * **Why the adapter hashes and does not ask the host to.**\n *\n * This looks like the library transforming data, and the cutting rule forbids\n * that. It is not. Meta does not define a field called \"email\" that happens\n * to want a hash: it defines `em` *as* the SHA-256 of the trimmed, lowercased\n * address, the same way it defines `event_time` as seconds rather than\n * milliseconds. Writing this line by hand you write\n * `sha256(email.trim().toLowerCase())`, and the adapter replicates exactly\n * that. Normalisation lives with the field it belongs to.\n *\n * The alternative is worse and is where integrations demonstrably go wrong:\n * three vendors want SHA-256 under three different normalisation rules, so a\n * host hashing on its own side has to hash the same address three ways and\n * discovers a mistake only as a quietly poor match rate.\n */\nconst normaliseEmail = (value: string): string => value.trim().toLowerCase();\n\n/**\n * \"Remove symbols, letters, and any leading zeros.\" The country code is not\n * added here: Meta wants one and the library does not know it, and guessing a\n * country onto a phone number invents an identifier for a different person.\n */\nconst normalisePhone = (value: string): string => value.replace(/\\D/g, '').replace(/^0+/, '');\n\n/** \"Lowercase only with no punctuation.\" Spaces and accents survive; Meta reads UTF-8. */\nconst normaliseName = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[\\p{P}\\p{S}]/gu, '');\n\n/**\n * GA4's `items` become Meta's `contents`, a closed shape: `id`, `quantity`,\n * `item_price`, `delivery_category`. The rest of a GA4 item is dropped rather\n * than forwarded, because a key Meta does not read inside `contents` looks\n * mapped and arrives nowhere.\n */\nfunction contents(items: readonly EventItem[]): Record<string, unknown>[] {\n return items.map((item) => {\n const content: Record<string, unknown> = {};\n\n if (item.item_id !== undefined) content.id = item.item_id;\n if (item.quantity !== undefined) content.quantity = item.quantity;\n if (item.price !== undefined) content.item_price = item.price;\n\n return content;\n });\n}\n\n/**\n * `value` and `currency` are spelled identically by both vendors. Everything\n * the host named itself passes through, because a business measures things\n * this vocabulary does not name.\n *\n * `transaction_id` becomes `order_id`, which this surface documents and the\n * pixel does not. It is one of the asymmetries between Meta's two halves an\n * adapter absorbs so nobody else has to.\n */\nfunction customData(data: EventData): Record<string, unknown> {\n const { items, transaction_id: transactionId, ...rest } = data;\n const custom: Record<string, unknown> = { ...rest };\n\n if (transactionId !== undefined) custom.order_id = transactionId;\n if (items) custom.contents = contents(items);\n\n return custom;\n}\n\n/**\n * The heaviest surface of the five vendors: four hashed identifiers, four raw\n * ones, and two cookies forwarded exactly as the pixel wrote them.\n *\n * Built in a fixed order, and hashed one after another rather than in\n * parallel, so that the same input produces the same JSON on every run. Two\n * identical events differing only in key order would be the library inventing\n * something, which is precisely what the conformance suite looks for.\n */\nasync function userData(context: ResolvedContext): Promise<Record<string, string>> {\n const user = context.user ?? {};\n const built: Record<string, string> = {};\n\n const hashed: readonly [string, string | undefined, (value: string) => string][] = [\n ['em', user.email, normaliseEmail],\n ['ph', user.phone, normalisePhone],\n ['fn', user.firstName, normaliseName],\n ['ln', user.lastName, normaliseName],\n ];\n\n for (const [field, raw, normalise] of hashed) {\n if (raw === undefined) continue;\n\n const normalised = normalise(raw);\n // An empty value still hashes to a perfectly valid digest, one that\n // matches nobody and counts as an identifier towards the minimum below.\n if (!normalised) continue;\n\n built[field] = await sha256(normalised);\n }\n\n // Raw by Meta's own instruction. `external_id` is the one it merely\n // *recommends* hashing, and it stays raw here so the value Meta receives is\n // the value the host holds. A host that also puts an external id in its\n // `fbq('init')` should know the pixel hashes what it finds there, so the two\n // surfaces match only if both sides send the same form: pre-hash on both,\n // or on neither. Meta's pages do not state which side should give way.\n if (user.userId !== undefined) built.external_id = user.userId;\n if (context.ip !== undefined) built.client_ip_address = context.ip;\n if (context.userAgent !== undefined) built.client_user_agent = context.userAgent;\n\n // Meta forwards these as-is; they are its own cookies in its own format.\n // Note what is *not* here: an `fbc` synthesised from an `fbclid` in the URL.\n // Meta documents that construction, and it needs a click timestamp the\n // library does not have, so building one would be inventing an identifier.\n const fbp = context.cookies._fbp;\n if (fbp) built.fbp = fbp;\n\n const fbc = context.cookies._fbc;\n if (fbc) built.fbc = fbc;\n\n return built;\n}\n\n/**\n * Meta's Conversions API.\n *\n * @param credentials - The pixel id and an access token.\n * @param config - Event overrides, the default action source, and Meta's own\n * levers: the API version, a test event code, and Limited Data Use.\n * @returns A provider for `createTracking` from `tracklane/server`.\n *\n * @example\n * ```ts\n * import { createTracking, meta } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [meta({ pixelId: '1234567890', accessToken: process.env.META_TOKEN! })],\n * });\n *\n * await track('purchase', order, {\n * user: { email: order.email },\n * cookies: request.headers.get('cookie'),\n * dedupId: order.id,\n * ip,\n * userAgent,\n * });\n * ```\n */\nexport function meta(\n credentials: MetaServerCredentials,\n config: MetaServerConfig = {},\n): ServerProvider {\n const { pixelId, accessToken } = credentials;\n const { actionSource = 'website', apiVersion = DEFAULT_API_VERSION, testEventCode } = config;\n\n return {\n name: 'meta',\n default: 'passthrough',\n events: { ...CANONICAL_EVENTS, ...config.events },\n\n async track(\n name: string,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void> {\n const user = await userData(context);\n\n if (Object.keys(user).length === 0) {\n // Not withholding on policy grounds: Meta requires at least one\n // `user_data` parameter and none can be invented. Its own page says\n // \"at least one of the following\" over the whole list, so a bare\n // `fbp` qualifies; whether matching is any good with a non-contact\n // identifier alone is Meta's business, not this adapter's to judge.\n // Naming the vendor's own field, so searching for the error leads\n // somewhere.\n throw new Error(\n 'meta: cannot build user_data, the Conversions API requires at least one identifier. Pass context.user, context.ip with context.userAgent, or the _fbp/_fbc cookies.',\n );\n }\n\n const event: Record<string, unknown> = {\n event_name: name,\n // Seconds, where the context carries milliseconds.\n event_time: Math.floor(context.timestamp / 1000),\n // Required on every event, which is why the factory carries a default\n // rather than letting the request fail.\n action_source: context.source ?? actionSource,\n user_data: user,\n };\n\n // Meta's key is `event_id` here and `eventID` on the pixel, matched\n // together with `event_name`. Never produced by the library.\n if (context.dedupId !== undefined) event.event_id = context.dedupId;\n if (context.url !== undefined) event.event_source_url = context.url;\n\n const custom = customData(data);\n if (Object.keys(custom).length > 0) event.custom_data = custom;\n\n if (config.dataProcessingOptions) {\n // Meta lists these among its *server event* parameters, alongside\n // `event_name` and `user_data`, which is why they sit inside the\n // event. No example on its pages states the level outright.\n event.data_processing_options = config.dataProcessingOptions;\n\n if (config.dataProcessingOptionsCountry !== undefined) {\n event.data_processing_options_country = config.dataProcessingOptionsCountry;\n }\n if (config.dataProcessingOptionsState !== undefined) {\n event.data_processing_options_state = config.dataProcessingOptionsState;\n }\n }\n\n // `context.traits` and `context.consent` map to nothing. Meta has no\n // person-properties slot on this endpoint, and its consent surface is a\n // browser command; the processing marking above is a different concept\n // wearing similar words.\n\n // Form-encoded, which is the shape Meta's own examples post, and it\n // keeps the token out of the query string. Unlike GA4, this vendor\n // offers a body slot for it, so query strings in proxy and APM logs are\n // avoidable here.\n const body = new URLSearchParams({\n data: JSON.stringify([event]),\n access_token: accessToken,\n });\n\n if (testEventCode) body.set('test_event_code', testEventCode);\n\n const response = await fetch(`${GRAPH}/${apiVersion}/${encodeURIComponent(pixelId)}/events`, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body,\n });\n\n if (!response.ok) {\n // The status only. The event carries raw personal data, and no\n // library-owned surface re-emits it into a host's logs.\n throw new Error(`meta: the Conversions API answered ${response.status}`);\n }\n\n // A body that will not parse must not turn a delivered conversion into\n // an error, which would tell a host's retry logic to send it again.\n const result = (await response.json().catch(() => null)) as {\n messages?: unknown[];\n fbtrace_id?: string;\n } | null;\n\n const messages = result?.messages;\n if (Array.isArray(messages) && messages.length > 0) {\n // A caveat about a send that already happened, so it reports rather\n // than throws. The count and the trace id only: Meta's warnings can\n // quote the parameter that upset it, and event contents never reach a\n // host's logs through this library.\n report(\n `accepted with ${messages.length} warning(s) from the Conversions API; read them under fbtrace_id ${result?.fbtrace_id ?? 'unknown'} in Events Manager`,\n );\n }\n },\n };\n}\n","import { assertUniqueProviders, makeReporter, messageOf, resolveEvent } from './dispatch.js';\n\nexport {\n type Ga4ServerConfig,\n type Ga4ServerCredentials,\n ga4,\n} from './providers/ga4.server.js';\nexport {\n type MetaServerConfig,\n type MetaServerCredentials,\n meta,\n} from './providers/meta.server.js';\n\nimport type {\n ActionSource,\n ConsentState,\n EventBinding,\n EventData,\n ProviderDefault,\n TrackingError,\n UserData,\n} from './vocabulary.js';\n\n/**\n * Everything a conversion API needs beyond the event itself: who the person\n * is, when it happened, and where it was observed.\n *\n * None of this is \"what happened\", which is why it does not travel in the\n * event data: putting it there would leak identity into the pass-through\n * event params of the vendors that forward the payload as-is.\n */\nexport interface EventContext {\n /** The person's identity, the server-side counterpart to `identify()` on the browser. */\n user?: UserData;\n /**\n * The request's raw `Cookie` header, or an already-parsed map.\n *\n * These are cookies the vendors' own browser tags set. This library never\n * writes one. On the server each adapter reads the cookies belonging to\n * its own vendor: Meta forwards its value as-is, Google's holds several\n * things at once and has to be opened. That knowledge lives in the\n * adapters; the core only splits `name=value; name=value` into pairs.\n *\n * **It splits, it does not interpret.** Values are handed over exactly as\n * they appear, with no percent-decoding. The cookies these vendors set do\n * not need it; a host reading some other cookie should decode it itself.\n */\n cookies?: string | Record<string, string> | null;\n /** Ties this send to a browser hit. Never invented by the library. */\n dedupId?: string;\n /**\n * When the conversion actually happened. Defaults to now.\n *\n * A webhook arrives after the fact and LinkedIn rejects conversions older\n * than 90 days, so reporting \"now\" for everything would quietly distort\n * attribution.\n */\n timestamp?: number | Date;\n /** Overrides the factory default. Meta requires it on every event. */\n source?: ActionSource;\n /** The page the conversion happened on. Meta's Conversions API reads it as `event_source_url`. */\n url?: string;\n /** The visitor's IP. Meta's Conversions API reads it as one of the identifiers in `user_data`. */\n ip?: string;\n /** The visitor's user agent. Meta's Conversions API reads it alongside `ip`. */\n userAgent?: string;\n /** What is known *about* the person: GA4 user properties, PostHog `$set`. */\n traits?: Record<string, unknown>;\n /**\n * Travels inside the event, for the vendors that document such a field.\n * Today that is GA4's Measurement Protocol, and it reads two of the\n * signals; the others have no slot and ignore it.\n */\n consent?: ConsentState;\n}\n\n/** The context an adapter receives, with the ambiguity resolved. */\nexport interface ResolvedContext extends Omit<EventContext, 'cookies' | 'timestamp'> {\n /** The request's cookies, already split into a `name → value` map. */\n cookies: Record<string, string>;\n /** Epoch milliseconds. Adapters convert to their vendor's spelling. */\n timestamp: number;\n}\n\n/**\n * A destination for server events.\n *\n * `track` may throw, on a non-2xx or where a vendor documents a\n * precondition the event cannot meet. The dispatcher isolates and reports\n * it, so adapters stay honest and loud.\n *\n * `report` is for a caveat about a request that already succeeded. It does\n * not throw: by then the send happened, and throwing would tell a host's\n * retry logic to resend a delivered conversion.\n */\nexport interface ServerProvider<Target = string> {\n /** The vendor's fixed name. Registering one twice is an error. */\n name: string;\n /** What happens to a canonical event this vendor has no binding for. */\n default: ProviderDefault;\n /** How this vendor spells each canonical event. */\n events?: Record<string, EventBinding<Target>>;\n /** Sends one event to this vendor's conversion API. May throw, or call `report` for a caveat. */\n track(\n name: Target,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void>;\n}\n\n/** Options accepted by {@link createTracking}. */\nexport interface ServerTrackingOptions {\n /** The vendors to send every event to. Registering the same `name` twice throws. */\n providers: readonly ServerProvider[];\n /**\n * The one diagnostic channel. Without it the library is silent, exactly as\n * a hand-written vendor call is.\n */\n onError?: (error: TrackingError) => void;\n}\n\n/** What {@link createTracking} returns. */\nexport interface ServerTracking {\n /**\n * Sends one event to every configured conversion API.\n *\n * Resolves once every provider has settled and never rejects: one vendor\n * being down is not the caller's failure to handle. Awaiting is about the\n * request surviving a serverless runtime, not about delivery being\n * guaranteed.\n */\n track(name: string, data?: EventData, context?: EventContext): Promise<void>;\n}\n\n/** `name=value; name=value`, the shape of a `Cookie` header. */\nfunction parseCookies(\n cookies: string | Record<string, string> | null | undefined,\n): Record<string, string> {\n if (!cookies) return {};\n if (typeof cookies !== 'string') return cookies;\n\n const parsed: Record<string, string> = {};\n\n for (const pair of cookies.split(';')) {\n const separator = pair.indexOf('=');\n if (separator < 1) continue;\n\n const name = pair.slice(0, separator).trim();\n // Cookie values may contain `=`, so only the first one separates.\n if (name) parsed[name] = pair.slice(separator + 1).trim();\n }\n\n return parsed;\n}\n\n/**\n * Creates the server tracking surface.\n *\n * There is no `identify` here and nothing is held between calls: a server\n * instance is shared by every request, so a retained identity would attach\n * one visitor to another visitor's conversion. Identity travels with the\n * call, which is also what every conversion API expects.\n *\n * There is no `consent` call either. Consent commands are properties of a\n * vendor's on-page tag, and a server request has no tag. The one vendor that\n * accepts consent server-side reads it from the context.\n *\n * @param options - The providers to send to, and an optional error channel.\n * @returns The `track` call.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret })],\n * });\n *\n * await track('purchase', order, { cookies: request.headers.get('cookie') });\n * ```\n */\nexport function createTracking(options: ServerTrackingOptions): ServerTracking {\n const { providers } = options;\n assertUniqueProviders(providers);\n\n const report = makeReporter(options.onError);\n\n return {\n async track(name, data = {}, context = {}) {\n const { cookies, timestamp, ...rest } = context;\n const resolved: ResolvedContext = {\n ...rest,\n cookies: parseCookies(cookies),\n timestamp: timestamp instanceof Date ? timestamp.getTime() : (timestamp ?? Date.now()),\n };\n\n const sends = providers.map(async (provider) => {\n const target = resolveEvent(provider, name);\n if (target === undefined) return;\n\n try {\n await provider.track(target, data, resolved, (message) => {\n report({ provider: provider.name, event: name, severity: 'warning', message });\n });\n } catch (cause) {\n report({\n provider: provider.name,\n event: name,\n severity: 'error',\n message: messageOf(cause),\n cause,\n });\n }\n });\n\n await Promise.all(sends);\n },\n };\n}\n"],"mappings":";;AAYA,MAAM,WAAW;;;;;;;;;AAuBjB,SAAS,UAAU,SAAqD;CACtE,MAAM,MAAM,QAAQ;CACpB,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,MAAM,SAAS,GAAG,OAAO,KAAA;CAE7B,OAAO,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,GAAG;AACjC;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,SAAiC,eAA2C;CAK7F,MAAM,UADQ,QAAQ,OAAO,cAAc,QAAQ,OAAO,EAAE,IACvC,EAAE,MAAM,GAAG,CAAC,CAAC;CAClC,IAAI,CAAC,SAAS,OAAO,KAAA;CAErB,MAAM,SAAS,UAAU,KAAK,OAAO;CACrC,IAAI,QAAQ,OAAO,OAAO;CAG1B,OAAO,QAAQ,KAAK,OAAO,IAAI,UAAU,KAAA;AAC3C;;;;;;AAOA,SAAS,YAAY,OAAqE;CACxF,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,MAAM,OAA+B,CAAC;CACtC,IAAI,MAAM,cAAc,KAAK,eAAe,MAAM,aAAa,YAAY;CAC3E,IAAI,MAAM,oBAAoB,KAAK,qBAAqB,MAAM,mBAAmB,YAAY;CAE7F,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,KAAA;AAC/C;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,IACd,aACA,SAA0B,CAAC,GACX;CAChB,MAAM,EAAE,eAAe,cAAc;CAErC,OAAO;EACL,MAAM;EACN,SAAS;EACT,GAAI,OAAO,SAAS,EAAE,QAAQ,O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,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,eAAe,SAAgD;CAC7E,MAAM,EAAE,cAAc;CACtB,sBAAsB,SAAS;CAE/B,MAAM,SAAS,aAAa,QAAQ,OAAO;CAE3C,OAAO,EACL,MAAM,MAAM,MAAM,OAAO,CAAC,GAAG,UAAU,CAAC,GAAG;EACzC,MAAM,EAAE,SAAS,WAAW,GAAG,SAAS;EACxC,MAAM,WAA4B;GAChC,GAAG;GACH,SAAS,aAAa,OAAO;GAC7B,WAAW,qBAAqB,OAAO,UAAU,QAAQ,IAAK,aAAa,KAAK,IAAI;EACtF;EAEA,MAAM,QAAQ,UAAU,IAAI,OAAO,aAAa;GAC9C,MAAM,SAAS,aAAa,UAAU,IAAI;GAC1C,IAAI,WAAW,KAAA,GAAW;GAE1B,IAAI;IACF,MAAM,SAAS,MAAM,QAAQ,MAAM,WAAW,YAAY;KACxD,OAAO;MAAE,UAAU,SAAS;MAAM,OAAO;MAAM,UAAU;MAAW;KAAQ,CAAC;IAC/E,CAAC;GACH,SAAS,OAAO;IACd,OAAO;KACL,UAAU,SAAS;KACnB,OAAO;KACP,UAAU;KACV,SAAS,UAAU,KAAK;KACxB;IACF,CAAC;GACH;EACF,CAAC;EAED,MAAM,QAAQ,IAAI,KAAK;CACzB,EACF;AACF"}
1
+ {"version":3,"file":"server.js","names":[],"sources":["../src/providers/ga4.server.ts","../src/providers/meta.server.ts","../src/providers/posthog.server.ts","../src/server.ts"],"sourcesContent":["// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n ConsentState,\n EventBinding,\n EventData,\n ResolvedContext,\n ServerProvider,\n} from '../index.js';\n\nconst ENDPOINT = 'https://www.google-analytics.com/mp/collect';\n\n/** Credentials for the GA4 Measurement Protocol. */\nexport interface Ga4ServerCredentials {\n /** The `G-` id of the data stream. */\n measurementId: string;\n /** Created under Admin → Data Streams → Measurement Protocol. */\n apiSecret: string;\n}\n\n/** Optional configuration for the GA4 server provider. */\nexport interface Ga4ServerConfig {\n events?: Record<string, EventBinding<string>>;\n}\n\n/**\n * The visitor cookie holds `GA1.<depth>.<client_id>`, and the client id\n * itself contains a dot, so the identifier is the last two segments, which\n * is what survives Google's varying prefix depth.\n *\n * The value must be the cookie as the browser wrote it. A host passing a\n * parsed map passes cookie values, not values it took apart itself.\n */\nfunction visitorId(cookies: Record<string, string>): string | undefined {\n const raw = cookies._ga;\n if (!raw) return undefined;\n\n const parts = raw.split('.');\n if (parts.length < 4) return undefined;\n\n return parts.slice(-2).join('.');\n}\n\n/**\n * The per-container cookie carries the session, in one of two layouts.\n *\n * Verified against Google's live tag on 2026-07-31 rather than assumed:\n *\n * - `GS2.1.s1785511401$o1$g0$t1785511401$j60$l0$h0`, the current one. The\n * third dot-segment packs several fields joined by `$`, and the session is\n * the first of them, prefixed with `s`.\n * - `GS1.1.1785511401.1.1.…`, the older one, where the third dot-segment is\n * the session on its own.\n *\n * Reading the third segment blindly works for the old layout and returns the\n * whole `s…$o1$g0$…` blob for the new one, which the vendor would accept and\n * silently fail to match. Hence the two shapes, and hence `undefined` rather\n * than a guess when neither fits.\n */\nfunction sessionId(cookies: Record<string, string>, measurementId: string): string | undefined {\n // Scoped to *this* property's cookie. A page with two GA4 properties has two\n // `_ga_*` cookies, and taking whichever came first would attach another\n // property's session to our event, which Google accepts and never matches.\n const value = cookies[`_ga_${measurementId.replace(/^G-/, '')}`];\n const segment = value?.split('.')[2];\n if (!segment) return undefined;\n\n const packed = /^s(\\d+)/.exec(segment);\n if (packed) return packed[1];\n\n // The older layout: a bare session id, nothing packed around it.\n return /^\\d+$/.test(segment) ? segment : undefined;\n}\n\n/**\n * The Measurement Protocol documents exactly two consent fields, and spells\n * their values in upper case where the browser spells them in lower, one of\n * the small asymmetries an adapter absorbs so nobody else has to.\n */\nfunction consentBody(state: ConsentState | undefined): Record<string, string> | undefined {\n if (!state) return undefined;\n\n const body: Record<string, string> = {};\n if (state.ad_user_data) body.ad_user_data = state.ad_user_data.toUpperCase();\n if (state.ad_personalization) body.ad_personalization = state.ad_personalization.toUpperCase();\n\n return Object.keys(body).length > 0 ? body : undefined;\n}\n\n/**\n * Google Analytics 4 on the server, through the Measurement Protocol.\n *\n * @param credentials - The measurement id and API secret.\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/server`.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret: process.env.GA4_SECRET! })],\n * });\n *\n * await track('purchase', order, { cookies: request.headers.get('cookie') });\n * ```\n */\nexport function ga4(\n credentials: Ga4ServerCredentials,\n config: Ga4ServerConfig = {},\n): ServerProvider {\n const { measurementId, apiSecret } = credentials;\n\n return {\n name: 'ga4',\n default: 'passthrough',\n ...(config.events ? { events: config.events } : {}),\n\n async track(\n name: string,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void> {\n const clientId = visitorId(context.cookies);\n if (!clientId) {\n // Not withholding on policy grounds: the protocol requires this and\n // it cannot be invented. The endpoint answers success even to\n // invalid payloads, so sending anyway would look like it worked.\n // Naming the vendor's own field, so that searching Google's docs\n // for the error leads somewhere.\n throw new Error(\n \"ga4: cannot build client_id, no _ga cookie among the cookies passed in context. Ensure GA4's browser tag has set it first.\",\n );\n }\n\n const session = sessionId(context.cookies, measurementId);\n if (!session) {\n report(\n 'no session cookie (_ga_<container>): Google will accept this event and it will not appear in any report',\n );\n }\n\n const params: Record<string, unknown> = { ...data };\n if (session) {\n params.session_id = session;\n // Google drops sessions with no engagement from its reports, so the\n // event would arrive and still be invisible without this.\n params.engagement_time_msec = 1;\n }\n\n // The dedup id maps nowhere: GA4 documents no browser-to-server\n // deduplication. `transaction_id` (business data) travels in params\n // and is the duplicate control this vendor does have.\n const body: Record<string, unknown> = {\n client_id: clientId,\n timestamp_micros: context.timestamp * 1000,\n events: [{ name, params }],\n };\n\n if (context.user?.userId !== undefined) body.user_id = context.user.userId;\n\n if (context.traits) {\n // Each property is an object with a `value` key here, where the\n // browser takes the bare value. Sending the bare value is rejected\n // by Google's validation endpoint and **accepted with 204 by the\n // collection endpoint**, which then drops it, verified on\n // 2026-07-31. One of several places where this vendor fails by\n // accepting.\n body.user_properties = Object.fromEntries(\n Object.entries(context.traits).map(([name, value]) => [name, { value }]),\n );\n }\n\n const consent = consentBody(context.consent);\n if (consent) body.consent = consent;\n\n // Credentials go in the query because the protocol offers no\n // alternative. Query strings land in proxy and APM logs; that\n // exposure is Google's design, not a choice made here.\n const url = `${ENDPOINT}?measurement_id=${encodeURIComponent(measurementId)}&api_secret=${encodeURIComponent(apiSecret)}`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n // The status only. The event carries raw personal data, and no\n // library-owned surface re-emits it into a host's logs.\n throw new Error(`ga4: the Measurement Protocol answered ${response.status}`);\n }\n },\n };\n}\n","// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type {\n ActionSource,\n EventBinding,\n EventData,\n EventItem,\n ResolvedContext,\n ServerProvider,\n} from '../index.js';\n\nconst GRAPH = 'https://graph.facebook.com';\n\n/**\n * Pinned on purpose. A Graph URL with no version resolves to the *oldest*\n * version still available, which silently changes what the endpoint accepts\n * the day Meta drops it.\n */\nconst DEFAULT_API_VERSION = 'v25.0';\n\n/**\n * How Meta spells the canonical vocabulary, which is GA4's. Kept in step with\n * `meta.browser.ts` by hand: the two halves are two libraries, and neither\n * imports the other.\n */\nconst CANONICAL_EVENTS: Record<string, EventBinding<string>> = {\n page_view: 'PageView',\n view_item: 'ViewContent',\n search: 'Search',\n add_to_cart: 'AddToCart',\n add_to_wishlist: 'AddToWishlist',\n begin_checkout: 'InitiateCheckout',\n add_payment_info: 'AddPaymentInfo',\n purchase: 'Purchase',\n sign_up: 'CompleteRegistration',\n generate_lead: 'Lead',\n};\n\n/** Credentials for Meta's Conversions API. */\nexport interface MetaServerCredentials {\n /** The pixel (dataset) id events are posted to. */\n pixelId: string;\n /** A system user or page access token with `ads_management`. It is a credential. */\n accessToken: string;\n}\n\n/** Optional configuration for the Meta server provider. */\nexport interface MetaServerConfig {\n /** How this pixel spells each canonical event, merged over the built-in map. */\n events?: Record<string, EventBinding<string>>;\n /**\n * Where conversions happen by default. Meta requires `action_source` on\n * every event, so there is always a value; `context.source` overrides it\n * per call, which is what a webhook and a checkout need.\n */\n actionSource?: ActionSource;\n /** The Graph API version in the URL. Defaults to a pinned one. */\n apiVersion?: string;\n /**\n * Routes events to the Test Events tab in Events Manager instead of the\n * live dataset. **Testing only**: Meta says to remove it before\n * production, and it is the only instrument that shows what a payload\n * actually became.\n */\n testEventCode?: string;\n /**\n * Meta's Limited Data Use marking, forwarded verbatim: `['LDU']` to enable\n * it, `[]` to disable it.\n *\n * This is a processing marking that some US state laws require, not a\n * consent declaration, which is why it is configuration on this factory and\n * not a reading of `context.consent`. The browser half has no equivalent:\n * `fbq('dataProcessingOptions', …)` is documented as running before\n * `fbq('init')`, and the snippet is the host's.\n */\n dataProcessingOptions?: readonly string[];\n /** `0` lets Meta geolocate. Meaningless without `dataProcessingOptions`. */\n dataProcessingOptionsCountry?: number;\n /** `0` lets Meta geolocate. Meaningless without `dataProcessingOptions`. */\n dataProcessingOptionsState?: number;\n}\n\n/**\n * Web Crypto rather than `node:crypto`, so the built server bundle stays\n * platform-neutral: this adapter is called from Cloudflare Workers, Deno and\n * Vercel's edge runtime as often as from a Node process, and a `node:` import\n * would rule those out for no gain.\n */\nasync function sha256(value: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));\n\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * **Why the adapter hashes and does not ask the host to.**\n *\n * This looks like the library transforming data, and the cutting rule forbids\n * that. It is not. Meta does not define a field called \"email\" that happens\n * to want a hash: it defines `em` *as* the SHA-256 of the trimmed, lowercased\n * address, the same way it defines `event_time` as seconds rather than\n * milliseconds. Writing this line by hand you write\n * `sha256(email.trim().toLowerCase())`, and the adapter replicates exactly\n * that. Normalisation lives with the field it belongs to.\n *\n * The alternative is worse and is where integrations demonstrably go wrong:\n * three vendors want SHA-256 under three different normalisation rules, so a\n * host hashing on its own side has to hash the same address three ways and\n * discovers a mistake only as a quietly poor match rate.\n */\nconst normaliseEmail = (value: string): string => value.trim().toLowerCase();\n\n/**\n * \"Remove symbols, letters, and any leading zeros.\" The country code is not\n * added here: Meta wants one and the library does not know it, and guessing a\n * country onto a phone number invents an identifier for a different person.\n */\nconst normalisePhone = (value: string): string => value.replace(/\\D/g, '').replace(/^0+/, '');\n\n/** \"Lowercase only with no punctuation.\" Spaces and accents survive; Meta reads UTF-8. */\nconst normaliseName = (value: string): string =>\n value\n .trim()\n .toLowerCase()\n .replace(/[\\p{P}\\p{S}]/gu, '');\n\n/**\n * GA4's `items` become Meta's `contents`, a closed shape: `id`, `quantity`,\n * `item_price`, `delivery_category`. The rest of a GA4 item is dropped rather\n * than forwarded, because a key Meta does not read inside `contents` looks\n * mapped and arrives nowhere.\n */\nfunction contents(items: readonly EventItem[]): Record<string, unknown>[] {\n return items.map((item) => {\n const content: Record<string, unknown> = {};\n\n if (item.item_id !== undefined) content.id = item.item_id;\n if (item.quantity !== undefined) content.quantity = item.quantity;\n if (item.price !== undefined) content.item_price = item.price;\n\n return content;\n });\n}\n\n/**\n * `value` and `currency` are spelled identically by both vendors. Everything\n * the host named itself passes through, because a business measures things\n * this vocabulary does not name.\n *\n * `transaction_id` becomes `order_id`, which this surface documents and the\n * pixel does not. It is one of the asymmetries between Meta's two halves an\n * adapter absorbs so nobody else has to.\n */\nfunction customData(data: EventData): Record<string, unknown> {\n const { items, transaction_id: transactionId, ...rest } = data;\n const custom: Record<string, unknown> = { ...rest };\n\n if (transactionId !== undefined) custom.order_id = transactionId;\n if (items) custom.contents = contents(items);\n\n return custom;\n}\n\n/**\n * The heaviest surface of the five vendors: four hashed identifiers, four raw\n * ones, and two cookies forwarded exactly as the pixel wrote them.\n *\n * Built in a fixed order, and hashed one after another rather than in\n * parallel, so that the same input produces the same JSON on every run. Two\n * identical events differing only in key order would be the library inventing\n * something, which is precisely what the conformance suite looks for.\n */\nasync function userData(context: ResolvedContext): Promise<Record<string, string>> {\n const user = context.user ?? {};\n const built: Record<string, string> = {};\n\n const hashed: readonly [string, string | undefined, (value: string) => string][] = [\n ['em', user.email, normaliseEmail],\n ['ph', user.phone, normalisePhone],\n ['fn', user.firstName, normaliseName],\n ['ln', user.lastName, normaliseName],\n ];\n\n for (const [field, raw, normalise] of hashed) {\n if (raw === undefined) continue;\n\n const normalised = normalise(raw);\n // An empty value still hashes to a perfectly valid digest, one that\n // matches nobody and counts as an identifier towards the minimum below.\n if (!normalised) continue;\n\n built[field] = await sha256(normalised);\n }\n\n // Raw by Meta's own instruction. `external_id` is the one it merely\n // *recommends* hashing, and it stays raw here so the value Meta receives is\n // the value the host holds. A host that also puts an external id in its\n // `fbq('init')` should know the pixel hashes what it finds there, so the two\n // surfaces match only if both sides send the same form: pre-hash on both,\n // or on neither. Meta's pages do not state which side should give way.\n if (user.userId !== undefined) built.external_id = user.userId;\n if (context.ip !== undefined) built.client_ip_address = context.ip;\n if (context.userAgent !== undefined) built.client_user_agent = context.userAgent;\n\n // Meta forwards these as-is; they are its own cookies in its own format.\n // Note what is *not* here: an `fbc` synthesised from an `fbclid` in the URL.\n // Meta documents that construction, and it needs a click timestamp the\n // library does not have, so building one would be inventing an identifier.\n const fbp = context.cookies._fbp;\n if (fbp) built.fbp = fbp;\n\n const fbc = context.cookies._fbc;\n if (fbc) built.fbc = fbc;\n\n return built;\n}\n\n/**\n * Meta's Conversions API.\n *\n * @param credentials - The pixel id and an access token.\n * @param config - Event overrides, the default action source, and Meta's own\n * levers: the API version, a test event code, and Limited Data Use.\n * @returns A provider for `createTracking` from `tracklane/server`.\n *\n * @example\n * ```ts\n * import { createTracking, meta } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [meta({ pixelId: '1234567890', accessToken: process.env.META_TOKEN! })],\n * });\n *\n * await track('purchase', order, {\n * user: { email: order.email },\n * cookies: request.headers.get('cookie'),\n * dedupId: order.id,\n * ip,\n * userAgent,\n * });\n * ```\n */\nexport function meta(\n credentials: MetaServerCredentials,\n config: MetaServerConfig = {},\n): ServerProvider {\n const { pixelId, accessToken } = credentials;\n const { actionSource = 'website', apiVersion = DEFAULT_API_VERSION, testEventCode } = config;\n\n return {\n name: 'meta',\n default: 'passthrough',\n events: { ...CANONICAL_EVENTS, ...config.events },\n\n async track(\n name: string,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void> {\n const user = await userData(context);\n\n if (Object.keys(user).length === 0) {\n // Not withholding on policy grounds: Meta requires at least one\n // `user_data` parameter and none can be invented. Its own page says\n // \"at least one of the following\" over the whole list, so a bare\n // `fbp` qualifies; whether matching is any good with a non-contact\n // identifier alone is Meta's business, not this adapter's to judge.\n // Naming the vendor's own field, so searching for the error leads\n // somewhere.\n throw new Error(\n 'meta: cannot build user_data, the Conversions API requires at least one identifier. Pass context.user, context.ip with context.userAgent, or the _fbp/_fbc cookies.',\n );\n }\n\n const event: Record<string, unknown> = {\n event_name: name,\n // Seconds, where the context carries milliseconds.\n event_time: Math.floor(context.timestamp / 1000),\n // Required on every event, which is why the factory carries a default\n // rather than letting the request fail.\n action_source: context.source ?? actionSource,\n user_data: user,\n };\n\n // Meta's key is `event_id` here and `eventID` on the pixel, matched\n // together with `event_name`. Never produced by the library.\n if (context.dedupId !== undefined) event.event_id = context.dedupId;\n if (context.url !== undefined) event.event_source_url = context.url;\n\n const custom = customData(data);\n if (Object.keys(custom).length > 0) event.custom_data = custom;\n\n if (config.dataProcessingOptions) {\n // Meta lists these among its *server event* parameters, alongside\n // `event_name` and `user_data`, which is why they sit inside the\n // event. No example on its pages states the level outright.\n event.data_processing_options = config.dataProcessingOptions;\n\n if (config.dataProcessingOptionsCountry !== undefined) {\n event.data_processing_options_country = config.dataProcessingOptionsCountry;\n }\n if (config.dataProcessingOptionsState !== undefined) {\n event.data_processing_options_state = config.dataProcessingOptionsState;\n }\n }\n\n // `context.traits` and `context.consent` map to nothing. Meta has no\n // person-properties slot on this endpoint, and its consent surface is a\n // browser command; the processing marking above is a different concept\n // wearing similar words.\n\n // Form-encoded, which is the shape Meta's own examples post, and it\n // keeps the token out of the query string. Unlike GA4, this vendor\n // offers a body slot for it, so query strings in proxy and APM logs are\n // avoidable here.\n const body = new URLSearchParams({\n data: JSON.stringify([event]),\n access_token: accessToken,\n });\n\n if (testEventCode) body.set('test_event_code', testEventCode);\n\n const response = await fetch(`${GRAPH}/${apiVersion}/${encodeURIComponent(pixelId)}/events`, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body,\n });\n\n if (!response.ok) {\n // The status only. The event carries raw personal data, and no\n // library-owned surface re-emits it into a host's logs.\n throw new Error(`meta: the Conversions API answered ${response.status}`);\n }\n\n // A body that will not parse must not turn a delivered conversion into\n // an error, which would tell a host's retry logic to send it again.\n const result = (await response.json().catch(() => null)) as {\n messages?: unknown[];\n fbtrace_id?: string;\n } | null;\n\n const messages = result?.messages;\n if (Array.isArray(messages) && messages.length > 0) {\n // A caveat about a send that already happened, so it reports rather\n // than throws. The count and the trace id only: Meta's warnings can\n // quote the parameter that upset it, and event contents never reach a\n // host's logs through this library.\n report(\n `accepted with ${messages.length} warning(s) from the Conversions API; read them under fbtrace_id ${result?.fbtrace_id ?? 'unknown'} in Events Manager`,\n );\n }\n },\n };\n}\n","// Through the public entry point, exactly as a provider written elsewhere\n// would import it. A provider that needs something not exported here is\n// telling us the contract is incomplete, which is a conversation rather than\n// a reason to reach inside.\nimport type { EventBinding, EventData, ResolvedContext, ServerProvider } from '../index.js';\n\nconst DEFAULT_HOST = 'https://us.i.posthog.com';\n\n/** Credentials for PostHog's Capture API. */\nexport interface PosthogServerCredentials {\n /** The project API key, the same one the browser SDK is initialised with (`phc_...`). */\n apiKey: string;\n /**\n * Where this project ingests events, when it is not PostHog's default US\n * Cloud instance — `https://eu.i.posthog.com` for the EU Cloud, or a\n * self-hosted deployment's own origin. Defaults to `https://us.i.posthog.com`.\n */\n host?: string;\n}\n\n/** Optional configuration for the PostHog server provider. */\nexport interface PosthogServerConfig {\n /**\n * How this project spells each canonical event. Rarely needed: `capture()`\n * accepts any string, so the canonical vocabulary already is PostHog's.\n */\n events?: Record<string, EventBinding<string>>;\n}\n\n/**\n * The distinct_id lives inside a cookie posthog-js writes by default, named\n * after this project's own api key: `ph_<api_key>_posthog`. Its value is\n * `encodeURIComponent(JSON.stringify({ distinct_id, ... }))`, so it has to be\n * decoded before it parses as JSON.\n *\n * Verified against a live project rather than read off the SDK's source: the\n * cookie was percent-encoded, held `distinct_id` alongside `$device_id` and\n * `$user_state`, and the id parsed out of it matched what the page's own\n * `posthog.get_distinct_id()` returned. A server event sent with it landed on\n * the same person the browser had created, which is the whole point.\n *\n * This is only the anonymous fallback. It is not read when the caller already\n * knows who the visitor is; see the comment in `track` for why.\n */\nfunction anonymousId(cookies: Record<string, string>, apiKey: string): string | undefined {\n const raw = cookies[`ph_${apiKey}_posthog`];\n if (!raw) return undefined;\n\n try {\n const parsed = JSON.parse(decodeURIComponent(raw)) as { distinct_id?: unknown };\n return typeof parsed.distinct_id === 'string' ? parsed.distinct_id : undefined;\n } catch {\n // A cookie that fails to decode or parse is not this vendor's cookie, or\n // not this shape of it. Either way, nothing to read.\n return undefined;\n }\n}\n\n/**\n * PostHog deduplicates on `uuid`, and the field holds a UUID rather than any\n * string: an invalid one is documented as dropped on ingestion, and has been\n * reported answering 400 instead. Since `dedupId` is whatever the host chose\n * — Meta's `event_id` takes anything, and this library's own example is an\n * order id — forwarding it unchecked would turn a duplicated purchase into no\n * purchase at all.\n *\n * Accepts any RFC 4122 layout rather than v4 alone, because v7 is what a\n * system minting ids today tends to produce.\n */\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/**\n * PostHog on the server, through the Capture API.\n *\n * **Deduplicating a retried webhook takes two things, not one.** `dedupId`\n * becomes PostHog's `uuid`, and PostHog collapses events sharing `uuid`, event\n * name, timestamp and `distinct_id` — so a `timestamp` left to default to the\n * clock differs on the retry and nothing is deduplicated. Pin it to a value\n * derived from the order, as below. The `dedupId` itself must be a UUID:\n * anything else is reported through `onError` and sent without the field,\n * because PostHog rejects other shapes rather than ignoring them.\n *\n * Deduplication is also eventual, happening during a background merge, so both\n * rows are visible for a while and a test that counts immediately will fail.\n *\n * @param credentials - The project API key, and the ingestion host for\n * anything other than PostHog's default US Cloud instance.\n * @param config - Rarely needed event name overrides.\n * @returns A provider for `createTracking` from `tracklane/server`.\n *\n * @example\n * ```ts\n * import { createTracking, posthog } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [posthog({ apiKey: process.env.POSTHOG_API_KEY! })],\n * });\n *\n * // Both fields come from the order, so the payment provider's second\n * // delivery of the same webhook produces the same event.\n * await track('purchase', order, {\n * user: { userId: order.userId },\n * cookies: request.headers.get('cookie'),\n * dedupId: order.eventId, // a UUID your checkout minted with the order\n * timestamp: order.paidAt,\n * });\n * ```\n */\nexport function posthog(\n credentials: PosthogServerCredentials,\n config: PosthogServerConfig = {},\n): ServerProvider {\n const { apiKey, host = DEFAULT_HOST } = credentials;\n\n return {\n name: 'posthog',\n // capture() accepts any string as an event name, so the canonical\n // vocabulary already is PostHog's, and every event passes through\n // unless the host says otherwise.\n default: 'passthrough',\n ...(config.events ? { events: config.events } : {}),\n\n async track(\n name: string,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void> {\n // PostHog has one identity slot, distinct_id — not two the way GA4 has\n // a required client_id plus an optional user_id. PostHog's own\n // guidance is to send the same distinct_id the browser SDK is using\n // for that visitor, so a known application user id (the same value\n // handed to `identify()` on the browser) is used first, because it is\n // what the visitor becomes once they are known. The anonymous id\n // PostHog's own tag already wrote to its cookie is the fallback for a\n // visitor nobody has identified yet. Inventing a third value here\n // would orphan the event: PostHog would accept it and never connect it\n // to anything, on either side.\n const id = context.user?.userId ?? anonymousId(context.cookies, apiKey);\n if (!id) {\n throw new Error(\n \"posthog: cannot resolve distinct_id — no user.userId in context and no ph_<api_key>_posthog cookie among the cookies passed in context. Pass user.userId once the visitor is known, or ensure PostHog's browser tag has set its cookie first.\",\n );\n }\n\n const properties: Record<string, unknown> = { ...data };\n // $set is the server-side slot for what is known *about* the person,\n // the same job `user_properties` does in GA4's Measurement Protocol\n // body — kept separate from the identifiers used to match someone.\n if (context.traits) properties.$set = context.traits;\n\n // The deduplication key is `uuid`, and it is the whole quartet of\n // `uuid`, event name, timestamp and distinct_id that PostHog collapses,\n // eventually, during a background merge. So this field alone does not\n // make a retry idempotent: the host has to pin `context.timestamp` to\n // something derived from the order rather than let it default to the\n // clock. That is documentation's job, not this adapter's.\n const dedup: { uuid?: string } = {};\n if (context.dedupId !== undefined) {\n if (UUID.test(context.dedupId)) {\n dedup.uuid = context.dedupId;\n } else {\n // Sent anyway, without the field. The alternative is the vendor\n // dropping the whole event over an id shape, which trades a visible\n // duplicate for an invisible absence.\n report(\n 'dedupId is not a UUID, so it was not forwarded as uuid: PostHog deduplicates on that field and rejects other shapes, so this event can duplicate on a retry',\n );\n }\n }\n\n const body = {\n api_key: apiKey,\n event: name,\n distinct_id: id,\n ...dedup,\n // context.url, context.ip and context.userAgent are not forwarded\n // either. PostHog documents override properties for some of these\n // on other surfaces, but nothing found here confirms one for this\n // endpoint with enough certainty to translate rather than guess, so\n // they are left unmapped. context.consent and context.source are\n // Google's and Meta's vocabularies respectively, and this endpoint\n // documents a slot for neither.\n properties,\n timestamp: new Date(context.timestamp).toISOString(),\n };\n\n const response = await fetch(`${host}/i/v0/e/`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n // The status only. The event carries raw personal data, and no\n // library-owned surface re-emits it into a host's logs.\n throw new Error(`posthog: the capture endpoint answered ${response.status}`);\n }\n },\n };\n}\n","import { assertUniqueProviders, makeReporter, messageOf, resolveEvent } from './dispatch.js';\n\nexport {\n type Ga4ServerConfig,\n type Ga4ServerCredentials,\n ga4,\n} from './providers/ga4.server.js';\nexport {\n type MetaServerConfig,\n type MetaServerCredentials,\n meta,\n} from './providers/meta.server.js';\nexport {\n type PosthogServerConfig,\n type PosthogServerCredentials,\n posthog,\n} from './providers/posthog.server.js';\n\nimport type {\n ActionSource,\n ConsentState,\n EventBinding,\n EventData,\n ProviderDefault,\n TrackingError,\n UserData,\n} from './vocabulary.js';\n\n/**\n * Everything a conversion API needs beyond the event itself: who the person\n * is, when it happened, and where it was observed.\n *\n * None of this is \"what happened\", which is why it does not travel in the\n * event data: putting it there would leak identity into the pass-through\n * event params of the vendors that forward the payload as-is.\n */\nexport interface EventContext {\n /** The person's identity, the server-side counterpart to `identify()` on the browser. */\n user?: UserData;\n /**\n * The request's raw `Cookie` header, or an already-parsed map.\n *\n * These are cookies the vendors' own browser tags set. This library never\n * writes one. On the server each adapter reads the cookies belonging to\n * its own vendor: Meta forwards its value as-is, Google's holds several\n * things at once and has to be opened. That knowledge lives in the\n * adapters; the core only splits `name=value; name=value` into pairs.\n *\n * **It splits, it does not interpret.** Values are handed over exactly as\n * they appear, with no percent-decoding. The cookies these vendors set do\n * not need it; a host reading some other cookie should decode it itself.\n */\n cookies?: string | Record<string, string> | null;\n /** Ties this send to a browser hit. Never invented by the library. */\n dedupId?: string;\n /**\n * When the conversion actually happened. Defaults to now.\n *\n * A webhook arrives after the fact and LinkedIn rejects conversions older\n * than 90 days, so reporting \"now\" for everything would quietly distort\n * attribution.\n */\n timestamp?: number | Date;\n /** Overrides the factory default. Meta requires it on every event. */\n source?: ActionSource;\n /** The page the conversion happened on. Meta's Conversions API reads it as `event_source_url`. */\n url?: string;\n /** The visitor's IP. Meta's Conversions API reads it as one of the identifiers in `user_data`. */\n ip?: string;\n /** The visitor's user agent. Meta's Conversions API reads it alongside `ip`. */\n userAgent?: string;\n /** What is known *about* the person: GA4 user properties, PostHog `$set`. */\n traits?: Record<string, unknown>;\n /**\n * Travels inside the event, for the vendors that document such a field.\n * Today that is GA4's Measurement Protocol, and it reads two of the\n * signals; the others have no slot and ignore it.\n */\n consent?: ConsentState;\n}\n\n/** The context an adapter receives, with the ambiguity resolved. */\nexport interface ResolvedContext extends Omit<EventContext, 'cookies' | 'timestamp'> {\n /** The request's cookies, already split into a `name → value` map. */\n cookies: Record<string, string>;\n /** Epoch milliseconds. Adapters convert to their vendor's spelling. */\n timestamp: number;\n}\n\n/**\n * A destination for server events.\n *\n * `track` may throw, on a non-2xx or where a vendor documents a\n * precondition the event cannot meet. The dispatcher isolates and reports\n * it, so adapters stay honest and loud.\n *\n * `report` is for a caveat about a request that already succeeded. It does\n * not throw: by then the send happened, and throwing would tell a host's\n * retry logic to resend a delivered conversion.\n */\nexport interface ServerProvider<Target = string> {\n /** The vendor's fixed name. Registering one twice is an error. */\n name: string;\n /** What happens to a canonical event this vendor has no binding for. */\n default: ProviderDefault;\n /** How this vendor spells each canonical event. */\n events?: Record<string, EventBinding<Target>>;\n /** Sends one event to this vendor's conversion API. May throw, or call `report` for a caveat. */\n track(\n name: Target,\n data: EventData,\n context: ResolvedContext,\n report: (message: string) => void,\n ): Promise<void>;\n}\n\n/** Options accepted by {@link createTracking}. */\nexport interface ServerTrackingOptions {\n /** The vendors to send every event to. Registering the same `name` twice throws. */\n providers: readonly ServerProvider[];\n /**\n * The one diagnostic channel. Without it the library is silent, exactly as\n * a hand-written vendor call is.\n */\n onError?: (error: TrackingError) => void;\n}\n\n/** What {@link createTracking} returns. */\nexport interface ServerTracking {\n /**\n * Sends one event to every configured conversion API.\n *\n * Resolves once every provider has settled and never rejects: one vendor\n * being down is not the caller's failure to handle. Awaiting is about the\n * request surviving a serverless runtime, not about delivery being\n * guaranteed.\n */\n track(name: string, data?: EventData, context?: EventContext): Promise<void>;\n}\n\n/** `name=value; name=value`, the shape of a `Cookie` header. */\nfunction parseCookies(\n cookies: string | Record<string, string> | null | undefined,\n): Record<string, string> {\n if (!cookies) return {};\n if (typeof cookies !== 'string') return cookies;\n\n const parsed: Record<string, string> = {};\n\n for (const pair of cookies.split(';')) {\n const separator = pair.indexOf('=');\n if (separator < 1) continue;\n\n const name = pair.slice(0, separator).trim();\n // Cookie values may contain `=`, so only the first one separates.\n if (name) parsed[name] = pair.slice(separator + 1).trim();\n }\n\n return parsed;\n}\n\n/**\n * Creates the server tracking surface.\n *\n * There is no `identify` here and nothing is held between calls: a server\n * instance is shared by every request, so a retained identity would attach\n * one visitor to another visitor's conversion. Identity travels with the\n * call, which is also what every conversion API expects.\n *\n * There is no `consent` call either. Consent commands are properties of a\n * vendor's on-page tag, and a server request has no tag. The one vendor that\n * accepts consent server-side reads it from the context.\n *\n * @param options - The providers to send to, and an optional error channel.\n * @returns The `track` call.\n *\n * @example\n * ```ts\n * import { createTracking, ga4 } from 'tracklane/server';\n *\n * const { track } = createTracking({\n * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret })],\n * });\n *\n * await track('purchase', order, { cookies: request.headers.get('cookie') });\n * ```\n */\nexport function createTracking(options: ServerTrackingOptions): ServerTracking {\n const { providers } = options;\n assertUniqueProviders(providers);\n\n const report = makeReporter(options.onError);\n\n return {\n async track(name, data = {}, context = {}) {\n const { cookies, timestamp, ...rest } = context;\n const resolved: ResolvedContext = {\n ...rest,\n cookies: parseCookies(cookies),\n timestamp: timestamp instanceof Date ? timestamp.getTime() : (timestamp ?? Date.now()),\n };\n\n const sends = providers.map(async (provider) => {\n const target = resolveEvent(provider, name);\n if (target === undefined) return;\n\n try {\n await provider.track(target, data, resolved, (message) => {\n report({ provider: provider.name, event: name, severity: 'warning', message });\n });\n } catch (cause) {\n report({\n provider: provider.name,\n event: name,\n severity: 'error',\n message: messageOf(cause),\n cause,\n });\n }\n });\n\n await Promise.all(sends);\n },\n };\n}\n"],"mappings":";;AAYA,MAAM,WAAW;;;;;;;;;AAuBjB,SAAS,UAAU,SAAqD;CACtE,MAAM,MAAM,QAAQ;CACpB,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,MAAM,SAAS,GAAG,OAAO,KAAA;CAE7B,OAAO,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,GAAG;AACjC;;;;;;;;;;;;;;;;;AAkBA,SAAS,UAAU,SAAiC,eAA2C;CAK7F,MAAM,UADQ,QAAQ,OAAO,cAAc,QAAQ,OAAO,EAAE,IACvC,EAAE,MAAM,GAAG,CAAC,CAAC;CAClC,IAAI,CAAC,SAAS,OAAO,KAAA;CAErB,MAAM,SAAS,UAAU,KAAK,OAAO;CACrC,IAAI,QAAQ,OAAO,OAAO;CAG1B,OAAO,QAAQ,KAAK,OAAO,IAAI,UAAU,KAAA;AAC3C;;;;;;AAOA,SAAS,YAAY,OAAqE;CACxF,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,MAAM,OAA+B,CAAC;CACtC,IAAI,MAAM,cAAc,KAAK,eAAe,MAAM,aAAa,YAAY;CAC3E,IAAI,MAAM,oBAAoB,KAAK,qBAAqB,MAAM,mBAAmB,YAAY;CAE7F,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,IAAI,OAAO,KAAA;AAC/C;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,IACd,aACA,SAA0B,CAAC,GACX;CAChB,MAAM,EAAE,eAAe,cAAc;CAErC,OAAO;EACL,MAAM;EACN,SAAS;EACT,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;EAEjD,MAAM,MACJ,MACA,MACA,SACA,QACe;GACf,MA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;;;;;;;;;;;;;;;AA4BA,SAAgB,eAAe,SAAgD;CAC7E,MAAM,EAAE,cAAc;CACtB,sBAAsB,SAAS;CAE/B,MAAM,SAAS,aAAa,QAAQ,OAAO;CAE3C,OAAO,EACL,MAAM,MAAM,MAAM,OAAO,CAAC,GAAG,UAAU,CAAC,GAAG;EACzC,MAAM,EAAE,SAAS,WAAW,GAAG,SAAS;EACxC,MAAM,WAA4B;GAChC,GAAG;GACH,SAAS,aAAa,OAAO;GAC7B,WAAW,qBAAqB,OAAO,UAAU,QAAQ,IAAK,aAAa,KAAK,IAAI;EACtF;EAEA,MAAM,QAAQ,UAAU,IAAI,OAAO,aAAa;GAC9C,MAAM,SAAS,aAAa,UAAU,IAAI;GAC1C,IAAI,WAAW,KAAA,GAAW;GAE1B,IAAI;IACF,MAAM,SAAS,MAAM,QAAQ,MAAM,WAAW,YAAY;KACxD,OAAO;MAAE,UAAU,SAAS;MAAM,OAAO;MAAM,UAAU;MAAW;KAAQ,CAAC;IAC/E,CAAC;GACH,SAAS,OAAO;IACd,OAAO;KACL,UAAU,SAAS;KACnB,OAAO;KACP,UAAU;KACV,SAAS,UAAU,KAAK;KACxB;IACF,CAAC;GACH;EACF,CAAC;EAED,MAAM,QAAQ,IAAI,KAAK;CACzB,EACF;AACF"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tracklane",
3
- "version": "0.2.0",
4
- "description": "One interface between your application and every tool that receives events, for the browser and server. GA4 and Meta today; LinkedIn, PostHog and X next.",
3
+ "version": "0.4.0",
4
+ "description": "One interface between your application and every tool that receives events, for the browser and server. GA4, Meta and PostHog today; LinkedIn and X next.",
5
5
  "keywords": [
6
6
  "analytics",
7
7
  "tracking",