@10x-media/analytics 1.0.0-beta.13 → 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 +53 -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 +26 -4
  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 +4 -2
  91. package/dist/providers/collection.js +29 -4
  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":"serverTrack.js","names":[],"sources":["../../../src/native/ingest/serverTrack.ts"],"sourcesContent":["import { createLocalReq, type Payload, type PayloadRequest } from 'payload'\nimport { captureRequest } from '../../capture/captureRequest'\nimport { warnUntrustedForwarding } from '../../capture/requestTrust'\nimport { gateHoldsAdapter } from '../../capture/slots'\nimport { currentDate } from '../../core/clock'\nimport type { AnalyticsAdapter } from '../../core/contract'\nimport {\n\tAnalyticsTrackError,\n\ttype ServerEventInput,\n\ttype ServerTrack,\n\ttype ServerTrackIdentity,\n\ttype ServerTrackOptions,\n} from '../../core/serverEvent'\nimport { kindOf } from '../../core/values'\nimport { openTransactionOf } from '../../db/openTransaction'\nimport { getRuntime } from '../../plugin/runtime'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { type NativeEngine, SERVER_CLOCK_SKEW_MS } from '../engine/engine'\nimport { type DailySalts, saltForHit } from '../engine/salt'\nimport type { SiteHosts } from '../engine/siteHosts'\nimport { toHit } from '../engine/toHit'\nimport type { HitWriter } from '../engine/writeBuffer'\nimport type { GeoResolver } from '../geo/geoResolver'\nimport { orderHitId, wireTwinOf } from '../store/ids'\nimport { type ClientIpOptions, overlayClientIp } from './clientIp'\nimport { SERVER_USER_AGENT } from './device'\nimport type { IngestAttribution, IngestResolvers } from './endpoint'\nimport { type ItemIngestOptions, normalizeEvent } from './normalizeEvent'\nimport { referrerHost } from './referrer'\nimport {\n\tdedupeKeyFor,\n\tisRefund,\n\tMAX_ORDER_ID_LENGTH,\n\torderDigestKey,\n\tsanitizeOrderId,\n\twarnUnconvertedOnce,\n\twarnUnmatchedRevenueGoal,\n} from './revenue'\nimport { rawEventError } from './validate'\n\n/** A warning each instance logs once, so a busy webhook says it once. */\nconst warningOncePer = (message: string): ((payload: Payload) => void) => {\n\tconst warned = new WeakSet<Payload>()\n\treturn (payload) => {\n\t\tif (warned.has(payload)) {\n\t\t\treturn\n\t\t}\n\t\twarned.add(payload)\n\t\tpayload.logger?.warn(message)\n\t}\n}\n\nconst warnUnresolvedZone = warningOncePer(\n\t'analytics: trackServerEvent hashes visitors by the UTC day for a scope whose reportingTimezone has never resolved: the resolver throws or answers something that is not an IANA timezone. Check that resolver, or pass event.timezone. Logged once.'\n)\n\n/** Ids of a sale's browser and server records, which a refund of it looks up. */\nconst saleRecordsOf = (sale: {\n\tscope: string | undefined\n\tgoal: string\n\torderId: string\n\tkey: Buffer | undefined\n}): { wire: string; server: string } => {\n\tconst parts = {\n\t\t...(sale.scope ? { tenant: sale.scope } : {}),\n\t\tgoal: sale.goal,\n\t\torderId: sale.orderId,\n\t\t...(sale.key ? { key: sale.key } : {}),\n\t}\n\treturn {\n\t\twire: orderHitId(dedupeKeyFor({ origin: 'wire', ...parts })),\n\t\tserver: orderHitId(dedupeKeyFor({ origin: 'server', ...parts })),\n\t}\n}\n\nconst isIdentity = (value: unknown): value is ServerTrackIdentity =>\n\tvalue === 'request' || value === 'none'\n\n/**\n * The identity of a call that names none: no visitor's while `capture.gate` holds a slot the\n * native beacon may fill, since the server cannot know the visitor's answer; else the request's.\n */\nconst defaultIdentity = (payload: Payload): ServerTrackIdentity => {\n\tconst runtime = getRuntime(payload)\n\tconst adapter = ingestAdapter(payload)\n\tif (!runtime || !adapter) {\n\t\treturn 'request'\n\t}\n\tconst kind = adapter.capture?.client.kind ?? 'native'\n\treturn gateHoldsAdapter(runtime, adapter.id, kind) ? 'none' : 'request'\n}\n\n/** An explicit `ip` or `userAgent` that the gated default set aside. */\nconst warnIgnoredVisitor = warningOncePer(\n\t\"analytics: trackServerEvent was given an ip or a userAgent but no identity, and capture.gate holds the native slot, so the event is recorded as no visitor's. Pass identity: 'request' where you know the visitor's answer allows it. Logged once.\"\n)\n\n/**\n * A scoped sale with neither `scope` nor `req` is filed under no tenant. Warned, never thrown: a\n * platform may record its own sales under the null scope on purpose.\n */\nconst warnUnscopedSale = warningOncePer(\n\t\"analytics: purchase or refund was called on a scoped install with neither scope nor req, so the sale is filed under the null scope: no tenant reports it, and the browser's record of the order never meets it. Pass scope (the tenant) or req. Logged once.\"\n)\n\n/** What one Payload instance stores a server event's hit through. */\nexport interface ServerTrackTarget {\n\tsalts: Pick<DailySalts, 'forHit' | 'forDay'>\n\twriter: Pick<HitWriter, 'write' | 'defer'>\n\titems?: ItemIngestOptions\n\t/** SQLite's single writer: a hit recorded inside an open host transaction waits for it. */\n\tsqlite: boolean\n\t/** Asks for maintenance in the background after a hit; it never waits for it. */\n\tnudge?: () => void\n\t/**\n\t * Refuses hits at or before the raw floor day, recounts a closed day a hit lands on, and says\n\t * where a refund's sale counts so the refund is filed beside it.\n\t */\n\tengine?: Pick<NativeEngine, 'serverHitDay' | 'reopen' | 'orderStored' | 'saleAttribution'>\n\t/** The hostnames each scope records hits under; absent, only the event's own is the site's. */\n\tsiteHosts?: SiteHosts\n}\n\ninterface ServerTrackDeps {\n\tgeoResolver: GeoResolver\n\t/** The salts, writer and items of the instance an event is recorded on. */\n\ttarget: (payload: Payload) => ServerTrackTarget\n\t/** Read late: the register context that carries them arrives after the adapter is built. */\n\tgetResolvers: () => IngestResolvers\n\t/** Read late for the same reason: the plugin option arrives with the register context. */\n\tgetAttribution: () => IngestAttribution\n}\n\n/**\n * The originating request's headers, so a server event attributes like its browser twin; `ip` and\n * `userAgent` override them. With neither, or `identity: 'none'`, the server agent stands in.\n */\nconst attributionHeaders = (\n\tevent: ServerEventInput,\n\ttrust: ClientIpOptions,\n\tbehind: { identity: ServerTrackIdentity; req: PayloadRequest | undefined }\n): Headers => {\n\tconst { identity, req } = behind\n\tif (identity === 'none') {\n\t\treturn new Headers({ 'user-agent': SERVER_USER_AGENT })\n\t}\n\tconst own = new Headers(req?.headers)\n\tconst headers = event.ip ? overlayClientIp(own, event.ip, trust) : own\n\tif (event.userAgent) {\n\t\theaders.set('user-agent', event.userAgent)\n\t}\n\tif (!headers.get('user-agent')) {\n\t\theaders.set('user-agent', SERVER_USER_AGENT)\n\t}\n\treturn headers\n}\n\n/**\n * The caller's scope, else the request's resolved without the signed-in user or cookies, so an\n * editor's sale is filed under the site it happened on.\n */\nconst resolveScope = async (\n\tevent: ServerEventInput,\n\topts: ServerTrackOptions | undefined,\n\tresolvers: IngestResolvers\n): Promise<string | undefined> => {\n\t// An unscoped install has no scope resolver and no scope field on its rows, so a scope\n\t// declared by the caller is ignored exactly as the endpoint ignores one on the wire.\n\tif (!resolvers.scope) {\n\t\treturn undefined\n\t}\n\tif (event.scope !== undefined) {\n\t\treturn event.scope ?? ''\n\t}\n\tif (!opts?.req) {\n\t\treturn ''\n\t}\n\treturn (await resolvers.scope(captureRequest(opts.req))) ?? ''\n}\n\n/**\n * `adapter.ingest.track`: the endpoint's write path, outside any caller transaction. On SQLite a\n * call inside an open transaction resolves at once and stores its hit when that transaction ends.\n */\nexport const makeServerTrack =\n\t(deps: ServerTrackDeps): ServerTrack =>\n\tasync (payload, event, opts) => {\n\t\t// Trusted server code: it supplies its own hostname, so the resolver the HTTP endpoint\n\t\t// runs is bypassed and the hostname stays required here.\n\t\tconst invalid = rawEventError(event, { allowRevenue: true, requireHostname: true })\n\t\tif (invalid) {\n\t\t\tthrow new AnalyticsTrackError(`analytics: trackServerEvent needs a valid \"${invalid}\"`)\n\t\t}\n\t\t// Refused rather than dropped: a sale stored without its key would count again on every retry.\n\t\tif (event.orderId !== undefined && sanitizeOrderId(event.orderId) === undefined) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t`analytics: trackServerEvent needs a valid \"orderId\": a string of 1 to ${MAX_ORDER_ID_LENGTH} characters without control characters, so a retried order counts once`\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\tisRefund(event.revenue === true, event.value) &&\n\t\t\tsanitizeOrderId(event.orderId) !== undefined &&\n\t\t\tsanitizeOrderId(event.refundId) === undefined\n\t\t) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t'analytics: trackServerEvent needs a valid \"refundId\" on a refund of an order: the refund\\'s own id, so each partial refund counts once'\n\t\t\t)\n\t\t}\n\t\t// Refused rather than read as the default: a misspelt 'none' must not attribute the visitor.\n\t\tif (opts?.identity !== undefined && !isIdentity(opts.identity)) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t`analytics: trackServerEvent's identity must be 'request' or 'none', got ${kindOf(opts.identity)}`\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\tevent.now !== undefined &&\n\t\t\t!(event.now instanceof Date && Number.isFinite(event.now.getTime()))\n\t\t) {\n\t\t\tthrow new AnalyticsTrackError('analytics: trackServerEvent needs a valid \"now\"')\n\t\t}\n\t\tconst identity = opts?.identity ?? defaultIdentity(payload)\n\t\tif (opts?.identity === undefined && identity === 'none' && (event.ip || event.userAgent)) {\n\t\t\twarnIgnoredVisitor(payload)\n\t\t}\n\t\tconst receivedAt = currentDate()\n\t\tconst now = event.now ?? receivedAt\n\t\tif (now.getTime() > receivedAt.getTime() + SERVER_CLOCK_SKEW_MS) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t`analytics: trackServerEvent's \"now\" (${now.toISOString()}) is more than ${SERVER_CLOCK_SKEW_MS / 60_000} minutes ahead of the server's clock`\n\t\t\t)\n\t\t}\n\t\tconst target = deps.target(payload)\n\t\tif (\n\t\t\tevent.revenue === true &&\n\t\t\tevent.scope === undefined &&\n\t\t\t!opts?.req &&\n\t\t\tdeps.getResolvers().scope\n\t\t) {\n\t\t\twarnUnscopedSale(payload)\n\t\t}\n\n\t\tconst record = async (): Promise<void> => {\n\t\t\tconst resolvers = deps.getResolvers()\n\t\t\tconst scope = await resolveScope(event, opts, resolvers)\n\t\t\t// Refused before anything is written: a day whose raw hits may be pruned is never counted.\n\t\t\tconst placed = await target.engine?.serverHitDay(scope ?? '', now)\n\t\t\t// createLocalReq mutates its request, so a caller's req never reaches it: resolvers see it\n\t\t\t// as a capture does, without the user or cookies, and a fresh one is built only on demand.\n\t\t\tlet local: PayloadRequest | undefined\n\t\t\tconst requestFor = async (): Promise<PayloadRequest> => {\n\t\t\t\tif (opts?.req) {\n\t\t\t\t\treturn captureRequest(opts.req)\n\t\t\t\t}\n\t\t\t\tlocal ??= await createLocalReq({}, payload)\n\t\t\t\treturn local\n\t\t\t}\n\t\t\tconst salt = await saltForHit(\n\t\t\t\ttarget.salts,\n\t\t\t\t{\n\t\t\t\t\tscope: scope ?? '',\n\t\t\t\t\tat: now,\n\t\t\t\t\tzone: async () =>\n\t\t\t\t\t\tevent.timezone ??\n\t\t\t\t\t\t(resolvers.timezone\n\t\t\t\t\t\t\t? resolvers.timezone(await requestFor(), scope ?? null)\n\t\t\t\t\t\t\t: DEFAULT_TIMEZONE),\n\t\t\t\t},\n\t\t\t\t() => warnUnresolvedZone(payload)\n\t\t\t)\n\t\t\t// Goals resolve under the scope the event is stamped with, so a tenant's server event\n\t\t\t// can only ever complete that tenant's goals.\n\t\t\tconst goals = resolvers.goals\n\t\t\t\t? await resolvers.goals(await requestFor(), scope ?? null)\n\t\t\t\t: undefined\n\t\t\tconst reportingCurrency = resolvers.currency\n\t\t\t\t? await resolvers.currency(await requestFor(), scope ?? null)\n\t\t\t\t: undefined\n\t\t\tconst attribution = deps.getAttribution()\n\t\t\tconst orderKey = orderDigestKey(payload.secret)\n\t\t\tconst trust: ClientIpOptions = {\n\t\t\t\ttrustedProxyHops: attribution.trustedProxyHops,\n\t\t\t\ttrustedPlatform: attribution.trustedPlatform,\n\t\t\t}\n\t\t\tif (opts?.req && !event.ip && identity !== 'none') {\n\t\t\t\twarnUntrustedForwarding(payload, opts.req.headers, trust)\n\t\t\t}\n\t\t\tconst siblings =\n\t\t\t\ttarget.siteHosts &&\n\t\t\t\tevent.type === 'pageview' &&\n\t\t\t\treferrerHost(event.referrer, event.hostname) !== undefined\n\t\t\t\t\t? await target.siteHosts.of(scope ?? '')\n\t\t\t\t\t: undefined\n\t\t\tconst normalized = await normalizeEvent({\n\t\t\t\traw: {\n\t\t\t\t\ttype: event.type,\n\t\t\t\t\tname: event.name,\n\t\t\t\t\tpath: event.path,\n\t\t\t\t\treferrer: event.referrer,\n\t\t\t\t\tquery: event.query,\n\t\t\t\t\tprops: event.props,\n\t\t\t\t\tvalue: event.value,\n\t\t\t\t\tcurrency: event.currency,\n\t\t\t\t\titems: event.items,\n\t\t\t\t\trevenue: event.revenue,\n\t\t\t\t\torderId: event.orderId,\n\t\t\t\t\trefundId: event.refundId,\n\t\t\t\t\titem: event.item,\n\t\t\t\t},\n\t\t\t\thostname: event.hostname,\n\t\t\t\theaders: attributionHeaders(event, trust, { identity, req: opts?.req }),\n\t\t\t\tgeoResolver: deps.geoResolver,\n\t\t\t\twarnGeo: (message) => payload.logger?.warn(message),\n\t\t\t\tsalt,\n\t\t\t\tnow,\n\t\t\t\tscope,\n\t\t\t\tgoals,\n\t\t\t\torigin: 'server',\n\t\t\t\treportingCurrency,\n\t\t\t\tconvertCurrency: resolvers.convertCurrency,\n\t\t\t\twarnUnconverted: () => warnUnconvertedOnce(payload.logger),\n\t\t\t\t...trust,\n\t\t\t\t...(target.items ? { items: target.items } : {}),\n\t\t\t\t...(siblings ? { siblings } : {}),\n\t\t\t\torderKey,\n\t\t\t})\n\t\t\t// Only the server path can reach this: a public beacon's caller must never be able to\n\t\t\t// write lines into the host's log.\n\t\t\tif (event.revenue === true && normalized.goals === undefined) {\n\t\t\t\twarnUnmatchedRevenueGoal(payload.logger, event.name ?? event.type)\n\t\t\t}\n\t\t\t// An order bypasses the buffer and meets its own primary key: a retry stores nothing. A hit\n\t\t\t// on a closed day is stored before its day is reopened, so the count after it holds it.\n\t\t\tconst late = placed?.closed === true\n\t\t\tconst counted = toHit(normalized, { receivedAt })\n\t\t\tconst orderId = sanitizeOrderId(event.orderId)\n\t\t\t// A refund with no visitor of its own is filed where its sale counts, so every breakdown\n\t\t\t// still sums to the total.\n\t\t\tconst hit =\n\t\t\t\tnormalized.refund && counted.v === '' && orderId !== undefined && target.engine\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...counted,\n\t\t\t\t\t\t\t...(await target.engine.saleAttribution(\n\t\t\t\t\t\t\t\tscope ?? '',\n\t\t\t\t\t\t\t\tsaleRecordsOf({\n\t\t\t\t\t\t\t\t\tscope,\n\t\t\t\t\t\t\t\t\tgoal: normalized.name ?? normalized.type,\n\t\t\t\t\t\t\t\t\torderId,\n\t\t\t\t\t\t\t\t\tkey: orderKey,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)),\n\t\t\t\t\t\t}\n\t\t\t\t\t: counted\n\t\t\tconst stored = await target.writer.write(hit, {\n\t\t\t\t...(opts?.flush || late ? { flush: true } : {}),\n\t\t\t})\n\t\t\ttarget.siteHosts?.saw(scope ?? '', normalized.hostname)\n\t\t\t// A retried order stores nothing, so it counts no day again.\n\t\t\tconst fresh = stored === undefined || stored.written > 0\n\t\t\tif (placed && late && fresh) {\n\t\t\t\tawait target.engine?.reopen(placed)\n\t\t\t}\n\t\t\tif (wireTwinOf(hit.id) !== undefined && !normalized.refund && fresh) {\n\t\t\t\tawait target.engine?.orderStored(scope ?? '', hit.id)\n\t\t\t}\n\t\t}\n\n\t\t// The host holds SQLite's one write lock until its transaction ends, and a write that waited\n\t\t// for it here would wait on the very caller it is part of.\n\t\tconst open = target.sqlite ? await openTransactionOf(payload, opts?.req) : undefined\n\t\tif (open) {\n\t\t\ttarget.writer.defer(record, open)\n\t\t\treturn\n\t\t}\n\t\tawait record()\n\t\ttarget.nudge?.()\n\t}\n\n/**\n * First registered adapter with a server ingestion seam. Callers read every other seam off it too,\n * so an event cannot be judged by one adapter and written by another.\n */\nexport const ingestAdapter = (payload: Payload): AnalyticsAdapter | undefined =>\n\tgetRuntime(payload)\n\t\t?.registry.all()\n\t\t.find((adapter) => adapter.ingest?.track)\n\n/**\n * Records an event from server code through the native adapter, normalized as a beacon is. Without\n * `opts.identity` it is no visitor's while `capture.gate` holds the native slot.\n */\nexport const trackServerEvent = async (\n\tpayload: Payload,\n\tevent: ServerEventInput,\n\topts?: ServerTrackOptions\n): Promise<void> => {\n\tconst track = ingestAdapter(payload)?.ingest?.track\n\tif (!track) {\n\t\tthrow new AnalyticsTrackError(\n\t\t\t'analytics: trackServerEvent needs the native adapter; provider-slot server tracking is not supported yet'\n\t\t)\n\t}\n\tawait track(payload, event, opts)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,kBAAkB,YAAkD;CACzE,MAAM,yBAAS,IAAI,QAAiB;CACpC,QAAQ,YAAY;EACnB,IAAI,OAAO,IAAI,OAAO,GACrB;EAED,OAAO,IAAI,OAAO;EAClB,QAAQ,QAAQ,KAAK,OAAO;CAC7B;AACD;AAEA,MAAM,qBAAqB,eAC1B,qPACD;;AAGA,MAAM,iBAAiB,SAKiB;CACvC,MAAM,QAAQ;EACb,GAAI,KAAK,QAAQ,EAAE,QAAQ,KAAK,MAAM,IAAI,CAAC;EAC3C,MAAM,KAAK;EACX,SAAS,KAAK;EACd,GAAI,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;CACrC;CACA,OAAO;EACN,MAAM,WAAW,aAAa;GAAE,QAAQ;GAAQ,GAAG;EAAM,CAAC,CAAC;EAC3D,QAAQ,WAAW,aAAa;GAAE,QAAQ;GAAU,GAAG;EAAM,CAAC,CAAC;CAChE;AACD;AAEA,MAAM,cAAc,UACnB,UAAU,aAAa,UAAU;;;;;AAMlC,MAAM,mBAAmB,YAA0C;CAClE,MAAM,UAAU,WAAW,OAAO;CAClC,MAAM,UAAU,cAAc,OAAO;CACrC,IAAI,CAAC,WAAW,CAAC,SAChB,OAAO;CAER,MAAM,OAAO,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I,oBACT,0GACD;CAED,MAAM,MAAM,SAAS,OAAO,IAAI;AACjC"}
1
+ {"version":3,"file":"serverTrack.js","names":[],"sources":["../../../src/native/ingest/serverTrack.ts"],"sourcesContent":["import { createLocalReq, type Payload, type PayloadRequest } from 'payload'\nimport { captureRequest } from '../../capture/captureRequest'\nimport { warnUntrustedForwarding } from '../../capture/requestTrust'\nimport { gateHoldsAdapter } from '../../capture/slots'\nimport { currentDate } from '../../core/clock'\nimport type { AnalyticsAdapter } from '../../core/contract'\nimport {\n\tAnalyticsTrackError,\n\ttype ServerEventInput,\n\ttype ServerTrack,\n\ttype ServerTrackIdentity,\n\ttype ServerTrackOptions,\n} from '../../core/serverEvent'\nimport { kindOf } from '../../core/values'\nimport { openTransactionOf } from '../../db/openTransaction'\nimport { getRuntime } from '../../plugin/runtime'\nimport { DEFAULT_TIMEZONE } from '../../timeframe/tz'\nimport { type NativeEngine, SERVER_CLOCK_SKEW_MS } from '../engine/engine'\nimport { type DailySalts, saltForHit } from '../engine/salt'\nimport type { SiteHosts } from '../engine/siteHosts'\nimport { toHit } from '../engine/toHit'\nimport type { HitWriter } from '../engine/writeBuffer'\nimport type { GeoResolver } from '../geo/geoResolver'\nimport { orderHitId, wireTwinOf } from '../store/ids'\nimport { type ClientIpOptions, overlayClientIp } from './clientIp'\nimport { SERVER_USER_AGENT } from './device'\nimport type { IngestAttribution, IngestResolvers } from './endpoint'\nimport { type ItemIngestOptions, normalizeEvent } from './normalizeEvent'\nimport { referrerHost } from './referrer'\nimport {\n\tdedupeKeyFor,\n\tisRefund,\n\tMAX_ORDER_ID_LENGTH,\n\torderDigestKey,\n\tsanitizeOrderId,\n\twarnUnconvertedOnce,\n\twarnUnmatchedRevenueGoal,\n} from './revenue'\nimport { rawEventError } from './validate'\n\n/** A warning each instance logs once, so a busy webhook says it once. */\nconst warningOncePer = (message: string): ((payload: Payload) => void) => {\n\tconst warned = new WeakSet<Payload>()\n\treturn (payload) => {\n\t\tif (warned.has(payload)) {\n\t\t\treturn\n\t\t}\n\t\twarned.add(payload)\n\t\tpayload.logger?.warn(message)\n\t}\n}\n\nconst warnUnresolvedZone = warningOncePer(\n\t'analytics: trackServerEvent hashes visitors by the UTC day for a scope whose reportingTimezone has never resolved: the resolver throws or answers something that is not an IANA timezone. Check that resolver, or pass event.timezone. Logged once.'\n)\n\n/** Ids of a sale's browser and server records, which a refund of it looks up. */\nconst saleRecordsOf = (sale: {\n\tscope: string | undefined\n\tgoal: string\n\torderId: string\n\tkey: Buffer | undefined\n}): { wire: string; server: string } => {\n\tconst parts = {\n\t\t...(sale.scope ? { tenant: sale.scope } : {}),\n\t\tgoal: sale.goal,\n\t\torderId: sale.orderId,\n\t\t...(sale.key ? { key: sale.key } : {}),\n\t}\n\treturn {\n\t\twire: orderHitId(dedupeKeyFor({ origin: 'wire', ...parts })),\n\t\tserver: orderHitId(dedupeKeyFor({ origin: 'server', ...parts })),\n\t}\n}\n\nconst isIdentity = (value: unknown): value is ServerTrackIdentity =>\n\tvalue === 'request' || value === 'none'\n\n/**\n * The identity of a call that names none: no visitor's while `capture.gate` holds a slot the\n * native beacon may fill, since the server cannot know the visitor's answer; else the request's.\n */\nconst defaultIdentity = (payload: Payload): ServerTrackIdentity => {\n\tconst runtime = getRuntime(payload)\n\tconst adapter = ingestAdapter(payload)\n\tif (!runtime || !adapter) {\n\t\treturn 'request'\n\t}\n\tconst kind = adapter.capture?.client.kind ?? 'native'\n\treturn gateHoldsAdapter(runtime, adapter.id, kind) ? 'none' : 'request'\n}\n\n/** An explicit `ip` or `userAgent` that the gated default set aside. */\nconst warnIgnoredVisitor = warningOncePer(\n\t\"analytics: trackServerEvent was given an ip or a userAgent but no identity, and capture.gate holds the native slot, so the event is recorded as no visitor's. Pass identity: 'request' where you know the visitor's answer allows it. Logged once.\"\n)\n\n/**\n * A scoped sale with neither `scope` nor `req` is filed under no tenant. Warned, never thrown: a\n * platform may record its own sales under the null scope on purpose.\n */\nconst warnUnscopedSale = warningOncePer(\n\t\"analytics: purchase or refund was called on a scoped install with neither scope nor req, so the sale is filed under the null scope: no tenant reports it, and the browser's record of the order never meets it. Pass scope (the tenant) or req. Logged once.\"\n)\n\n/** What one Payload instance stores a server event's hit through. */\nexport interface ServerTrackTarget {\n\tsalts: Pick<DailySalts, 'forHit' | 'forDay'>\n\twriter: Pick<HitWriter, 'write' | 'defer'>\n\titems?: ItemIngestOptions\n\t/** SQLite's single writer: a hit recorded inside an open host transaction waits for it. */\n\tsqlite: boolean\n\t/** Asks for maintenance in the background after a hit; it never waits for it. */\n\tnudge?: () => void\n\t/**\n\t * Refuses hits at or before the raw floor day, recounts a closed day a hit lands on, and says\n\t * where a refund's sale counts so the refund is filed beside it.\n\t */\n\tengine?: Pick<NativeEngine, 'serverHitDay' | 'reopen' | 'orderStored' | 'saleAttribution'>\n\t/** The hostnames each scope records hits under; absent, only the event's own is the site's. */\n\tsiteHosts?: SiteHosts\n}\n\ninterface ServerTrackDeps {\n\tgeoResolver: GeoResolver\n\t/** The salts, writer and items of the instance an event is recorded on. */\n\ttarget: (payload: Payload) => ServerTrackTarget\n\t/** Read late: the register context that carries them arrives after the adapter is built. */\n\tgetResolvers: () => IngestResolvers\n\t/** Read late for the same reason: the plugin option arrives with the register context. */\n\tgetAttribution: () => IngestAttribution\n}\n\n/**\n * The originating request's headers, so a server event attributes like its browser twin; `ip` and\n * `userAgent` override them. With neither, or `identity: 'none'`, the server agent stands in.\n */\nconst attributionHeaders = (\n\tevent: ServerEventInput,\n\ttrust: ClientIpOptions,\n\tbehind: { identity: ServerTrackIdentity; req: PayloadRequest | undefined }\n): Headers => {\n\tconst { identity, req } = behind\n\tif (identity === 'none') {\n\t\treturn new Headers({ 'user-agent': SERVER_USER_AGENT })\n\t}\n\tconst own = new Headers(req?.headers)\n\tconst headers = event.ip ? overlayClientIp(own, event.ip, trust) : own\n\tif (event.userAgent) {\n\t\theaders.set('user-agent', event.userAgent)\n\t}\n\tif (!headers.get('user-agent')) {\n\t\theaders.set('user-agent', SERVER_USER_AGENT)\n\t}\n\treturn headers\n}\n\n/**\n * The caller's scope, else the request's resolved without the signed-in user or cookies, so an\n * editor's sale is filed under the site it happened on.\n */\nconst resolveScope = async (\n\tevent: ServerEventInput,\n\topts: ServerTrackOptions | undefined,\n\tresolvers: IngestResolvers\n): Promise<string | undefined> => {\n\t// An unscoped install has no scope resolver and no scope field on its rows, so a scope\n\t// declared by the caller is ignored exactly as the endpoint ignores one on the wire.\n\tif (!resolvers.scope) {\n\t\treturn undefined\n\t}\n\tif (event.scope !== undefined) {\n\t\treturn event.scope ?? ''\n\t}\n\tif (!opts?.req) {\n\t\treturn ''\n\t}\n\treturn (await resolvers.scope(captureRequest(opts.req))) ?? ''\n}\n\n/**\n * `adapter.ingest.track`: the endpoint's write path, outside any caller transaction. On SQLite a\n * call inside an open transaction resolves at once and stores its hit when that transaction ends.\n */\nexport const makeServerTrack =\n\t(deps: ServerTrackDeps): ServerTrack =>\n\tasync (payload, event, opts) => {\n\t\t// Trusted server code: it supplies its own hostname, so the resolver the HTTP endpoint\n\t\t// runs is bypassed and the hostname stays required here.\n\t\tconst invalid = rawEventError(event, { allowRevenue: true, requireHostname: true })\n\t\tif (invalid) {\n\t\t\tthrow new AnalyticsTrackError(`analytics: trackServerEvent needs a valid \"${invalid}\"`)\n\t\t}\n\t\t// Refused rather than dropped: a sale stored without its key would count again on every retry.\n\t\tif (event.orderId !== undefined && sanitizeOrderId(event.orderId) === undefined) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t`analytics: trackServerEvent needs a valid \"orderId\": a string of 1 to ${MAX_ORDER_ID_LENGTH} characters without control characters, so a retried order counts once`\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\tisRefund(event.revenue === true, event.value) &&\n\t\t\tsanitizeOrderId(event.orderId) !== undefined &&\n\t\t\tsanitizeOrderId(event.refundId) === undefined\n\t\t) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t'analytics: trackServerEvent needs a valid \"refundId\" on a refund of an order: the refund\\'s own id, so each partial refund counts once'\n\t\t\t)\n\t\t}\n\t\t// Refused rather than read as the default: a misspelt 'none' must not attribute the visitor.\n\t\tif (opts?.identity !== undefined && !isIdentity(opts.identity)) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t`analytics: trackServerEvent's identity must be 'request' or 'none', got ${kindOf(opts.identity)}`\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\tevent.now !== undefined &&\n\t\t\t!(event.now instanceof Date && Number.isFinite(event.now.getTime()))\n\t\t) {\n\t\t\tthrow new AnalyticsTrackError('analytics: trackServerEvent needs a valid \"now\"')\n\t\t}\n\t\tconst identity = opts?.identity ?? defaultIdentity(payload)\n\t\tif (opts?.identity === undefined && identity === 'none' && (event.ip || event.userAgent)) {\n\t\t\twarnIgnoredVisitor(payload)\n\t\t}\n\t\tconst receivedAt = currentDate()\n\t\tconst now = event.now ?? receivedAt\n\t\tif (now.getTime() > receivedAt.getTime() + SERVER_CLOCK_SKEW_MS) {\n\t\t\tthrow new AnalyticsTrackError(\n\t\t\t\t`analytics: trackServerEvent's \"now\" (${now.toISOString()}) is more than ${SERVER_CLOCK_SKEW_MS / 60_000} minutes ahead of the server's clock`\n\t\t\t)\n\t\t}\n\t\tconst target = deps.target(payload)\n\t\tif (\n\t\t\tevent.revenue === true &&\n\t\t\tevent.scope === undefined &&\n\t\t\t!opts?.req &&\n\t\t\tdeps.getResolvers().scope\n\t\t) {\n\t\t\twarnUnscopedSale(payload)\n\t\t}\n\n\t\tconst record = async (): Promise<void> => {\n\t\t\tconst resolvers = deps.getResolvers()\n\t\t\tconst scope = await resolveScope(event, opts, resolvers)\n\t\t\t// Refused before anything is written: a day whose raw hits may be pruned is never counted.\n\t\t\tconst placed = await target.engine?.serverHitDay(scope ?? '', now)\n\t\t\t// createLocalReq mutates its request, so a caller's req never reaches it: resolvers see it\n\t\t\t// as a capture does, without the user or cookies, and a fresh one is built only on demand.\n\t\t\tlet local: PayloadRequest | undefined\n\t\t\tconst requestFor = async (): Promise<PayloadRequest> => {\n\t\t\t\tif (opts?.req) {\n\t\t\t\t\treturn captureRequest(opts.req)\n\t\t\t\t}\n\t\t\t\tlocal ??= await createLocalReq({}, payload)\n\t\t\t\treturn local\n\t\t\t}\n\t\t\tconst salt = await saltForHit(\n\t\t\t\ttarget.salts,\n\t\t\t\t{\n\t\t\t\t\tscope: scope ?? '',\n\t\t\t\t\tat: now,\n\t\t\t\t\tzone: async () =>\n\t\t\t\t\t\tevent.timezone ??\n\t\t\t\t\t\t(resolvers.timezone\n\t\t\t\t\t\t\t? resolvers.timezone(await requestFor(), scope ?? null)\n\t\t\t\t\t\t\t: DEFAULT_TIMEZONE),\n\t\t\t\t},\n\t\t\t\t() => warnUnresolvedZone(payload)\n\t\t\t)\n\t\t\t// Goals resolve under the scope the event is stamped with, so a tenant's server event\n\t\t\t// can only ever complete that tenant's goals.\n\t\t\tconst goals = resolvers.goals\n\t\t\t\t? await resolvers.goals(await requestFor(), scope ?? null)\n\t\t\t\t: undefined\n\t\t\tconst reportingCurrency = resolvers.currency\n\t\t\t\t? await resolvers.currency(await requestFor(), scope ?? null)\n\t\t\t\t: undefined\n\t\t\tconst attribution = deps.getAttribution()\n\t\t\tconst orderKey = orderDigestKey(payload.secret)\n\t\t\tconst trust: ClientIpOptions = {\n\t\t\t\ttrustedProxyHops: attribution.trustedProxyHops,\n\t\t\t\ttrustedPlatform: attribution.trustedPlatform,\n\t\t\t}\n\t\t\tif (opts?.req && !event.ip && identity !== 'none') {\n\t\t\t\twarnUntrustedForwarding(payload, opts.req.headers, trust)\n\t\t\t}\n\t\t\tconst siblings =\n\t\t\t\ttarget.siteHosts &&\n\t\t\t\tevent.type === 'pageview' &&\n\t\t\t\treferrerHost(event.referrer, event.hostname) !== undefined\n\t\t\t\t\t? await target.siteHosts.of(scope ?? '')\n\t\t\t\t\t: undefined\n\t\t\tconst normalized = await normalizeEvent({\n\t\t\t\traw: {\n\t\t\t\t\ttype: event.type,\n\t\t\t\t\tname: event.name,\n\t\t\t\t\tpath: event.path,\n\t\t\t\t\treferrer: event.referrer,\n\t\t\t\t\tquery: event.query,\n\t\t\t\t\tprops: event.props,\n\t\t\t\t\tvalue: event.value,\n\t\t\t\t\tcurrency: event.currency,\n\t\t\t\t\titems: event.items,\n\t\t\t\t\trevenue: event.revenue,\n\t\t\t\t\torderId: event.orderId,\n\t\t\t\t\trefundId: event.refundId,\n\t\t\t\t\titem: event.item,\n\t\t\t\t},\n\t\t\t\thostname: event.hostname,\n\t\t\t\theaders: attributionHeaders(event, trust, { identity, req: opts?.req }),\n\t\t\t\tgeoResolver: deps.geoResolver,\n\t\t\t\twarnGeo: (message) => payload.logger?.warn(message),\n\t\t\t\tsalt,\n\t\t\t\tnow,\n\t\t\t\tscope,\n\t\t\t\tgoals,\n\t\t\t\torigin: 'server',\n\t\t\t\treportingCurrency,\n\t\t\t\tconvertCurrency: resolvers.convertCurrency,\n\t\t\t\twarnUnconverted: () => warnUnconvertedOnce(payload.logger),\n\t\t\t\t...trust,\n\t\t\t\t...(target.items ? { items: target.items } : {}),\n\t\t\t\t...(siblings ? { siblings } : {}),\n\t\t\t\torderKey,\n\t\t\t\tmode: identity === 'none' ? 'a' : 'f',\n\t\t\t})\n\t\t\t// Only the server path can reach this: a public beacon's caller must never be able to\n\t\t\t// write lines into the host's log.\n\t\t\tif (event.revenue === true && normalized.goals === undefined) {\n\t\t\t\twarnUnmatchedRevenueGoal(payload.logger, event.name ?? event.type)\n\t\t\t}\n\t\t\t// An order bypasses the buffer and meets its own primary key: a retry stores nothing. A hit\n\t\t\t// on a closed day is stored before its day is reopened, so the count after it holds it.\n\t\t\tconst late = placed?.closed === true\n\t\t\tconst counted = toHit(normalized, { receivedAt })\n\t\t\tconst orderId = sanitizeOrderId(event.orderId)\n\t\t\t// A refund with no visitor of its own is filed where its sale counts, so every breakdown\n\t\t\t// still sums to the total.\n\t\t\tconst hit =\n\t\t\t\tnormalized.refund && counted.v === '' && orderId !== undefined && target.engine\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...counted,\n\t\t\t\t\t\t\t...(await target.engine.saleAttribution(\n\t\t\t\t\t\t\t\tscope ?? '',\n\t\t\t\t\t\t\t\tsaleRecordsOf({\n\t\t\t\t\t\t\t\t\tscope,\n\t\t\t\t\t\t\t\t\tgoal: normalized.name ?? normalized.type,\n\t\t\t\t\t\t\t\t\torderId,\n\t\t\t\t\t\t\t\t\tkey: orderKey,\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t)),\n\t\t\t\t\t\t}\n\t\t\t\t\t: counted\n\t\t\tconst stored = await target.writer.write(hit, {\n\t\t\t\t...(opts?.flush || late ? { flush: true } : {}),\n\t\t\t})\n\t\t\ttarget.siteHosts?.saw(scope ?? '', normalized.hostname)\n\t\t\t// A retried order stores nothing, so it counts no day again.\n\t\t\tconst fresh = stored === undefined || stored.written > 0\n\t\t\tif (placed && late && fresh) {\n\t\t\t\tawait target.engine?.reopen(placed)\n\t\t\t}\n\t\t\tif (wireTwinOf(hit.id) !== undefined && !normalized.refund && fresh) {\n\t\t\t\tawait target.engine?.orderStored(scope ?? '', hit.id)\n\t\t\t}\n\t\t}\n\n\t\t// The host holds SQLite's one write lock until its transaction ends, and a write that waited\n\t\t// for it here would wait on the very caller it is part of.\n\t\tconst open = target.sqlite ? await openTransactionOf(payload, opts?.req) : undefined\n\t\tif (open) {\n\t\t\ttarget.writer.defer(record, open)\n\t\t\treturn\n\t\t}\n\t\tawait record()\n\t\ttarget.nudge?.()\n\t}\n\n/**\n * First registered adapter with a server ingestion seam. Callers read every other seam off it too,\n * so an event cannot be judged by one adapter and written by another.\n */\nexport const ingestAdapter = (payload: Payload): AnalyticsAdapter | undefined =>\n\tgetRuntime(payload)\n\t\t?.registry.all()\n\t\t.find((adapter) => adapter.ingest?.track)\n\n/**\n * Records an event from server code through the native adapter, normalized as a beacon is. Without\n * `opts.identity` it is no visitor's while `capture.gate` holds the native slot.\n */\nexport const trackServerEvent = async (\n\tpayload: Payload,\n\tevent: ServerEventInput,\n\topts?: ServerTrackOptions\n): Promise<void> => {\n\tconst track = ingestAdapter(payload)?.ingest?.track\n\tif (!track) {\n\t\tthrow new AnalyticsTrackError(\n\t\t\t'analytics: trackServerEvent needs the native adapter; provider-slot server tracking is not supported yet'\n\t\t)\n\t}\n\tawait track(payload, event, opts)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,kBAAkB,YAAkD;CACzE,MAAM,yBAAS,IAAI,QAAiB;CACpC,QAAQ,YAAY;EACnB,IAAI,OAAO,IAAI,OAAO,GACrB;EAED,OAAO,IAAI,OAAO;EAClB,QAAQ,QAAQ,KAAK,OAAO;CAC7B;AACD;AAEA,MAAM,qBAAqB,eAC1B,qPACD;;AAGA,MAAM,iBAAiB,SAKiB;CACvC,MAAM,QAAQ;EACb,GAAI,KAAK,QAAQ,EAAE,QAAQ,KAAK,MAAM,IAAI,CAAC;EAC3C,MAAM,KAAK;EACX,SAAS,KAAK;EACd,GAAI,KAAK,MAAM,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;CACrC;CACA,OAAO;EACN,MAAM,WAAW,aAAa;GAAE,QAAQ;GAAQ,GAAG;EAAM,CAAC,CAAC;EAC3D,QAAQ,WAAW,aAAa;GAAE,QAAQ;GAAU,GAAG;EAAM,CAAC,CAAC;CAChE;AACD;AAEA,MAAM,cAAc,UACnB,UAAU,aAAa,UAAU;;;;;AAMlC,MAAM,mBAAmB,YAA0C;CAClE,MAAM,UAAU,WAAW,OAAO;CAClC,MAAM,UAAU,cAAc,OAAO;CACrC,IAAI,CAAC,WAAW,CAAC,SAChB,OAAO;CAER,MAAM,OAAO,QAAQ,SAAS,OAAO,QAAQ;CAC7C,OAAO,iBAAiB,SAAS,QAAQ,IAAI,IAAI,IAAI,SAAS;AAC/D;;AAGA,MAAM,qBAAqB,eAC1B,oPACD;;;;;AAMA,MAAM,mBAAmB,eACxB,8PACD;;;;;AAkCA,MAAM,sBACL,OACA,O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U,gBAAgB,MAAM,OAAO;EAG7C,MAAM,MACL,WAAW,UAAU,QAAQ,MAAM,MAAM,YAAY,KAAA,KAAa,OAAO,SACtE;GACA,GAAG;GACH,GAAI,MAAM,OAAO,OAAO,gBACvB,SAAS,IACT,cAAc;IACb;IACA,MAAM,WAAW,QAAQ,WAAW;IACpC;IACA,KAAK;GACN,CAAC,CACF;EACD,IACC;EACJ,MAAM,SAAS,MAAM,OAAO,OAAO,MAAM,KAAK,EAC7C,GAAI,MAAM,SAAS,OAAO,EAAE,OAAO,KAAK,IAAI,CAAC,EAC9C,CAAC;EACD,OAAO,WAAW,IAAI,SAAS,IAAI,WAAW,QAAQ;EAEtD,MAAM,QAAQ,WAAW,KAAA,KAAa,OAAO,UAAU;EACvD,IAAI,UAAU,QAAQ,OACrB,MAAM,OAAO,QAAQ,OAAO,MAAM;EAEnC,IAAI,WAAW,IAAI,EAAE,MAAM,KAAA,KAAa,CAAC,WAAW,UAAU,OAC7D,MAAM,OAAO,QAAQ,YAAY,SAAS,IAAI,IAAI,EAAE;CAEtD;CAIA,MAAM,OAAO,OAAO,SAAS,MAAM,kBAAkB,SAAS,MAAM,GAAG,IAAI,KAAA;CAC3E,IAAI,MAAM;EACT,OAAO,OAAO,MAAM,QAAQ,IAAI;EAChC;CACD;CACA,MAAM,OAAO;CACb,OAAO,QAAQ;AAChB;;;;;AAMD,MAAa,iBAAiB,YAC7B,WAAW,OAAO,GACf,SAAS,IAAI,EACd,MAAM,YAAY,QAAQ,QAAQ,KAAK;;;;;AAM1C,MAAa,mBAAmB,OAC/B,SACA,OACA,SACmB;CACnB,MAAM,QAAQ,cAAc,OAAO,GAAG,QAAQ;CAC9C,IAAI,CAAC,OACJ,MAAM,IAAI,oBACT,0GACD;CAED,MAAM,MAAM,SAAS,OAAO,IAAI;AACjC"}
@@ -1,4 +1,6 @@
1
+ import { isOneOf } from "../../core/values.js";
1
2
  import "../../goals/constants.js";
3
+ import { HIT_MODES } from "../store/types.js";
2
4
  //#region src/native/ingest/validate.ts
3
5
  const TYPES = new Set([
4
6
  "pageview",
@@ -18,6 +20,7 @@ const rawEventError = (raw, check = {}) => {
18
20
  if (!nonEmptyString(raw.path)) return "path";
19
21
  if (!(check.requireHostname ? nonEmptyString(raw.hostname) : raw.hostname === void 0 || typeof raw.hostname === "string")) return "hostname";
20
22
  if (NAMED.has(raw.type) && !nonEmptyString(raw.name)) return "name";
23
+ if (raw.m !== void 0 && !isOneOf(HIT_MODES, raw.m)) return "m";
21
24
  if (!check.allowRevenue) {
22
25
  if (raw.revenue !== void 0 && raw.revenue !== false) return "revenue";
23
26
  if (typeof raw.value === "number" && raw.value < 0) return "value";
@@ -1 +1 @@
1
- {"version":3,"file":"validate.js","names":[],"sources":["../../../src/native/ingest/validate.ts"],"sourcesContent":["import { MAX_SINCE_MS } from '../../goals/constants'\nimport type { HitType } from '../store/types'\nimport type { RawEventInput } from './normalizeEvent'\n\nconst TYPES: ReadonlySet<string> = new Set<HitType>(['pageview', 'event', 'goal', 'engagement'])\n\n/** The types a `name` means something on; a pageview and an engagement carry none. */\nconst NAMED: ReadonlySet<string> = new Set<HitType>(['event', 'goal'])\n\nconst nonEmptyString = (value: unknown): boolean => typeof value === 'string' && value.length > 0\n\nexport type RawEventField = 'type' | 'path' | 'hostname' | 'name' | 'revenue' | 'value'\n\ninterface RawEventCheck {\n\t/**\n\t * Wire events may omit a hostname (ingest attributes them to the request); server code has no\n\t * request to fall back on, so it requires one.\n\t */\n\trequireHostname?: boolean\n\t/**\n\t * Only `trackServerEvent` sets this. On the wire a `revenue` flag or negative amount is refused,\n\t * not sanitized away, because it is a forgery attempt, not a typo.\n\t */\n\tallowRevenue?: boolean\n}\n\n/**\n * First field an event fails on. Other optional fields are dropped later in `normalizeEvent` when\n * malformed, but server-only revenue is refused here so a forged body is not quietly recorded.\n */\nexport const rawEventError = (\n\traw: RawEventInput | undefined,\n\tcheck: RawEventCheck = {}\n): RawEventField | undefined => {\n\tif (!raw || !TYPES.has(raw.type)) {\n\t\treturn 'type'\n\t}\n\tif (!nonEmptyString(raw.path)) {\n\t\treturn 'path'\n\t}\n\tconst hostname = check.requireHostname\n\t\t? nonEmptyString(raw.hostname)\n\t\t: raw.hostname === undefined || typeof raw.hostname === 'string'\n\tif (!hostname) {\n\t\treturn 'hostname'\n\t}\n\tif (NAMED.has(raw.type) && !nonEmptyString(raw.name)) {\n\t\treturn 'name'\n\t}\n\tif (!check.allowRevenue) {\n\t\tif (raw.revenue !== undefined && raw.revenue !== false) {\n\t\t\treturn 'revenue'\n\t\t}\n\t\tif (typeof raw.value === 'number' && raw.value < 0) {\n\t\t\treturn 'value'\n\t\t}\n\t}\n\treturn undefined\n}\n\n/**\n * An engagement's `sinceMs` as ingest believes it: whole milliseconds from 0 to a day, else\n * undefined, and the engagement is then filed when it arrives. Never a reason to refuse one.\n */\nexport const boundedSinceMs = (value: unknown): number | undefined =>\n\ttypeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= MAX_SINCE_MS\n\t\t? Math.round(value)\n\t\t: undefined\n\n/** Whether a pageview is a single-page app's navigation: `nav: 1`, and nothing else. */\nexport const isNavigation = (value: unknown): boolean => value === 1\n"],"mappings":";;AAIA,MAAM,QAA6B,IAAI,IAAa;CAAC;CAAY;CAAS;CAAQ;AAAY,CAAC;;AAG/F,MAAM,QAA6B,IAAI,IAAa,CAAC,SAAS,MAAM,CAAC;AAErE,MAAM,kBAAkB,UAA4B,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;AAqBhG,MAAa,iBACZ,KACA,QAAuB,CAAC,MACO;CAC/B,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,IAAI,GAC9B,OAAO;CAER,IAAI,CAAC,eAAe,IAAI,IAAI,GAC3B,OAAO;CAKR,IAAI,EAHa,MAAM,kBACpB,eAAe,IAAI,QAAQ,IAC3B,IAAI,aAAa,KAAA,KAAa,OAAO,IAAI,aAAa,WAExD,OAAO;CAER,IAAI,MAAM,IAAI,IAAI,IAAI,KAAK,CAAC,eAAe,IAAI,IAAI,GAClD,OAAO;CAER,IAAI,CAAC,MAAM,cAAc;EACxB,IAAI,IAAI,YAAY,KAAA,KAAa,IAAI,YAAY,OAChD,OAAO;EAER,IAAI,OAAO,IAAI,UAAU,YAAY,IAAI,QAAQ,GAChD,OAAO;CAET;AAED;;;;;AAMA,MAAa,kBAAkB,UAC9B,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS,KAAK,SAAA,QAClE,KAAK,MAAM,KAAK,IAChB,KAAA;;AAGJ,MAAa,gBAAgB,UAA4B,UAAU"}
1
+ {"version":3,"file":"validate.js","names":[],"sources":["../../../src/native/ingest/validate.ts"],"sourcesContent":["import { isOneOf } from '../../core/values'\nimport { MAX_SINCE_MS } from '../../goals/constants'\nimport { HIT_MODES, type HitType } from '../store/types'\nimport type { RawEventInput } from './normalizeEvent'\n\nconst TYPES: ReadonlySet<string> = new Set<HitType>(['pageview', 'event', 'goal', 'engagement'])\n\n/** The types a `name` means something on; a pageview and an engagement carry none. */\nconst NAMED: ReadonlySet<string> = new Set<HitType>(['event', 'goal'])\n\nconst nonEmptyString = (value: unknown): boolean => typeof value === 'string' && value.length > 0\n\nexport type RawEventField = 'type' | 'path' | 'hostname' | 'name' | 'revenue' | 'value' | 'm'\n\ninterface RawEventCheck {\n\t/**\n\t * Wire events may omit a hostname (ingest attributes them to the request); server code has no\n\t * request to fall back on, so it requires one.\n\t */\n\trequireHostname?: boolean\n\t/**\n\t * Only `trackServerEvent` sets this. On the wire a `revenue` flag or negative amount is refused,\n\t * not sanitized away, because it is a forgery attempt, not a typo.\n\t */\n\tallowRevenue?: boolean\n}\n\n/**\n * First field an event fails on. Other optional fields are dropped later in `normalizeEvent` when\n * malformed, but server-only revenue is refused here so a forged body is not quietly recorded.\n */\nexport const rawEventError = (\n\traw: RawEventInput | undefined,\n\tcheck: RawEventCheck = {}\n): RawEventField | undefined => {\n\tif (!raw || !TYPES.has(raw.type)) {\n\t\treturn 'type'\n\t}\n\tif (!nonEmptyString(raw.path)) {\n\t\treturn 'path'\n\t}\n\tconst hostname = check.requireHostname\n\t\t? nonEmptyString(raw.hostname)\n\t\t: raw.hostname === undefined || typeof raw.hostname === 'string'\n\tif (!hostname) {\n\t\treturn 'hostname'\n\t}\n\tif (NAMED.has(raw.type) && !nonEmptyString(raw.name)) {\n\t\treturn 'name'\n\t}\n\t// Refused rather than read as some mode: a mode ingest does not know may allow less than any.\n\tif (raw.m !== undefined && !isOneOf(HIT_MODES, raw.m)) {\n\t\treturn 'm'\n\t}\n\tif (!check.allowRevenue) {\n\t\tif (raw.revenue !== undefined && raw.revenue !== false) {\n\t\t\treturn 'revenue'\n\t\t}\n\t\tif (typeof raw.value === 'number' && raw.value < 0) {\n\t\t\treturn 'value'\n\t\t}\n\t}\n\treturn undefined\n}\n\n/**\n * An engagement's `sinceMs` as ingest believes it: whole milliseconds from 0 to a day, else\n * undefined, and the engagement is then filed when it arrives. Never a reason to refuse one.\n */\nexport const boundedSinceMs = (value: unknown): number | undefined =>\n\ttypeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= MAX_SINCE_MS\n\t\t? Math.round(value)\n\t\t: undefined\n\n/** Whether a pageview is a single-page app's navigation: `nav: 1`, and nothing else. */\nexport const isNavigation = (value: unknown): boolean => value === 1\n"],"mappings":";;;;AAKA,MAAM,QAA6B,IAAI,IAAa;CAAC;CAAY;CAAS;CAAQ;AAAY,CAAC;;AAG/F,MAAM,QAA6B,IAAI,IAAa,CAAC,SAAS,MAAM,CAAC;AAErE,MAAM,kBAAkB,UAA4B,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;AAqBhG,MAAa,iBACZ,KACA,QAAuB,CAAC,MACO;CAC/B,IAAI,CAAC,OAAO,CAAC,MAAM,IAAI,IAAI,IAAI,GAC9B,OAAO;CAER,IAAI,CAAC,eAAe,IAAI,IAAI,GAC3B,OAAO;CAKR,IAAI,EAHa,MAAM,kBACpB,eAAe,IAAI,QAAQ,IAC3B,IAAI,aAAa,KAAA,KAAa,OAAO,IAAI,aAAa,WAExD,OAAO;CAER,IAAI,MAAM,IAAI,IAAI,IAAI,KAAK,CAAC,eAAe,IAAI,IAAI,GAClD,OAAO;CAGR,IAAI,IAAI,MAAM,KAAA,KAAa,CAAC,QAAQ,WAAW,IAAI,CAAC,GACnD,OAAO;CAER,IAAI,CAAC,MAAM,cAAc;EACxB,IAAI,IAAI,YAAY,KAAA,KAAa,IAAI,YAAY,OAChD,OAAO;EAER,IAAI,OAAO,IAAI,UAAU,YAAY,IAAI,QAAQ,GAChD,OAAO;CAET;AAED;;;;;AAMA,MAAa,kBAAkB,UAC9B,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,KAAK,SAAS,KAAK,SAAA,QAClE,KAAK,MAAM,KAAK,IAChB,KAAA;;AAGJ,MAAa,gBAAgB,UAA4B,UAAU"}
@@ -1,3 +1,4 @@
1
+ import { WithoutConsentLevel } from "../tracker/config.js";
1
2
  import { AnalyticsCollectionOptions } from "../core/collectionOption.js";
2
3
  import { GeoResolver } from "./geo/geoResolver.js";
3
4
  import { CapsOption } from "./store/caps.js";
@@ -94,7 +95,15 @@ interface NativeOptions {
94
95
  * change admin settings, access and `dbName`, but no field: the boot checks it.
95
96
  */
96
97
  collections?: NativeCollections;
98
+ /**
99
+ * What this source's held slot does without consent, over `capture.withoutConsent`.
100
+ * `'cookieless'` is native's own capture, which stores nothing on the device; `'anonymous'` also
101
+ * keeps no visitor id, region, city or engagement for those hits; `'off'` sends nothing.
102
+ */
103
+ withoutConsent?: NativeWithoutConsent;
97
104
  }
105
+ /** Native's levels without consent: the vendor ones, plus `anonymous`. */
106
+ type NativeWithoutConsent = WithoutConsentLevel | 'anonymous';
98
107
  /** The engine's collections, by what they hold; each defaults to its `analytics-` slug. */
99
108
  interface NativeCollections {
100
109
  /** `analytics-hits`, one row per hit. */
@@ -128,5 +137,5 @@ interface NativeAdapter extends AnalyticsAdapter {
128
137
  }
129
138
  declare function native(options?: NativeOptions): NativeAdapter;
130
139
  //#endregion
131
- export { NativeAdapter, NativeCollections, NativeOptions, NativeRetention, NativeSqlite, NativeToday, native };
140
+ export { NativeAdapter, NativeCollections, NativeOptions, NativeRetention, NativeSqlite, NativeToday, NativeWithoutConsent, native };
132
141
  //# sourceMappingURL=nativeAdapter.d.ts.map
@@ -5,6 +5,7 @@ import { isDestroyed } from "../plugin/destroy.js";
5
5
  import { routePaths } from "../plugin/routes.js";
6
6
  import { getRuntime } from "../plugin/runtime.js";
7
7
  import { adapterLabel } from "../core/sourceLabel.js";
8
+ import { adapterWithoutConsent, cookielessCapture } from "../capture/withoutConsent.js";
8
9
  import { DEFAULT_STORE_SLUGS } from "./collections/slugs.js";
9
10
  import { resolveCollectionOption } from "../core/collectionOption.js";
10
11
  import { DEFAULT_JOBS } from "../core/jobs.js";
@@ -44,6 +45,11 @@ import { makeIngestHandler } from "./ingest/endpoint.js";
44
45
  import { createEventStore } from "./store/eventStore.js";
45
46
  import { createLocalReq } from "payload";
46
47
  //#region src/native/nativeAdapter.ts
48
+ const NATIVE_WITHOUT_CONSENT = [
49
+ "cookieless",
50
+ "anonymous",
51
+ "off"
52
+ ];
47
53
  /** The config native adapter's id, which a `native` provider document grants to a scope. */
48
54
  const NATIVE_ADAPTER_ID = "native";
49
55
  const D1_REFUSAL = "analytics: native() does not support Cloudflare D1 (@payloadcms/db-d1-sqlite) yet. The vendor adapters (Plausible, Umami, GA4, PostHog) work on D1: drop native() from adapters, or run the app on MongoDB, Postgres or SQLite.";
@@ -140,6 +146,7 @@ function native(options = {}) {
140
146
  const sqliteThread = sqliteThreadOf(options.sqlite);
141
147
  const platformHostnames = hostnameSet(options.platformHostnames, "platformHostnames");
142
148
  const collections = storeCollectionsOf(options.collections);
149
+ const withoutConsent = adapterWithoutConsent(options.withoutConsent, "native({ withoutConsent })", NATIVE_WITHOUT_CONSENT);
143
150
  const slugs = {
144
151
  hits: collections.hits.slug,
145
152
  aggregates: collections.aggregates.slug,
@@ -369,7 +376,10 @@ function native(options = {}) {
369
376
  get capabilities() {
370
377
  return capabilities;
371
378
  },
372
- capture: nativeCapture,
379
+ capture: {
380
+ ...nativeCapture,
381
+ ...cookielessCapture({ kind: "inherent" }, withoutConsent)
382
+ },
373
383
  ingest,
374
384
  isConfigured: () => true,
375
385
  flush: async (payload) => {
@@ -1 +1 @@
1
- {"version":3,"file":"nativeAdapter.js","names":[],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcreateLocalReq,\n\ttype Payload,\n\ttype PayloadHandler,\n\ttype PayloadRequest,\n} from 'payload'\nimport { captureRequest } from '../capture/captureRequest'\nimport type { CaptureSupport } from '../core/capture'\nimport { currentDate } from '../core/clock'\nimport {\n\ttype AnalyticsCollectionOptions,\n\ttype ResolvedCollectionOption,\n\tresolveCollectionOption,\n} from '../core/collectionOption'\nimport type {\n\tAdapterContext,\n\tAdapterRegisterContext,\n\tAdapterSchemaContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n} from '../core/contract'\nimport { type AdapterJobs, DEFAULT_JOBS } from '../core/jobs'\nimport { assertNoLegacyOptions, LEGACY_NATIVE_OPTIONS } from '../core/legacyOptions'\nimport type { MaxmindSdk } from '../core/sdks'\nimport type { IngestHostnameResolver } from '../core/serverEvent'\nimport { type AdapterLabelOption, adapterLabel } from '../core/sourceLabel'\nimport { isRecord, kindOf } from '../core/values'\nimport { dbKind, isD1 } from '../db/kind'\nimport { DEFAULT_ORDER_SIGNATURE } from '../goals/match'\nimport { itemIdTypes } from '../items/collectionIdType'\nimport { shapeCollection } from '../plugin/collectionChecks'\nimport { isDestroyed } from '../plugin/destroy'\nimport { createKeepAlive } from '../plugin/keepAlive'\nimport { isProductionBuild, MAXMIND_SDK_WARNING } from '../plugin/peers'\nimport { DEFAULT_ROUTE_BASE, routePaths } from '../plugin/routes'\nimport { getRuntime } from '../plugin/runtime'\nimport { addTask, schemaOnlyTask } from '../plugin/schemaOnly'\nimport { TASK_SWEEP_BATCHES } from '../surfacing/cacheSweep'\nimport { aggregatesCollection } from './collections/aggregates'\nimport { hitsCollection } from './collections/hits'\nimport { DEFAULT_STORE_SLUGS, type StoreSlugs } from './collections/slugs'\nimport { stateCollection } from './collections/state'\nimport { DEFAULT_RAW_DAYS, nativeCapabilities } from './engine/capabilities'\nimport { createEngine } from './engine/engine'\nimport { closeNativeInstance, type NativeInstance, nativeInstanceFor } from './engine/instance'\nimport type { RebuildDaysInput, RebuildDaysReport } from './engine/rebuild'\nimport { createDailySalts } from './engine/salt'\nimport { createSiteHosts } from './engine/siteHosts'\nimport { createHitWriter, resolveWriteBuffer, type WriteBufferOption } from './engine/writeBuffer'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, needsMaxmindSdk, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { type BotFilter, resolveBotFilter } from './ingest/bots'\nimport { type IngestAttribution, type IngestResolvers, makeIngestHandler } from './ingest/endpoint'\nimport { type ItemSignatureMode, itemRefKey } from './ingest/itemSignature'\nimport type { ItemIngestOptions } from './ingest/normalizeEvent'\nimport { orderRefKey } from './ingest/orderSignature'\nimport {\n\ttype HostnameOption,\n\thostnameSet,\n\tresolveEventHostname,\n\tresolveHostnameOption,\n} from './ingest/resolveHostname'\nimport { makeServerTrack } from './ingest/serverTrack'\nimport { type CapsOption, resolveCaps } from './store/caps'\nimport { createEventStore } from './store/eventStore'\nimport { TWIN_WINDOW_MS } from './store/hits'\nimport { rawFilterMap } from './store/rawRead'\nimport { createSqlExecutor } from './store/sql/executor'\nimport { isSqliteThread, SQLITE_THREADS, type SqliteThread } from './store/sql/sqliteThread'\nimport { createStateStore } from './store/stateStore'\nimport {\n\tMAINTAIN_TASK_BUDGET_MS,\n\tMAINTAIN_TASK_SLUG,\n\ttype MaintainTaskOutput,\n\tmaintainTask,\n} from './tasks/maintainTask'\n\nexport type { EventHostnameResolver, HostnameOption } from './ingest/resolveHostname'\n\n/** How long the native engine keeps what it stores. */\nexport interface NativeRetention {\n\t/**\n\t * Days of raw hits kept, today counted: how far back filtered and hourly reads reach. `null`\n\t * keeps every hit. Default 90.\n\t */\n\trawDays?: number | null\n\t/**\n\t * Days of daily totals kept, today counted; at least `rawDays`, which must then be set too.\n\t * `null` keeps every day's. Default null.\n\t */\n\taggregateDays?: number | null\n}\n\n/** How the native engine reads the day still running. */\nexport interface NativeToday {\n\t/**\n\t * Hits up to which today is read live; above it, from a background snapshot of its totals.\n\t * Default 5,000 on Postgres, 2,000 on SQLite and MongoDB; 0 always reads a snapshot.\n\t */\n\tsnapshotAboveHits?: number\n\t/**\n\t * Ms a snapshot is served before a background refresh. Default grows with the day's hits (one\n\t * minute up to 50,000, five at 500,000) and with its counting cost. At least 1,000.\n\t */\n\tmaxAgeMs?: number\n}\n\nexport interface NativeOptions {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Payload'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/**\n\t * Where each event's country, region and city come from. One that throws costs the event its\n\t * location, never the event, and is logged at most once an hour while it fails.\n\t */\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\t/** Where the beacon endpoint listens, under `routes.api`. Default `<routes.base>/e`. */\n\tingestPath?: string\n\t/**\n\t * `true` batches hits in memory (200 hits or one second, at most 5,000 held); an object sets\n\t * `maxSize`, `maxAgeMs` or `maxPending`. Unset writes each as it arrives. Orders are never held.\n\t */\n\tbuffer?: WriteBufferOption\n\t/**\n\t * `'request'` (default) stores the request's host and ignores the body's claim; a list stores it\n\t * only when listed; a resolver decides per event, and null drops it.\n\t */\n\thostname?: HostnameOption\n\t/**\n\t * Platform domains that ingest under the null scope when the request resolves none. Tenant\n\t * domains need no entry: `scope.resolve` already answers for them.\n\t */\n\tplatformHostnames?: string[]\n\t/**\n\t * Drops crawlers, monitors and headless clients by user agent, on by default. A function receives\n\t * the raw agent; `false` counts every beacon. `trackServerEvent` is never filtered.\n\t */\n\tfilterBots?: boolean | BotFilter\n\t/**\n\t * `signature: 'required'` (default) keeps a page's item only when the server signed its ref\n\t * (`signItemRef`, `itemAttributesFor`); `'optional'` also keeps unsigned refs.\n\t */\n\titems?: { signature?: ItemSignatureMode }\n\t/**\n\t * Values each kind of daily total keeps per scope, day and hostname, the rest folded into one\n\t * `(other)` row; null keeps all. Kinds left out keep the defaults (`DEFAULT_CAPS`).\n\t */\n\tcaps?: CapsOption\n\tretention?: NativeRetention\n\t/** Today: read live while small, else from a snapshot (see `NativeToday`). */\n\ttoday?: NativeToday\n\t/** SQLite on a local file: where the engine's statements run (see `NativeSqlite`). */\n\tsqlite?: NativeSqlite\n\t/**\n\t * The engine's collections, renamed with `slug` and reshaped with `overrides`. An override may\n\t * change admin settings, access and `dbName`, but no field: the boot checks it.\n\t */\n\tcollections?: NativeCollections\n}\n\n/** The engine's collections, by what they hold; each defaults to its `analytics-` slug. */\nexport interface NativeCollections {\n\t/** `analytics-hits`, one row per hit. */\n\thits?: AnalyticsCollectionOptions\n\t/** `analytics-aggregates`, the daily totals. */\n\taggregates?: AnalyticsCollectionOptions\n\t/** `analytics-state`: the daily salts, day markers, leases and heartbeats. */\n\tstate?: AnalyticsCollectionOptions\n}\n\n/** Where the engine runs its statements on a local SQLite file. Remote libsql never blocks. */\nexport interface NativeSqlite {\n\t/**\n\t * `'auto'` (default) uses worker threads in WAL mode with `busyTimeout` >= 5,000 ms, else the main\n\t * thread, warning once. `ANALYTICS_SQLITE_THREAD` sets it where this does not.\n\t */\n\tthread?: SqliteThread\n}\n\n/** The config native adapter's id, which a `native` provider document grants to a scope. */\nexport const NATIVE_ADAPTER_ID = 'native'\n\nconst D1_REFUSAL =\n\t'analytics: native() does not support Cloudflare D1 (@payloadcms/db-d1-sqlite) yet. The vendor adapters (Plausible, Umami, GA4, PostHog) work on D1: drop native() from adapters, or run the app on MongoDB, Postgres or SQLite.'\n\nexport interface NativeAdapter extends AnalyticsAdapter {\n\t/**\n\t * Writes out what one instance holds back: its write buffer, and the server events that waited\n\t * on a transaction which has since ended.\n\t */\n\tflush(payload: Payload): Promise<void>\n\t/**\n\t * Takes one beacon as the ingest endpoint does, for a request built outside Payload's own\n\t * routing: what `ingestRoute` from `@10x-media/analytics/next` calls.\n\t */\n\treceive(req: PayloadRequest): Promise<Response>\n\t/** Counts a stretch of one instance's days again, as `rebuildDays` asks. */\n\trebuild(payload: Payload, input: RebuildDaysInput): Promise<RebuildDaysReport>\n}\n\n/** The native adapter among a runtime's adapters, recognized by its own seam. */\nexport const isNativeAdapter = (adapter: AnalyticsAdapter): adapter is NativeAdapter =>\n\tadapter.id === NATIVE_ADAPTER_ID &&\n\ttypeof Reflect.get(adapter, 'receive') === 'function' &&\n\ttypeof Reflect.get(adapter, 'flush') === 'function' &&\n\ttypeof Reflect.get(adapter, 'rebuild') === 'function'\n\n// The tracker itself is the client (`AnalyticsScripts` boots it), so there is nothing to\n// proxy or inject; the ingest path is carried by the tracker config resolver instead.\nconst nativeCapture: CaptureSupport = {\n\tproxy: { routes: [] },\n\tsnippet: () => ({ scripts: [] }),\n\tclient: { kind: 'native' },\n}\n\n/** What every store filters with, which is what is declared before a store exists. */\nconst ANY_STORE_FILTERS = rawFilterMap(['eq', 'contains'])\n\n/** Config-time check, so a mistyped mode fails the boot rather than every item at ingest. */\nconst itemSignatureMode = (value: unknown): ItemSignatureMode => {\n\tif (value === undefined || value === 'required') {\n\t\treturn 'required'\n\t}\n\tif (value === 'optional') {\n\t\treturn 'optional'\n\t}\n\tthrow new Error(\n\t\t`analytics: native items.signature must be 'required' or 'optional', got ${String(value)}`\n\t)\n}\n\n/** A `retention` option as given, refused unless it is unset, null or a whole number of days. */\nconst retentionDays = (\n\tretention: NativeRetention | undefined,\n\tname: keyof NativeRetention\n): number | null | undefined => {\n\tconst value = retention?.[name]\n\tif (value !== undefined && value !== null && (!Number.isInteger(value) || value < 1)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.${name} must be a whole number of days of at least 1, or null, got ${String(value)}`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `retention.rawDays`, so a window no read can start from fails the boot. */\nconst rawDaysOf = (retention: NativeRetention | undefined): number | null => {\n\tconst value = retentionDays(retention, 'rawDays')\n\treturn value === undefined ? DEFAULT_RAW_DAYS : value\n}\n\n/**\n * Config-time check of `retention.aggregateDays`: daily totals deleted while a day's raw hits are\n * still kept would be counted again on the next read, and deleted again after.\n */\nconst aggregateDaysOf = (\n\tretention: NativeRetention | undefined,\n\trawDays: number | null\n): number | null => {\n\tconst value = retentionDays(retention, 'aggregateDays') ?? null\n\tif (value === null) {\n\t\treturn null\n\t}\n\tif (rawDays === null || value < rawDays) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.aggregateDays (${value}) must be at least retention.rawDays (${rawDays ?? 'null, every hit kept'}): daily totals deleted while their raw hits are kept would be counted again`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `today`, so a value no read could use fails the boot. */\nconst todayOf = (today: NativeToday | undefined): NativeToday => {\n\tconst check = (name: keyof NativeToday, value: number | undefined, min: number): void => {\n\t\tif (value !== undefined && (!Number.isInteger(value) || value < min)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native today.${name} must be a whole number of at least ${min.toLocaleString('en-US')}, got ${String(value)}`\n\t\t\t)\n\t\t}\n\t}\n\tcheck('snapshotAboveHits', today?.snapshotAboveHits, 0)\n\tcheck('maxAgeMs', today?.maxAgeMs, 1_000)\n\treturn {\n\t\t...(today?.snapshotAboveHits === undefined\n\t\t\t? {}\n\t\t\t: { snapshotAboveHits: today.snapshotAboveHits }),\n\t\t...(today?.maxAgeMs === undefined ? {} : { maxAgeMs: today.maxAgeMs }),\n\t}\n}\n\nconst STORE_KEYS = ['hits', 'aggregates', 'state'] as const satisfies ReadonlyArray<\n\tkeyof StoreSlugs\n>\n\ntype StoreCollections = Readonly<Record<keyof StoreSlugs, ResolvedCollectionOption>>\n\n/** Config-time check of `collections`, so an unknown key, a bad slug or two alike fail the boot. */\nconst storeCollectionsOf = (value: unknown): StoreCollections => {\n\tconst given = value ?? {}\n\tif (!isRecord(given) || Array.isArray(given)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections must be an object such as { hits: { slug: 'site-hits' } }, got ${kindOf(value)}`\n\t\t)\n\t}\n\tfor (const key of Object.keys(given)) {\n\t\tif (!STORE_KEYS.some((known) => known === key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native() collections.${key} is not a collection of the engine; it has ${STORE_KEYS.join(', ')}`\n\t\t\t)\n\t\t}\n\t}\n\tconst of = (key: keyof StoreSlugs): ResolvedCollectionOption =>\n\t\tresolveCollectionOption(given[key], {\n\t\t\tpath: `native() collections.${key}`,\n\t\t\tfallback: DEFAULT_STORE_SLUGS[key],\n\t\t})\n\tconst collections = { hits: of('hits'), aggregates: of('aggregates'), state: of('state') }\n\tconst slugs = STORE_KEYS.map((key) => collections[key].slug)\n\tif (new Set(slugs).size !== slugs.length) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections name one slug twice (${slugs.join(', ')}); each of the engine's collections needs its own`\n\t\t)\n\t}\n\treturn collections\n}\n\n/** Config-time check of `sqlite.thread`, so a mistyped mode fails the boot. */\nconst sqliteThreadOf = (sqlite: NativeSqlite | undefined): SqliteThread | undefined => {\n\tconst value = sqlite?.thread\n\tif (value === undefined || isSqliteThread(value)) {\n\t\treturn value\n\t}\n\tthrow new Error(\n\t\t`analytics: native sqlite.thread must be one of ${SQLITE_THREADS.map((each) => `'${each}'`).join(', ')}, got ${kindOf(value)}`\n\t)\n}\n\n/** What one `register()` call handed the adapter, which every instance built after it uses. */\ninterface Registration {\n\tscoped: boolean\n\tmaxmind?: MaxmindSdk\n\tresolvers: IngestResolvers\n\tattribution: IngestAttribution\n\t/** The collections bound as items and whether they are counted per page, when any are bound. */\n\titems?: { collections: ReadonlySet<string>; pages: boolean }\n\trevenue?: AdapterRegisterContext['revenue']\n\t/** The maintenance task's queue and schedule, or false when the install registers none. */\n\tjobs: AdapterJobs\n\t/** Whether the task may carry a concurrency key: the host's `jobs.enableConcurrencyControl`. */\n\tjobsConcurrency: boolean\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tassertNoLegacyOptions(options, { legacy: LEGACY_NATIVE_OPTIONS, owner: 'native() option ' })\n\t// Validated here so a bad value fails the boot rather than the first beacon or read.\n\tconst hostname = resolveHostnameOption(options.hostname)\n\tconst filterBots = resolveBotFilter(options.filterBots)\n\tconst signatureMode = itemSignatureMode(options.items?.signature)\n\tconst caps = resolveCaps(options.caps)\n\tresolveWriteBuffer(options.buffer)\n\tconst rawDays = rawDaysOf(options.retention)\n\tconst aggregateDays = aggregateDaysOf(options.retention, rawDays)\n\tconst today = todayOf(options.today)\n\tconst sqliteThread = sqliteThreadOf(options.sqlite)\n\tconst platformHostnames = hostnameSet(options.platformHostnames, 'platformHostnames')\n\tconst collections = storeCollectionsOf(options.collections)\n\tconst slugs: StoreSlugs = {\n\t\thits: collections.hits.slug,\n\t\taggregates: collections.aggregates.slug,\n\t\tstate: collections.state.slug,\n\t}\n\tconst configuredGeo =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\tlet warnedMaxmind = false\n\tlet mountedIngestPath = routePaths(DEFAULT_ROUTE_BASE).ingest\n\n\tconst registrationOf = (context: AdapterRegisterContext | undefined): Registration => {\n\t\tconst scoped = context?.scoped ?? false\n\t\tconst grantedForScope = context?.adapterGrantedForScope\n\t\treturn {\n\t\t\tscoped,\n\t\t\t...(context?.sdks?.maxmind ? { maxmind: context.sdks.maxmind } : {}),\n\t\t\tresolvers: {\n\t\t\t\t...(scoped && context ? { scope: context.resolveScope } : {}),\n\t\t\t\t...(context ? { timezone: context.resolveTimezoneStrict } : {}),\n\t\t\t\t...(context ? { currency: context.revenue.currency } : {}),\n\t\t\t\t...(context?.revenue.convert ? { convertCurrency: context.revenue.convert } : {}),\n\t\t\t\t...(context ? { goals: context.resolveGoals } : {}),\n\t\t\t\t...(scoped && grantedForScope\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranted: (req: PayloadRequest, scope: string | null) =>\n\t\t\t\t\t\t\t\tgrantedForScope(req, scope, NATIVE_ADAPTER_ID),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tattribution: {\n\t\t\t\ttrustedProxyHops: context?.trustedProxyHops,\n\t\t\t\ttrustedPlatform: context?.trustedPlatform,\n\t\t\t\t...(context?.allowedOrigins ? { allowedOrigins: context.allowedOrigins } : {}),\n\t\t\t\thostname,\n\t\t\t\tplatformHostnames,\n\t\t\t},\n\t\t\t...(context?.items && context.items.collections.size > 0 ? { items: context.items } : {}),\n\t\t\t...(context?.revenue ? { revenue: context.revenue } : {}),\n\t\t\tjobs: context?.jobs ?? DEFAULT_JOBS,\n\t\t\tjobsConcurrency: context?.jobsConcurrency === true,\n\t\t}\n\t}\n\n\t/** What the adapter declares for a registration, with the filters its store applies. */\n\tconst capabilitiesOf = (\n\t\tregistration: Registration,\n\t\tfilters: AnalyticsCapabilities['filters']\n\t): AnalyticsCapabilities =>\n\t\tnativeCapabilities({\n\t\t\tfilters: filters ?? ANY_STORE_FILTERS,\n\t\t\trawDays,\n\t\t\tscoped: registration.scoped,\n\t\t\t...(registration.revenue ? { revenue: registration.revenue } : {}),\n\t\t\titems: registration.items !== undefined,\n\t\t})\n\n\t/** Each collection checked after the host's overrides; boot warnings go to `notice`. */\n\tconst addStoreCollections = (\n\t\tconfig: Config,\n\t\tnotice: ((message: string) => void) | undefined\n\t): void => {\n\t\tconst built = {\n\t\t\thits: hitsCollection(slugs.hits),\n\t\t\taggregates: aggregatesCollection(slugs.aggregates),\n\t\t\tstate: stateCollection(slugs.state),\n\t\t}\n\t\tconst shaped = STORE_KEYS.map((key) => {\n\t\t\tconst { overrides } = collections[key]\n\t\t\treturn shapeCollection(built[key], {\n\t\t\t\trole: key,\n\t\t\t\toption: `native() collections.${key}`,\n\t\t\t\tdb: config.db?.name,\n\t\t\t\t...(overrides ? { overrides } : {}),\n\t\t\t})\n\t\t})\n\t\tfor (const message of shaped.flatMap((each) => each.notices)) {\n\t\t\tnotice?.(message)\n\t\t}\n\t\tconfig.collections = [...(config.collections ?? []), ...shaped.map((each) => each.collection)]\n\t}\n\n\tlet registration = registrationOf(undefined)\n\tlet capabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\n\tconst geoResolver: GeoResolver = (headers, opts) => {\n\t\tconst maxmind = registration.maxmind\n\t\treturn configuredGeo(headers, maxmind ? { ...opts, maxmind } : opts)\n\t}\n\n\tconst build = (payload: Payload, built: Registration): NativeInstance => {\n\t\tif (isD1(payload)) {\n\t\t\tthrow new Error(D1_REFUSAL)\n\t\t}\n\t\tconst executor =\n\t\t\tdbKind(payload) === 'mongo'\n\t\t\t\t? undefined\n\t\t\t\t: createSqlExecutor(payload, sqliteThread === undefined ? {} : { thread: sqliteThread })\n\t\t// Every browser record is the server's own when signatures are required: none is forged, so\n\t\t// the two records of an order are one sale however far apart they lie.\n\t\tconst ordersSigned = built.revenue?.orderSignature === 'required'\n\t\tconst twinWindowMs = ordersSigned ? null : TWIN_WINDOW_MS\n\t\tconst store = createEventStore(payload, {\n\t\t\tslugs,\n\t\t\ttwinWindowMs,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst state = createStateStore(payload, {\n\t\t\tslug: slugs.state,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst declared = capabilitiesOf(built, store.features.filters)\n\t\tcapabilities = declared\n\t\t// A request of its own per call: one kept would hold its dataloader's documents and its\n\t\t// context for the life of the process.\n\t\tconst localRequest = (): Promise<PayloadRequest> => createLocalReq({}, payload)\n\t\tconst zoneOf = built.resolvers.timezone\n\t\tconst currencyOf = built.resolvers.currency\n\t\tconst engine = createEngine({\n\t\t\tpayload,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\toptions: {\n\t\t\t\tscoped: built.scoped,\n\t\t\t\t...(zoneOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttimezone: async (scope: string, req?: PayloadRequest) =>\n\t\t\t\t\t\t\t\tzoneOf(req ?? (await localRequest()), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(currencyOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcurrency: async (scope: string) =>\n\t\t\t\t\t\t\t\tcurrencyOf(await localRequest(), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tdimensions: declared.dimensions,\n\t\t\t\t...(declared.filters ? { filters: declared.filters } : {}),\n\t\t\t\tcaps,\n\t\t\t\titemPages: built.items?.pages ?? true,\n\t\t\t\trawDays,\n\t\t\t\taggregateDays,\n\t\t\t\ttoday,\n\t\t\t\tmaintenance:\n\t\t\t\t\tbuilt.jobs === false\n\t\t\t\t\t\t? { runner: false }\n\t\t\t\t\t\t: { runner: true, intervalMs: built.jobs.maintain.intervalMs },\n\t\t\t\ttwinWindowMs,\n\t\t\t},\n\t\t})\n\t\tconst secret: unknown = payload.secret\n\t\tconst keyed = typeof secret === 'string' && secret !== ''\n\t\tconst items: ItemIngestOptions | undefined = built.items\n\t\t\t? {\n\t\t\t\t\tcollections: built.items.collections,\n\t\t\t\t\tidTypes: itemIdTypes(payload, built.items.collections),\n\t\t\t\t\t// Without a secret no signature a page sends can be checked: only server items are kept.\n\t\t\t\t\t...(keyed ? { signature: { mode: signatureMode, key: itemRefKey(secret) } } : {}),\n\t\t\t\t}\n\t\t\t: undefined\n\t\tconst warn = (message: string) => payload.logger.warn(message)\n\t\tconst keepAlive = createKeepAlive({\n\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next's marker for processes where `after()` works\n\t\t\tenv: process.env,\n\t\t\twarn,\n\t\t})\n\t\treturn {\n\t\t\tregistration: built,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\tengine,\n\t\t\t// Without a secret no order signature can be checked: with signatures required, none passes.\n\t\t\torders: {\n\t\t\t\tmode: built.revenue?.orderSignature ?? DEFAULT_ORDER_SIGNATURE,\n\t\t\t\t...(keyed ? { key: orderRefKey(secret) } : {}),\n\t\t\t},\n\t\t\tkeepAlive: (work: Promise<unknown>) => {\n\t\t\t\tkeepAlive(work).catch(() => undefined)\n\t\t\t},\n\t\t\tsalts: createDailySalts({ state, warn, recorded: (scope) => state.lastZone(scope) }),\n\t\t\twriter: createHitWriter({\n\t\t\t\tstore,\n\t\t\t\t...(options.buffer === undefined ? {} : { buffer: options.buffer }),\n\t\t\t\tlogger: payload.logger,\n\t\t\t}),\n\t\t\titems,\n\t\t\tsqlite: dbKind(payload) === 'sqlite',\n\t\t\tnudge: () => engine.nudge(),\n\t\t\tsiteHosts: createSiteHosts({ store, now: currentDate, warn }),\n\t\t\t...(executor ? { release: () => executor.close() } : {}),\n\t\t}\n\t}\n\n\t/** The instance's engine, built on first use and again after the adapter is registered anew. */\n\tconst instanceOf = (payload: Payload): NativeInstance => {\n\t\tif (isDestroyed(payload)) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: this Payload instance was destroyed, so its native engine is closed'\n\t\t\t)\n\t\t}\n\t\tconst current = registration\n\t\treturn nativeInstanceFor(payload, current, () => build(payload, current))\n\t}\n\n\tconst payloadOf = (ctx: AdapterContext | undefined): Payload => {\n\t\tif (!ctx?.payload) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: the native adapter reads through the Payload instance in its context, and none was given'\n\t\t\t)\n\t\t}\n\t\treturn ctx.payload\n\t}\n\n\tconst beaconHandler = (): PayloadHandler =>\n\t\tmakeIngestHandler({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tresolvers: registration.resolvers,\n\t\t\tattribution: registration.attribution,\n\t\t\tfilterBots,\n\t\t\t...(registration.revenue?.browserAmounts\n\t\t\t\t? { browserAmounts: registration.revenue.browserAmounts }\n\t\t\t\t: {}),\n\t\t})\n\n\t// One handler per registration, so its once-a-process warnings are said once, not per beacon.\n\tlet receiveBeacon = beaconHandler()\n\tconst receive = async (req: PayloadRequest): Promise<Response> => {\n\t\t// A beacon can be the first thing an instance serves (a worker booted without onInit, a\n\t\t// fresh HMR config): the runtime attaches the adapter to it first.\n\t\tgetRuntime(req.payload)\n\t\treturn receiveBeacon(req)\n\t}\n\n\t/**\n\t * One run of `analytics-maintain`, on whichever instance the job runner took it on: the engine's\n\t * upkeep, then the read cache's expired entries, under the sweep's own lease.\n\t */\n\tconst maintainOnTask = async (\n\t\treq: PayloadRequest,\n\t\tinput: { rebuild?: RebuildDaysInput }\n\t): Promise<MaintainTaskOutput> => {\n\t\t// A worker booted without onInit may run the task before anything else built its runtime.\n\t\tconst runtime = getRuntime(req.payload)\n\t\tconst report = await instanceOf(req.payload).engine.maintain({\n\t\t\tbudgetMs: MAINTAIN_TASK_BUDGET_MS,\n\t\t\treq,\n\t\t\theartbeat: true,\n\t\t\t...(input.rebuild ? { rebuild: input.rebuild } : {}),\n\t\t})\n\t\tlet sweptCache = 0\n\t\ttry {\n\t\t\tsweptCache = (await runtime?.cache?.sweeper.sweep(TASK_SWEEP_BATCHES))?.swept ?? 0\n\t\t} catch (err) {\n\t\t\treq.payload.logger.warn(`analytics: sweeping expired cache entries failed: ${String(err)}`)\n\t\t}\n\t\treturn { ...report, sweptCache }\n\t}\n\n\tconst ingest = {\n\t\t// Read late: the plugin's base arrives with the register context.\n\t\tget path() {\n\t\t\treturn options.ingestPath ?? mountedIngestPath\n\t\t},\n\t\ttrack: makeServerTrack({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tgetResolvers: () => registration.resolvers,\n\t\t\tgetAttribution: () => registration.attribution,\n\t\t}),\n\t\t// The endpoint's hostname policy without the scoped drop rule (this caller knows its\n\t\t// boundary); a capture call site, so the host's resolver sees the visit, not the user.\n\t\thostname: (args: Parameters<IngestHostnameResolver>[0]) =>\n\t\t\tresolveEventHostname({\n\t\t\t\toption: hostname,\n\t\t\t\tclaimed: args.claimed,\n\t\t\t\treq: captureRequest(args.req),\n\t\t\t\tscope: args.scope ?? null,\n\t\t\t\ttrustedProxyHops: registration.attribution.trustedProxyHops,\n\t\t\t}),\n\t}\n\n\treturn {\n\t\tid: NATIVE_ADAPTER_ID,\n\t\t...adapterLabel(options.label, 'Payload', 'native({ label })'),\n\t\tget capabilities() {\n\t\t\treturn capabilities\n\t\t},\n\t\tcapture: nativeCapture,\n\t\tingest,\n\t\tisConfigured: () => true,\n\t\tflush: async (payload) => {\n\t\t\tawait instanceOf(payload).writer.flush()\n\t\t},\n\t\trebuild: (payload, input) => {\n\t\t\tgetRuntime(payload)\n\t\t\treturn instanceOf(payload).engine.rebuild(input)\n\t\t},\n\t\treceive,\n\t\tregister(config: Config, context) {\n\t\t\tif (isD1({ db: { name: config.db?.name ?? '' } })) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tregistration = registrationOf(context)\n\t\t\tcapabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\t\t\tif (context?.routes) {\n\t\t\t\tmountedIngestPath = context.routes.ingest\n\t\t\t}\n\t\t\treceiveBeacon = beaconHandler()\n\t\t\taddStoreCollections(config, context?.notice)\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'post', path: ingest.path, handler: receive },\n\t\t\t]\n\t\t\tconst { jobs } = registration\n\t\t\tif (jobs !== false) {\n\t\t\t\taddTask(\n\t\t\t\t\tconfig,\n\t\t\t\t\tmaintainTask({\n\t\t\t\t\t\tschedule: jobs.maintain,\n\t\t\t\t\t\trun: maintainOnTask,\n\t\t\t\t\t\tconcurrency: registration.jobsConcurrency,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t\tregisterSchema(config: Config, context: AdapterSchemaContext) {\n\t\t\taddStoreCollections(config, context.notice)\n\t\t\tif (context.jobs !== false) {\n\t\t\t\taddTask(config, schemaOnlyTask(MAINTAIN_TASK_SLUG, context.jobs.maintain))\n\t\t\t}\n\t\t},\n\t\tattach(payload: Payload) {\n\t\t\tif (isD1(payload)) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tif (\n\t\t\t\t!warnedMaxmind &&\n\t\t\t\tregistration.maxmind === undefined &&\n\t\t\t\tneedsMaxmindSdk(configuredGeo) &&\n\t\t\t\tisProductionBuild()\n\t\t\t) {\n\t\t\t\twarnedMaxmind = true\n\t\t\t\tpayload.logger?.warn(MAXMIND_SDK_WARNING)\n\t\t\t}\n\t\t\tinstanceOf(payload)\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tawait closeNativeInstance(payload, registration)\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.read(q, ctx)\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.realtime(q, ctx)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2LA,MAAa,oBAAoB;AAEjC,MAAM,aACL;;AAkBD,MAAa,mBAAmB,YAC/B,QAAQ,OAAA,YACR,OAAO,QAAQ,IAAI,SAAS,SAAS,MAAM,cAC3C,OAAO,QAAQ,IAAI,SAAS,OAAO,MAAM,cACzC,OAAO,QAAQ,IAAI,SAAS,SAAS,MAAM;AAI5C,MAAM,gBAAgC;CACrC,OAAO,EAAE,QAAQ,CAAC,EAAE;CACpB,gBAAgB,EAAE,SAAS,CAAC,EAAE;CAC9B,QAAQ,EAAE,MAAM,SAAS;AAC1B;;AAGA,MAAM,oBAAoB,aAAa,CA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D;GACjF,OAAO,WAAW,UAAU,GAAG,CAAC,EAAE,OAAO,SAAS,GAAG,GAAG;EACzD;CACD;AACD"}
1
+ {"version":3,"file":"nativeAdapter.js","names":[],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcreateLocalReq,\n\ttype Payload,\n\ttype PayloadHandler,\n\ttype PayloadRequest,\n} from 'payload'\nimport { captureRequest } from '../capture/captureRequest'\nimport { adapterWithoutConsent, cookielessCapture } from '../capture/withoutConsent'\nimport type { CaptureSupport } from '../core/capture'\nimport { currentDate } from '../core/clock'\nimport {\n\ttype AnalyticsCollectionOptions,\n\ttype ResolvedCollectionOption,\n\tresolveCollectionOption,\n} from '../core/collectionOption'\nimport type {\n\tAdapterContext,\n\tAdapterRegisterContext,\n\tAdapterSchemaContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n} from '../core/contract'\nimport { type AdapterJobs, DEFAULT_JOBS } from '../core/jobs'\nimport { assertNoLegacyOptions, LEGACY_NATIVE_OPTIONS } from '../core/legacyOptions'\nimport type { MaxmindSdk } from '../core/sdks'\nimport type { IngestHostnameResolver } from '../core/serverEvent'\nimport { type AdapterLabelOption, adapterLabel } from '../core/sourceLabel'\nimport { isRecord, kindOf } from '../core/values'\nimport { dbKind, isD1 } from '../db/kind'\nimport { DEFAULT_ORDER_SIGNATURE } from '../goals/match'\nimport { itemIdTypes } from '../items/collectionIdType'\nimport { shapeCollection } from '../plugin/collectionChecks'\nimport { isDestroyed } from '../plugin/destroy'\nimport { createKeepAlive } from '../plugin/keepAlive'\nimport { isProductionBuild, MAXMIND_SDK_WARNING } from '../plugin/peers'\nimport { DEFAULT_ROUTE_BASE, routePaths } from '../plugin/routes'\nimport { getRuntime } from '../plugin/runtime'\nimport { addTask, schemaOnlyTask } from '../plugin/schemaOnly'\nimport { TASK_SWEEP_BATCHES } from '../surfacing/cacheSweep'\nimport type { WithoutConsentLevel } from '../tracker/config'\nimport { aggregatesCollection } from './collections/aggregates'\nimport { hitsCollection } from './collections/hits'\nimport { DEFAULT_STORE_SLUGS, type StoreSlugs } from './collections/slugs'\nimport { stateCollection } from './collections/state'\nimport { DEFAULT_RAW_DAYS, nativeCapabilities } from './engine/capabilities'\nimport { createEngine } from './engine/engine'\nimport { closeNativeInstance, type NativeInstance, nativeInstanceFor } from './engine/instance'\nimport type { RebuildDaysInput, RebuildDaysReport } from './engine/rebuild'\nimport { createDailySalts } from './engine/salt'\nimport { createSiteHosts } from './engine/siteHosts'\nimport { createHitWriter, resolveWriteBuffer, type WriteBufferOption } from './engine/writeBuffer'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, needsMaxmindSdk, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { type BotFilter, resolveBotFilter } from './ingest/bots'\nimport { type IngestAttribution, type IngestResolvers, makeIngestHandler } from './ingest/endpoint'\nimport { type ItemSignatureMode, itemRefKey } from './ingest/itemSignature'\nimport type { ItemIngestOptions } from './ingest/normalizeEvent'\nimport { orderRefKey } from './ingest/orderSignature'\nimport {\n\ttype HostnameOption,\n\thostnameSet,\n\tresolveEventHostname,\n\tresolveHostnameOption,\n} from './ingest/resolveHostname'\nimport { makeServerTrack } from './ingest/serverTrack'\nimport { type CapsOption, resolveCaps } from './store/caps'\nimport { createEventStore } from './store/eventStore'\nimport { TWIN_WINDOW_MS } from './store/hits'\nimport { rawFilterMap } from './store/rawRead'\nimport { createSqlExecutor } from './store/sql/executor'\nimport { isSqliteThread, SQLITE_THREADS, type SqliteThread } from './store/sql/sqliteThread'\nimport { createStateStore } from './store/stateStore'\nimport {\n\tMAINTAIN_TASK_BUDGET_MS,\n\tMAINTAIN_TASK_SLUG,\n\ttype MaintainTaskOutput,\n\tmaintainTask,\n} from './tasks/maintainTask'\n\nexport type { EventHostnameResolver, HostnameOption } from './ingest/resolveHostname'\n\n/** How long the native engine keeps what it stores. */\nexport interface NativeRetention {\n\t/**\n\t * Days of raw hits kept, today counted: how far back filtered and hourly reads reach. `null`\n\t * keeps every hit. Default 90.\n\t */\n\trawDays?: number | null\n\t/**\n\t * Days of daily totals kept, today counted; at least `rawDays`, which must then be set too.\n\t * `null` keeps every day's. Default null.\n\t */\n\taggregateDays?: number | null\n}\n\n/** How the native engine reads the day still running. */\nexport interface NativeToday {\n\t/**\n\t * Hits up to which today is read live; above it, from a background snapshot of its totals.\n\t * Default 5,000 on Postgres, 2,000 on SQLite and MongoDB; 0 always reads a snapshot.\n\t */\n\tsnapshotAboveHits?: number\n\t/**\n\t * Ms a snapshot is served before a background refresh. Default grows with the day's hits (one\n\t * minute up to 50,000, five at 500,000) and with its counting cost. At least 1,000.\n\t */\n\tmaxAgeMs?: number\n}\n\nexport interface NativeOptions {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Payload'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/**\n\t * Where each event's country, region and city come from. One that throws costs the event its\n\t * location, never the event, and is logged at most once an hour while it fails.\n\t */\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\t/** Where the beacon endpoint listens, under `routes.api`. Default `<routes.base>/e`. */\n\tingestPath?: string\n\t/**\n\t * `true` batches hits in memory (200 hits or one second, at most 5,000 held); an object sets\n\t * `maxSize`, `maxAgeMs` or `maxPending`. Unset writes each as it arrives. Orders are never held.\n\t */\n\tbuffer?: WriteBufferOption\n\t/**\n\t * `'request'` (default) stores the request's host and ignores the body's claim; a list stores it\n\t * only when listed; a resolver decides per event, and null drops it.\n\t */\n\thostname?: HostnameOption\n\t/**\n\t * Platform domains that ingest under the null scope when the request resolves none. Tenant\n\t * domains need no entry: `scope.resolve` already answers for them.\n\t */\n\tplatformHostnames?: string[]\n\t/**\n\t * Drops crawlers, monitors and headless clients by user agent, on by default. A function receives\n\t * the raw agent; `false` counts every beacon. `trackServerEvent` is never filtered.\n\t */\n\tfilterBots?: boolean | BotFilter\n\t/**\n\t * `signature: 'required'` (default) keeps a page's item only when the server signed its ref\n\t * (`signItemRef`, `itemAttributesFor`); `'optional'` also keeps unsigned refs.\n\t */\n\titems?: { signature?: ItemSignatureMode }\n\t/**\n\t * Values each kind of daily total keeps per scope, day and hostname, the rest folded into one\n\t * `(other)` row; null keeps all. Kinds left out keep the defaults (`DEFAULT_CAPS`).\n\t */\n\tcaps?: CapsOption\n\tretention?: NativeRetention\n\t/** Today: read live while small, else from a snapshot (see `NativeToday`). */\n\ttoday?: NativeToday\n\t/** SQLite on a local file: where the engine's statements run (see `NativeSqlite`). */\n\tsqlite?: NativeSqlite\n\t/**\n\t * The engine's collections, renamed with `slug` and reshaped with `overrides`. An override may\n\t * change admin settings, access and `dbName`, but no field: the boot checks it.\n\t */\n\tcollections?: NativeCollections\n\t/**\n\t * What this source's held slot does without consent, over `capture.withoutConsent`.\n\t * `'cookieless'` is native's own capture, which stores nothing on the device; `'anonymous'` also\n\t * keeps no visitor id, region, city or engagement for those hits; `'off'` sends nothing.\n\t */\n\twithoutConsent?: NativeWithoutConsent\n}\n\n/** Native's levels without consent: the vendor ones, plus `anonymous`. */\nexport type NativeWithoutConsent = WithoutConsentLevel | 'anonymous'\n\nconst NATIVE_WITHOUT_CONSENT: readonly NativeWithoutConsent[] = ['cookieless', 'anonymous', 'off']\n\n/** The engine's collections, by what they hold; each defaults to its `analytics-` slug. */\nexport interface NativeCollections {\n\t/** `analytics-hits`, one row per hit. */\n\thits?: AnalyticsCollectionOptions\n\t/** `analytics-aggregates`, the daily totals. */\n\taggregates?: AnalyticsCollectionOptions\n\t/** `analytics-state`: the daily salts, day markers, leases and heartbeats. */\n\tstate?: AnalyticsCollectionOptions\n}\n\n/** Where the engine runs its statements on a local SQLite file. Remote libsql never blocks. */\nexport interface NativeSqlite {\n\t/**\n\t * `'auto'` (default) uses worker threads in WAL mode with `busyTimeout` >= 5,000 ms, else the main\n\t * thread, warning once. `ANALYTICS_SQLITE_THREAD` sets it where this does not.\n\t */\n\tthread?: SqliteThread\n}\n\n/** The config native adapter's id, which a `native` provider document grants to a scope. */\nexport const NATIVE_ADAPTER_ID = 'native'\n\nconst D1_REFUSAL =\n\t'analytics: native() does not support Cloudflare D1 (@payloadcms/db-d1-sqlite) yet. The vendor adapters (Plausible, Umami, GA4, PostHog) work on D1: drop native() from adapters, or run the app on MongoDB, Postgres or SQLite.'\n\nexport interface NativeAdapter extends AnalyticsAdapter {\n\t/**\n\t * Writes out what one instance holds back: its write buffer, and the server events that waited\n\t * on a transaction which has since ended.\n\t */\n\tflush(payload: Payload): Promise<void>\n\t/**\n\t * Takes one beacon as the ingest endpoint does, for a request built outside Payload's own\n\t * routing: what `ingestRoute` from `@10x-media/analytics/next` calls.\n\t */\n\treceive(req: PayloadRequest): Promise<Response>\n\t/** Counts a stretch of one instance's days again, as `rebuildDays` asks. */\n\trebuild(payload: Payload, input: RebuildDaysInput): Promise<RebuildDaysReport>\n}\n\n/** The native adapter among a runtime's adapters, recognized by its own seam. */\nexport const isNativeAdapter = (adapter: AnalyticsAdapter): adapter is NativeAdapter =>\n\tadapter.id === NATIVE_ADAPTER_ID &&\n\ttypeof Reflect.get(adapter, 'receive') === 'function' &&\n\ttypeof Reflect.get(adapter, 'flush') === 'function' &&\n\ttypeof Reflect.get(adapter, 'rebuild') === 'function'\n\n// The tracker itself is the client (`AnalyticsScripts` boots it), so there is nothing to\n// proxy or inject; the ingest path is carried by the tracker config resolver instead.\nconst nativeCapture: CaptureSupport = {\n\tproxy: { routes: [] },\n\tsnippet: () => ({ scripts: [] }),\n\tclient: { kind: 'native' },\n}\n\n/** What every store filters with, which is what is declared before a store exists. */\nconst ANY_STORE_FILTERS = rawFilterMap(['eq', 'contains'])\n\n/** Config-time check, so a mistyped mode fails the boot rather than every item at ingest. */\nconst itemSignatureMode = (value: unknown): ItemSignatureMode => {\n\tif (value === undefined || value === 'required') {\n\t\treturn 'required'\n\t}\n\tif (value === 'optional') {\n\t\treturn 'optional'\n\t}\n\tthrow new Error(\n\t\t`analytics: native items.signature must be 'required' or 'optional', got ${String(value)}`\n\t)\n}\n\n/** A `retention` option as given, refused unless it is unset, null or a whole number of days. */\nconst retentionDays = (\n\tretention: NativeRetention | undefined,\n\tname: keyof NativeRetention\n): number | null | undefined => {\n\tconst value = retention?.[name]\n\tif (value !== undefined && value !== null && (!Number.isInteger(value) || value < 1)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.${name} must be a whole number of days of at least 1, or null, got ${String(value)}`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `retention.rawDays`, so a window no read can start from fails the boot. */\nconst rawDaysOf = (retention: NativeRetention | undefined): number | null => {\n\tconst value = retentionDays(retention, 'rawDays')\n\treturn value === undefined ? DEFAULT_RAW_DAYS : value\n}\n\n/**\n * Config-time check of `retention.aggregateDays`: daily totals deleted while a day's raw hits are\n * still kept would be counted again on the next read, and deleted again after.\n */\nconst aggregateDaysOf = (\n\tretention: NativeRetention | undefined,\n\trawDays: number | null\n): number | null => {\n\tconst value = retentionDays(retention, 'aggregateDays') ?? null\n\tif (value === null) {\n\t\treturn null\n\t}\n\tif (rawDays === null || value < rawDays) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.aggregateDays (${value}) must be at least retention.rawDays (${rawDays ?? 'null, every hit kept'}): daily totals deleted while their raw hits are kept would be counted again`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `today`, so a value no read could use fails the boot. */\nconst todayOf = (today: NativeToday | undefined): NativeToday => {\n\tconst check = (name: keyof NativeToday, value: number | undefined, min: number): void => {\n\t\tif (value !== undefined && (!Number.isInteger(value) || value < min)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native today.${name} must be a whole number of at least ${min.toLocaleString('en-US')}, got ${String(value)}`\n\t\t\t)\n\t\t}\n\t}\n\tcheck('snapshotAboveHits', today?.snapshotAboveHits, 0)\n\tcheck('maxAgeMs', today?.maxAgeMs, 1_000)\n\treturn {\n\t\t...(today?.snapshotAboveHits === undefined\n\t\t\t? {}\n\t\t\t: { snapshotAboveHits: today.snapshotAboveHits }),\n\t\t...(today?.maxAgeMs === undefined ? {} : { maxAgeMs: today.maxAgeMs }),\n\t}\n}\n\nconst STORE_KEYS = ['hits', 'aggregates', 'state'] as const satisfies ReadonlyArray<\n\tkeyof StoreSlugs\n>\n\ntype StoreCollections = Readonly<Record<keyof StoreSlugs, ResolvedCollectionOption>>\n\n/** Config-time check of `collections`, so an unknown key, a bad slug or two alike fail the boot. */\nconst storeCollectionsOf = (value: unknown): StoreCollections => {\n\tconst given = value ?? {}\n\tif (!isRecord(given) || Array.isArray(given)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections must be an object such as { hits: { slug: 'site-hits' } }, got ${kindOf(value)}`\n\t\t)\n\t}\n\tfor (const key of Object.keys(given)) {\n\t\tif (!STORE_KEYS.some((known) => known === key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native() collections.${key} is not a collection of the engine; it has ${STORE_KEYS.join(', ')}`\n\t\t\t)\n\t\t}\n\t}\n\tconst of = (key: keyof StoreSlugs): ResolvedCollectionOption =>\n\t\tresolveCollectionOption(given[key], {\n\t\t\tpath: `native() collections.${key}`,\n\t\t\tfallback: DEFAULT_STORE_SLUGS[key],\n\t\t})\n\tconst collections = { hits: of('hits'), aggregates: of('aggregates'), state: of('state') }\n\tconst slugs = STORE_KEYS.map((key) => collections[key].slug)\n\tif (new Set(slugs).size !== slugs.length) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections name one slug twice (${slugs.join(', ')}); each of the engine's collections needs its own`\n\t\t)\n\t}\n\treturn collections\n}\n\n/** Config-time check of `sqlite.thread`, so a mistyped mode fails the boot. */\nconst sqliteThreadOf = (sqlite: NativeSqlite | undefined): SqliteThread | undefined => {\n\tconst value = sqlite?.thread\n\tif (value === undefined || isSqliteThread(value)) {\n\t\treturn value\n\t}\n\tthrow new Error(\n\t\t`analytics: native sqlite.thread must be one of ${SQLITE_THREADS.map((each) => `'${each}'`).join(', ')}, got ${kindOf(value)}`\n\t)\n}\n\n/** What one `register()` call handed the adapter, which every instance built after it uses. */\ninterface Registration {\n\tscoped: boolean\n\tmaxmind?: MaxmindSdk\n\tresolvers: IngestResolvers\n\tattribution: IngestAttribution\n\t/** The collections bound as items and whether they are counted per page, when any are bound. */\n\titems?: { collections: ReadonlySet<string>; pages: boolean }\n\trevenue?: AdapterRegisterContext['revenue']\n\t/** The maintenance task's queue and schedule, or false when the install registers none. */\n\tjobs: AdapterJobs\n\t/** Whether the task may carry a concurrency key: the host's `jobs.enableConcurrencyControl`. */\n\tjobsConcurrency: boolean\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tassertNoLegacyOptions(options, { legacy: LEGACY_NATIVE_OPTIONS, owner: 'native() option ' })\n\t// Validated here so a bad value fails the boot rather than the first beacon or read.\n\tconst hostname = resolveHostnameOption(options.hostname)\n\tconst filterBots = resolveBotFilter(options.filterBots)\n\tconst signatureMode = itemSignatureMode(options.items?.signature)\n\tconst caps = resolveCaps(options.caps)\n\tresolveWriteBuffer(options.buffer)\n\tconst rawDays = rawDaysOf(options.retention)\n\tconst aggregateDays = aggregateDaysOf(options.retention, rawDays)\n\tconst today = todayOf(options.today)\n\tconst sqliteThread = sqliteThreadOf(options.sqlite)\n\tconst platformHostnames = hostnameSet(options.platformHostnames, 'platformHostnames')\n\tconst collections = storeCollectionsOf(options.collections)\n\tconst withoutConsent = adapterWithoutConsent(\n\t\toptions.withoutConsent,\n\t\t'native({ withoutConsent })',\n\t\tNATIVE_WITHOUT_CONSENT\n\t)\n\tconst slugs: StoreSlugs = {\n\t\thits: collections.hits.slug,\n\t\taggregates: collections.aggregates.slug,\n\t\tstate: collections.state.slug,\n\t}\n\tconst configuredGeo =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\tlet warnedMaxmind = false\n\tlet mountedIngestPath = routePaths(DEFAULT_ROUTE_BASE).ingest\n\n\tconst registrationOf = (context: AdapterRegisterContext | undefined): Registration => {\n\t\tconst scoped = context?.scoped ?? false\n\t\tconst grantedForScope = context?.adapterGrantedForScope\n\t\treturn {\n\t\t\tscoped,\n\t\t\t...(context?.sdks?.maxmind ? { maxmind: context.sdks.maxmind } : {}),\n\t\t\tresolvers: {\n\t\t\t\t...(scoped && context ? { scope: context.resolveScope } : {}),\n\t\t\t\t...(context ? { timezone: context.resolveTimezoneStrict } : {}),\n\t\t\t\t...(context ? { currency: context.revenue.currency } : {}),\n\t\t\t\t...(context?.revenue.convert ? { convertCurrency: context.revenue.convert } : {}),\n\t\t\t\t...(context ? { goals: context.resolveGoals } : {}),\n\t\t\t\t...(scoped && grantedForScope\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranted: (req: PayloadRequest, scope: string | null) =>\n\t\t\t\t\t\t\t\tgrantedForScope(req, scope, NATIVE_ADAPTER_ID),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tattribution: {\n\t\t\t\ttrustedProxyHops: context?.trustedProxyHops,\n\t\t\t\ttrustedPlatform: context?.trustedPlatform,\n\t\t\t\t...(context?.allowedOrigins ? { allowedOrigins: context.allowedOrigins } : {}),\n\t\t\t\thostname,\n\t\t\t\tplatformHostnames,\n\t\t\t},\n\t\t\t...(context?.items && context.items.collections.size > 0 ? { items: context.items } : {}),\n\t\t\t...(context?.revenue ? { revenue: context.revenue } : {}),\n\t\t\tjobs: context?.jobs ?? DEFAULT_JOBS,\n\t\t\tjobsConcurrency: context?.jobsConcurrency === true,\n\t\t}\n\t}\n\n\t/** What the adapter declares for a registration, with the filters its store applies. */\n\tconst capabilitiesOf = (\n\t\tregistration: Registration,\n\t\tfilters: AnalyticsCapabilities['filters']\n\t): AnalyticsCapabilities =>\n\t\tnativeCapabilities({\n\t\t\tfilters: filters ?? ANY_STORE_FILTERS,\n\t\t\trawDays,\n\t\t\tscoped: registration.scoped,\n\t\t\t...(registration.revenue ? { revenue: registration.revenue } : {}),\n\t\t\titems: registration.items !== undefined,\n\t\t})\n\n\t/** Each collection checked after the host's overrides; boot warnings go to `notice`. */\n\tconst addStoreCollections = (\n\t\tconfig: Config,\n\t\tnotice: ((message: string) => void) | undefined\n\t): void => {\n\t\tconst built = {\n\t\t\thits: hitsCollection(slugs.hits),\n\t\t\taggregates: aggregatesCollection(slugs.aggregates),\n\t\t\tstate: stateCollection(slugs.state),\n\t\t}\n\t\tconst shaped = STORE_KEYS.map((key) => {\n\t\t\tconst { overrides } = collections[key]\n\t\t\treturn shapeCollection(built[key], {\n\t\t\t\trole: key,\n\t\t\t\toption: `native() collections.${key}`,\n\t\t\t\tdb: config.db?.name,\n\t\t\t\t...(overrides ? { overrides } : {}),\n\t\t\t})\n\t\t})\n\t\tfor (const message of shaped.flatMap((each) => each.notices)) {\n\t\t\tnotice?.(message)\n\t\t}\n\t\tconfig.collections = [...(config.collections ?? []), ...shaped.map((each) => each.collection)]\n\t}\n\n\tlet registration = registrationOf(undefined)\n\tlet capabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\n\tconst geoResolver: GeoResolver = (headers, opts) => {\n\t\tconst maxmind = registration.maxmind\n\t\treturn configuredGeo(headers, maxmind ? { ...opts, maxmind } : opts)\n\t}\n\n\tconst build = (payload: Payload, built: Registration): NativeInstance => {\n\t\tif (isD1(payload)) {\n\t\t\tthrow new Error(D1_REFUSAL)\n\t\t}\n\t\tconst executor =\n\t\t\tdbKind(payload) === 'mongo'\n\t\t\t\t? undefined\n\t\t\t\t: createSqlExecutor(payload, sqliteThread === undefined ? {} : { thread: sqliteThread })\n\t\t// Every browser record is the server's own when signatures are required: none is forged, so\n\t\t// the two records of an order are one sale however far apart they lie.\n\t\tconst ordersSigned = built.revenue?.orderSignature === 'required'\n\t\tconst twinWindowMs = ordersSigned ? null : TWIN_WINDOW_MS\n\t\tconst store = createEventStore(payload, {\n\t\t\tslugs,\n\t\t\ttwinWindowMs,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst state = createStateStore(payload, {\n\t\t\tslug: slugs.state,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst declared = capabilitiesOf(built, store.features.filters)\n\t\tcapabilities = declared\n\t\t// A request of its own per call: one kept would hold its dataloader's documents and its\n\t\t// context for the life of the process.\n\t\tconst localRequest = (): Promise<PayloadRequest> => createLocalReq({}, payload)\n\t\tconst zoneOf = built.resolvers.timezone\n\t\tconst currencyOf = built.resolvers.currency\n\t\tconst engine = createEngine({\n\t\t\tpayload,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\toptions: {\n\t\t\t\tscoped: built.scoped,\n\t\t\t\t...(zoneOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttimezone: async (scope: string, req?: PayloadRequest) =>\n\t\t\t\t\t\t\t\tzoneOf(req ?? (await localRequest()), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(currencyOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcurrency: async (scope: string) =>\n\t\t\t\t\t\t\t\tcurrencyOf(await localRequest(), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tdimensions: declared.dimensions,\n\t\t\t\t...(declared.filters ? { filters: declared.filters } : {}),\n\t\t\t\tcaps,\n\t\t\t\titemPages: built.items?.pages ?? true,\n\t\t\t\trawDays,\n\t\t\t\taggregateDays,\n\t\t\t\ttoday,\n\t\t\t\tmaintenance:\n\t\t\t\t\tbuilt.jobs === false\n\t\t\t\t\t\t? { runner: false }\n\t\t\t\t\t\t: { runner: true, intervalMs: built.jobs.maintain.intervalMs },\n\t\t\t\ttwinWindowMs,\n\t\t\t},\n\t\t})\n\t\tconst secret: unknown = payload.secret\n\t\tconst keyed = typeof secret === 'string' && secret !== ''\n\t\tconst items: ItemIngestOptions | undefined = built.items\n\t\t\t? {\n\t\t\t\t\tcollections: built.items.collections,\n\t\t\t\t\tidTypes: itemIdTypes(payload, built.items.collections),\n\t\t\t\t\t// Without a secret no signature a page sends can be checked: only server items are kept.\n\t\t\t\t\t...(keyed ? { signature: { mode: signatureMode, key: itemRefKey(secret) } } : {}),\n\t\t\t\t}\n\t\t\t: undefined\n\t\tconst warn = (message: string) => payload.logger.warn(message)\n\t\tconst keepAlive = createKeepAlive({\n\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next's marker for processes where `after()` works\n\t\t\tenv: process.env,\n\t\t\twarn,\n\t\t})\n\t\treturn {\n\t\t\tregistration: built,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\tengine,\n\t\t\t// Without a secret no order signature can be checked: with signatures required, none passes.\n\t\t\torders: {\n\t\t\t\tmode: built.revenue?.orderSignature ?? DEFAULT_ORDER_SIGNATURE,\n\t\t\t\t...(keyed ? { key: orderRefKey(secret) } : {}),\n\t\t\t},\n\t\t\tkeepAlive: (work: Promise<unknown>) => {\n\t\t\t\tkeepAlive(work).catch(() => undefined)\n\t\t\t},\n\t\t\tsalts: createDailySalts({ state, warn, recorded: (scope) => state.lastZone(scope) }),\n\t\t\twriter: createHitWriter({\n\t\t\t\tstore,\n\t\t\t\t...(options.buffer === undefined ? {} : { buffer: options.buffer }),\n\t\t\t\tlogger: payload.logger,\n\t\t\t}),\n\t\t\titems,\n\t\t\tsqlite: dbKind(payload) === 'sqlite',\n\t\t\tnudge: () => engine.nudge(),\n\t\t\tsiteHosts: createSiteHosts({ store, now: currentDate, warn }),\n\t\t\t...(executor ? { release: () => executor.close() } : {}),\n\t\t}\n\t}\n\n\t/** The instance's engine, built on first use and again after the adapter is registered anew. */\n\tconst instanceOf = (payload: Payload): NativeInstance => {\n\t\tif (isDestroyed(payload)) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: this Payload instance was destroyed, so its native engine is closed'\n\t\t\t)\n\t\t}\n\t\tconst current = registration\n\t\treturn nativeInstanceFor(payload, current, () => build(payload, current))\n\t}\n\n\tconst payloadOf = (ctx: AdapterContext | undefined): Payload => {\n\t\tif (!ctx?.payload) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: the native adapter reads through the Payload instance in its context, and none was given'\n\t\t\t)\n\t\t}\n\t\treturn ctx.payload\n\t}\n\n\tconst beaconHandler = (): PayloadHandler =>\n\t\tmakeIngestHandler({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tresolvers: registration.resolvers,\n\t\t\tattribution: registration.attribution,\n\t\t\tfilterBots,\n\t\t\t...(registration.revenue?.browserAmounts\n\t\t\t\t? { browserAmounts: registration.revenue.browserAmounts }\n\t\t\t\t: {}),\n\t\t})\n\n\t// One handler per registration, so its once-a-process warnings are said once, not per beacon.\n\tlet receiveBeacon = beaconHandler()\n\tconst receive = async (req: PayloadRequest): Promise<Response> => {\n\t\t// A beacon can be the first thing an instance serves (a worker booted without onInit, a\n\t\t// fresh HMR config): the runtime attaches the adapter to it first.\n\t\tgetRuntime(req.payload)\n\t\treturn receiveBeacon(req)\n\t}\n\n\t/**\n\t * One run of `analytics-maintain`, on whichever instance the job runner took it on: the engine's\n\t * upkeep, then the read cache's expired entries, under the sweep's own lease.\n\t */\n\tconst maintainOnTask = async (\n\t\treq: PayloadRequest,\n\t\tinput: { rebuild?: RebuildDaysInput }\n\t): Promise<MaintainTaskOutput> => {\n\t\t// A worker booted without onInit may run the task before anything else built its runtime.\n\t\tconst runtime = getRuntime(req.payload)\n\t\tconst report = await instanceOf(req.payload).engine.maintain({\n\t\t\tbudgetMs: MAINTAIN_TASK_BUDGET_MS,\n\t\t\treq,\n\t\t\theartbeat: true,\n\t\t\t...(input.rebuild ? { rebuild: input.rebuild } : {}),\n\t\t})\n\t\tlet sweptCache = 0\n\t\ttry {\n\t\t\tsweptCache = (await runtime?.cache?.sweeper.sweep(TASK_SWEEP_BATCHES))?.swept ?? 0\n\t\t} catch (err) {\n\t\t\treq.payload.logger.warn(`analytics: sweeping expired cache entries failed: ${String(err)}`)\n\t\t}\n\t\treturn { ...report, sweptCache }\n\t}\n\n\tconst ingest = {\n\t\t// Read late: the plugin's base arrives with the register context.\n\t\tget path() {\n\t\t\treturn options.ingestPath ?? mountedIngestPath\n\t\t},\n\t\ttrack: makeServerTrack({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tgetResolvers: () => registration.resolvers,\n\t\t\tgetAttribution: () => registration.attribution,\n\t\t}),\n\t\t// The endpoint's hostname policy without the scoped drop rule (this caller knows its\n\t\t// boundary); a capture call site, so the host's resolver sees the visit, not the user.\n\t\thostname: (args: Parameters<IngestHostnameResolver>[0]) =>\n\t\t\tresolveEventHostname({\n\t\t\t\toption: hostname,\n\t\t\t\tclaimed: args.claimed,\n\t\t\t\treq: captureRequest(args.req),\n\t\t\t\tscope: args.scope ?? null,\n\t\t\t\ttrustedProxyHops: registration.attribution.trustedProxyHops,\n\t\t\t}),\n\t}\n\n\treturn {\n\t\tid: NATIVE_ADAPTER_ID,\n\t\t...adapterLabel(options.label, 'Payload', 'native({ label })'),\n\t\tget capabilities() {\n\t\t\treturn capabilities\n\t\t},\n\t\tcapture: { ...nativeCapture, ...cookielessCapture({ kind: 'inherent' }, withoutConsent) },\n\t\tingest,\n\t\tisConfigured: () => true,\n\t\tflush: async (payload) => {\n\t\t\tawait instanceOf(payload).writer.flush()\n\t\t},\n\t\trebuild: (payload, input) => {\n\t\t\tgetRuntime(payload)\n\t\t\treturn instanceOf(payload).engine.rebuild(input)\n\t\t},\n\t\treceive,\n\t\tregister(config: Config, context) {\n\t\t\tif (isD1({ db: { name: config.db?.name ?? '' } })) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tregistration = registrationOf(context)\n\t\t\tcapabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\t\t\tif (context?.routes) {\n\t\t\t\tmountedIngestPath = context.routes.ingest\n\t\t\t}\n\t\t\treceiveBeacon = beaconHandler()\n\t\t\taddStoreCollections(config, context?.notice)\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'post', path: ingest.path, handler: receive },\n\t\t\t]\n\t\t\tconst { jobs } = registration\n\t\t\tif (jobs !== false) {\n\t\t\t\taddTask(\n\t\t\t\t\tconfig,\n\t\t\t\t\tmaintainTask({\n\t\t\t\t\t\tschedule: jobs.maintain,\n\t\t\t\t\t\trun: maintainOnTask,\n\t\t\t\t\t\tconcurrency: registration.jobsConcurrency,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t\tregisterSchema(config: Config, context: AdapterSchemaContext) {\n\t\t\taddStoreCollections(config, context.notice)\n\t\t\tif (context.jobs !== false) {\n\t\t\t\taddTask(config, schemaOnlyTask(MAINTAIN_TASK_SLUG, context.jobs.maintain))\n\t\t\t}\n\t\t},\n\t\tattach(payload: Payload) {\n\t\t\tif (isD1(payload)) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tif (\n\t\t\t\t!warnedMaxmind &&\n\t\t\t\tregistration.maxmind === undefined &&\n\t\t\t\tneedsMaxmindSdk(configuredGeo) &&\n\t\t\t\tisProductionBuild()\n\t\t\t) {\n\t\t\t\twarnedMaxmind = true\n\t\t\t\tpayload.logger?.warn(MAXMIND_SDK_WARNING)\n\t\t\t}\n\t\t\tinstanceOf(payload)\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tawait closeNativeInstance(payload, registration)\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.read(q, ctx)\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.realtime(q, ctx)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;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EF;EACA,eAAe,QAAgB,SAA+B;GAC7D,oBAAoB,QAAQ,QAAQ,MAAM;GAC1C,IAAI,QAAQ,SAAS,OACpB,QAAQ,QAAQ,eAAe,oBAAoB,QAAQ,KAAK,QAAQ,CAAC;EAE3E;EACA,OAAO,SAAkB;GACxB,IAAI,KAAK,OAAO,GACf,MAAM,IAAI,MAAM,UAAU;GAE3B,IACC,CAAC,iBACD,aAAa,YAAY,KAAA,KACzB,gBAAgB,aAAa,KAC7B,kBAAkB,GACjB;IACD,gBAAgB;IAChB,QAAQ,QAAQ,KAAK,mBAAmB;GACzC;GACA,WAAW,OAAO;EACnB;EACA,MAAM,MAAM,SAAkB;GAC7B,MAAM,oBAAoB,SAAS,YAAY;EAChD;EACA,MAAM,MAAM,GAAmB,KAAgD;GAC9E,OAAO,WAAW,UAAU,GAAG,CAAC,EAAE,OAAO,KAAK,GAAG,GAAG;EACrD;EACA,MAAM,SAAS,GAAmB,KAAgD;GACjF,OAAO,WAAW,UAAU,GAAG,CAAC,EAAE,OAAO,SAAS,GAAG,GAAG;EACzD;CACD;AACD"}
@@ -6,7 +6,7 @@ import { PART_KEYS, addParts, emptyParts } from "./parts.js";
6
6
  import { SESSION_DIMENSIONS, checkOrder, checkRowLimit, checkScopes, compareRanked, countedParts, countsSomething, isSessionDimension, partsFrom } from "./rawRead.js";
7
7
  import { UNKNOWN_WHEN_FOLDED, compareByRank, foldParts, resolveCaps } from "./caps.js";
8
8
  import { aggregateId, ulid } from "./ids.js";
9
- /** Rows per statement or bulk write: 23 values each, well under SQLite's parameter limit. */
9
+ /** Rows per statement or bulk write: 25 values each, well under SQLite's parameter limit. */
10
10
  const AGGREGATE_CHUNK = 500;
11
11
  /** The parts a hit kind's rows count. */
12
12
  const HIT_COUNTED = countedParts("hit", true);
@@ -1 +1 @@
1
- {"version":3,"file":"aggregate.js","names":[],"sources":["../../../src/native/store/aggregate.ts"],"sourcesContent":["import { type CalendarDay, calendarDayStart, isCalendarDay } from '../../timeframe/calendar'\nimport { isValidTimeZone } from '../../timeframe/tz'\nimport {\n\ttype CapKey,\n\ttype CappableRow,\n\ttype CardinalityCaps,\n\tcompareByRank,\n\tfoldParts,\n\tOTHER_VALUE,\n\tresolveCaps,\n\tUNKNOWN_WHEN_FOLDED,\n} from './caps'\nimport { chunksOf, mapInSlices } from './chunks'\nimport { aggregateId, ulid } from './ids'\nimport { addParts, emptyParts, type MetricParts, PART_KEYS, sumParts } from './parts'\nimport {\n\tcheckOrder,\n\tcheckRowLimit,\n\tcheckScopes,\n\tcompareRanked,\n\tcountedParts,\n\tcountsSomething,\n\tisSessionDimension,\n\tpartsFrom,\n\tSESSION_DIMENSIONS,\n\ttype SessionAttribute,\n} from './rawRead'\nimport { DAY_LEASE_MS, dayEnd, dayFinalAfter, dayKey } from './state'\nimport type {\n\tAggDim,\n\tAggregateHooks,\n\tAggregateRead,\n\tAggregateResult,\n\tAggregateRow,\n\tAggregateRun,\n\tCompletedDayStatus,\n\tDayMarker,\n\tDayWindow,\n\tFoldRead,\n\tStateStore,\n} from './types'\n\n/**\n * Bumped whenever what a day's rows count changes, so days written under an older version read as\n * stale and are aggregated again.\n */\nexport const AGGREGATION_VERSION = 4\n\n/** Rows per statement or bulk write: 23 values each, well under SQLite's parameter limit. */\nconst AGGREGATE_CHUNK = 500\n\n/**\n * Where a kind's values come from: the day, the hit's visit, the hit (`name` on events only),\n * each goal it completed (alone or with a visit attribute), or each item clicked or seen.\n */\ntype KindSource =\n\t| { from: 'site' }\n\t| { from: 'visit'; attribute: SessionAttribute }\n\t| { from: 'hit'; field: 'path' | 'name' | 'currency' }\n\t| { from: 'goal'; attribute: SessionAttribute | null }\n\t| { from: 'item'; page: boolean }\n\n/** One kind of aggregate row: a dimension, or a pair of them. */\nexport interface AggregateKind {\n\t/** Its place in {@link AGGREGATE_KINDS}, which is how a day's read names it. */\n\tindex: number\n\tdim: AggDim\n\tdim2: AggDim\n\t/** The cap bounding its values; null for the site row, which has one value. */\n\tcap: CapKey | null\n\tsource: KindSource\n\t/** The parts its rows count; every other part is null. */\n\tcounted: ReadonlySet<keyof MetricParts>\n}\n\n/** The parts a hit kind's rows count. */\nexport const HIT_COUNTED = countedParts('hit', true)\n/** The parts an item kind's rows count. */\nexport const ITEM_COUNTED = countedParts('item', true)\n\nconst SESSION_KINDS = Object.keys(SESSION_DIMENSIONS)\n\t.filter(isSessionDimension)\n\t.map(\n\t\t(dim): Omit<AggregateKind, 'index'> => ({\n\t\t\tdim,\n\t\t\tdim2: '',\n\t\t\tcap: dim,\n\t\t\tsource: { from: 'visit', attribute: SESSION_DIMENSIONS[dim] },\n\t\t\tcounted: HIT_COUNTED,\n\t\t})\n\t)\n\nconst goalKind = (\n\tdim2: AggDim,\n\tattribute: SessionAttribute | null\n): Omit<AggregateKind, 'index'> => ({\n\tdim: 'goal',\n\tdim2,\n\tcap: attribute === null ? 'goal' : 'goalPairs',\n\tsource: { from: 'goal', attribute },\n\tcounted: HIT_COUNTED,\n})\n\nconst KINDS: ReadonlyArray<Omit<AggregateKind, 'index'>> = [\n\t{ dim: '', dim2: '', cap: null, source: { from: 'site' }, counted: HIT_COUNTED },\n\t...SESSION_KINDS,\n\t{\n\t\tdim: 'page',\n\t\tdim2: '',\n\t\tcap: 'page',\n\t\tsource: { from: 'hit', field: 'path' },\n\t\tcounted: HIT_COUNTED,\n\t},\n\t{\n\t\tdim: 'event',\n\t\tdim2: '',\n\t\tcap: 'event',\n\t\tsource: { from: 'hit', field: 'name' },\n\t\tcounted: HIT_COUNTED,\n\t},\n\t{\n\t\tdim: 'currency',\n\t\tdim2: '',\n\t\tcap: 'currency',\n\t\tsource: { from: 'hit', field: 'currency' },\n\t\tcounted: HIT_COUNTED,\n\t},\n\tgoalKind('', null),\n\tgoalKind('channel', 'channel'),\n\tgoalKind('source', 'source'),\n\tgoalKind('utmCampaign', 'utmCampaign'),\n\t{\n\t\tdim: 'item',\n\t\tdim2: '',\n\t\tcap: 'item',\n\t\tsource: { from: 'item', page: false },\n\t\tcounted: ITEM_COUNTED,\n\t},\n\t{\n\t\tdim: 'item',\n\t\tdim2: 'page',\n\t\tcap: 'itemPages',\n\t\tsource: { from: 'item', page: true },\n\t\tcounted: ITEM_COUNTED,\n\t},\n]\n\n/**\n * Every kind a day is aggregated into, per hostname only: a visitor id is per hostname, so a sum\n * over hostnames is exact and a row across them would only repeat it.\n */\nexport const AGGREGATE_KINDS: readonly AggregateKind[] = KINDS.map((kind, index) => ({\n\t...kind,\n\tindex,\n}))\n\n/** The kinds a day writes: all of them, the item by page rows only when the install keeps them. */\nexport const kindsWritten = (itemPages: boolean): AggregateKind[] =>\n\tAGGREGATE_KINDS.filter((kind) => itemPages || kind.source.from !== 'item' || !kind.source.page)\n\n/** Every `dim` and every `dim2` a kind can have: what bounds a sweep of one day's rows. */\nexport const KIND_DIMS: readonly AggDim[] = [...new Set(AGGREGATE_KINDS.map((kind) => kind.dim))]\nexport const KIND_DIMS2: readonly AggDim[] = [...new Set(AGGREGATE_KINDS.map((kind) => kind.dim2))]\n\nexport const kindOf = (dim: AggDim, dim2: AggDim): AggregateKind | undefined =>\n\tAGGREGATE_KINDS.find((kind) => kind.dim === dim && kind.dim2 === dim2)\n\nconst refuse = (message: string): never => {\n\tthrow new Error(`analytics: ${message}`)\n}\n\n/** A local day of a scope, cut in `tz`. */\nexport const dayWindow = (scope: string, day: CalendarDay, tz: string): DayWindow => ({\n\tscope,\n\tday,\n\ttz,\n\tstart: calendarDayStart(day, tz),\n\tend: dayEnd(day, tz),\n})\n\n/**\n * A day's window starting at `start` instead, where the day before keeps a count that ended\n * there (see `windowOf`); unchanged without one.\n */\nexport const startingAt = (window: DayWindow, start: Date | undefined): DayWindow =>\n\tstart === undefined ? window : { ...window, start }\n\n/** How far a window's start may stray from its day's: zones' days start at most 26 hours apart. */\nconst SEAM_REACH_MS = 2 * 86_400_000\n\n/**\n * Refuses a window that is not its day's in its zone: it must end at the next day's start, and\n * start at its own or within a seam's reach of it, never after its end.\n */\nexport const checkDayWindow = (window: DayWindow): void => {\n\tif (typeof window.scope !== 'string') {\n\t\trefuse('a day window needs a scope, \"\" for none')\n\t}\n\tif (!isCalendarDay(window.day)) {\n\t\trefuse(`${String(window.day)} is not a calendar day (yyyymmdd)`)\n\t}\n\tif (!isValidTimeZone(window.tz)) {\n\t\trefuse(`\"${window.tz}\" is not an IANA time zone`)\n\t}\n\tconst expected = dayWindow(window.scope, window.day, window.tz)\n\tif (\n\t\t!(window.start instanceof Date) ||\n\t\t!(window.end instanceof Date) ||\n\t\tNumber.isNaN(window.start.getTime()) ||\n\t\twindow.end.getTime() !== expected.end.getTime() ||\n\t\twindow.start > window.end ||\n\t\tMath.abs(window.start.getTime() - expected.start.getTime()) > SEAM_REACH_MS\n\t) {\n\t\trefuse(\n\t\t\t`${window.day} in ${window.tz} runs from ${expected.start.toISOString()} (or a seam near it) to ${expected.end.toISOString()}`\n\t\t)\n\t}\n}\n\n/** Where a window starts when that is not its day's own start in its zone, else null. */\nexport const seamOf = (window: DayWindow): Date | null =>\n\twindow.start.getTime() === calendarDayStart(window.day, window.tz).getTime()\n\t\t? null\n\t\t: new Date(window.start.getTime())\n\nconst COMPLETED: readonly CompletedDayStatus[] = ['partial', 'provisional', 'final']\n\n/** A run checked, with its caps filled in from the defaults. */\nexport const checkRun = (run: AggregateRun): { caps: CardinalityCaps; itemPages: boolean } => {\n\tif (typeof run.runId !== 'string' || run.runId === '') {\n\t\trefuse('an aggregation run needs the id it holds the day lease under')\n\t}\n\tif (!COMPLETED.includes(run.status)) {\n\t\trefuse(`a day is completed as ${COMPLETED.join(', ')}, not \"${String(run.status)}\"`)\n\t}\n\tif (run.itemPages !== undefined && typeof run.itemPages !== 'boolean') {\n\t\trefuse('itemPages is true or false')\n\t}\n\tif (run.timeoutMs !== undefined && (!Number.isInteger(run.timeoutMs) || run.timeoutMs < 1)) {\n\t\trefuse(`a count's timeout is a whole number of milliseconds, got ${run.timeoutMs}`)\n\t}\n\treturn { caps: resolveCaps(run.caps), itemPages: run.itemPages ?? true }\n}\n\n/** One row of a day's read, before capping. */\nexport interface DayRow extends CappableRow {\n\tkind: AggregateKind\n}\n\n/**\n * A row of a day's read, the parts its kind does not count null; a `folded` row (the database's\n * `(other)`) leaves visitors and visits unknown. Undefined for an index no kind has.\n */\nexport const dayRowOf = (\n\trow: { kind: number; hostname: string; value: string; value2: string; folded?: boolean },\n\tpart: (key: keyof MetricParts) => number | null\n): DayRow | undefined => {\n\tconst kind = AGGREGATE_KINDS[row.kind]\n\tif (!kind) {\n\t\treturn undefined\n\t}\n\tconst parts = partsFrom(kind.counted, part)\n\tif (row.folded === true) {\n\t\tfor (const unknown of UNKNOWN_WHEN_FOLDED) {\n\t\t\tparts[unknown] = null\n\t\t}\n\t}\n\treturn { kind, hostname: row.hostname, value: row.value, value2: row.value2, parts }\n}\n\n/** Whether a row is an `(other)` row: a capped kind's row with no value of its own. */\nconst isOtherRow = (row: DayRow): boolean =>\n\trow.kind.cap !== null && (row.kind.dim2 === '' ? row.value : row.value2) === OTHER_VALUE\n\n/**\n * A day's rows capped per hostname and kind (a pair's per first value, its `(other)` row keeping\n * it), each tail folded with any `(other)` row the database folded: capping twice changes nothing.\n */\nexport const capDay = (rows: readonly DayRow[], caps: CardinalityCaps): DayRow[] => {\n\tconst groups = new Map<string, DayRow[]>()\n\tfor (const row of rows) {\n\t\tconst pair = row.kind.dim2 !== ''\n\t\tconst key = JSON.stringify([row.hostname, row.kind.index, pair ? row.value : null])\n\t\tconst group = groups.get(key)\n\t\tif (group) {\n\t\t\tgroup.push(row)\n\t\t} else {\n\t\t\tgroups.set(key, [row])\n\t\t}\n\t}\n\tconst capped: DayRow[] = []\n\tfor (const group of groups.values()) {\n\t\tconst [first] = group\n\t\tif (!first) {\n\t\t\tcontinue\n\t\t}\n\t\tconst { kind, hostname } = first\n\t\tconst cap = kind.cap === null ? null : caps[kind.cap]\n\t\tif (cap === null) {\n\t\t\tcapped.push(...group)\n\t\t\tcontinue\n\t\t}\n\t\tconst own = group.filter((row) => !isOtherRow(row))\n\t\tconst ranked = own.length <= cap ? own : [...own].sort(compareByRank)\n\t\tconst tail = [...ranked.slice(cap), ...group.filter(isOtherRow)]\n\t\tcapped.push(...ranked.slice(0, cap))\n\t\tif (tail.length > 0) {\n\t\t\tcapped.push({\n\t\t\t\tkind,\n\t\t\t\thostname,\n\t\t\t\tvalue: kind.dim2 === '' ? OTHER_VALUE : first.value,\n\t\t\t\tvalue2: OTHER_VALUE,\n\t\t\t\tparts: foldParts(tail),\n\t\t\t})\n\t\t}\n\t}\n\treturn capped\n}\n\n/** An aggregate row as written: its key, the generation that wrote it, and its parts. */\nexport interface AggregateRecord {\n\t/** Its key's content id: a rewrite of the day writes the same id again. */\n\tid: string\n\tscope: string\n\tday: CalendarDay\n\thostname: string\n\tdim: AggDim\n\tvalue: string\n\tdim2: AggDim\n\tvalue2: string\n\tgen: string\n\tparts: MetricParts\n}\n\n/** One of a day's rows as a record of generation `gen`. */\nexport const recordOf = (window: DayWindow, row: DayRow, gen: string): AggregateRecord => {\n\tconst key = {\n\t\tscope: window.scope,\n\t\tday: window.day,\n\t\thostname: row.hostname,\n\t\tdim: row.kind.dim,\n\t\tvalue: row.value,\n\t\tdim2: row.kind.dim2,\n\t\tvalue2: row.value2,\n\t}\n\treturn { id: aggregateId(key), ...key, gen, parts: row.parts }\n}\n\n/**\n * Records in id order, so writers lock keys in one order. Ids are base64url, plain ASCII, so the\n * operators' order is code point order, at a quarter of `compareCodePoints`' cost on a busy day.\n */\nexport const byRecordId = (a: AggregateRecord, b: AggregateRecord): number =>\n\ta.id < b.id ? -1 : a.id > b.id ? 1 : 0\n\n/** The marker a run completes its day with: its rows' generation, readable from then on. */\nexport const completedMarker = (\n\twindow: DayWindow,\n\trun: { status: CompletedDayStatus; gen: string; hits: number; at: Date }\n): DayMarker => ({\n\tscope: window.scope,\n\tday: window.day,\n\ttz: window.tz,\n\tstart: seamOf(window),\n\tstatus: run.status,\n\tversion: AGGREGATION_VERSION,\n\tgen: run.gen,\n\thits: run.hits,\n\tleaseOwner: null,\n\tleaseUntil: null,\n\tfinalAfter: dayFinalAfter(window.day, window.tz),\n\taggregatedAt: run.at,\n})\n\n/** An aggregate read checked, with the kind it reads and the column it groups by. */\nexport interface AggregatePlan {\n\tread: AggregateRead\n\tkind: AggregateKind\n\tgroup: 'day' | 'value' | 'value2' | null\n}\n\nconst GROUPS: ReadonlyArray<AggregateRead['groupBy']> = ['total', 'day', 'value', 'value2']\n\n/** Refuses days that are not one or more ranges of calendar days, each in order. */\nconst checkDayRanges = (days: AggregateRead['days'], read: string): void => {\n\tif (!Array.isArray(days) || days.length === 0) {\n\t\trefuse(`${read} needs at least one range of days`)\n\t}\n\tfor (const [from, to] of days) {\n\t\tif (!isCalendarDay(from) || !isCalendarDay(to) || from > to) {\n\t\t\trefuse(`${String(from)} to ${String(to)} is not a range of calendar days`)\n\t\t}\n\t}\n}\n\n/** A read checked against the kinds there are; anything malformed throws. */\nexport const planAggregateRead = (read: AggregateRead): AggregatePlan => {\n\tconst dim2 = read.dim2 ?? ''\n\tconst kind = kindOf(read.dim, dim2)\n\tif (!kind) {\n\t\treturn refuse(`no aggregate rows are kept by \"${read.dim}\" and \"${dim2}\"`)\n\t}\n\tif (!GROUPS.includes(read.groupBy)) {\n\t\trefuse(`an aggregate read groups by ${GROUPS.join(', ')}, not \"${String(read.groupBy)}\"`)\n\t}\n\tif (read.groupBy === 'value' && kind.dim === '') {\n\t\trefuse('the site row has no values to group by')\n\t}\n\tif (read.groupBy === 'value2' && kind.dim2 === '') {\n\t\trefuse('only a pair has a second value to group by')\n\t}\n\tif (read.values !== undefined && read.groupBy !== 'value' && read.groupBy !== 'value2') {\n\t\trefuse('values fill in a breakdown, so they need groupBy value or value2')\n\t}\n\tcheckDayRanges(read.days, 'an aggregate read')\n\tcheckScopes(read)\n\tcheckOrder(read.order)\n\tcheckRowLimit(read.limit)\n\treturn {\n\t\tread,\n\t\tkind,\n\t\tgroup: read.groupBy === 'total' ? null : read.groupBy,\n\t}\n}\n\n/** A fold read checked against the kinds there are, with the kind it reads. */\nexport const planFoldRead = (read: FoldRead): AggregateKind => {\n\tconst kind = kindOf(read.dim, read.dim2 ?? '')\n\tif (!kind || kind.dim === '') {\n\t\treturn refuse(`no folded values are kept by \"${read.dim}\" and \"${read.dim2 ?? ''}\"`)\n\t}\n\tif (typeof read.value !== 'string' || read.value === OTHER_VALUE) {\n\t\trefuse('a fold read asks about one value, never the (other) row')\n\t}\n\tcheckDayRanges(read.days, 'a fold read')\n\treturn kind\n}\n\n/**\n * The days a fold read's rows show folded, oldest first. `rows` are the completed days' rows of\n * the value and the `(other)` row: a pair's are its first value's `(other)` rows alone.\n */\nexport const foldedDaysOf = (\n\tkind: AggregateKind,\n\tread: FoldRead,\n\trows: ReadonlyArray<{ day: CalendarDay; hostname: string; value: string; value2: string }>\n): CalendarDay[] => {\n\tconst days = new Set<CalendarDay>()\n\tif (kind.dim2 !== '') {\n\t\tfor (const row of rows) {\n\t\t\tif (row.value === read.value && row.value2 === OTHER_VALUE) {\n\t\t\t\tdays.add(row.day)\n\t\t\t}\n\t\t}\n\t\treturn [...days].sort((a, b) => a - b)\n\t}\n\tconst seen = new Map<string, { day: CalendarDay; other: boolean; own: boolean }>()\n\tfor (const row of rows) {\n\t\tconst key = JSON.stringify([row.day, row.hostname])\n\t\tconst entry = seen.get(key) ?? { day: row.day, other: false, own: false }\n\t\tseen.set(key, entry)\n\t\tif (row.value === OTHER_VALUE) {\n\t\t\tentry.other = true\n\t\t} else if (row.value === read.value) {\n\t\t\tentry.own = true\n\t\t}\n\t}\n\tfor (const entry of seen.values()) {\n\t\tif (entry.other && !entry.own) {\n\t\t\tdays.add(entry.day)\n\t\t}\n\t}\n\treturn [...days].sort((a, b) => a - b)\n}\n\n/** Whether a day lies in any of the ranges, both ends included. */\nexport const inRanges = (\n\tday: CalendarDay,\n\tranges: ReadonlyArray<readonly [CalendarDay, CalendarDay]>\n): boolean => ranges.some(([from, to]) => day >= from && day <= to)\n\n/** The one row a total answers when no completed day holds a row of its kind. */\nexport const emptyAggregateRow = (plan: AggregatePlan): AggregateRow => ({\n\tvalue: null,\n\tparts: partsFrom(plan.kind.counted, () => 0),\n})\n\n/**\n * A read's summed rows as it answers them: a total its one row, anything grouped without its empty\n * rows, ordered and cut.\n */\nconst answered = (plan: AggregatePlan, rows: readonly AggregateRow[]): AggregateRow[] => {\n\tif (plan.group === null) {\n\t\treturn [rows[0] ?? emptyAggregateRow(plan)]\n\t}\n\tconst ranked = rows\n\t\t.filter((row) => countsSomething(row.parts))\n\t\t.sort(compareRanked<AggregateRow>(plan.read.order, (row) => row.day ?? 0))\n\treturn plan.read.limit === undefined ? ranked : ranked.slice(0, plan.read.limit)\n}\n\n/**\n * The rows a read answers out of the rows it matched, summed in memory: the reference answer every\n * database store must match.\n */\nexport const answerAggregateRead = (\n\tplan: AggregatePlan,\n\tmatched: ReadonlyArray<{ day: CalendarDay; value: string; value2: string; parts: MetricParts }>\n): AggregateRow[] => {\n\tconst { read } = plan\n\tconst values = read.values === undefined ? null : new Set(read.values)\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ value: string | null; day?: CalendarDay; parts: MetricParts[] }\n\t>()\n\tfor (const row of matched) {\n\t\tconst value = plan.group === 'value' ? row.value : plan.group === 'value2' ? row.value2 : null\n\t\tif (value === OTHER_VALUE || (values && (value === null || !values.has(value)))) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = plan.group === 'day' ? row.day : undefined\n\t\tconst key = JSON.stringify([value, day ?? null])\n\t\tconst group = groups.get(key) ?? { value, ...(day === undefined ? {} : { day }), parts: [] }\n\t\tgroups.set(key, group)\n\t\tgroup.parts.push(row.parts)\n\t}\n\treturn answered(\n\t\tplan,\n\t\t[...groups.values()].map(\n\t\t\t({ parts, ...group }): AggregateRow => ({ ...group, parts: sumParts(parts) })\n\t\t)\n\t)\n}\n\n/**\n * What reads of one plan over disjoint sets of rows answered (none of them filled in or cut), as\n * one read would: summed by value and day, the empty groups dropped, ordered and cut.\n */\nexport const mergeAggregateRows = (\n\tplan: AggregatePlan,\n\trows: readonly AggregateRow[]\n): AggregateRow[] => {\n\tconst groups = new Map<string, AggregateRow>()\n\tfor (const row of rows) {\n\t\tconst key = JSON.stringify([row.value, row.day ?? null])\n\t\tconst held = groups.get(key)\n\t\tgroups.set(key, held ? { ...held, parts: addParts(held.parts, row.parts) } : row)\n\t}\n\treturn answered(plan, [...groups.values()])\n}\n\n/** The parts of a row summed by a database: null where no row it summed counted the part. */\nexport const partsOfSums = (part: (key: keyof MetricParts) => number | null): MetricParts => {\n\tconst parts = emptyParts()\n\tfor (const key of PART_KEYS) {\n\t\tparts[key] = part(key)\n\t}\n\treturn parts\n}\n\nconst dayMarker = async (state: StateStore, window: DayWindow): Promise<DayMarker | undefined> => {\n\tconst [marker] = await state.markers(window.scope, window.day, window.day)\n\treturn marker\n}\n\n/** The day's marker while `runId` holds its lease, or undefined when it holds none. */\nexport const heldMarker = async (\n\tstate: StateStore,\n\twindow: DayWindow,\n\trunId: string\n): Promise<DayMarker | undefined> => {\n\tconst marker = await dayMarker(state, window)\n\treturn marker?.leaseOwner === runId ? marker : undefined\n}\n\n/** A run that wrote nothing readers will see. */\nexport const refusedRun = (hits: number): AggregateResult => ({ completed: false, hits, rows: 0 })\n\n/**\n * Records made per slice of the event loop: a busy day's tens of thousands, each hashed for its id,\n * would otherwise hold the thread for most of a second.\n */\nconst RECORD_SLICE = 2_000\n\n/** Where a store keeps a day's rows, one generation beside another. */\nexport interface GenerationWriter {\n\t/** Every generation the day's rows carry. */\n\tgens(window: DayWindow): Promise<string[]>\n\t/** Writes records as rows of their own generation, never over another generation's. */\n\twrite(records: readonly AggregateRecord[]): Promise<void>\n\tdrop(window: DayWindow, gens: readonly string[]): Promise<void>\n}\n\n/**\n * Writes a day beside its readable rows, then completes the marker to switch to them. Deletes only\n * dead generations: \"all but mine\" from a run frozen past its lease would hit its successor's.\n */\nexport const writeBeside = async (args: {\n\tstate: StateStore\n\twriter: GenerationWriter\n\twindow: DayWindow\n\t/** `gen`: the marker's generation when the run began, which must still be the readable one. */\n\trun: { runId: string; status: CompletedDayStatus; gen: string | null }\n\trows: readonly DayRow[]\n\thits: number\n\tnow: () => Date\n\thooks?: AggregateHooks\n}): Promise<AggregateResult> => {\n\tconst { state, writer, window, run, hooks } = args\n\t// Renewed, never claimed: a lease a dirty mark revoked must stay lost to this run.\n\tif (!(await state.renew(dayKey(window.scope, window.day), run.runId, DAY_LEASE_MS))) {\n\t\treturn refusedRun(args.hits)\n\t}\n\tconst current = await dayMarker(state, window)\n\tif (current?.leaseOwner !== run.runId || current.gen !== run.gen) {\n\t\treturn refusedRun(args.hits)\n\t}\n\tconst leftovers = (await writer.gens(window)).filter((gen) => gen !== run.gen)\n\tconst gen = ulid(args.now())\n\tconst note = { scope: window.scope, day: window.day, gen }\n\tawait state.noteDrop(note)\n\tconst records = (\n\t\tawait mapInSlices(args.rows, RECORD_SLICE, (row) => recordOf(window, row, gen))\n\t).sort(byRecordId)\n\ttry {\n\t\tlet written = 0\n\t\tfor (const chunk of chunksOf(records, AGGREGATE_CHUNK)) {\n\t\t\tawait writer.write(chunk)\n\t\t\twritten += chunk.length\n\t\t\tawait hooks?.afterChunk?.(written)\n\t\t}\n\t\tconst marker = completedMarker(window, {\n\t\t\tstatus: run.status,\n\t\t\tgen,\n\t\t\thits: args.hits,\n\t\t\tat: args.now(),\n\t\t})\n\t\tif (!(await state.complete(marker, run.runId))) {\n\t\t\tawait writer.drop(window, [gen])\n\t\t\tawait state.clearDrop(note)\n\t\t\treturn refusedRun(args.hits)\n\t\t}\n\t} catch (err) {\n\t\t// A completion that failed in transit may still have landed, making its rows the readable ones.\n\t\tconst readable = await dayMarker(state, window).then(\n\t\t\t(after) => after?.gen === gen,\n\t\t\t() => true\n\t\t)\n\t\tif (!readable) {\n\t\t\tawait writer.drop(window, [gen]).then(\n\t\t\t\t() => state.clearDrop(note),\n\t\t\t\t() => undefined\n\t\t\t)\n\t\t}\n\t\tthrow err\n\t}\n\tawait hooks?.afterComplete?.()\n\tconst dead = [...(run.gen === null ? [] : [run.gen]), ...leftovers]\n\ttry {\n\t\tif (dead.length > 0) {\n\t\t\tawait writer.drop(window, dead)\n\t\t}\n\t\tawait state.clearDrop(note)\n\t} catch {\n\t\t// The day is complete either way; maintenance finishes the note a failed drop leaves.\n\t}\n\treturn { completed: true, hits: args.hits, rows: records.length }\n}\n\n/** A scope and a day as one key of the map of the generation each completed day reads. */\nexport const dayGenKey = (scope: string, day: CalendarDay): string => JSON.stringify([scope, day])\n\nconst STABLE_ATTEMPTS = 3\n\n/**\n * Reads days' rows between two reads of their generations, again when a day was swapped meanwhile,\n * as a store without transactions has no snapshot to read in.\n */\nexport const readStable = async <T>(args: {\n\tgens: () => Promise<ReadonlyMap<string, string>>\n\trows: (gens: ReadonlyMap<string, string>) => Promise<T>\n}): Promise<T> => {\n\tfor (let attempt = 1; ; attempt++) {\n\t\tconst before = await args.gens()\n\t\tconst result = await args.rows(before)\n\t\tconst after = await args.gens()\n\t\tif ([...before].every(([key, gen]) => after.get(key) === gen)) {\n\t\t\treturn result\n\t\t}\n\t\tif (attempt >= STABLE_ATTEMPTS) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: the days read were rewritten during each of ${STABLE_ATTEMPTS} reads; read them again`\n\t\t\t)\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;AAiDA,MAAM,kBAAkB;;AA2BxB,MAAa,cAAc,aAAa,OAAO,IAAI;;AAEnD,MAAa,eAAe,aAAa,QAAQ,IAAI;AAErD,MAAM,gBAAgB,OAAO,KAAK,kBAAkB,EAClD,OAAO,kBAAkB,EACzB,KACC,SAAuC;CACvC;CACA,MAAM;CACN,KAAK;CACL,QAAQ;EAAE,MAAM;EAAS,WAAW,mBAAmB;CAAK;CAC5D,SAAS;AACV,EACD;AAED,MAAM,YACL,MACA,eACmC;CACnC,KAAK;CACL;CACA,KAAK,cAAc,OAAO,SAAS;CACnC,QAAQ;EAAE,M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AAI,GAAG,GAAI,GAAG,SAAS;CAClE,IAAI;EACH,IAAI,KAAK,SAAS,GACjB,MAAM,OAAO,KAAK,QAAQ,IAAI;EAE/B,MAAM,MAAM,UAAU,IAAI;CAC3B,QAAQ,CAER;CACA,OAAO;EAAE,WAAW;EAAM,MAAM,KAAK;EAAM,MAAM,QAAQ;CAAO;AACjE;;AAGA,MAAa,aAAa,OAAe,QAA6B,KAAK,UAAU,CAAC,OAAO,GAAG,CAAC;AAEjG,MAAM,kBAAkB;;;;;AAMxB,MAAa,aAAa,OAAU,SAGlB;CACjB,KAAK,IAAI,UAAU,IAAK,WAAW;EAClC,MAAM,SAAS,MAAM,KAAK,KAAK;EAC/B,MAAM,SAAS,MAAM,KAAK,KAAK,MAAM;EACrC,MAAM,QAAQ,MAAM,KAAK,KAAK;EAC9B,IAAI,CAAC,GAAG,MAAM,EAAE,OAAO,CAAC,KAAK,SAAS,MAAM,IAAI,GAAG,MAAM,GAAG,GAC3D,OAAO;EAER,IAAI,WAAW,iBACd,MAAM,IAAI,MACT,0DAA0D,gBAAgB,wBAC3E;CAEF;AACD"}
1
+ {"version":3,"file":"aggregate.js","names":[],"sources":["../../../src/native/store/aggregate.ts"],"sourcesContent":["import { type CalendarDay, calendarDayStart, isCalendarDay } from '../../timeframe/calendar'\nimport { isValidTimeZone } from '../../timeframe/tz'\nimport {\n\ttype CapKey,\n\ttype CappableRow,\n\ttype CardinalityCaps,\n\tcompareByRank,\n\tfoldParts,\n\tOTHER_VALUE,\n\tresolveCaps,\n\tUNKNOWN_WHEN_FOLDED,\n} from './caps'\nimport { chunksOf, mapInSlices } from './chunks'\nimport { aggregateId, ulid } from './ids'\nimport { addParts, emptyParts, type MetricParts, PART_KEYS, sumParts } from './parts'\nimport {\n\tcheckOrder,\n\tcheckRowLimit,\n\tcheckScopes,\n\tcompareRanked,\n\tcountedParts,\n\tcountsSomething,\n\tisSessionDimension,\n\tpartsFrom,\n\tSESSION_DIMENSIONS,\n\ttype SessionAttribute,\n} from './rawRead'\nimport { DAY_LEASE_MS, dayEnd, dayFinalAfter, dayKey } from './state'\nimport type {\n\tAggDim,\n\tAggregateHooks,\n\tAggregateRead,\n\tAggregateResult,\n\tAggregateRow,\n\tAggregateRun,\n\tCompletedDayStatus,\n\tDayMarker,\n\tDayWindow,\n\tFoldRead,\n\tStateStore,\n} from './types'\n\n/**\n * Bumped whenever what a day's rows count changes, so days written under an older version read as\n * stale and are aggregated again.\n */\nexport const AGGREGATION_VERSION = 4\n\n/** Rows per statement or bulk write: 25 values each, well under SQLite's parameter limit. */\nconst AGGREGATE_CHUNK = 500\n\n/**\n * Where a kind's values come from: the day, the hit's visit, the hit (`name` on events only),\n * each goal it completed (alone or with a visit attribute), or each item clicked or seen.\n */\ntype KindSource =\n\t| { from: 'site' }\n\t| { from: 'visit'; attribute: SessionAttribute }\n\t| { from: 'hit'; field: 'path' | 'name' | 'currency' }\n\t| { from: 'goal'; attribute: SessionAttribute | null }\n\t| { from: 'item'; page: boolean }\n\n/** One kind of aggregate row: a dimension, or a pair of them. */\nexport interface AggregateKind {\n\t/** Its place in {@link AGGREGATE_KINDS}, which is how a day's read names it. */\n\tindex: number\n\tdim: AggDim\n\tdim2: AggDim\n\t/** The cap bounding its values; null for the site row, which has one value. */\n\tcap: CapKey | null\n\tsource: KindSource\n\t/** The parts its rows count; every other part is null. */\n\tcounted: ReadonlySet<keyof MetricParts>\n}\n\n/** The parts a hit kind's rows count. */\nexport const HIT_COUNTED = countedParts('hit', true)\n/** The parts an item kind's rows count. */\nexport const ITEM_COUNTED = countedParts('item', true)\n\nconst SESSION_KINDS = Object.keys(SESSION_DIMENSIONS)\n\t.filter(isSessionDimension)\n\t.map(\n\t\t(dim): Omit<AggregateKind, 'index'> => ({\n\t\t\tdim,\n\t\t\tdim2: '',\n\t\t\tcap: dim,\n\t\t\tsource: { from: 'visit', attribute: SESSION_DIMENSIONS[dim] },\n\t\t\tcounted: HIT_COUNTED,\n\t\t})\n\t)\n\nconst goalKind = (\n\tdim2: AggDim,\n\tattribute: SessionAttribute | null\n): Omit<AggregateKind, 'index'> => ({\n\tdim: 'goal',\n\tdim2,\n\tcap: attribute === null ? 'goal' : 'goalPairs',\n\tsource: { from: 'goal', attribute },\n\tcounted: HIT_COUNTED,\n})\n\nconst KINDS: ReadonlyArray<Omit<AggregateKind, 'index'>> = [\n\t{ dim: '', dim2: '', cap: null, source: { from: 'site' }, counted: HIT_COUNTED },\n\t...SESSION_KINDS,\n\t{\n\t\tdim: 'page',\n\t\tdim2: '',\n\t\tcap: 'page',\n\t\tsource: { from: 'hit', field: 'path' },\n\t\tcounted: HIT_COUNTED,\n\t},\n\t{\n\t\tdim: 'event',\n\t\tdim2: '',\n\t\tcap: 'event',\n\t\tsource: { from: 'hit', field: 'name' },\n\t\tcounted: HIT_COUNTED,\n\t},\n\t{\n\t\tdim: 'currency',\n\t\tdim2: '',\n\t\tcap: 'currency',\n\t\tsource: { from: 'hit', field: 'currency' },\n\t\tcounted: HIT_COUNTED,\n\t},\n\tgoalKind('', null),\n\tgoalKind('channel', 'channel'),\n\tgoalKind('source', 'source'),\n\tgoalKind('utmCampaign', 'utmCampaign'),\n\t{\n\t\tdim: 'item',\n\t\tdim2: '',\n\t\tcap: 'item',\n\t\tsource: { from: 'item', page: false },\n\t\tcounted: ITEM_COUNTED,\n\t},\n\t{\n\t\tdim: 'item',\n\t\tdim2: 'page',\n\t\tcap: 'itemPages',\n\t\tsource: { from: 'item', page: true },\n\t\tcounted: ITEM_COUNTED,\n\t},\n]\n\n/**\n * Every kind a day is aggregated into, per hostname only: a visitor id is per hostname, so a sum\n * over hostnames is exact and a row across them would only repeat it.\n */\nexport const AGGREGATE_KINDS: readonly AggregateKind[] = KINDS.map((kind, index) => ({\n\t...kind,\n\tindex,\n}))\n\n/** The kinds a day writes: all of them, the item by page rows only when the install keeps them. */\nexport const kindsWritten = (itemPages: boolean): AggregateKind[] =>\n\tAGGREGATE_KINDS.filter((kind) => itemPages || kind.source.from !== 'item' || !kind.source.page)\n\n/** Every `dim` and every `dim2` a kind can have: what bounds a sweep of one day's rows. */\nexport const KIND_DIMS: readonly AggDim[] = [...new Set(AGGREGATE_KINDS.map((kind) => kind.dim))]\nexport const KIND_DIMS2: readonly AggDim[] = [...new Set(AGGREGATE_KINDS.map((kind) => kind.dim2))]\n\nexport const kindOf = (dim: AggDim, dim2: AggDim): AggregateKind | undefined =>\n\tAGGREGATE_KINDS.find((kind) => kind.dim === dim && kind.dim2 === dim2)\n\nconst refuse = (message: string): never => {\n\tthrow new Error(`analytics: ${message}`)\n}\n\n/** A local day of a scope, cut in `tz`. */\nexport const dayWindow = (scope: string, day: CalendarDay, tz: string): DayWindow => ({\n\tscope,\n\tday,\n\ttz,\n\tstart: calendarDayStart(day, tz),\n\tend: dayEnd(day, tz),\n})\n\n/**\n * A day's window starting at `start` instead, where the day before keeps a count that ended\n * there (see `windowOf`); unchanged without one.\n */\nexport const startingAt = (window: DayWindow, start: Date | undefined): DayWindow =>\n\tstart === undefined ? window : { ...window, start }\n\n/** How far a window's start may stray from its day's: zones' days start at most 26 hours apart. */\nconst SEAM_REACH_MS = 2 * 86_400_000\n\n/**\n * Refuses a window that is not its day's in its zone: it must end at the next day's start, and\n * start at its own or within a seam's reach of it, never after its end.\n */\nexport const checkDayWindow = (window: DayWindow): void => {\n\tif (typeof window.scope !== 'string') {\n\t\trefuse('a day window needs a scope, \"\" for none')\n\t}\n\tif (!isCalendarDay(window.day)) {\n\t\trefuse(`${String(window.day)} is not a calendar day (yyyymmdd)`)\n\t}\n\tif (!isValidTimeZone(window.tz)) {\n\t\trefuse(`\"${window.tz}\" is not an IANA time zone`)\n\t}\n\tconst expected = dayWindow(window.scope, window.day, window.tz)\n\tif (\n\t\t!(window.start instanceof Date) ||\n\t\t!(window.end instanceof Date) ||\n\t\tNumber.isNaN(window.start.getTime()) ||\n\t\twindow.end.getTime() !== expected.end.getTime() ||\n\t\twindow.start > window.end ||\n\t\tMath.abs(window.start.getTime() - expected.start.getTime()) > SEAM_REACH_MS\n\t) {\n\t\trefuse(\n\t\t\t`${window.day} in ${window.tz} runs from ${expected.start.toISOString()} (or a seam near it) to ${expected.end.toISOString()}`\n\t\t)\n\t}\n}\n\n/** Where a window starts when that is not its day's own start in its zone, else null. */\nexport const seamOf = (window: DayWindow): Date | null =>\n\twindow.start.getTime() === calendarDayStart(window.day, window.tz).getTime()\n\t\t? null\n\t\t: new Date(window.start.getTime())\n\nconst COMPLETED: readonly CompletedDayStatus[] = ['partial', 'provisional', 'final']\n\n/** A run checked, with its caps filled in from the defaults. */\nexport const checkRun = (run: AggregateRun): { caps: CardinalityCaps; itemPages: boolean } => {\n\tif (typeof run.runId !== 'string' || run.runId === '') {\n\t\trefuse('an aggregation run needs the id it holds the day lease under')\n\t}\n\tif (!COMPLETED.includes(run.status)) {\n\t\trefuse(`a day is completed as ${COMPLETED.join(', ')}, not \"${String(run.status)}\"`)\n\t}\n\tif (run.itemPages !== undefined && typeof run.itemPages !== 'boolean') {\n\t\trefuse('itemPages is true or false')\n\t}\n\tif (run.timeoutMs !== undefined && (!Number.isInteger(run.timeoutMs) || run.timeoutMs < 1)) {\n\t\trefuse(`a count's timeout is a whole number of milliseconds, got ${run.timeoutMs}`)\n\t}\n\treturn { caps: resolveCaps(run.caps), itemPages: run.itemPages ?? true }\n}\n\n/** One row of a day's read, before capping. */\nexport interface DayRow extends CappableRow {\n\tkind: AggregateKind\n}\n\n/**\n * A row of a day's read, the parts its kind does not count null; a `folded` row (the database's\n * `(other)`) leaves visitors and visits unknown. Undefined for an index no kind has.\n */\nexport const dayRowOf = (\n\trow: { kind: number; hostname: string; value: string; value2: string; folded?: boolean },\n\tpart: (key: keyof MetricParts) => number | null\n): DayRow | undefined => {\n\tconst kind = AGGREGATE_KINDS[row.kind]\n\tif (!kind) {\n\t\treturn undefined\n\t}\n\tconst parts = partsFrom(kind.counted, part)\n\tif (row.folded === true) {\n\t\tfor (const unknown of UNKNOWN_WHEN_FOLDED) {\n\t\t\tparts[unknown] = null\n\t\t}\n\t}\n\treturn { kind, hostname: row.hostname, value: row.value, value2: row.value2, parts }\n}\n\n/** Whether a row is an `(other)` row: a capped kind's row with no value of its own. */\nconst isOtherRow = (row: DayRow): boolean =>\n\trow.kind.cap !== null && (row.kind.dim2 === '' ? row.value : row.value2) === OTHER_VALUE\n\n/**\n * A day's rows capped per hostname and kind (a pair's per first value, its `(other)` row keeping\n * it), each tail folded with any `(other)` row the database folded: capping twice changes nothing.\n */\nexport const capDay = (rows: readonly DayRow[], caps: CardinalityCaps): DayRow[] => {\n\tconst groups = new Map<string, DayRow[]>()\n\tfor (const row of rows) {\n\t\tconst pair = row.kind.dim2 !== ''\n\t\tconst key = JSON.stringify([row.hostname, row.kind.index, pair ? row.value : null])\n\t\tconst group = groups.get(key)\n\t\tif (group) {\n\t\t\tgroup.push(row)\n\t\t} else {\n\t\t\tgroups.set(key, [row])\n\t\t}\n\t}\n\tconst capped: DayRow[] = []\n\tfor (const group of groups.values()) {\n\t\tconst [first] = group\n\t\tif (!first) {\n\t\t\tcontinue\n\t\t}\n\t\tconst { kind, hostname } = first\n\t\tconst cap = kind.cap === null ? null : caps[kind.cap]\n\t\tif (cap === null) {\n\t\t\tcapped.push(...group)\n\t\t\tcontinue\n\t\t}\n\t\tconst own = group.filter((row) => !isOtherRow(row))\n\t\tconst ranked = own.length <= cap ? own : [...own].sort(compareByRank)\n\t\tconst tail = [...ranked.slice(cap), ...group.filter(isOtherRow)]\n\t\tcapped.push(...ranked.slice(0, cap))\n\t\tif (tail.length > 0) {\n\t\t\tcapped.push({\n\t\t\t\tkind,\n\t\t\t\thostname,\n\t\t\t\tvalue: kind.dim2 === '' ? OTHER_VALUE : first.value,\n\t\t\t\tvalue2: OTHER_VALUE,\n\t\t\t\tparts: foldParts(tail),\n\t\t\t})\n\t\t}\n\t}\n\treturn capped\n}\n\n/** An aggregate row as written: its key, the generation that wrote it, and its parts. */\nexport interface AggregateRecord {\n\t/** Its key's content id: a rewrite of the day writes the same id again. */\n\tid: string\n\tscope: string\n\tday: CalendarDay\n\thostname: string\n\tdim: AggDim\n\tvalue: string\n\tdim2: AggDim\n\tvalue2: string\n\tgen: string\n\tparts: MetricParts\n}\n\n/** One of a day's rows as a record of generation `gen`. */\nexport const recordOf = (window: DayWindow, row: DayRow, gen: string): AggregateRecord => {\n\tconst key = {\n\t\tscope: window.scope,\n\t\tday: window.day,\n\t\thostname: row.hostname,\n\t\tdim: row.kind.dim,\n\t\tvalue: row.value,\n\t\tdim2: row.kind.dim2,\n\t\tvalue2: row.value2,\n\t}\n\treturn { id: aggregateId(key), ...key, gen, parts: row.parts }\n}\n\n/**\n * Records in id order, so writers lock keys in one order. Ids are base64url, plain ASCII, so the\n * operators' order is code point order, at a quarter of `compareCodePoints`' cost on a busy day.\n */\nexport const byRecordId = (a: AggregateRecord, b: AggregateRecord): number =>\n\ta.id < b.id ? -1 : a.id > b.id ? 1 : 0\n\n/** The marker a run completes its day with: its rows' generation, readable from then on. */\nexport const completedMarker = (\n\twindow: DayWindow,\n\trun: { status: CompletedDayStatus; gen: string; hits: number; at: Date }\n): DayMarker => ({\n\tscope: window.scope,\n\tday: window.day,\n\ttz: window.tz,\n\tstart: seamOf(window),\n\tstatus: run.status,\n\tversion: AGGREGATION_VERSION,\n\tgen: run.gen,\n\thits: run.hits,\n\tleaseOwner: null,\n\tleaseUntil: null,\n\tfinalAfter: dayFinalAfter(window.day, window.tz),\n\taggregatedAt: run.at,\n})\n\n/** An aggregate read checked, with the kind it reads and the column it groups by. */\nexport interface AggregatePlan {\n\tread: AggregateRead\n\tkind: AggregateKind\n\tgroup: 'day' | 'value' | 'value2' | null\n}\n\nconst GROUPS: ReadonlyArray<AggregateRead['groupBy']> = ['total', 'day', 'value', 'value2']\n\n/** Refuses days that are not one or more ranges of calendar days, each in order. */\nconst checkDayRanges = (days: AggregateRead['days'], read: string): void => {\n\tif (!Array.isArray(days) || days.length === 0) {\n\t\trefuse(`${read} needs at least one range of days`)\n\t}\n\tfor (const [from, to] of days) {\n\t\tif (!isCalendarDay(from) || !isCalendarDay(to) || from > to) {\n\t\t\trefuse(`${String(from)} to ${String(to)} is not a range of calendar days`)\n\t\t}\n\t}\n}\n\n/** A read checked against the kinds there are; anything malformed throws. */\nexport const planAggregateRead = (read: AggregateRead): AggregatePlan => {\n\tconst dim2 = read.dim2 ?? ''\n\tconst kind = kindOf(read.dim, dim2)\n\tif (!kind) {\n\t\treturn refuse(`no aggregate rows are kept by \"${read.dim}\" and \"${dim2}\"`)\n\t}\n\tif (!GROUPS.includes(read.groupBy)) {\n\t\trefuse(`an aggregate read groups by ${GROUPS.join(', ')}, not \"${String(read.groupBy)}\"`)\n\t}\n\tif (read.groupBy === 'value' && kind.dim === '') {\n\t\trefuse('the site row has no values to group by')\n\t}\n\tif (read.groupBy === 'value2' && kind.dim2 === '') {\n\t\trefuse('only a pair has a second value to group by')\n\t}\n\tif (read.values !== undefined && read.groupBy !== 'value' && read.groupBy !== 'value2') {\n\t\trefuse('values fill in a breakdown, so they need groupBy value or value2')\n\t}\n\tcheckDayRanges(read.days, 'an aggregate read')\n\tcheckScopes(read)\n\tcheckOrder(read.order)\n\tcheckRowLimit(read.limit)\n\treturn {\n\t\tread,\n\t\tkind,\n\t\tgroup: read.groupBy === 'total' ? null : read.groupBy,\n\t}\n}\n\n/** A fold read checked against the kinds there are, with the kind it reads. */\nexport const planFoldRead = (read: FoldRead): AggregateKind => {\n\tconst kind = kindOf(read.dim, read.dim2 ?? '')\n\tif (!kind || kind.dim === '') {\n\t\treturn refuse(`no folded values are kept by \"${read.dim}\" and \"${read.dim2 ?? ''}\"`)\n\t}\n\tif (typeof read.value !== 'string' || read.value === OTHER_VALUE) {\n\t\trefuse('a fold read asks about one value, never the (other) row')\n\t}\n\tcheckDayRanges(read.days, 'a fold read')\n\treturn kind\n}\n\n/**\n * The days a fold read's rows show folded, oldest first. `rows` are the completed days' rows of\n * the value and the `(other)` row: a pair's are its first value's `(other)` rows alone.\n */\nexport const foldedDaysOf = (\n\tkind: AggregateKind,\n\tread: FoldRead,\n\trows: ReadonlyArray<{ day: CalendarDay; hostname: string; value: string; value2: string }>\n): CalendarDay[] => {\n\tconst days = new Set<CalendarDay>()\n\tif (kind.dim2 !== '') {\n\t\tfor (const row of rows) {\n\t\t\tif (row.value === read.value && row.value2 === OTHER_VALUE) {\n\t\t\t\tdays.add(row.day)\n\t\t\t}\n\t\t}\n\t\treturn [...days].sort((a, b) => a - b)\n\t}\n\tconst seen = new Map<string, { day: CalendarDay; other: boolean; own: boolean }>()\n\tfor (const row of rows) {\n\t\tconst key = JSON.stringify([row.day, row.hostname])\n\t\tconst entry = seen.get(key) ?? { day: row.day, other: false, own: false }\n\t\tseen.set(key, entry)\n\t\tif (row.value === OTHER_VALUE) {\n\t\t\tentry.other = true\n\t\t} else if (row.value === read.value) {\n\t\t\tentry.own = true\n\t\t}\n\t}\n\tfor (const entry of seen.values()) {\n\t\tif (entry.other && !entry.own) {\n\t\t\tdays.add(entry.day)\n\t\t}\n\t}\n\treturn [...days].sort((a, b) => a - b)\n}\n\n/** Whether a day lies in any of the ranges, both ends included. */\nexport const inRanges = (\n\tday: CalendarDay,\n\tranges: ReadonlyArray<readonly [CalendarDay, CalendarDay]>\n): boolean => ranges.some(([from, to]) => day >= from && day <= to)\n\n/** The one row a total answers when no completed day holds a row of its kind. */\nexport const emptyAggregateRow = (plan: AggregatePlan): AggregateRow => ({\n\tvalue: null,\n\tparts: partsFrom(plan.kind.counted, () => 0),\n})\n\n/**\n * A read's summed rows as it answers them: a total its one row, anything grouped without its empty\n * rows, ordered and cut.\n */\nconst answered = (plan: AggregatePlan, rows: readonly AggregateRow[]): AggregateRow[] => {\n\tif (plan.group === null) {\n\t\treturn [rows[0] ?? emptyAggregateRow(plan)]\n\t}\n\tconst ranked = rows\n\t\t.filter((row) => countsSomething(row.parts))\n\t\t.sort(compareRanked<AggregateRow>(plan.read.order, (row) => row.day ?? 0))\n\treturn plan.read.limit === undefined ? ranked : ranked.slice(0, plan.read.limit)\n}\n\n/**\n * The rows a read answers out of the rows it matched, summed in memory: the reference answer every\n * database store must match.\n */\nexport const answerAggregateRead = (\n\tplan: AggregatePlan,\n\tmatched: ReadonlyArray<{ day: CalendarDay; value: string; value2: string; parts: MetricParts }>\n): AggregateRow[] => {\n\tconst { read } = plan\n\tconst values = read.values === undefined ? null : new Set(read.values)\n\tconst groups = new Map<\n\t\tstring,\n\t\t{ value: string | null; day?: CalendarDay; parts: MetricParts[] }\n\t>()\n\tfor (const row of matched) {\n\t\tconst value = plan.group === 'value' ? row.value : plan.group === 'value2' ? row.value2 : null\n\t\tif (value === OTHER_VALUE || (values && (value === null || !values.has(value)))) {\n\t\t\tcontinue\n\t\t}\n\t\tconst day = plan.group === 'day' ? row.day : undefined\n\t\tconst key = JSON.stringify([value, day ?? null])\n\t\tconst group = groups.get(key) ?? { value, ...(day === undefined ? {} : { day }), parts: [] }\n\t\tgroups.set(key, group)\n\t\tgroup.parts.push(row.parts)\n\t}\n\treturn answered(\n\t\tplan,\n\t\t[...groups.values()].map(\n\t\t\t({ parts, ...group }): AggregateRow => ({ ...group, parts: sumParts(parts) })\n\t\t)\n\t)\n}\n\n/**\n * What reads of one plan over disjoint sets of rows answered (none of them filled in or cut), as\n * one read would: summed by value and day, the empty groups dropped, ordered and cut.\n */\nexport const mergeAggregateRows = (\n\tplan: AggregatePlan,\n\trows: readonly AggregateRow[]\n): AggregateRow[] => {\n\tconst groups = new Map<string, AggregateRow>()\n\tfor (const row of rows) {\n\t\tconst key = JSON.stringify([row.value, row.day ?? null])\n\t\tconst held = groups.get(key)\n\t\tgroups.set(key, held ? { ...held, parts: addParts(held.parts, row.parts) } : row)\n\t}\n\treturn answered(plan, [...groups.values()])\n}\n\n/** The parts of a row summed by a database: null where no row it summed counted the part. */\nexport const partsOfSums = (part: (key: keyof MetricParts) => number | null): MetricParts => {\n\tconst parts = emptyParts()\n\tfor (const key of PART_KEYS) {\n\t\tparts[key] = part(key)\n\t}\n\treturn parts\n}\n\nconst dayMarker = async (state: StateStore, window: DayWindow): Promise<DayMarker | undefined> => {\n\tconst [marker] = await state.markers(window.scope, window.day, window.day)\n\treturn marker\n}\n\n/** The day's marker while `runId` holds its lease, or undefined when it holds none. */\nexport const heldMarker = async (\n\tstate: StateStore,\n\twindow: DayWindow,\n\trunId: string\n): Promise<DayMarker | undefined> => {\n\tconst marker = await dayMarker(state, window)\n\treturn marker?.leaseOwner === runId ? marker : undefined\n}\n\n/** A run that wrote nothing readers will see. */\nexport const refusedRun = (hits: number): AggregateResult => ({ completed: false, hits, rows: 0 })\n\n/**\n * Records made per slice of the event loop: a busy day's tens of thousands, each hashed for its id,\n * would otherwise hold the thread for most of a second.\n */\nconst RECORD_SLICE = 2_000\n\n/** Where a store keeps a day's rows, one generation beside another. */\nexport interface GenerationWriter {\n\t/** Every generation the day's rows carry. */\n\tgens(window: DayWindow): Promise<string[]>\n\t/** Writes records as rows of their own generation, never over another generation's. */\n\twrite(records: readonly AggregateRecord[]): Promise<void>\n\tdrop(window: DayWindow, gens: readonly string[]): Promise<void>\n}\n\n/**\n * Writes a day beside its readable rows, then completes the marker to switch to them. Deletes only\n * dead generations: \"all but mine\" from a run frozen past its lease would hit its successor's.\n */\nexport const writeBeside = async (args: {\n\tstate: StateStore\n\twriter: GenerationWriter\n\twindow: DayWindow\n\t/** `gen`: the marker's generation when the run began, which must still be the readable one. */\n\trun: { runId: string; status: CompletedDayStatus; gen: string | null }\n\trows: readonly DayRow[]\n\thits: number\n\tnow: () => Date\n\thooks?: AggregateHooks\n}): Promise<AggregateResult> => {\n\tconst { state, writer, window, run, hooks } = args\n\t// Renewed, never claimed: a lease a dirty mark revoked must stay lost to this run.\n\tif (!(await state.renew(dayKey(window.scope, window.day), run.runId, DAY_LEASE_MS))) {\n\t\treturn refusedRun(args.hits)\n\t}\n\tconst current = await dayMarker(state, window)\n\tif (current?.leaseOwner !== run.runId || current.gen !== run.gen) {\n\t\treturn refusedRun(args.hits)\n\t}\n\tconst leftovers = (await writer.gens(window)).filter((gen) => gen !== run.gen)\n\tconst gen = ulid(args.now())\n\tconst note = { scope: window.scope, day: window.day, gen }\n\tawait state.noteDrop(note)\n\tconst records = (\n\t\tawait mapInSlices(args.rows, RECORD_SLICE, (row) => recordOf(window, row, gen))\n\t).sort(byRecordId)\n\ttry {\n\t\tlet written = 0\n\t\tfor (const chunk of chunksOf(records, AGGREGATE_CHUNK)) {\n\t\t\tawait writer.write(chunk)\n\t\t\twritten += chunk.length\n\t\t\tawait hooks?.afterChunk?.(written)\n\t\t}\n\t\tconst marker = completedMarker(window, {\n\t\t\tstatus: run.status,\n\t\t\tgen,\n\t\t\thits: args.hits,\n\t\t\tat: args.now(),\n\t\t})\n\t\tif (!(await state.complete(marker, run.runId))) {\n\t\t\tawait writer.drop(window, [gen])\n\t\t\tawait state.clearDrop(note)\n\t\t\treturn refusedRun(args.hits)\n\t\t}\n\t} catch (err) {\n\t\t// A completion that failed in transit may still have landed, making its rows the readable ones.\n\t\tconst readable = await dayMarker(state, window).then(\n\t\t\t(after) => after?.gen === gen,\n\t\t\t() => true\n\t\t)\n\t\tif (!readable) {\n\t\t\tawait writer.drop(window, [gen]).then(\n\t\t\t\t() => state.clearDrop(note),\n\t\t\t\t() => undefined\n\t\t\t)\n\t\t}\n\t\tthrow err\n\t}\n\tawait hooks?.afterComplete?.()\n\tconst dead = [...(run.gen === null ? [] : [run.gen]), ...leftovers]\n\ttry {\n\t\tif (dead.length > 0) {\n\t\t\tawait writer.drop(window, dead)\n\t\t}\n\t\tawait state.clearDrop(note)\n\t} catch {\n\t\t// The day is complete either way; maintenance finishes the note a failed drop leaves.\n\t}\n\treturn { completed: true, hits: args.hits, rows: records.length }\n}\n\n/** A scope and a day as one key of the map of the generation each completed day reads. */\nexport const dayGenKey = (scope: string, day: CalendarDay): string => JSON.stringify([scope, day])\n\nconst STABLE_ATTEMPTS = 3\n\n/**\n * Reads days' rows between two reads of their generations, again when a day was swapped meanwhile,\n * as a store without transactions has no snapshot to read in.\n */\nexport const readStable = async <T>(args: {\n\tgens: () => Promise<ReadonlyMap<string, string>>\n\trows: (gens: ReadonlyMap<string, string>) => Promise<T>\n}): Promise<T> => {\n\tfor (let attempt = 1; ; attempt++) {\n\t\tconst before = await args.gens()\n\t\tconst result = await args.rows(before)\n\t\tconst after = await args.gens()\n\t\tif ([...before].every(([key, gen]) => after.get(key) === gen)) {\n\t\t\treturn result\n\t\t}\n\t\tif (attempt >= STABLE_ATTEMPTS) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: the days read were rewritten during each of ${STABLE_ATTEMPTS} reads; read them again`\n\t\t\t)\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;AAiDA,MAAM,kBAAkB;;AA2BxB,MAAa,cAAc,aAAa,OAAO,IAAI;;AAEnD,MAAa,eAAe,aAAa,QAAQ,IAAI;AAErD,MAAM,gBAAgB,OAAO,KAAK,kBAAkB,EAClD,OAAO,kBAAkB,EACzB,KACC,SAAuC;CACvC;CACA,MAAM;CACN,KAAK;CACL,QAAQ;EAAE,MAAM;EAAS,WAAW,mBAAmB;CAAK;CAC5D,SAAS;AACV,EACD;AAED,MAAM,YACL,MACA,eACmC;CACnC,KAAK;CACL;CACA,KAAK,cAAc,OAAO,SAAS;CACnC,QAAQ;EAAE,MAAM;EAAQ;CAAU;CAClC,SAAS;AACV;;;;;AAkDA,MAAa,kBAA4C;CA/CxD;EAAE,KAAK;EAAI,MAAM;EAAI,KAAK;EAAM,QAAQ,EAAE,MAAM,OAAO;EAAG,SAAS;CAAY;CAC/E,GAAG;CACH;EACC,KAAK;EACL,MAAM;EACN,KAAK;EACL,QAAQ;GAAE,MAAM;GAAO,OAAO;EAAO;EACrC,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,KAAK;EACL,QAAQ;GAAE,MAAM;GAAO,OAAO;EAAO;EACrC,SAAS;CACV;CACA;EACC,KAAK;EACL,MAAM;EACN,KAAK;EACL,QAAQ;GAAE,MAAM;GAAO,OAA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