@10x-media/analytics 0.1.0-beta.5 → 1.0.0-beta.6

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 (70) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -21
  3. package/dist/adapters/ga4/ga4.js +13 -0
  4. package/dist/adapters/ga4/ga4.js.map +1 -1
  5. package/dist/adapters/plausible/plausible.js +11 -0
  6. package/dist/adapters/plausible/plausible.js.map +1 -1
  7. package/dist/adapters/posthog/posthog.js +37 -3
  8. package/dist/adapters/posthog/posthog.js.map +1 -1
  9. package/dist/adapters/series.js +11 -1
  10. package/dist/adapters/series.js.map +1 -1
  11. package/dist/adapters/umami/umami.js +2 -0
  12. package/dist/adapters/umami/umami.js.map +1 -1
  13. package/dist/core/capabilities.d.ts +5 -1
  14. package/dist/core/capabilities.js +4 -0
  15. package/dist/core/capabilities.js.map +1 -1
  16. package/dist/core/contract.d.ts +7 -2
  17. package/dist/core/contract.js.map +1 -1
  18. package/dist/exports/rsc.d.ts +2 -2
  19. package/dist/exports/types.d.ts +2 -2
  20. package/dist/index.js +6 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/native/collections/rollups.js +15 -3
  23. package/dist/native/collections/rollups.js.map +1 -1
  24. package/dist/native/nativeAdapter.js +81 -2
  25. package/dist/native/nativeAdapter.js.map +1 -1
  26. package/dist/native/query/eventAgg.js +135 -0
  27. package/dist/native/query/eventAgg.js.map +1 -0
  28. package/dist/native/rollups/applyDistinctDeltas.js +1 -1
  29. package/dist/native/rollups/applyDistinctDeltas.js.map +1 -1
  30. package/dist/native/rollups/bumpRollup.js +2 -1
  31. package/dist/native/rollups/bumpRollup.js.map +1 -1
  32. package/dist/native/rollups/deltas.js +45 -8
  33. package/dist/native/rollups/deltas.js.map +1 -1
  34. package/dist/sync/collection.js +23 -7
  35. package/dist/sync/collection.js.map +1 -1
  36. package/dist/sync/syncTask.js +12 -4
  37. package/dist/sync/syncTask.js.map +1 -1
  38. package/dist/testing/memoryAdapter.js +7 -0
  39. package/dist/testing/memoryAdapter.js.map +1 -1
  40. package/dist/translations/ar.js +77 -0
  41. package/dist/translations/ar.js.map +1 -0
  42. package/dist/translations/es.js +77 -0
  43. package/dist/translations/es.js.map +1 -0
  44. package/dist/translations/fr.js +77 -0
  45. package/dist/translations/fr.js.map +1 -0
  46. package/dist/translations/id.js +77 -0
  47. package/dist/translations/id.js.map +1 -0
  48. package/dist/translations/index.d.ts +10 -1
  49. package/dist/translations/index.js +19 -1
  50. package/dist/translations/index.js.map +1 -1
  51. package/dist/translations/ko.js +77 -0
  52. package/dist/translations/ko.js.map +1 -0
  53. package/dist/translations/pt.js +77 -0
  54. package/dist/translations/pt.js.map +1 -0
  55. package/dist/translations/ru.js +77 -0
  56. package/dist/translations/ru.js.map +1 -0
  57. package/dist/translations/uk.js +77 -0
  58. package/dist/translations/uk.js.map +1 -0
  59. package/dist/translations/zh.js +77 -0
  60. package/dist/translations/zh.js.map +1 -0
  61. package/dist/widgets/readForWidget.d.ts +2 -1
  62. package/dist/widgets/readForWidget.js +10 -2
  63. package/dist/widgets/readForWidget.js.map +1 -1
  64. package/dist/widgets/readForWidgetBreakdown.d.ts +2 -1
  65. package/dist/widgets/readForWidgetBreakdown.js +7 -2
  66. package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
  67. package/dist/widgets/readForWidgetSeries.d.ts +2 -1
  68. package/dist/widgets/readForWidgetSeries.js +10 -2
  69. package/dist/widgets/readForWidgetSeries.js.map +1 -1
  70. package/package.json +6 -6
package/dist/index.js CHANGED
@@ -125,7 +125,12 @@ const analytics = definePlugin({
125
125
  tasks: [...config.jobs?.tasks ?? [], warmTask(resolved.cache.warm.cron, defaultLayout)]
126
126
  };
127
127
  if (resolved.sync.enabled) {
128
- config.collections = [...config.collections ?? [], syncCollection(resolved.sync.collectionSlug, resolved.sync.hidden)];
128
+ config.collections = [...config.collections ?? [], syncCollection(resolved.sync.collectionSlug, resolved.sync.hidden, {
129
+ scoped: resolved.scoped,
130
+ scopeField: "scope",
131
+ resolveScope,
132
+ platformRead: resolved.access.platformRead
133
+ })];
129
134
  config.jobs = {
130
135
  ...config.jobs,
131
136
  tasks: [...config.jobs?.tasks ?? [], syncTask({
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Config, definePlugin, type PayloadRequest } from 'payload'\n\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { makeSourcesHandler, SOURCES_PATH } from './plugin/sourcesEndpoint'\nimport { warmTask } from './plugin/warmTask'\nimport type { BuildSecretField } from './providers/collection'\nimport { buildProvidersCollection } from './providers/collection'\nimport {\n\tcollectionProvidersSource,\n\tcombineRegistries,\n\tcreateScopedRegistryResolver,\n} from './providers/resolver'\nimport { kvCacheStore } from './surfacing/cacheStore'\nimport { createEngine } from './surfacing/engine'\nimport { syncCollection } from './sync/collection'\nimport { syncTask } from './sync/syncTask'\nimport { DEFAULT_TIMEZONE, isValidTimeZone } from './timeframe/tz'\nimport { registerWidgets } from './widgets/registerWidgets'\n\ndeclare module 'payload' {\n\tinterface RegisteredPlugins {\n\t\t'@10x-media/analytics': AnalyticsPluginOptions\n\t}\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tif (options.disabled === true) {\n\t\t\treturn config\n\t\t}\n\t\tconst resolved = resolveOptions(options)\n\t\tconst defaultLayout = config.admin?.dashboard?.defaultLayout\n\t\tregisterTranslations(config, options.translations)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\tconst registryBase = { adapters: resolved.adapters, defaultId: resolved.defaultAdapter }\n\t\tlet resolveRegistry = staticRegistryResolver(registry)\n\t\tlet invalidateProviders = () => {}\n\t\tconst providersResolve = resolved.providers.resolve\n\t\tif (providersResolve) {\n\t\t\tresolveRegistry = async (args) =>\n\t\t\t\tcombineRegistries(\n\t\t\t\t\tregistryBase,\n\t\t\t\t\tawait providersResolve({ payload: args.payload, req: args.req, scope: args.scope })\n\t\t\t\t)\n\t\t} else if (resolved.providers.collection.enabled) {\n\t\t\tconst scoped = createScopedRegistryResolver({\n\t\t\t\tbase: registryBase,\n\t\t\t\tsource: collectionProvidersSource(\n\t\t\t\t\tresolved.providers.collection.slug,\n\t\t\t\t\tresolved.providers.collection.scopeField\n\t\t\t\t),\n\t\t\t})\n\t\t\tresolveRegistry = scoped.resolver\n\t\t\tinvalidateProviders = scoped.invalidate\n\t\t}\n\t\tconst resolveScope = async (req: PayloadRequest) => resolved.scopeResolver({ req })\n\t\tif (resolved.providers.collection.enabled) {\n\t\t\tconst { encryptedField, withEncryptedQueryRewrite } = await import(\n\t\t\t\t'@10x-media/fields/encrypted'\n\t\t\t).catch((err: unknown) => {\n\t\t\t\tif (isModuleNotFoundError(err)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'analytics: providers.collection requires @10x-media/fields (peer). Install it: pnpm add @10x-media/fields'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t})\n\t\t\tconst encryption = resolved.providers.collection.encryption\n\t\t\tconst buildSecret: BuildSecretField = (source) =>\n\t\t\t\tencryptedField(source, {\n\t\t\t\t\tprotection: 'writeOnly',\n\t\t\t\t\taadScope: '10x-analytics:providers',\n\t\t\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t\t\t...(encryption?.keys ? { keys: encryption.keys } : {}),\n\t\t\t\t})\n\t\t\tconst providersCollection = buildProvidersCollection({\n\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\taccess: resolved.providers.collection.access,\n\t\t\t\toverrides: resolved.providers.collection.overrides,\n\t\t\t\tonChange: () => invalidateProviders(),\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\tresolveScope,\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbuildSecret,\n\t\t\t})\n\t\t\t// Always wrap, even though a consumer's own @10x-media/fields plugin (if\n\t\t\t// registered) may wrap this collection again later: double application is\n\t\t\t// inert here (writeOnly forbids queryable, so there are no blind-index\n\t\t\t// markers to rewrite and the response strip is an idempotent delete),\n\t\t\t// while skipping would leak ciphertext whenever fields() runs before this\n\t\t\t// collection exists (e.g. an earlier plugin `order`).\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\twithEncryptedQueryRewrite(providersCollection),\n\t\t\t]\n\t\t}\n\t\tconst resolveTimezone = async (req: PayloadRequest, scope?: string | null): Promise<string> => {\n\t\t\tconst opt = resolved.reportingTimezone\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tz =\n\t\t\t\t\ttypeof opt === 'string'\n\t\t\t\t\t\t? opt\n\t\t\t\t\t\t: await opt({ req, scope: scope !== undefined ? scope : await resolveScope(req) })\n\t\t\t\treturn tz && isValidTimeZone(tz) ? tz : DEFAULT_TIMEZONE\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: reportingTimezone resolution failed, falling back to UTC: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t}\n\t\tfor (const adapter of resolved.adapters) {\n\t\t\tadapter.register?.(config, { scoped: resolved.scoped, resolveScope, resolveTimezone })\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function')\n\t\t) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: REALTIME_PATH, handler: makeRealtimeHandler() },\n\t\t\t]\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: DOCUMENT_PATH, handler: makeDocumentHandler() },\n\t\t\t]\n\t\t}\n\t\tconfig.endpoints = [\n\t\t\t...(config.endpoints ?? []),\n\t\t\t{ method: 'get', path: SOURCES_PATH, handler: makeSourcesHandler() },\n\t\t]\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider =\n\t\t\t\tregistry.isMultiProvider() ||\n\t\t\t\tresolved.providers.collection.enabled ||\n\t\t\t\tBoolean(resolved.providers.resolve)\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tdisabled: resolved.widgets.disabled,\n\t\t\t\tregister: resolved.widgets.register,\n\t\t\t\tlocalizeText: resolved.widgets.localizeText,\n\t\t\t\tdefaultId: resolved.defaultAdapter,\n\t\t\t})\n\t\t}\n\t\tif (resolved.cache.warm.enabled) {\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), warmTask(resolved.cache.warm.cron, defaultLayout)],\n\t\t\t}\n\t\t}\n\t\tif (resolved.sync.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tsyncCollection(resolved.sync.collectionSlug, resolved.sync.hidden),\n\t\t\t]\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tcron: resolved.sync.cron,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collectionSlug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// The runtime is installed before the app's own onInit runs so consumer init code\n\t\t// (seeding, cache warming, sync passes) can already read through the plugin.\n\t\tconfig.onInit = async (payload) => {\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await import('@10x-media/fields/encrypted')\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst engine = createEngine({\n\t\t\t\tstore: kvCacheStore(payload.kv),\n\t\t\t\tqueue: { concurrency: 4 },\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t})\n\t\t\tsetRuntime(payload, {\n\t\t\t\tregistry,\n\t\t\t\tresolveRegistry,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t\t\tconfigAdapterIds: new Set(resolved.adapters.map((a) => a.id)),\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbindings: resolved.bindings,\n\t\t\t\tengine,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\tcomparison: resolved.widgets.comparison,\n\t\t\t})\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport { PLATFORM_SCOPE } from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatOptions,\n\tAnalyticsStatRowOptions,\n\tAnalyticsTabOptions,\n} from './fields/factories'\nexport {\n\tanalyticsFields,\n\tanalyticsStat,\n\tanalyticsStatRow,\n\tanalyticsTab,\n\tanalyticsTabsField,\n} from './fields/factories'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,YAAY,aAAqC;CAC7D,MAAM;CACN,QAAQ,OAAO,EAAE,QAAQ,SAAS,UAAU,GAAG,cAA+B;EAC7E,IAAI,QAAQ,aAAa,MACxB,OAAO;EAER,MAAM,WAAW,eAAe,OAAO;EACvC,MAAM,gBAAgB,OAAO,OAAO,WAAW;EAC/C,qBAAqB,QAAQ,QAAQ,YAAY;EACjD,MAAM,WAAW,eAAe,SAAS,UAAU,SAAS,cAAc;EAC1E,MAAM,eAAe;GAAE,UAAU,SAAS;GAAU,WAAW,SAAS;EAAe;EACvF,IAAI,kBAAkB,uBAAuB,QAAQ;EACrD,IAAI,4BAA4B,CAAC;EACjC,MAAM,mBAAmB,SAAS,UAAU;EAC5C,IAAI,kBACH,kBAAkB,OAAO,SACxB,kBACC,cACA,MAAM,iBAAiB;GAAE,SAAS,KAAK;GAAS,KAAK,KAAK;GAAK,OAAO,KAAK;EAAM,CAAC,CACnF;OACK,IAAI,SAAS,UAAU,WAAW,SAAS;GACjD,MAAM,SAAS,6BAA6B;IAC3C,MAAM;IACN,QAAQ,0BACP,SAAS,UAAU,WAAW,MAC9B,SAAS,UAAU,WAAW,UAC/B;GACD,CAAC;GACD,kBAAkB,OAAO;GACzB,sBAAsB,OAAO;EAC9B;EACA,MAAM,eAAe,OAAO,QAAwB,SAAS,cAAc,EAAE,IAAI,CAAC;EAClF,IAA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B,CAAC,CACF;GACD;EACD;EACA,MAAM,aAAa,OAAO;EAG1B,OAAO,SAAS,OAAO,YAAY;GAClC,IAAI,SAAS,UAAU,WAAW,SAAS;IAC1C,MAAM,EAAE,0BAA0B,MAAM,OAAO;IAC/C,MAAM,sBAAsB,SAAS,SAAS,UAAU,WAAW,YAAY,IAAI;GACpF;GACA,MAAM,SAAS,aAAa;IAC3B,OAAO,aAAa,QAAQ,EAAE;IAC9B,OAAO,EAAE,aAAa,EAAE;IACxB,KAAK,SAAS,MAAM;GACrB,CAAC;GACD,WAAW,SAAS;IACnB;IACA;IACA;IACA;IACA,mBAAmB,SAAS;IAC5B,kBAAkB,IAAI,IAAI,SAAS,SAAS,KAAK,MAAM,EAAE,EAAE,CAAC;IAC5D,cAAc,SAAS,OAAO;IAC9B,UAAU,SAAS;IACnB;IACA,KAAK,SAAS,MAAM;IACpB,YAAY,SAAS,QAAQ;GAC9B,CAAC;GACD,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Config, definePlugin, type PayloadRequest } from 'payload'\n\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { makeSourcesHandler, SOURCES_PATH } from './plugin/sourcesEndpoint'\nimport { warmTask } from './plugin/warmTask'\nimport type { BuildSecretField } from './providers/collection'\nimport { buildProvidersCollection } from './providers/collection'\nimport {\n\tcollectionProvidersSource,\n\tcombineRegistries,\n\tcreateScopedRegistryResolver,\n} from './providers/resolver'\nimport { kvCacheStore } from './surfacing/cacheStore'\nimport { createEngine } from './surfacing/engine'\nimport { syncCollection } from './sync/collection'\nimport { syncTask } from './sync/syncTask'\nimport { DEFAULT_TIMEZONE, isValidTimeZone } from './timeframe/tz'\nimport { registerWidgets } from './widgets/registerWidgets'\n\ndeclare module 'payload' {\n\tinterface RegisteredPlugins {\n\t\t'@10x-media/analytics': AnalyticsPluginOptions\n\t}\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tif (options.disabled === true) {\n\t\t\treturn config\n\t\t}\n\t\tconst resolved = resolveOptions(options)\n\t\tconst defaultLayout = config.admin?.dashboard?.defaultLayout\n\t\tregisterTranslations(config, options.translations)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\tconst registryBase = { adapters: resolved.adapters, defaultId: resolved.defaultAdapter }\n\t\tlet resolveRegistry = staticRegistryResolver(registry)\n\t\tlet invalidateProviders = () => {}\n\t\tconst providersResolve = resolved.providers.resolve\n\t\tif (providersResolve) {\n\t\t\tresolveRegistry = async (args) =>\n\t\t\t\tcombineRegistries(\n\t\t\t\t\tregistryBase,\n\t\t\t\t\tawait providersResolve({ payload: args.payload, req: args.req, scope: args.scope })\n\t\t\t\t)\n\t\t} else if (resolved.providers.collection.enabled) {\n\t\t\tconst scoped = createScopedRegistryResolver({\n\t\t\t\tbase: registryBase,\n\t\t\t\tsource: collectionProvidersSource(\n\t\t\t\t\tresolved.providers.collection.slug,\n\t\t\t\t\tresolved.providers.collection.scopeField\n\t\t\t\t),\n\t\t\t})\n\t\t\tresolveRegistry = scoped.resolver\n\t\t\tinvalidateProviders = scoped.invalidate\n\t\t}\n\t\tconst resolveScope = async (req: PayloadRequest) => resolved.scopeResolver({ req })\n\t\tif (resolved.providers.collection.enabled) {\n\t\t\tconst { encryptedField, withEncryptedQueryRewrite } = await import(\n\t\t\t\t'@10x-media/fields/encrypted'\n\t\t\t).catch((err: unknown) => {\n\t\t\t\tif (isModuleNotFoundError(err)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t'analytics: providers.collection requires @10x-media/fields (peer). Install it: pnpm add @10x-media/fields'\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tthrow err\n\t\t\t})\n\t\t\tconst encryption = resolved.providers.collection.encryption\n\t\t\tconst buildSecret: BuildSecretField = (source) =>\n\t\t\t\tencryptedField(source, {\n\t\t\t\t\tprotection: 'writeOnly',\n\t\t\t\t\taadScope: '10x-analytics:providers',\n\t\t\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t\t\t...(encryption?.keys ? { keys: encryption.keys } : {}),\n\t\t\t\t})\n\t\t\tconst providersCollection = buildProvidersCollection({\n\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\taccess: resolved.providers.collection.access,\n\t\t\t\toverrides: resolved.providers.collection.overrides,\n\t\t\t\tonChange: () => invalidateProviders(),\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\tresolveScope,\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbuildSecret,\n\t\t\t})\n\t\t\t// Always wrap, even though a consumer's own @10x-media/fields plugin (if\n\t\t\t// registered) may wrap this collection again later: double application is\n\t\t\t// inert here (writeOnly forbids queryable, so there are no blind-index\n\t\t\t// markers to rewrite and the response strip is an idempotent delete),\n\t\t\t// while skipping would leak ciphertext whenever fields() runs before this\n\t\t\t// collection exists (e.g. an earlier plugin `order`).\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\twithEncryptedQueryRewrite(providersCollection),\n\t\t\t]\n\t\t}\n\t\tconst resolveTimezone = async (req: PayloadRequest, scope?: string | null): Promise<string> => {\n\t\t\tconst opt = resolved.reportingTimezone\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst tz =\n\t\t\t\t\ttypeof opt === 'string'\n\t\t\t\t\t\t? opt\n\t\t\t\t\t\t: await opt({ req, scope: scope !== undefined ? scope : await resolveScope(req) })\n\t\t\t\treturn tz && isValidTimeZone(tz) ? tz : DEFAULT_TIMEZONE\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: reportingTimezone resolution failed, falling back to UTC: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn DEFAULT_TIMEZONE\n\t\t\t}\n\t\t}\n\t\tfor (const adapter of resolved.adapters) {\n\t\t\tadapter.register?.(config, { scoped: resolved.scoped, resolveScope, resolveTimezone })\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function')\n\t\t) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: REALTIME_PATH, handler: makeRealtimeHandler() },\n\t\t\t]\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'get', path: DOCUMENT_PATH, handler: makeDocumentHandler() },\n\t\t\t]\n\t\t}\n\t\tconfig.endpoints = [\n\t\t\t...(config.endpoints ?? []),\n\t\t\t{ method: 'get', path: SOURCES_PATH, handler: makeSourcesHandler() },\n\t\t]\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider =\n\t\t\t\tregistry.isMultiProvider() ||\n\t\t\t\tresolved.providers.collection.enabled ||\n\t\t\t\tBoolean(resolved.providers.resolve)\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tdisabled: resolved.widgets.disabled,\n\t\t\t\tregister: resolved.widgets.register,\n\t\t\t\tlocalizeText: resolved.widgets.localizeText,\n\t\t\t\tdefaultId: resolved.defaultAdapter,\n\t\t\t})\n\t\t}\n\t\tif (resolved.cache.warm.enabled) {\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), warmTask(resolved.cache.warm.cron, defaultLayout)],\n\t\t\t}\n\t\t}\n\t\tif (resolved.sync.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tsyncCollection(resolved.sync.collectionSlug, resolved.sync.hidden, {\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: 'scope',\n\t\t\t\t\tresolveScope,\n\t\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\t}),\n\t\t\t]\n\t\t\tconfig.jobs = {\n\t\t\t\t...config.jobs,\n\t\t\t\ttasks: [\n\t\t\t\t\t...(config.jobs?.tasks ?? []),\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tcron: resolved.sync.cron,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collectionSlug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// The runtime is installed before the app's own onInit runs so consumer init code\n\t\t// (seeding, cache warming, sync passes) can already read through the plugin.\n\t\tconfig.onInit = async (payload) => {\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await import('@10x-media/fields/encrypted')\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst engine = createEngine({\n\t\t\t\tstore: kvCacheStore(payload.kv),\n\t\t\t\tqueue: { concurrency: 4 },\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t})\n\t\t\tsetRuntime(payload, {\n\t\t\t\tregistry,\n\t\t\t\tresolveRegistry,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t\t\tconfigAdapterIds: new Set(resolved.adapters.map((a) => a.id)),\n\t\t\t\tplatformRead: resolved.access.platformRead,\n\t\t\t\tbindings: resolved.bindings,\n\t\t\t\tengine,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\tcomparison: resolved.widgets.comparison,\n\t\t\t})\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport { PLATFORM_SCOPE } from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatOptions,\n\tAnalyticsStatRowOptions,\n\tAnalyticsTabOptions,\n} from './fields/factories'\nexport {\n\tanalyticsFields,\n\tanalyticsStat,\n\tanalyticsStatRow,\n\tanalyticsTab,\n\tanalyticsTabsField,\n} from './fields/factories'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,YAAY,aAAqC;CAC7D,MAAM;CACN,QAAQ,OAAO,EAAE,QAAQ,SAAS,UAAU,GAAG,cAA+B;EAC7E,IAAI,QAAQ,aAAa,MACxB,OAAO;EAER,MAAM,WAAW,eAAe,OAAO;EACvC,MAAM,gBAAgB,OAAO,OAAO,WAAW;EAC/C,qBAAqB,QAAQ,QAAQ,YAAY;EACjD,MAAM,WAAW,eAAe,SAAS,UAAU,SAAS,cAAc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,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC"}
@@ -1,9 +1,13 @@
1
1
  //#region src/native/collections/rollups.ts
2
2
  const ROLLUPS_SLUG = "analytics-rollups";
3
3
  /**
4
- * Scoped installs add a required scope key ('' = the null scope) to every rollup
4
+ * `hostname` ('' = the hostname-less family) is part of the unique bucket on every
5
+ * native install: unfiltered reads hit the '' family and hostname-scoped reads hit the
6
+ * exact-hostname family, both kept per-bucket exact by dual emission in computeRollupDeltas.
7
+ * Scoped installs add a further required scope key ('' = the null scope) to every rollup
5
8
  * row and to the unique bucket index, so each scope accumulates its own buckets.
6
- * Existing native installs enabling scope need a migration for the new column.
9
+ * Existing native installs need a migration for the new hostname column (and, if
10
+ * enabling scope, the scope column too).
7
11
  */
8
12
  const rollupsCollection = (scoped = false) => ({
9
13
  slug: ROLLUPS_SLUG,
@@ -44,6 +48,12 @@ const rollupsCollection = (scoped = false) => ({
44
48
  required: true,
45
49
  defaultValue: ""
46
50
  },
51
+ {
52
+ name: "hostname",
53
+ type: "text",
54
+ required: true,
55
+ defaultValue: ""
56
+ },
47
57
  ...scoped ? [{
48
58
  name: "scope",
49
59
  type: "text",
@@ -95,6 +105,7 @@ const rollupsCollection = (scoped = false) => ({
95
105
  "path",
96
106
  "dimension",
97
107
  "dimvalue",
108
+ "hostname",
98
109
  "scope"
99
110
  ],
100
111
  unique: true
@@ -104,7 +115,8 @@ const rollupsCollection = (scoped = false) => ({
104
115
  "period",
105
116
  "path",
106
117
  "dimension",
107
- "dimvalue"
118
+ "dimvalue",
119
+ "hostname"
108
120
  ],
109
121
  unique: true
110
122
  }]
@@ -1 +1 @@
1
- {"version":3,"file":"rollups.js","names":[],"sources":["../../../src/native/collections/rollups.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const ROLLUPS_SLUG = 'analytics-rollups'\n\n/**\n * Scoped installs add a required scope key ('' = the null scope) to every rollup\n * row and to the unique bucket index, so each scope accumulates its own buckets.\n * Existing native installs enabling scope need a migration for the new column.\n */\nexport const rollupsCollection = (scoped = false): CollectionConfig => ({\n\tslug: ROLLUPS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => true, delete: () => true },\n\tfields: [\n\t\t{ name: 'granularity', type: 'text', required: true },\n\t\t{ name: 'period', type: 'date', required: true, index: true },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'dimension', type: 'text', required: true, defaultValue: '' },\n\t\t{ name: 'dimvalue', type: 'text', required: true, defaultValue: '' },\n\t\t...(scoped\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'scope',\n\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\tdefaultValue: '',\n\t\t\t\t\t\tindex: true,\n\t\t\t\t\t} satisfies Field,\n\t\t\t\t]\n\t\t\t: []),\n\t\t{ name: 'pageviews', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'events', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'durationMs', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'visitors', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'sessions', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'samples', type: 'number', required: true, defaultValue: 0 },\n\t],\n\tindexes: [\n\t\tscoped\n\t\t\t? {\n\t\t\t\t\tfields: ['granularity', 'period', 'path', 'dimension', 'dimvalue', 'scope'],\n\t\t\t\t\tunique: true,\n\t\t\t\t}\n\t\t\t: { fields: ['granularity', 'period', 'path', 'dimension', 'dimvalue'], unique: true },\n\t],\n})\n"],"mappings":";AAEA,MAAa,eAAe;;;;;;AAO5B,MAAa,qBAAqB,SAAS,WAA6B;CACvE,MAAM;CACN,OAAO,EAAE,QAAQ,KAAK;CACtB,QAAQ;EAAE,YAAY;EAAO,cAAc;EAAM,cAAc;EAAM,cAAc;CAAK;CACxF,QAAQ;EACP;GAAE,MAAM;GAAe,MAAM;GAAQ,UAAU;EAAK;EACpD;GAAE,MAAM;GAAU,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC5D;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACpE;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACnE,GAAI,SACD,CACA;GACC,MAAM;GACN,MAAM;GACN,UAAU;GACV,cAAc;GACd,OAAO;EACR,CACD,IACC,CAAC;EACJ;GAAE,MAAM;GAAa,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACrE;GAAE,MAAM;GAAU,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EAClE;GAAE,MAAM;GAAc,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACtE;GAAE,MAAM;GAAY,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACpE;GAAE,MAAM;GAAY,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACpE;GAAE,MAAM;GAAW,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;CACpE;CACA,SAAS,CACR,SACG;EACA,QAAQ;GAAC;GAAe;GAAU;GAAQ;GAAa;GAAY;EAAO;EAC1E,QAAQ;CACT,IACC;EAAE,QAAQ;GAAC;GAAe;GAAU;GAAQ;GAAa;EAAU;EAAG,QAAQ;CAAK,CACvF;AACD"}
1
+ {"version":3,"file":"rollups.js","names":[],"sources":["../../../src/native/collections/rollups.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const ROLLUPS_SLUG = 'analytics-rollups'\n\n/**\n * `hostname` ('' = the hostname-less family) is part of the unique bucket on every\n * native install: unfiltered reads hit the '' family and hostname-scoped reads hit the\n * exact-hostname family, both kept per-bucket exact by dual emission in computeRollupDeltas.\n * Scoped installs add a further required scope key ('' = the null scope) to every rollup\n * row and to the unique bucket index, so each scope accumulates its own buckets.\n * Existing native installs need a migration for the new hostname column (and, if\n * enabling scope, the scope column too).\n */\nexport const rollupsCollection = (scoped = false): CollectionConfig => ({\n\tslug: ROLLUPS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => true, delete: () => true },\n\tfields: [\n\t\t{ name: 'granularity', type: 'text', required: true },\n\t\t{ name: 'period', type: 'date', required: true, index: true },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'dimension', type: 'text', required: true, defaultValue: '' },\n\t\t{ name: 'dimvalue', type: 'text', required: true, defaultValue: '' },\n\t\t{ name: 'hostname', type: 'text', required: true, defaultValue: '' },\n\t\t...(scoped\n\t\t\t? [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'scope',\n\t\t\t\t\t\ttype: 'text',\n\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\tdefaultValue: '',\n\t\t\t\t\t\tindex: true,\n\t\t\t\t\t} satisfies Field,\n\t\t\t\t]\n\t\t\t: []),\n\t\t{ name: 'pageviews', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'events', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'durationMs', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'visitors', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'sessions', type: 'number', required: true, defaultValue: 0 },\n\t\t{ name: 'samples', type: 'number', required: true, defaultValue: 0 },\n\t],\n\tindexes: [\n\t\tscoped\n\t\t\t? {\n\t\t\t\t\tfields: ['granularity', 'period', 'path', 'dimension', 'dimvalue', 'hostname', 'scope'],\n\t\t\t\t\tunique: true,\n\t\t\t\t}\n\t\t\t: {\n\t\t\t\t\tfields: ['granularity', 'period', 'path', 'dimension', 'dimvalue', 'hostname'],\n\t\t\t\t\tunique: true,\n\t\t\t\t},\n\t],\n})\n"],"mappings":";AAEA,MAAa,eAAe;;;;;;;;;;AAW5B,MAAa,qBAAqB,SAAS,WAA6B;CACvE,MAAM;CACN,OAAO,EAAE,QAAQ,KAAK;CACtB,QAAQ;EAAE,YAAY;EAAO,cAAc;EAAM,cAAc;EAAM,cAAc;CAAK;CACxF,QAAQ;EACP;GAAE,MAAM;GAAe,MAAM;GAAQ,UAAU;EAAK;EACpD;GAAE,MAAM;GAAU,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC5D;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACpE;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACnE;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;GAAM,cAAc;EAAG;EACnE,GAAI,SACD,CACA;GACC,MAAM;GACN,MAAM;GACN,UAAU;GACV,cAAc;GACd,OAAO;EACR,CACD,IACC,CAAC;EACJ;GAAE,MAAM;GAAa,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACrE;GAAE,MAAM;GAAU,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EAClE;GAAE,MAAM;GAAc,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACtE;GAAE,MAAM;GAAY,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACpE;GAAE,MAAM;GAAY,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;EACpE;GAAE,MAAM;GAAW,MAAM;GAAU,UAAU;GAAM,cAAc;EAAE;CACpE;CACA,SAAS,CACR,SACG;EACA,QAAQ;GAAC;GAAe;GAAU;GAAQ;GAAa;GAAY;GAAY;EAAO;EACtF,QAAQ;CACT,IACC;EACA,QAAQ;GAAC;GAAe;GAAU;GAAQ;GAAa;GAAY;EAAU;EAC7E,QAAQ;CACT,CACH;AACD"}
@@ -7,6 +7,7 @@ import { seenCollection } from "./collections/seen.js";
7
7
  import { flushBatch } from "./ingest/flushBatch.js";
8
8
  import { makeIngestHandler } from "./ingest/endpoint.js";
9
9
  import { createWriteBuffer } from "./ingest/writeBuffer.js";
10
+ import { aggregateEvents, filtersToWhere } from "./query/eventAgg.js";
10
11
  import { buildRealtime } from "./realtime/buildRealtime.js";
11
12
  import { pruneEventsTask } from "./retention/pruneTask.js";
12
13
  import { add, emptyAcc, selectMetrics, seriesFromRollups } from "./rollupAcc.js";
@@ -22,7 +23,8 @@ const dimensions = new Set([
22
23
  "page",
23
24
  "country",
24
25
  "source",
25
- "device"
26
+ "device",
27
+ "event"
26
28
  ]);
27
29
  const REALTIME_EVENT_LIMIT = 5e4;
28
30
  const baseCapabilities = {
@@ -30,10 +32,20 @@ const baseCapabilities = {
30
32
  realtime: true,
31
33
  realtimeWindowMinutes: 60,
32
34
  comparison: true,
33
- minGranularity: "day",
35
+ minGranularity: "hour",
34
36
  maxLookbackDays: null,
35
37
  metrics,
36
38
  dimensions,
39
+ filters: new Set([
40
+ "page",
41
+ "country",
42
+ "region",
43
+ "city",
44
+ "device",
45
+ "source",
46
+ "event"
47
+ ]),
48
+ filterOperators: new Set(["eq", "contains"]),
37
49
  batchPageReport: true,
38
50
  rateLimit: null,
39
51
  recommendedTtl: {
@@ -41,6 +53,66 @@ const baseCapabilities = {
41
53
  aggregate: 300
42
54
  }
43
55
  };
56
+ const DAY_MS = 864e5;
57
+ /**
58
+ * Filtered/hour-granularity reads bypass the day-bucketed rollups and aggregate raw
59
+ * events directly, under the same hard cap as `realtime()`. `retentionDays` clamps how
60
+ * far back the read can reach when it would otherwise ask for events the prune task has
61
+ * already deleted (or will delete before they're queryable).
62
+ */
63
+ async function queryEvents(payload, q, ctx) {
64
+ const fetchedAt = q.dateRange.end.toISOString();
65
+ let start = q.dateRange.start;
66
+ let clamped = false;
67
+ if (ctx.retentionDays && ctx.retentionDays > 0) {
68
+ const floor = /* @__PURE__ */ new Date(Date.now() - ctx.retentionDays * DAY_MS);
69
+ if (start < floor) {
70
+ start = floor;
71
+ clamped = true;
72
+ }
73
+ }
74
+ const baseWhere = {
75
+ timestamp: {
76
+ greater_than_equal: start.toISOString(),
77
+ less_than_equal: q.dateRange.end.toISOString()
78
+ },
79
+ ...q.hostname ? { hostname: { equals: q.hostname } } : {},
80
+ ...q.path ? { path: { equals: q.path } } : {},
81
+ ...ctx.scopeWhere(q)
82
+ };
83
+ const filterWhere = filtersToWhere(q.filters ?? []);
84
+ const where = Object.keys(filterWhere).length > 0 ? { and: [baseWhere, filterWhere] } : baseWhere;
85
+ const { docs } = await payload.find({
86
+ collection: EVENTS_SLUG,
87
+ where,
88
+ limit: REALTIME_EVENT_LIMIT,
89
+ pagination: false,
90
+ depth: 0,
91
+ sort: "-timestamp"
92
+ });
93
+ const events = docs;
94
+ const dim = q.dimensions?.find((d) => dimensions.has(d));
95
+ const granularity = q.granularity === "hour" || q.granularity === "day" ? q.granularity : void 0;
96
+ const { rows, totals } = aggregateEvents(events, {
97
+ metrics: q.metrics,
98
+ dimension: dim,
99
+ granularity,
100
+ timezone: q.timezone,
101
+ order: q.order,
102
+ limit: q.limit
103
+ });
104
+ const meta = {
105
+ provider: "native",
106
+ fetchedAt
107
+ };
108
+ if (clamped) meta.clamped = true;
109
+ if (events.length >= REALTIME_EVENT_LIMIT) meta.sampled = true;
110
+ return {
111
+ rows,
112
+ totals,
113
+ meta
114
+ };
115
+ }
44
116
  function native(options = {}) {
45
117
  const geoResolver = options.geoResolver ?? (options.geoDbPath ? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath })) : platformHeaderResolver);
46
118
  const capabilities = { ...baseCapabilities };
@@ -106,6 +178,10 @@ function native(options = {}) {
106
178
  },
107
179
  async query(q) {
108
180
  if (!payloadRef) throw new Error("analytics: native adapter queried before init");
181
+ if (q.filters && q.filters.length > 0 || q.granularity === "hour") return queryEvents(payloadRef, q, {
182
+ retentionDays: options.retentionDays,
183
+ scopeWhere
184
+ });
109
185
  const fetchedAt = q.dateRange.end.toISOString();
110
186
  const periodWhere = {
111
187
  greater_than_equal: q.dateRange.start.toISOString(),
@@ -117,6 +193,7 @@ function native(options = {}) {
117
193
  granularity: { equals: "day" },
118
194
  dimension: { equals: "" },
119
195
  path: { equals: totalsPath },
196
+ hostname: { equals: q.hostname ?? "" },
120
197
  period: periodWhere,
121
198
  ...scopeWhere(q)
122
199
  });
@@ -145,12 +222,14 @@ function native(options = {}) {
145
222
  granularity: { equals: "day" },
146
223
  dimension: { equals: "" },
147
224
  path: { not_equals: "" },
225
+ hostname: { equals: q.hostname ?? "" },
148
226
  period: periodWhere,
149
227
  ...scopeWhere(q)
150
228
  } : {
151
229
  granularity: { equals: "day" },
152
230
  dimension: { equals: dim },
153
231
  path: { equals: "" },
232
+ hostname: { equals: q.hostname ?? "" },
154
233
  period: periodWhere,
155
234
  ...scopeWhere(q)
156
235
  };
@@ -1 +1 @@
1
- {"version":3,"file":"nativeAdapter.js","names":["events"],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import type { Config, Payload } from 'payload'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport { EVENTS_SLUG, eventsCollection } from './collections/events'\nimport { ROLLUPS_SLUG, rollupsCollection } from './collections/rollups'\nimport { seenCollection } from './collections/seen'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { makeIngestHandler } from './ingest/endpoint'\nimport { flushBatch } from './ingest/flushBatch'\nimport type { StoredEvent } from './ingest/normalizeEvent'\nimport { createWriteBuffer, type WriteBuffer } from './ingest/writeBuffer'\nimport { buildRealtime, type RealtimeEvent } from './realtime/buildRealtime'\nimport { pruneEventsTask } from './retention/pruneTask'\nimport {\n\ttype Acc,\n\tadd,\n\temptyAcc,\n\ttype RollupDoc,\n\tselectMetrics,\n\tseriesFromRollups,\n} from './rollupAcc'\n\nexport interface NativeOptions {\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\tingestPath?: string\n\tretentionDays?: number\n\t/** Opt-in in-process write batching. `true` uses defaults (maxSize 50, maxAgeMs 2000). */\n\tbuffer?: boolean | { maxSize?: number; maxAgeMs?: number }\n}\n\nexport type NativeAdapter = AnalyticsAdapter & { flush: () => Promise<void> }\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'events',\n\t'avgDuration',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set(['page', 'country', 'source', 'device'])\n\nconst REALTIME_EVENT_LIMIT = 50_000\n\nconst baseCapabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 60,\n\tcomparison: true,\n\tminGranularity: 'day',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 10, aggregate: 300 },\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tconst geoResolver =\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\t// Per-instance copy: register() flips scopedQueries when the install is scoped.\n\tconst capabilities: AnalyticsCapabilities = { ...baseCapabilities }\n\tlet payloadRef: Payload | null = null\n\tlet buffer: WriteBuffer<StoredEvent> | null = null\n\tlet scoped = false\n\n\tconst scopeWhere = (q: AnalyticsQuery): Record<string, unknown> =>\n\t\tscoped && q.scope !== undefined ? { scope: { equals: q.scope } } : {}\n\n\tconst readRollups = async (\n\t\tpayload: Payload,\n\t\twhere: Record<string, unknown>\n\t): Promise<RollupDoc[]> => {\n\t\tconst { docs } = await payload.find({\n\t\t\tcollection: ROLLUPS_SLUG as never,\n\t\t\twhere: where as never,\n\t\t\tlimit: 100_000,\n\t\t\tpagination: false,\n\t\t})\n\t\treturn docs as unknown as RollupDoc[]\n\t}\n\n\treturn {\n\t\tid: 'native',\n\t\tlabel: 'Native (Payload)',\n\t\tcapabilities,\n\t\tisConfigured: () => true,\n\t\tflush: () => buffer?.flush() ?? Promise.resolve(),\n\t\tregister(config: Config, context) {\n\t\t\tscoped = context?.scoped ?? false\n\t\t\tif (scoped) {\n\t\t\t\tcapabilities.scopedQueries = true\n\t\t\t}\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\teventsCollection(scoped),\n\t\t\t\trollupsCollection(scoped),\n\t\t\t\tseenCollection(),\n\t\t\t]\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{\n\t\t\t\t\tmethod: 'post',\n\t\t\t\t\tpath: options.ingestPath ?? '/analytics/ingest',\n\t\t\t\t\thandler: makeIngestHandler(geoResolver, () => buffer, {\n\t\t\t\t\t\tscope: scoped ? context?.resolveScope : undefined,\n\t\t\t\t\t\ttimezone: context?.resolveTimezone,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t]\n\t\t\tif (options.retentionDays && options.retentionDays > 0) {\n\t\t\t\tconfig.jobs = {\n\t\t\t\t\t...config.jobs,\n\t\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), pruneEventsTask(options.retentionDays)],\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevOnInit = config.onInit\n\t\t\t// payloadRef is set before the app's own onInit so consumer init code can\n\t\t\t// already query the native adapter.\n\t\t\tconfig.onInit = async (p) => {\n\t\t\t\tpayloadRef = p\n\t\t\t\tif (options.buffer) {\n\t\t\t\t\tconst cfg = options.buffer === true ? {} : options.buffer\n\t\t\t\t\tbuffer = createWriteBuffer<StoredEvent>({\n\t\t\t\t\t\tmaxSize: cfg.maxSize ?? 50,\n\t\t\t\t\t\tmaxAgeMs: cfg.maxAgeMs ?? 2000,\n\t\t\t\t\t\tonFlush: (batch) => flushBatch(p, batch),\n\t\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\t\tp.logger.error({ err: error, msg: 'analytics: write buffer flush failed' })\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tawait prevOnInit?.(p)\n\t\t\t}\n\t\t},\n\t\tasync query(q: AnalyticsQuery): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst periodWhere = {\n\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t}\n\t\t\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\n\t\t\t// Distinct metrics (visitors/sessions) must not be summed across breakdown rows.\n\t\t\t// Totals always come from the non-dimensioned aggregate row. A dimensioned query\n\t\t\t// reports site-wide totals (path=''), a plain query uses the path-scoped row.\n\t\t\tconst totalsPath = dim ? '' : (q.path ?? '')\n\t\t\tconst totalsDocs = await readRollups(payloadRef, {\n\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\tdimension: { equals: '' },\n\t\t\t\tpath: { equals: totalsPath },\n\t\t\t\tperiod: periodWhere,\n\t\t\t\t...scopeWhere(q),\n\t\t\t})\n\t\t\tconst totalsAcc = emptyAcc()\n\t\t\tfor (const d of totalsDocs) {\n\t\t\t\tadd(totalsAcc, d)\n\t\t\t}\n\t\t\tconst totals = selectMetrics(totalsAcc, q.metrics)\n\n\t\t\tif (!dim) {\n\t\t\t\tif (q.granularity === 'day') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\trows: seriesFromRollups(totalsDocs, q.metrics, q.timezone),\n\t\t\t\t\t\ttotals,\n\t\t\t\t\t\tmeta: { provider: 'native', fetchedAt },\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'native', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst breakdownWhere =\n\t\t\t\tdim === 'page'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: '' },\n\t\t\t\t\t\t\tpath: { not_equals: '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: dim },\n\t\t\t\t\t\t\tpath: { equals: '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\tconst groups = new Map<string, Acc>()\n\t\t\tfor (const d of await readRollups(payloadRef, breakdownWhere)) {\n\t\t\t\tconst value = dim === 'page' ? d.path : d.dimvalue\n\t\t\t\tlet acc = groups.get(value)\n\t\t\t\tif (!acc) {\n\t\t\t\t\tacc = emptyAcc()\n\t\t\t\t\tgroups.set(value, acc)\n\t\t\t\t}\n\t\t\t\tadd(acc, d)\n\t\t\t}\n\t\t\tlet rows: AnalyticsRow[] = [...groups].map(([value, acc]) => ({\n\t\t\t\tdimensions: { [dim]: value } as Partial<Record<DimensionKey, string>>,\n\t\t\t\tmetrics: selectMetrics(acc, q.metrics),\n\t\t\t}))\n\t\t\tconst sortMetric = q.order?.metric ?? 'pageviews'\n\t\t\tconst direction = (q.order?.direction ?? 'desc') === 'asc' ? 1 : -1\n\t\t\trows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction)\n\t\t\tif (q.limit) {\n\t\t\t\trows = rows.slice(0, q.limit)\n\t\t\t}\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst { docs } = await payloadRef.find({\n\t\t\t\tcollection: EVENTS_SLUG as never,\n\t\t\t\twhere: {\n\t\t\t\t\ttimestamp: {\n\t\t\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t\t\t},\n\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t} as never,\n\t\t\t\t// Newest-first under a hard cap: if a very busy site has more events than the\n\t\t\t\t// cap in the window, keep the most recent activity rather than the oldest.\n\t\t\t\t// Unbounded accuracy via DB-side aggregation is deferred to the hardening spec.\n\t\t\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\tsort: '-timestamp',\n\t\t\t})\n\t\t\tconst events = docs as unknown as RealtimeEvent[]\n\t\t\tconst { rows, totals } = buildRealtime(events, q.dateRange, q.metrics)\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;AA2CA,MAAM,UAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MAAM,aAAwC,IAAI,IAAI;CAAC;CAAQ;CAAW;CAAU;AAAQ,CAAC;AAE7F,MAAM,uBAAuB;AAE7B,MAAM,mBAA0C;CAC/C,cAAc;CACd,UAAU;CACV,uBAAuB;CACvB,YAAY;CACZ,gBAAgB;CAChB,iBAAiB;CACjB;CACA;CACA,iBAAiB;CACjB,WAAW;CACX,gBAAgB;EAAE,UAAU;EAAI,WAAW;CAAI;AAChD;AAEA,SAAgB,OAAO,UAAyB,CAAC,GAAkB;CAClE,MAAM,cACL,QAAQ,gBACP,QAAQ,YACN,oBAAoB,wBAAwB,gBAAgB,EAAE,QAAQ,QAAQ,UAAU,CAAC,CAAC,IAC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P,MAAM;GACP,CAAC;GAED,MAAM,EAAE,MAAM,WAAW,cAAcA,MAAQ,EAAE,WAAW,EAAE,OAAO;GACrE,OAAO;IAAE;IAAM;IAAQ,MAAM;KAAE,UAAU;KAAU;IAAU;GAAE;EAChE;CACD;AACD"}
1
+ {"version":3,"file":"nativeAdapter.js","names":["events"],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import type { Config, Payload } from 'payload'\nimport type {\n\tAdapterContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n\tAnalyticsRow,\n\tDimensionKey,\n\tMetricKey,\n} from '../core/contract'\nimport { EVENTS_SLUG, eventsCollection } from './collections/events'\nimport { ROLLUPS_SLUG, rollupsCollection } from './collections/rollups'\nimport { seenCollection } from './collections/seen'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { makeIngestHandler } from './ingest/endpoint'\nimport { flushBatch } from './ingest/flushBatch'\nimport type { StoredEvent } from './ingest/normalizeEvent'\nimport { createWriteBuffer, type WriteBuffer } from './ingest/writeBuffer'\nimport { aggregateEvents, type EventLike, filtersToWhere } from './query/eventAgg'\nimport { buildRealtime, type RealtimeEvent } from './realtime/buildRealtime'\nimport { pruneEventsTask } from './retention/pruneTask'\nimport {\n\ttype Acc,\n\tadd,\n\temptyAcc,\n\ttype RollupDoc,\n\tselectMetrics,\n\tseriesFromRollups,\n} from './rollupAcc'\n\nexport interface NativeOptions {\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\tingestPath?: string\n\tretentionDays?: number\n\t/** Opt-in in-process write batching. `true` uses defaults (maxSize 50, maxAgeMs 2000). */\n\tbuffer?: boolean | { maxSize?: number; maxAgeMs?: number }\n}\n\nexport type NativeAdapter = AnalyticsAdapter & { flush: () => Promise<void> }\n\nconst metrics: ReadonlySet<MetricKey> = new Set([\n\t'pageviews',\n\t'visitors',\n\t'sessions',\n\t'events',\n\t'avgDuration',\n])\nconst dimensions: ReadonlySet<DimensionKey> = new Set([\n\t'page',\n\t'country',\n\t'source',\n\t'device',\n\t'event',\n])\n\nconst REALTIME_EVENT_LIMIT = 50_000\n\nconst baseCapabilities: AnalyticsCapabilities = {\n\tperPageQuery: true,\n\trealtime: true,\n\trealtimeWindowMinutes: 60,\n\tcomparison: true,\n\tminGranularity: 'hour',\n\tmaxLookbackDays: null,\n\tmetrics,\n\tdimensions,\n\tfilters: new Set(['page', 'country', 'region', 'city', 'device', 'source', 'event']),\n\tfilterOperators: new Set(['eq', 'contains']),\n\tbatchPageReport: true,\n\trateLimit: null,\n\trecommendedTtl: { realtime: 10, aggregate: 300 },\n}\n\nconst DAY_MS = 86_400_000\n\ninterface QueryEventsContext {\n\tretentionDays?: number\n\tscopeWhere: (q: AnalyticsQuery) => Record<string, unknown>\n}\n\n/**\n * Filtered/hour-granularity reads bypass the day-bucketed rollups and aggregate raw\n * events directly, under the same hard cap as `realtime()`. `retentionDays` clamps how\n * far back the read can reach when it would otherwise ask for events the prune task has\n * already deleted (or will delete before they're queryable).\n */\nasync function queryEvents(\n\tpayload: Payload,\n\tq: AnalyticsQuery,\n\tctx: QueryEventsContext\n): Promise<AnalyticsResult> {\n\tconst fetchedAt = q.dateRange.end.toISOString()\n\tlet start = q.dateRange.start\n\tlet clamped = false\n\tif (ctx.retentionDays && ctx.retentionDays > 0) {\n\t\tconst floor = new Date(Date.now() - ctx.retentionDays * DAY_MS)\n\t\tif (start < floor) {\n\t\t\tstart = floor\n\t\t\tclamped = true\n\t\t}\n\t}\n\tconst baseWhere: Record<string, unknown> = {\n\t\ttimestamp: {\n\t\t\tgreater_than_equal: start.toISOString(),\n\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t},\n\t\t...(q.hostname ? { hostname: { equals: q.hostname } } : {}),\n\t\t...(q.path ? { path: { equals: q.path } } : {}),\n\t\t...ctx.scopeWhere(q),\n\t}\n\t// filtersToWhere can also key off 'path' (a page filter); AND rather than spread so\n\t// q.path and a page filter both constrain the query instead of one overwriting the other.\n\tconst filterWhere = filtersToWhere(q.filters ?? [])\n\tconst where: Record<string, unknown> =\n\t\tObject.keys(filterWhere).length > 0 ? { and: [baseWhere, filterWhere] } : baseWhere\n\tconst { docs } = await payload.find({\n\t\tcollection: EVENTS_SLUG as never,\n\t\twhere: where as never,\n\t\t// Newest-first under a hard cap, same tradeoff as realtime(): a very busy site\n\t\t// with more events than the cap in range keeps its most recent activity.\n\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\tsort: '-timestamp',\n\t})\n\tconst events = docs as unknown as EventLike[]\n\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\tconst granularity =\n\t\tq.granularity === 'hour' || q.granularity === 'day' ? q.granularity : undefined\n\tconst { rows, totals } = aggregateEvents(events, {\n\t\tmetrics: q.metrics,\n\t\tdimension: dim,\n\t\tgranularity,\n\t\ttimezone: q.timezone,\n\t\torder: q.order,\n\t\tlimit: q.limit,\n\t})\n\tconst meta: AnalyticsResult['meta'] = { provider: 'native', fetchedAt }\n\tif (clamped) meta.clamped = true\n\tif (events.length >= REALTIME_EVENT_LIMIT) meta.sampled = true\n\treturn { rows, totals, meta }\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tconst geoResolver =\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\t// Per-instance copy: register() flips scopedQueries when the install is scoped.\n\tconst capabilities: AnalyticsCapabilities = { ...baseCapabilities }\n\tlet payloadRef: Payload | null = null\n\tlet buffer: WriteBuffer<StoredEvent> | null = null\n\tlet scoped = false\n\n\tconst scopeWhere = (q: AnalyticsQuery): Record<string, unknown> =>\n\t\tscoped && q.scope !== undefined ? { scope: { equals: q.scope } } : {}\n\n\tconst readRollups = async (\n\t\tpayload: Payload,\n\t\twhere: Record<string, unknown>\n\t): Promise<RollupDoc[]> => {\n\t\tconst { docs } = await payload.find({\n\t\t\tcollection: ROLLUPS_SLUG as never,\n\t\t\twhere: where as never,\n\t\t\tlimit: 100_000,\n\t\t\tpagination: false,\n\t\t})\n\t\treturn docs as unknown as RollupDoc[]\n\t}\n\n\treturn {\n\t\tid: 'native',\n\t\tlabel: 'Native (Payload)',\n\t\tcapabilities,\n\t\tisConfigured: () => true,\n\t\tflush: () => buffer?.flush() ?? Promise.resolve(),\n\t\tregister(config: Config, context) {\n\t\t\tscoped = context?.scoped ?? false\n\t\t\tif (scoped) {\n\t\t\t\tcapabilities.scopedQueries = true\n\t\t\t}\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\teventsCollection(scoped),\n\t\t\t\trollupsCollection(scoped),\n\t\t\t\tseenCollection(),\n\t\t\t]\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{\n\t\t\t\t\tmethod: 'post',\n\t\t\t\t\tpath: options.ingestPath ?? '/analytics/ingest',\n\t\t\t\t\thandler: makeIngestHandler(geoResolver, () => buffer, {\n\t\t\t\t\t\tscope: scoped ? context?.resolveScope : undefined,\n\t\t\t\t\t\ttimezone: context?.resolveTimezone,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t]\n\t\t\tif (options.retentionDays && options.retentionDays > 0) {\n\t\t\t\tconfig.jobs = {\n\t\t\t\t\t...config.jobs,\n\t\t\t\t\ttasks: [...(config.jobs?.tasks ?? []), pruneEventsTask(options.retentionDays)],\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst prevOnInit = config.onInit\n\t\t\t// payloadRef is set before the app's own onInit so consumer init code can\n\t\t\t// already query the native adapter.\n\t\t\tconfig.onInit = async (p) => {\n\t\t\t\tpayloadRef = p\n\t\t\t\tif (options.buffer) {\n\t\t\t\t\tconst cfg = options.buffer === true ? {} : options.buffer\n\t\t\t\t\tbuffer = createWriteBuffer<StoredEvent>({\n\t\t\t\t\t\tmaxSize: cfg.maxSize ?? 50,\n\t\t\t\t\t\tmaxAgeMs: cfg.maxAgeMs ?? 2000,\n\t\t\t\t\t\tonFlush: (batch) => flushBatch(p, batch),\n\t\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\t\tp.logger.error({ err: error, msg: 'analytics: write buffer flush failed' })\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\tawait prevOnInit?.(p)\n\t\t\t}\n\t\t},\n\t\tasync query(q: AnalyticsQuery): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tif ((q.filters && q.filters.length > 0) || q.granularity === 'hour') {\n\t\t\t\treturn queryEvents(payloadRef, q, { retentionDays: options.retentionDays, scopeWhere })\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst periodWhere = {\n\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t}\n\t\t\tconst dim = q.dimensions?.find((d) => dimensions.has(d))\n\n\t\t\t// Distinct metrics (visitors/sessions) must not be summed across breakdown rows.\n\t\t\t// Totals always come from the non-dimensioned aggregate row. A dimensioned query\n\t\t\t// reports site-wide totals (path=''), a plain query uses the path-scoped row.\n\t\t\tconst totalsPath = dim ? '' : (q.path ?? '')\n\t\t\tconst totalsDocs = await readRollups(payloadRef, {\n\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\tdimension: { equals: '' },\n\t\t\t\tpath: { equals: totalsPath },\n\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\tperiod: periodWhere,\n\t\t\t\t...scopeWhere(q),\n\t\t\t})\n\t\t\tconst totalsAcc = emptyAcc()\n\t\t\tfor (const d of totalsDocs) {\n\t\t\t\tadd(totalsAcc, d)\n\t\t\t}\n\t\t\tconst totals = selectMetrics(totalsAcc, q.metrics)\n\n\t\t\tif (!dim) {\n\t\t\t\tif (q.granularity === 'day') {\n\t\t\t\t\treturn {\n\t\t\t\t\t\trows: seriesFromRollups(totalsDocs, q.metrics, q.timezone),\n\t\t\t\t\t\ttotals,\n\t\t\t\t\t\tmeta: { provider: 'native', fetchedAt },\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn { rows: [{ metrics: totals }], totals, meta: { provider: 'native', fetchedAt } }\n\t\t\t}\n\n\t\t\tconst breakdownWhere =\n\t\t\t\tdim === 'page'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: '' },\n\t\t\t\t\t\t\tpath: { not_equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tgranularity: { equals: 'day' },\n\t\t\t\t\t\t\tdimension: { equals: dim },\n\t\t\t\t\t\t\tpath: { equals: '' },\n\t\t\t\t\t\t\thostname: { equals: q.hostname ?? '' },\n\t\t\t\t\t\t\tperiod: periodWhere,\n\t\t\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t\t\t}\n\t\t\tconst groups = new Map<string, Acc>()\n\t\t\tfor (const d of await readRollups(payloadRef, breakdownWhere)) {\n\t\t\t\tconst value = dim === 'page' ? d.path : d.dimvalue\n\t\t\t\tlet acc = groups.get(value)\n\t\t\t\tif (!acc) {\n\t\t\t\t\tacc = emptyAcc()\n\t\t\t\t\tgroups.set(value, acc)\n\t\t\t\t}\n\t\t\t\tadd(acc, d)\n\t\t\t}\n\t\t\tlet rows: AnalyticsRow[] = [...groups].map(([value, acc]) => ({\n\t\t\t\tdimensions: { [dim]: value } as Partial<Record<DimensionKey, string>>,\n\t\t\t\tmetrics: selectMetrics(acc, q.metrics),\n\t\t\t}))\n\t\t\tconst sortMetric = q.order?.metric ?? 'pageviews'\n\t\t\tconst direction = (q.order?.direction ?? 'desc') === 'asc' ? 1 : -1\n\t\t\trows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction)\n\t\t\tif (q.limit) {\n\t\t\t\trows = rows.slice(0, q.limit)\n\t\t\t}\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, _ctx: AdapterContext): Promise<AnalyticsResult> {\n\t\t\tif (!payloadRef) {\n\t\t\t\tthrow new Error('analytics: native adapter queried before init')\n\t\t\t}\n\t\t\tconst fetchedAt = q.dateRange.end.toISOString()\n\t\t\tconst { docs } = await payloadRef.find({\n\t\t\t\tcollection: EVENTS_SLUG as never,\n\t\t\t\twhere: {\n\t\t\t\t\ttimestamp: {\n\t\t\t\t\t\tgreater_than_equal: q.dateRange.start.toISOString(),\n\t\t\t\t\t\tless_than_equal: q.dateRange.end.toISOString(),\n\t\t\t\t\t},\n\t\t\t\t\t...scopeWhere(q),\n\t\t\t\t} as never,\n\t\t\t\t// Newest-first under a hard cap: if a very busy site has more events than the\n\t\t\t\t// cap in the window, keep the most recent activity rather than the oldest.\n\t\t\t\t// Unbounded accuracy via DB-side aggregation is deferred to the hardening spec.\n\t\t\t\tlimit: REALTIME_EVENT_LIMIT,\n\t\t\t\tpagination: false,\n\t\t\t\tdepth: 0,\n\t\t\t\tsort: '-timestamp',\n\t\t\t})\n\t\t\tconst events = docs as unknown as RealtimeEvent[]\n\t\t\tconst { rows, totals } = buildRealtime(events, q.dateRange, q.metrics)\n\t\t\treturn { rows, totals, meta: { provider: 'native', fetchedAt } }\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA4CA,MAAM,UAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;AACD,CAAC;AACD,MA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,IAAI,KAAK;IAC1B,IAAI,CAAC,KAAK;KACT,MAAM,SAAS;KACf,OAAO,IAAI,OAAO,GAAG;IACtB;IACA,IAAI,KAAK,CAAC;GACX;GACA,IAAI,OAAuB,CAAC,GAAG,MAAM,EAAE,KAAK,CAAC,OAAO,UAAU;IAC7D,YAAY,GAAG,MAAM,MAAM;IAC3B,SAAS,cAAc,KAAK,EAAE,OAAO;GACtC,EAAE;GACF,MAAM,aAAa,EAAE,OAAO,UAAU;GACtC,MAAM,aAAa,EAAE,OAAO,aAAa,YAAY,QAAQ,IAAI;GACjE,KAAK,MAAM,GAAG,QAAQ,EAAE,QAAQ,eAAe,MAAM,EAAE,QAAQ,eAAe,MAAM,SAAS;GAC7F,IAAI,EAAE,OACL,OAAO,KAAK,MAAM,GAAG,EAAE,KAAK;GAE7B,OAAO;IAAE;IAAM;IAAQ,MAAM;KAAE,UAAU;KAAU;IAAU;GAAE;EAChE;EACA,MAAM,SAAS,GAAmB,MAAgD;GACjF,IAAI,CAAC,YACJ,MAAM,IAAI,MAAM,+CAA+C;GAEhE,MAAM,YAAY,EAAE,UAAU,IAAI,YAAY;GAC9C,MAAM,EAAE,SAAS,MAAM,WAAW,KAAK;IACtC,YAAY;IACZ,OAAO;KACN,WAAW;MACV,oBAAoB,EAAE,UAAU,MAAM,YAAY;MAClD,iBAAiB,EAAE,UAAU,IAAI,YAAY;KAC9C;KACA,GAAG,WAAW,CAAC;IAChB;IAIA,OAAO;IACP,YAAY;IACZ,OAAO;IACP,MAAM;GACP,CAAC;GAED,MAAM,EAAE,MAAM,WAAW,cAAcA,MAAQ,EAAE,WAAW,EAAE,OAAO;GACrE,OAAO;IAAE;IAAM;IAAQ,MAAM;KAAE,UAAU;KAAU;IAAU;GAAE;EAChE;CACD;AACD"}
@@ -0,0 +1,135 @@
1
+ import { startOfDayInTz } from "../../timeframe/tz.js";
2
+ //#region src/native/query/eventAgg.ts
3
+ const HOUR_MS = 36e5;
4
+ /** Dimensions native can filter/group on directly against the events collection. */
5
+ const EVENT_FIELD = {
6
+ page: "path",
7
+ country: "country",
8
+ region: "region",
9
+ city: "city",
10
+ device: "device",
11
+ source: "source",
12
+ event: "name"
13
+ };
14
+ const FILTER_OPERATOR = {
15
+ eq: "equals",
16
+ contains: "contains"
17
+ };
18
+ /**
19
+ * Payload where fragment for supported filters; unsupported dimensions/operators are
20
+ * dropped. Capability gating (`filters`/`filterOperators`) is the real contract upstream,
21
+ * this is just the safety net so a stray unsupported filter never throws.
22
+ * `contains` is case-insensitive on both DBs; on Postgres its value is a raw ILIKE
23
+ * pattern (`%`/`_` act as wildcards), while Mongo regex-escapes the value first.
24
+ */
25
+ const filtersToWhere = (filters) => {
26
+ const where = {};
27
+ for (const filter of filters) {
28
+ const field = EVENT_FIELD[filter.dimension];
29
+ if (!field || filter.operator === "matches") continue;
30
+ const op = FILTER_OPERATOR[filter.operator];
31
+ if (!op) continue;
32
+ where[field] = {
33
+ ...where[field],
34
+ [op]: filter.value
35
+ };
36
+ }
37
+ return where;
38
+ };
39
+ const emptyBucket = () => ({
40
+ pageviews: 0,
41
+ events: 0,
42
+ durationMs: 0,
43
+ visitors: /* @__PURE__ */ new Set(),
44
+ sessions: /* @__PURE__ */ new Set()
45
+ });
46
+ const addEvent = (bucket, event) => {
47
+ if (event.type === "pageview") {
48
+ bucket.pageviews++;
49
+ bucket.durationMs += event.durationMs ?? 0;
50
+ } else bucket.events++;
51
+ bucket.visitors.add(event.visitorHash);
52
+ bucket.sessions.add(event.sessionId);
53
+ };
54
+ const selectMetrics = (bucket, wanted) => {
55
+ const out = {};
56
+ if (wanted.includes("pageviews")) out.pageviews = bucket.pageviews;
57
+ if (wanted.includes("events")) out.events = bucket.events;
58
+ if (wanted.includes("visitors")) out.visitors = bucket.visitors.size;
59
+ if (wanted.includes("sessions")) out.sessions = bucket.sessions.size;
60
+ if (wanted.includes("avgDuration")) out.avgDuration = bucket.pageviews > 0 ? Math.round(bucket.durationMs / bucket.pageviews) : 0;
61
+ return out;
62
+ };
63
+ /**
64
+ * Hour buckets are UTC-hour floors regardless of `timezone`; sub-day bucketing ignoring
65
+ * the reporting timezone is a documented v1 limitation. Day buckets floor in `timezone`
66
+ * to stay aligned with native rollup day boundaries.
67
+ */
68
+ const bucketKeyFor = (event, granularity, timezone) => {
69
+ const ts = new Date(event.timestamp);
70
+ if (granularity === "hour") return (/* @__PURE__ */ new Date(Math.floor(ts.getTime() / HOUR_MS) * HOUR_MS)).toISOString();
71
+ return startOfDayInTz(ts, timezone).toISOString();
72
+ };
73
+ /**
74
+ * Aggregate raw events into totals, plus one of: dimension breakdown rows or hour/day
75
+ * series rows (dimension wins if both are requested). Totals always cover every event
76
+ * passed in, independent of which rows a breakdown or series produces.
77
+ */
78
+ const aggregateEvents = (events, { metrics, dimension, granularity, timezone = "UTC", order, limit }) => {
79
+ const totalsBucket = emptyBucket();
80
+ for (const event of events) addEvent(totalsBucket, event);
81
+ const totals = selectMetrics(totalsBucket, metrics);
82
+ const field = dimension ? EVENT_FIELD[dimension] : void 0;
83
+ if (dimension && field) {
84
+ const groups = /* @__PURE__ */ new Map();
85
+ for (const event of events) {
86
+ const value = event[field];
87
+ if (!value) continue;
88
+ let bucket = groups.get(value);
89
+ if (!bucket) {
90
+ bucket = emptyBucket();
91
+ groups.set(value, bucket);
92
+ }
93
+ addEvent(bucket, event);
94
+ }
95
+ let rows = [...groups].map(([value, bucket]) => ({
96
+ dimensions: { [dimension]: value },
97
+ metrics: selectMetrics(bucket, metrics)
98
+ }));
99
+ const sortMetric = order?.metric ?? "pageviews";
100
+ const direction = (order?.direction ?? "desc") === "asc" ? 1 : -1;
101
+ rows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction);
102
+ if (limit) rows = rows.slice(0, limit);
103
+ return {
104
+ rows,
105
+ totals
106
+ };
107
+ }
108
+ if (granularity) {
109
+ const buckets = /* @__PURE__ */ new Map();
110
+ for (const event of events) {
111
+ const key = bucketKeyFor(event, granularity, timezone);
112
+ let bucket = buckets.get(key);
113
+ if (!bucket) {
114
+ bucket = emptyBucket();
115
+ buckets.set(key, bucket);
116
+ }
117
+ addEvent(bucket, event);
118
+ }
119
+ return {
120
+ rows: [...buckets.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([timestamp, bucket]) => ({
121
+ timestamp,
122
+ metrics: selectMetrics(bucket, metrics)
123
+ })),
124
+ totals
125
+ };
126
+ }
127
+ return {
128
+ rows: [{ metrics: totals }],
129
+ totals
130
+ };
131
+ };
132
+ //#endregion
133
+ export { aggregateEvents, filtersToWhere };
134
+
135
+ //# sourceMappingURL=eventAgg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"eventAgg.js","names":[],"sources":["../../../src/native/query/eventAgg.ts"],"sourcesContent":["import type { AnalyticsFilter, AnalyticsRow, DimensionKey, MetricKey } from '../../core/contract'\nimport { DEFAULT_TIMEZONE, startOfDayInTz } from '../../timeframe/tz'\n\n/** Raw event shape aggregateEvents/filtersToWhere operate on; matches StoredEvent as read back from the events collection (timestamp comes back as an ISO string). */\nexport interface EventLike {\n\ttimestamp: string | Date\n\ttype: 'pageview' | 'event'\n\tname?: string\n\tpath: string\n\tdevice?: string\n\tsource?: string\n\tcountry?: string\n\tregion?: string\n\tcity?: string\n\tvisitorHash: string\n\tsessionId: string\n\tdurationMs?: number\n}\n\nconst HOUR_MS = 3_600_000\n\ntype EventStringField = 'path' | 'country' | 'region' | 'city' | 'device' | 'source' | 'name'\n\n/** Dimensions native can filter/group on directly against the events collection. */\nconst EVENT_FIELD: Partial<Record<DimensionKey, EventStringField>> = {\n\tpage: 'path',\n\tcountry: 'country',\n\tregion: 'region',\n\tcity: 'city',\n\tdevice: 'device',\n\tsource: 'source',\n\tevent: 'name',\n}\n\nconst FILTER_OPERATOR: Record<'eq' | 'contains', string> = { eq: 'equals', contains: 'contains' }\n\n/**\n * Payload where fragment for supported filters; unsupported dimensions/operators are\n * dropped. Capability gating (`filters`/`filterOperators`) is the real contract upstream,\n * this is just the safety net so a stray unsupported filter never throws.\n * `contains` is case-insensitive on both DBs; on Postgres its value is a raw ILIKE\n * pattern (`%`/`_` act as wildcards), while Mongo regex-escapes the value first.\n */\nexport const filtersToWhere = (filters: AnalyticsFilter[]): Record<string, unknown> => {\n\tconst where: Record<string, unknown> = {}\n\tfor (const filter of filters) {\n\t\tconst field = EVENT_FIELD[filter.dimension]\n\t\tif (!field || filter.operator === 'matches') {\n\t\t\tcontinue\n\t\t}\n\t\tconst op = FILTER_OPERATOR[filter.operator]\n\t\tif (!op) {\n\t\t\tcontinue\n\t\t}\n\t\twhere[field] = { ...(where[field] as object | undefined), [op]: filter.value }\n\t}\n\treturn where\n}\n\ninterface Bucket {\n\tpageviews: number\n\tevents: number\n\tdurationMs: number\n\tvisitors: Set<string>\n\tsessions: Set<string>\n}\n\nconst emptyBucket = (): Bucket => ({\n\tpageviews: 0,\n\tevents: 0,\n\tdurationMs: 0,\n\tvisitors: new Set(),\n\tsessions: new Set(),\n})\n\nconst addEvent = (bucket: Bucket, event: EventLike): void => {\n\tif (event.type === 'pageview') {\n\t\tbucket.pageviews++\n\t\tbucket.durationMs += event.durationMs ?? 0\n\t} else {\n\t\tbucket.events++\n\t}\n\tbucket.visitors.add(event.visitorHash)\n\tbucket.sessions.add(event.sessionId)\n}\n\nconst selectMetrics = (bucket: Bucket, wanted: MetricKey[]): Partial<Record<MetricKey, number>> => {\n\tconst out: Partial<Record<MetricKey, number>> = {}\n\tif (wanted.includes('pageviews')) out.pageviews = bucket.pageviews\n\tif (wanted.includes('events')) out.events = bucket.events\n\tif (wanted.includes('visitors')) out.visitors = bucket.visitors.size\n\tif (wanted.includes('sessions')) out.sessions = bucket.sessions.size\n\tif (wanted.includes('avgDuration')) {\n\t\tout.avgDuration = bucket.pageviews > 0 ? Math.round(bucket.durationMs / bucket.pageviews) : 0\n\t}\n\treturn out\n}\n\nexport interface AggregateEventsArgs {\n\tmetrics: MetricKey[]\n\tdimension?: DimensionKey\n\tgranularity?: 'hour' | 'day'\n\ttimezone?: string\n\t/** Sort for dimension breakdown rows; defaults to pageviews desc, same as the rollup path. */\n\torder?: { metric: MetricKey; direction: 'asc' | 'desc' }\n\t/** Row cap for dimension breakdown rows, applied after sorting. */\n\tlimit?: number\n}\n\nexport interface AggregateEventsResult {\n\trows: AnalyticsRow[]\n\ttotals: Partial<Record<MetricKey, number>>\n}\n\n/**\n * Hour buckets are UTC-hour floors regardless of `timezone`; sub-day bucketing ignoring\n * the reporting timezone is a documented v1 limitation. Day buckets floor in `timezone`\n * to stay aligned with native rollup day boundaries.\n */\nconst bucketKeyFor = (event: EventLike, granularity: 'hour' | 'day', timezone: string): string => {\n\tconst ts = new Date(event.timestamp)\n\tif (granularity === 'hour') {\n\t\treturn new Date(Math.floor(ts.getTime() / HOUR_MS) * HOUR_MS).toISOString()\n\t}\n\treturn startOfDayInTz(ts, timezone).toISOString()\n}\n\n/**\n * Aggregate raw events into totals, plus one of: dimension breakdown rows or hour/day\n * series rows (dimension wins if both are requested). Totals always cover every event\n * passed in, independent of which rows a breakdown or series produces.\n */\nexport const aggregateEvents = (\n\tevents: EventLike[],\n\t{\n\t\tmetrics,\n\t\tdimension,\n\t\tgranularity,\n\t\ttimezone = DEFAULT_TIMEZONE,\n\t\torder,\n\t\tlimit,\n\t}: AggregateEventsArgs\n): AggregateEventsResult => {\n\tconst totalsBucket = emptyBucket()\n\tfor (const event of events) {\n\t\taddEvent(totalsBucket, event)\n\t}\n\tconst totals = selectMetrics(totalsBucket, metrics)\n\n\tconst field = dimension ? EVENT_FIELD[dimension] : undefined\n\tif (dimension && field) {\n\t\tconst groups = new Map<string, Bucket>()\n\t\tfor (const event of events) {\n\t\t\tconst value = event[field]\n\t\t\tif (!value) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlet bucket = groups.get(value)\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = emptyBucket()\n\t\t\t\tgroups.set(value, bucket)\n\t\t\t}\n\t\t\taddEvent(bucket, event)\n\t\t}\n\t\tlet rows: AnalyticsRow[] = [...groups].map(([value, bucket]) => ({\n\t\t\tdimensions: { [dimension]: value } as Partial<Record<DimensionKey, string>>,\n\t\t\tmetrics: selectMetrics(bucket, metrics),\n\t\t}))\n\t\tconst sortMetric = order?.metric ?? 'pageviews'\n\t\tconst direction = (order?.direction ?? 'desc') === 'asc' ? 1 : -1\n\t\trows.sort((a, b) => ((a.metrics[sortMetric] ?? 0) - (b.metrics[sortMetric] ?? 0)) * direction)\n\t\tif (limit) {\n\t\t\trows = rows.slice(0, limit)\n\t\t}\n\t\treturn { rows, totals }\n\t}\n\n\tif (granularity) {\n\t\tconst buckets = new Map<string, Bucket>()\n\t\tfor (const event of events) {\n\t\t\tconst key = bucketKeyFor(event, granularity, timezone)\n\t\t\tlet bucket = buckets.get(key)\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = emptyBucket()\n\t\t\t\tbuckets.set(key, bucket)\n\t\t\t}\n\t\t\taddEvent(bucket, event)\n\t\t}\n\t\tconst rows: AnalyticsRow[] = [...buckets.entries()]\n\t\t\t.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n\t\t\t.map(([timestamp, bucket]) => ({ timestamp, metrics: selectMetrics(bucket, metrics) }))\n\t\treturn { rows, totals }\n\t}\n\n\treturn { rows: [{ metrics: totals }], totals }\n}\n"],"mappings":";;AAmBA,MAAM,UAAU;;AAKhB,MAAM,cAA+D;CACpE,MAAM;CACN,SAAS;CACT,QAAQ;CACR,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,OAAO;AACR;AAEA,MAAM,kBAAqD;CAAE,IAAI;CAAU,UAAU;AAAW;;;;;;;;AAShG,MAAa,kBAAkB,YAAwD;CACtF,MAAM,QAAiC,CAAC;CACxC,KAAK,MAAM,UAAU,SAAS;EAC7B,MAAM,QAAQ,YAAY,OAAO;EACjC,IAAI,CAAC,SAAS,OAAO,aAAa,WACjC;EAED,MAAM,KAAK,gBAAgB,OAAO;EACl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;GAAE,EACzE;GAAG;EAAO;CACvB;CAEA,OAAO;EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,CAAC;EAAG;CAAO;AAC9C"}
@@ -1,6 +1,6 @@
1
1
  //#region src/native/rollups/applyDistinctDeltas.ts
2
2
  function bucketKey(key) {
3
- const base = `${key.granularity}|${key.period.toISOString()}|${key.path}|${key.dimension}|${key.dimvalue}`;
3
+ const base = `${key.granularity}|${key.period.toISOString()}|${key.path}|${key.dimension}|${key.dimvalue}|${key.hostname}`;
4
4
  return key.scope !== void 0 ? `${base}|${key.scope}` : base;
5
5
  }
6
6
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"applyDistinctDeltas.js","names":[],"sources":["../../../src/native/rollups/applyDistinctDeltas.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { SEEN_SLUG } from '../collections/seen'\nimport type { StoredEvent } from '../ingest/normalizeEvent'\nimport { bumpRollup } from './bumpRollup'\nimport type { RollupDelta, RollupKey } from './deltas'\nimport { insertIfNew } from './insertIfNew'\n\nexport function bucketKey(key: RollupKey): string {\n\tconst base = `${key.granularity}|${key.period.toISOString()}|${key.path}|${key.dimension}|${key.dimvalue}`\n\treturn key.scope !== undefined ? `${base}|${key.scope}` : base\n}\n\n// For each rollup bucket the event touches, count this visitor and session at most once.\n// insertIfNew is the dedup gate; only a genuinely new ledger row bumps the distinct counter.\nexport async function applyDistinctDeltas(\n\tpayload: Payload,\n\tevent: StoredEvent,\n\tdeltas: RollupDelta[]\n): Promise<void> {\n\tfor (const d of deltas) {\n\t\tconst bucket = bucketKey(d.key)\n\t\tconst period = d.key.period\n\t\tif (\n\t\t\tawait insertIfNew(payload, SEEN_SLUG, {\n\t\t\t\tbucket,\n\t\t\t\tkind: 'visitor',\n\t\t\t\tvalue: event.visitorHash,\n\t\t\t\tperiod,\n\t\t\t})\n\t\t) {\n\t\t\tawait bumpRollup(payload, d.key, { visitors: 1 })\n\t\t}\n\t\tif (\n\t\t\tawait insertIfNew(payload, SEEN_SLUG, {\n\t\t\t\tbucket,\n\t\t\t\tkind: 'session',\n\t\t\t\tvalue: event.sessionId,\n\t\t\t\tperiod,\n\t\t\t})\n\t\t) {\n\t\t\tawait bumpRollup(payload, d.key, { sessions: 1 })\n\t\t}\n\t}\n}\n"],"mappings":";AAOA,SAAgB,UAAU,KAAwB;CACjD,MAAM,OAAO,GAAG,IAAI,YAAY,GAAG,IAAI,OAAO,YAAY,EAAE,GAAG,IAAI,KAAK,GAAG,IAAI,UAAU,GAAG,IAAI;CAChG,OAAO,IAAI,UAAU,KAAA,IAAY,GAAG,KAAK,GAAG,IAAI,UAAU;AAC3D"}
1
+ {"version":3,"file":"applyDistinctDeltas.js","names":[],"sources":["../../../src/native/rollups/applyDistinctDeltas.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { SEEN_SLUG } from '../collections/seen'\nimport type { StoredEvent } from '../ingest/normalizeEvent'\nimport { bumpRollup } from './bumpRollup'\nimport type { RollupDelta, RollupKey } from './deltas'\nimport { insertIfNew } from './insertIfNew'\n\nexport function bucketKey(key: RollupKey): string {\n\tconst base = `${key.granularity}|${key.period.toISOString()}|${key.path}|${key.dimension}|${key.dimvalue}|${key.hostname}`\n\treturn key.scope !== undefined ? `${base}|${key.scope}` : base\n}\n\n// For each rollup bucket the event touches, count this visitor and session at most once.\n// insertIfNew is the dedup gate; only a genuinely new ledger row bumps the distinct counter.\nexport async function applyDistinctDeltas(\n\tpayload: Payload,\n\tevent: StoredEvent,\n\tdeltas: RollupDelta[]\n): Promise<void> {\n\tfor (const d of deltas) {\n\t\tconst bucket = bucketKey(d.key)\n\t\tconst period = d.key.period\n\t\tif (\n\t\t\tawait insertIfNew(payload, SEEN_SLUG, {\n\t\t\t\tbucket,\n\t\t\t\tkind: 'visitor',\n\t\t\t\tvalue: event.visitorHash,\n\t\t\t\tperiod,\n\t\t\t})\n\t\t) {\n\t\t\tawait bumpRollup(payload, d.key, { visitors: 1 })\n\t\t}\n\t\tif (\n\t\t\tawait insertIfNew(payload, SEEN_SLUG, {\n\t\t\t\tbucket,\n\t\t\t\tkind: 'session',\n\t\t\t\tvalue: event.sessionId,\n\t\t\t\tperiod,\n\t\t\t})\n\t\t) {\n\t\t\tawait bumpRollup(payload, d.key, { sessions: 1 })\n\t\t}\n\t}\n}\n"],"mappings":";AAOA,SAAgB,UAAU,KAAwB;CACjD,MAAM,OAAO,GAAG,IAAI,YAAY,GAAG,IAAI,OAAO,YAAY,EAAE,GAAG,IAAI,KAAK,GAAG,IAAI,UAAU,GAAG,IAAI,SAAS,GAAG,IAAI;CAChH,OAAO,IAAI,UAAU,KAAA,IAAY,GAAG,KAAK,GAAG,IAAI,UAAU;AAC3D"}
@@ -50,7 +50,8 @@ async function bumpRollup(payload, key, inc) {
50
50
  table.period,
51
51
  table.path,
52
52
  table.dimension,
53
- table.dimvalue
53
+ table.dimvalue,
54
+ table.hostname
54
55
  ];
55
56
  if (key.scope !== void 0) target.push(table.scope);
56
57
  await db.drizzle.insert(table).values({
@@ -1 +1 @@
1
- {"version":3,"file":"bumpRollup.js","names":[],"sources":["../../../src/native/rollups/bumpRollup.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { ROLLUPS_SLUG } from '../collections/rollups'\nimport type { RollupKey, RollupMetric } from './deltas'\n\nconst PG_TABLE_KEY = 'analytics_rollups'\n\ntype PostgresSqlModule = { sql: typeof import('@payloadcms/db-postgres')['sql'] }\n\n/**\n * Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,\n * Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even\n * though this branch is unreachable there. The function-built specifier is opaque to their\n * analyzers, the ignore comments cover bundlers that would still warn, and the type-only\n * reference above erases at compile time, so the package is touched only when the Postgres\n * branch actually runs.\n */\nconst importPostgresSql = (): Promise<PostgresSqlModule> => {\n\tconst specifier = ['@payloadcms', 'db-postgres'].join('/')\n\treturn import(\n\t\t/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier\n\t) as Promise<PostgresSqlModule>\n}\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance for atomic upserts (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{ collection: { updateOne: (f: object, u: object, o: object) => Promise<unknown> } }\n\t>\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: {\n\t\tinsert: (t: unknown) => {\n\t\t\tvalues: (v: unknown) => { onConflictDoUpdate: (c: unknown) => Promise<unknown> }\n\t\t}\n\t}\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\nconst ZERO: Record<RollupMetric, number> = {\n\tpageviews: 0,\n\tevents: 0,\n\tdurationMs: 0,\n\tsamples: 0,\n\tvisitors: 0,\n\tsessions: 0,\n}\n\n// Always seed every metric on insert: Payload's defaultValue is applied app-side, not as\n// a SQL default, so a raw insert that omits a NOT NULL metric column would fail on Postgres.\nexport async function bumpRollup(\n\tpayload: Payload,\n\tkey: RollupKey,\n\tinc: Partial<Record<RollupMetric, number>>\n): Promise<void> {\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[ROLLUPS_SLUG]\n\t\tif (!model) throw new Error(`analytics: mongoose collection \"${ROLLUPS_SLUG}\" not found`)\n\t\tconst setOnInsert: Record<string, unknown> = { ...key }\n\t\tfor (const [metric, zero] of Object.entries(ZERO)) {\n\t\t\tif (!(metric in inc)) setOnInsert[metric] = zero\n\t\t}\n\t\tawait model.collection.updateOne(\n\t\t\tkey,\n\t\t\t{ $inc: inc, $setOnInsert: setOnInsert },\n\t\t\t{ upsert: true }\n\t\t)\n\t\treturn\n\t}\n\tconst { sql } = await importPostgresSql()\n\tconst db = payload.db as unknown as PgDb\n\tconst tableName = db.tableNameMap.get(PG_TABLE_KEY)\n\tif (!tableName) throw new Error(`analytics: drizzle table \"${PG_TABLE_KEY}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`analytics: drizzle table object for \"${tableName}\" not found`)\n\tconst set: Record<string, unknown> = {}\n\tfor (const [metric, amount] of Object.entries(inc)) {\n\t\tset[metric] = sql`${table[metric]} + ${amount}`\n\t}\n\t// The conflict target must match the unique index exactly, which includes the\n\t// scope column only in scoped installs (mirrored by a scope key on RollupKey).\n\tconst target = [table.granularity, table.period, table.path, table.dimension, table.dimvalue]\n\tif (key.scope !== undefined) {\n\t\ttarget.push(table.scope)\n\t}\n\tawait db.drizzle\n\t\t.insert(table)\n\t\t.values({ ...key, ...ZERO, ...inc })\n\t\t.onConflictDoUpdate({ target, set })\n}\n"],"mappings":";;AAIA,MAAM,eAAe;;;;;;;;;AAYrB,MAAM,0BAAsD;CAE3D,OAAO;;;;EADW,CAAC,eAAe,aAAa,EAAE,KAAK,GAE4B;;AAEnF;AAsBA,MAAM,OAAqC;CAC1C,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,SAAS;CACT,UAAU;CACV,UAAU;AACX;AAIA,eAAsB,WACrB,SACA,KACA,KACgB;CAChB,IAAI,QAAQ,GAAG,SAAS,YAAY;EAEnC,MAAM,QADK,QAAQ,GACF,YAAY;EAC7B,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,mCAAmC,aAAa,YAAY;EACxF,MAAM,cAAuC,EAAE,GAAG,IAAI;EACtD,KAAK,MAAM,CAAC,QAAQ,SAAS,OAAO,QAAQ,IAAI,GAC/C,IAAI,EAAE,UAAU,MAAM,YAAY,UAAU;EAE7C,MAAM,MAAM,WAAW,UACtB,KACA;GAAE,MAAM;GAAK,cAAc;EAAY,GACvC,EAAE,QAAQ,KAAK,CAChB;EACA;CACD;CACA,MAAM,EAAE,QAAQ,MAAM,kBAAkB;CACxC,MAAM,KAAK,QAAQ;CACnB,MAAM,YAAY,GAAG,aAAa,IAAI,YAAY;CAClD,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,6BAA6B,aAAa,YAAY;CACtF,MAAM,QAAQ,GAAG,OAAO;CACxB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,wCAAwC,UAAU,YAAY;CAC1F,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,CAAC,QAAQ,WAAW,OAAO,QAAQ,GAAG,GAChD,IAAI,UAAU,GAAG,GAAG,MAAM,QAAQ,KAAK;CAIxC,MAAM,SAAS;EAAC,MAAM;EAAa,MAAM;EAAQ,MAAM;EAAM,MAAM;EAAW,MAAM;CAAQ;CAC5F,IAAI,IAAI,UAAU,KAAA,GACjB,OAAO,KAAK,MAAM,KAAK;CAExB,MAAM,GAAG,QACP,OAAO,KAAK,EACZ,OAAO;EAAE,GAAG;EAAK,GAAG;EAAM,GAAG;CAAI,CAAC,EAClC,mBAAmB;EAAE;EAAQ;CAAI,CAAC;AACrC"}
1
+ {"version":3,"file":"bumpRollup.js","names":[],"sources":["../../../src/native/rollups/bumpRollup.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { ROLLUPS_SLUG } from '../collections/rollups'\nimport type { RollupKey, RollupMetric } from './deltas'\n\nconst PG_TABLE_KEY = 'analytics_rollups'\n\ntype PostgresSqlModule = { sql: typeof import('@payloadcms/db-postgres')['sql'] }\n\n/**\n * Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,\n * Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even\n * though this branch is unreachable there. The function-built specifier is opaque to their\n * analyzers, the ignore comments cover bundlers that would still warn, and the type-only\n * reference above erases at compile time, so the package is touched only when the Postgres\n * branch actually runs.\n */\nconst importPostgresSql = (): Promise<PostgresSqlModule> => {\n\tconst specifier = ['@payloadcms', 'db-postgres'].join('/')\n\treturn import(\n\t\t/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier\n\t) as Promise<PostgresSqlModule>\n}\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance for atomic upserts (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{ collection: { updateOne: (f: object, u: object, o: object) => Promise<unknown> } }\n\t>\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: {\n\t\tinsert: (t: unknown) => {\n\t\t\tvalues: (v: unknown) => { onConflictDoUpdate: (c: unknown) => Promise<unknown> }\n\t\t}\n\t}\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\nconst ZERO: Record<RollupMetric, number> = {\n\tpageviews: 0,\n\tevents: 0,\n\tdurationMs: 0,\n\tsamples: 0,\n\tvisitors: 0,\n\tsessions: 0,\n}\n\n// Always seed every metric on insert: Payload's defaultValue is applied app-side, not as\n// a SQL default, so a raw insert that omits a NOT NULL metric column would fail on Postgres.\nexport async function bumpRollup(\n\tpayload: Payload,\n\tkey: RollupKey,\n\tinc: Partial<Record<RollupMetric, number>>\n): Promise<void> {\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[ROLLUPS_SLUG]\n\t\tif (!model) throw new Error(`analytics: mongoose collection \"${ROLLUPS_SLUG}\" not found`)\n\t\tconst setOnInsert: Record<string, unknown> = { ...key }\n\t\tfor (const [metric, zero] of Object.entries(ZERO)) {\n\t\t\tif (!(metric in inc)) setOnInsert[metric] = zero\n\t\t}\n\t\tawait model.collection.updateOne(\n\t\t\tkey,\n\t\t\t{ $inc: inc, $setOnInsert: setOnInsert },\n\t\t\t{ upsert: true }\n\t\t)\n\t\treturn\n\t}\n\tconst { sql } = await importPostgresSql()\n\tconst db = payload.db as unknown as PgDb\n\tconst tableName = db.tableNameMap.get(PG_TABLE_KEY)\n\tif (!tableName) throw new Error(`analytics: drizzle table \"${PG_TABLE_KEY}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`analytics: drizzle table object for \"${tableName}\" not found`)\n\tconst set: Record<string, unknown> = {}\n\tfor (const [metric, amount] of Object.entries(inc)) {\n\t\tset[metric] = sql`${table[metric]} + ${amount}`\n\t}\n\t// The conflict target must match the unique index exactly, which includes the\n\t// scope column only in scoped installs (mirrored by a scope key on RollupKey).\n\tconst target = [\n\t\ttable.granularity,\n\t\ttable.period,\n\t\ttable.path,\n\t\ttable.dimension,\n\t\ttable.dimvalue,\n\t\ttable.hostname,\n\t]\n\tif (key.scope !== undefined) {\n\t\ttarget.push(table.scope)\n\t}\n\tawait db.drizzle\n\t\t.insert(table)\n\t\t.values({ ...key, ...ZERO, ...inc })\n\t\t.onConflictDoUpdate({ target, set })\n}\n"],"mappings":";;AAIA,MAAM,eAAe;;;;;;;;;AAYrB,MAAM,0BAAsD;CAE3D,OAAO;;;;EADW,CAAC,eAAe,aAAa,EAAE,KAAK,GAE4B;;AAEnF;AAsBA,MAAM,OAAqC;CAC1C,WAAW;CACX,QAAQ;CACR,YAAY;CACZ,SAAS;CACT,UAAU;CACV,UAAU;AACX;AAIA,eAAsB,WACrB,SACA,KACA,KACgB;CAChB,IAAI,QAAQ,GAAG,SAAS,YAAY;EAEnC,MAAM,QADK,QAAQ,GACF,YAAY;EAC7B,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,mCAAmC,aAAa,YAAY;EACxF,MAAM,cAAuC,EAAE,GAAG,IAAI;EACtD,KAAK,MAAM,CAAC,QAAQ,SAAS,OAAO,QAAQ,IAAI,GAC/C,IAAI,EAAE,UAAU,MAAM,YAAY,UAAU;EAE7C,MAAM,MAAM,WAAW,UACtB,KACA;GAAE,MAAM;GAAK,cAAc;EAAY,GACvC,EAAE,QAAQ,KAAK,CAChB;EACA;CACD;CACA,MAAM,EAAE,QAAQ,MAAM,kBAAkB;CACxC,MAAM,KAAK,QAAQ;CACnB,MAAM,YAAY,GAAG,aAAa,IAAI,YAAY;CAClD,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,6BAA6B,aAAa,YAAY;CACtF,MAAM,QAAQ,GAAG,OAAO;CACxB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,wCAAwC,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