@buildinams/tracking 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +267 -2
  2. package/dist/chunk-KLN5K6PR.js +6 -0
  3. package/dist/chunk-KLN5K6PR.js.map +1 -0
  4. package/dist/compatibility-Dc1JmTeG.d.ts +35 -0
  5. package/dist/consent/cookiebot/index.d.ts +5 -0
  6. package/dist/consent/cookiebot/index.js +27 -0
  7. package/dist/consent/cookiebot/index.js.map +1 -0
  8. package/dist/consent/index.d.ts +18 -0
  9. package/dist/consent/index.js +3 -0
  10. package/dist/consent/index.js.map +1 -0
  11. package/dist/consent/onetrust/index.d.ts +9 -0
  12. package/dist/consent/onetrust/index.js +35 -0
  13. package/dist/consent/onetrust/index.js.map +1 -0
  14. package/dist/consent/shopify/index.d.ts +13 -0
  15. package/dist/consent/shopify/index.js +77 -0
  16. package/dist/consent/shopify/index.js.map +1 -0
  17. package/dist/destinations/ga4/index.d.ts +16 -0
  18. package/dist/destinations/ga4/index.js +15 -0
  19. package/dist/destinations/ga4/index.js.map +1 -0
  20. package/dist/destinations/index.d.ts +9 -0
  21. package/dist/destinations/index.js +17 -0
  22. package/dist/destinations/index.js.map +1 -0
  23. package/dist/destinations/shopify/index.d.ts +12 -0
  24. package/dist/destinations/shopify/index.js +18 -0
  25. package/dist/destinations/shopify/index.js.map +1 -0
  26. package/dist/events/index.d.ts +16 -0
  27. package/dist/events/index.js +77 -0
  28. package/dist/events/index.js.map +1 -0
  29. package/dist/flow/index.d.ts +16 -0
  30. package/dist/flow/index.js +82 -0
  31. package/dist/flow/index.js.map +1 -0
  32. package/dist/page/index.d.ts +27 -0
  33. package/dist/page/index.js +56 -0
  34. package/dist/page/index.js.map +1 -0
  35. package/dist/sources/cart/index.d.ts +27 -0
  36. package/dist/sources/cart/index.js +38 -0
  37. package/dist/sources/cart/index.js.map +1 -0
  38. package/dist/sources/cart/shopify/index.d.ts +28 -0
  39. package/dist/sources/cart/shopify/index.js +16 -0
  40. package/dist/sources/cart/shopify/index.js.map +1 -0
  41. package/dist/sources/dom/index.d.ts +190 -0
  42. package/dist/sources/dom/index.js +558 -0
  43. package/dist/sources/dom/index.js.map +1 -0
  44. package/dist/sources/index.d.ts +6 -0
  45. package/dist/sources/index.js +3 -0
  46. package/dist/sources/index.js.map +1 -0
  47. package/dist/types-BfJsv8AV.d.ts +30 -0
  48. package/dist/types-DfPz7mBl.d.ts +49 -0
  49. package/docs/decisions/001-vendor-neutral-event-pipeline.md +33 -0
  50. package/docs/events.md +186 -0
  51. package/package.json +141 -5
@@ -0,0 +1,18 @@
1
+ import { IS_DEVELOPMENT } from '../../chunk-KLN5K6PR.js';
2
+
3
+ // src/destinations/shopify/shopify.ts
4
+ var shopify = () => ({
5
+ name: "shopify",
6
+ send({ name, payload }) {
7
+ const analytics = window.Shopify?.analytics;
8
+ if (analytics) analytics.publish(name, payload);
9
+ else if (IS_DEVELOPMENT)
10
+ console.warn(
11
+ `[tracking] Shopify.analytics isn't loaded; "${name}" not sent.`
12
+ );
13
+ }
14
+ });
15
+
16
+ export { shopify };
17
+ //# sourceMappingURL=index.js.map
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/destinations/shopify/shopify.ts"],"names":[],"mappings":";;;AAYO,IAAM,UAAU,OAAkC;AAAA,EACxD,IAAA,EAAM,SAAA;AAAA,EACN,IAAA,CAAK,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG;AACvB,IAAA,MAAM,SAAA,GAAa,OAAyB,OAAA,EAAS,SAAA;AACrD,IAAA,IAAI,SAAA,EAAW,SAAA,CAAU,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,SAAA,IACrC,cAAA;AACR,MAAA,OAAA,CAAQ,IAAA;AAAA,QACP,+CAA+C,IAAI,CAAA,WAAA;AAAA,OACpD;AAAA,EACF;AACD,CAAA","file":"index.js","sourcesContent":["import { IS_DEVELOPMENT } from \"../../config\";\nimport type { Destination } from \"..\";\n\nexport type ShopifyEvent = { name: string; payload: Record<string, unknown> };\n\ntype ShopifyGlobal = {\n\tShopify?: {\n\t\tanalytics?: { publish(name: string, payload: unknown): void };\n\t};\n};\n\n/** Publishes to Shopify's analytics bus, `Shopify.analytics.publish()`. */\nexport const shopify = (): Destination<ShopifyEvent> => ({\n\tname: \"shopify\",\n\tsend({ name, payload }) {\n\t\tconst analytics = (window as ShopifyGlobal).Shopify?.analytics;\n\t\tif (analytics) analytics.publish(name, payload);\n\t\telse if (IS_DEVELOPMENT)\n\t\t\tconsole.warn(\n\t\t\t\t`[tracking] Shopify.analytics isn't loaded; \"${name}\" not sent.`,\n\t\t\t);\n\t},\n});\n"]}
@@ -0,0 +1,16 @@
1
+ export { C as CheckPublished, R as RequireCompatible } from '../compatibility-Dc1JmTeG.js';
2
+ import { C as Catalog, E as EventBroker, S as Shape } from '../types-DfPz7mBl.js';
3
+ export { B as BrokerEvents, c as CatalogEntry, d as Composition, b as EventData, e as EventMeta, a as EventName, f as SubscribeOptions, T as TrackingEvent } from '../types-DfPz7mBl.js';
4
+
5
+ type EventBrokerOptions<Cx> = {
6
+ /** Read on every publish; its return type is the Events' Context. */
7
+ context?: () => Cx;
8
+ /** Events held while nobody asked for replay; past it the oldest are dropped. */
9
+ limit?: number;
10
+ };
11
+ declare const createEventBroker: <C extends Catalog, Cx = undefined>(events: C, { context, limit }?: EventBrokerOptions<Cx>) => EventBroker<C, Cx>;
12
+
13
+ /** Declares a type in the Event Catalog; holds nothing at runtime. */
14
+ declare const shape: <T>() => Shape<T>;
15
+
16
+ export { Catalog, EventBroker, type EventBrokerOptions, Shape, createEventBroker, shape };
@@ -0,0 +1,77 @@
1
+ import { IS_DEVELOPMENT } from '../chunk-KLN5K6PR.js';
2
+
3
+ // src/events/create-event-broker.ts
4
+ var createId = () => globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
5
+ var createEventBroker = (events, { context, limit = 100 } = {}) => {
6
+ const listeners = /* @__PURE__ */ new Set();
7
+ const held = [];
8
+ const queue = [];
9
+ let replaying = 0;
10
+ let seq = 0;
11
+ let delivering = false;
12
+ const call = (listener, event) => {
13
+ try {
14
+ listener(event);
15
+ } catch (error) {
16
+ if (IS_DEVELOPMENT) console.error(error);
17
+ }
18
+ };
19
+ const drain = () => {
20
+ if (delivering) return;
21
+ delivering = true;
22
+ try {
23
+ for (let next = queue.shift(); next; next = queue.shift())
24
+ for (const listener of next.to) call(listener, next.event);
25
+ } finally {
26
+ delivering = false;
27
+ }
28
+ };
29
+ return {
30
+ events,
31
+ publish(name, data, composed) {
32
+ if (typeof window === "undefined") return;
33
+ const event = Object.freeze({
34
+ name,
35
+ data,
36
+ composed: Object.freeze({ ...composed }),
37
+ context: context && Object.freeze(context()),
38
+ meta: Object.freeze({
39
+ id: createId(),
40
+ timestamp: Date.now(),
41
+ seq: ++seq
42
+ })
43
+ });
44
+ if (!replaying) {
45
+ held.push(event);
46
+ if (held.length > limit) {
47
+ const [dropped] = held.splice(0, held.length - limit);
48
+ if (IS_DEVELOPMENT)
49
+ console.warn(
50
+ `[tracking] More than ${limit} Events held for replay; dropped "${dropped?.name}".`
51
+ );
52
+ }
53
+ }
54
+ queue.push({ event, to: [...listeners] });
55
+ drain();
56
+ },
57
+ subscribe(listener, { replay = false } = {}) {
58
+ if (replay) {
59
+ replaying++;
60
+ for (const event of held.splice(0))
61
+ queue.push({ event, to: [listener] });
62
+ }
63
+ listeners.add(listener);
64
+ drain();
65
+ return () => {
66
+ if (listeners.delete(listener) && replay) replaying--;
67
+ };
68
+ }
69
+ };
70
+ };
71
+
72
+ // src/events/shape.ts
73
+ var shape = () => ({});
74
+
75
+ export { createEventBroker, shape };
76
+ //# sourceMappingURL=index.js.map
77
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/events/create-event-broker.ts","../../src/events/sh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A;AAChC,UAAA,KAAA,CAAM,KAAK,EAAE,KAAA,EAAO,IAAI,CAAC,QAAQ,GAAG,CAAA;AAAA,MACtC;AACA,MAAA,SAAA,CAAU,IAAI,QAAQ,CAAA;AACtB,MAAA,KAAA,EAAM;AACN,MAAA,OAAO,MAAM;AACZ,QAAA,IAAI,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA,IAAK,MAAA,EAAQ,SAAA,EAAA;AAAA,MAC3C,CAAA;AAAA,IACD;AAAA,GACD;AACD;;;AChGO,IAAM,KAAA,GAAQ,OAAoB,EAAC","file":"index.js","sourcesContent":["import { IS_DEVELOPMENT } from \"../config\";\nimport type {\n\tBrokerEvents,\n\tCatalog,\n\tEventBroker,\n\tEventName,\n\tTrackingEvent,\n} from \"./types\";\n\nexport type EventBrokerOptions<Cx> = {\n\t/** Read on every publish; its return type is the Events' Context. */\n\tcontext?: () => Cx;\n\t/** Events held while nobody asked for replay; past it the oldest are dropped. */\n\tlimit?: number;\n};\n\nconst createId = () =>\n\tglobalThis.crypto?.randomUUID?.() ??\n\t`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;\n\nexport const createEventBroker = <C extends Catalog, Cx = undefined>(\n\tevents: C,\n\t{ context, limit = 100 }: EventBrokerOptions<Cx> = {},\n): EventBroker<C, Cx> => {\n\ttype BrokerEvent = TrackingEvent<C, EventName<C>, Cx>;\n\ttype Listener = (event: BrokerEvent) => void;\n\n\tconst listeners = new Set<Listener>();\n\tconst held: BrokerEvent[] = [];\n\tconst queue: { event: BrokerEvent; to: Iterable<Listener> }[] = [];\n\tlet replaying = 0;\n\tlet seq = 0;\n\tlet delivering = false;\n\n\tconst call = (listener: Listener, event: BrokerEvent) => {\n\t\ttry {\n\t\t\tlistener(event);\n\t\t} catch (error) {\n\t\t\tif (IS_DEVELOPMENT) console.error(error);\n\t\t}\n\t};\n\n\t// Delivered from a loop rather than recursively, so an Event published by a listener still arrives after the one being delivered.\n\tconst drain = () => {\n\t\tif (delivering) return;\n\t\tdelivering = true;\n\t\ttry {\n\t\t\tfor (let next = queue.shift(); next; next = queue.shift())\n\t\t\t\tfor (const listener of next.to) call(listener, next.event);\n\t\t} finally {\n\t\t\tdelivering = false;\n\t\t}\n\t};\n\n\treturn {\n\t\tevents: events as BrokerEvents<C, Cx>,\n\n\t\tpublish(name, data, composed) {\n\t\t\tif (typeof window === \"undefined\") return;\n\n\t\t\tconst event = Object.freeze({\n\t\t\t\tname,\n\t\t\t\tdata,\n\t\t\t\tcomposed: Object.freeze({ ...composed }),\n\t\t\t\tcontext: context && Object.freeze(context()),\n\t\t\t\tmeta: Object.freeze({\n\t\t\t\t\tid: createId(),\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\tseq: ++seq,\n\t\t\t\t}),\n\t\t\t}) as unknown as BrokerEvent;\n\n\t\t\tif (!replaying) {\n\t\t\t\theld.push(event);\n\t\t\t\tif (held.length > limit) {\n\t\t\t\t\tconst [dropped] = held.splice(0, held.length - limit);\n\t\t\t\t\tif (IS_DEVELOPMENT)\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`[tracking] More than ${limit} Events held for replay; dropped \"${dropped?.name}\".`,\n\t\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tqueue.push({ event, to: [...listeners] });\n\t\t\tdrain();\n\t\t},\n\n\t\tsubscribe(listener, { replay = false } = {}) {\n\t\t\tif (replay) {\n\t\t\t\treplaying++;\n\t\t\t\tfor (const event of held.splice(0))\n\t\t\t\t\tqueue.push({ event, to: [listener] });\n\t\t\t}\n\t\t\tlisteners.add(listener);\n\t\t\tdrain();\n\t\t\treturn () => {\n\t\t\t\tif (listeners.delete(listener) && replay) replaying--;\n\t\t\t};\n\t\t},\n\t};\n};\n","import type { Shape } from \"./types\";\n\n/** Declares a type in the Event Catalog; holds nothing at runtime. */\nexport const shape = <T>(): Shape<T> => ({});\n"]}
@@ -0,0 +1,16 @@
1
+ import { ConsentSink, ConsentProvider } from '../consent/index.js';
2
+ import { C as Catalog, E as EventBroker } from '../types-DfPz7mBl.js';
3
+ import { D as Destinations } from '../types-BfJsv8AV.js';
4
+ import { Source } from '../sources/index.js';
5
+
6
+ type TrackingOptions = {
7
+ /** Started with the Flow and stopped with it. */
8
+ sources?: Source[];
9
+ /** Told every consent answer before Destinations receive Events under it. */
10
+ consentSinks?: ConsentSink[];
11
+ /** Events held per Destination while consent is unanswered. */
12
+ limit?: number;
13
+ };
14
+ declare const startTracking: <C extends Catalog, Cx>(broker: EventBroker<C, Cx>, consentProvider: ConsentProvider, destinations: Destinations<C, Cx>, { sources, consentSinks, limit }?: TrackingOptions) => (() => void);
15
+
16
+ export { type TrackingOptions, startTracking };
@@ -0,0 +1,82 @@
1
+ import { IS_DEVELOPMENT } from '../chunk-KLN5K6PR.js';
2
+
3
+ // src/flow/start-tracking.ts
4
+ var CURRENT_FLOW = Symbol.for("@buildinams/tracking/flow");
5
+ var isAllowed = (destination, consent) => {
6
+ if (destination.requires === "none") return true;
7
+ if (!consent) return void 0;
8
+ return destination.requires.every((category) => consent[category]);
9
+ };
10
+ var reportFailure = (kind, name, error) => {
11
+ if (IS_DEVELOPMENT)
12
+ console.error(`[tracking] ${kind} "${name}" failed`, error);
13
+ };
14
+ var send = (destination, event) => {
15
+ try {
16
+ const result = destination.deliver(event);
17
+ if (result instanceof Promise)
18
+ result.catch(
19
+ (error) => reportFailure("Destination", destination.name, error)
20
+ );
21
+ } catch (error) {
22
+ reportFailure("Destination", destination.name, error);
23
+ }
24
+ };
25
+ var startTracking = (broker, consentProvider, destinations, { sources = [], consentSinks = [], limit = 100 } = {}) => {
26
+ if (typeof window === "undefined") return () => {
27
+ };
28
+ const flowGlobal = globalThis;
29
+ flowGlobal[CURRENT_FLOW]?.();
30
+ const held = new Map(destinations.mapped.map((destination) => [destination, []]));
31
+ const sinks = consentSinks.filter(
32
+ (sink) => sink.name !== consentProvider.name
33
+ );
34
+ const applyConsent = (answer) => {
35
+ if (!answer) return;
36
+ for (const sink of sinks) {
37
+ try {
38
+ sink.apply(answer);
39
+ } catch (error) {
40
+ reportFailure("Consent sink", sink.name, error);
41
+ }
42
+ }
43
+ };
44
+ let consent = consentProvider.get();
45
+ applyConsent(consent);
46
+ const unsubscribeConsent = consentProvider.subscribe((next) => {
47
+ consent = next;
48
+ applyConsent(consent);
49
+ for (const [destination, events] of held) {
50
+ const allowed = isAllowed(destination, consent);
51
+ if (allowed === void 0) continue;
52
+ const pending = events.splice(0);
53
+ if (allowed) for (const event of pending) send(destination, event);
54
+ }
55
+ });
56
+ const unsubscribeBroker = broker.subscribe(
57
+ (event) => {
58
+ for (const [destination, events] of held) {
59
+ const allowed = isAllowed(destination, consent);
60
+ if (allowed) send(destination, event);
61
+ else if (allowed === void 0) {
62
+ events.push(event);
63
+ if (events.length > limit) events.shift();
64
+ }
65
+ }
66
+ },
67
+ { replay: true }
68
+ );
69
+ const stopSources = sources.map((source) => source.start());
70
+ const stop = () => {
71
+ unsubscribeBroker();
72
+ unsubscribeConsent();
73
+ for (const stopSource of stopSources) stopSource();
74
+ if (flowGlobal[CURRENT_FLOW] === stop) delete flowGlobal[CURRENT_FLOW];
75
+ };
76
+ flowGlobal[CURRENT_FLOW] = stop;
77
+ return stop;
78
+ };
79
+
80
+ export { startTracking };
81
+ //# sourceMappingURL=index.js.map
82
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/flow/start-tracking.ts"],"names":[],"mappings":";;;AAeA,IAAM,YAAA,GAAe,MAAA,CAAO,GAAA,CAAI,2BAA2B,CAAA;AAM3D,IAAM,SAAA,GAAY,CAAC,WAAA,EAA8B,OAAA,KAA4B;AAC5E,EAAA,IAAI,WAAA,CAAY,QAAA,KAAa,MAAA,EAAQ,OAAO,IAAA;AAC5C,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,OAAO,YAAY,QAAA,CAAS,KAAA,CAAM,CAAC,QAAA,KAAa,OAAA,CAAQ,QAAQ,C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AW;AAC/B,UAAA,MAAA,CAAO,KAAK,KAAK,CAAA;AACjB,UAAA,IAAI,MAAA,CAAO,MAAA,GAAS,KAAA,EAAO,MAAA,CAAO,KAAA,EAAM;AAAA,QACzC;AAAA,MACD;AAAA,IACD,CAAA;AAAA,IACA,EAAE,QAAQ,IAAA;AAAK,GAChB;AAEA,EAAA,MAAM,cAAc,OAAA,CAAQ,GAAA,CAAI,CAAC,MAAA,KAAW,MAAA,CAAO,OAAO,CAAA;AAE1D,EAAA,MAAM,OAAO,MAAM;AAClB,IAAA,iBAAA,EAAkB;AAClB,IAAA,kBAAA,EAAmB;AACnB,IAAA,KAAA,MAAW,UAAA,IAAc,aAAa,UAAA,EAAW;AACjD,IAAA,IAAI,WAAW,YAAY,CAAA,KAAM,IAAA,EAAM,OAAO,WAAW,YAAY,CAAA;AAAA,EACtE,CAAA;AACA,EAAA,UAAA,CAAW,YAAY,CAAA,GAAI,IAAA;AAC3B,EAAA,OAAO,IAAA;AACR","file":"index.js","sourcesContent":["import { IS_DEVELOPMENT } from \"../config\";\nimport type { Consent, ConsentProvider, ConsentSink } from \"../consent\";\nimport type { Destinations, MappedDestination } from \"../destinations\";\nimport type { Catalog, EventBroker, EventName, TrackingEvent } from \"../events\";\nimport type { Source } from \"../sources\";\n\nexport type TrackingOptions = {\n\t/** Started with the Flow and stopped with it. */\n\tsources?: Source[];\n\t/** Told every consent answer before Destinations receive Events under it. */\n\tconsentSinks?: ConsentSink[];\n\t/** Events held per Destination while consent is unanswered. */\n\tlimit?: number;\n};\n\nconst CURRENT_FLOW = Symbol.for(\"@buildinams/tracking/flow\");\n\ntype FlowGlobal = { [CURRENT_FLOW]?: () => void };\n\ntype DestinationInfo = Pick<MappedDestination<Catalog>, \"name\" | \"requires\">;\n\nconst isAllowed = (destination: DestinationInfo, consent: Consent | null) => {\n\tif (destination.requires === \"none\") return true;\n\tif (!consent) return undefined;\n\treturn destination.requires.every((category) => consent[category]);\n};\n\nconst reportFailure = (\n\tkind: \"Destination\" | \"Consent sink\",\n\tname: string,\n\terror: unknown,\n) => {\n\tif (IS_DEVELOPMENT)\n\t\tconsole.error(`[tracking] ${kind} \"${name}\" failed`, error);\n};\n\nconst send = <C extends Catalog, Cx>(\n\tdestination: MappedDestination<C, Cx>,\n\tevent: TrackingEvent<C, EventName<C>, Cx>,\n) => {\n\ttry {\n\t\tconst result = destination.deliver(event);\n\t\tif (result instanceof Promise)\n\t\t\tresult.catch((error: unknown) =>\n\t\t\t\treportFailure(\"Destination\", destination.name, error),\n\t\t\t);\n\t} catch (error) {\n\t\treportFailure(\"Destination\", destination.name, error);\n\t}\n};\n\nexport const startTracking = <C extends Catalog, Cx>(\n\tbroker: EventBroker<C, Cx>,\n\tconsentProvider: ConsentProvider,\n\tdestinations: Destinations<C, Cx>,\n\t{ sources = [], consentSinks = [], limit = 100 }: TrackingOptions = {},\n): (() => void) => {\n\tif (typeof window === \"undefined\") return () => {};\n\n\t// A module re-run by HMR starts a new Flow; the previous one must stop or every Event is sent twice.\n\tconst flowGlobal = globalThis as FlowGlobal;\n\tflowGlobal[CURRENT_FLOW]?.();\n\n\tconst held = new Map<\n\t\tMappedDestination<C, Cx>,\n\t\tTrackingEvent<C, EventName<C>, Cx>[]\n\t>(destinations.mapped.map((destination) => [destination, []]));\n\tconst sinks = consentSinks.filter(\n\t\t(sink) => sink.name !== consentProvider.name,\n\t);\n\tconst applyConsent = (answer: Consent | null) => {\n\t\tif (!answer) return;\n\t\tfor (const sink of sinks) {\n\t\t\ttry {\n\t\t\t\tsink.apply(answer);\n\t\t\t} catch (error) {\n\t\t\t\treportFailure(\"Consent sink\", sink.name, error);\n\t\t\t}\n\t\t}\n\t};\n\n\tlet consent = consentProvider.get();\n\tapplyConsent(consent);\n\n\tconst unsubscribeConsent = consentProvider.subscribe((next) => {\n\t\tconsent = next;\n\t\tapplyConsent(consent);\n\t\tfor (const [destination, events] of held) {\n\t\t\tconst allowed = isAllowed(destination, consent);\n\t\t\tif (allowed === undefined) continue;\n\t\t\tconst pending = events.splice(0);\n\t\t\tif (allowed) for (const event of pending) send(destination, event);\n\t\t}\n\t});\n\n\tconst unsubscribeBroker = broker.subscribe(\n\t\t(event) => {\n\t\t\tfor (const [destination, events] of held) {\n\t\t\t\tconst allowed = isAllowed(destination, consent);\n\t\t\t\tif (allowed) send(destination, event);\n\t\t\t\telse if (allowed === undefined) {\n\t\t\t\t\tevents.push(event);\n\t\t\t\t\tif (events.length > limit) events.shift();\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t{ replay: true },\n\t);\n\n\tconst stopSources = sources.map((source) => source.start());\n\n\tconst stop = () => {\n\t\tunsubscribeBroker();\n\t\tunsubscribeConsent();\n\t\tfor (const stopSource of stopSources) stopSource();\n\t\tif (flowGlobal[CURRENT_FLOW] === stop) delete flowGlobal[CURRENT_FLOW];\n\t};\n\tflowGlobal[CURRENT_FLOW] = stop;\n\treturn stop;\n};\n"]}
@@ -0,0 +1,27 @@
1
+ type PageFacts = {
2
+ url: string;
3
+ path: string;
4
+ title: string;
5
+ referrer: string;
6
+ language: string;
7
+ };
8
+ type PageListener = {
9
+ /** The Page is ending; still the current one. */
10
+ leave?(): void;
11
+ /** The next Page has started. */
12
+ enter?(): void;
13
+ };
14
+ type CurrentPage = {
15
+ read(): PageFacts;
16
+ /** Starts the next Page if the URL's key changed since the last call; call it after every client-side navigation. */
17
+ sync(): void;
18
+ /** Every listener's `leave()` runs before the Page changes, every `enter()` after. */
19
+ subscribe(listener: PageListener): () => void;
20
+ };
21
+ type CurrentPageOptions = {
22
+ /** What makes a URL another Page; by default its pathname, so query and hash changes aren't. */
23
+ key?: (url: URL) => string;
24
+ };
25
+ declare const createCurrentPage: ({ key, }?: CurrentPageOptions) => CurrentPage;
26
+
27
+ export { type CurrentPage, type CurrentPageOptions, type PageFacts, type PageListener, createCurrentPage };
@@ -0,0 +1,56 @@
1
+ import { IS_DEVELOPMENT } from '../chunk-KLN5K6PR.js';
2
+
3
+ // src/page/create-current-page.ts
4
+ var createCurrentPage = ({
5
+ key = (url) => url.pathname
6
+ } = {}) => {
7
+ const listeners = /* @__PURE__ */ new Set();
8
+ const notify = (step, subscribed) => {
9
+ for (const listener of subscribed) {
10
+ try {
11
+ listener[step]?.();
12
+ } catch (error) {
13
+ if (IS_DEVELOPMENT) console.error(error);
14
+ }
15
+ }
16
+ };
17
+ let page;
18
+ const current = () => page ??= {
19
+ key: key(new URL(location.href)),
20
+ url: location.href,
21
+ referrer: document.referrer
22
+ };
23
+ if (typeof window !== "undefined") current();
24
+ return {
25
+ read: () => ({
26
+ url: location.href,
27
+ path: location.pathname,
28
+ title: document.title,
29
+ referrer: current().referrer,
30
+ language: document.documentElement.lang || navigator.language
31
+ }),
32
+ sync() {
33
+ if (typeof window === "undefined") return;
34
+ const previous = current();
35
+ const next = key(new URL(location.href));
36
+ if (next === previous.key) {
37
+ previous.url = location.href;
38
+ return;
39
+ }
40
+ const subscribed = [...listeners];
41
+ notify("leave", subscribed);
42
+ page = { key: next, url: location.href, referrer: previous.url };
43
+ notify("enter", subscribed);
44
+ },
45
+ subscribe(listener) {
46
+ listeners.add(listener);
47
+ return () => {
48
+ listeners.delete(listener);
49
+ };
50
+ }
51
+ };
52
+ };
53
+
54
+ export { createCurrentPage };
55
+ //# sourceMappingURL=index.js.map
56
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/page/create-current-page.ts"],"names":[],"mappings":";;;AA8BO,IAAM,oBAAoB,CAAC;AAAA,EACjC,GAAA,GAAM,CAAC,GAAA,KAAQ,GAAA,CAAI;AACpB,CAAA,GAAwB,EAAC,KAAmB;AAC3C,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAkB;AACxC,EAAA,MAAM,MAAA,GAAS,CAAC,IAAA,EAAyB,UAAA,KAA+B;AACvE,IAAA,KAAA,MAAW,YAAY,UAAA,EAAY;AAClC,MAAA,IAAI;AACH,QAAA,QAAA,CAAS,IAAI,CAAA,IAAI;AAAA,MAClB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,SAAS,UAAU,CAAA;AAAA,IAC3B,CAAA;AAAA,IACA,UAAU,QAAA,EAAU;AACnB,MAAA,SAAA,CAAU,IAAI,QAAQ,CAAA;AACtB,MAAA,OAAO,MAAM;AACZ,QAAA,SAAA,CAAU,OAAO,QAAQ,CAAA;AAAA,MAC1B,CAAA;AAAA,IACD;AAAA,GACD;AACD","file":"index.js","sourcesContent":["import { IS_DEVELOPMENT } from \"../config\";\n\nexport type PageFacts = {\n\turl: string;\n\tpath: string;\n\ttitle: string;\n\treferrer: string;\n\tlanguage: string;\n};\n\nexport type PageListener = {\n\t/** The Page is ending; still the current one. */\n\tleave?(): void;\n\t/** The next Page has started. */\n\tenter?(): void;\n};\n\nexport type CurrentPage = {\n\tread(): PageFacts;\n\t/** Starts the next Page if the URL's key changed since the last call; call it after every client-side navigation. */\n\tsync(): void;\n\t/** Every listener's `leave()` runs before the Page changes, every `enter()` after. */\n\tsubscribe(listener: PageListener): () => void;\n};\n\nexport type CurrentPageOptions = {\n\t/** What makes a URL another Page; by default its pathname, so query and hash changes aren't. */\n\tkey?: (url: URL) => string;\n};\n\nexport const createCurrentPage = ({\n\tkey = (url) => url.pathname,\n}: CurrentPageOptions = {}): CurrentPage => {\n\tconst listeners = new Set<PageListener>();\n\tconst notify = (step: \"leave\" | \"enter\", subscribed: PageListener[]) => {\n\t\tfor (const listener of subscribed) {\n\t\t\ttry {\n\t\t\t\tlistener[step]?.();\n\t\t\t} catch (error) {\n\t\t\t\tif (IS_DEVELOPMENT) console.error(error);\n\t\t\t}\n\t\t}\n\t};\n\tlet page: { key: string; url: string; referrer: string } | undefined;\n\n\tconst current = () =>\n\t\t(page ??= {\n\t\t\tkey: key(new URL(location.href)),\n\t\t\turl: location.href,\n\t\t\treferrer: document.referrer,\n\t\t});\n\t// The URL it was created on is the first Page, even if the first `sync()` comes after a navigation.\n\tif (typeof window !== \"undefined\") current();\n\n\treturn {\n\t\tread: () => ({\n\t\t\turl: location.href,\n\t\t\tpath: location.pathname,\n\t\t\ttitle: document.title,\n\t\t\treferrer: current().referrer,\n\t\t\tlanguage: document.documentElement.lang || navigator.language,\n\t\t}),\n\t\tsync() {\n\t\t\tif (typeof window === \"undefined\") return;\n\t\t\tconst previous = current();\n\t\t\tconst next = key(new URL(location.href));\n\t\t\tif (next === previous.key) {\n\t\t\t\tprevious.url = location.href;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst subscribed = [...listeners];\n\t\t\tnotify(\"leave\", subscribed);\n\t\t\tpage = { key: next, url: location.href, referrer: previous.url };\n\t\t\tnotify(\"enter\", subscribed);\n\t\t},\n\t\tsubscribe(listener) {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t};\n};\n"]}
@@ -0,0 +1,27 @@
1
+ import { R as RequireCompatible } from '../../compatibility-Dc1JmTeG.js';
2
+ import { C as Catalog, c as CatalogEntry, E as EventBroker } from '../../types-DfPz7mBl.js';
3
+ import { Source } from '../index.js';
4
+
5
+ type CartChange<Line> = {
6
+ line: Line;
7
+ quantity: number;
8
+ };
9
+ /** How the Cart Source reads a cart; see `shopifyCart()` in `/sources/cart/shopify`. */
10
+ type CartAdapter<Cart, Line> = {
11
+ lines(cart: Cart): readonly Line[];
12
+ /** Identifies a line across Snapshots; lines sharing a key are summed, and a changed key is a remove plus an add. */
13
+ key(line: Line): string;
14
+ quantity(line: Line): number;
15
+ };
16
+ type CartPublished<Line> = {
17
+ "cart:add": CartChange<Line>;
18
+ "cart:remove": CartChange<Line>;
19
+ };
20
+ type CartSource<Cart> = Source & {
21
+ /** `null` or `undefined` while the cart isn't loaded; ignored. */
22
+ setSnapshot(cart: Cart | null | undefined): void;
23
+ };
24
+ type CartCatalog = Catalog & Record<"cart:add" | "cart:remove", CatalogEntry>;
25
+ declare const createCartSource: <C extends CartCatalog, Cart, Line>(broker: EventBroker<C>, { lines, key, quantity, }: CartAdapter<Cart, Line> & RequireCompatible<C, CartPublished<Line>>) => CartSource<Cart>;
26
+
27
+ export { type CartAdapter, type CartChange, type CartSource, createCartSource };
@@ -0,0 +1,38 @@
1
+ // src/sources/cart/create-cart-source.ts
2
+ var createCartSource = (broker, {
3
+ lines,
4
+ key,
5
+ quantity
6
+ }) => {
7
+ let previous;
8
+ const publish = broker.publish;
9
+ return {
10
+ start: () => () => {
11
+ },
12
+ setSnapshot(cart) {
13
+ if (cart == null) return;
14
+ const next = /* @__PURE__ */ new Map();
15
+ for (const line of lines(cart)) {
16
+ const id = key(line);
17
+ next.set(id, {
18
+ line,
19
+ total: (next.get(id)?.total ?? 0) + quantity(line)
20
+ });
21
+ }
22
+ if (previous) {
23
+ for (const [id, { line, total }] of previous)
24
+ if (!next.has(id)) publish("cart:remove", { line, quantity: total });
25
+ for (const [id, { line, total }] of next) {
26
+ const delta = total - (previous.get(id)?.total ?? 0);
27
+ if (delta > 0) publish("cart:add", { line, quantity: delta });
28
+ if (delta < 0) publish("cart:remove", { line, quantity: -delta });
29
+ }
30
+ }
31
+ previous = next;
32
+ }
33
+ };
34
+ };
35
+
36
+ export { createCartSource };
37
+ //# sourceMappingURL=index.js.map
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/sources/cart/create-cart-source.ts"],"names":[],"mappings":";AA8BO,IAAM,gBAAA,GAAmB,CAC/B,MAAA,EACA;AAAA,EACC,KAAA;AAAA,EACA,GAAA;AAAA,EACA;AACD,CAAA,KACsB;AACtB,EAAA,IAAI,QAAA;AACJ,EAAA,MAAM,UAAU,MAAA,CAAO,OAAA;AAKvB,EAAA,OAAO;AAAA,IACN,KAAA,EAAO,MAAM,MAAM;AAAA,IAAC,CAAA;AAAA,IACpB,YAAY,IAAA,EAAM;AACjB,MAAA,IAAI,QAAQ,IAAA,EAAM;AAElB,MAAA,MAAM,IAAA,uBAAW,GAAA,EAA2C;AAC5D,MAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,CAAM,IAAI,CAAA,EAAG;AAC/B,QAAA,MAAM,EAAA,GAAK,IAAI,IAAI,CAAA;AACnB,QAAA,IAAA,CAAK,IAAI,EAAA,EAAI;AAAA,UACZ,IAAA;AAAA,UACA,KAAA,EAAA,CAAQ,KAAK,GAAA,CAAI,EAAE,GAAG,KAAA,IAAS,CAAA,IAAK,SAAS,IAAI;AAAA,SACjD,CAAA;AAAA,MACF;AAGA,MAAA,IAAI,QAAA,EAAU;AACb,QAAA,KAAA,MAAW,CAAC,EAAA,EAAI,EAAE,IAAA,EAAM,KAAA,EAAO,CAAA,IAAK,QAAA;AACnC,UAAA,IAAI,CAAC,IAAA,CAAK,GAAA,CAAI,EAAE,CAAA,EAAG,OAAA,CAAQ,aAAA,EAAe,EAAE,IAAA,EAAM,QAAA,EAAU,KAAA,EAAO,CAAA;AACpE,QAAA,KAAA,MAAW,CAAC,EAAA,EAAI,EAAE,MAAM,KAAA,EAAO,KAAK,IAAA,EAAM;AACzC,UAAA,MAAM,QAAQ,KAAA,IAAS,QAAA,CAAS,GAAA,CAAI,EAAE,GAAG,KAAA,IAAS,CAAA,CAAA;AAClD,UAAA,IAAI,KAAA,GAAQ,GAAG,OAAA,CAAQ,UAAA,EAAY,EAAE,IAAA,EAAM,QAAA,EAAU,OAAO,CAAA;AAC5D,UAAA,IAAI,KAAA,GAAQ,GAAG,OAAA,CAAQ,aAAA,EAAe,EAAE,IAAA,EAAM,QAAA,EAAU,CAAC,KAAA,EAAO,CAAA;AAAA,QACjE;AAAA,MACD;AACA,MAAA,QAAA,GAAW,IAAA;AAAA,IACZ;AAAA,GACD;AACD","file":"index.js","sourcesContent":["import type {\n\tCatalog,\n\tCatalogEntry,\n\tEventBroker,\n\tRequireCompatible,\n} from \"../../events\";\nimport type { Source } from \"../types\";\n\nexport type CartChange<Line> = { line: Line; quantity: number };\n\n/** How the Cart Source reads a cart; see `shopifyCart()` in `/sources/cart/shopify`. */\nexport type CartAdapter<Cart, Line> = {\n\tlines(cart: Cart): readonly Line[];\n\t/** Identifies a line across Snapshots; lines sharing a key are summed, and a changed key is a remove plus an add. */\n\tkey(line: Line): string;\n\tquantity(line: Line): number;\n};\n\ntype CartPublished<Line> = {\n\t\"cart:add\": CartChange<Line>;\n\t\"cart:remove\": CartChange<Line>;\n};\n\nexport type CartSource<Cart> = Source & {\n\t/** `null` or `undefined` while the cart isn't loaded; ignored. */\n\tsetSnapshot(cart: Cart | null | undefined): void;\n};\n\ntype CartCatalog = Catalog & Record<\"cart:add\" | \"cart:remove\", CatalogEntry>;\n\nexport const createCartSource = <C extends CartCatalog, Cart, Line>(\n\tbroker: EventBroker<C>,\n\t{\n\t\tlines,\n\t\tkey,\n\t\tquantity,\n\t}: CartAdapter<Cart, Line> & RequireCompatible<C, CartPublished<Line>>,\n): CartSource<Cart> => {\n\tlet previous: Map<string, { line: Line; total: number }> | undefined;\n\tconst publish = broker.publish as (\n\t\tname: \"cart:add\" | \"cart:remove\",\n\t\tdata: CartChange<Line>,\n\t) => void;\n\n\treturn {\n\t\tstart: () => () => {},\n\t\tsetSnapshot(cart) {\n\t\t\tif (cart == null) return;\n\t\t\t// Summed per key: e.g. the same variant can sit on several lines with different attributes.\n\t\t\tconst next = new Map<string, { line: Line; total: number }>();\n\t\t\tfor (const line of lines(cart)) {\n\t\t\t\tconst id = key(line);\n\t\t\t\tnext.set(id, {\n\t\t\t\t\tline,\n\t\t\t\t\ttotal: (next.get(id)?.total ?? 0) + quantity(line),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// The first Snapshot is the cart as loaded, not something the shopper did.\n\t\t\tif (previous) {\n\t\t\t\tfor (const [id, { line, total }] of previous)\n\t\t\t\t\tif (!next.has(id)) publish(\"cart:remove\", { line, quantity: total });\n\t\t\t\tfor (const [id, { line, total }] of next) {\n\t\t\t\t\tconst delta = total - (previous.get(id)?.total ?? 0);\n\t\t\t\t\tif (delta > 0) publish(\"cart:add\", { line, quantity: delta });\n\t\t\t\t\tif (delta < 0) publish(\"cart:remove\", { line, quantity: -delta });\n\t\t\t\t}\n\t\t\t}\n\t\t\tprevious = next;\n\t\t},\n\t};\n};\n"]}
@@ -0,0 +1,28 @@
1
+ import { CartAdapter } from '../index.js';
2
+ import '../../../compatibility-Dc1JmTeG.js';
3
+ import '../../../types-DfPz7mBl.js';
4
+ import '../../index.js';
5
+
6
+ type ShopifyCartLine = {
7
+ id: string;
8
+ quantity: number;
9
+ merchandise?: {
10
+ id: string;
11
+ };
12
+ };
13
+ /** Storefront API connections and Hydrogen's flattened arrays both fit. */
14
+ type Lines<Line> = readonly Line[] | {
15
+ nodes: readonly Line[];
16
+ } | {
17
+ edges: readonly {
18
+ node: Line;
19
+ }[];
20
+ };
21
+ type ShopifyCart = {
22
+ lines?: Lines<ShopifyCartLine> | null;
23
+ };
24
+ type ShopifyCartLineOf<Cart extends ShopifyCart> = (NonNullable<Cart["lines"]> extends Lines<infer Line> ? Line : never) & ShopifyCartLine;
25
+ /** Reads Storefront API and Hydrogen carts, keying lines by variant. */
26
+ declare const shopifyCart: <Cart extends ShopifyCart = ShopifyCart>() => CartAdapter<Cart, ShopifyCartLineOf<Cart>>;
27
+
28
+ export { type ShopifyCart, type ShopifyCartLine, type ShopifyCartLineOf, shopifyCart };
@@ -0,0 +1,16 @@
1
+ // src/sources/cart/shopify/shopify-cart.ts
2
+ var shopifyCart = () => ({
3
+ lines(cart) {
4
+ const lines = cart.lines;
5
+ if (!lines) return [];
6
+ if ("nodes" in lines) return lines.nodes;
7
+ if ("edges" in lines) return lines.edges.map(({ node }) => node);
8
+ return lines;
9
+ },
10
+ key: (line) => line.merchandise?.id ?? line.id,
11
+ quantity: (line) => line.quantity
12
+ });
13
+
14
+ export { shopifyCart };
15
+ //# sourceMappingURL=index.js.map
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../src/sources/cart/shopify/shopify-cart.ts"],"names":[],"mappings":";AAwBO,IAAM,cAAc,OAEyB;AAAA,EACnD,MAAM,IAAA,EAAM;AACX,IAAA,MAAM,QAAQ,IAAA,CAAK,KAAA;AAInB,IAAA,IAAI,CAAC,KAAA,EAAO,OAAO,EAAC;AACpB,IAAA,IAAI,OAAA,IAAW,KAAA,EAAO,OAAO,KAAA,CAAM,KAAA;AACnC,IAAA,IAAI,OAAA,IAAW,KAAA,EAAO,OAAO,KAAA,CAAM,KAAA,CAAM,IAAI,CAAC,EAAE,IAAA,EAAK,KAAM,IAAI,CAAA;AAC/D,IAAA,OAAO,KAAA;AAAA,EACR,CAAA;AAAA,EACA,KAAK,CAAC,IAAA,KAAS,IAAA,CAAK,WAAA,EAAa,MAAM,IAAA,CAAK,EAAA;AAAA,EAC5C,QAAA,EAAU,CAAC,IAAA,KAAS,IAAA,CAAK;AAC1B,CAAA","file":"index.js","sourcesContent":["import type { CartAdapter } from \"..\";\n\nexport type ShopifyCartLine = {\n\tid: string;\n\tquantity: number;\n\tmerchandise?: { id: string };\n};\n\n/** Storefront API connections and Hydrogen's flattened arrays both fit. */\ntype Lines<Line> =\n\t| readonly Line[]\n\t| { nodes: readonly Line[] }\n\t| { edges: readonly { node: Line }[] };\n\nexport type ShopifyCart = { lines?: Lines<ShopifyCartLine> | null };\n\nexport type ShopifyCartLineOf<Cart extends ShopifyCart> = (NonNullable<\n\tCart[\"lines\"]\n> extends Lines<infer Line>\n\t? Line\n\t: never) &\n\tShopifyCartLine;\n\n/** Reads Storefront API and Hydrogen carts, keying lines by variant. */\nexport const shopifyCart = <\n\tCart extends ShopifyCart = ShopifyCart,\n>(): CartAdapter<Cart, ShopifyCartLineOf<Cart>> => ({\n\tlines(cart) {\n\t\tconst lines = cart.lines as\n\t\t\t| Lines<ShopifyCartLineOf<Cart>>\n\t\t\t| null\n\t\t\t| undefined;\n\t\tif (!lines) return [];\n\t\tif (\"nodes\" in lines) return lines.nodes;\n\t\tif (\"edges\" in lines) return lines.edges.map(({ node }) => node);\n\t\treturn lines;\n\t},\n\tkey: (line) => line.merchandise?.id ?? line.id,\n\tquantity: (line) => line.quantity,\n});\n"]}