@10x-media/analytics 1.0.0-beta.14 → 1.0.0-beta.16

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 (175) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +1 -1
  3. package/dist/adapters/ga4/ga4.d.ts +7 -0
  4. package/dist/adapters/ga4/ga4.js +17 -3
  5. package/dist/adapters/ga4/ga4.js.map +1 -1
  6. package/dist/adapters/plausible/plausible.d.ts +6 -0
  7. package/dist/adapters/plausible/plausible.js +6 -3
  8. package/dist/adapters/plausible/plausible.js.map +1 -1
  9. package/dist/adapters/posthog/cloud.js +20 -0
  10. package/dist/adapters/posthog/cloud.js.map +1 -0
  11. package/dist/adapters/posthog/credentials.js +20 -0
  12. package/dist/adapters/posthog/credentials.js.map +1 -0
  13. package/dist/adapters/posthog/posthog.d.ts +10 -3
  14. package/dist/adapters/posthog/posthog.js +100 -27
  15. package/dist/adapters/posthog/posthog.js.map +1 -1
  16. package/dist/adapters/posthog/projectCheck.js +56 -0
  17. package/dist/adapters/posthog/projectCheck.js.map +1 -0
  18. package/dist/adapters/umami/umami.d.ts +6 -0
  19. package/dist/adapters/umami/umami.js +3 -1
  20. package/dist/adapters/umami/umami.js.map +1 -1
  21. package/dist/capture/trackerConfig.js +29 -6
  22. package/dist/capture/trackerConfig.js.map +1 -1
  23. package/dist/capture/withoutConsent.js +91 -0
  24. package/dist/capture/withoutConsent.js.map +1 -0
  25. package/dist/core/capture.d.ts +41 -11
  26. package/dist/core/captureOptions.js +97 -8
  27. package/dist/core/captureOptions.js.map +1 -1
  28. package/dist/core/contract.d.ts +25 -0
  29. package/dist/core/contract.js.map +1 -1
  30. package/dist/core/options.d.ts +24 -2
  31. package/dist/core/options.js.map +1 -1
  32. package/dist/core/sourceOptions.js +2 -1
  33. package/dist/core/sourceOptions.js.map +1 -1
  34. package/dist/exports/adapters/contract.d.ts +3 -3
  35. package/dist/exports/adapters/ga4.d.ts +4 -4
  36. package/dist/exports/adapters/native.d.ts +5 -5
  37. package/dist/exports/adapters/plausible.d.ts +4 -4
  38. package/dist/exports/adapters/posthog.d.ts +4 -4
  39. package/dist/exports/adapters/umami.d.ts +4 -4
  40. package/dist/exports/next.d.ts +4 -4
  41. package/dist/exports/react.d.ts +3 -2
  42. package/dist/exports/site.d.ts +2 -2
  43. package/dist/exports/testing.d.ts +4 -4
  44. package/dist/exports/tracker.d.ts +3 -2
  45. package/dist/exports/types.d.ts +5 -5
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.js +2 -0
  48. package/dist/index.js.map +1 -1
  49. package/dist/native/collections/hits.js +1 -0
  50. package/dist/native/collections/hits.js.map +1 -1
  51. package/dist/native/engine/engine.js +5 -1
  52. package/dist/native/engine/engine.js.map +1 -1
  53. package/dist/native/engine/planner.js +2 -1
  54. package/dist/native/engine/planner.js.map +1 -1
  55. package/dist/native/engine/toHit.js +4 -2
  56. package/dist/native/engine/toHit.js.map +1 -1
  57. package/dist/native/ingest/endpoint.js +5 -2
  58. package/dist/native/ingest/endpoint.js.map +1 -1
  59. package/dist/native/ingest/normalizeEvent.d.ts +6 -1
  60. package/dist/native/ingest/normalizeEvent.js +17 -7
  61. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  62. package/dist/native/ingest/serverTrack.js +2 -1
  63. package/dist/native/ingest/serverTrack.js.map +1 -1
  64. package/dist/native/ingest/validate.js +3 -0
  65. package/dist/native/ingest/validate.js.map +1 -1
  66. package/dist/native/nativeAdapter.d.ts +10 -1
  67. package/dist/native/nativeAdapter.js +11 -1
  68. package/dist/native/nativeAdapter.js.map +1 -1
  69. package/dist/native/store/aggregate.js +1 -1
  70. package/dist/native/store/aggregate.js.map +1 -1
  71. package/dist/native/store/hitRow.js +3 -0
  72. package/dist/native/store/hitRow.js.map +1 -1
  73. package/dist/native/store/hits.js +3 -1
  74. package/dist/native/store/hits.js.map +1 -1
  75. package/dist/native/store/mongo/aggregatePipelines.js +10 -2
  76. package/dist/native/store/mongo/aggregatePipelines.js.map +1 -1
  77. package/dist/native/store/mongo/pipelines.js +15 -5
  78. package/dist/native/store/mongo/pipelines.js.map +1 -1
  79. package/dist/native/store/parts.js +9 -3
  80. package/dist/native/store/parts.js.map +1 -1
  81. package/dist/native/store/rawRead.js +6 -3
  82. package/dist/native/store/rawRead.js.map +1 -1
  83. package/dist/native/store/sql/aggregateSql.js +6 -2
  84. package/dist/native/store/sql/aggregateSql.js.map +1 -1
  85. package/dist/native/store/sql/columns.js +1 -0
  86. package/dist/native/store/sql/columns.js.map +1 -1
  87. package/dist/native/store/sql/compile.js +19 -7
  88. package/dist/native/store/sql/compile.js.map +1 -1
  89. package/dist/native/store/types.d.ts +7 -1
  90. package/dist/native/store/types.js +10 -0
  91. package/dist/native/store/types.js.map +1 -0
  92. package/dist/plugin/createRuntime.js +10 -1
  93. package/dist/plugin/createRuntime.js.map +1 -1
  94. package/dist/plugin/runtime.js.map +1 -1
  95. package/dist/providers/collection.d.ts +2 -0
  96. package/dist/providers/collection.js +36 -9
  97. package/dist/providers/collection.js.map +1 -1
  98. package/dist/providers/factory.d.ts +9 -1
  99. package/dist/providers/factory.js +14 -5
  100. package/dist/providers/factory.js.map +1 -1
  101. package/dist/providers/hosts.js +14 -6
  102. package/dist/providers/hosts.js.map +1 -1
  103. package/dist/providers/registry.js +2 -1
  104. package/dist/providers/registry.js.map +1 -1
  105. package/dist/react/AnalyticsProvider.d.ts +6 -0
  106. package/dist/react/AnalyticsProvider.js.map +1 -1
  107. package/dist/react/useAnalytics.js +9 -5
  108. package/dist/react/useAnalytics.js.map +1 -1
  109. package/dist/site/AnalyticsScripts.d.ts +4 -3
  110. package/dist/site/AnalyticsScripts.js +18 -4
  111. package/dist/site/AnalyticsScripts.js.map +1 -1
  112. package/dist/surfacing/todaySplit.js +7 -1
  113. package/dist/surfacing/todaySplit.js.map +1 -1
  114. package/dist/tracker/config.d.ts +26 -1
  115. package/dist/tracker/config.js.map +1 -1
  116. package/dist/tracker/createTracker.d.ts +2 -1
  117. package/dist/tracker/createTracker.js +91 -59
  118. package/dist/tracker/createTracker.js.map +1 -1
  119. package/dist/tracker/gate.d.ts +8 -0
  120. package/dist/tracker/gate.js +61 -11
  121. package/dist/tracker/gate.js.map +1 -1
  122. package/dist/tracker/loadScript.js +2 -1
  123. package/dist/tracker/loadScript.js.map +1 -1
  124. package/dist/tracker/registry.js +14 -3
  125. package/dist/tracker/registry.js.map +1 -1
  126. package/dist/tracker/sinks/createSink.js +27 -8
  127. package/dist/tracker/sinks/createSink.js.map +1 -1
  128. package/dist/tracker/sinks/ga4.js +38 -6
  129. package/dist/tracker/sinks/ga4.js.map +1 -1
  130. package/dist/tracker/sinks/native.js +17 -3
  131. package/dist/tracker/sinks/native.js.map +1 -1
  132. package/dist/tracker/sinks/plausible.js +8 -2
  133. package/dist/tracker/sinks/plausible.js.map +1 -1
  134. package/dist/tracker/sinks/posthog.js +108 -16
  135. package/dist/tracker/sinks/posthog.js.map +1 -1
  136. package/dist/tracker/sinks/umami.js +2 -2
  137. package/dist/tracker/sinks/umami.js.map +1 -1
  138. package/dist/tracker/sinks/vendor.js +25 -11
  139. package/dist/tracker/sinks/vendor.js.map +1 -1
  140. package/dist/tracker/types.d.ts +10 -3
  141. package/dist/translations/ar.js +10 -0
  142. package/dist/translations/ar.js.map +1 -1
  143. package/dist/translations/de.js +10 -0
  144. package/dist/translations/de.js.map +1 -1
  145. package/dist/translations/en.js +10 -0
  146. package/dist/translations/en.js.map +1 -1
  147. package/dist/translations/es.js +10 -0
  148. package/dist/translations/es.js.map +1 -1
  149. package/dist/translations/fr.js +10 -0
  150. package/dist/translations/fr.js.map +1 -1
  151. package/dist/translations/id.js +10 -0
  152. package/dist/translations/id.js.map +1 -1
  153. package/dist/translations/keys.d.ts +10 -0
  154. package/dist/translations/keys.js +11 -1
  155. package/dist/translations/keys.js.map +1 -1
  156. package/dist/translations/ko.js +10 -0
  157. package/dist/translations/ko.js.map +1 -1
  158. package/dist/translations/pt.js +10 -0
  159. package/dist/translations/pt.js.map +1 -1
  160. package/dist/translations/ru.js +10 -0
  161. package/dist/translations/ru.js.map +1 -1
  162. package/dist/translations/uk.js +10 -0
  163. package/dist/translations/uk.js.map +1 -1
  164. package/dist/translations/zh.js +10 -0
  165. package/dist/translations/zh.js.map +1 -1
  166. package/dist/view/consentShare.js +15 -0
  167. package/dist/view/consentShare.js.map +1 -0
  168. package/dist/view/sections/OverviewCards.js +38 -28
  169. package/dist/view/sections/OverviewCards.js.map +1 -1
  170. package/dist/widgets/notices.js +6 -1
  171. package/dist/widgets/notices.js.map +1 -1
  172. package/dist/widgets/readMeta.d.ts +4 -0
  173. package/dist/widgets/readMeta.js +5 -0
  174. package/dist/widgets/readMeta.js.map +1 -1
  175. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"gate.js","names":[],"sources":["../../src/tracker/gate.ts"],"sourcesContent":["import type { CaptureSlot, TrackerSlotConfig } from './config'\nimport { writeStorage } from './storage'\nimport type { GateState, GateStatus, TrackerEvent, TrackerWindow } from './types'\n\n/**\n * How many events one slot holds while its gate is pending before the oldest is dropped: a\n * visitor who never answers the banner must not grow the tab's memory without bound.\n */\nexport const GATE_QUEUE_LIMIT = 100\n\n/**\n * Where 1.0.0-beta.11 persisted the consent decision. The tracker deletes it once a slot opens, for\n * the whole 1.x line: a stale decision must never outlive the host's own answer.\n */\nexport const LEGACY_CONSENT_KEYS = ['analytics:consent'] as const\n\n/** Every capture slot, in slot order. Kept here because `/tracker` cannot load `capture/slots`. */\nexport const GATE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport type GateSnapshot = Readonly<Record<CaptureSlot, GateStatus>>\n\n/** The snapshot of a window with no tracker and no answer yet, and of the server render. */\nexport const ALL_PENDING: GateSnapshot = Object.freeze({ global: 'pending', tenant: 'pending' })\n\n/** Deletes beta.11's consent key. Blocked storage holds none to delete. */\nexport const forgetLegacyConsent = (win: TrackerWindow): void => {\n\tfor (const key of LEGACY_CONSENT_KEYS) {\n\t\twriteStorage(win, key, null)\n\t}\n}\n\n/** The config filling `slot`, if any. */\nexport const slotConfigOf = (\n\tslots: readonly TrackerSlotConfig[],\n\tslot: CaptureSlot\n): TrackerSlotConfig | undefined => slots.find((candidate) => candidate.slot === slot)\n\n/**\n * Whether `capture.gate` holds a slot. A config cached from 1.0.0-beta.11 carries\n * `requiresConsent` instead, and one carrying neither is held: a slot fails closed.\n */\nexport const slotIsGated = (slot: TrackerSlotConfig): boolean => {\n\tif (typeof slot.gated === 'boolean') {\n\t\treturn slot.gated\n\t}\n\tconst legacy: unknown = Reflect.get(slot, 'requiresConsent')\n\treturn typeof legacy === 'boolean' ? legacy : true\n}\n\n/**\n * What one answer says about one slot: a boolean answers for the held slots alone, a record for\n * the slots it names. Undefined leaves the slot's gate as it is.\n */\nexport const gateAnswer = (\n\tstate: GateState | undefined,\n\tslot: CaptureSlot,\n\tgated: boolean\n): boolean | undefined => {\n\tif (state === undefined) {\n\t\treturn undefined\n\t}\n\tif (typeof state === 'boolean') {\n\t\treturn gated ? state : undefined\n\t}\n\treturn state[slot]\n}\n\n/** Whether a slot's gate is open as the page boots: the server's answer, else open unless held. */\nexport const openAtBoot = (slot: TrackerSlotConfig, state: GateState | undefined): boolean => {\n\tconst gated = slotIsGated(slot)\n\treturn gateAnswer(state, slot.slot, gated) ?? !gated\n}\n\n/**\n * Adds an answer to a window's collected ones, keeping the latest boolean and each slot's latest\n * named answer: replayed in order, they settle every slot as the full history would.\n */\nexport const appendGateAnswer = (answers: readonly GateState[], state: GateState): GateState[] => {\n\tif (typeof state === 'boolean') {\n\t\treturn [...answers.filter((answer) => typeof answer !== 'boolean'), state]\n\t}\n\tconst named = GATE_SLOTS.filter((slot) => state[slot] !== undefined)\n\tconst kept = answers.filter(\n\t\t(answer) => typeof answer === 'boolean' || !named.some((slot) => answer[slot] !== undefined)\n\t)\n\treturn [...kept, ...named.map((slot) => ({ [slot]: state[slot] }))]\n}\n\n/**\n * Folds answers given in order into the one a tracker boots with, for the slots `slots` holds or\n * not: the latest answer that speaks for each slot. Undefined when none speaks for any.\n */\nexport const settleGateAnswers = (\n\tslots: readonly TrackerSlotConfig[],\n\tanswers: readonly GateState[]\n): GateState | undefined => {\n\tconst settled: Partial<Record<CaptureSlot, boolean>> = {}\n\tlet any = false\n\tfor (const slot of GATE_SLOTS) {\n\t\tconst config = slotConfigOf(slots, slot)\n\t\tconst gated = config ? slotIsGated(config) : true\n\t\tfor (const answer of answers) {\n\t\t\tconst open = gateAnswer(answer, slot, gated)\n\t\t\tif (open !== undefined) {\n\t\t\t\tsettled[slot] = open\n\t\t\t\tany = true\n\t\t\t}\n\t\t}\n\t}\n\treturn any ? settled : undefined\n}\n\n/**\n * What one slot's gate says once `answers` are replayed over it: `gated` holds it pending until an\n * answer speaks for it, and an ungated slot starts open and moves only by name.\n */\nconst replayed = (answers: readonly GateState[], slot: CaptureSlot, gated: boolean): GateStatus => {\n\tlet status: GateStatus = gated ? 'pending' : 'open'\n\tfor (const answer of answers) {\n\t\tconst open = gateAnswer(answer, slot, gated)\n\t\tif (open !== undefined) {\n\t\t\tstatus = open ? 'open' : 'closed'\n\t\t}\n\t}\n\treturn status\n}\n\n/**\n * The gate a window's answers describe, exactly a booting tracker's once `slots` is known. Before\n * that, a slot where held and ungated readings disagree is pending.\n */\nexport const answeredSnapshot = (\n\tanswers: readonly GateState[],\n\tslots?: readonly TrackerSlotConfig[]\n): GateSnapshot => {\n\tif (slots !== undefined) {\n\t\tconst gate = createGate(slots)\n\t\tfor (const answer of answers) {\n\t\t\tgate.answer(answer)\n\t\t}\n\t\treturn gate.snapshot\n\t}\n\tconst status = (slot: CaptureSlot): GateStatus => {\n\t\tconst held = replayed(answers, slot, true)\n\t\treturn held === replayed(answers, slot, false) ? held : 'pending'\n\t}\n\treturn Object.freeze({ global: status('global'), tenant: status('tenant') })\n}\n\n/**\n * What may wait in a pending slot's queue: an engagement only for a native slot, since a vendor\n * drops one, and never the items seen, which count only while a slot may receive them.\n */\nexport const queueable = (\n\tevent: TrackerEvent,\n\tkind: TrackerSlotConfig['kind']\n): TrackerEvent | null => {\n\tif (event.type === 'engagement' && kind !== 'native') {\n\t\treturn null\n\t}\n\tif (event.impressions === undefined) {\n\t\treturn event\n\t}\n\tconst { impressions: _impressions, ...rest } = event\n\treturn rest.type === 'engagement' && !rest.durationMs && !rest.scrollDepth ? null : rest\n}\n\nexport interface GateQueue<T> {\n\tpush(item: T): void\n\tdrain(): T[]\n\tclear(): void\n\treadonly size: number\n}\n\n/** Bounded FIFO buffer holding one slot's events while its gate is pending. */\nexport const createGateQueue = <T>(limit: number = GATE_QUEUE_LIMIT): GateQueue<T> => {\n\tlet items: T[] = []\n\treturn {\n\t\tpush(item) {\n\t\t\titems.push(item)\n\t\t\tif (items.length > limit) {\n\t\t\t\titems.splice(0, items.length - limit)\n\t\t\t}\n\t\t},\n\t\tdrain() {\n\t\t\tconst drained = items\n\t\t\titems = []\n\t\t\treturn drained\n\t\t},\n\t\tclear() {\n\t\t\titems = []\n\t\t},\n\t\tget size() {\n\t\t\treturn items.length\n\t\t},\n\t}\n}\n\n/** A slot an answer opened or closed, for the tracker to act on, and the status it left. */\nexport interface GateTransition {\n\tslot: CaptureSlot\n\tfrom: GateStatus\n\tto: 'open' | 'closed'\n}\n\nexport interface Gate {\n\tstatus(slot: CaptureSlot): GateStatus\n\t/** Frozen, and the same object until a slot's gate changes. */\n\treadonly snapshot: GateSnapshot\n\t/**\n\t * Applies one answer and returns the slots it moved. A slot's first explicit `true` counts as\n\t * opening even when already open, so a held-open slot clears a refusal from an earlier page.\n\t */\n\tanswer(state: GateState): GateTransition[]\n\t/** Puts every held slot back to pending and forgets its answers. Says whether one moved. */\n\treset(): boolean\n}\n\n/**\n * The gate's side-effect-free state machine: a held slot starts pending, others open, and a slot the\n * config does not fill stays closed, since no answer could make it capture anything.\n */\nexport const createGate = (slots: readonly TrackerSlotConfig[]): Gate => {\n\tconst initial = (slot: CaptureSlot): GateStatus => {\n\t\tconst config = slotConfigOf(slots, slot)\n\t\tif (config === undefined) {\n\t\t\treturn 'closed'\n\t\t}\n\t\treturn slotIsGated(config) ? 'pending' : 'open'\n\t}\n\tconst statuses: Record<CaptureSlot, GateStatus> = {\n\t\tglobal: initial('global'),\n\t\ttenant: initial('tenant'),\n\t}\n\tconst answered = new Set<CaptureSlot>()\n\tlet snapshot: GateSnapshot = Object.freeze({ ...statuses })\n\treturn {\n\t\tstatus: (slot) => statuses[slot],\n\t\tget snapshot() {\n\t\t\treturn snapshot\n\t\t},\n\t\tanswer(state) {\n\t\t\tconst moved: GateTransition[] = []\n\t\t\tlet changed = false\n\t\t\tfor (const slot of GATE_SLOTS) {\n\t\t\t\tconst config = slotConfigOf(slots, slot)\n\t\t\t\tconst open = config && gateAnswer(state, slot, slotIsGated(config))\n\t\t\t\tif (open === undefined) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst to = open ? 'open' : 'closed'\n\t\t\t\tconst from = statuses[slot]\n\t\t\t\tif (from === to && answered.has(slot)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tanswered.add(slot)\n\t\t\t\tchanged ||= from !== to\n\t\t\t\tstatuses[slot] = to\n\t\t\t\tmoved.push({ slot, from, to })\n\t\t\t}\n\t\t\tif (changed) {\n\t\t\t\tsnapshot = Object.freeze({ ...statuses })\n\t\t\t}\n\t\t\treturn moved\n\t\t},\n\t\treset() {\n\t\t\tlet changed = false\n\t\t\tfor (const slot of GATE_SLOTS) {\n\t\t\t\tconst config = slotConfigOf(slots, slot)\n\t\t\t\tif (config === undefined || !slotIsGated(config)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tanswered.delete(slot)\n\t\t\t\tchanged ||= statuses[slot] !== 'pending'\n\t\t\t\tstatuses[slot] = 'pending'\n\t\t\t}\n\t\t\tif (changed) {\n\t\t\t\tsnapshot = Object.freeze({ ...statuses })\n\t\t\t}\n\t\t\treturn changed\n\t\t},\n\t}\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AAM,QAAQ,YAAY;IAC9B,MAAM,SAAS,aAAa,OAAO,IAAI;IACvC,IAAI,WAAW,KAAA,KAAa,CAAC,YAAY,MAAM,GAC9C;IAED,SAAS,OAAO,IAAI;IACpB,YAAY,SAAS,UAAU;IAC/B,SAAS,QAAQ;GAClB;GACA,IAAI,SACH,WAAW,OAAO,OAAO,EAAE,GAAG,SAAS,CAAC;GAEzC,OAAO;EACR;CACD;AACD"}
1
+ {"version":3,"file":"gate.js","names":[],"sources":["../../src/tracker/gate.ts"],"sourcesContent":["import type { CaptureSlot, HeldSlotMode, SlotMode, TrackerSlotConfig } from './config'\nimport { writeStorage } from './storage'\nimport type { GateState, GateStatus, TrackerEvent, TrackerWindow } from './types'\n\n/**\n * How many events one slot holds while it is pending and sends nothing before the oldest is dropped:\n * a visitor who never answers the banner must not grow the tab's memory without bound.\n */\nexport const GATE_QUEUE_LIMIT = 100\n\n/**\n * Where 1.0.0-beta.11 persisted the consent decision. The tracker deletes it once a slot opens, for\n * the whole 1.x line: a stale decision must never outlive the host's own answer.\n */\nexport const LEGACY_CONSENT_KEYS = ['analytics:consent'] as const\n\n/** Every capture slot, in slot order. Kept here because `/tracker` cannot load `capture/slots`. */\nexport const GATE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport type GateSnapshot = Readonly<Record<CaptureSlot, GateStatus>>\n\n/** The snapshot of a window with no tracker and no answer yet, and of the server render. */\nexport const ALL_PENDING: GateSnapshot = Object.freeze({ global: 'pending', tenant: 'pending' })\n\n/** What each capture slot captures with, as `tracker.mode` and `useAnalytics().mode` give it. */\nexport type ModeSnapshot = Readonly<Record<CaptureSlot, SlotMode>>\n\n/** The modes of a window with no tracker config yet, and of the server render. */\nexport const ALL_OFF: ModeSnapshot = Object.freeze({ global: 'off', tenant: 'off' })\n\nconst HELD_MODES: readonly HeldSlotMode[] = ['off', 'cookieless', 'anonymous']\n\nconst isHeldMode = (value: unknown): value is HeldSlotMode =>\n\tHELD_MODES.some((mode) => mode === value)\n\n/**\n * What a slot captures with under `status`: in full once open, else its level for the phase without\n * consent. A slot the gate does not hold, and a config naming no level (cached from 1.0.0-beta.14),\n * send nothing until open.\n */\nexport const slotMode = (config: TrackerSlotConfig | undefined, status: GateStatus): SlotMode => {\n\tif (config === undefined) {\n\t\treturn 'off'\n\t}\n\tif (status === 'open') {\n\t\treturn 'full'\n\t}\n\tif (!slotIsGated(config)) {\n\t\treturn 'off'\n\t}\n\tconst level: unknown = config.withoutConsent?.[status === 'pending' ? 'pending' : 'refused']\n\treturn isHeldMode(level) ? level : 'off'\n}\n\n/** Deletes beta.11's consent key. Blocked storage holds none to delete. */\nexport const forgetLegacyConsent = (win: TrackerWindow): void => {\n\tfor (const key of LEGACY_CONSENT_KEYS) {\n\t\twriteStorage(win, key, null)\n\t}\n}\n\n/** The config filling `slot`, if any. */\nexport const slotConfigOf = (\n\tslots: readonly TrackerSlotConfig[],\n\tslot: CaptureSlot\n): TrackerSlotConfig | undefined => slots.find((candidate) => candidate.slot === slot)\n\n/**\n * Whether `capture.gate` holds a slot. A config cached from 1.0.0-beta.11 carries\n * `requiresConsent` instead, and one carrying neither is held: a slot fails closed.\n */\nexport const slotIsGated = (slot: TrackerSlotConfig): boolean => {\n\tif (typeof slot.gated === 'boolean') {\n\t\treturn slot.gated\n\t}\n\tconst legacy: unknown = Reflect.get(slot, 'requiresConsent')\n\treturn typeof legacy === 'boolean' ? legacy : true\n}\n\n/**\n * What one answer says about one slot: a boolean answers for the held slots alone, a record for\n * the slots it names. Undefined leaves the slot's gate as it is.\n */\nexport const gateAnswer = (\n\tstate: GateState | undefined,\n\tslot: CaptureSlot,\n\tgated: boolean\n): boolean | undefined => {\n\tif (state === undefined) {\n\t\treturn undefined\n\t}\n\tif (typeof state === 'boolean') {\n\t\treturn gated ? state : undefined\n\t}\n\treturn state[slot]\n}\n\n/** Whether a slot's gate is open as the page boots: the server's answer, else open unless held. */\nexport const openAtBoot = (slot: TrackerSlotConfig, state: GateState | undefined): boolean => {\n\tconst gated = slotIsGated(slot)\n\treturn gateAnswer(state, slot.slot, gated) ?? !gated\n}\n\n/**\n * Adds an answer to a window's collected ones, keeping the latest boolean and each slot's latest\n * named answer: replayed in order, they settle every slot as the full history would.\n */\nexport const appendGateAnswer = (answers: readonly GateState[], state: GateState): GateState[] => {\n\tif (typeof state === 'boolean') {\n\t\treturn [...answers.filter((answer) => typeof answer !== 'boolean'), state]\n\t}\n\tconst named = GATE_SLOTS.filter((slot) => state[slot] !== undefined)\n\tconst kept = answers.filter(\n\t\t(answer) => typeof answer === 'boolean' || !named.some((slot) => answer[slot] !== undefined)\n\t)\n\treturn [...kept, ...named.map((slot) => ({ [slot]: state[slot] }))]\n}\n\n/**\n * Folds answers given in order into the one a tracker boots with, for the slots `slots` holds or\n * not: the latest answer that speaks for each slot. Undefined when none speaks for any.\n */\nexport const settleGateAnswers = (\n\tslots: readonly TrackerSlotConfig[],\n\tanswers: readonly GateState[]\n): GateState | undefined => {\n\tconst settled: Partial<Record<CaptureSlot, boolean>> = {}\n\tlet any = false\n\tfor (const slot of GATE_SLOTS) {\n\t\tconst config = slotConfigOf(slots, slot)\n\t\tconst gated = config ? slotIsGated(config) : true\n\t\tfor (const answer of answers) {\n\t\t\tconst open = gateAnswer(answer, slot, gated)\n\t\t\tif (open !== undefined) {\n\t\t\t\tsettled[slot] = open\n\t\t\t\tany = true\n\t\t\t}\n\t\t}\n\t}\n\treturn any ? settled : undefined\n}\n\n/**\n * What one slot's gate says once `answers` are replayed over it: `gated` holds it pending until an\n * answer speaks for it, and an ungated slot starts open and moves only by name.\n */\nconst replayed = (answers: readonly GateState[], slot: CaptureSlot, gated: boolean): GateStatus => {\n\tlet status: GateStatus = gated ? 'pending' : 'open'\n\tfor (const answer of answers) {\n\t\tconst open = gateAnswer(answer, slot, gated)\n\t\tif (open !== undefined) {\n\t\t\tstatus = open ? 'open' : 'closed'\n\t\t}\n\t}\n\treturn status\n}\n\n/**\n * The gate a window's answers describe, exactly a booting tracker's once `slots` is known. Before\n * that, a slot where held and ungated readings disagree is pending.\n */\nexport const answeredSnapshot = (\n\tanswers: readonly GateState[],\n\tslots?: readonly TrackerSlotConfig[]\n): GateSnapshot => {\n\tif (slots !== undefined) {\n\t\tconst gate = createGate(slots)\n\t\tfor (const answer of answers) {\n\t\t\tgate.answer(answer)\n\t\t}\n\t\treturn gate.snapshot\n\t}\n\tconst status = (slot: CaptureSlot): GateStatus => {\n\t\tconst held = replayed(answers, slot, true)\n\t\treturn held === replayed(answers, slot, false) ? held : 'pending'\n\t}\n\treturn Object.freeze({ global: status('global'), tenant: status('tenant') })\n}\n\n/**\n * Whether a held slot counts without consent in either phase, which its snippet booted for: PostHog\n * then switches between cookieless and full rather than stopping.\n */\nexport const slotCountsWithoutConsent = (config: TrackerSlotConfig): boolean =>\n\tslotMode(config, 'pending') !== 'off' || slotMode(config, 'closed') !== 'off'\n\n/** The modes a window's answers give `slots`, exactly a booting tracker's; all off before a config. */\nexport const answeredModes = (\n\tanswers: readonly GateState[],\n\tslots?: readonly TrackerSlotConfig[]\n): ModeSnapshot => {\n\tif (slots === undefined) {\n\t\treturn ALL_OFF\n\t}\n\tconst gate = createGate(slots)\n\tfor (const answer of answers) {\n\t\tgate.answer(answer)\n\t}\n\treturn gate.modes\n}\n\n/**\n * What may wait in the queue of a slot pending and sending nothing: an engagement only for a\n * native slot, since a vendor drops one, and never the items seen, which count only while a slot\n * may receive them.\n */\nexport const queueable = (\n\tevent: TrackerEvent,\n\tkind: TrackerSlotConfig['kind']\n): TrackerEvent | null => {\n\tif (event.type === 'engagement' && kind !== 'native') {\n\t\treturn null\n\t}\n\tif (event.impressions === undefined) {\n\t\treturn event\n\t}\n\tconst { impressions: _impressions, ...rest } = event\n\treturn rest.type === 'engagement' && !rest.durationMs && !rest.scrollDepth ? null : rest\n}\n\nexport interface GateQueue<T> {\n\tpush(item: T): void\n\tdrain(): T[]\n\tclear(): void\n\treadonly size: number\n}\n\n/** Bounded FIFO buffer holding one slot's events while it is pending and sends nothing. */\nexport const createGateQueue = <T>(limit: number = GATE_QUEUE_LIMIT): GateQueue<T> => {\n\tlet items: T[] = []\n\treturn {\n\t\tpush(item) {\n\t\t\titems.push(item)\n\t\t\tif (items.length > limit) {\n\t\t\t\titems.splice(0, items.length - limit)\n\t\t\t}\n\t\t},\n\t\tdrain() {\n\t\t\tconst drained = items\n\t\t\titems = []\n\t\t\treturn drained\n\t\t},\n\t\tclear() {\n\t\t\titems = []\n\t\t},\n\t\tget size() {\n\t\t\treturn items.length\n\t\t},\n\t}\n}\n\n/** A slot an answer opened or closed, for the tracker to act on, and the status it left. */\nexport interface GateTransition {\n\tslot: CaptureSlot\n\tfrom: GateStatus\n\tto: 'open' | 'closed'\n}\n\nexport interface Gate {\n\tstatus(slot: CaptureSlot): GateStatus\n\tmode(slot: CaptureSlot): SlotMode\n\t/** Frozen, and the same object until a slot's gate changes. */\n\treadonly snapshot: GateSnapshot\n\t/** Each slot's mode. Frozen, and the same object until a slot's mode changes. */\n\treadonly modes: ModeSnapshot\n\t/**\n\t * Applies one answer and returns the slots it moved. A slot's first explicit `true` counts as\n\t * opening even when already open, so a held-open slot clears a refusal from an earlier page.\n\t */\n\tanswer(state: GateState): GateTransition[]\n\t/** Puts every held slot back to pending and forgets its answers. Says whether one moved. */\n\treset(): boolean\n}\n\n/**\n * The gate's side-effect-free state machine: a held slot starts pending, others open, and a slot the\n * config does not fill stays closed, since no answer could make it capture anything.\n */\nexport const createGate = (slots: readonly TrackerSlotConfig[]): Gate => {\n\tconst initial = (slot: CaptureSlot): GateStatus => {\n\t\tconst config = slotConfigOf(slots, slot)\n\t\tif (config === undefined) {\n\t\t\treturn 'closed'\n\t\t}\n\t\treturn slotIsGated(config) ? 'pending' : 'open'\n\t}\n\tconst statuses: Record<CaptureSlot, GateStatus> = {\n\t\tglobal: initial('global'),\n\t\ttenant: initial('tenant'),\n\t}\n\tconst answered = new Set<CaptureSlot>()\n\tconst modesOf = (): ModeSnapshot =>\n\t\tObject.freeze({\n\t\t\tglobal: slotMode(slotConfigOf(slots, 'global'), statuses.global),\n\t\t\ttenant: slotMode(slotConfigOf(slots, 'tenant'), statuses.tenant),\n\t\t})\n\tlet snapshot: GateSnapshot = Object.freeze({ ...statuses })\n\tlet modes = modesOf()\n\tconst changed = () => {\n\t\tsnapshot = Object.freeze({ ...statuses })\n\t\tconst next = modesOf()\n\t\tif (GATE_SLOTS.some((slot) => next[slot] !== modes[slot])) {\n\t\t\tmodes = next\n\t\t}\n\t}\n\treturn {\n\t\tstatus: (slot) => statuses[slot],\n\t\tmode: (slot) => modes[slot],\n\t\tget snapshot() {\n\t\t\treturn snapshot\n\t\t},\n\t\tget modes() {\n\t\t\treturn modes\n\t\t},\n\t\tanswer(state) {\n\t\t\tconst moved: GateTransition[] = []\n\t\t\tlet moving = false\n\t\t\tfor (const slot of GATE_SLOTS) {\n\t\t\t\tconst config = slotConfigOf(slots, slot)\n\t\t\t\tconst open = config && gateAnswer(state, slot, slotIsGated(config))\n\t\t\t\tif (open === undefined) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconst to = open ? 'open' : 'closed'\n\t\t\t\tconst from = statuses[slot]\n\t\t\t\tif (from === to && answered.has(slot)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tanswered.add(slot)\n\t\t\t\tmoving ||= from !== to\n\t\t\t\tstatuses[slot] = to\n\t\t\t\tmoved.push({ slot, from, to })\n\t\t\t}\n\t\t\tif (moving) {\n\t\t\t\tchanged()\n\t\t\t}\n\t\t\treturn moved\n\t\t},\n\t\treset() {\n\t\t\tlet moving = false\n\t\t\tfor (const slot of GATE_SLOTS) {\n\t\t\t\tconst config = slotConfigOf(slots, slot)\n\t\t\t\tif (config === undefined || !slotIsGated(config)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tanswered.delete(slot)\n\t\t\t\tmoving ||= statuses[slot] !== 'pending'\n\t\t\t\tstatuses[slot] = 'pending'\n\t\t\t}\n\t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IAAI;IACpB,WAAW,SAAS,UAAU;IAC9B,SAAS,QAAQ;GAClB;GACA,IAAI,QACH,QAAQ;GAET,OAAO;EACR;CACD;AACD"}
@@ -1,4 +1,5 @@
1
1
  //#region src/tracker/loadScript.ts
2
+ /** Whether the page already holds the script: the same `src`, or the same inline text. */
2
3
  const alreadyPresent = (win, script) => {
3
4
  for (const el of win.document.querySelectorAll("script")) {
4
5
  if (script.src && el.getAttribute("src") === script.src) return true;
@@ -43,6 +44,6 @@ const createScriptLoader = (win, nonce) => (script) => new Promise((resolve, rej
43
44
  win.document.head.appendChild(el);
44
45
  });
45
46
  //#endregion
46
- export { createScriptLoader };
47
+ export { alreadyPresent, createScriptLoader };
47
48
 
48
49
  //# sourceMappingURL=loadScript.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loadScript.js","names":[],"sources":["../../src/tracker/loadScript.ts"],"sourcesContent":["import type { SnippetScript } from './config'\nimport type { LoadScript, TrackerWindow } from './types'\n\nconst alreadyPresent = (win: TrackerWindow, script: SnippetScript): boolean => {\n\tfor (const el of win.document.querySelectorAll('script')) {\n\t\tif (script.src && el.getAttribute('src') === script.src) {\n\t\t\treturn true\n\t\t}\n\t\tif (script.inline && el.textContent === script.inline) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nconst scriptElement = (\n\twin: TrackerWindow,\n\tscript: SnippetScript,\n\tnonce: string | undefined\n): HTMLScriptElement => {\n\tconst el = win.document.createElement('script')\n\tfor (const [name, value] of Object.entries(script.attrs ?? {})) {\n\t\tel.setAttribute(name, value)\n\t}\n\tif (script.type) {\n\t\tel.type = script.type\n\t}\n\tif (nonce) {\n\t\tel.setAttribute('nonce', nonce)\n\t}\n\treturn el\n}\n\n/**\n * The default `loadScript`: injects a snippet script into `<head>`, resolving once it has run. A\n * script already on the page is a no-op, so booting over `AnalyticsScripts`' render loads no copy.\n */\nexport const createScriptLoader =\n\t(win: TrackerWindow, nonce?: string): LoadScript =>\n\t(script) =>\n\t\tnew Promise((resolve, reject) => {\n\t\t\tconst { src, inline } = script\n\t\t\tif (alreadyPresent(win, script)) {\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (inline) {\n\t\t\t\tconst el = scriptElement(win, script, nonce)\n\t\t\t\tel.text = inline\n\t\t\t\twin.document.head.appendChild(el)\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (!src) {\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst el = scriptElement(win, script, nonce)\n\t\t\tel.async = script.async ?? false\n\t\t\tel.defer = script.defer ?? false\n\t\t\tel.addEventListener('load', () => resolve())\n\t\t\tel.addEventListener('error', () => reject(new Error(`analytics: failed to load ${src}`)))\n\t\t\tel.src = src\n\t\t\twin.document.head.appendChild(el)\n\t\t})\n"],"mappings":";AAGA,MAAM,kBAAkB,KAAoB,WAAmC;CAC9E,KAAK,MAAM,MAAM,IAAI,SAAS,iBAAiB,QAAQ,GAAG;EACzD,IAAI,OAAO,OAAO,GAAG,aAAa,KAAK,MAAM,OAAO,KACnD,OAAO;EAER,IAAI,OAAO,UAAU,GAAG,gBAAgB,OAAO,QAC9C,OAAO;CAET;CACA,OAAO;AACR;AAEA,MAAM,iBACL,KACA,QACA,UACuB;CACvB,MAAM,KAAK,IAAI,SAAS,cAAc,QAAQ;CAC9C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,SAAS,CAAC,CAAC,GAC5D,GAAG,aAAa,MAAM,KAAK;CAE5B,IAAI,OAAO,MACV,GAAG,OAAO,OAAO;CAElB,IAAI,OACH,GAAG,aAAa,SAAS,KAAK;CAE/B,OAAO;AACR;;;;;AAMA,MAAa,sBACX,KAAoB,WACpB,WACA,IAAI,SAAS,SAAS,WAAW;CAChC,MAAM,EAAE,KAAK,WAAW;CACxB,IAAI,eAAe,KAAK,MAAM,GAAG;EAChC,QAAQ;EACR;CACD;CACA,IAAI,QAAQ;EACX,MAAM,KAAK,cAAc,KAAK,QAAQ,KAAK;EAC3C,GAAG,OAAO;EACV,IAAI,SAAS,KAAK,YAAY,EAAE;EAChC,QAAQ;EACR;CACD;CACA,IAAI,CAAC,KAAK;EACT,QAAQ;EACR;CACD;CACA,MAAM,KAAK,cAAc,KAAK,QAAQ,KAAK;CAC3C,GAAG,QAAQ,OAAO,SAAS;CAC3B,GAAG,QAAQ,OAAO,SAAS;CAC3B,GAAG,iBAAiB,cAAc,QAAQ,CAAC;CAC3C,GAAG,iBAAiB,eAAe,uBAAO,IAAI,MAAM,6BAA6B,KAAK,CAAC,CAAC;CACxF,GAAG,MAAM;CACT,IAAI,SAAS,KAAK,YAAY,EAAE;AACjC,CAAC"}
1
+ {"version":3,"file":"loadScript.js","names":[],"sources":["../../src/tracker/loadScript.ts"],"sourcesContent":["import type { SnippetScript } from './config'\nimport type { LoadScript, TrackerWindow } from './types'\n\n/** Whether the page already holds the script: the same `src`, or the same inline text. */\nexport const alreadyPresent = (win: TrackerWindow, script: SnippetScript): boolean => {\n\tfor (const el of win.document.querySelectorAll('script')) {\n\t\tif (script.src && el.getAttribute('src') === script.src) {\n\t\t\treturn true\n\t\t}\n\t\tif (script.inline && el.textContent === script.inline) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nconst scriptElement = (\n\twin: TrackerWindow,\n\tscript: SnippetScript,\n\tnonce: string | undefined\n): HTMLScriptElement => {\n\tconst el = win.document.createElement('script')\n\tfor (const [name, value] of Object.entries(script.attrs ?? {})) {\n\t\tel.setAttribute(name, value)\n\t}\n\tif (script.type) {\n\t\tel.type = script.type\n\t}\n\tif (nonce) {\n\t\tel.setAttribute('nonce', nonce)\n\t}\n\treturn el\n}\n\n/**\n * The default `loadScript`: injects a snippet script into `<head>`, resolving once it has run. A\n * script already on the page is a no-op, so booting over `AnalyticsScripts`' render loads no copy.\n */\nexport const createScriptLoader =\n\t(win: TrackerWindow, nonce?: string): LoadScript =>\n\t(script) =>\n\t\tnew Promise((resolve, reject) => {\n\t\t\tconst { src, inline } = script\n\t\t\tif (alreadyPresent(win, script)) {\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (inline) {\n\t\t\t\tconst el = scriptElement(win, script, nonce)\n\t\t\t\tel.text = inline\n\t\t\t\twin.document.head.appendChild(el)\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif (!src) {\n\t\t\t\tresolve()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst el = scriptElement(win, script, nonce)\n\t\t\tel.async = script.async ?? false\n\t\t\tel.defer = script.defer ?? false\n\t\t\tel.addEventListener('load', () => resolve())\n\t\t\tel.addEventListener('error', () => reject(new Error(`analytics: failed to load ${src}`)))\n\t\t\tel.src = src\n\t\t\twin.document.head.appendChild(el)\n\t\t})\n"],"mappings":";;AAIA,MAAa,kBAAkB,KAAoB,WAAmC;CACrF,KAAK,MAAM,MAAM,IAAI,SAAS,iBAAiB,QAAQ,GAAG;EACzD,IAAI,OAAO,OAAO,GAAG,aAAa,KAAK,MAAM,OAAO,KACnD,OAAO;EAER,IAAI,OAAO,UAAU,GAAG,gBAAgB,OAAO,QAC9C,OAAO;CAET;CACA,OAAO;AACR;AAEA,MAAM,iBACL,KACA,QACA,UACuB;CACvB,MAAM,KAAK,IAAI,SAAS,cAAc,QAAQ;CAC9C,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,SAAS,CAAC,CAAC,GAC5D,GAAG,aAAa,MAAM,KAAK;CAE5B,IAAI,OAAO,MACV,GAAG,OAAO,OAAO;CAElB,IAAI,OACH,GAAG,aAAa,SAAS,KAAK;CAE/B,OAAO;AACR;;;;;AAMA,MAAa,sBACX,KAAoB,WACpB,WACA,IAAI,SAAS,SAAS,WAAW;CAChC,MAAM,EAAE,KAAK,WAAW;CACxB,IAAI,eAAe,KAAK,MAAM,GAAG;EAChC,QAAQ;EACR;CACD;CACA,IAAI,QAAQ;EACX,MAAM,KAAK,cAAc,KAAK,QAAQ,KAAK;EAC3C,GAAG,OAAO;EACV,IAAI,SAAS,KAAK,YAAY,EAAE;EAChC,QAAQ;EACR;CACD;CACA,IAAI,CAAC,KAAK;EACT,QAAQ;EACR;CACD;CACA,MAAM,KAAK,cAAc,KAAK,QAAQ,KAAK;CAC3C,GAAG,QAAQ,OAAO,SAAS;CAC3B,GAAG,QAAQ,OAAO,SAAS;CAC3B,GAAG,iBAAiB,cAAc,QAAQ,CAAC;CAC3C,GAAG,iBAAiB,eAAe,uBAAO,IAAI,MAAM,6BAA6B,KAAK,CAAC,CAAC;CACxF,GAAG,MAAM;CACT,IAAI,SAAS,KAAK,YAAY,EAAE;AACjC,CAAC"}
@@ -1,4 +1,4 @@
1
- import { ALL_PENDING, GATE_SLOTS, answeredSnapshot, appendGateAnswer, settleGateAnswers, slotConfigOf, slotIsGated } from "./gate.js";
1
+ import { ALL_OFF, ALL_PENDING, GATE_SLOTS, answeredModes, answeredSnapshot, appendGateAnswer, settleGateAnswers, slotConfigOf, slotIsGated } from "./gate.js";
2
2
  import { currentWindow } from "./window.js";
3
3
  import { createNoopTracker, createTracker, restoreGate } from "./createTracker.js";
4
4
  //#region src/tracker/registry.ts
@@ -11,6 +11,7 @@ const notify = (win) => {
11
11
  const keepAnswers = (kept, answers) => {
12
12
  kept.answers = answers;
13
13
  kept.answered = answeredSnapshot(answers, kept.slots);
14
+ kept.answeredModes = answeredModes(answers, kept.slots);
14
15
  };
15
16
  /** Whether an answer names ungated slots alone, which a restored page keeps answered. */
16
17
  const namesUngatedOnly = (answer, slots) => {
@@ -35,6 +36,7 @@ const windowGate = (win) => {
35
36
  const kept = {
36
37
  answers: [],
37
38
  answered: ALL_PENDING,
39
+ answeredModes: ALL_OFF,
38
40
  listeners: /* @__PURE__ */ new Set(),
39
41
  detach: () => win.removeEventListener("pageshow", onPageShow)
40
42
  };
@@ -67,7 +69,13 @@ const windowGateSnapshot = (window) => {
67
69
  if (!win) return ALL_PENDING;
68
70
  return entries.get(win)?.tracker.gate ?? gates.get(win)?.answered ?? ALL_PENDING;
69
71
  };
70
- /** Calls `listener` whenever the window's gate may have changed. Returns the unsubscribe. */
72
+ /** The window's slot modes: its tracker's, else what the answers given so far give its last config. */
73
+ const windowModeSnapshot = (window) => {
74
+ const win = currentWindow(window);
75
+ if (!win) return ALL_OFF;
76
+ return entries.get(win)?.tracker.mode ?? gates.get(win)?.answeredModes ?? ALL_OFF;
77
+ };
78
+ /** Calls `listener` whenever the window's gate or modes may have changed. Returns the unsubscribe. */
71
79
  const subscribeWindowGate = (listener, window) => {
72
80
  const win = currentWindow(window);
73
81
  if (!win) return () => void 0;
@@ -93,6 +101,9 @@ const leasedTracker = (lease, window) => {
93
101
  get gate() {
94
102
  return tracker.gate;
95
103
  },
104
+ get mode() {
105
+ return tracker.mode;
106
+ },
96
107
  get excluded() {
97
108
  return tracker.excluded;
98
109
  },
@@ -156,6 +167,6 @@ const acquireTracker = (config, options = {}) => {
156
167
  };
157
168
  };
158
169
  //#endregion
159
- export { acquireTracker, leasedTracker, liveTracker, setWindowGate, subscribeWindowGate, windowGateSnapshot };
170
+ export { acquireTracker, leasedTracker, liveTracker, setWindowGate, subscribeWindowGate, windowGateSnapshot, windowModeSnapshot };
160
171
 
161
172
  //# sourceMappingURL=registry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","names":[],"sources":["../../src/tracker/registry.ts"],"sourcesContent":["import type { TrackerConfig, TrackerSlotConfig } from './config'\nimport { createNoopTracker, createTracker, restoreGate } from './createTracker'\nimport {\n\tALL_PENDING,\n\tansweredSnapshot,\n\tappendGateAnswer,\n\tGATE_SLOTS,\n\ttype GateSnapshot,\n\tsettleGateAnswers,\n\tslotConfigOf,\n\tslotIsGated,\n} from './gate'\nimport type { GateState, Tracker, TrackerOptions, TrackerWindow } from './types'\nimport { currentWindow } from './window'\n\nexport interface TrackerLease {\n\ttracker: Tracker\n\t/** Gives up this holder's claim. Safe to call more than once. */\n\trelease(): void\n}\n\ninterface Entry {\n\ttracker: Tracker\n\trefs: number\n\tteardown: ReturnType<Window['setTimeout']> | null\n}\n\n/**\n * The gate answers a window has been given, for as long as the page lives: a tracker booted\n * after them, or booted again after a remount, starts from them rather than from pending.\n */\ninterface WindowGate {\n\tanswers: GateState[]\n\t/** What the answers say while no tracker holds the window. */\n\tanswered: GateSnapshot\n\t/** The slots of the config the window last booted a tracker with, which say which are held. */\n\tslots?: readonly TrackerSlotConfig[]\n\tlisteners: Set<() => void>\n\t/** Takes the window's back/forward cache listener off. */\n\tdetach: () => void\n}\n\nconst entries = new WeakMap<TrackerWindow, Entry>()\n\nconst gates = new WeakMap<TrackerWindow, WindowGate>()\n\nconst notify = (win: TrackerWindow): void => {\n\tfor (const listener of gates.get(win)?.listeners ?? []) {\n\t\tlistener()\n\t}\n}\n\n/** Replaces the window's answers, and what they say while no tracker holds the window. */\nconst keepAnswers = (kept: WindowGate, answers: GateState[]): void => {\n\tkept.answers = answers\n\tkept.answered = answeredSnapshot(answers, kept.slots)\n}\n\n/** Whether an answer names ungated slots alone, which a restored page keeps answered. */\nconst namesUngatedOnly = (\n\tanswer: GateState,\n\tslots: readonly TrackerSlotConfig[] | undefined\n): boolean => {\n\tif (typeof answer === 'boolean' || slots === undefined) {\n\t\treturn false\n\t}\n\treturn GATE_SLOTS.every((slot) => {\n\t\tconst config = slotConfigOf(slots, slot)\n\t\treturn answer[slot] === undefined || (config !== undefined && !slotIsGated(config))\n\t})\n}\n\nconst windowGate = (win: TrackerWindow): WindowGate => {\n\tconst existing = gates.get(win)\n\tif (existing) {\n\t\treturn existing\n\t}\n\t// A restored page waits for the host to answer for its held slots again, as a new load would.\n\tconst onPageShow = (event: PageTransitionEvent) => {\n\t\tconst restored = gates.get(win)\n\t\tif (!event.persisted || !restored) {\n\t\t\treturn\n\t\t}\n\t\tkeepAnswers(\n\t\t\trestored,\n\t\t\trestored.answers.filter((answer) => namesUngatedOnly(answer, restored.slots))\n\t\t)\n\t\tconst tracker = entries.get(win)?.tracker\n\t\tif (tracker) {\n\t\t\trestoreGate(tracker, event)\n\t\t}\n\t\tnotify(win)\n\t}\n\twin.addEventListener('pageshow', onPageShow)\n\tconst kept: WindowGate = {\n\t\tanswers: [],\n\t\tanswered: ALL_PENDING,\n\t\tlisteners: new Set(),\n\t\tdetach: () => win.removeEventListener('pageshow', onPageShow),\n\t}\n\tgates.set(win, kept)\n\treturn kept\n}\n\n/**\n * The tracker a window already holds, or null: a peek that takes no lease, for callers with no\n * config of their own such as `useAnalytics` outside a provider.\n */\nexport const liveTracker = (window?: TrackerWindow): Tracker | null => {\n\tconst win = currentWindow(window)\n\treturn win ? (entries.get(win)?.tracker ?? null) : null\n}\n\n/**\n * Answers the window's gate: kept for every tracker the page boots and applied to the current one,\n * so a consent bridge may answer before any tracker exists.\n */\nexport const setWindowGate = (state: GateState, window?: TrackerWindow): void => {\n\tconst win = currentWindow(window)\n\tif (!win) {\n\t\treturn\n\t}\n\tconst kept = windowGate(win)\n\tkeepAnswers(kept, appendGateAnswer(kept.answers, state))\n\tentries.get(win)?.tracker.setGate(state)\n\tnotify(win)\n}\n\n/** The window's gate: its tracker's, else what the answers given so far say. */\nexport const windowGateSnapshot = (window?: TrackerWindow): GateSnapshot => {\n\tconst win = currentWindow(window)\n\tif (!win) {\n\t\treturn ALL_PENDING\n\t}\n\treturn entries.get(win)?.tracker.gate ?? gates.get(win)?.answered ?? ALL_PENDING\n}\n\n/** Calls `listener` whenever the window's gate may have changed. Returns the unsubscribe. */\nexport const subscribeWindowGate = (listener: () => void, window?: TrackerWindow): (() => void) => {\n\tconst win = currentWindow(window)\n\tif (!win) {\n\t\treturn () => undefined\n\t}\n\tconst { listeners } = windowGate(win)\n\tlisteners.add(listener)\n\treturn () => {\n\t\tlisteners.delete(listener)\n\t}\n}\n\n/** Forgets the window's gate answers. For tests, which share one window across cases. */\nexport const forgetWindowGate = (window?: TrackerWindow): void => {\n\tconst win = currentWindow(window)\n\tif (win) {\n\t\tgates.get(win)?.detach()\n\t\tgates.delete(win)\n\t}\n}\n\n/**\n * The lease's tracker for a sole holder: `destroy` returns the lease instead of ending a shared\n * tracker, and `setGate` answers for the window so a later boot starts from that answer.\n */\nexport const leasedTracker = (lease: TrackerLease, window?: TrackerWindow): Tracker => {\n\tconst { tracker } = lease\n\treturn {\n\t\tpage: () => tracker.page(),\n\t\ttrack: (name, props, opts) => tracker.track(name, props, opts),\n\t\ttrackGoal: (slug, opts) => tracker.trackGoal(slug, opts),\n\t\tpurchase: (input) => tracker.purchase(input),\n\t\trefund: (input) => tracker.refund(input),\n\t\tsetGate: (state) => setWindowGate(state, window),\n\t\tget gate() {\n\t\t\treturn tracker.gate\n\t\t},\n\t\tget excluded() {\n\t\t\treturn tracker.excluded\n\t\t},\n\t\texclude: (next) => tracker.exclude(next),\n\t\tflush: () => tracker.flush(),\n\t\tdestroy: () => lease.release(),\n\t}\n}\n\n/**\n * Hands out the window's one tracker, reference counted, so StrictMode remounts and sibling\n * components share it. The first holder's config wins; the window's gate answers outrank `gate`.\n */\nexport const acquireTracker = (\n\tconfig: TrackerConfig,\n\toptions: TrackerOptions = {}\n): TrackerLease => {\n\tconst win = currentWindow(options.window)\n\tif (!win) {\n\t\treturn { tracker: createNoopTracker(), release: () => undefined }\n\t}\n\tlet entry = entries.get(win)\n\tif (!entry) {\n\t\tconst kept = windowGate(win)\n\t\tconst gate = settleGateAnswers(config.slots, [\n\t\t\t...(options.gate === undefined ? [] : [options.gate]),\n\t\t\t...kept.answers,\n\t\t])\n\t\tkept.slots = config.slots\n\t\tkeepAnswers(kept, kept.answers)\n\t\tentry = {\n\t\t\ttracker: createTracker(config, { ...options, window: win, gate }),\n\t\t\trefs: 0,\n\t\t\tteardown: null,\n\t\t}\n\t\tentries.set(win, entry)\n\t\tnotify(win)\n\t}\n\tif (entry.teardown !== null) {\n\t\twin.clearTimeout(entry.teardown)\n\t\tentry.teardown = null\n\t}\n\tentry.refs += 1\n\tconst leased = entry\n\tlet released = false\n\n\treturn {\n\t\ttracker: entry.tracker,\n\t\trelease() {\n\t\t\tif (released) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\treleased = true\n\t\t\tleased.refs -= 1\n\t\t\tif (leased.refs > 0 || leased.teardown !== null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tleased.teardown = win.setTimeout(() => {\n\t\t\t\tleased.teardown = null\n\t\t\t\tif (leased.refs > 0) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tleased.tracker.destroy()\n\t\t\t\tif (entries.get(win) === leased) {\n\t\t\t\t\tentries.delete(win)\n\t\t\t\t\tnotify(win)\n\t\t\t\t}\n\t\t\t}, 0)\n\t\t},\n\t}\n}\n"],"mappings":";;;;AA0CA,MAAM,0BAAU,IAAI,QAA8B;AAElD,MAAM,wBAAQ,IAAI,QAAmC;AAErD,MAAM,UAAU,QAA6B;CAC5C,KAAK,MAAM,YAAY,MAAM,IAAI,GAAG,GAAG,aAAa,CAAC,GACpD,SAAS;AAEX;;AAGA,MAAM,eAAe,MAAkB,YAA+B;CACrE,KAAK,UAAU;CACf,KAAK,WAAW,iBAAiB,SAAS,KAAK,KAAK;AACrD;;AAGA,MAAM,oBACL,QACA,UACa;CACb,IAAI,OAAO,WAAW,aAAa,UAAU,KAAA,GAC5C,OAAO;CAER,OAAO,WAAW,OAAO,SAAS;EACjC,MAAM,SAAS,aAAa,OAAO,IAAI;EACvC,OAAO,OAAO,UAAU,KAAA,KAAc,WAAW,KAAA,KAAa,CAAC,YAAY,MAAM;CAClF,CAAC;AACF;AAEA,MAAM,cAAc,QAAmC;CACtD,MAAM,WAAW,MAAM,IAAI,GAAG;CAC9B,IAAI,UACH,OAAO;CAGR,MAAM,cAAc,UAA+B;EAClD,MAAM,WAAW,MAAM,IAAI,GAAG;EAC9B,IAAI,CAAC,MAAM,aAAa,CAAC,UACxB;EAED,YACC,UACA,SAAS,QAAQ,QAAQ,WAAW,iBAAiB,QAAQ,SAAS,KAAK,CAAC,CAC7E;EACA,MAAM,UAA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IACtC,OAAO,WAAW;IAClB,IAAI,OAAO,OAAO,GACjB;IAED,OAAO,QAAQ,QAAQ;IACvB,IAAI,QAAQ,IAAI,GAAG,MAAM,QAAQ;KAChC,QAAQ,OAAO,GAAG;KAClB,OAAO,GAAG;IACX;GACD,GAAG,CAAC;EACL;CACD;AACD"}
1
+ {"version":3,"file":"registry.js","names":[],"sources":["../../src/tracker/registry.ts"],"sourcesContent":["import type { TrackerConfig, TrackerSlotConfig } from './config'\nimport { createNoopTracker, createTracker, restoreGate } from './createTracker'\nimport {\n\tALL_OFF,\n\tALL_PENDING,\n\tansweredModes,\n\tansweredSnapshot,\n\tappendGateAnswer,\n\tGATE_SLOTS,\n\ttype GateSnapshot,\n\ttype ModeSnapshot,\n\tsettleGateAnswers,\n\tslotConfigOf,\n\tslotIsGated,\n} from './gate'\nimport type { GateState, Tracker, TrackerOptions, TrackerWindow } from './types'\nimport { currentWindow } from './window'\n\nexport interface TrackerLease {\n\ttracker: Tracker\n\t/** Gives up this holder's claim. Safe to call more than once. */\n\trelease(): void\n}\n\ninterface Entry {\n\ttracker: Tracker\n\trefs: number\n\tteardown: ReturnType<Window['setTimeout']> | null\n}\n\n/**\n * The gate answers a window has been given, for as long as the page lives: a tracker booted\n * after them, or booted again after a remount, starts from them rather than from pending.\n */\ninterface WindowGate {\n\tanswers: GateState[]\n\t/** What the answers say while no tracker holds the window. */\n\tanswered: GateSnapshot\n\t/** The modes they give while no tracker holds the window, all off before a config is known. */\n\tansweredModes: ModeSnapshot\n\t/** The slots of the config the window last booted a tracker with, which say which are held. */\n\tslots?: readonly TrackerSlotConfig[]\n\tlisteners: Set<() => void>\n\t/** Takes the window's back/forward cache listener off. */\n\tdetach: () => void\n}\n\nconst entries = new WeakMap<TrackerWindow, Entry>()\n\nconst gates = new WeakMap<TrackerWindow, WindowGate>()\n\nconst notify = (win: TrackerWindow): void => {\n\tfor (const listener of gates.get(win)?.listeners ?? []) {\n\t\tlistener()\n\t}\n}\n\n/** Replaces the window's answers, and what they say while no tracker holds the window. */\nconst keepAnswers = (kept: WindowGate, answers: GateState[]): void => {\n\tkept.answers = answers\n\tkept.answered = answeredSnapshot(answers, kept.slots)\n\tkept.answeredModes = answeredModes(answers, kept.slots)\n}\n\n/** Whether an answer names ungated slots alone, which a restored page keeps answered. */\nconst namesUngatedOnly = (\n\tanswer: GateState,\n\tslots: readonly TrackerSlotConfig[] | undefined\n): boolean => {\n\tif (typeof answer === 'boolean' || slots === undefined) {\n\t\treturn false\n\t}\n\treturn GATE_SLOTS.every((slot) => {\n\t\tconst config = slotConfigOf(slots, slot)\n\t\treturn answer[slot] === undefined || (config !== undefined && !slotIsGated(config))\n\t})\n}\n\nconst windowGate = (win: TrackerWindow): WindowGate => {\n\tconst existing = gates.get(win)\n\tif (existing) {\n\t\treturn existing\n\t}\n\t// A restored page waits for the host to answer for its held slots again, as a new load would.\n\tconst onPageShow = (event: PageTransitionEvent) => {\n\t\tconst restored = gates.get(win)\n\t\tif (!event.persisted || !restored) {\n\t\t\treturn\n\t\t}\n\t\tkeepAnswers(\n\t\t\trestored,\n\t\t\trestored.answers.filter((answer) => namesUngatedOnly(answer, restored.slots))\n\t\t)\n\t\tconst tracker = entries.get(win)?.tracker\n\t\tif (tracker) {\n\t\t\trestoreGate(tracker, event)\n\t\t}\n\t\tnotify(win)\n\t}\n\twin.addEventListener('pageshow', onPageShow)\n\tconst kept: WindowGate = {\n\t\tanswers: [],\n\t\tanswered: ALL_PENDING,\n\t\tansweredModes: ALL_OFF,\n\t\tlisteners: new Set(),\n\t\tdetach: () => win.removeEventListener('pageshow', onPageShow),\n\t}\n\tgates.set(win, kept)\n\treturn kept\n}\n\n/**\n * The tracker a window already holds, or null: a peek that takes no lease, for callers with no\n * config of their own such as `useAnalytics` outside a provider.\n */\nexport const liveTracker = (window?: TrackerWindow): Tracker | null => {\n\tconst win = currentWindow(window)\n\treturn win ? (entries.get(win)?.tracker ?? null) : null\n}\n\n/**\n * Answers the window's gate: kept for every tracker the page boots and applied to the current one,\n * so a consent bridge may answer before any tracker exists.\n */\nexport const setWindowGate = (state: GateState, window?: TrackerWindow): void => {\n\tconst win = currentWindow(window)\n\tif (!win) {\n\t\treturn\n\t}\n\tconst kept = windowGate(win)\n\tkeepAnswers(kept, appendGateAnswer(kept.answers, state))\n\tentries.get(win)?.tracker.setGate(state)\n\tnotify(win)\n}\n\n/** The window's gate: its tracker's, else what the answers given so far say. */\nexport const windowGateSnapshot = (window?: TrackerWindow): GateSnapshot => {\n\tconst win = currentWindow(window)\n\tif (!win) {\n\t\treturn ALL_PENDING\n\t}\n\treturn entries.get(win)?.tracker.gate ?? gates.get(win)?.answered ?? ALL_PENDING\n}\n\n/** The window's slot modes: its tracker's, else what the answers given so far give its last config. */\nexport const windowModeSnapshot = (window?: TrackerWindow): ModeSnapshot => {\n\tconst win = currentWindow(window)\n\tif (!win) {\n\t\treturn ALL_OFF\n\t}\n\treturn entries.get(win)?.tracker.mode ?? gates.get(win)?.answeredModes ?? ALL_OFF\n}\n\n/** Calls `listener` whenever the window's gate or modes may have changed. Returns the unsubscribe. */\nexport const subscribeWindowGate = (listener: () => void, window?: TrackerWindow): (() => void) => {\n\tconst win = currentWindow(window)\n\tif (!win) {\n\t\treturn () => undefined\n\t}\n\tconst { listeners } = windowGate(win)\n\tlisteners.add(listener)\n\treturn () => {\n\t\tlisteners.delete(listener)\n\t}\n}\n\n/** Forgets the window's gate answers. For tests, which share one window across cases. */\nexport const forgetWindowGate = (window?: TrackerWindow): void => {\n\tconst win = currentWindow(window)\n\tif (win) {\n\t\tgates.get(win)?.detach()\n\t\tgates.delete(win)\n\t}\n}\n\n/**\n * The lease's tracker for a sole holder: `destroy` returns the lease instead of ending a shared\n * tracker, and `setGate` answers for the window so a later boot starts from that answer.\n */\nexport const leasedTracker = (lease: TrackerLease, window?: TrackerWindow): Tracker => {\n\tconst { tracker } = lease\n\treturn {\n\t\tpage: () => tracker.page(),\n\t\ttrack: (name, props, opts) => tracker.track(name, props, opts),\n\t\ttrackGoal: (slug, opts) => tracker.trackGoal(slug, opts),\n\t\tpurchase: (input) => tracker.purchase(input),\n\t\trefund: (input) => tracker.refund(input),\n\t\tsetGate: (state) => setWindowGate(state, window),\n\t\tget gate() {\n\t\t\treturn tracker.gate\n\t\t},\n\t\tget mode() {\n\t\t\treturn tracker.mode\n\t\t},\n\t\tget excluded() {\n\t\t\treturn tracker.excluded\n\t\t},\n\t\texclude: (next) => tracker.exclude(next),\n\t\tflush: () => tracker.flush(),\n\t\tdestroy: () => lease.release(),\n\t}\n}\n\n/**\n * Hands out the window's one tracker, reference counted, so StrictMode remounts and sibling\n * components share it. The first holder's config wins; the window's gate answers outrank `gate`.\n */\nexport const acquireTracker = (\n\tconfig: TrackerConfig,\n\toptions: TrackerOptions = {}\n): TrackerLease => {\n\tconst win = currentWindow(options.window)\n\tif (!win) {\n\t\treturn { tracker: createNoopTracker(), release: () => undefined }\n\t}\n\tlet entry = entries.get(win)\n\tif (!entry) {\n\t\tconst kept = windowGate(win)\n\t\tconst gate = settleGateAnswers(config.slots, [\n\t\t\t...(options.gate === undefined ? [] : [options.gate]),\n\t\t\t...kept.answers,\n\t\t])\n\t\tkept.slots = config.slots\n\t\tkeepAnswers(kept, kept.answers)\n\t\tentry = {\n\t\t\ttracker: createTracker(config, { ...options, window: win, gate }),\n\t\t\trefs: 0,\n\t\t\tteardown: null,\n\t\t}\n\t\tentries.set(win, entry)\n\t\tnotify(win)\n\t}\n\tif (entry.teardown !== null) {\n\t\twin.clearTimeout(entry.teardown)\n\t\tentry.teardown = null\n\t}\n\tentry.refs += 1\n\tconst leased = entry\n\tlet released = false\n\n\treturn {\n\t\ttracker: entry.tracker,\n\t\trelease() {\n\t\t\tif (released) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\treleased = true\n\t\t\tleased.refs -= 1\n\t\t\tif (leased.refs > 0 || leased.teardown !== null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tleased.teardown = win.setTimeout(() => {\n\t\t\t\tleased.teardown = null\n\t\t\t\tif (leased.refs > 0) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tleased.tracker.destroy()\n\t\t\t\tif (entries.get(win) === leased) {\n\t\t\t\t\tentries.delete(win)\n\t\t\t\t\tnotify(win)\n\t\t\t\t}\n\t\t\t}, 0)\n\t\t},\n\t}\n}\n"],"mappings":";;;;AA+CA,MAAM,0BAAU,IAAI,QAA8B;AAElD,MAAM,wBAAQ,IAAI,QAAmC;AAErD,MAAM,UAAU,QAA6B;CAC5C,KAAK,MAAM,YAAY,MAAM,IAAI,GAAG,GAAG,aAAa,CAAC,GACpD,SAAS;AAEX;;AAGA,MAAM,eAAe,MAAkB,YAA+B;CACrE,KAAK,UAAU;CACf,KAAK,WAAW,iBAAiB,SAAS,KAAK,KAAK;CACpD,KAAK,gBAAgB,cAAc,SAAS,KAAK,KAAK;AACvD;;AAGA,MAAM,oBACL,QACA,UACa;CACb,IAAI,OAAO,WAAW,aAAa,UAAU,KAAA,GAC5C,OAAO;CAER,OAAO,WAAW,OAAO,SAAS;EACjC,MAAM,SAAS,aAAa,OAAO,IAAI;EACvC,OAAO,OAAO,UAAU,KAAA,KAAc,WAAW,KAAA,KAAa,CAAC,YAAY,MAAM;CAClF,CAAC;AACF;AAEA,MAAM,cAAc,QAAmC;CACtD,MAAM,WAAW,MAAM,IAAI,GAAG;CAC9B,IAAI,UACH,OAAO;CAGR,MAAM,cAAc,UAA+B;EAClD,MAAM,WAAW,MAAM,IAAI,GAAG;EAC9B,IAAI,CAAC,MAAM,aAAa,CAAC,UACxB;EAED,YACC,UACA,SAAS,QAAQ,QAAQ,WAAW,iBAAiB,QAAQ,SAAS,KAAK,CAAC,CAC7E;EACA,MAAM,UAAU,QAAQ,IAAI,GAAG,GAAG;EAClC,IAAI,SACH,YAAY,SAAS,KAAK;EAE3B,OAAO,GAAG;CACX;CACA,IAAI,iBAAiB,YAAY,UAAU;CAC3C,MAAM,OAAmB;EACxB,SAAS,CAAC;EACV,UAAU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AO,OAAO,KAAK,OAAO,aAAa,MAC1C;GAED,OAAO,WAAW,IAAI,iBAAiB;IACtC,OAAO,WAAW;IAClB,IAAI,OAAO,OAAO,GACjB;IAED,OAAO,QAAQ,QAAQ;IACvB,IAAI,QAAQ,IAAI,GAAG,MAAM,QAAQ;KAChC,QAAQ,OAAO,GAAG;KAClB,OAAO,GAAG;IACX;GACD,GAAG,CAAC;EACL;CACD;AACD"}
@@ -1,3 +1,5 @@
1
+ import { slotCountsWithoutConsent } from "../gate.js";
2
+ import { alreadyPresent } from "../loadScript.js";
1
3
  import { createGa4Sink } from "./ga4.js";
2
4
  import { createNativeSink } from "./native.js";
3
5
  import { createPlausibleSink } from "./plausible.js";
@@ -6,8 +8,18 @@ import { createUmamiSink } from "./umami.js";
6
8
  //#region src/tracker/sinks/createSink.ts
7
9
  /** The sink delivering one slot's events, by the kind of adapter filling it. */
8
10
  const createSink = (args) => {
9
- const { slot, win, loadScript, ingestPath, snippets } = args;
10
- const scripts = snippets ? slot.snippet.scripts : [];
11
+ const { slot, win, loadScript, ingestPath, snippets, mode } = args;
12
+ const rendered = (snippet) => snippet.scripts.every((script) => alreadyPresent(win, script));
13
+ /**
14
+ * Whichever variant the server rendered, so none is injected twice; else the one the slot's mode
15
+ * asks for as it loads. With no scripts a sink injects nothing and forwards once the global exists.
16
+ */
17
+ const scripts = () => {
18
+ const full = slot.fullSnippet;
19
+ if (!snippets) return [];
20
+ if (full === void 0 || rendered(slot.snippet)) return slot.snippet.scripts;
21
+ return rendered(full) || mode() === "full" ? full.scripts : slot.snippet.scripts;
22
+ };
11
23
  const vendor = {
12
24
  slot: slot.slot,
13
25
  win,
@@ -18,19 +30,26 @@ const createSink = (args) => {
18
30
  case "native": return createNativeSink({
19
31
  slot: slot.slot,
20
32
  win,
21
- url: ingestPath
22
- });
23
- case "posthog": return createPosthogSink({
24
- ...vendor,
25
- ...slot.instance === void 0 ? {} : { instance: slot.instance }
33
+ url: ingestPath,
34
+ mode
26
35
  });
36
+ case "posthog": {
37
+ const { token } = slot.client;
38
+ return createPosthogSink({
39
+ ...vendor,
40
+ ...slot.instance === void 0 ? {} : { instance: slot.instance },
41
+ ...typeof token === "string" ? { token } : {},
42
+ cookieless: slotCountsWithoutConsent(slot)
43
+ });
44
+ }
27
45
  case "plausible": return createPlausibleSink(vendor);
28
46
  case "umami": return createUmamiSink(vendor);
29
47
  case "ga4": {
30
48
  const { measurementId } = slot.client;
31
49
  return createGa4Sink({
32
50
  ...vendor,
33
- ...typeof measurementId === "string" ? { measurementId } : {}
51
+ ...typeof measurementId === "string" ? { measurementId } : {},
52
+ cookieless: slotCountsWithoutConsent(slot)
34
53
  });
35
54
  }
36
55
  }
@@ -1 +1 @@
1
- {"version":3,"file":"createSink.js","names":[],"sources":["../../../src/tracker/sinks/createSink.ts"],"sourcesContent":["import type { TrackerSlotConfig } from '../config'\nimport type { LoadScript, Sink, TrackerWindow } from '../types'\nimport { createGa4Sink } from './ga4'\nimport { createNativeSink } from './native'\nimport { createPlausibleSink } from './plausible'\nimport { createPosthogSink } from './posthog'\nimport { createUmamiSink } from './umami'\n\n/** The sink delivering one slot's events, by the kind of adapter filling it. */\nexport const createSink = (args: {\n\tslot: TrackerSlotConfig\n\twin: TrackerWindow\n\tloadScript: LoadScript\n\tingestPath: string\n\t/** False when the host loads the vendor scripts itself. */\n\tsnippets: boolean\n}): Sink => {\n\tconst { slot, win, loadScript, ingestPath, snippets } = args\n\t// With no scripts a vendor sink injects nothing and forwards once the vendor's global exists.\n\tconst scripts = snippets ? slot.snippet.scripts : []\n\tconst vendor = { slot: slot.slot, win, scripts, loadScript }\n\tswitch (slot.kind) {\n\t\tcase 'native':\n\t\t\treturn createNativeSink({ slot: slot.slot, win, url: ingestPath })\n\t\tcase 'posthog':\n\t\t\treturn createPosthogSink({\n\t\t\t\t...vendor,\n\t\t\t\t...(slot.instance === undefined ? {} : { instance: slot.instance }),\n\t\t\t})\n\t\tcase 'plausible':\n\t\t\treturn createPlausibleSink(vendor)\n\t\tcase 'umami':\n\t\t\treturn createUmamiSink(vendor)\n\t\tcase 'ga4': {\n\t\t\tconst { measurementId } = slot.client\n\t\t\treturn createGa4Sink({\n\t\t\t\t...vendor,\n\t\t\t\t...(typeof measurementId === 'string' ? { measurementId } : {}),\n\t\t\t})\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;AASA,MAAa,cAAc,SAOf;CACX,MAAM,EAAE,MAAM,KAAK,YAAY,YAAY,aAAa;CAExD,MAAM,UAAU,WAAW,KAAK,QAAQ,UAAU,CAAC;CACnD,MAAM,SAAS;EAAE,MAAM,KAAK;EAAM;EAAK;EAAS;CAAW;CAC3D,QAAQ,KAAK,MAAb;EACC,KAAK,UACJ,OAAO,iBAAiB;GAAE,MAAM,KAAK;GAAM;GAAK,KAAK;EAAW,CAAC;EAClE,KAAK,WACJ,OAAO,kBAAkB;GACxB,GAAG;GACH,GAAI,KAAK,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;EAClE,CAAC;EACF,KAAK,aACJ,OAAO,oBAAoB,MAAM;EAClC,KAAK,SACJ,OAAO,gBAAgB,MAAM;EAC9B,KAAK,OAAO;GACX,MAAM,EAAE,kBAAkB,KAAK;GAC/B,OAAO,cAAc;IACpB,GAAG;IACH,GAAI,OAAO,kBAAkB,WAAW,EAAE,cAAc,IAAI,CAAC;GAC9D,CAAC;EACF;CACD;AACD"}
1
+ {"version":3,"file":"createSink.js","names":[],"sources":["../../../src/tracker/sinks/createSink.ts"],"sourcesContent":["import type { CaptureSnippet, SlotMode, SnippetScript, TrackerSlotConfig } from '../config'\nimport { slotCountsWithoutConsent } from '../gate'\nimport { alreadyPresent } from '../loadScript'\nimport type { LoadScript, Sink, TrackerWindow } from '../types'\nimport { createGa4Sink } from './ga4'\nimport { createNativeSink } from './native'\nimport { createPlausibleSink } from './plausible'\nimport { createPosthogSink } from './posthog'\nimport { createUmamiSink } from './umami'\n\n/** The sink delivering one slot's events, by the kind of adapter filling it. */\nexport const createSink = (args: {\n\tslot: TrackerSlotConfig\n\twin: TrackerWindow\n\tloadScript: LoadScript\n\tingestPath: string\n\t/** False when the host loads the vendor scripts itself. */\n\tsnippets: boolean\n\t/** The slot's mode as an event is sent. */\n\tmode: () => SlotMode\n}): Sink => {\n\tconst { slot, win, loadScript, ingestPath, snippets, mode } = args\n\tconst rendered = (snippet: CaptureSnippet): boolean =>\n\t\tsnippet.scripts.every((script) => alreadyPresent(win, script))\n\t/**\n\t * Whichever variant the server rendered, so none is injected twice; else the one the slot's mode\n\t * asks for as it loads. With no scripts a sink injects nothing and forwards once the global exists.\n\t */\n\tconst scripts = (): readonly SnippetScript[] => {\n\t\tconst full = slot.fullSnippet\n\t\tif (!snippets) {\n\t\t\treturn []\n\t\t}\n\t\tif (full === undefined || rendered(slot.snippet)) {\n\t\t\treturn slot.snippet.scripts\n\t\t}\n\t\treturn rendered(full) || mode() === 'full' ? full.scripts : slot.snippet.scripts\n\t}\n\tconst vendor = { slot: slot.slot, win, scripts, loadScript }\n\tswitch (slot.kind) {\n\t\tcase 'native':\n\t\t\treturn createNativeSink({ slot: slot.slot, win, url: ingestPath, mode })\n\t\tcase 'posthog': {\n\t\t\tconst { token } = slot.client\n\t\t\treturn createPosthogSink({\n\t\t\t\t...vendor,\n\t\t\t\t...(slot.instance === undefined ? {} : { instance: slot.instance }),\n\t\t\t\t...(typeof token === 'string' ? { token } : {}),\n\t\t\t\tcookieless: slotCountsWithoutConsent(slot),\n\t\t\t})\n\t\t}\n\t\tcase 'plausible':\n\t\t\treturn createPlausibleSink(vendor)\n\t\tcase 'umami':\n\t\t\treturn createUmamiSink(vendor)\n\t\tcase 'ga4': {\n\t\t\tconst { measurementId } = slot.client\n\t\t\treturn createGa4Sink({\n\t\t\t\t...vendor,\n\t\t\t\t...(typeof measurementId === 'string' ? { measurementId } : {}),\n\t\t\t\tcookieless: slotCountsWithoutConsent(slot),\n\t\t\t})\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;AAWA,MAAa,cAAc,SASf;CACX,MAAM,EAAE,MAAM,KAAK,YAAY,YAAY,UAAU,SAAS;CAC9D,MAAM,YAAY,YACjB,QAAQ,QAAQ,OAAO,WAAW,eAAe,KAAK,MAAM,CAAC;;;;;CAK9D,MAAM,gBAA0C;EAC/C,MAAM,OAAO,KAAK;EAClB,IAAI,CAAC,UACJ,OAAO,CAAC;EAET,IAAI,SAAS,KAAA,KAAa,SAAS,KAAK,OAAO,GAC9C,OAAO,KAAK,QAAQ;EAErB,OAAO,SAAS,IAAI,KAAK,KAAK,MAAM,SAAS,KAAK,UAAU,KAAK,QAAQ;CAC1E;CACA,MAAM,SAAS;EAAE,MAAM,KAAK;EAAM;EAAK;EAAS;CAAW;CAC3D,QAAQ,KAAK,MAAb;EACC,KAAK,UACJ,OAAO,iBAAiB;GAAE,MAAM,KAAK;GAAM;GAAK,KAAK;GAAY;EAAK,CAAC;EACxE,KAAK,WAAW;GACf,MAAM,EAAE,UAAU,KAAK;GACvB,OAAO,kBAAkB;IACxB,GAAG;IACH,GAAI,KAAK,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,KAAK,SAAS;IACjE,GAAI,OAAO,UAAU,WAAW,EAAE,MAAM,IAAI,CAAC;IAC7C,YAAY,yBAAyB,IAAI;GAC1C,CAAC;EACF;EACA,KAAK,aACJ,OAAO,oBAAoB,MAAM;EAClC,KAAK,SACJ,OAAO,gBAAgB,MAAM;EAC9B,KAAK,OAAO;GACX,MAAM,EAAE,kBAAkB,KAAK;GAC/B,OAAO,cAAc;IACpB,GAAG;IACH,GAAI,OAAO,kBAAkB,WAAW,EAAE,cAAc,IAAI,CAAC;IAC7D,YAAY,yBAAyB,IAAI;GAC1C,CAAC;EACF;CACD;AACD"}
@@ -24,6 +24,23 @@ const configured = (win, measurementId) => {
24
24
  const layer = Reflect.get(win, "dataLayer");
25
25
  return Array.isArray(layer) && layer.some((entry) => typeof entry === "object" && entry !== null && Reflect.get(entry, 0) === "config" && Reflect.get(entry, 1) === measurementId);
26
26
  };
27
+ /** The cookies gtag.js keeps past a denied update: `_ga`, and the stream's own `_ga_<id>` without `G-`. */
28
+ const gaCookieNames = (measurementId) => ["_ga", `_ga_${measurementId.replace(/^G-/, "")}`];
29
+ /**
30
+ * Expires the tag's cookies at `/` on the host and on every parent domain: gtag.js's `auto` cookie
31
+ * domain sets them on the highest one it can, and an expiry reaches only the domain it names.
32
+ */
33
+ const expireGaCookies = (win, measurementId) => {
34
+ const labels = win.location.hostname.split(".");
35
+ const domains = labels.slice(0, -1).map((_, index) => labels.slice(index).join("."));
36
+ try {
37
+ for (const name of gaCookieNames(measurementId)) {
38
+ const expired = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;
39
+ win.document.cookie = expired;
40
+ for (const domain of domains) win.document.cookie = `${expired}; domain=${domain}`;
41
+ }
42
+ } catch {}
43
+ };
27
44
  /**
28
45
  * A click on a content item in GA4's promotion vocabulary, so its own promotion reports read
29
46
  * it: the ref as `promotion_id` and as the one line's `item_id`, its name beside both.
@@ -46,14 +63,29 @@ const isItemClickEvent = (event) => event.type === "event" && event.name === "it
46
63
  * Forwards events and goals to `gtag('event')` under GA4-safe names, sales with `transaction_id` and
47
64
  * `items`. No pageviews: enhanced measurement counts navigations and must stay on for the stream.
48
65
  */
49
- const createGa4Sink = ({ measurementId, ...args }) => {
66
+ const createGa4Sink = ({ measurementId, cookieless, ...args }) => {
50
67
  const gtag = () => vendorGlobal(args.win, "gtag");
68
+ /** Whether this page granted analytics storage, which a cookieless slot's tag starts without. */
69
+ let granted = false;
51
70
  return createVendorSink(args, {
52
- ...measurementId ? { exclude: (excluded) => {
53
- Reflect.set(args.win, ga4DisableKey(measurementId), excluded);
54
- const tag = gtag();
55
- if (excluded && typeof tag === "function" && configured(args.win, measurementId)) tag("consent", "update", { ...GA4_DENIED_CONSENT });
56
- } } : {},
71
+ ...measurementId ? {
72
+ mode: (next, from) => {
73
+ const off = next.mode === "off";
74
+ Reflect.set(args.win, ga4DisableKey(measurementId), off);
75
+ const tag = gtag();
76
+ if (typeof tag === "function") {
77
+ if (off) {
78
+ granted = false;
79
+ if (configured(args.win, measurementId)) tag("consent", "update", { ...GA4_DENIED_CONSENT });
80
+ } else if (cookieless && next.mode === "full" !== granted) {
81
+ granted = next.mode === "full";
82
+ tag("consent", "update", { analytics_storage: granted ? "granted" : "denied" });
83
+ }
84
+ }
85
+ if (from === "full" && next.mode !== "full" && !next.refused) expireGaCookies(args.win, measurementId);
86
+ },
87
+ forget: () => expireGaCookies(args.win, measurementId)
88
+ } : {},
57
89
  has: () => typeof gtag() === "function",
58
90
  dispatch: (event) => {
59
91
  if (isItemClickEvent(event)) {
@@ -1 +1 @@
1
- {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/tracker/sinks/ga4.ts"],"sourcesContent":["import { ga4DisableKey } from '../../adapters/ga4/disableKey'\nimport { ga4EventName } from '../../adapters/ga4/eventName'\nimport { ITEM_CLICK_EVENT } from '../../goals/constants'\nimport { bareItemRef } from '../../items/ref'\nimport type { Sink, TrackerEvent, TrackerWindow } from '../types'\nimport {\n\tcreateVendorSink,\n\tflatProps,\n\ttype VendorSinkArgs,\n\tvendorEventName,\n\tvendorGlobal,\n} from './vendor'\n\ninterface Gtag {\n\t(command: 'event', name: string, params?: Record<string, unknown>): void\n\t(command: 'consent', action: 'update', params: Record<string, 'granted' | 'denied'>): void\n}\n\n/**\n * Consent mode's update telling a tag that already ran to stop using its cookies: every storage\n * type it reads, analytics and advertising alike.\n */\nconst GA4_DENIED_CONSENT: Readonly<Record<string, 'denied'>> = Object.freeze({\n\tanalytics_storage: 'denied',\n\tad_storage: 'denied',\n\tad_user_data: 'denied',\n\tad_personalization: 'denied',\n})\n\n/** GA4's own event for a click on a promotion, which is what a click on a content item is. */\nconst GA4_ITEM_CLICK_EVENT = 'select_promotion'\n\n/**\n * Whether this measurement id's tag ran on the page: its `gtag('config', id)` is in the\n * `dataLayer`, as an `arguments` object, which gtag.js leaves there once it has read it.\n */\nconst configured = (win: TrackerWindow, measurementId: string): boolean => {\n\tconst layer: unknown = Reflect.get(win, 'dataLayer')\n\treturn (\n\t\tArray.isArray(layer) &&\n\t\tlayer.some(\n\t\t\t(entry: unknown) =>\n\t\t\t\ttypeof entry === 'object' &&\n\t\t\t\tentry !== null &&\n\t\t\t\tReflect.get(entry, 0) === 'config' &&\n\t\t\t\tReflect.get(entry, 1) === measurementId\n\t\t)\n\t)\n}\n\nexport interface Ga4SinkArgs extends VendorSinkArgs {\n\t/** From the slot's client descriptor: the switch is per measurement id. */\n\tmeasurementId?: string\n}\n\n/**\n * A click on a content item in GA4's promotion vocabulary, so its own promotion reports read\n * it: the ref as `promotion_id` and as the one line's `item_id`, its name beside both.\n */\nconst promotionParams = (event: TrackerEvent & { item: string }): Record<string, unknown> => {\n\tconst id = bareItemRef(event.item)\n\tconst name = event.itemName\n\treturn {\n\t\t...event.props,\n\t\tpromotion_id: id,\n\t\t...(name === undefined ? {} : { promotion_name: name }),\n\t\titems: [{ item_id: id, ...(name === undefined ? {} : { item_name: name }) }],\n\t}\n}\n\nconst isItemClickEvent = (event: TrackerEvent): event is TrackerEvent & { item: string } =>\n\tevent.type === 'event' && event.name === ITEM_CLICK_EVENT && event.item !== undefined\n\n/**\n * Forwards events and goals to `gtag('event')` under GA4-safe names, sales with `transaction_id` and\n * `items`. No pageviews: enhanced measurement counts navigations and must stay on for the stream.\n */\nexport const createGa4Sink = ({ measurementId, ...args }: Ga4SinkArgs): Sink => {\n\tconst gtag = () => vendorGlobal<Gtag>(args.win, 'gtag')\n\treturn createVendorSink(args, {\n\t\t...(measurementId\n\t\t\t? {\n\t\t\t\t\t// The rendered snippet sets the switch for itself; re-asserting it covers a gated\n\t\t\t\t\t// slot, whose snippet this sink injects, and a runtime flip either way.\n\t\t\t\t\texclude: (excluded: boolean) => {\n\t\t\t\t\t\tReflect.set(args.win, ga4DisableKey(measurementId), excluded)\n\t\t\t\t\t\t// Google honours the switch only before the first gtag() call, so a tag that ran is denied\n\t\t\t\t\t\t// storage too; nothing grants it back, since the host's own consent mode may hold it.\n\t\t\t\t\t\tconst tag = gtag()\n\t\t\t\t\t\tif (excluded && typeof tag === 'function' && configured(args.win, measurementId)) {\n\t\t\t\t\t\t\ttag('consent', 'update', { ...GA4_DENIED_CONSENT })\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\thas: () => typeof gtag() === 'function',\n\t\tdispatch: (event) => {\n\t\t\tif (isItemClickEvent(event)) {\n\t\t\t\tgtag()?.('event', GA4_ITEM_CLICK_EVENT, promotionParams(event))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgtag()?.('event', ga4EventName(vendorEventName(event)), {\n\t\t\t\t...flatProps(event),\n\t\t\t\t...(event.orderId === undefined ? {} : { transaction_id: event.orderId }),\n\t\t\t\t...(event.items === undefined ? {} : { items: event.items }),\n\t\t\t})\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;AAsBA,MAAM,qBAAyD,OAAO,OAAO;CAC5E,mBAAmB;CACnB,YAAY;CACZ,cAAc;CACd,oBAAoB;AACrB,CAAC;;AAGD,MAAM,uBAAuB;;;;;AAM7B,MAAM,cAAc,KAAoB,kBAAmC;CAC1E,MAAM,QAAiB,QAAQ,IAAI,KAAK,WAAW;CACnD,OACC,MAAM,QAAQ,KAAK,KACnB,MAAM,MACJ,UACA,OAAO,UAAU,YACjB,UAAU,QACV,QAAQ,IAAI,OAAO,CAAC,MAAM,YAC1B,QAAQ,IAAI,OAAO,CAAC,MAAM,aAC5B;AAEF;;;;;AAWA,MAAM,mBAAmB,UAAoE;CAC5F,MAAM,KAAK,YAAY,MAAM,IAAI;CACjC,MAAM,OAAO,MAAM;CACnB,OAAO;EACN,GAAG,MAAM;EACT,cAAc;EACd,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB,KAAK;EACrD,OAAO,CAAC;GAAE,SAAS;GAAI,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,WAAW,KAAK;EAAG,CAAC;CAC5E;AACD;AAEA,MAAM,oBAAoB,UACzB,MAAM,SAAS,WAAW,MAAM,SAAA,gBAA6B,MAAM,SAAS,KAAA;;;;;AAM7E,MAAa,iBAAiB,EAAE,eAAe,GAAG,WAA8B;CAC/E,MAAM,aAAa,aAAmB,KAAK,KAAK,MAAM;CACtD,OAAO,iBAAiB,MAAM;EAC7B,GAAI,gBACD,EAGA,UAAU,aAAsB;GAC/B,QAAQ,IAAI,KAAK,KAAK,cAAc,aAAa,GAAG,QAAQ;GAG5D,MAAM,MAAM,KAAK;GACjB,IAAI,YAAY,OAAO,QAAQ,cAAc,WAAW,KAAK,KAAK,aAAa,GAC9E,IAAI,WAAW,UAAU,EAAE,GAAG,mBAAmB,CAAC;EAEpD,EACD,IACC,CAAC;EACJ,WAAW,OAAO,KAAK,MAAM;EAC7B,WAAW,UAAU;GACpB,IAAI,iBAAiB,KAAK,GAAG;IAC5B,KAAK,IAAI,SAAS,sBAAsB,gBAAgB,KAAK,CAAC;IAC9D;GACD;GACA,KAAK,IAAI,SAAS,aAAa,gBAAgB,KAAK,CAAC,GAAG;IACvD,GAAG,UAAU,KAAK;IAClB,GAAI,MAAM,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB,MAAM,QAAQ;IACvE,GAAI,MAAM,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,MAAM,MAAM;GAC3D,CAAC;EACF;CACD,CAAC;AACF"}
1
+ {"version":3,"file":"ga4.js","names":[],"sources":["../../../src/tracker/sinks/ga4.ts"],"sourcesContent":["import { ga4DisableKey } from '../../adapters/ga4/disableKey'\nimport { ga4EventName } from '../../adapters/ga4/eventName'\nimport { ITEM_CLICK_EVENT } from '../../goals/constants'\nimport { bareItemRef } from '../../items/ref'\nimport type { Sink, TrackerEvent, TrackerWindow, VendorMode, VendorSwitch } from '../types'\nimport {\n\tcreateVendorSink,\n\tflatProps,\n\ttype VendorSinkArgs,\n\tvendorEventName,\n\tvendorGlobal,\n} from './vendor'\n\ninterface Gtag {\n\t(command: 'event', name: string, params?: Record<string, unknown>): void\n\t(command: 'consent', action: 'update', params: Record<string, 'granted' | 'denied'>): void\n}\n\n/**\n * Consent mode's update telling a tag that already ran to stop using its cookies: every storage\n * type it reads, analytics and advertising alike.\n */\nconst GA4_DENIED_CONSENT: Readonly<Record<string, 'denied'>> = Object.freeze({\n\tanalytics_storage: 'denied',\n\tad_storage: 'denied',\n\tad_user_data: 'denied',\n\tad_personalization: 'denied',\n})\n\n/** GA4's own event for a click on a promotion, which is what a click on a content item is. */\nconst GA4_ITEM_CLICK_EVENT = 'select_promotion'\n\n/**\n * Whether this measurement id's tag ran on the page: its `gtag('config', id)` is in the\n * `dataLayer`, as an `arguments` object, which gtag.js leaves there once it has read it.\n */\nconst configured = (win: TrackerWindow, measurementId: string): boolean => {\n\tconst layer: unknown = Reflect.get(win, 'dataLayer')\n\treturn (\n\t\tArray.isArray(layer) &&\n\t\tlayer.some(\n\t\t\t(entry: unknown) =>\n\t\t\t\ttypeof entry === 'object' &&\n\t\t\t\tentry !== null &&\n\t\t\t\tReflect.get(entry, 0) === 'config' &&\n\t\t\t\tReflect.get(entry, 1) === measurementId\n\t\t)\n\t)\n}\n\n/** The cookies gtag.js keeps past a denied update: `_ga`, and the stream's own `_ga_<id>` without `G-`. */\nexport const gaCookieNames = (measurementId: string): string[] => [\n\t'_ga',\n\t`_ga_${measurementId.replace(/^G-/, '')}`,\n]\n\n/**\n * Expires the tag's cookies at `/` on the host and on every parent domain: gtag.js's `auto` cookie\n * domain sets them on the highest one it can, and an expiry reaches only the domain it names.\n */\nexport const expireGaCookies = (win: TrackerWindow, measurementId: string): void => {\n\tconst labels = win.location.hostname.split('.')\n\tconst domains = labels.slice(0, -1).map((_, index) => labels.slice(index).join('.'))\n\ttry {\n\t\tfor (const name of gaCookieNames(measurementId)) {\n\t\t\tconst expired = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`\n\t\t\twin.document.cookie = expired\n\t\t\tfor (const domain of domains) {\n\t\t\t\twin.document.cookie = `${expired}; domain=${domain}`\n\t\t\t}\n\t\t}\n\t} catch {\n\t\t// A sandboxed document without cookies holds none of the tag's either.\n\t}\n}\n\nexport interface Ga4SinkArgs extends VendorSinkArgs {\n\t/** From the slot's client descriptor: the switch is per measurement id. */\n\tmeasurementId?: string\n\t/**\n\t * True when the slot counts without consent in some phase, so its snippet set every consent signal\n\t * denied before the tag loaded: the sink grants analytics storage on consent and denies it again.\n\t */\n\tcookieless?: boolean\n}\n\n/**\n * A click on a content item in GA4's promotion vocabulary, so its own promotion reports read\n * it: the ref as `promotion_id` and as the one line's `item_id`, its name beside both.\n */\nconst promotionParams = (event: TrackerEvent & { item: string }): Record<string, unknown> => {\n\tconst id = bareItemRef(event.item)\n\tconst name = event.itemName\n\treturn {\n\t\t...event.props,\n\t\tpromotion_id: id,\n\t\t...(name === undefined ? {} : { promotion_name: name }),\n\t\titems: [{ item_id: id, ...(name === undefined ? {} : { item_name: name }) }],\n\t}\n}\n\nconst isItemClickEvent = (event: TrackerEvent): event is TrackerEvent & { item: string } =>\n\tevent.type === 'event' && event.name === ITEM_CLICK_EVENT && event.item !== undefined\n\n/**\n * Forwards events and goals to `gtag('event')` under GA4-safe names, sales with `transaction_id` and\n * `items`. No pageviews: enhanced measurement counts navigations and must stay on for the stream.\n */\nexport const createGa4Sink = ({ measurementId, cookieless, ...args }: Ga4SinkArgs): Sink => {\n\tconst gtag = () => vendorGlobal<Gtag>(args.win, 'gtag')\n\t/** Whether this page granted analytics storage, which a cookieless slot's tag starts without. */\n\tlet granted = false\n\treturn createVendorSink(args, {\n\t\t...(measurementId\n\t\t\t? {\n\t\t\t\t\t// The rendered snippet sets the switch for itself; re-asserting it covers a gated\n\t\t\t\t\t// slot, whose snippet this sink injects, and a runtime flip either way.\n\t\t\t\t\tmode: (next: VendorSwitch, from: VendorMode | null) => {\n\t\t\t\t\t\tconst off = next.mode === 'off'\n\t\t\t\t\t\tReflect.set(args.win, ga4DisableKey(measurementId), off)\n\t\t\t\t\t\tconst tag = gtag()\n\t\t\t\t\t\tif (typeof tag === 'function') {\n\t\t\t\t\t\t\t// Google honours the switch only before the first gtag() call, so a tag that ran is\n\t\t\t\t\t\t\t// denied storage too; nothing grants it back, since the host's own consent mode may hold it.\n\t\t\t\t\t\t\tif (off) {\n\t\t\t\t\t\t\t\tgranted = false\n\t\t\t\t\t\t\t\tif (configured(args.win, measurementId)) {\n\t\t\t\t\t\t\t\t\ttag('consent', 'update', { ...GA4_DENIED_CONSENT })\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (cookieless && (next.mode === 'full') !== granted) {\n\t\t\t\t\t\t\t\t// Analytics storage alone: advertising signals stay denied unless the host grants them.\n\t\t\t\t\t\t\t\tgranted = next.mode === 'full'\n\t\t\t\t\t\t\t\ttag('consent', 'update', { analytics_storage: granted ? 'granted' : 'denied' })\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A refusal expires them through `forget`; this covers an exclusion over a grant.\n\t\t\t\t\t\tif (from === 'full' && next.mode !== 'full' && !next.refused) {\n\t\t\t\t\t\t\texpireGaCookies(args.win, measurementId)\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tforget: () => expireGaCookies(args.win, measurementId),\n\t\t\t\t}\n\t\t\t: {}),\n\t\thas: () => typeof gtag() === 'function',\n\t\tdispatch: (event) => {\n\t\t\tif (isItemClickEvent(event)) {\n\t\t\t\tgtag()?.('event', GA4_ITEM_CLICK_EVENT, promotionParams(event))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgtag()?.('event', ga4EventName(vendorEventName(event)), {\n\t\t\t\t...flatProps(event),\n\t\t\t\t...(event.orderId === undefined ? {} : { transaction_id: event.orderId }),\n\t\t\t\t...(event.items === undefined ? {} : { items: event.items }),\n\t\t\t})\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;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3
  /**
4
- * Posts every event to the plugin's own ingest endpoint the moment it is sent. An item's
5
- * display name stays behind: it is for the vendor slots, and native stores the ref alone.
4
+ * How a beacon says the page measured it: `c` cookieless, `a` anonymous. Full sends none, as a
5
+ * tracker from before modes did; anything but those three reads as the strictest.
6
+ */
7
+ const wireMode = (mode) => {
8
+ if (mode === "full") return;
9
+ return mode === "cookieless" ? "c" : "a";
10
+ };
11
+ /**
12
+ * Posts every event to the plugin's own ingest endpoint the moment it is sent, stamped with the
13
+ * slot's mode at that moment. An item's display name stays behind: it is for the vendor slots, and
14
+ * native stores the ref alone. Anonymous keeps no engagement, so none is sent.
6
15
  */
7
16
  const createNativeSink = (args) => {
8
17
  const { slot, win, url } = args;
@@ -10,8 +19,13 @@ const createNativeSink = (args) => {
10
19
  slot,
11
20
  ready: () => Promise.resolve(),
12
21
  send(event) {
22
+ const m = wireMode(args.mode?.() ?? "full");
23
+ if (m === "a" && event.type === "engagement") return;
13
24
  const { itemName: _itemName, ...wire } = event;
14
- sendPayload(win, url, wire);
25
+ sendPayload(win, url, m === void 0 ? wire : {
26
+ ...wire,
27
+ m
28
+ });
15
29
  }
16
30
  };
17
31
  };
@@ -1 +1 @@
1
- {"version":3,"file":"native.js","names":[],"sources":["../../../src/tracker/sinks/native.ts"],"sourcesContent":["import { sendPayload } from '../transport'\nimport type { Sink, TrackerWindow } from '../types'\n\n/**\n * Posts every event to the plugin's own ingest endpoint the moment it is sent. An item's\n * display name stays behind: it is for the vendor slots, and native stores the ref alone.\n */\nexport const createNativeSink = (args: {\n\tslot: Sink['slot']\n\twin: TrackerWindow\n\turl: string\n}): Sink => {\n\tconst { slot, win, url } = args\n\treturn {\n\t\tslot,\n\t\tready: () => Promise.resolve(),\n\t\tsend(event) {\n\t\t\tconst { itemName: _itemName, ...wire } = event\n\t\t\tsendPayload(win, url, wire)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;AAOA,MAAa,oBAAoB,SAIrB;CACX,MAAM,EAAE,MAAM,KAAK,QAAQ;CAC3B,OAAO;EACN;EACA,aAAa,QAAQ,QAAQ;EAC7B,KAAK,OAAO;GACX,MAAM,EAAE,UAAU,WAAW,GAAG,SAAS;GACzC,YAAY,KAAK,KAAK,IAAI;EAC3B;CACD;AACD"}
1
+ {"version":3,"file":"native.js","names":[],"sources":["../../../src/tracker/sinks/native.ts"],"sourcesContent":["import type { SlotMode } from '../config'\nimport { sendPayload } from '../transport'\nimport type { Sink, TrackerWindow } from '../types'\n\n/**\n * How a beacon says the page measured it: `c` cookieless, `a` anonymous. Full sends none, as a\n * tracker from before modes did; anything but those three reads as the strictest.\n */\nconst wireMode = (mode: SlotMode): 'c' | 'a' | undefined => {\n\tif (mode === 'full') {\n\t\treturn undefined\n\t}\n\treturn mode === 'cookieless' ? 'c' : 'a'\n}\n\n/**\n * Posts every event to the plugin's own ingest endpoint the moment it is sent, stamped with the\n * slot's mode at that moment. An item's display name stays behind: it is for the vendor slots, and\n * native stores the ref alone. Anonymous keeps no engagement, so none is sent.\n */\nexport const createNativeSink = (args: {\n\tslot: Sink['slot']\n\twin: TrackerWindow\n\turl: string\n\t/** The slot's mode as each event is sent. Unset, every event is sent in full. */\n\tmode?: () => SlotMode\n}): Sink => {\n\tconst { slot, win, url } = args\n\treturn {\n\t\tslot,\n\t\tready: () => Promise.resolve(),\n\t\tsend(event) {\n\t\t\tconst m = wireMode(args.mode?.() ?? 'full')\n\t\t\tif (m === 'a' && event.type === 'engagement') {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst { itemName: _itemName, ...wire } = event\n\t\t\tsendPayload(win, url, m === undefined ? wire : { ...wire, m })\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;AAQA,MAAM,YAAY,SAA0C;CAC3D,IAAI,SAAS,QACZ;CAED,OAAO,SAAS,eAAe,MAAM;AACtC;;;;;;AAOA,MAAa,oBAAoB,SAMrB;CACX,MAAM,EAAE,MAAM,KAAK,QAAQ;CAC3B,OAAO;EACN;EACA,aAAa,QAAQ,QAAQ;EAC7B,KAAK,OAAO;GACX,MAAM,IAAI,SAAS,KAAK,OAAO,KAAK,MAAM;GAC1C,IAAI,MAAM,OAAO,MAAM,SAAS,cAC/B;GAED,MAAM,EAAE,UAAU,WAAW,GAAG,SAAS;GACzC,YAAY,KAAK,KAAK,MAAM,KAAA,IAAY,OAAO;IAAE,GAAG;IAAM;GAAE,CAAC;EAC9D;CACD;AACD"}
@@ -1,4 +1,5 @@
1
- import { createVendorSink, itemProps, orderProps, vendorEventName, vendorGlobal, vendorStorageExclusion } from "./vendor.js";
1
+ import { readStorage } from "../storage.js";
2
+ import { createVendorSink, itemProps, orderProps, vendorEventName, vendorGlobal, vendorStorageSwitch } from "./vendor.js";
2
3
  //#region src/tracker/sinks/plausible.ts
3
4
  /**
4
5
  * Plausible's own opt-out flag, which its script checks before every event
@@ -11,8 +12,13 @@ const PLAUSIBLE_IGNORE_KEY = "plausible_ignore";
11
12
  */
12
13
  const createPlausibleSink = (args) => {
13
14
  const plausible = () => vendorGlobal(args.win, "plausible");
15
+ const ignore = vendorStorageSwitch(args.win, PLAUSIBLE_IGNORE_KEY, "true");
14
16
  return createVendorSink(args, {
15
- exclude: vendorStorageExclusion(args.win, PLAUSIBLE_IGNORE_KEY, "true"),
17
+ mode: (next) => {
18
+ ignore(next);
19
+ const sdk = plausible();
20
+ if (next.mode === "off" && sdk?.l === true && readStorage(args.win, "plausible_ignore") === "true") sdk("pageview");
21
+ },
16
22
  has: () => typeof plausible() === "function",
17
23
  dispatch: (event) => {
18
24
  const props = {
@@ -1 +1 @@
1
- {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/tracker/sinks/plausible.ts"],"sourcesContent":["import type { Sink } from '../types'\nimport {\n\tcreateVendorSink,\n\titemProps,\n\torderProps,\n\ttype VendorSinkArgs,\n\tvendorEventName,\n\tvendorGlobal,\n\tvendorStorageExclusion,\n} from './vendor'\n\n/**\n * Plausible's own opt-out flag, which its script checks before every event\n * (https://plausible.io/docs/excluding-localstorage).\n */\nexport const PLAUSIBLE_IGNORE_KEY = 'plausible_ignore'\n\ninterface PlausibleOptions {\n\tprops?: Record<string, unknown>\n\trevenue?: { amount: number; currency?: string }\n}\n\ntype Plausible = (name: string, options?: PlausibleOptions) => void\n\n/**\n * Forwards events and goals to the `plausible` queue, revenue in its ecommerce shape. Props are\n * scalars, so a sale's lines are left out and its order id travels as the `orderId` prop.\n */\nexport const createPlausibleSink = (args: VendorSinkArgs): Sink => {\n\tconst plausible = () => vendorGlobal<Plausible>(args.win, 'plausible')\n\treturn createVendorSink(args, {\n\t\texclude: vendorStorageExclusion(args.win, PLAUSIBLE_IGNORE_KEY, 'true'),\n\t\thas: () => typeof plausible() === 'function',\n\t\tdispatch: (event) => {\n\t\t\tconst props = { ...event.props, ...orderProps(event), ...itemProps(event) }\n\t\t\tconst options: PlausibleOptions = {\n\t\t\t\t...(Object.keys(props).length > 0 ? { props } : {}),\n\t\t\t\t...(event.value === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\trevenue: {\n\t\t\t\t\t\t\t\tamount: event.value,\n\t\t\t\t\t\t\t\t...(event.currency === undefined ? {} : { currency: event.currency }),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t}\n\t\t\tplausible()?.(vendorEventName(event), options)\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;AAeA,MAAa,uBAAuB;;;;;AAapC,MAAa,uBAAuB,SAA+B;CAClE,MAAM,kBAAkB,aAAwB,KAAK,KAAK,WAAW;CACrE,OAAO,iBAAiB,MAAM;EAC7B,SAAS,uBAAuB,KAAK,KAAK,sBAAsB,MAAM;EACtE,WAAW,OAAO,UAAU,MAAM;EAClC,WAAW,UAAU;GACpB,MAAM,QAAQ;IAAE,GAAG,MAAM;IAAO,GAAG,WAAW,KAAK;IAAG,GAAG,UAAU,KAAK;GAAE;GAC1E,MAAM,UAA4B;IACjC,GAAI,OAAO,KAAK,KAAK,EAAE,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;IACjD,GAAI,MAAM,UAAU,KAAA,IACjB,CAAC,IACD,EACA,SAAS;KACR,QAAQ,MAAM;KACd,GAAI,MAAM,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,MAAM,SAAS;IACpE,EACD;GACH;GACA,UAAU,IAAI,gBAAgB,KAAK,GAAG,OAAO;EAC9C;CACD,CAAC;AACF"}
1
+ {"version":3,"file":"plausible.js","names":[],"sources":["../../../src/tracker/sinks/plausible.ts"],"sourcesContent":["import { readStorage } from '../storage'\nimport type { Sink } from '../types'\nimport {\n\tcreateVendorSink,\n\titemProps,\n\torderProps,\n\ttype VendorSinkArgs,\n\tvendorEventName,\n\tvendorGlobal,\n\tvendorStorageSwitch,\n} from './vendor'\n\n/**\n * Plausible's own opt-out flag, which its script checks before every event\n * (https://plausible.io/docs/excluding-localstorage).\n */\nexport const PLAUSIBLE_IGNORE_KEY = 'plausible_ignore'\n\ninterface PlausibleOptions {\n\tprops?: Record<string, unknown>\n\trevenue?: { amount: number; currency?: string }\n}\n\ntype Plausible = ((name: string, options?: PlausibleOptions) => void) & {\n\t/** Set once Plausible's script replaced the snippet's queue stub. */\n\tl?: boolean\n}\n\n/**\n * Forwards events and goals to the `plausible` queue, revenue in its ecommerce shape. Props are\n * scalars, so a sale's lines are left out and its order id travels as the `orderId` prop.\n */\nexport const createPlausibleSink = (args: VendorSinkArgs): Sink => {\n\tconst plausible = () => vendorGlobal<Plausible>(args.win, 'plausible')\n\tconst ignore = vendorStorageSwitch(args.win, PLAUSIBLE_IGNORE_KEY, 'true')\n\treturn createVendorSink(args, {\n\t\tmode: (next) => {\n\t\t\tignore(next)\n\t\t\t// A running script checks the flag only on a pageview, and until one it keeps sending its\n\t\t\t// own engagement whenever the tab is hidden: a pageview it ignores stops that for the page.\n\t\t\t// With storage blocked the flag is not there, and the pageview would be counted.\n\t\t\tconst sdk = plausible()\n\t\t\tif (\n\t\t\t\tnext.mode === 'off' &&\n\t\t\t\tsdk?.l === true &&\n\t\t\t\treadStorage(args.win, PLAUSIBLE_IGNORE_KEY) === 'true'\n\t\t\t) {\n\t\t\t\tsdk('pageview')\n\t\t\t}\n\t\t},\n\t\thas: () => typeof plausible() === 'function',\n\t\tdispatch: (event) => {\n\t\t\tconst props = { ...event.props, ...orderProps(event), ...itemProps(event) }\n\t\t\tconst options: PlausibleOptions = {\n\t\t\t\t...(Object.keys(props).length > 0 ? { props } : {}),\n\t\t\t\t...(event.value === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\trevenue: {\n\t\t\t\t\t\t\t\tamount: event.value,\n\t\t\t\t\t\t\t\t...(event.currency === undefined ? {} : { currency: event.currency }),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t}\n\t\t\tplausible()?.(vendorEventName(event), options)\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;AAgBA,MAAa,uBAAuB;;;;;AAgBpC,MAAa,uBAAuB,SAA+B;CAClE,MAAM,kBAAkB,aAAwB,KAAK,KAAK,WAAW;CACrE,MAAM,SAAS,oBAAoB,KAAK,KAAK,sBAAsB,MAAM;CACzE,OAAO,iBAAiB,MAAM;EAC7B,OAAO,SAAS;GACf,OAAO,IAAI;GAIX,MAAM,MAAM,UAAU;GACtB,IACC,KAAK,SAAS,SACd,KAAK,MAAM,QACX,YAAY,KAAK,KAAA,kBAAyB,MAAM,QAEhD,IAAI,UAAU;EAEhB;EACA,WAAW,OAAO,UAAU,MAAM;EAClC,WAAW,UAAU;GACpB,MAAM,QAAQ;IAAE,GAAG,MAAM;IAAO,GAAG,WAAW,KAAK;IAAG,GAAG,UAAU,KAAK;GAAE;GAC1E,MAAM,UAA4B;IACjC,GAAI,OAAO,KAAK,KAAK,EAAE,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;IACjD,GAAI,MAAM,UAAU,KAAA,IACjB,CAAC,IACD,EACA,SAAS;KACR,QAAQ,MAAM;KACd,GAAI,MAAM,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU,MAAM,SAAS;IACpE,EACD;GACH;GACA,UAAU,IAAI,gBAAgB,KAAK,GAAG,OAAO;EAC9C;CACD,CAAC;AACF"}