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

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 (168) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/adapters/ga4/ga4.d.ts +7 -0
  3. package/dist/adapters/ga4/ga4.js +17 -3
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.d.ts +6 -0
  6. package/dist/adapters/plausible/plausible.js +6 -3
  7. package/dist/adapters/plausible/plausible.js.map +1 -1
  8. package/dist/adapters/posthog/posthog.d.ts +7 -0
  9. package/dist/adapters/posthog/posthog.js +92 -19
  10. package/dist/adapters/posthog/posthog.js.map +1 -1
  11. package/dist/adapters/posthog/projectCheck.js +56 -0
  12. package/dist/adapters/posthog/projectCheck.js.map +1 -0
  13. package/dist/adapters/umami/umami.d.ts +6 -0
  14. package/dist/adapters/umami/umami.js +3 -1
  15. package/dist/adapters/umami/umami.js.map +1 -1
  16. package/dist/capture/trackerConfig.js +29 -6
  17. package/dist/capture/trackerConfig.js.map +1 -1
  18. package/dist/capture/withoutConsent.js +91 -0
  19. package/dist/capture/withoutConsent.js.map +1 -0
  20. package/dist/core/capture.d.ts +41 -11
  21. package/dist/core/captureOptions.js +97 -8
  22. package/dist/core/captureOptions.js.map +1 -1
  23. package/dist/core/contract.d.ts +25 -0
  24. package/dist/core/contract.js.map +1 -1
  25. package/dist/core/options.d.ts +24 -2
  26. package/dist/core/options.js.map +1 -1
  27. package/dist/core/sourceOptions.js +2 -1
  28. package/dist/core/sourceOptions.js.map +1 -1
  29. package/dist/exports/adapters/contract.d.ts +3 -3
  30. package/dist/exports/adapters/ga4.d.ts +4 -4
  31. package/dist/exports/adapters/native.d.ts +5 -5
  32. package/dist/exports/adapters/plausible.d.ts +4 -4
  33. package/dist/exports/adapters/posthog.d.ts +4 -4
  34. package/dist/exports/adapters/umami.d.ts +4 -4
  35. package/dist/exports/next.d.ts +4 -4
  36. package/dist/exports/react.d.ts +3 -2
  37. package/dist/exports/site.d.ts +2 -2
  38. package/dist/exports/testing.d.ts +4 -4
  39. package/dist/exports/tracker.d.ts +3 -2
  40. package/dist/exports/types.d.ts +5 -5
  41. package/dist/index.d.ts +5 -5
  42. package/dist/index.js +2 -0
  43. package/dist/index.js.map +1 -1
  44. package/dist/native/collections/hits.js +1 -0
  45. package/dist/native/collections/hits.js.map +1 -1
  46. package/dist/native/engine/engine.js +5 -1
  47. package/dist/native/engine/engine.js.map +1 -1
  48. package/dist/native/engine/planner.js +2 -1
  49. package/dist/native/engine/planner.js.map +1 -1
  50. package/dist/native/engine/toHit.js +4 -2
  51. package/dist/native/engine/toHit.js.map +1 -1
  52. package/dist/native/ingest/endpoint.js +5 -2
  53. package/dist/native/ingest/endpoint.js.map +1 -1
  54. package/dist/native/ingest/normalizeEvent.d.ts +6 -1
  55. package/dist/native/ingest/normalizeEvent.js +17 -7
  56. package/dist/native/ingest/normalizeEvent.js.map +1 -1
  57. package/dist/native/ingest/serverTrack.js +2 -1
  58. package/dist/native/ingest/serverTrack.js.map +1 -1
  59. package/dist/native/ingest/validate.js +3 -0
  60. package/dist/native/ingest/validate.js.map +1 -1
  61. package/dist/native/nativeAdapter.d.ts +10 -1
  62. package/dist/native/nativeAdapter.js +11 -1
  63. package/dist/native/nativeAdapter.js.map +1 -1
  64. package/dist/native/store/aggregate.js +1 -1
  65. package/dist/native/store/aggregate.js.map +1 -1
  66. package/dist/native/store/hitRow.js +3 -0
  67. package/dist/native/store/hitRow.js.map +1 -1
  68. package/dist/native/store/hits.js +3 -1
  69. package/dist/native/store/hits.js.map +1 -1
  70. package/dist/native/store/mongo/aggregatePipelines.js +10 -2
  71. package/dist/native/store/mongo/aggregatePipelines.js.map +1 -1
  72. package/dist/native/store/mongo/pipelines.js +15 -5
  73. package/dist/native/store/mongo/pipelines.js.map +1 -1
  74. package/dist/native/store/parts.js +9 -3
  75. package/dist/native/store/parts.js.map +1 -1
  76. package/dist/native/store/rawRead.js +6 -3
  77. package/dist/native/store/rawRead.js.map +1 -1
  78. package/dist/native/store/sql/aggregateSql.js +6 -2
  79. package/dist/native/store/sql/aggregateSql.js.map +1 -1
  80. package/dist/native/store/sql/columns.js +1 -0
  81. package/dist/native/store/sql/columns.js.map +1 -1
  82. package/dist/native/store/sql/compile.js +19 -7
  83. package/dist/native/store/sql/compile.js.map +1 -1
  84. package/dist/native/store/types.d.ts +7 -1
  85. package/dist/native/store/types.js +10 -0
  86. package/dist/native/store/types.js.map +1 -0
  87. package/dist/plugin/createRuntime.js +10 -1
  88. package/dist/plugin/createRuntime.js.map +1 -1
  89. package/dist/plugin/runtime.js.map +1 -1
  90. package/dist/providers/collection.d.ts +2 -0
  91. package/dist/providers/collection.js +22 -1
  92. package/dist/providers/collection.js.map +1 -1
  93. package/dist/providers/factory.d.ts +9 -1
  94. package/dist/providers/factory.js +14 -5
  95. package/dist/providers/factory.js.map +1 -1
  96. package/dist/providers/registry.js +2 -1
  97. package/dist/providers/registry.js.map +1 -1
  98. package/dist/react/AnalyticsProvider.d.ts +6 -0
  99. package/dist/react/AnalyticsProvider.js.map +1 -1
  100. package/dist/react/useAnalytics.js +9 -5
  101. package/dist/react/useAnalytics.js.map +1 -1
  102. package/dist/site/AnalyticsScripts.d.ts +4 -3
  103. package/dist/site/AnalyticsScripts.js +18 -4
  104. package/dist/site/AnalyticsScripts.js.map +1 -1
  105. package/dist/surfacing/todaySplit.js +7 -1
  106. package/dist/surfacing/todaySplit.js.map +1 -1
  107. package/dist/tracker/config.d.ts +26 -1
  108. package/dist/tracker/config.js.map +1 -1
  109. package/dist/tracker/createTracker.d.ts +2 -1
  110. package/dist/tracker/createTracker.js +91 -59
  111. package/dist/tracker/createTracker.js.map +1 -1
  112. package/dist/tracker/gate.d.ts +8 -0
  113. package/dist/tracker/gate.js +61 -11
  114. package/dist/tracker/gate.js.map +1 -1
  115. package/dist/tracker/loadScript.js +2 -1
  116. package/dist/tracker/loadScript.js.map +1 -1
  117. package/dist/tracker/registry.js +14 -3
  118. package/dist/tracker/registry.js.map +1 -1
  119. package/dist/tracker/sinks/createSink.js +27 -8
  120. package/dist/tracker/sinks/createSink.js.map +1 -1
  121. package/dist/tracker/sinks/ga4.js +38 -6
  122. package/dist/tracker/sinks/ga4.js.map +1 -1
  123. package/dist/tracker/sinks/native.js +17 -3
  124. package/dist/tracker/sinks/native.js.map +1 -1
  125. package/dist/tracker/sinks/plausible.js +8 -2
  126. package/dist/tracker/sinks/plausible.js.map +1 -1
  127. package/dist/tracker/sinks/posthog.js +108 -16
  128. package/dist/tracker/sinks/posthog.js.map +1 -1
  129. package/dist/tracker/sinks/umami.js +2 -2
  130. package/dist/tracker/sinks/umami.js.map +1 -1
  131. package/dist/tracker/sinks/vendor.js +25 -11
  132. package/dist/tracker/sinks/vendor.js.map +1 -1
  133. package/dist/tracker/types.d.ts +10 -3
  134. package/dist/translations/ar.js +7 -0
  135. package/dist/translations/ar.js.map +1 -1
  136. package/dist/translations/de.js +7 -0
  137. package/dist/translations/de.js.map +1 -1
  138. package/dist/translations/en.js +7 -0
  139. package/dist/translations/en.js.map +1 -1
  140. package/dist/translations/es.js +7 -0
  141. package/dist/translations/es.js.map +1 -1
  142. package/dist/translations/fr.js +7 -0
  143. package/dist/translations/fr.js.map +1 -1
  144. package/dist/translations/id.js +7 -0
  145. package/dist/translations/id.js.map +1 -1
  146. package/dist/translations/keys.d.ts +7 -0
  147. package/dist/translations/keys.js +8 -1
  148. package/dist/translations/keys.js.map +1 -1
  149. package/dist/translations/ko.js +7 -0
  150. package/dist/translations/ko.js.map +1 -1
  151. package/dist/translations/pt.js +7 -0
  152. package/dist/translations/pt.js.map +1 -1
  153. package/dist/translations/ru.js +7 -0
  154. package/dist/translations/ru.js.map +1 -1
  155. package/dist/translations/uk.js +7 -0
  156. package/dist/translations/uk.js.map +1 -1
  157. package/dist/translations/zh.js +7 -0
  158. package/dist/translations/zh.js.map +1 -1
  159. package/dist/view/consentShare.js +15 -0
  160. package/dist/view/consentShare.js.map +1 -0
  161. package/dist/view/sections/OverviewCards.js +38 -28
  162. package/dist/view/sections/OverviewCards.js.map +1 -1
  163. package/dist/widgets/notices.js +6 -1
  164. package/dist/widgets/notices.js.map +1 -1
  165. package/dist/widgets/readMeta.d.ts +4 -0
  166. package/dist/widgets/readMeta.js +5 -0
  167. package/dist/widgets/readMeta.js.map +1 -1
  168. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","names":[],"sources":["../../src/providers/registry.ts"],"sourcesContent":["import { createLocalReq, type Payload } from 'payload'\nimport { currentTime } from '../core/clock'\nimport { isCollectionSlug } from '../core/collectionSlug'\nimport type { AnalyticsAdapter, AnalyticsCapabilities } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { ProvidersResolve } from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { SourceMisconfiguredError } from '../core/sourceErrors'\nimport { throttled } from '../core/throttle'\nimport { isRecord, valueAt } from '../core/values'\nimport { loadEncrypted } from '../plugin/encrypted'\nimport { GA4_SDK_WARNING, isProductionBuild } from '../plugin/peers'\nimport { remember } from '../surfacing/bounded'\nimport { createEpochFallback, type EpochStore, FIXED_CONFIG_EPOCH } from '../surfacing/epoch'\nimport { createAdapterPool, type PooledDocument } from './adapterPool'\nimport {\n\tadapterFromProviderDoc,\n\tdocumentAdapterId,\n\tfailingAdapter,\n\tPROVIDER_IDS,\n\ttype ProviderDoc,\n\ttype ProviderId,\n} from './factory'\nimport type { ProviderHostPolicy } from './hosts'\nimport { createCollectionProbe, type Probe, type ProbeRow, scopeOf, versionOf } from './probe'\nimport {\n\tcombineRegistries,\n\tnoGuardedConnection,\n\ttype ProviderAdapter,\n\tproviderScopeWhere,\n\ttype RegistryBase,\n} from './resolver'\nimport { SECRET_PATHS } from './secrets'\n\n/** How often a failing probe is reported, at most. */\nconst WARN_EVERY_MS = 60_000\n\n/**\n * How long a document whose adapter could not be built (its secrets did not decrypt, its settings\n * threw) stands in as a failing source before its scope's registry reads it again.\n */\nexport const FAILED_DOCUMENT_RETRY_MS = 60_000\n\n/** Where an install's runtime provider adapters come from. */\nexport type ProviderPlan =\n\t| { kind: 'static' }\n\t| {\n\t\t\tkind: 'collection'\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\t/** Types the install serves, every one when absent; a document of another is no source. */\n\t\t\ttypes?: readonly ProviderId[]\n\t\t\t/** The install's config native adapter, which a `native` document grants to its scope. */\n\t\t\tnativeAdapter?: AnalyticsAdapter\n\t }\n\t| { kind: 'resolve'; resolve: ProvidersResolve }\n\ninterface ProviderRegistryOptions {\n\tpayload: Payload\n\tplan: ProviderPlan\n\t/** The config adapters every scope's registry starts from. */\n\tbase: RegistryBase\n\t/** The config registry as an install without runtime providers hands it out. */\n\tregistry: AdapterRegistry\n\t/** Applied to every scope's registry: revenue removed on an install that measures no money. */\n\tnarrow: (registry: AdapterRegistry) => AdapterRegistry\n\thosts: ProviderHostPolicy\n\t/** Missing, every document adapter refuses rather than going out unguarded. */\n\tfetch: FetchLike | undefined\n\tsdks: AnalyticsSdks\n\t/** A `providers.resolve` install's configuration tokens, which `refresh` bumps. */\n\ttokens?: EpochStore\n\tnow?: () => number\n}\n\n/** One instance's runtime provider adapters, and the epoch that says when they changed. */\ninterface ProviderRegistry {\n\tresolve: RegistryResolver\n\t/** The scope's provider configuration epoch, which every cache key carries. */\n\tepoch(scope: string | null): Promise<string>\n\t/**\n\t * Whether the scope's own available documents grant `adapterId`, as its registry does. The native\n\t * adapter is answered from the committed rows alone, decrypting nothing, so a beacon stays cheap.\n\t * Only on the providers collection.\n\t */\n\tgranted?(scope: string | null, adapterId: string): Promise<boolean>\n\t/** A save on this instance touched these scopes, which it then reads again as soon as it commits. */\n\tchanged(scopes: Iterable<string | null>): void\n\t/** Retires the scope's cached reads on every instance: `refreshProviders()`. */\n\trefresh(scope: string | null): Promise<void>\n\tclose(): Promise<void>\n}\n\ntype DecryptFieldValue = Awaited<ReturnType<typeof loadEncrypted>>['decryptFieldValue']\n\n/** Sets a `group.field` secret in place; a document without that group is left as it is. */\nconst setAtPath = (doc: Record<string, unknown>, path: string, value: string): void => {\n\tconst [group = '', field] = path.split('.')\n\tconst target = doc[group]\n\tif (field !== undefined && isRecord(target)) {\n\t\ttarget[field] = value\n\t}\n}\n\n/** The secrets a document stores, by path; blank ones are left out. */\nconst storedSecrets = (doc: Record<string, unknown>): Array<{ path: string; value: string }> =>\n\tSECRET_PATHS.flatMap(({ path }) => {\n\t\tconst value = valueAt(doc, path)\n\t\treturn typeof value === 'string' && value !== '' ? [{ path, value }] : []\n\t})\n\nconst refOf = (doc: { id: string; version: string }): string => `${doc.id}@${doc.version}`\n\n/** The registry of an install without runtime providers: the config adapters, for every scope. */\nconst staticRegistry = (options: ProviderRegistryOptions): ProviderRegistry => ({\n\tresolve: async () => ({ registry: options.registry, grants: NO_GRANTS }),\n\tepoch: async () => FIXED_CONFIG_EPOCH,\n\tchanged: () => {},\n\trefresh: async () => {},\n\tclose: async () => {},\n})\n\n/**\n * `providers.resolve`: the host's function answers every read, uncached, and the configuration\n * epoch is a token the host bumps through `refreshProviders()` once it changed its own storage.\n */\nconst resolveRegistry = (\n\toptions: ProviderRegistryOptions,\n\tresolve: ProvidersResolve\n): ProviderRegistry => {\n\tconst { tokens } = options\n\treturn {\n\t\tresolve: async ({ payload, req, scope }) => {\n\t\t\tconst adapters = await resolve({\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t\tscope,\n\t\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\t\thosts: options.hosts,\n\t\t\t\tsdks: options.sdks,\n\t\t\t})\n\t\t\tconst combined = combineRegistries(\n\t\t\t\toptions.base,\n\t\t\t\tadapters.map((adapter) => ({ adapter, docId: adapter.id }))\n\t\t\t)\n\t\t\treturn { ...combined, registry: options.narrow(combined.registry) }\n\t\t},\n\t\tepoch: (scope) => tokens?.get(scope) ?? Promise.resolve(FIXED_CONFIG_EPOCH),\n\t\tchanged: () => {},\n\t\trefresh: async (scope) => {\n\t\t\tawait tokens?.bump(scope)\n\t\t},\n\t\tclose: async () => {},\n\t}\n}\n\ninterface CachedRegistry {\n\tepoch: string\n\tresolved: Promise<ScopeRegistry>\n\t/** The enabled documents it was built from, kept in use while it is handed out. */\n\tids: readonly string[]\n\t/** Each as `id@updatedAt`, so disposing a version drops exactly the registries built on it. */\n\trefs: ReadonlySet<string>\n\t/** Set when a document stood in as a failing source: the registry is built again from then on. */\n\tretryAt?: number\n}\n\n/** What one document built: its adapter, or a stand-in when it could not be read. */\ntype Built =\n\t| { ok: true; adapter: AnalyticsAdapter | null }\n\t| { ok: false; standIn: AnalyticsAdapter }\n\n/** What a stand-in declares when the document's settings build nothing even without its secrets. */\nconst STAND_IN_CAPABILITIES: AnalyticsCapabilities = {\n\trealtime: false,\n\tminGranularity: 'day',\n\tmaxLookbackDays: null,\n\tmetrics: new Set(['pageviews', 'visitors']),\n\tdimensions: new Set(),\n\tfilters: {},\n\trateLimit: null,\n\trecommendedTtl: { realtime: 60, aggregate: 60 },\n}\n\n/**\n * Stands in while a document's adapter cannot be built: keeps its identity, and its capabilities\n * where settings build without secrets; reads fail as `source_misconfigured`, capture none.\n */\nconst standInFor = (\n\traw: Record<string, unknown>,\n\tcause: unknown,\n\tbuild: (doc: Record<string, unknown>) => AnalyticsAdapter | null\n): AnalyticsAdapter => {\n\tconst blank = structuredClone(raw)\n\tfor (const { path } of storedSecrets(blank)) {\n\t\tsetAtPath(blank, path, '')\n\t}\n\tlet shape: AnalyticsAdapter | null = null\n\ttry {\n\t\tshape = build(blank)\n\t} catch {\n\t\tshape = null\n\t}\n\tconst id = documentAdapterId(raw.provider, raw.id)\n\treturn failingAdapter(\n\t\t{\n\t\t\tid,\n\t\t\tlabel: shape?.label ?? (typeof raw.name === 'string' && raw.name !== '' ? raw.name : id),\n\t\t\tcapabilities: shape?.capabilities ?? STAND_IN_CAPABILITIES,\n\t\t\trealtime: shape?.realtime,\n\t\t},\n\t\t() =>\n\t\t\tnew SourceMisconfiguredError(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" could not be read; check its settings and keys`,\n\t\t\t\t{ cause }\n\t\t\t)\n\t)\n}\n\n/**\n * A scope's registry is cached under the epoch the probe reads before any document, so it is never\n * filed under an older epoch. Only unseen document versions are read and decrypted.\n */\nconst collectionRegistry = (\n\toptions: ProviderRegistryOptions,\n\tplan: Extract<ProviderPlan, { kind: 'collection' }>\n): ProviderRegistry => {\n\tconst { payload, now } = options\n\tconst { slug } = plan\n\tconst probe = createCollectionProbe({\n\t\tpayload,\n\t\tslug,\n\t\tscopeField: plan.scopeField,\n\t\twhere: (scope) => providerScopeWhere(plan.scopeField, scope),\n\t\tprovider: true,\n\t\t...(now ? { now } : {}),\n\t})\n\tconst registries = new Map<string, CachedRegistry>()\n\tconst pool = createAdapterPool({\n\t\tpayload,\n\t\t...(now ? { now } : {}),\n\t\tonDispose: (doc) => {\n\t\t\tconst ref = refOf(doc)\n\t\t\tfor (const [key, cached] of registries) {\n\t\t\t\tif (cached.refs.has(ref)) {\n\t\t\t\t\tregistries.delete(key)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\tlet warnedGa4 = false\n\tconst clock = now ?? currentTime\n\tconst warnProbeFailed = throttled((message) => payload.logger?.warn(message), {\n\t\tnow: clock,\n\t\tintervalMs: WARN_EVERY_MS,\n\t})\n\t// A failing probe keys on the last epoch read, which the registry in use was built from.\n\tconst fallback = createEpochFallback(clock)\n\tconst types: readonly string[] = plan.types ?? PROVIDER_IDS\n\n\t/** An enabled document of a type the install serves, which its adapter may then make a source. */\n\tconst servable = (row: ProbeRow): boolean => row.enabled && types.includes(row.provider ?? '')\n\n\t/** A probed id as the collection stores it: rows carry every id as text. */\n\tconst idOf = (id: string): string | number => {\n\t\tconst custom = isCollectionSlug(payload, slug)\n\t\t\t? payload.collections[slug]?.customIDType\n\t\t\t: undefined\n\t\treturn (custom ?? payload.db.defaultIDType) === 'number' && /^\\d+$/.test(id) ? Number(id) : id\n\t}\n\n\tconst fromDocument = (doc: Record<string, unknown>): AnalyticsAdapter | null =>\n\t\t// A row of the providers collection, whose fields `ProviderDoc` mirrors.\n\t\tadapterFromProviderDoc(doc as ProviderDoc, {\n\t\t\t...(plan.nativeAdapter ? { native: plan.nativeAdapter } : {}),\n\t\t\thosts: options.hosts,\n\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\tsdks: options.sdks,\n\t\t})\n\n\tconst adapterOf = async (\n\t\traw: Record<string, unknown>,\n\t\tdecrypt: DecryptFieldValue\n\t): Promise<Built> => {\n\t\ttry {\n\t\t\tconst doc = structuredClone(raw)\n\t\t\tfor (const { path, value } of storedSecrets(doc)) {\n\t\t\t\tconst plain = await decrypt(payload, { collection: slug, path, value })\n\t\t\t\tsetAtPath(doc, path, typeof plain === 'string' ? plain : '')\n\t\t\t}\n\t\t\tconst adapter = fromDocument(doc)\n\t\t\t// The first GA4 document is the earliest this install shows it reads GA4 at all.\n\t\t\tif (raw.provider === 'ga4' && !options.sdks.ga4 && !warnedGa4 && isProductionBuild()) {\n\t\t\t\twarnedGa4 = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t\treturn { ok: true, adapter }\n\t\t} catch (err) {\n\t\t\t// A corrupt or key-rotated ciphertext must neither take the scope's registry down nor drop\n\t\t\t// the source silently: it stands in as a failing source until the retry.\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" (${String(raw.provider)}) could not be read, its reads fail until it can: ${String(err)}`\n\t\t\t)\n\t\t\treturn { ok: false, standIn: standInFor(raw, err, fromDocument) }\n\t\t}\n\t}\n\n\t/**\n\t * Reads and builds the documents the pool has no adapter for, answering each by id. A stand-in\n\t * is never pooled, so the document is read again once its registry expires.\n\t */\n\tconst buildDocuments = async (\n\t\tscope: string | null,\n\t\tids: readonly string[]\n\t): Promise<{ built: Map<string, AnalyticsAdapter | null>; failed: boolean }> => {\n\t\tif (!isCollectionSlug(payload, slug)) {\n\t\t\tthrow new Error(`analytics: no \"${slug}\" collection is registered for the providers`)\n\t\t}\n\t\tconst { decryptFieldValue, withRawEncrypted } = await loadEncrypted()\n\t\t// Never the caller's: the raw window is not a concurrency boundary, so a request shared with\n\t\t// other reads would hand them ciphertext, and it may also hold an uncommitted transaction.\n\t\tconst req = await createLocalReq({}, payload)\n\t\tconst { docs } = await withRawEncrypted(req, () =>\n\t\t\tpayload.find({\n\t\t\t\tcollection: slug,\n\t\t\t\twhere: {\n\t\t\t\t\tand: [\n\t\t\t\t\t\t{ id: { in: ids.map(idOf) } },\n\t\t\t\t\t\t{ enabled: { equals: true } },\n\t\t\t\t\t\tproviderScopeWhere(plan.scopeField, scope),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tlimit: ids.length,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\toverrideAccess: true,\n\t\t\t\treq,\n\t\t\t})\n\t\t)\n\t\tconst found: unknown[] = docs\n\t\tconst built = new Map<string, AnalyticsAdapter | null>()\n\t\tlet failed = false\n\t\tfor (const raw of found.filter(isRecord)) {\n\t\t\tconst doc: PooledDocument = { id: String(raw.id), version: versionOf(raw.updatedAt), scope }\n\t\t\tconst outcome = await adapterOf(raw, decryptFieldValue)\n\t\t\tif (outcome.ok) {\n\t\t\t\tbuilt.set(doc.id, pool.put(doc, outcome.adapter, raw.provider !== 'native'))\n\t\t\t} else {\n\t\t\t\tbuilt.set(doc.id, outcome.standIn)\n\t\t\t\tfailed = true\n\t\t\t}\n\t\t}\n\t\treturn { built, failed }\n\t}\n\n\tconst build = async (\n\t\tscope: string | null,\n\t\tdocs: readonly PooledDocument[],\n\t\tflagged: ReadonlySet<string>\n\t): Promise<{ registry: ScopeRegistry; failed: boolean }> => {\n\t\tconst missing = docs.filter((doc) => pool.get(doc) === undefined).map((doc) => doc.id)\n\t\tconst read = missing.length > 0 ? await buildDocuments(scope, missing) : undefined\n\t\tconst extras: ProviderAdapter[] = []\n\t\tfor (const doc of docs) {\n\t\t\tconst adapter = read?.built.has(doc.id) ? read.built.get(doc.id) : pool.get(doc)\n\t\t\t// Lacking what its adapter reads with, a document is no source and grants nothing; a\n\t\t\t// stand-in for one that failed to decrypt still is, configured but failing.\n\t\t\tif (adapter?.isConfigured()) {\n\t\t\t\textras.push({ adapter, docId: doc.id, isDefault: flagged.has(doc.id) })\n\t\t\t}\n\t\t}\n\t\tpool.retain(scope, new Set(docs.map((doc) => doc.id)))\n\t\tconst combined = combineRegistries(options.base, extras)\n\t\treturn {\n\t\t\tregistry: { ...combined, registry: options.narrow(combined.registry) },\n\t\t\tfailed: read?.failed === true,\n\t\t}\n\t}\n\n\tconst probed = async (scope: string | null): Promise<Probe | undefined> => {\n\t\ttry {\n\t\t\treturn await probe.read(scope)\n\t\t} catch (err) {\n\t\t\twarnProbeFailed(\n\t\t\t\t`analytics: reading the provider documents failed, cached reads key on the last epoch this instance read: ${String(err)}`\n\t\t\t)\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tconst isCurrent = (cached: CachedRegistry, epoch: string): boolean =>\n\t\tcached.epoch === epoch && (cached.retryAt === undefined || clock() < cached.retryAt)\n\n\tconst registryOf = async (scope: string | null): Promise<ScopeRegistry> => {\n\t\tconst key = scope ?? ''\n\t\tconst state = await probe.read(scope)\n\t\tfallback.read(scope, state.epoch)\n\t\tconst cached = registries.get(key)\n\t\tif (cached && isCurrent(cached, state.epoch)) {\n\t\t\tpool.touch(cached.ids)\n\t\t\treturn cached.resolved\n\t\t}\n\t\tconst rows = state.rows.filter(servable)\n\t\tconst docs: PooledDocument[] = rows.map((row) => ({\n\t\t\tid: row.id,\n\t\t\tversion: row.updatedAt,\n\t\t\tscope,\n\t\t}))\n\t\tconst flagged = new Set(rows.filter((row) => row.isDefault).map((row) => row.id))\n\t\tconst built = build(scope, docs, flagged)\n\t\tconst entry: CachedRegistry = {\n\t\t\tepoch: state.epoch,\n\t\t\tresolved: built.then((done) => done.registry),\n\t\t\tids: docs.map((doc) => doc.id),\n\t\t\trefs: new Set(docs.map(refOf)),\n\t\t}\n\t\tbuilt.then(\n\t\t\t(done) => {\n\t\t\t\tif (done.failed) {\n\t\t\t\t\tentry.retryAt = clock() + FAILED_DOCUMENT_RETRY_MS\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {}\n\t\t)\n\t\tremember(registries, [key, entry])\n\t\tentry.resolved.catch(() => {\n\t\t\tif (registries.get(key) === entry) {\n\t\t\t\tregistries.delete(key)\n\t\t\t}\n\t\t})\n\t\treturn entry.resolved\n\t}\n\n\treturn {\n\t\tresolve: (args) => registryOf(scopeOf(args.scope)),\n\t\tepoch: async (raw) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst state = await probed(scope)\n\t\t\treturn state ? fallback.read(scope, state.epoch) : fallback.failed(scope)\n\t\t},\n\t\tgranted: async (raw, adapterId) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst native = plan.nativeAdapter\n\t\t\tif (native && native.id === adapterId) {\n\t\t\t\tconst { rows } = await probe.read(scope)\n\t\t\t\treturn (\n\t\t\t\t\tnative.isConfigured() && rows.some((row) => row.provider === 'native' && servable(row))\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn (await registryOf(scope)).grants.has(adapterId)\n\t\t},\n\t\tchanged: (scopes) => probe.expedite(scopes),\n\t\trefresh: async (scope) => probe.expedite([scope]),\n\t\tclose: () => pool.close(),\n\t}\n}\n\n/** The runtime provider registry of one Payload instance, for the install's plan. */\nexport const createProviderRegistry = (options: ProviderRegistryOptions): ProviderRegistry => {\n\tconst { plan } = options\n\tswitch (plan.kind) {\n\t\tcase 'collection':\n\t\t\treturn collectionRegistry(options, plan)\n\t\tcase 'resolve':\n\t\t\treturn resolveRegistry(options, plan.resolve)\n\t\tdefault:\n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AS;EACtD;EACA,UAAU,WAAW,MAAM,SAAS,MAAM;EAC1C,SAAS,OAAO,UAAU,MAAM,SAAS,CAAC,KAAK,CAAC;EAChD,aAAa,KAAK,MAAM;CACzB;AACD;;AAGA,MAAa,0BAA0B,YAAuD;CAC7F,MAAM,EAAE,SAAS;CACjB,QAAQ,KAAK,MAAb;EACC,KAAK,cACJ,OAAO,mBAAmB,SAAS,IAAI;EACxC,KAAK,WACJ,OAAO,gBAAgB,SAAS,KAAK,OAAO;EAC7C,SACC,OAAO,eAAe,OAAO;CAC/B;AACD"}
1
+ {"version":3,"file":"registry.js","names":[],"sources":["../../src/providers/registry.ts"],"sourcesContent":["import { createLocalReq, type Payload } from 'payload'\nimport { currentTime } from '../core/clock'\nimport { isCollectionSlug } from '../core/collectionSlug'\nimport type { AnalyticsAdapter, AnalyticsCapabilities } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { ProvidersResolve } from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { SourceMisconfiguredError } from '../core/sourceErrors'\nimport { throttled } from '../core/throttle'\nimport { isRecord, valueAt } from '../core/values'\nimport { loadEncrypted } from '../plugin/encrypted'\nimport { GA4_SDK_WARNING, isProductionBuild } from '../plugin/peers'\nimport { remember } from '../surfacing/bounded'\nimport { createEpochFallback, type EpochStore, FIXED_CONFIG_EPOCH } from '../surfacing/epoch'\nimport { createAdapterPool, type PooledDocument } from './adapterPool'\nimport {\n\tadapterFromProviderDoc,\n\tdocumentAdapterId,\n\tfailingAdapter,\n\tPROVIDER_IDS,\n\ttype ProviderDoc,\n\ttype ProviderFactoryContext,\n\ttype ProviderId,\n} from './factory'\nimport type { ProviderHostPolicy } from './hosts'\nimport { createCollectionProbe, type Probe, type ProbeRow, scopeOf, versionOf } from './probe'\nimport {\n\tcombineRegistries,\n\tnoGuardedConnection,\n\ttype ProviderAdapter,\n\tproviderScopeWhere,\n\ttype RegistryBase,\n} from './resolver'\nimport { SECRET_PATHS } from './secrets'\n\n/** How often a failing probe is reported, at most. */\nconst WARN_EVERY_MS = 60_000\n\n/**\n * How long a document whose adapter could not be built (its secrets did not decrypt, its settings\n * threw) stands in as a failing source before its scope's registry reads it again.\n */\nexport const FAILED_DOCUMENT_RETRY_MS = 60_000\n\n/** Where an install's runtime provider adapters come from. */\nexport type ProviderPlan =\n\t| { kind: 'static' }\n\t| {\n\t\t\tkind: 'collection'\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\t/** Types the install serves, every one when absent; a document of another is no source. */\n\t\t\ttypes?: readonly ProviderId[]\n\t\t\t/** The install's config native adapter, which a `native` document grants to its scope. */\n\t\t\tnativeAdapter?: AnalyticsAdapter\n\t }\n\t| { kind: 'resolve'; resolve: ProvidersResolve }\n\ninterface ProviderRegistryOptions {\n\tpayload: Payload\n\tplan: ProviderPlan\n\t/** How every document's adapter counts without consent beyond its own setting. */\n\twithoutConsent?: Pick<\n\t\tProviderFactoryContext,\n\t\t'heldWithoutConsent' | 'followingCountsWithoutConsent'\n\t>\n\t/** The config adapters every scope's registry starts from. */\n\tbase: RegistryBase\n\t/** The config registry as an install without runtime providers hands it out. */\n\tregistry: AdapterRegistry\n\t/** Applied to every scope's registry: revenue removed on an install that measures no money. */\n\tnarrow: (registry: AdapterRegistry) => AdapterRegistry\n\thosts: ProviderHostPolicy\n\t/** Missing, every document adapter refuses rather than going out unguarded. */\n\tfetch: FetchLike | undefined\n\tsdks: AnalyticsSdks\n\t/** A `providers.resolve` install's configuration tokens, which `refresh` bumps. */\n\ttokens?: EpochStore\n\tnow?: () => number\n}\n\n/** One instance's runtime provider adapters, and the epoch that says when they changed. */\ninterface ProviderRegistry {\n\tresolve: RegistryResolver\n\t/** The scope's provider configuration epoch, which every cache key carries. */\n\tepoch(scope: string | null): Promise<string>\n\t/**\n\t * Whether the scope's own available documents grant `adapterId`, as its registry does. The native\n\t * adapter is answered from the committed rows alone, decrypting nothing, so a beacon stays cheap.\n\t * Only on the providers collection.\n\t */\n\tgranted?(scope: string | null, adapterId: string): Promise<boolean>\n\t/** A save on this instance touched these scopes, which it then reads again as soon as it commits. */\n\tchanged(scopes: Iterable<string | null>): void\n\t/** Retires the scope's cached reads on every instance: `refreshProviders()`. */\n\trefresh(scope: string | null): Promise<void>\n\tclose(): Promise<void>\n}\n\ntype DecryptFieldValue = Awaited<ReturnType<typeof loadEncrypted>>['decryptFieldValue']\n\n/** Sets a `group.field` secret in place; a document without that group is left as it is. */\nconst setAtPath = (doc: Record<string, unknown>, path: string, value: string): void => {\n\tconst [group = '', field] = path.split('.')\n\tconst target = doc[group]\n\tif (field !== undefined && isRecord(target)) {\n\t\ttarget[field] = value\n\t}\n}\n\n/** The secrets a document stores, by path; blank ones are left out. */\nconst storedSecrets = (doc: Record<string, unknown>): Array<{ path: string; value: string }> =>\n\tSECRET_PATHS.flatMap(({ path }) => {\n\t\tconst value = valueAt(doc, path)\n\t\treturn typeof value === 'string' && value !== '' ? [{ path, value }] : []\n\t})\n\nconst refOf = (doc: { id: string; version: string }): string => `${doc.id}@${doc.version}`\n\n/** The registry of an install without runtime providers: the config adapters, for every scope. */\nconst staticRegistry = (options: ProviderRegistryOptions): ProviderRegistry => ({\n\tresolve: async () => ({ registry: options.registry, grants: NO_GRANTS }),\n\tepoch: async () => FIXED_CONFIG_EPOCH,\n\tchanged: () => {},\n\trefresh: async () => {},\n\tclose: async () => {},\n})\n\n/**\n * `providers.resolve`: the host's function answers every read, uncached, and the configuration\n * epoch is a token the host bumps through `refreshProviders()` once it changed its own storage.\n */\nconst resolveRegistry = (\n\toptions: ProviderRegistryOptions,\n\tresolve: ProvidersResolve\n): ProviderRegistry => {\n\tconst { tokens } = options\n\treturn {\n\t\tresolve: async ({ payload, req, scope }) => {\n\t\t\tconst adapters = await resolve({\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t\tscope,\n\t\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\t\thosts: options.hosts,\n\t\t\t\tsdks: options.sdks,\n\t\t\t})\n\t\t\tconst combined = combineRegistries(\n\t\t\t\toptions.base,\n\t\t\t\tadapters.map((adapter) => ({ adapter, docId: adapter.id }))\n\t\t\t)\n\t\t\treturn { ...combined, registry: options.narrow(combined.registry) }\n\t\t},\n\t\tepoch: (scope) => tokens?.get(scope) ?? Promise.resolve(FIXED_CONFIG_EPOCH),\n\t\tchanged: () => {},\n\t\trefresh: async (scope) => {\n\t\t\tawait tokens?.bump(scope)\n\t\t},\n\t\tclose: async () => {},\n\t}\n}\n\ninterface CachedRegistry {\n\tepoch: string\n\tresolved: Promise<ScopeRegistry>\n\t/** The enabled documents it was built from, kept in use while it is handed out. */\n\tids: readonly string[]\n\t/** Each as `id@updatedAt`, so disposing a version drops exactly the registries built on it. */\n\trefs: ReadonlySet<string>\n\t/** Set when a document stood in as a failing source: the registry is built again from then on. */\n\tretryAt?: number\n}\n\n/** What one document built: its adapter, or a stand-in when it could not be read. */\ntype Built =\n\t| { ok: true; adapter: AnalyticsAdapter | null }\n\t| { ok: false; standIn: AnalyticsAdapter }\n\n/** What a stand-in declares when the document's settings build nothing even without its secrets. */\nconst STAND_IN_CAPABILITIES: AnalyticsCapabilities = {\n\trealtime: false,\n\tminGranularity: 'day',\n\tmaxLookbackDays: null,\n\tmetrics: new Set(['pageviews', 'visitors']),\n\tdimensions: new Set(),\n\tfilters: {},\n\trateLimit: null,\n\trecommendedTtl: { realtime: 60, aggregate: 60 },\n}\n\n/**\n * Stands in while a document's adapter cannot be built: keeps its identity, and its capabilities\n * where settings build without secrets; reads fail as `source_misconfigured`, capture none.\n */\nconst standInFor = (\n\traw: Record<string, unknown>,\n\tcause: unknown,\n\tbuild: (doc: Record<string, unknown>) => AnalyticsAdapter | null\n): AnalyticsAdapter => {\n\tconst blank = structuredClone(raw)\n\tfor (const { path } of storedSecrets(blank)) {\n\t\tsetAtPath(blank, path, '')\n\t}\n\tlet shape: AnalyticsAdapter | null = null\n\ttry {\n\t\tshape = build(blank)\n\t} catch {\n\t\tshape = null\n\t}\n\tconst id = documentAdapterId(raw.provider, raw.id)\n\treturn failingAdapter(\n\t\t{\n\t\t\tid,\n\t\t\tlabel: shape?.label ?? (typeof raw.name === 'string' && raw.name !== '' ? raw.name : id),\n\t\t\tcapabilities: shape?.capabilities ?? STAND_IN_CAPABILITIES,\n\t\t\trealtime: shape?.realtime,\n\t\t},\n\t\t() =>\n\t\t\tnew SourceMisconfiguredError(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" could not be read; check its settings and keys`,\n\t\t\t\t{ cause }\n\t\t\t)\n\t)\n}\n\n/**\n * A scope's registry is cached under the epoch the probe reads before any document, so it is never\n * filed under an older epoch. Only unseen document versions are read and decrypted.\n */\nconst collectionRegistry = (\n\toptions: ProviderRegistryOptions,\n\tplan: Extract<ProviderPlan, { kind: 'collection' }>\n): ProviderRegistry => {\n\tconst { payload, now } = options\n\tconst { slug } = plan\n\tconst probe = createCollectionProbe({\n\t\tpayload,\n\t\tslug,\n\t\tscopeField: plan.scopeField,\n\t\twhere: (scope) => providerScopeWhere(plan.scopeField, scope),\n\t\tprovider: true,\n\t\t...(now ? { now } : {}),\n\t})\n\tconst registries = new Map<string, CachedRegistry>()\n\tconst pool = createAdapterPool({\n\t\tpayload,\n\t\t...(now ? { now } : {}),\n\t\tonDispose: (doc) => {\n\t\t\tconst ref = refOf(doc)\n\t\t\tfor (const [key, cached] of registries) {\n\t\t\t\tif (cached.refs.has(ref)) {\n\t\t\t\t\tregistries.delete(key)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t})\n\tlet warnedGa4 = false\n\tconst clock = now ?? currentTime\n\tconst warnProbeFailed = throttled((message) => payload.logger?.warn(message), {\n\t\tnow: clock,\n\t\tintervalMs: WARN_EVERY_MS,\n\t})\n\t// A failing probe keys on the last epoch read, which the registry in use was built from.\n\tconst fallback = createEpochFallback(clock)\n\tconst types: readonly string[] = plan.types ?? PROVIDER_IDS\n\n\t/** An enabled document of a type the install serves, which its adapter may then make a source. */\n\tconst servable = (row: ProbeRow): boolean => row.enabled && types.includes(row.provider ?? '')\n\n\t/** A probed id as the collection stores it: rows carry every id as text. */\n\tconst idOf = (id: string): string | number => {\n\t\tconst custom = isCollectionSlug(payload, slug)\n\t\t\t? payload.collections[slug]?.customIDType\n\t\t\t: undefined\n\t\treturn (custom ?? payload.db.defaultIDType) === 'number' && /^\\d+$/.test(id) ? Number(id) : id\n\t}\n\n\tconst fromDocument = (doc: Record<string, unknown>): AnalyticsAdapter | null =>\n\t\t// A row of the providers collection, whose fields `ProviderDoc` mirrors.\n\t\tadapterFromProviderDoc(doc as ProviderDoc, {\n\t\t\t...(plan.nativeAdapter ? { native: plan.nativeAdapter } : {}),\n\t\t\thosts: options.hosts,\n\t\t\tfetch: options.fetch ?? noGuardedConnection,\n\t\t\tsdks: options.sdks,\n\t\t\t...options.withoutConsent,\n\t\t})\n\n\tconst adapterOf = async (\n\t\traw: Record<string, unknown>,\n\t\tdecrypt: DecryptFieldValue\n\t): Promise<Built> => {\n\t\ttry {\n\t\t\tconst doc = structuredClone(raw)\n\t\t\tfor (const { path, value } of storedSecrets(doc)) {\n\t\t\t\tconst plain = await decrypt(payload, { collection: slug, path, value })\n\t\t\t\tsetAtPath(doc, path, typeof plain === 'string' ? plain : '')\n\t\t\t}\n\t\t\tconst adapter = fromDocument(doc)\n\t\t\t// The first GA4 document is the earliest this install shows it reads GA4 at all.\n\t\t\tif (raw.provider === 'ga4' && !options.sdks.ga4 && !warnedGa4 && isProductionBuild()) {\n\t\t\t\twarnedGa4 = true\n\t\t\t\tpayload.logger?.warn(GA4_SDK_WARNING)\n\t\t\t}\n\t\t\treturn { ok: true, adapter }\n\t\t} catch (err) {\n\t\t\t// A corrupt or key-rotated ciphertext must neither take the scope's registry down nor drop\n\t\t\t// the source silently: it stands in as a failing source until the retry.\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: provider document \"${String(raw.id)}\" (${String(raw.provider)}) could not be read, its reads fail until it can: ${String(err)}`\n\t\t\t)\n\t\t\treturn { ok: false, standIn: standInFor(raw, err, fromDocument) }\n\t\t}\n\t}\n\n\t/**\n\t * Reads and builds the documents the pool has no adapter for, answering each by id. A stand-in\n\t * is never pooled, so the document is read again once its registry expires.\n\t */\n\tconst buildDocuments = async (\n\t\tscope: string | null,\n\t\tids: readonly string[]\n\t): Promise<{ built: Map<string, AnalyticsAdapter | null>; failed: boolean }> => {\n\t\tif (!isCollectionSlug(payload, slug)) {\n\t\t\tthrow new Error(`analytics: no \"${slug}\" collection is registered for the providers`)\n\t\t}\n\t\tconst { decryptFieldValue, withRawEncrypted } = await loadEncrypted()\n\t\t// Never the caller's: the raw window is not a concurrency boundary, so a request shared with\n\t\t// other reads would hand them ciphertext, and it may also hold an uncommitted transaction.\n\t\tconst req = await createLocalReq({}, payload)\n\t\tconst { docs } = await withRawEncrypted(req, () =>\n\t\t\tpayload.find({\n\t\t\t\tcollection: slug,\n\t\t\t\twhere: {\n\t\t\t\t\tand: [\n\t\t\t\t\t\t{ id: { in: ids.map(idOf) } },\n\t\t\t\t\t\t{ enabled: { equals: true } },\n\t\t\t\t\t\tproviderScopeWhere(plan.scopeField, scope),\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\tlimit: ids.length,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\toverrideAccess: true,\n\t\t\t\treq,\n\t\t\t})\n\t\t)\n\t\tconst found: unknown[] = docs\n\t\tconst built = new Map<string, AnalyticsAdapter | null>()\n\t\tlet failed = false\n\t\tfor (const raw of found.filter(isRecord)) {\n\t\t\tconst doc: PooledDocument = { id: String(raw.id), version: versionOf(raw.updatedAt), scope }\n\t\t\tconst outcome = await adapterOf(raw, decryptFieldValue)\n\t\t\tif (outcome.ok) {\n\t\t\t\tbuilt.set(doc.id, pool.put(doc, outcome.adapter, raw.provider !== 'native'))\n\t\t\t} else {\n\t\t\t\tbuilt.set(doc.id, outcome.standIn)\n\t\t\t\tfailed = true\n\t\t\t}\n\t\t}\n\t\treturn { built, failed }\n\t}\n\n\tconst build = async (\n\t\tscope: string | null,\n\t\tdocs: readonly PooledDocument[],\n\t\tflagged: ReadonlySet<string>\n\t): Promise<{ registry: ScopeRegistry; failed: boolean }> => {\n\t\tconst missing = docs.filter((doc) => pool.get(doc) === undefined).map((doc) => doc.id)\n\t\tconst read = missing.length > 0 ? await buildDocuments(scope, missing) : undefined\n\t\tconst extras: ProviderAdapter[] = []\n\t\tfor (const doc of docs) {\n\t\t\tconst adapter = read?.built.has(doc.id) ? read.built.get(doc.id) : pool.get(doc)\n\t\t\t// Lacking what its adapter reads with, a document is no source and grants nothing; a\n\t\t\t// stand-in for one that failed to decrypt still is, configured but failing.\n\t\t\tif (adapter?.isConfigured()) {\n\t\t\t\textras.push({ adapter, docId: doc.id, isDefault: flagged.has(doc.id) })\n\t\t\t}\n\t\t}\n\t\tpool.retain(scope, new Set(docs.map((doc) => doc.id)))\n\t\tconst combined = combineRegistries(options.base, extras)\n\t\treturn {\n\t\t\tregistry: { ...combined, registry: options.narrow(combined.registry) },\n\t\t\tfailed: read?.failed === true,\n\t\t}\n\t}\n\n\tconst probed = async (scope: string | null): Promise<Probe | undefined> => {\n\t\ttry {\n\t\t\treturn await probe.read(scope)\n\t\t} catch (err) {\n\t\t\twarnProbeFailed(\n\t\t\t\t`analytics: reading the provider documents failed, cached reads key on the last epoch this instance read: ${String(err)}`\n\t\t\t)\n\t\t\treturn undefined\n\t\t}\n\t}\n\n\tconst isCurrent = (cached: CachedRegistry, epoch: string): boolean =>\n\t\tcached.epoch === epoch && (cached.retryAt === undefined || clock() < cached.retryAt)\n\n\tconst registryOf = async (scope: string | null): Promise<ScopeRegistry> => {\n\t\tconst key = scope ?? ''\n\t\tconst state = await probe.read(scope)\n\t\tfallback.read(scope, state.epoch)\n\t\tconst cached = registries.get(key)\n\t\tif (cached && isCurrent(cached, state.epoch)) {\n\t\t\tpool.touch(cached.ids)\n\t\t\treturn cached.resolved\n\t\t}\n\t\tconst rows = state.rows.filter(servable)\n\t\tconst docs: PooledDocument[] = rows.map((row) => ({\n\t\t\tid: row.id,\n\t\t\tversion: row.updatedAt,\n\t\t\tscope,\n\t\t}))\n\t\tconst flagged = new Set(rows.filter((row) => row.isDefault).map((row) => row.id))\n\t\tconst built = build(scope, docs, flagged)\n\t\tconst entry: CachedRegistry = {\n\t\t\tepoch: state.epoch,\n\t\t\tresolved: built.then((done) => done.registry),\n\t\t\tids: docs.map((doc) => doc.id),\n\t\t\trefs: new Set(docs.map(refOf)),\n\t\t}\n\t\tbuilt.then(\n\t\t\t(done) => {\n\t\t\t\tif (done.failed) {\n\t\t\t\t\tentry.retryAt = clock() + FAILED_DOCUMENT_RETRY_MS\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {}\n\t\t)\n\t\tremember(registries, [key, entry])\n\t\tentry.resolved.catch(() => {\n\t\t\tif (registries.get(key) === entry) {\n\t\t\t\tregistries.delete(key)\n\t\t\t}\n\t\t})\n\t\treturn entry.resolved\n\t}\n\n\treturn {\n\t\tresolve: (args) => registryOf(scopeOf(args.scope)),\n\t\tepoch: async (raw) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst state = await probed(scope)\n\t\t\treturn state ? fallback.read(scope, state.epoch) : fallback.failed(scope)\n\t\t},\n\t\tgranted: async (raw, adapterId) => {\n\t\t\tconst scope = scopeOf(raw)\n\t\t\tconst native = plan.nativeAdapter\n\t\t\tif (native && native.id === adapterId) {\n\t\t\t\tconst { rows } = await probe.read(scope)\n\t\t\t\treturn (\n\t\t\t\t\tnative.isConfigured() && rows.some((row) => row.provider === 'native' && servable(row))\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn (await registryOf(scope)).grants.has(adapterId)\n\t\t},\n\t\tchanged: (scopes) => probe.expedite(scopes),\n\t\trefresh: async (scope) => probe.expedite([scope]),\n\t\tclose: () => pool.close(),\n\t}\n}\n\n/** The runtime provider registry of one Payload instance, for the install's plan. */\nexport const createProviderRegistry = (options: ProviderRegistryOptions): ProviderRegistry => {\n\tconst { plan } = options\n\tswitch (plan.kind) {\n\t\tcase 'collection':\n\t\t\treturn collectionRegistry(options, plan)\n\t\tcase 'resolve':\n\t\t\treturn resolveRegistry(options, plan.resolve)\n\t\tdefault:\n\t\t\treturn staticRegistry(options)\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0CA,MAAM,gBAAgB;;;;;AAMtB,MAAa,2BAA2B;;AA4DxC,MAAM,aAAa,KAA8B,MAAc,UAAwB;CACtF,MAAM,CAAC,QAAQ,IAAI,SAAS,KAAK,MAAM,GAAG;CAC1C,MAAM,SAAS,IAAI;CACnB,IAAI,UAAU,KAAA,KAAa,SAAS,MAAM,GACzC,OAAO,SAAS;AAElB;;AAGA,MAAM,iBAAiB,QACtB,aAAa,SAAS,EAAE,WAAW;CAClC,MAAM,QAAQ,QAAQ,KAAK,IAAI;CAC/B,OAAO,OAAO,UAAU,YAAY,UAAU,KAAK,CAAC;EAAE;EAAM;CAAM,CAAC,IAAI,CAAC;AACzE,CAAC;AAEF,MAAM,SAAS,QAAiD,GAAG,IAAI,GAAG,GAAG,IAAI;;AAGjF,MAAM,kBAAkB,aAAwD;CAC/E,SAAS,aAAa;EAAE,UAAU,QAAQ;EAAU,QAAQ;CAAU;CACtE,OAAO,YAAA;CACP,eAAe,CAAC;CAChB,SAAS,YAAY,CAAC;CACtB,OAAO,YAAY,CAAC;AACrB;;;;;AAMA,MAAM,mBACL,SACA,YACsB;CACtB,MAAM,EAAE,WAAW;CACnB,OAAO;EACN,SAAS,OAAO,EAAE,SAAS,KAAK,YAAY;GAC3C,MAAM,WAAW,MAAM,QAAQ;IAC9B;IACA;IACA;IACA,OAAO,QAAQ,SAAS;IACxB,OAAO,QAAQ;IACf,MAAM,QAAQ;GACf,CAAC;GACD,MAAM,WAAW,kBAChB,QAAQ,MACR,SAAS,KAAK,aAAa;IAAE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AM,SAAS,KAAK;GACpB,IAAI,UAAU,OAAO,OAAO,WAAW;IACtC,MAAM,EAAE,SAAS,MAAM,MAAM,KAAK,KAAK;IACvC,OACC,OAAO,aAAa,KAAK,KAAK,MAAM,QAAQ,IAAI,aAAa,YAAY,SAAS,GAAG,CAAC;GAExF;GACA,QAAQ,MAAM,WAAW,KAAK,GAAG,OAAO,IAAI,SAAS;EACtD;EACA,UAAU,WAAW,MAAM,SAAS,MAAM;EAC1C,SAAS,OAAO,UAAU,MAAM,SAAS,CAAC,KAAK,CAAC;EAChD,aAAa,KAAK,MAAM;CACzB;AACD;;AAGA,MAAa,0BAA0B,YAAuD;CAC7F,MAAM,EAAE,SAAS;CACjB,QAAQ,KAAK,MAAb;EACC,KAAK,cACJ,OAAO,mBAAmB,SAAS,IAAI;EACxC,KAAK,WACJ,OAAO,gBAAgB,SAAS,KAAK,OAAO;EAC7C,SACC,OAAO,eAAe,OAAO;CAC/B;AACD"}
@@ -1,5 +1,6 @@
1
1
  import { CaptureSlot, TrackerConfig } from "../tracker/config.js";
2
2
  import { GateState, GateStatus, LoadScript, Tracker } from "../tracker/types.js";
3
+ import { ModeSnapshot } from "../tracker/gate.js";
3
4
  import { ReactElement, ReactNode } from "react";
4
5
 
5
6
  //#region src/react/AnalyticsProvider.d.ts
@@ -25,6 +26,11 @@ interface AnalyticsApi extends AnalyticsCommands {
25
26
  excluded: boolean;
26
27
  /** Each capture slot's gate. A change re-renders the caller. */
27
28
  gate: Readonly<Record<CaptureSlot, GateStatus>>;
29
+ /**
30
+ * What each capture slot captures with: `full` once open, else its level without consent (`off`,
31
+ * `cookieless`, `anonymous`). All `off` until a tracker booted. A change re-renders the caller.
32
+ */
33
+ mode: ModeSnapshot;
28
34
  }
29
35
  interface AnalyticsProviderProps {
30
36
  /** Resolved server-side by `getTrackerConfig`, or fetched from the tracker endpoint. */
@@ -1 +1 @@
1
- {"version":3,"file":"AnalyticsProvider.js","names":[],"sources":["../../src/react/AnalyticsProvider.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tcreateContext,\n\ttype ReactElement,\n\ttype ReactNode,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n} from 'react'\nimport type { CaptureSlot, TrackerConfig } from '../tracker/config'\nimport { acquireTracker, setWindowGate, type TrackerLease } from '../tracker/registry'\nimport type { GateState, GateStatus, LoadScript, Tracker } from '../tracker/types'\n\n/** What a component can ask the tracker to do. Stable for the life of the provider. */\nexport interface AnalyticsCommands {\n\ttrack: Tracker['track']\n\ttrackGoal: Tracker['trackGoal']\n\t/** Records a sale, with the amount that actually moved rather than the goal's own. */\n\tpurchase: Tracker['purchase']\n\t/** A no-op in the browser, with a development warning: refunds are server-side. */\n\trefund: Tracker['refund']\n\t/**\n\t * Opens or closes capture slots for the host's consent manager. Safe before the tracker has\n\t * booted: the answer is kept for the window and applied at boot.\n\t */\n\tsetGate: (state: GateState) => void\n\t/** Takes this browser out of capture, or puts it back. */\n\tsetExcluded: Tracker['exclude']\n}\n\n/** The tracker surface a component gets from `useAnalytics`. */\nexport interface AnalyticsApi extends AnalyticsCommands {\n\t/** True while this browser is excluded from capture. Flipping it re-renders the caller. */\n\texcluded: boolean\n\t/** Each capture slot's gate. A change re-renders the caller. */\n\tgate: Readonly<Record<CaptureSlot, GateStatus>>\n}\n\nexport const AnalyticsContext = createContext<AnalyticsCommands | null>(null)\n\nexport interface AnalyticsProviderProps {\n\t/** Resolved server-side by `getTrackerConfig`, or fetched from the tracker endpoint. */\n\tconfig: TrackerConfig\n\tchildren?: ReactNode\n\t/** CSP nonce applied to the vendor scripts the tracker injects. */\n\tnonce?: string\n\t/**\n\t * Replaces script injection, for a framework script loader. A function cannot cross from a\n\t * server component, so pass it from a client component of your own.\n\t */\n\tloadScript?: LoadScript\n\t/** The answer the host already has at boot, as `<AnalyticsScripts gate>` takes it. */\n\tgate?: GateState\n\t/** `false` injects no vendor script at all, for a consent manager that loads them itself. */\n\tsnippets?: boolean\n}\n\n/**\n * Shares the window's one tracker with the tree through `useAnalytics`, leased after mount. The\n * first component to boot it owns its options: after `<AnalyticsScripts />`, this one's are ignored.\n */\nexport const AnalyticsProvider = ({\n\tconfig,\n\tchildren,\n\tnonce,\n\tloadScript,\n\tgate,\n\tsnippets,\n}: AnalyticsProviderProps): ReactElement => {\n\tconst boot = useRef({ config, nonce, loadScript, gate, snippets })\n\tboot.current = { config, nonce, loadScript, gate, snippets }\n\tconst lease = useRef<TrackerLease | null>(null)\n\tconst unmounted = useRef(false)\n\n\tconst ensure = useCallback((): Tracker | null => {\n\t\tif (!lease.current && !unmounted.current && typeof window !== 'undefined') {\n\t\t\tconst current = boot.current\n\t\t\tlease.current = acquireTracker(current.config, {\n\t\t\t\tnonce: current.nonce,\n\t\t\t\tloadScript: current.loadScript,\n\t\t\t\tgate: current.gate,\n\t\t\t\tsnippets: current.snippets,\n\t\t\t})\n\t\t}\n\t\treturn lease.current?.tracker ?? null\n\t}, [])\n\n\tuseEffect(() => {\n\t\tunmounted.current = false\n\t\tensure()\n\t\treturn () => {\n\t\t\t// A stale `track` call held past unmount must not resurrect the tracker.\n\t\t\tunmounted.current = true\n\t\t\tlease.current?.release()\n\t\t\tlease.current = null\n\t\t}\n\t}, [ensure])\n\n\tconst api = useMemo<AnalyticsCommands>(\n\t\t() => ({\n\t\t\ttrack: (name, props, opts) => ensure()?.track(name, props, opts),\n\t\t\ttrackGoal: (slug, opts) => ensure()?.trackGoal(slug, opts),\n\t\t\tpurchase: (input) => ensure()?.purchase(input),\n\t\t\trefund: (input) => ensure()?.refund(input),\n\t\t\t// Recorded before the boot, which a child's effect can trigger ahead of the provider's own:\n\t\t\t// a tracker booted first would load and send under the previous answer.\n\t\t\tsetGate: (state) => {\n\t\t\t\tsetWindowGate(state)\n\t\t\t\tensure()\n\t\t\t},\n\t\t\tsetExcluded: (next) => ensure()?.exclude(next),\n\t\t}),\n\t\t[ensure]\n\t)\n\n\treturn <AnalyticsContext.Provider value={api}>{children}</AnalyticsContext.Provider>\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sources":["../../src/react/AnalyticsProvider.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tcreateContext,\n\ttype ReactElement,\n\ttype ReactNode,\n\tuseCallback,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n} from 'react'\nimport type { CaptureSlot, TrackerConfig } from '../tracker/config'\nimport type { ModeSnapshot } from '../tracker/gate'\nimport { acquireTracker, setWindowGate, type TrackerLease } from '../tracker/registry'\nimport type { GateState, GateStatus, LoadScript, Tracker } from '../tracker/types'\n\n/** What a component can ask the tracker to do. Stable for the life of the provider. */\nexport interface AnalyticsCommands {\n\ttrack: Tracker['track']\n\ttrackGoal: Tracker['trackGoal']\n\t/** Records a sale, with the amount that actually moved rather than the goal's own. */\n\tpurchase: Tracker['purchase']\n\t/** A no-op in the browser, with a development warning: refunds are server-side. */\n\trefund: Tracker['refund']\n\t/**\n\t * Opens or closes capture slots for the host's consent manager. Safe before the tracker has\n\t * booted: the answer is kept for the window and applied at boot.\n\t */\n\tsetGate: (state: GateState) => void\n\t/** Takes this browser out of capture, or puts it back. */\n\tsetExcluded: Tracker['exclude']\n}\n\n/** The tracker surface a component gets from `useAnalytics`. */\nexport interface AnalyticsApi extends AnalyticsCommands {\n\t/** True while this browser is excluded from capture. Flipping it re-renders the caller. */\n\texcluded: boolean\n\t/** Each capture slot's gate. A change re-renders the caller. */\n\tgate: Readonly<Record<CaptureSlot, GateStatus>>\n\t/**\n\t * What each capture slot captures with: `full` once open, else its level without consent (`off`,\n\t * `cookieless`, `anonymous`). All `off` until a tracker booted. A change re-renders the caller.\n\t */\n\tmode: ModeSnapshot\n}\n\nexport const AnalyticsContext = createContext<AnalyticsCommands | null>(null)\n\nexport interface AnalyticsProviderProps {\n\t/** Resolved server-side by `getTrackerConfig`, or fetched from the tracker endpoint. */\n\tconfig: TrackerConfig\n\tchildren?: ReactNode\n\t/** CSP nonce applied to the vendor scripts the tracker injects. */\n\tnonce?: string\n\t/**\n\t * Replaces script injection, for a framework script loader. A function cannot cross from a\n\t * server component, so pass it from a client component of your own.\n\t */\n\tloadScript?: LoadScript\n\t/** The answer the host already has at boot, as `<AnalyticsScripts gate>` takes it. */\n\tgate?: GateState\n\t/** `false` injects no vendor script at all, for a consent manager that loads them itself. */\n\tsnippets?: boolean\n}\n\n/**\n * Shares the window's one tracker with the tree through `useAnalytics`, leased after mount. The\n * first component to boot it owns its options: after `<AnalyticsScripts />`, this one's are ignored.\n */\nexport const AnalyticsProvider = ({\n\tconfig,\n\tchildren,\n\tnonce,\n\tloadScript,\n\tgate,\n\tsnippets,\n}: AnalyticsProviderProps): ReactElement => {\n\tconst boot = useRef({ config, nonce, loadScript, gate, snippets })\n\tboot.current = { config, nonce, loadScript, gate, snippets }\n\tconst lease = useRef<TrackerLease | null>(null)\n\tconst unmounted = useRef(false)\n\n\tconst ensure = useCallback((): Tracker | null => {\n\t\tif (!lease.current && !unmounted.current && typeof window !== 'undefined') {\n\t\t\tconst current = boot.current\n\t\t\tlease.current = acquireTracker(current.config, {\n\t\t\t\tnonce: current.nonce,\n\t\t\t\tloadScript: current.loadScript,\n\t\t\t\tgate: current.gate,\n\t\t\t\tsnippets: current.snippets,\n\t\t\t})\n\t\t}\n\t\treturn lease.current?.tracker ?? null\n\t}, [])\n\n\tuseEffect(() => {\n\t\tunmounted.current = false\n\t\tensure()\n\t\treturn () => {\n\t\t\t// A stale `track` call held past unmount must not resurrect the tracker.\n\t\t\tunmounted.current = true\n\t\t\tlease.current?.release()\n\t\t\tlease.current = null\n\t\t}\n\t}, [ensure])\n\n\tconst api = useMemo<AnalyticsCommands>(\n\t\t() => ({\n\t\t\ttrack: (name, props, opts) => ensure()?.track(name, props, opts),\n\t\t\ttrackGoal: (slug, opts) => ensure()?.trackGoal(slug, opts),\n\t\t\tpurchase: (input) => ensure()?.purchase(input),\n\t\t\trefund: (input) => ensure()?.refund(input),\n\t\t\t// Recorded before the boot, which a child's effect can trigger ahead of the provider's own:\n\t\t\t// a tracker booted first would load and send under the previous answer.\n\t\t\tsetGate: (state) => {\n\t\t\t\tsetWindowGate(state)\n\t\t\t\tensure()\n\t\t\t},\n\t\t\tsetExcluded: (next) => ensure()?.exclude(next),\n\t\t}),\n\t\t[ensure]\n\t)\n\n\treturn <AnalyticsContext.Provider value={api}>{children}</AnalyticsContext.Provider>\n}\n"],"mappings":";;;;;AA8CA,MAAa,mBAAmB,cAAwC,IAAI;;;;;AAuB5E,MAAa,qBAAqB,EACjC,QACA,UACA,OACA,YACA,MACA,eAC2C;CAC3C,MAAM,OAAO,OAAO;EAAE;EAAQ;EAAO;EAAY;EAAM;CAAS,CAAC;CACjE,KAAK,UAAU;EAAE;EAAQ;EAAO;EAAY;EAAM;CAAS;CAC3D,MAAM,QAAQ,OAA4B,IAAI;CAC9C,MAAM,YAAY,OAAO,KAAK;CAE9B,MAAM,SAAS,kBAAkC;EAChD,IAAI,CAAC,MAAM,WAAW,CAAC,UAAU,WAAW,OAAO,WAAW,aAAa;GAC1E,MAAM,UAAU,KAAK;GACrB,MAAM,UAAU,eAAe,QAAQ,QAAQ;IAC9C,OAAO,QAAQ;IACf,YAAY,QAAQ;IACpB,MAAM,QAAQ;IACd,UAAU,QAAQ;GACnB,CAAC;EACF;EACA,OAAO,MAAM,SAAS,WAAW;CAClC,GAAG,CAAC,CAAC;CAEL,gBAAgB;EACf,UAAU,UAAU;EACpB,OAAO;EACP,aAAa;GAEZ,UAAU,UAAU;GACpB,MAAM,SAAS,QAAQ;GACvB,MAAM,UAAU;EACjB;CACD,GAAG,CAAC,MAAM,CAAC;CAEX,MAAM,MAAM,eACJ;EACN,QAAQ,MAAM,OAAO,SAAS,OAAO,GAAG,MAAM,MAAM,OAAO,IAAI;EAC/D,YAAY,MAAM,SAAS,OAAO,GAAG,UAAU,MAAM,IAAI;EACzD,WAAW,UAAU,OAAO,GAAG,SAAS,KAAK;EAC7C,SAAS,UAAU,OAAO,GAAG,OAAO,KAAK;EAGzC,UAAU,UAAU;GACnB,cAAc,KAAK;GACnB,OAAO;EACR;EACA,cAAc,SAAS,OAAO,GAAG,QAAQ,IAAI;CAC9C,IACA,CAAC,MAAM,CACR;CAEA,OAAO,oBAAC,iBAAiB,UAAlB;EAA2B,OAAO;EAAM;CAAoC,CAAA;AACpF"}
@@ -1,15 +1,16 @@
1
1
  "use client";
2
2
  import { subscribeExclusion } from "../tracker/exclusion.js";
3
- import { ALL_PENDING } from "../tracker/gate.js";
4
- import { liveTracker, setWindowGate, subscribeWindowGate, windowGateSnapshot } from "../tracker/registry.js";
3
+ import { ALL_OFF, ALL_PENDING } from "../tracker/gate.js";
4
+ import { liveTracker, setWindowGate, subscribeWindowGate, windowGateSnapshot, windowModeSnapshot } from "../tracker/registry.js";
5
5
  import { AnalyticsContext } from "./AnalyticsProvider.js";
6
6
  import { useContext, useMemo, useSyncExternalStore } from "react";
7
7
  //#region src/react/useAnalytics.tsx
8
8
  const NO_TRACKER = "analytics: useAnalytics found no tracker. Render <AnalyticsScripts /> (or <AnalyticsProvider>) above this component.";
9
- /** The live tracker's flag, never storage: false until a tracker has read it, once a slot opened. */
9
+ /** The live tracker's flag, never storage: false until a tracker has read it, once a slot ran in full. */
10
10
  const exclusionSnapshot = () => liveTracker()?.excluded ?? false;
11
11
  const serverExclusionSnapshot = () => false;
12
12
  const serverGateSnapshot = () => ALL_PENDING;
13
+ const serverModeSnapshot = () => ALL_OFF;
13
14
  /**
14
15
  * The window's tracker, from `<AnalyticsProvider>` or else whatever `<AnalyticsScripts />` booted.
15
16
  * A call with neither throws, except `setGate`, which is kept until a tracker boots.
@@ -18,6 +19,7 @@ const useAnalytics = () => {
18
19
  const provided = useContext(AnalyticsContext);
19
20
  const excluded = useSyncExternalStore(subscribeExclusion, exclusionSnapshot, serverExclusionSnapshot);
20
21
  const gate = useSyncExternalStore(subscribeWindowGate, windowGateSnapshot, serverGateSnapshot);
22
+ const mode = useSyncExternalStore(subscribeWindowGate, windowModeSnapshot, serverModeSnapshot);
21
23
  const commands = useMemo(() => {
22
24
  if (provided) return provided;
23
25
  const tracker = () => {
@@ -37,11 +39,13 @@ const useAnalytics = () => {
37
39
  return useMemo(() => ({
38
40
  ...commands,
39
41
  excluded,
40
- gate
42
+ gate,
43
+ mode
41
44
  }), [
42
45
  commands,
43
46
  excluded,
44
- gate
47
+ gate,
48
+ mode
45
49
  ]);
46
50
  };
47
51
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"useAnalytics.js","names":[],"sources":["../../src/react/useAnalytics.tsx"],"sourcesContent":["'use client'\n\nimport { useContext, useMemo, useSyncExternalStore } from 'react'\nimport { subscribeExclusion } from '../tracker/exclusion'\nimport { ALL_PENDING, type GateSnapshot } from '../tracker/gate'\nimport {\n\tliveTracker,\n\tsetWindowGate,\n\tsubscribeWindowGate,\n\twindowGateSnapshot,\n} from '../tracker/registry'\nimport type { Tracker } from '../tracker/types'\nimport { type AnalyticsApi, type AnalyticsCommands, AnalyticsContext } from './AnalyticsProvider'\n\nconst NO_TRACKER =\n\t'analytics: useAnalytics found no tracker. Render <AnalyticsScripts /> (or <AnalyticsProvider>) above this component.'\n\n/** The live tracker's flag, never storage: false until a tracker has read it, once a slot opened. */\nconst exclusionSnapshot = (): boolean => liveTracker()?.excluded ?? false\n\nconst serverExclusionSnapshot = (): boolean => false\n\nconst serverGateSnapshot = (): GateSnapshot => ALL_PENDING\n\n/**\n * The window's tracker, from `<AnalyticsProvider>` or else whatever `<AnalyticsScripts />` booted.\n * A call with neither throws, except `setGate`, which is kept until a tracker boots.\n */\nexport const useAnalytics = (): AnalyticsApi => {\n\tconst provided = useContext(AnalyticsContext)\n\tconst excluded = useSyncExternalStore(\n\t\tsubscribeExclusion,\n\t\texclusionSnapshot,\n\t\tserverExclusionSnapshot\n\t)\n\tconst gate = useSyncExternalStore(subscribeWindowGate, windowGateSnapshot, serverGateSnapshot)\n\tconst commands = useMemo<AnalyticsCommands>(() => {\n\t\tif (provided) {\n\t\t\treturn provided\n\t\t}\n\t\t// Per call, not per render: the boot effect may not have run yet when a sibling renders.\n\t\tconst tracker = (): Tracker => {\n\t\t\tconst live = liveTracker()\n\t\t\tif (!live) {\n\t\t\t\tthrow new Error(NO_TRACKER)\n\t\t\t}\n\t\t\treturn live\n\t\t}\n\t\treturn {\n\t\t\ttrack: (name, props, opts) => tracker().track(name, props, opts),\n\t\t\ttrackGoal: (slug, opts) => tracker().trackGoal(slug, opts),\n\t\t\tpurchase: (input) => tracker().purchase(input),\n\t\t\trefund: (input) => tracker().refund(input),\n\t\t\tsetGate: (state) => setWindowGate(state),\n\t\t\tsetExcluded: (next) => tracker().exclude(next),\n\t\t}\n\t}, [provided])\n\n\treturn useMemo<AnalyticsApi>(() => ({ ...commands, excluded, gate }), [commands, excluded, gate])\n}\n"],"mappings":";;;;;;;AAcA,MAAM,aACL;;AAGD,MAAM,0BAAmC,YAAY,GAAG,YAAY;AAEpE,MAAM,gCAAyC;AAE/C,MAAM,2BAAyC;;;;;AAM/C,MAAa,qBAAmC;CAC/C,MAAM,WAAW,WAAW,gBAAgB;CAC5C,MAAM,WAAW,qBAChB,oBACA,mBACA,uBACD;CACA,MAAM,OAAO,qBAAqB,qBAAqB,oBAAoB,kBAAkB;CAC7F,MAAM,WAAW,cAAiC;EACjD,IAAI,UACH,OAAO;EAGR,MAAM,gBAAyB;GAC9B,MAAM,OAAO,YAAY;GACzB,IAAI,CAAC,MACJ,MAAM,IAAI,MAAM,UAAU;GAE3B,OAAO;EACR;EACA,OAAO;GACN,QAAQ,MAAM,OAAO,SAAS,QAAQ,EAAE,MAAM,MAAM,OAAO,IAAI;GAC/D,YAAY,MAAM,SAAS,QAAQ,EAAE,UAAU,MAAM,IAAI;GACzD,WAAW,UAAU,QAAQ,EAAE,SAAS,KAAK;GAC7C,SAAS,UAAU,QAAQ,EAAE,OAAO,KAAK;GACzC,UAAU,UAAU,cAAc,KAAK;GACvC,cAAc,SAAS,QAAQ,EAAE,QAAQ,IAAI;EAC9C;CACD,GAAG,CAAC,QAAQ,CAAC;CAEb,OAAO,eAA6B;EAAE,GAAG;EAAU;EAAU;CAAK,IAAI;EAAC;EAAU;EAAU;CAAI,CAAC;AACjG"}
1
+ {"version":3,"file":"useAnalytics.js","names":[],"sources":["../../src/react/useAnalytics.tsx"],"sourcesContent":["'use client'\n\nimport { useContext, useMemo, useSyncExternalStore } from 'react'\nimport { subscribeExclusion } from '../tracker/exclusion'\nimport { ALL_OFF, ALL_PENDING, type GateSnapshot, type ModeSnapshot } from '../tracker/gate'\nimport {\n\tliveTracker,\n\tsetWindowGate,\n\tsubscribeWindowGate,\n\twindowGateSnapshot,\n\twindowModeSnapshot,\n} from '../tracker/registry'\nimport type { Tracker } from '../tracker/types'\nimport { type AnalyticsApi, type AnalyticsCommands, AnalyticsContext } from './AnalyticsProvider'\n\nconst NO_TRACKER =\n\t'analytics: useAnalytics found no tracker. Render <AnalyticsScripts /> (or <AnalyticsProvider>) above this component.'\n\n/** The live tracker's flag, never storage: false until a tracker has read it, once a slot ran in full. */\nconst exclusionSnapshot = (): boolean => liveTracker()?.excluded ?? false\n\nconst serverExclusionSnapshot = (): boolean => false\n\nconst serverGateSnapshot = (): GateSnapshot => ALL_PENDING\n\nconst serverModeSnapshot = (): ModeSnapshot => ALL_OFF\n\n/**\n * The window's tracker, from `<AnalyticsProvider>` or else whatever `<AnalyticsScripts />` booted.\n * A call with neither throws, except `setGate`, which is kept until a tracker boots.\n */\nexport const useAnalytics = (): AnalyticsApi => {\n\tconst provided = useContext(AnalyticsContext)\n\tconst excluded = useSyncExternalStore(\n\t\tsubscribeExclusion,\n\t\texclusionSnapshot,\n\t\tserverExclusionSnapshot\n\t)\n\tconst gate = useSyncExternalStore(subscribeWindowGate, windowGateSnapshot, serverGateSnapshot)\n\tconst mode = useSyncExternalStore(subscribeWindowGate, windowModeSnapshot, serverModeSnapshot)\n\tconst commands = useMemo<AnalyticsCommands>(() => {\n\t\tif (provided) {\n\t\t\treturn provided\n\t\t}\n\t\t// Per call, not per render: the boot effect may not have run yet when a sibling renders.\n\t\tconst tracker = (): Tracker => {\n\t\t\tconst live = liveTracker()\n\t\t\tif (!live) {\n\t\t\t\tthrow new Error(NO_TRACKER)\n\t\t\t}\n\t\t\treturn live\n\t\t}\n\t\treturn {\n\t\t\ttrack: (name, props, opts) => tracker().track(name, props, opts),\n\t\t\ttrackGoal: (slug, opts) => tracker().trackGoal(slug, opts),\n\t\t\tpurchase: (input) => tracker().purchase(input),\n\t\t\trefund: (input) => tracker().refund(input),\n\t\t\tsetGate: (state) => setWindowGate(state),\n\t\t\tsetExcluded: (next) => tracker().exclude(next),\n\t\t}\n\t}, [provided])\n\n\treturn useMemo<AnalyticsApi>(\n\t\t() => ({ ...commands, excluded, gate, mode }),\n\t\t[commands, excluded, gate, mode]\n\t)\n}\n"],"mappings":";;;;;;;AAeA,MAAM,aACL;;AAGD,MAAM,0BAAmC,YAAY,GAAG,YAAY;AAEpE,MAAM,gCAAyC;AAE/C,MAAM,2BAAyC;AAE/C,MAAM,2BAAyC;;;;;AAM/C,MAAa,qBAAmC;CAC/C,MAAM,WAAW,WAAW,gBAAgB;CAC5C,MAAM,WAAW,qBAChB,oBACA,mBACA,uBACD;CACA,MAAM,OAAO,qBAAqB,qBAAqB,oBAAoB,kBAAkB;CAC7F,MAAM,OAAO,qBAAqB,qBAAqB,oBAAoB,kBAAkB;CAC7F,MAAM,WAAW,cAAiC;EACjD,IAAI,UACH,OAAO;EAGR,MAAM,gBAAyB;GAC9B,MAAM,OAAO,YAAY;GACzB,IAAI,CAAC,MACJ,MAAM,IAAI,MAAM,UAAU;GAE3B,OAAO;EACR;EACA,OAAO;GACN,QAAQ,MAAM,OAAO,SAAS,QAAQ,EAAE,MAAM,MAAM,OAAO,IAAI;GAC/D,YAAY,MAAM,SAAS,QAAQ,EAAE,UAAU,MAAM,IAAI;GACzD,WAAW,UAAU,QAAQ,EAAE,SAAS,KAAK;GAC7C,SAAS,UAAU,QAAQ,EAAE,OAAO,KAAK;GACzC,UAAU,UAAU,cAAc,KAAK;GACvC,cAAc,SAAS,QAAQ,EAAE,QAAQ,IAAI;EAC9C;CACD,GAAG,CAAC,QAAQ,CAAC;CAEb,OAAO,eACC;EAAE,GAAG;EAAU;EAAU;EAAM;CAAK,IAC3C;EAAC;EAAU;EAAU;EAAM;CAAI,CAChC;AACD"}
@@ -8,7 +8,7 @@ interface AnalyticsScriptsProps {
8
8
  config: TrackerConfig;
9
9
  /**
10
10
  * The visitor's decision when the server knows it: opened slots render and boot open, closed ones
11
- * render nothing. Omitted, every held slot waits for `setGate` in the browser.
11
+ * render only when they count after a refusal. Omitted, every held slot boots pending.
12
12
  */
13
13
  gate?: GateState;
14
14
  /**
@@ -20,8 +20,9 @@ interface AnalyticsScriptsProps {
20
20
  nonce?: string;
21
21
  }
22
22
  /**
23
- * Renders each boot-open slot's snippet, then boots the tracker; a held slot's snippet is injected
24
- * once `setGate` opens it. A draft page renders none while `capture.skip.previews` is on.
23
+ * Renders the snippet of each slot capturing at boot, then boots the tracker; a slot sending
24
+ * nothing yet gets its snippet once `setGate` opens it. A draft page renders none while
25
+ * `capture.skip.previews` is on.
25
26
  */
26
27
  declare const AnalyticsScripts: ({
27
28
  config,
@@ -1,15 +1,29 @@
1
1
  import { skipsDraft } from "../tracker/skip.js";
2
- import { openAtBoot } from "../tracker/gate.js";
2
+ import { gateAnswer, openAtBoot, slotIsGated, slotMode } from "../tracker/gate.js";
3
3
  import { TrackerBoot } from "../react/TrackerBoot.js";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  //#region src/site/AnalyticsScripts.tsx
6
+ const bootStatus = (slot, gate) => {
7
+ if (openAtBoot(slot, gate)) return "open";
8
+ return gateAnswer(gate, slot.slot, slotIsGated(slot)) === false ? "closed" : "pending";
9
+ };
10
+ /**
11
+ * The snippet a slot renders with the page, so its first pageview is counted with it: the full
12
+ * variant when open, the slot's own while it counts without consent, none while it sends nothing.
13
+ */
14
+ const bootSnippet = (slot, gate) => {
15
+ const status = bootStatus(slot, gate);
16
+ if (slotMode(slot, status) === "off") return;
17
+ return status === "open" ? slot.fullSnippet ?? slot.snippet : slot.snippet;
18
+ };
6
19
  /**
7
- * Renders each boot-open slot's snippet, then boots the tracker; a held slot's snippet is injected
8
- * once `setGate` opens it. A draft page renders none while `capture.skip.previews` is on.
20
+ * Renders the snippet of each slot capturing at boot, then boots the tracker; a slot sending
21
+ * nothing yet gets its snippet once `setGate` opens it. A draft page renders none while
22
+ * `capture.skip.previews` is on.
9
23
  */
10
24
  const AnalyticsScripts = ({ config, gate, snippets = true, nonce }) => {
11
25
  const rendersSnippets = snippets && !skipsDraft(config);
12
- return /* @__PURE__ */ jsxs(Fragment, { children: [config.slots.flatMap((slot) => rendersSnippets && openAtBoot(slot, gate) ? slot.snippet.scripts.map((script, index) => /* @__PURE__ */ jsx("script", {
26
+ return /* @__PURE__ */ jsxs(Fragment, { children: [config.slots.flatMap((slot) => rendersSnippets ? (bootSnippet(slot, gate)?.scripts ?? []).map((script, index) => /* @__PURE__ */ jsx("script", {
13
27
  ...script.attrs,
14
28
  async: script.async,
15
29
  defer: script.defer,
@@ -1 +1 @@
1
- {"version":3,"file":"AnalyticsScripts.js","names":[],"sources":["../../src/site/AnalyticsScripts.tsx"],"sourcesContent":["import type { ReactElement } from 'react'\nimport { TrackerBoot } from '../react/TrackerBoot'\nimport type { TrackerConfig } from '../tracker/config'\nimport { openAtBoot } from '../tracker/gate'\nimport { skipsDraft } from '../tracker/skip'\nimport type { GateState } from '../tracker/types'\n\nexport interface AnalyticsScriptsProps {\n\t/** Resolved server-side, by `getTrackerConfig` or the tracker endpoint. */\n\tconfig: TrackerConfig\n\t/**\n\t * The visitor's decision when the server knows it: opened slots render and boot open, closed ones\n\t * render nothing. Omitted, every held slot waits for `setGate` in the browser.\n\t */\n\tgate?: GateState\n\t/**\n\t * `false` renders no vendor snippet and has the tracker inject none either, for a consent\n\t * manager that loads the vendor SDKs itself. Default true.\n\t */\n\tsnippets?: boolean\n\t/** CSP nonce, applied to every script this renders and the tracker injects. */\n\tnonce?: string\n}\n\n/**\n * Renders each boot-open slot's snippet, then boots the tracker; a held slot's snippet is injected\n * once `setGate` opens it. A draft page renders none while `capture.skip.previews` is on.\n */\nexport const AnalyticsScripts = ({\n\tconfig,\n\tgate,\n\tsnippets = true,\n\tnonce,\n}: AnalyticsScriptsProps): ReactElement => {\n\tconst rendersSnippets = snippets && !skipsDraft(config)\n\treturn (\n\t\t<>\n\t\t\t{config.slots.flatMap((slot) =>\n\t\t\t\trendersSnippets && openAtBoot(slot, gate)\n\t\t\t\t\t? slot.snippet.scripts.map((script, index) => (\n\t\t\t\t\t\t\t<script\n\t\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noArrayIndexKey: a snippet's scripts are a fixed list, never reordered\n\t\t\t\t\t\t\t\tkey={`${slot.slot}-${index}`}\n\t\t\t\t\t\t\t\t{...script.attrs}\n\t\t\t\t\t\t\t\tasync={script.async}\n\t\t\t\t\t\t\t\tdefer={script.defer}\n\t\t\t\t\t\t\t\t// biome-ignore lint/security/noDangerouslySetInnerHtml: adapter-authored vendor init\n\t\t\t\t\t\t\t\tdangerouslySetInnerHTML={script.inline ? { __html: script.inline } : undefined}\n\t\t\t\t\t\t\t\tnonce={nonce}\n\t\t\t\t\t\t\t\tsrc={script.inline ? undefined : script.src}\n\t\t\t\t\t\t\t\ttype={script.type}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t))\n\t\t\t\t\t: []\n\t\t\t)}\n\t\t\t<TrackerBoot config={config} gate={gate} nonce={nonce} snippets={snippets} />\n\t\t</>\n\t)\n}\n"],"mappings":";;;;;;;;;AA4BA,MAAa,oBAAoB,EAChC,QACA,MACA,WAAW,MACX,YAC0C;CAC1C,MAAM,kBAAkB,YAAY,CAAC,WAAW,MAAM;CACtD,OACC,qBAAA,UAAA,EAAA,UAAA,CACE,OAAO,MAAM,SAAS,SACtB,mBAAmB,WAAW,MAAM,IAAI,IACrC,KAAK,QAAQ,QAAQ,KAAK,QAAQ,UAClC,oBAAC,UAAD;EAGC,GAAI,OAAO;EACX,OAAO,OAAO;EACd,OAAO,OAAO;EAEd,yBAAyB,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,KAAA;EAC9D;EACP,KAAK,OAAO,SAAS,KAAA,IAAY,OAAO;EACxC,MAAM,OAAO;CACb,GATK,GAAG,KAAK,KAAK,GAAG,OASrB,CACD,IACA,CAAC,CACL,GACA,oBAAC,aAAD;EAAqB;EAAc;EAAa;EAAiB;CAAW,CAAA,CAC3E,EAAA,CAAA;AAEJ"}
1
+ {"version":3,"file":"AnalyticsScripts.js","names":[],"sources":["../../src/site/AnalyticsScripts.tsx"],"sourcesContent":["import type { ReactElement } from 'react'\nimport { TrackerBoot } from '../react/TrackerBoot'\nimport type { CaptureSnippet, TrackerConfig, TrackerSlotConfig } from '../tracker/config'\nimport { gateAnswer, openAtBoot, slotIsGated, slotMode } from '../tracker/gate'\nimport { skipsDraft } from '../tracker/skip'\nimport type { GateState, GateStatus } from '../tracker/types'\n\nexport interface AnalyticsScriptsProps {\n\t/** Resolved server-side, by `getTrackerConfig` or the tracker endpoint. */\n\tconfig: TrackerConfig\n\t/**\n\t * The visitor's decision when the server knows it: opened slots render and boot open, closed ones\n\t * render only when they count after a refusal. Omitted, every held slot boots pending.\n\t */\n\tgate?: GateState\n\t/**\n\t * `false` renders no vendor snippet and has the tracker inject none either, for a consent\n\t * manager that loads the vendor SDKs itself. Default true.\n\t */\n\tsnippets?: boolean\n\t/** CSP nonce, applied to every script this renders and the tracker injects. */\n\tnonce?: string\n}\n\nconst bootStatus = (slot: TrackerSlotConfig, gate: GateState | undefined): GateStatus => {\n\tif (openAtBoot(slot, gate)) {\n\t\treturn 'open'\n\t}\n\treturn gateAnswer(gate, slot.slot, slotIsGated(slot)) === false ? 'closed' : 'pending'\n}\n\n/**\n * The snippet a slot renders with the page, so its first pageview is counted with it: the full\n * variant when open, the slot's own while it counts without consent, none while it sends nothing.\n */\nconst bootSnippet = (\n\tslot: TrackerSlotConfig,\n\tgate: GateState | undefined\n): CaptureSnippet | undefined => {\n\tconst status = bootStatus(slot, gate)\n\tif (slotMode(slot, status) === 'off') {\n\t\treturn undefined\n\t}\n\treturn status === 'open' ? (slot.fullSnippet ?? slot.snippet) : slot.snippet\n}\n\n/**\n * Renders the snippet of each slot capturing at boot, then boots the tracker; a slot sending\n * nothing yet gets its snippet once `setGate` opens it. A draft page renders none while\n * `capture.skip.previews` is on.\n */\nexport const AnalyticsScripts = ({\n\tconfig,\n\tgate,\n\tsnippets = true,\n\tnonce,\n}: AnalyticsScriptsProps): ReactElement => {\n\tconst rendersSnippets = snippets && !skipsDraft(config)\n\treturn (\n\t\t<>\n\t\t\t{config.slots.flatMap((slot) =>\n\t\t\t\trendersSnippets\n\t\t\t\t\t? (bootSnippet(slot, gate)?.scripts ?? []).map((script, index) => (\n\t\t\t\t\t\t\t<script\n\t\t\t\t\t\t\t\t// biome-ignore lint/suspicious/noArrayIndexKey: a snippet's scripts are a fixed list, never reordered\n\t\t\t\t\t\t\t\tkey={`${slot.slot}-${index}`}\n\t\t\t\t\t\t\t\t{...script.attrs}\n\t\t\t\t\t\t\t\tasync={script.async}\n\t\t\t\t\t\t\t\tdefer={script.defer}\n\t\t\t\t\t\t\t\t// biome-ignore lint/security/noDangerouslySetInnerHtml: adapter-authored vendor init\n\t\t\t\t\t\t\t\tdangerouslySetInnerHTML={script.inline ? { __html: script.inline } : undefined}\n\t\t\t\t\t\t\t\tnonce={nonce}\n\t\t\t\t\t\t\t\tsrc={script.inline ? undefined : script.src}\n\t\t\t\t\t\t\t\ttype={script.type}\n\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t))\n\t\t\t\t\t: []\n\t\t\t)}\n\t\t\t<TrackerBoot config={config} gate={gate} nonce={nonce} snippets={snippets} />\n\t\t</>\n\t)\n}\n"],"mappings":";;;;;AAwBA,MAAM,cAAc,MAAyB,SAA4C;CACxF,IAAI,WAAW,MAAM,IAAI,GACxB,OAAO;CAER,OAAO,WAAW,MAAM,KAAK,MAAM,YAAY,IAAI,CAAC,MAAM,QAAQ,WAAW;AAC9E;;;;;AAMA,MAAM,eACL,MACA,SACgC;CAChC,MAAM,SAAS,WAAW,MAAM,IAAI;CACpC,IAAI,SAAS,MAAM,MAAM,MAAM,OAC9B;CAED,OAAO,WAAW,SAAU,KAAK,eAAe,KAAK,UAAW,KAAK;AACtE;;;;;;AAOA,MAAa,oBAAoB,EAChC,QACA,MACA,WAAW,MACX,YAC0C;CAC1C,MAAM,kBAAkB,YAAY,CAAC,WAAW,MAAM;CACtD,OACC,qBAAA,UAAA,EAAA,UAAA,CACE,OAAO,MAAM,SAAS,SACtB,mBACI,YAAY,MAAM,IAAI,GAAG,WAAW,CAAC,GAAG,KAAK,QAAQ,UACtD,oBAAC,UAAD;EAGC,GAAI,OAAO;EACX,OAAO,OAAO;EACd,OAAO,OAAO;EAEd,yBAAyB,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,KAAA;EAC9D;EACP,KAAK,OAAO,SAAS,KAAA,IAAY,OAAO;EACxC,MAAM,OAAO;CACb,GATK,GAAG,KAAK,KAAK,GAAG,OASrB,CACD,IACA,CAAC,CACL,GACA,oBAAC,aAAD;EAAqB;EAAc;EAAa;EAAiB;CAAW,CAAA,CAC3E,EAAA,CAAA;AAEJ"}
@@ -56,6 +56,7 @@ const sumMetrics = (parts, metrics) => {
56
56
  };
57
57
  const byTimestamp = (a, b) => Date.parse(a.timestamp ?? "") - Date.parse(b.timestamp ?? "");
58
58
  const totalDays = (a, b) => (a?.days ?? 0) + (b?.days ?? 0);
59
+ const totalPageviews = (a, b) => (a?.pageviews ?? 0) + (b?.pageviews ?? 0);
59
60
  const filtersOf = (a, b) => {
60
61
  const seen = /* @__PURE__ */ new Map();
61
62
  for (const filter of [...a ?? [], ...b ?? []]) seen.set(JSON.stringify([
@@ -76,6 +77,8 @@ const mergeAtToday = (closed, today, q) => {
76
77
  const partial = (a.partial?.missingDays ?? 0) + (b.partial?.missingDays ?? 0);
77
78
  const capped = totalDays(a.capped, b.capped);
78
79
  const failed = totalDays(a.failed, b.failed);
80
+ const withoutConsent = totalPageviews(a.withoutConsent, b.withoutConsent);
81
+ const withoutVisitor = totalPageviews(a.withoutVisitor, b.withoutVisitor);
79
82
  const currencies = new Set([...a.mixedCurrencies ?? [], ...b.mixedCurrencies ?? []]);
80
83
  const unapplied = filtersOf(a.unappliedFilters, b.unappliedFilters);
81
84
  const fetchedAt = earlierInstant(a.fetchedAt, b.fetchedAt);
@@ -103,7 +106,10 @@ const mergeAtToday = (closed, today, q) => {
103
106
  ...a.stale || b.stale ? { stale: true } : {},
104
107
  ...sourceError ? { sourceError } : {},
105
108
  ...unapplied.length > 0 ? { unappliedFilters: unapplied } : {},
106
- ...a.goalsUnresolved || b.goalsUnresolved ? { goalsUnresolved: true } : {}
109
+ ...a.goalsUnresolved || b.goalsUnresolved ? { goalsUnresolved: true } : {},
110
+ ...withoutConsent > 0 ? { withoutConsent: { pageviews: withoutConsent } } : {},
111
+ ...withoutVisitor > 0 ? { withoutVisitor: { pageviews: withoutVisitor } } : {},
112
+ ...a.withoutConsentDropped || b.withoutConsentDropped ? { withoutConsentDropped: true } : {}
107
113
  }
108
114
  };
109
115
  };
@@ -1 +1 @@
1
- {"version":3,"file":"todaySplit.js","names":[],"sources":["../../src/surfacing/todaySplit.ts"],"sourcesContent":["import type {\n\tAnalyticsFilter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tMetricKey,\n\tMetricValues,\n} from '../core/contract'\nimport { earlierInstant } from '../core/values'\n\n/**\n * Event counts, which add back up exactly across any cut in time; visitors, visits and averages\n * do not, as a source counts their days in the scope's zone, not at the read's midnight.\n */\nconst EVENT_COUNTS: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'events',\n\t'conversions',\n\t'revenue',\n\t'impressions',\n\t'interactions',\n])\n\nexport interface TodaySplit {\n\t/** The window's whole days before today, which no longer change once counted. */\n\tclosed: AnalyticsQuery\n\ttoday: AnalyticsQuery\n}\n\n/**\n * A read reaching from a closed day into today, cut at today's start: only totals or a day series\n * of event counts, with no breakdown, whose two halves add back up to exactly the whole.\n */\nexport const splitAtToday = (q: AnalyticsQuery, todayStart: number): TodaySplit | undefined => {\n\tconst { start, end } = q.dateRange\n\tif (start.getTime() >= todayStart || end.getTime() < todayStart) {\n\t\treturn undefined\n\t}\n\tif ((q.dimensions?.length ?? 0) > 0 || (q.granularity !== undefined && q.granularity !== 'day')) {\n\t\treturn undefined\n\t}\n\tif (q.metrics.length === 0 || !q.metrics.every((metric) => EVENT_COUNTS.has(metric))) {\n\t\treturn undefined\n\t}\n\treturn {\n\t\tclosed: { ...q, dateRange: { start, end: new Date(todayStart - 1) } },\n\t\ttoday: { ...q, dateRange: { start: new Date(todayStart), end } },\n\t}\n}\n\nconst sumMetrics = (\n\tparts: ReadonlyArray<MetricValues | undefined>,\n\tmetrics: readonly MetricKey[]\n): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tlet seen = false\n\t\tlet sum = 0\n\t\tfor (const part of parts) {\n\t\t\tconst value = part?.[metric]\n\t\t\tif (typeof value === 'number' && Number.isFinite(value)) {\n\t\t\t\tseen = true\n\t\t\t\tsum += value\n\t\t\t}\n\t\t}\n\t\tif (seen) {\n\t\t\tout[metric] = sum\n\t\t}\n\t}\n\treturn out\n}\n\nconst byTimestamp = (a: AnalyticsRow, b: AnalyticsRow): number =>\n\tDate.parse(a.timestamp ?? '') - Date.parse(b.timestamp ?? '')\n\nconst totalDays = (a: { days: number } | undefined, b: { days: number } | undefined): number =>\n\t(a?.days ?? 0) + (b?.days ?? 0)\n\nconst filtersOf = (a?: AnalyticsFilter[], b?: AnalyticsFilter[]): AnalyticsFilter[] => {\n\tconst seen = new Map<string, AnalyticsFilter>()\n\tfor (const filter of [...(a ?? []), ...(b ?? [])]) {\n\t\tseen.set(JSON.stringify([filter.dimension, filter.operator, filter.value]), filter)\n\t}\n\treturn [...seen.values()]\n}\n\n/** The answer for the whole window out of its two halves: counts add up, caveats carry over. */\nexport const mergeAtToday = (\n\tclosed: AnalyticsResult,\n\ttoday: AnalyticsResult,\n\tq: AnalyticsQuery\n): AnalyticsResult => {\n\tconst series = [...closed.rows, ...today.rows]\n\t\t.filter((row) => row.timestamp !== undefined)\n\t\t.sort(byTimestamp)\n\tconst flat = [...closed.rows, ...today.rows].filter((row) => row.timestamp === undefined)\n\tconst rows =\n\t\tflat.length === 0\n\t\t\t? series\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tmetrics: sumMetrics(\n\t\t\t\t\t\t\tflat.map((row) => row.metrics),\n\t\t\t\t\t\t\tq.metrics\n\t\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t\t...series,\n\t\t\t\t]\n\tconst totals =\n\t\tclosed.totals === undefined && today.totals === undefined\n\t\t\t? undefined\n\t\t\t: sumMetrics([closed.totals, today.totals], q.metrics)\n\tconst a = closed.meta\n\tconst b = today.meta\n\tconst partial = (a.partial?.missingDays ?? 0) + (b.partial?.missingDays ?? 0)\n\tconst capped = totalDays(a.capped, b.capped)\n\tconst failed = totalDays(a.failed, b.failed)\n\tconst currencies = new Set([...(a.mixedCurrencies ?? []), ...(b.mixedCurrencies ?? [])])\n\tconst unapplied = filtersOf(a.unappliedFilters, b.unappliedFilters)\n\tconst fetchedAt = earlierInstant(a.fetchedAt, b.fetchedAt)\n\tconst asOf = earlierInstant(a.asOf, b.asOf)\n\tconst dataTo = earlierInstant(a.dataTo, b.dataTo)\n\tconst sourceError = a.sourceError ?? b.sourceError\n\tconst currency = a.currency ?? b.currency\n\treturn {\n\t\trows,\n\t\t...(totals ? { totals } : {}),\n\t\tmeta: {\n\t\t\tprovider: a.provider,\n\t\t\tfetchedAt,\n\t\t\t...(asOf ? { asOf } : {}),\n\t\t\t...(a.clamped || b.clamped ? { clamped: true } : {}),\n\t\t\t...(a.dataFrom ? { dataFrom: a.dataFrom } : {}),\n\t\t\t...(dataTo ? { dataTo } : {}),\n\t\t\t...(a.sampled || b.sampled ? { sampled: true } : {}),\n\t\t\t...(partial > 0 ? { partial: { missingDays: partial } } : {}),\n\t\t\t...(capped > 0 ? { capped: { days: capped } } : {}),\n\t\t\t...(failed > 0 ? { failed: { days: failed } } : {}),\n\t\t\t...(a.timezoneUnresolved || b.timezoneUnresolved ? { timezoneUnresolved: true } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t\t...(currencies.size > 1 ? { mixedCurrencies: [...currencies].sort() } : {}),\n\t\t\t...(a.stale || b.stale ? { stale: true } : {}),\n\t\t\t...(sourceError ? { sourceError } : {}),\n\t\t\t...(unapplied.length > 0 ? { unappliedFilters: unapplied } : {}),\n\t\t\t...(a.goalsUnresolved || b.goalsUnresolved ? { goalsUnresolved: true } : {}),\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;AAcA,MAAM,eAAuC,IAAI,IAAe;CAC/D;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;AAYD,MAAa,gBAAgB,GAAmB,eAA+C;CAC9F,MAAM,EAAE,OAAO,QAAQ,EAAE;CACzB,IAAI,MAAM,QAAQ,KAAK,cAAc,IAAI,QAAQ,IAAI,YACpD;CAED,KAAK,EAAE,YAAY,UAAU,KAAK,KAAM,EAAE,gBAAgB,KAAA,KAAa,EAAE,gBAAgB,OACxF;CAED,IAAI,EAAE,QAAQ,WAAW,KAAK,CAAC,EAAE,QAAQ,OAAO,WAAW,aAAa,IAAI,MAAM,CAAC,GAClF;CAED,OAAO;EACN,QAAQ;GAAE,GAAG;GAAG,WAAW;IAAE;IAAO,qBAAK,IAAI,KAAK,aAAa,CAAC;GAAE;EAAE;EACpE,OAAO;GAAE,GAAG;GAAG,WAAW;IAAE,OAAO,IAAI,KAAK,UAAU;IAAG;GAAI;EAAE;CAChE;AACD;AAEA,MAAM,cACL,OACA,YACkB;CAClB,MAAM,MAAoB,CAAC;CAC3B,KAAK,MAAM,UAAU,SAAS;EAC7B,IAAI,OAAO;EACX,IAAI,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I,CAAC;GAC/B,GAAI,WAAW,OAAO,IAAI,EAAE,iBAAiB,CAAC,GAAG,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC;GACzE,GAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,KAAK,IAAI,CAAC;GAC5C,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;GACrC,GAAI,UAAU,SAAS,IAAI,EAAE,kBAAkB,UAAU,IAAI,CAAC;GAC9D,GAAI,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,iBAAiB,KAAK,IAAI,CAAC;EAC3E;CACD;AACD"}
1
+ {"version":3,"file":"todaySplit.js","names":[],"sources":["../../src/surfacing/todaySplit.ts"],"sourcesContent":["import type {\n\tAnalyticsFilter,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tMetricKey,\n\tMetricValues,\n} from '../core/contract'\nimport { earlierInstant } from '../core/values'\n\n/**\n * Event counts, which add back up exactly across any cut in time; visitors, visits and averages\n * do not, as a source counts their days in the scope's zone, not at the read's midnight.\n */\nconst EVENT_COUNTS: ReadonlySet<MetricKey> = new Set<MetricKey>([\n\t'pageviews',\n\t'events',\n\t'conversions',\n\t'revenue',\n\t'impressions',\n\t'interactions',\n])\n\nexport interface TodaySplit {\n\t/** The window's whole days before today, which no longer change once counted. */\n\tclosed: AnalyticsQuery\n\ttoday: AnalyticsQuery\n}\n\n/**\n * A read reaching from a closed day into today, cut at today's start: only totals or a day series\n * of event counts, with no breakdown, whose two halves add back up to exactly the whole.\n */\nexport const splitAtToday = (q: AnalyticsQuery, todayStart: number): TodaySplit | undefined => {\n\tconst { start, end } = q.dateRange\n\tif (start.getTime() >= todayStart || end.getTime() < todayStart) {\n\t\treturn undefined\n\t}\n\tif ((q.dimensions?.length ?? 0) > 0 || (q.granularity !== undefined && q.granularity !== 'day')) {\n\t\treturn undefined\n\t}\n\tif (q.metrics.length === 0 || !q.metrics.every((metric) => EVENT_COUNTS.has(metric))) {\n\t\treturn undefined\n\t}\n\treturn {\n\t\tclosed: { ...q, dateRange: { start, end: new Date(todayStart - 1) } },\n\t\ttoday: { ...q, dateRange: { start: new Date(todayStart), end } },\n\t}\n}\n\nconst sumMetrics = (\n\tparts: ReadonlyArray<MetricValues | undefined>,\n\tmetrics: readonly MetricKey[]\n): MetricValues => {\n\tconst out: MetricValues = {}\n\tfor (const metric of metrics) {\n\t\tlet seen = false\n\t\tlet sum = 0\n\t\tfor (const part of parts) {\n\t\t\tconst value = part?.[metric]\n\t\t\tif (typeof value === 'number' && Number.isFinite(value)) {\n\t\t\t\tseen = true\n\t\t\t\tsum += value\n\t\t\t}\n\t\t}\n\t\tif (seen) {\n\t\t\tout[metric] = sum\n\t\t}\n\t}\n\treturn out\n}\n\nconst byTimestamp = (a: AnalyticsRow, b: AnalyticsRow): number =>\n\tDate.parse(a.timestamp ?? '') - Date.parse(b.timestamp ?? '')\n\nconst totalDays = (a: { days: number } | undefined, b: { days: number } | undefined): number =>\n\t(a?.days ?? 0) + (b?.days ?? 0)\n\nconst totalPageviews = (\n\ta: { pageviews: number } | undefined,\n\tb: { pageviews: number } | undefined\n): number => (a?.pageviews ?? 0) + (b?.pageviews ?? 0)\n\nconst filtersOf = (a?: AnalyticsFilter[], b?: AnalyticsFilter[]): AnalyticsFilter[] => {\n\tconst seen = new Map<string, AnalyticsFilter>()\n\tfor (const filter of [...(a ?? []), ...(b ?? [])]) {\n\t\tseen.set(JSON.stringify([filter.dimension, filter.operator, filter.value]), filter)\n\t}\n\treturn [...seen.values()]\n}\n\n/** The answer for the whole window out of its two halves: counts add up, caveats carry over. */\nexport const mergeAtToday = (\n\tclosed: AnalyticsResult,\n\ttoday: AnalyticsResult,\n\tq: AnalyticsQuery\n): AnalyticsResult => {\n\tconst series = [...closed.rows, ...today.rows]\n\t\t.filter((row) => row.timestamp !== undefined)\n\t\t.sort(byTimestamp)\n\tconst flat = [...closed.rows, ...today.rows].filter((row) => row.timestamp === undefined)\n\tconst rows =\n\t\tflat.length === 0\n\t\t\t? series\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tmetrics: sumMetrics(\n\t\t\t\t\t\t\tflat.map((row) => row.metrics),\n\t\t\t\t\t\t\tq.metrics\n\t\t\t\t\t\t),\n\t\t\t\t\t},\n\t\t\t\t\t...series,\n\t\t\t\t]\n\tconst totals =\n\t\tclosed.totals === undefined && today.totals === undefined\n\t\t\t? undefined\n\t\t\t: sumMetrics([closed.totals, today.totals], q.metrics)\n\tconst a = closed.meta\n\tconst b = today.meta\n\tconst partial = (a.partial?.missingDays ?? 0) + (b.partial?.missingDays ?? 0)\n\tconst capped = totalDays(a.capped, b.capped)\n\tconst failed = totalDays(a.failed, b.failed)\n\tconst withoutConsent = totalPageviews(a.withoutConsent, b.withoutConsent)\n\tconst withoutVisitor = totalPageviews(a.withoutVisitor, b.withoutVisitor)\n\tconst currencies = new Set([...(a.mixedCurrencies ?? []), ...(b.mixedCurrencies ?? [])])\n\tconst unapplied = filtersOf(a.unappliedFilters, b.unappliedFilters)\n\tconst fetchedAt = earlierInstant(a.fetchedAt, b.fetchedAt)\n\tconst asOf = earlierInstant(a.asOf, b.asOf)\n\tconst dataTo = earlierInstant(a.dataTo, b.dataTo)\n\tconst sourceError = a.sourceError ?? b.sourceError\n\tconst currency = a.currency ?? b.currency\n\treturn {\n\t\trows,\n\t\t...(totals ? { totals } : {}),\n\t\tmeta: {\n\t\t\tprovider: a.provider,\n\t\t\tfetchedAt,\n\t\t\t...(asOf ? { asOf } : {}),\n\t\t\t...(a.clamped || b.clamped ? { clamped: true } : {}),\n\t\t\t...(a.dataFrom ? { dataFrom: a.dataFrom } : {}),\n\t\t\t...(dataTo ? { dataTo } : {}),\n\t\t\t...(a.sampled || b.sampled ? { sampled: true } : {}),\n\t\t\t...(partial > 0 ? { partial: { missingDays: partial } } : {}),\n\t\t\t...(capped > 0 ? { capped: { days: capped } } : {}),\n\t\t\t...(failed > 0 ? { failed: { days: failed } } : {}),\n\t\t\t...(a.timezoneUnresolved || b.timezoneUnresolved ? { timezoneUnresolved: true } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t\t...(currencies.size > 1 ? { mixedCurrencies: [...currencies].sort() } : {}),\n\t\t\t...(a.stale || b.stale ? { stale: true } : {}),\n\t\t\t...(sourceError ? { sourceError } : {}),\n\t\t\t...(unapplied.length > 0 ? { unappliedFilters: unapplied } : {}),\n\t\t\t...(a.goalsUnresolved || b.goalsUnresolved ? { goalsUnresolved: true } : {}),\n\t\t\t...(withoutConsent > 0 ? { withoutConsent: { pageviews: withoutConsent } } : {}),\n\t\t\t...(withoutVisitor > 0 ? { withoutVisitor: { pageviews: withoutVisitor } } : {}),\n\t\t\t...(a.withoutConsentDropped || b.withoutConsentDropped\n\t\t\t\t? { withoutConsentDropped: true }\n\t\t\t\t: {}),\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;AAcA,MAAM,eAAuC,IAAI,IAAe;CAC/D;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;AAYD,MAAa,gBAAgB,GAAmB,eAA+C;CAC9F,MAAM,EAAE,OAAO,QAAQ,EAAE;CACzB,IAAI,MAAM,QAAQ,KAAK,cAAc,IAAI,QAAQ,IAAI,YACpD;CAED,KAAK,EAAE,YAAY,UAAU,KAAK,KAAM,EAAE,gBAAgB,KAAA,KAAa,EAAE,gBAAgB,OACxF;CAED,IAAI,EAAE,QAAQ,WAAW,KAAK,CAAC,EAAE,QAAQ,OAAO,WAAW,aAAa,IAAI,MAAM,CAAC,GAClF;CAED,OAAO;EACN,QAAQ;GAAE,GAAG;GAAG,WAAW;IAAE;IAAO,qBAAK,IAAI,KAAK,aAAa,CAAC;GAAE;EAAE;EACpE,OAAO;GAAE,GAAG;GAAG,WAAW;IAAE,OAAO,IAAI,KAAK,UAAU;IAAG;GAAI;EAAE;CAChE;AACD;AAEA,MAAM,cACL,OACA,YACkB;CAClB,MAAM,MAAoB,CAAC;CAC3B,KAAK,MAAM,UAAU,SAAS;EAC7B,IA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AAC;GACjD,GAAI,SAAS,IAAI,EAAE,QAAQ,EAAE,MAAM,OAAO,EAAE,IAAI,CAAC;GACjD,GAAI,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,oBAAoB,KAAK,IAAI,CAAC;GACnF,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;GAC/B,GAAI,WAAW,OAAO,IAAI,EAAE,iBAAiB,CAAC,GAAG,UAAU,EAAE,KAAK,EAAE,IAAI,CAAC;GACzE,GAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,OAAO,KAAK,IAAI,CAAC;GAC5C,GAAI,cAAc,EAAE,YAAY,IAAI,CAAC;GACrC,GAAI,UAAU,SAAS,IAAI,EAAE,kBAAkB,UAAU,IAAI,CAAC;GAC9D,GAAI,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,iBAAiB,KAAK,IAAI,CAAC;GAC1E,GAAI,iBAAiB,IAAI,EAAE,gBAAgB,EAAE,WAAW,eAAe,EAAE,IAAI,CAAC;GAC9E,GAAI,iBAAiB,IAAI,EAAE,gBAAgB,EAAE,WAAW,eAAe,EAAE,IAAI,CAAC;GAC9E,GAAI,EAAE,yBAAyB,EAAE,wBAC9B,EAAE,uBAAuB,KAAK,IAC9B,CAAC;EACL;CACD;AACD"}
@@ -6,6 +6,19 @@
6
6
  /** The two capture slots an install can fill: the platform's own and the tenant's. */
7
7
  type CaptureSlot = 'global' | 'tenant';
8
8
  type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami' | 'ga4';
9
+ /** What a held slot does without consent in one phase. */
10
+ type WithoutConsentLevel = 'cookieless' | 'off';
11
+ /** The two phases a held slot spends without consent: no answer yet, and refused. */
12
+ type ConsentPhase = 'pending' | 'refused';
13
+ /**
14
+ * What a slot captures with right now. `cookieless` counts without storing anything on the device;
15
+ * `anonymous` (native only) also keeps no visitor id; `full` is the vendor's normal tracking.
16
+ */
17
+ type SlotMode = 'off' | 'cookieless' | 'anonymous' | 'full';
18
+ /** A held slot's mode in a phase without consent. */
19
+ type HeldSlotMode = Exclude<SlotMode, 'full'>;
20
+ /** A held slot's resolved mode per phase without consent. */
21
+ type SlotWithoutConsent = Record<ConsentPhase, HeldSlotMode>;
9
22
  interface SnippetScript {
10
23
  src?: string;
11
24
  inline?: string;
@@ -99,7 +112,13 @@ interface TrackerSlotConfig {
99
112
  adapterId: string;
100
113
  /** Mount the snippet and the sink talk to, relative and behind the Next basePath. */
101
114
  path: string;
115
+ /** For a slot counting without consent, the variant it starts cookieless in. */
102
116
  snippet: CaptureSnippet;
117
+ /**
118
+ * The variant a slot counting without consent starts in when it is open at boot, present only
119
+ * where it differs from `snippet` (PostHog, GA4). The tracker adopts whichever one is on the page.
120
+ */
121
+ fullSnippet?: CaptureSnippet;
103
122
  /** What the adapter hands its browser client: public settings only, never a credential. */
104
123
  client: {
105
124
  kind: CaptureClientKind;
@@ -114,6 +133,12 @@ interface TrackerSlotConfig {
114
133
  * `requiresConsent` in 1.0.0-beta.11; the tracker still reads that from a cached config.
115
134
  */
116
135
  gated: boolean;
136
+ /**
137
+ * What a held slot does before an answer and after a refusal, resolved on the server so the
138
+ * browser never runs a host function. Absent (a config cached from 1.0.0-beta.14, or an adapter
139
+ * that cannot run cookieless) means `off` in both phases.
140
+ */
141
+ withoutConsent?: SlotWithoutConsent;
117
142
  }
118
143
  /**
119
144
  * Everything the browser tracker needs, served to any visitor: adapters' public `client` and
@@ -145,5 +170,5 @@ interface TrackerConfig {
145
170
  admin?: AdminDigest;
146
171
  }
147
172
  //#endregion
148
- export { AdminDigest, CaptureClientKind, CaptureSlot, CaptureSnippet, GoalMatch, ResolvedAutoCapture, ResolvedItemCapture, RevenueItem, SnippetScript, TrackerConfig, TrackerExclusion, TrackerGoal, TrackerSkip, TrackerSlotConfig };
173
+ export { AdminDigest, CaptureClientKind, CaptureSlot, CaptureSnippet, ConsentPhase, GoalMatch, HeldSlotMode, ResolvedAutoCapture, ResolvedItemCapture, RevenueItem, SlotMode, SlotWithoutConsent, SnippetScript, TrackerConfig, TrackerExclusion, TrackerGoal, TrackerSkip, TrackerSlotConfig, WithoutConsentLevel };
149
174
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../../src/tracker/config.ts"],"sourcesContent":["/**\n * What the browser tracker is booted with, shared with the server that builds it. Imports\n * nothing, so `/tracker`, `/react` and `/site` declare it without reaching Payload or Node.\n */\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami' | 'ga4'\n\nexport interface SnippetScript {\n\tsrc?: string\n\tinline?: string\n\tattrs?: Record<string, string>\n\tasync?: boolean\n\tdefer?: boolean\n\ttype?: string\n}\n\nexport interface CaptureSnippet {\n\tscripts: SnippetScript[]\n}\n\n/**\n * How an incoming event is recognized as a completion of a goal. `goal` matches an explicit\n * `trackGoal(slug)` call, which is what the attribute and action hookups emit.\n */\nexport type GoalMatch =\n\t| { kind: 'event'; name: string }\n\t| { kind: 'path'; pattern: string }\n\t| { kind: 'goal' }\n\n/** The goal fields the browser tracker needs; a goal's admin-facing name never leaves the server. */\nexport interface TrackerGoal {\n\t/** Stable identifier, kebab-case; unique across the install's goals. */\n\tslug: string\n\tmatch: GoalMatch\n\t/** Revenue for one completion: a fixed amount, or read from an event property. */\n\tvalue?: { fixed?: number; prop?: string }\n\t/** ISO 4217 code the goal's value is denominated in. */\n\tcurrency?: string\n}\n\n/**\n * One line of a sale, shaped like a GA4 `items` entry so a vendor sink forwards it as it stands.\n * Only the id is required.\n */\nexport interface RevenueItem {\n\tid: string\n\tname?: string\n\tquantity?: number\n\tprice?: number\n}\n\n/** `capture.autoCapture.items` with every default filled in. */\nexport interface ResolvedItemCapture {\n\timpressions: boolean\n\tclicks: boolean\n\tpages: boolean\n}\n\n/** `capture.autoCapture` with every default filled in. */\nexport interface ResolvedAutoCapture {\n\tscrollDepth: boolean\n\toutboundLinks: boolean\n\tfileDownloads: boolean\n\tgoalAttribute: boolean\n\tquery: boolean\n\titems: ResolvedItemCapture\n}\n\nexport const DEFAULT_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: true,\n\tclicks: true,\n\tpages: true,\n}\n\n/** Item capture off: what `items: false` asks for, and what an install binding no item collection gets. */\nexport const NO_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: false,\n\tclicks: false,\n\tpages: false,\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n\tquery: true,\n\titems: DEFAULT_ITEM_CAPTURE,\n}\n\n/**\n * The exclusion link while `capture.exclusion` is on: its parameter and the SHA-256 (lowercase hex)\n * of the value that excludes. The token itself never reaches a page.\n */\nexport interface TrackerExclusion {\n\tparam: string\n\ttokenHash: string\n}\n\n/** What the tracker leaves uncounted (`capture.skip`), each on unless the install turns it off. */\nexport interface TrackerSkip {\n\t/** A browser driven by automation, which says so in `navigator.webdriver`. */\n\tautomation: boolean\n\t/** A page rendered in draft mode, and one shown in Payload's live preview. */\n\tpreviews: boolean\n}\n\n/**\n * Where Payload's admin answers, as SHA-256 digests (lowercase hex) a page can check an address\n * against but never read the admin's address from.\n */\nexport interface AdminDigest {\n\t/** Of the admin's origin; absent when the admin is served from the page's own origin. */\n\torigin?: string\n\t/** Of the admin route's path, behind the Next basePath, with no trailing slash (`/` for the root). */\n\tpath: string\n}\n\nexport interface TrackerSlotConfig {\n\tslot: CaptureSlot\n\tkind: CaptureClientKind\n\tadapterId: string\n\t/** Mount the snippet and the sink talk to, relative and behind the Next basePath. */\n\tpath: string\n\tsnippet: CaptureSnippet\n\t/** What the adapter hands its browser client: public settings only, never a credential. */\n\tclient: { kind: CaptureClientKind } & Record<string, string | number | boolean>\n\t/**\n\t * The named vendor client this slot captures with, beside the other slot's client of the same\n\t * vendor: PostHog's `window.posthog[instance]`. Absent, the vendor's primary client.\n\t */\n\tinstance?: string\n\t/**\n\t * True when `capture.gate` holds this slot until the host's consent manager answers. Was\n\t * `requiresConsent` in 1.0.0-beta.11; the tracker still reads that from a cached config.\n\t */\n\tgated: boolean\n}\n\n/**\n * Everything the browser tracker needs, served to any visitor: adapters' public `client` and\n * `snippet` settings only, never a query credential or a goal's admin-facing name.\n */\nexport interface TrackerConfig {\n\tslots: TrackerSlotConfig[]\n\tautoCapture: ResolvedAutoCapture\n\t/**\n\t * The request scope's goals, config merged with the collection. Built-in `purchase` stays out: it\n\t * matches by slug, and shipping it would tell every site it has a goal.\n\t */\n\tgoals: TrackerGoal[]\n\t/** Where the native sink posts events, relative and behind the Next basePath. */\n\tingestPath: string\n\t/**\n\t * The exclusion link for this request's scope, while `capture.exclusion` is on: its\n\t * parameter and the hash of its token. Absent, the tracker ignores the parameter.\n\t */\n\texclusion?: TrackerExclusion\n\t/** `capture.skip`, present only when the install turned one off. Absent, every skip is on. */\n\tskip?: TrackerSkip\n\t/** The page was rendered in draft mode (`getTrackerConfig`'s `draft`). */\n\tdraft?: true\n\t/**\n\t * Where Payload's admin answers, while previews are skipped: a page shown by one of its pages is\n\t * its live preview. Digests alone, so no page names the admin's host or route.\n\t */\n\tadmin?: AdminDigest\n}\n"],"mappings":";AAuEA,MAAa,uBAA4C;CACxD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,kBAAuC;CACnD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,uBAA4C;CACxD,aAAa;CACb,eAAe;CACf,eAAe;CACf,eAAe;CACf,OAAO;CACP,OAAO;AACR"}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../../src/tracker/config.ts"],"sourcesContent":["/**\n * What the browser tracker is booted with, shared with the server that builds it. Imports\n * nothing, so `/tracker`, `/react` and `/site` declare it without reaching Payload or Node.\n */\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport type CaptureClientKind = 'native' | 'posthog' | 'plausible' | 'umami' | 'ga4'\n\n/** What a held slot does without consent in one phase. */\nexport type WithoutConsentLevel = 'cookieless' | 'off'\n\n/** The two phases a held slot spends without consent: no answer yet, and refused. */\nexport type ConsentPhase = 'pending' | 'refused'\n\n/**\n * What a slot captures with right now. `cookieless` counts without storing anything on the device;\n * `anonymous` (native only) also keeps no visitor id; `full` is the vendor's normal tracking.\n */\nexport type SlotMode = 'off' | 'cookieless' | 'anonymous' | 'full'\n\n/** A held slot's mode in a phase without consent. */\nexport type HeldSlotMode = Exclude<SlotMode, 'full'>\n\n/** A held slot's resolved mode per phase without consent. */\nexport type SlotWithoutConsent = Record<ConsentPhase, HeldSlotMode>\n\nexport interface SnippetScript {\n\tsrc?: string\n\tinline?: string\n\tattrs?: Record<string, string>\n\tasync?: boolean\n\tdefer?: boolean\n\ttype?: string\n}\n\nexport interface CaptureSnippet {\n\tscripts: SnippetScript[]\n}\n\n/**\n * How an incoming event is recognized as a completion of a goal. `goal` matches an explicit\n * `trackGoal(slug)` call, which is what the attribute and action hookups emit.\n */\nexport type GoalMatch =\n\t| { kind: 'event'; name: string }\n\t| { kind: 'path'; pattern: string }\n\t| { kind: 'goal' }\n\n/** The goal fields the browser tracker needs; a goal's admin-facing name never leaves the server. */\nexport interface TrackerGoal {\n\t/** Stable identifier, kebab-case; unique across the install's goals. */\n\tslug: string\n\tmatch: GoalMatch\n\t/** Revenue for one completion: a fixed amount, or read from an event property. */\n\tvalue?: { fixed?: number; prop?: string }\n\t/** ISO 4217 code the goal's value is denominated in. */\n\tcurrency?: string\n}\n\n/**\n * One line of a sale, shaped like a GA4 `items` entry so a vendor sink forwards it as it stands.\n * Only the id is required.\n */\nexport interface RevenueItem {\n\tid: string\n\tname?: string\n\tquantity?: number\n\tprice?: number\n}\n\n/** `capture.autoCapture.items` with every default filled in. */\nexport interface ResolvedItemCapture {\n\timpressions: boolean\n\tclicks: boolean\n\tpages: boolean\n}\n\n/** `capture.autoCapture` with every default filled in. */\nexport interface ResolvedAutoCapture {\n\tscrollDepth: boolean\n\toutboundLinks: boolean\n\tfileDownloads: boolean\n\tgoalAttribute: boolean\n\tquery: boolean\n\titems: ResolvedItemCapture\n}\n\nexport const DEFAULT_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: true,\n\tclicks: true,\n\tpages: true,\n}\n\n/** Item capture off: what `items: false` asks for, and what an install binding no item collection gets. */\nexport const NO_ITEM_CAPTURE: ResolvedItemCapture = {\n\timpressions: false,\n\tclicks: false,\n\tpages: false,\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n\tquery: true,\n\titems: DEFAULT_ITEM_CAPTURE,\n}\n\n/**\n * The exclusion link while `capture.exclusion` is on: its parameter and the SHA-256 (lowercase hex)\n * of the value that excludes. The token itself never reaches a page.\n */\nexport interface TrackerExclusion {\n\tparam: string\n\ttokenHash: string\n}\n\n/** What the tracker leaves uncounted (`capture.skip`), each on unless the install turns it off. */\nexport interface TrackerSkip {\n\t/** A browser driven by automation, which says so in `navigator.webdriver`. */\n\tautomation: boolean\n\t/** A page rendered in draft mode, and one shown in Payload's live preview. */\n\tpreviews: boolean\n}\n\n/**\n * Where Payload's admin answers, as SHA-256 digests (lowercase hex) a page can check an address\n * against but never read the admin's address from.\n */\nexport interface AdminDigest {\n\t/** Of the admin's origin; absent when the admin is served from the page's own origin. */\n\torigin?: string\n\t/** Of the admin route's path, behind the Next basePath, with no trailing slash (`/` for the root). */\n\tpath: string\n}\n\nexport interface TrackerSlotConfig {\n\tslot: CaptureSlot\n\tkind: CaptureClientKind\n\tadapterId: string\n\t/** Mount the snippet and the sink talk to, relative and behind the Next basePath. */\n\tpath: string\n\t/** For a slot counting without consent, the variant it starts cookieless in. */\n\tsnippet: CaptureSnippet\n\t/**\n\t * The variant a slot counting without consent starts in when it is open at boot, present only\n\t * where it differs from `snippet` (PostHog, GA4). The tracker adopts whichever one is on the page.\n\t */\n\tfullSnippet?: CaptureSnippet\n\t/** What the adapter hands its browser client: public settings only, never a credential. */\n\tclient: { kind: CaptureClientKind } & Record<string, string | number | boolean>\n\t/**\n\t * The named vendor client this slot captures with, beside the other slot's client of the same\n\t * vendor: PostHog's `window.posthog[instance]`. Absent, the vendor's primary client.\n\t */\n\tinstance?: string\n\t/**\n\t * True when `capture.gate` holds this slot until the host's consent manager answers. Was\n\t * `requiresConsent` in 1.0.0-beta.11; the tracker still reads that from a cached config.\n\t */\n\tgated: boolean\n\t/**\n\t * What a held slot does before an answer and after a refusal, resolved on the server so the\n\t * browser never runs a host function. Absent (a config cached from 1.0.0-beta.14, or an adapter\n\t * that cannot run cookieless) means `off` in both phases.\n\t */\n\twithoutConsent?: SlotWithoutConsent\n}\n\n/**\n * Everything the browser tracker needs, served to any visitor: adapters' public `client` and\n * `snippet` settings only, never a query credential or a goal's admin-facing name.\n */\nexport interface TrackerConfig {\n\tslots: TrackerSlotConfig[]\n\tautoCapture: ResolvedAutoCapture\n\t/**\n\t * The request scope's goals, config merged with the collection. Built-in `purchase` stays out: it\n\t * matches by slug, and shipping it would tell every site it has a goal.\n\t */\n\tgoals: TrackerGoal[]\n\t/** Where the native sink posts events, relative and behind the Next basePath. */\n\tingestPath: string\n\t/**\n\t * The exclusion link for this request's scope, while `capture.exclusion` is on: its\n\t * parameter and the hash of its token. Absent, the tracker ignores the parameter.\n\t */\n\texclusion?: TrackerExclusion\n\t/** `capture.skip`, present only when the install turned one off. Absent, every skip is on. */\n\tskip?: TrackerSkip\n\t/** The page was rendered in draft mode (`getTrackerConfig`'s `draft`). */\n\tdraft?: true\n\t/**\n\t * Where Payload's admin answers, while previews are skipped: a page shown by one of its pages is\n\t * its live preview. Digests alone, so no page names the admin's host or route.\n\t */\n\tadmin?: AdminDigest\n}\n"],"mappings":";AAyFA,MAAa,uBAA4C;CACxD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,kBAAuC;CACnD,aAAa;CACb,QAAQ;CACR,OAAO;AACR;;AAGA,MAAa,uBAA4C;CACxD,aAAa;CACb,eAAe;CACf,eAAe;CACf,eAAe;CACf,OAAO;CACP,OAAO;AACR"}
@@ -4,7 +4,8 @@ import { Tracker, TrackerOptions } from "./types.js";
4
4
  //#region src/tracker/createTracker.d.ts
5
5
  /**
6
6
  * The browser tracker: one sink per slot behind a gate the host's consent manager answers, kept in
7
- * memory alone. No storage is touched before a slot opens, the exclusion link's own write aside.
7
+ * memory alone, each slot capturing in the mode its gate gives it. No storage is touched before a
8
+ * slot runs in full, the exclusion link's own aside.
8
9
  */
9
10
  declare const createTracker: (config: TrackerConfig, options?: TrackerOptions) => Tracker;
10
11
  //#endregion