tracklane 0.1.1 → 0.2.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
@@ -1,14 +1,20 @@
1
1
  # tracklane
2
2
 
3
- > One interface between your application and every tool that receives events.
3
+ > One interface between your application and every analytics and advertising tool, in the browser
4
+ > and through their conversion APIs.
4
5
 
5
6
  Every analytics and advertising tool arrives with its own SDK, its own event names and its own
6
7
  payload format. Add a second one and the tracking call at each conversion point stops being a line
7
8
  and becomes a block. Add a third and every one of those blocks has to change.
8
9
 
9
- `tracklane` gives your application one interface. Name what happened once, in GA4's vocabulary,
10
- and it reaches every tool you configured, in the browser and through their server-side conversion
11
- APIs.
10
+ The server-side half is worse. Each vendor ships a separate conversion API with a different name
11
+ and a different contract: Google's Measurement Protocol, Meta's Conversions API, LinkedIn's
12
+ Conversions API, PostHog's Capture API. Each wants its own identifiers, its own hashing rules, and
13
+ its own way of tying a server event back to the browser event so the two are not counted twice.
14
+
15
+ `tracklane` gives your application one interface for both. Name what happened once, in GA4's
16
+ vocabulary, and it reaches every tool you configured, translated into that tool's event names,
17
+ payload shape and identifiers.
12
18
 
13
19
  **Documentation:** https://tracklane.codar.me
14
20
 
@@ -40,6 +46,10 @@ consent('update', { ad_storage: 'granted', analytics_storage: 'granted' });
40
46
 
41
47
  ## Server
42
48
 
49
+ Each vendor's conversion API, behind the call you already wrote. The credentials are that vendor's
50
+ own: GA4's Measurement Protocol wants a `measurementId` alongside its `apiSecret`, exactly as its
51
+ own endpoint does.
52
+
43
53
  ```ts
44
54
  import { createTracking, ga4 } from 'tracklane/server';
45
55
 
@@ -72,7 +82,20 @@ install vendor tags.
72
82
 
73
83
  ## Providers
74
84
 
75
- **GA4** ships today, on both surfaces. **Meta, LinkedIn, PostHog and X** are next.
85
+ Both surfaces, or it does not count as shipped. This table is checked against the source on every
86
+ build, so it is never ahead of the library.
87
+
88
+ <!-- providers:start -->
89
+
90
+ | Vendor | Conversion API | Status |
91
+ | -------- | -------------------- | ------ |
92
+ | GA4 | Measurement Protocol | shipped |
93
+ | Meta | Conversions API | shipped |
94
+ | LinkedIn | Conversions API | next |
95
+ | PostHog | Capture API | next |
96
+ | X | Conversions API | next |
97
+
98
+ <!-- providers:end -->
76
99
 
77
100
  Any tool that receives events about what your users do can be a destination, and writing your own
78
101
  uses the same public contract the built-in ones use, without a registry entry, an allow-list, or a
@@ -0,0 +1,552 @@
1
+ //#region src/providers/ga4.server.d.ts
2
+ /** Credentials for the GA4 Measurement Protocol. */
3
+ interface Ga4ServerCredentials {
4
+ /** The `G-` id of the data stream. */
5
+ measurementId: string;
6
+ /** Created under Admin → Data Streams → Measurement Protocol. */
7
+ apiSecret: string;
8
+ }
9
+ /** Optional configuration for the GA4 server provider. */
10
+ interface Ga4ServerConfig {
11
+ events?: Record<string, EventBinding<string>>;
12
+ }
13
+ /**
14
+ * Google Analytics 4 on the server, through the Measurement Protocol.
15
+ *
16
+ * @param credentials - The measurement id and API secret.
17
+ * @param config - Rarely needed event name overrides.
18
+ * @returns A provider for `createTracking` from `tracklane/server`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { createTracking, ga4 } from 'tracklane/server';
23
+ *
24
+ * const { track } = createTracking({
25
+ * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret: process.env.GA4_SECRET! })],
26
+ * });
27
+ *
28
+ * await track('purchase', order, { cookies: request.headers.get('cookie') });
29
+ * ```
30
+ */
31
+ declare function ga4$1(credentials: Ga4ServerCredentials, config?: Ga4ServerConfig): ServerProvider;
32
+ //#endregion
33
+ //#region src/providers/meta.server.d.ts
34
+ /** Credentials for Meta's Conversions API. */
35
+ interface MetaServerCredentials {
36
+ /** The pixel (dataset) id events are posted to. */
37
+ pixelId: string;
38
+ /** A system user or page access token with `ads_management`. It is a credential. */
39
+ accessToken: string;
40
+ }
41
+ /** Optional configuration for the Meta server provider. */
42
+ interface MetaServerConfig {
43
+ /** How this pixel spells each canonical event, merged over the built-in map. */
44
+ events?: Record<string, EventBinding<string>>;
45
+ /**
46
+ * Where conversions happen by default. Meta requires `action_source` on
47
+ * every event, so there is always a value; `context.source` overrides it
48
+ * per call, which is what a webhook and a checkout need.
49
+ */
50
+ actionSource?: ActionSource;
51
+ /** The Graph API version in the URL. Defaults to a pinned one. */
52
+ apiVersion?: string;
53
+ /**
54
+ * Routes events to the Test Events tab in Events Manager instead of the
55
+ * live dataset. **Testing only**: Meta says to remove it before
56
+ * production, and it is the only instrument that shows what a payload
57
+ * actually became.
58
+ */
59
+ testEventCode?: string;
60
+ /**
61
+ * Meta's Limited Data Use marking, forwarded verbatim: `['LDU']` to enable
62
+ * it, `[]` to disable it.
63
+ *
64
+ * This is a processing marking that some US state laws require, not a
65
+ * consent declaration, which is why it is configuration on this factory and
66
+ * not a reading of `context.consent`. The browser half has no equivalent:
67
+ * `fbq('dataProcessingOptions', …)` is documented as running before
68
+ * `fbq('init')`, and the snippet is the host's.
69
+ */
70
+ dataProcessingOptions?: readonly string[];
71
+ /** `0` lets Meta geolocate. Meaningless without `dataProcessingOptions`. */
72
+ dataProcessingOptionsCountry?: number;
73
+ /** `0` lets Meta geolocate. Meaningless without `dataProcessingOptions`. */
74
+ dataProcessingOptionsState?: number;
75
+ }
76
+ /**
77
+ * Meta's Conversions API.
78
+ *
79
+ * @param credentials - The pixel id and an access token.
80
+ * @param config - Event overrides, the default action source, and Meta's own
81
+ * levers: the API version, a test event code, and Limited Data Use.
82
+ * @returns A provider for `createTracking` from `tracklane/server`.
83
+ *
84
+ * @example
85
+ * ```ts
86
+ * import { createTracking, meta } from 'tracklane/server';
87
+ *
88
+ * const { track } = createTracking({
89
+ * providers: [meta({ pixelId: '1234567890', accessToken: process.env.META_TOKEN! })],
90
+ * });
91
+ *
92
+ * await track('purchase', order, {
93
+ * user: { email: order.email },
94
+ * cookies: request.headers.get('cookie'),
95
+ * dedupId: order.id,
96
+ * ip,
97
+ * userAgent,
98
+ * });
99
+ * ```
100
+ */
101
+ declare function meta$1(credentials: MetaServerCredentials, config?: MetaServerConfig): ServerProvider;
102
+ //#endregion
103
+ //#region src/vocabulary.d.ts
104
+ /**
105
+ * The vocabulary shared by the browser and server libraries.
106
+ *
107
+ * These two libraries never talk to each other. They share no runtime, no
108
+ * state, no instance in common. What they share is this: the names of
109
+ * events and the shape of the data that travels with them, so that
110
+ * `purchase` means the same thing on both sides. This is the only overlap
111
+ * that exists on purpose.
112
+ */
113
+ /** One item inside an ecommerce event, spelled the way GA4 spells it. */
114
+ interface EventItem {
115
+ /** The SKU or catalogue id for this line. */
116
+ item_id?: string;
117
+ /** The product name for this line, shown in reports. */
118
+ item_name?: string;
119
+ /** The unit price for this line, before `quantity`. */
120
+ price?: number;
121
+ /** How many units of this line. */
122
+ quantity?: number;
123
+ [key: string]: unknown;
124
+ }
125
+ /**
126
+ * The business payload of an event.
127
+ *
128
+ * The named fields are the ones adapters read to build vendor-specific value
129
+ * and content slots. The index signature is deliberate: a business measures
130
+ * things this vocabulary does not name, and closing the bag would make the
131
+ * library the arbiter of what may be measured.
132
+ */
133
+ interface EventData {
134
+ /** The order id. GA4 needs it, together with `items`, to record a purchase. */
135
+ transaction_id?: string;
136
+ /** The monetary amount, paired with `currency`. */
137
+ value?: number;
138
+ /** An ISO 4217 code. GA4 requires it whenever `value` is set. */
139
+ currency?: string;
140
+ /** The cart or order lines, required by GA4 alongside `transaction_id` for a purchase. */
141
+ items?: EventItem[];
142
+ [key: string]: unknown;
143
+ }
144
+ /**
145
+ * Who the person is.
146
+ *
147
+ * One identifier for the person, which every vendor receives under its own
148
+ * name. Values are always raw: hashing and normalisation are field formats
149
+ * each vendor defines, applied inside the adapter that owns the field.
150
+ *
151
+ * Everything else that identifies someone arrives through cookies on the
152
+ * server, read by whichever adapter knows the format.
153
+ */
154
+ interface UserData {
155
+ /** One id for the person, translated per vendor. */
156
+ userId?: string;
157
+ /** Raw and unhashed. Adapters that need it hashed (Meta, LinkedIn) do that themselves. */
158
+ email?: string;
159
+ /** Raw, in whatever format the host has it. An adapter normalises it if its vendor needs to. */
160
+ phone?: string;
161
+ /** Raw, read only by vendors whose identity match uses names, such as Meta. */
162
+ firstName?: string;
163
+ /** Raw, read only by vendors whose identity match uses names, such as Meta. */
164
+ lastName?: string;
165
+ /** From the URL rather than a cookie, which is why it is named here. */
166
+ twclid?: string;
167
+ }
168
+ /**
169
+ * Consent signals, in Google's own spelling.
170
+ *
171
+ * Google's is the most granular surface any of the five vendors exposes, so
172
+ * every other vendor receives a *collapse* of it. Carrying the finest
173
+ * resolution and reducing per vendor means a projection never claims more
174
+ * than the host declared. Expanding a coarse answer into fine signals would
175
+ * invent information, and this library never does that.
176
+ *
177
+ * An absent signal produces no key. Treating silence as a denial would put
178
+ * words in the visitor's mouth, just as treating it as a grant would.
179
+ */
180
+ interface ConsentState {
181
+ /** Governs Google's ad cookies. Browser only, since GA4's server-side API has no slot for it. */
182
+ ad_storage?: "granted" | "denied";
183
+ /** Governs Google's analytics cookies. Browser only, since GA4's server-side API has no slot. */
184
+ analytics_storage?: "granted" | "denied";
185
+ /** Whether user data may be sent for ads. GA4's server-side API reads this one, uppercased. */
186
+ ad_user_data?: "granted" | "denied";
187
+ /** Whether ads may be personalised. GA4's server-side API reads this one too, uppercased. */
188
+ ad_personalization?: "granted" | "denied";
189
+ }
190
+ /**
191
+ * Where a conversion happened.
192
+ *
193
+ * Meta's vocabulary, adopted verbatim, because it is the only vendor of the
194
+ * five that documents the concept and requires the field on every server
195
+ * event. Inventing a taxonomy and translating it would be both incomplete
196
+ * for Meta and meaningless to everyone else.
197
+ */
198
+ type ActionSource = "website" | "app" | "email" | "phone_call" | "chat" | "physical_store" | "system_generated" | "business_messaging" | "other";
199
+ /**
200
+ * How a canonical event name is spelled for one vendor, or `null` to say
201
+ * "never send this event here".
202
+ */
203
+ type EventBinding<Target> = Target | null;
204
+ /** What a provider does with a canonical event it has no binding for. */
205
+ type ProviderDefault = "passthrough" | "ignore";
206
+ /**
207
+ * Reported out of band, never thrown at the call site.
208
+ *
209
+ * Fanning out to N vendors means no single call site can catch anything, so
210
+ * this is the replica of the `try/catch` a host would have written around a
211
+ * hand-made call. `severity` separates "this did not arrive" from "this
212
+ * arrived, and here is something you should know".
213
+ *
214
+ * It never carries event contents: the payload holds raw personal data by
215
+ * design, and no library-owned surface re-emits it into a host's logs.
216
+ */
217
+ interface TrackingError {
218
+ /** Which vendor produced this. It matches the `name` on the provider that registered it. */
219
+ provider: string;
220
+ /** The canonical event name being sent when this happened. */
221
+ event: string;
222
+ /** `'error'` when the event did not arrive; `'warning'` when it arrived but is worth a look. */
223
+ severity: "error" | "warning";
224
+ /** What happened, in one line, excluding the payload: event data never appears here. */
225
+ message: string;
226
+ /** The original thrown value, where one exists, for a host that wants more than `message`. */
227
+ cause?: unknown;
228
+ }
229
+ //#endregion
230
+ //#region src/server.d.ts
231
+ /**
232
+ * Everything a conversion API needs beyond the event itself: who the person
233
+ * is, when it happened, and where it was observed.
234
+ *
235
+ * None of this is "what happened", which is why it does not travel in the
236
+ * event data: putting it there would leak identity into the pass-through
237
+ * event params of the vendors that forward the payload as-is.
238
+ */
239
+ interface EventContext {
240
+ /** The person's identity, the server-side counterpart to `identify()` on the browser. */
241
+ user?: UserData;
242
+ /**
243
+ * The request's raw `Cookie` header, or an already-parsed map.
244
+ *
245
+ * These are cookies the vendors' own browser tags set. This library never
246
+ * writes one. On the server each adapter reads the cookies belonging to
247
+ * its own vendor: Meta forwards its value as-is, Google's holds several
248
+ * things at once and has to be opened. That knowledge lives in the
249
+ * adapters; the core only splits `name=value; name=value` into pairs.
250
+ *
251
+ * **It splits, it does not interpret.** Values are handed over exactly as
252
+ * they appear, with no percent-decoding. The cookies these vendors set do
253
+ * not need it; a host reading some other cookie should decode it itself.
254
+ */
255
+ cookies?: string | Record<string, string> | null;
256
+ /** Ties this send to a browser hit. Never invented by the library. */
257
+ dedupId?: string;
258
+ /**
259
+ * When the conversion actually happened. Defaults to now.
260
+ *
261
+ * A webhook arrives after the fact and LinkedIn rejects conversions older
262
+ * than 90 days, so reporting "now" for everything would quietly distort
263
+ * attribution.
264
+ */
265
+ timestamp?: number | Date;
266
+ /** Overrides the factory default. Meta requires it on every event. */
267
+ source?: ActionSource;
268
+ /** The page the conversion happened on. Meta's Conversions API reads it as `event_source_url`. */
269
+ url?: string;
270
+ /** The visitor's IP. Meta's Conversions API reads it as one of the identifiers in `user_data`. */
271
+ ip?: string;
272
+ /** The visitor's user agent. Meta's Conversions API reads it alongside `ip`. */
273
+ userAgent?: string;
274
+ /** What is known *about* the person: GA4 user properties, PostHog `$set`. */
275
+ traits?: Record<string, unknown>;
276
+ /**
277
+ * Travels inside the event, for the vendors that document such a field.
278
+ * Today that is GA4's Measurement Protocol, and it reads two of the
279
+ * signals; the others have no slot and ignore it.
280
+ */
281
+ consent?: ConsentState;
282
+ }
283
+ /** The context an adapter receives, with the ambiguity resolved. */
284
+ interface ResolvedContext extends Omit<EventContext, "cookies" | "timestamp"> {
285
+ /** The request's cookies, already split into a `name → value` map. */
286
+ cookies: Record<string, string>;
287
+ /** Epoch milliseconds. Adapters convert to their vendor's spelling. */
288
+ timestamp: number;
289
+ }
290
+ /**
291
+ * A destination for server events.
292
+ *
293
+ * `track` may throw, on a non-2xx or where a vendor documents a
294
+ * precondition the event cannot meet. The dispatcher isolates and reports
295
+ * it, so adapters stay honest and loud.
296
+ *
297
+ * `report` is for a caveat about a request that already succeeded. It does
298
+ * not throw: by then the send happened, and throwing would tell a host's
299
+ * retry logic to resend a delivered conversion.
300
+ */
301
+ interface ServerProvider<Target = string> {
302
+ /** The vendor's fixed name. Registering one twice is an error. */
303
+ name: string;
304
+ /** What happens to a canonical event this vendor has no binding for. */
305
+ default: ProviderDefault;
306
+ /** How this vendor spells each canonical event. */
307
+ events?: Record<string, EventBinding<Target>>;
308
+ /** Sends one event to this vendor's conversion API. May throw, or call `report` for a caveat. */
309
+ track(name: Target, data: EventData, context: ResolvedContext, report: (message: string) => void): Promise<void>;
310
+ }
311
+ /** Options accepted by {@link createTracking}. */
312
+ interface ServerTrackingOptions {
313
+ /** The vendors to send every event to. Registering the same `name` twice throws. */
314
+ providers: readonly ServerProvider[];
315
+ /**
316
+ * The one diagnostic channel. Without it the library is silent, exactly as
317
+ * a hand-written vendor call is.
318
+ */
319
+ onError?: (error: TrackingError) => void;
320
+ }
321
+ /** What {@link createTracking} returns. */
322
+ interface ServerTracking {
323
+ /**
324
+ * Sends one event to every configured conversion API.
325
+ *
326
+ * Resolves once every provider has settled and never rejects: one vendor
327
+ * being down is not the caller's failure to handle. Awaiting is about the
328
+ * request surviving a serverless runtime, not about delivery being
329
+ * guaranteed.
330
+ */
331
+ track(name: string, data?: EventData, context?: EventContext): Promise<void>;
332
+ }
333
+ /**
334
+ * Creates the server tracking surface.
335
+ *
336
+ * There is no `identify` here and nothing is held between calls: a server
337
+ * instance is shared by every request, so a retained identity would attach
338
+ * one visitor to another visitor's conversion. Identity travels with the
339
+ * call, which is also what every conversion API expects.
340
+ *
341
+ * There is no `consent` call either. Consent commands are properties of a
342
+ * vendor's on-page tag, and a server request has no tag. The one vendor that
343
+ * accepts consent server-side reads it from the context.
344
+ *
345
+ * @param options - The providers to send to, and an optional error channel.
346
+ * @returns The `track` call.
347
+ *
348
+ * @example
349
+ * ```ts
350
+ * import { createTracking, ga4 } from 'tracklane/server';
351
+ *
352
+ * const { track } = createTracking({
353
+ * providers: [ga4({ measurementId: 'G-XXXXXXX', apiSecret })],
354
+ * });
355
+ *
356
+ * await track('purchase', order, { cookies: request.headers.get('cookie') });
357
+ * ```
358
+ */
359
+ declare function createTracking$1(options: ServerTrackingOptions): ServerTracking;
360
+ //#endregion
361
+ //#region src/providers/ga4.browser.d.ts
362
+ /** Optional configuration for the GA4 browser provider. */
363
+ interface Ga4BrowserConfig {
364
+ /**
365
+ * How this property spells each canonical event. Rarely needed: the
366
+ * canonical vocabulary already is GA4's.
367
+ */
368
+ events?: Record<string, EventBinding<string>>;
369
+ }
370
+ /**
371
+ * Google Analytics 4 in the browser, through `gtag.js`.
372
+ *
373
+ * **This provider does not load Google's tag.** The tag belongs on the page,
374
+ * installed the way Google documents it: a snippet in the HTML, or a tag
375
+ * manager. This library talks to the tag that is already there; it never
376
+ * injects a third-party script into your page, and it never issues the
377
+ * property configuration that would emit a second page view.
378
+ *
379
+ * Which also means the initial consent declaration is not ours to make:
380
+ * Google requires it before the property is configured, and the snippet that
381
+ * configures the property is yours. Use {@link ConsentState} through
382
+ * `consent()` for changes after that.
383
+ *
384
+ * @param measurementId - The `G-` id of the data stream, matching the tag on
385
+ * the page.
386
+ * @param config - Rarely needed event name overrides.
387
+ * @returns A provider for `createTracking` from `tracklane/browser`.
388
+ *
389
+ * @example
390
+ * ```ts
391
+ * import { createTracking, ga4 } from 'tracklane/browser';
392
+ *
393
+ * // Google's own snippet is already in the page.
394
+ * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });
395
+ *
396
+ * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
397
+ * ```
398
+ */
399
+ declare function ga4(measurementId: string, config?: Ga4BrowserConfig): BrowserProvider;
400
+ //#endregion
401
+ //#region src/providers/meta.browser.d.ts
402
+ /** Optional configuration for the Meta browser provider. */
403
+ interface MetaBrowserConfig {
404
+ /**
405
+ * How this pixel spells each canonical event, merged over the built-in map.
406
+ *
407
+ * This is how the eight standard events with no GA4 counterpart are
408
+ * reached, and how an event is kept out of Meta entirely with `null`.
409
+ */
410
+ events?: Record<string, EventBinding<string>>;
411
+ }
412
+ /**
413
+ * The Meta pixel in the browser, through `fbq`.
414
+ *
415
+ * **This provider does not load Meta's pixel.** The base code belongs on the
416
+ * page, installed the way
417
+ * [Meta documents it](https://developers.facebook.com/docs/meta-pixel/get-started):
418
+ * a snippet in the HTML, or a tag manager. This library talks to the pixel
419
+ * that is already there; it never injects a third-party script and never
420
+ * issues `fbq('init')`.
421
+ *
422
+ * Three consequences follow from that, and all three are Meta's rules rather
423
+ * than ours:
424
+ *
425
+ * - **There is no `identify` here.** Meta accepts advanced matching only in
426
+ * the base code ("be sure to place advanced matching parameters in the
427
+ * pixel base code or the values will not be treated as manual advanced
428
+ * matching values"), and the base code is yours. Put `em`, `ph`, `fn`, `ln`
429
+ * in your own `fbq('init')`, where the pixel normalises and hashes them for
430
+ * you. On the server, where there is no snippet, the same identity travels
431
+ * in `context.user` and is hashed by the adapter.
432
+ * - **The initial consent declaration is not ours.** Meta wants
433
+ * `fbq('consent', 'revoke')` before `init`, and by the time you hold what
434
+ * `createTracking` returns that moment has passed. Ours is every
435
+ * declaration after it, through `consent()`.
436
+ * - **Limited Data Use is not ours either.** `fbq('dataProcessingOptions', …)`
437
+ * is documented as running before `init`. It belongs in your snippet. The
438
+ * server half, which has no snippet, carries it on its factory.
439
+ *
440
+ * **There is no pixel id here**, and that is deliberate rather than an
441
+ * omission. `fbq('track')` reaches every pixel the page initialised, so an id
442
+ * passed in would address nothing and the parameter would promise something
443
+ * this adapter cannot deliver. Which pixels exist is declared by your snippet,
444
+ * in `fbq('init')`.
445
+ *
446
+ * @param config - Event name overrides, merged over the built-in map.
447
+ * @returns A provider for `createTracking` from `tracklane/browser`.
448
+ *
449
+ * @example
450
+ * ```ts
451
+ * import { createTracking, meta } from 'tracklane/browser';
452
+ *
453
+ * // Meta's own base code is already in the page, and it named the pixel.
454
+ * const { track } = createTracking({ providers: [meta()] });
455
+ *
456
+ * // fbq('track', 'Purchase', { value: 49.9, currency: 'BRL' }, { eventID: 'T-1' })
457
+ * track('purchase', { value: 49.9, currency: 'BRL' }, { dedupId: 'T-1' });
458
+ * ```
459
+ */
460
+ declare function meta(config?: MetaBrowserConfig): BrowserProvider;
461
+ //#endregion
462
+ //#region src/browser.d.ts
463
+ /**
464
+ * Everything the browser needs beyond the event itself.
465
+ *
466
+ * There is one field, and that is the point: in the browser each vendor tag
467
+ * reads its own cookies and holds its own session, so the only thing left
468
+ * for the host to supply is the value that ties this hit to a server-side
469
+ * one.
470
+ */
471
+ interface TrackOptions {
472
+ /**
473
+ * The value that lets a vendor recognise this hit and a server-side hit as
474
+ * one event. The library never invents it: the browser and the server do
475
+ * not share a process, so only a value the host already owns (an order id)
476
+ * can match on both sides.
477
+ */
478
+ dedupId?: string;
479
+ }
480
+ /**
481
+ * A destination for browser events.
482
+ *
483
+ * This is the whole contract. A provider written outside this package
484
+ * implements it exactly as the providers shipped here do.
485
+ */
486
+ interface BrowserProvider<Target = string> {
487
+ /** The vendor's fixed name. Registering one twice is an error. */
488
+ name: string;
489
+ /** What happens to a canonical event this vendor has no binding for. */
490
+ default: ProviderDefault;
491
+ /** How this vendor spells each canonical event. */
492
+ events?: Record<string, EventBinding<Target>>;
493
+ /**
494
+ * Loads the vendor tag, at creation.
495
+ *
496
+ * **Make it idempotent.** A host that rebuilds its tracking, as
497
+ * `@tracklane/consent` does on every consent answer, creates again and
498
+ * installs again, including providers that were already there.
499
+ */
500
+ install?(): void | Promise<void>;
501
+ /** Sends one event to this vendor. Throwing here reaches `onError`, not the caller. */
502
+ track(name: Target, data: EventData, options: TrackOptions): void;
503
+ /** Absent where the vendor keeps no user of its own. */
504
+ identify?(user: UserData, traits?: Record<string, unknown>): void;
505
+ /** Absent where the vendor documents no consent command. */
506
+ consent?(command: "default" | "update", state: ConsentState): void;
507
+ }
508
+ /** Options accepted by {@link createTracking}. */
509
+ interface BrowserTrackingOptions {
510
+ /** The vendors to send every event to. Registering the same `name` twice throws. */
511
+ providers: readonly BrowserProvider[];
512
+ /**
513
+ * The one diagnostic channel. Without it the library is silent, exactly as
514
+ * a hand-written vendor call is.
515
+ */
516
+ onError?: (error: TrackingError) => void;
517
+ }
518
+ /** What {@link createTracking} returns. */
519
+ interface BrowserTracking {
520
+ /** Sends one event to every configured vendor. Never throws. */
521
+ track(name: string, data?: EventData, options?: TrackOptions): void;
522
+ /** Forwards the user to the vendors that hold one, and to nobody else. */
523
+ identify(user: UserData, traits?: Record<string, unknown>): void;
524
+ /**
525
+ * Forwards a consent declaration to every vendor that documents a command
526
+ * for it. It never decides, stores or withholds anything.
527
+ */
528
+ consent(command: "default" | "update", state: ConsentState): void;
529
+ }
530
+ /**
531
+ * Creates the browser tracking surface.
532
+ *
533
+ * Providers install eagerly, which is what pasting a vendor snippet does and
534
+ * what lets each vendor record its own initial page view. Every vendor
535
+ * shipped here queues its own commands until its script lands, so nothing is
536
+ * lost to loading and this library needs no queue of its own.
537
+ *
538
+ * @param options - The providers to send to, and an optional error channel.
539
+ * @returns The `track`, `identify` and `consent` calls.
540
+ *
541
+ * @example
542
+ * ```ts
543
+ * import { createTracking, ga4 } from 'tracklane/browser';
544
+ *
545
+ * const { track } = createTracking({ providers: [ga4('G-XXXXXXX')] });
546
+ * track('purchase', { transaction_id: 'T-1', value: 49.9, currency: 'BRL' });
547
+ * ```
548
+ */
549
+ declare function createTracking(options: BrowserTrackingOptions): BrowserTracking;
550
+ //#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
package/dist/browser.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as createTracking, i as TrackOptions, n as BrowserTracking, o as Ga4BrowserConfig, r as BrowserTrackingOptions, s as ga4, t as BrowserProvider } from "./browser-usMUxJhU.js";
2
- export { BrowserProvider, BrowserTracking, BrowserTrackingOptions, type Ga4BrowserConfig, TrackOptions, createTracking, ga4 };
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 };