@10x-media/analytics 1.0.0-beta.8 → 1.0.0-beta.9
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.
- package/CHANGELOG.md +70 -0
- package/LICENSE +21 -21
- package/README.md +3 -3
- package/dist/adapters/ga4/eventName.d.ts +15 -0
- package/dist/adapters/ga4/eventName.js +19 -0
- package/dist/adapters/ga4/eventName.js.map +1 -0
- package/dist/adapters/ga4/ga4.d.ts +5 -0
- package/dist/adapters/ga4/ga4.js +178 -70
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +15 -0
- package/dist/adapters/ga4/measurementId.js.map +1 -0
- package/dist/adapters/goalRead.js +126 -0
- package/dist/adapters/goalRead.js.map +1 -0
- package/dist/adapters/plausible/plausible.d.ts +15 -0
- package/dist/adapters/plausible/plausible.js +110 -42
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.js +47 -25
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +8 -0
- package/dist/adapters/umami/umami.js +237 -28
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/BarList.js +8 -2
- package/dist/charts/BarList.js.map +1 -1
- package/dist/core/cacheKey.js +11 -1
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/capabilities.js +7 -2
- package/dist/core/capabilities.js.map +1 -1
- package/dist/core/capture.d.ts +1 -1
- package/dist/core/contract.d.ts +32 -2
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +8 -2
- package/dist/core/options.js +4 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/serverEvent.d.ts +4 -2
- package/dist/core/serverEvent.js.map +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -1
- package/dist/exports/adapters/ga4.js +2 -1
- package/dist/exports/client.d.ts +5 -2
- package/dist/exports/client.js +4 -1
- package/dist/exports/rsc.d.ts +2 -1
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/tracker.js +2 -1
- package/dist/exports/types.d.ts +2 -1
- package/dist/exports/types.js +2 -1
- package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
- package/dist/fields/config/FilterDimensionSelectField.js +77 -0
- package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
- package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
- package/dist/fields/config/FilterOperatorSelectField.js +75 -0
- package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
- package/dist/fields/config/MetricSelectField.js +1 -1
- package/dist/fields/config/SourceSelectField.js +1 -1
- package/dist/fields/config/sourcesState.js +19 -3
- package/dist/fields/config/sourcesState.js.map +1 -1
- package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
- package/dist/fields/config/useAnalyticsSources.js +9 -6
- package/dist/fields/config/useAnalyticsSources.js.map +1 -1
- package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
- package/dist/fields/config/useFilterCapabilities.js +52 -0
- package/dist/fields/config/useFilterCapabilities.js.map +1 -0
- package/dist/fields/readForDocument.js +16 -4
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +36 -0
- package/dist/native/collections/events.js.map +1 -1
- package/dist/native/eventScan.js +25 -0
- package/dist/native/eventScan.js.map +1 -0
- package/dist/native/ingest/browser.js +47 -0
- package/dist/native/ingest/browser.js.map +1 -0
- package/dist/native/ingest/flushBatch.js +26 -26
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/language.js +14 -0
- package/dist/native/ingest/language.js.map +1 -0
- package/dist/native/ingest/normalizeEvent.d.ts +6 -0
- package/dist/native/ingest/normalizeEvent.js +32 -5
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/referrer.js +48 -0
- package/dist/native/ingest/referrer.js.map +1 -0
- package/dist/native/ingest/serverTrack.js +1 -0
- package/dist/native/ingest/serverTrack.js.map +1 -1
- package/dist/native/ingest/source.d.ts +7 -0
- package/dist/native/ingest/source.js +139 -14
- package/dist/native/ingest/source.js.map +1 -1
- package/dist/native/ingest/utm.js +33 -0
- package/dist/native/ingest/utm.js.map +1 -0
- package/dist/native/nativeAdapter.js +32 -26
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +14 -1
- package/dist/native/query/eventAgg.js.map +1 -1
- package/dist/native/rollups/bucketKey.js +15 -0
- package/dist/native/rollups/bucketKey.js.map +1 -0
- package/dist/native/rollups/bumpRollups.js +116 -0
- package/dist/native/rollups/bumpRollups.js.map +1 -0
- package/dist/native/rollups/deltas.js +30 -15
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/native/rollups/insertManyIfNew.js +93 -0
- package/dist/native/rollups/insertManyIfNew.js.map +1 -0
- package/dist/next/captureRewrites.d.ts +3 -2
- package/dist/next/captureRewrites.js +3 -2
- package/dist/next/captureRewrites.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +26 -7
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/goalHint.d.ts +1 -0
- package/dist/plugin/goalHint.js +24 -0
- package/dist/plugin/goalHint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +19 -12
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/realtimeEndpoint.js +40 -15
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/responses.js +17 -0
- package/dist/plugin/responses.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +10 -3
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/collection.js +14 -4
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +4 -2
- package/dist/providers/factory.js.map +1 -1
- package/dist/query/response.d.ts +4 -1
- package/dist/query/response.js +11 -0
- package/dist/query/response.js.map +1 -0
- package/dist/surfacing/engine.js +1 -1
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/testing/memoryAdapter.js +0 -1
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/tracker/createTracker.js +13 -1
- package/dist/tracker/createTracker.js.map +1 -1
- package/dist/tracker/sinks/ga4.d.ts +21 -0
- package/dist/tracker/sinks/ga4.js +26 -0
- package/dist/tracker/sinks/ga4.js.map +1 -0
- package/dist/tracker/types.d.ts +5 -0
- package/dist/translations/ar.js +30 -1
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +30 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +30 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +30 -1
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +30 -1
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +30 -1
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +29 -0
- package/dist/translations/keys.js +30 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +30 -1
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/metricKeys.js +7 -1
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +30 -1
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +30 -1
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/server.js.map +1 -1
- package/dist/translations/uk.js +30 -1
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +30 -1
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/AnalyticsViewClient.js +13 -2
- package/dist/view/AnalyticsViewClient.js.map +1 -1
- package/dist/view/gating.js +40 -3
- package/dist/view/gating.js.map +1 -1
- package/dist/view/labels.js +21 -1
- package/dist/view/labels.js.map +1 -1
- package/dist/view/sections/Breakdowns.js +78 -38
- package/dist/view/sections/Breakdowns.js.map +1 -1
- package/dist/view/sections/FilterChips.js +8 -3
- package/dist/view/sections/FilterChips.js.map +1 -1
- package/dist/view/sections/GoalsPanel.js +2 -1
- package/dist/view/sections/GoalsPanel.js.map +1 -1
- package/dist/view/sections/RealtimeStrip.js +4 -1
- package/dist/view/sections/RealtimeStrip.js.map +1 -1
- package/dist/view/sections/Toolbar.js +10 -3
- package/dist/view/sections/Toolbar.js.map +1 -1
- package/dist/view/sections/Trend.js +8 -2
- package/dist/view/sections/Trend.js.map +1 -1
- package/dist/view/state.js +7 -2
- package/dist/view/state.js.map +1 -1
- package/dist/view/useViewQueries.js +6 -3
- package/dist/view/useViewQueries.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +59 -10
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +10 -2
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +30 -3
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +3 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +30 -3
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/RealtimeCounter.d.ts +4 -0
- package/dist/widgets/RealtimeCounter.js +10 -1
- package/dist/widgets/RealtimeCounter.js.map +1 -1
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/comparison.js +15 -1
- package/dist/widgets/comparison.js.map +1 -1
- package/dist/widgets/defaults.d.ts +6 -2
- package/dist/widgets/defaults.js +72 -25
- package/dist/widgets/defaults.js.map +1 -1
- package/dist/widgets/filterCaption.js +27 -0
- package/dist/widgets/filterCaption.js.map +1 -0
- package/dist/widgets/filterField.d.ts +19 -0
- package/dist/widgets/filterField.js +75 -0
- package/dist/widgets/filterField.js.map +1 -0
- package/dist/widgets/prepareWidgetRead.d.ts +7 -0
- package/dist/widgets/prepareWidgetRead.js +74 -0
- package/dist/widgets/prepareWidgetRead.js.map +1 -0
- package/dist/widgets/readForWidget.d.ts +12 -2
- package/dist/widgets/readForWidget.js +34 -49
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +17 -1
- package/dist/widgets/readForWidgetBreakdown.js +29 -42
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +11 -1
- package/dist/widgets/readForWidgetGoals.js +44 -30
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
- package/dist/widgets/readForWidgetRealtime.js +21 -20
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +11 -1
- package/dist/widgets/readForWidgetSeries.js +38 -49
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/readMeta.js +18 -0
- package/dist/widgets/readMeta.js.map +1 -0
- package/dist/widgets/registerWidgets.js +5 -2
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.d.ts +15 -0
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.js +5 -2
- package/dist/widgets/viewLink.js.map +1 -1
- package/package.json +5 -5
- package/dist/native/rollups/applyDistinctDeltas.js +0 -9
- package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
- package/dist/native/rollups/bumpRollup.js +0 -73
- package/dist/native/rollups/bumpRollup.js.map +0 -1
- package/dist/native/rollups/insertIfNew.js +0 -53
- package/dist/native/rollups/insertIfNew.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readForDocument.js","names":[],"sources":["../../src/fields/readForDocument.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { resolveHostname, resolvePathCached } from '../binding/resolvePath'\nimport type { BindingDoc } from '../binding/types'\nimport { satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, DateRange, MetricKey } from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { previousWindow } from '../widgets/comparison'\nimport { fillDailySeries, type SeriesPoint } from '../widgets/readForWidgetSeries'\n\nexport type FieldReadStatus = 'ok' | 'no-path' | 'not-bound' | 'not-configured' | 'unavailable'\n\nexport interface FieldReadResult {\n\tstatus: FieldReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\t/** The reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tmetrics: Partial<Record<MetricKey, number>>\n\t/** Requested metrics the adapter supports, in request order; the set actually read. */\n\tsupportedMetrics: MetricKey[]\n\t/** Requested metrics the adapter cannot serve, dropped from the read. */\n\tdroppedMetrics: MetricKey[]\n\t/** Previous-window totals, present only when comparison was requested and supported. */\n\tpreviousMetrics?: Partial<Record<MetricKey, number>>\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/** Per-day series for the first supported metric, present only when requested. */\n\tpoints?: SeriesPoint[]\n}\n\nexport interface ReadForFieldArgs {\n\treq: PayloadRequest\n\tcollectionSlug: string\n\tdata: BindingDoc\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\t/** Overrides the preset window (custom range). */\n\trange?: DateRange\n\tadapterId?: string\n\tnow: Date\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\t/** Also read the previous comparable window when the adapter supports comparison. */\n\tcompare?: boolean\n\t/** Also read a daily series for the first supported metric when the adapter can. */\n\tseries?: boolean\n}\n\n/**\n * Resolve a document's analytics for one display field: look up the runtime, resolve\n * the bound path, capability-gate the requested metrics against the active adapter,\n * then read through the surfacing engine. Returns a discriminated status so the\n * rendering component can show the right empty state without throwing.\n *\n * A metric the adapter does not support is dropped (with one warning per field\n * render), not fatal; `unavailable` is returned only when no requested metric\n * survives or the adapter cannot query per page at all.\n */\nexport const readForField = async (args: ReadForFieldArgs): Promise<FieldReadResult> => {\n\tconst { req, collectionSlug, data, metrics, timeframe, range, adapterId, now } = args\n\tlet dateRange = range ?? resolveTimeframe(timeframe, now)\n\tconst empty = { metrics: {}, supportedMetrics: [], droppedMetrics: [] }\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn {\n\t\t\tstatus: 'not-bound',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange,\n\t\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t\t...empty,\n\t\t}\n\t}\n\tconst binding = runtime.bindings[collectionSlug]\n\tif (!binding) {\n\t\treturn {\n\t\t\tstatus: 'not-bound',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange,\n\t\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t\t...empty,\n\t\t}\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange,\n\t\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t\t...empty,\n\t\t}\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tdateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tconst bindingCtx = { req, locale: req.locale ?? undefined }\n\tlet path: string | null\n\ttry {\n\t\tpath = await resolvePathCached(binding, data, bindingCtx)\n\t} catch {\n\t\tpath = null\n\t}\n\tif (!path) {\n\t\treturn { status: 'no-path', adapterId: adapter.id, dateRange, timezone: tz, ...empty }\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, dateRange, timezone: tz, ...empty }\n\t}\n\tconst supportedMetrics = metrics.filter((m) => adapter.capabilities.metrics.has(m))\n\tconst droppedMetrics = metrics.filter((m) => !adapter.capabilities.metrics.has(m))\n\tif (droppedMetrics.length > 0) {\n\t\treq.payload.logger.warn(\n\t\t\t`analytics: adapter \"${adapter.id}\" does not support metric(s) ${droppedMetrics.join(', ')}; dropped from the \"${collectionSlug}\" display field`\n\t\t)\n\t}\n\tif (\n\t\tsupportedMetrics.length === 0 ||\n\t\t!satisfiesCapabilities(adapter.capabilities, { metrics: supportedMetrics, perPageQuery: true })\n\t) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapter.id,\n\t\t\tdateRange,\n\t\t\ttimezone: tz,\n\t\t\tmetrics: {},\n\t\t\tsupportedMetrics: [],\n\t\t\tdroppedMetrics: metrics,\n\t\t}\n\t}\n\tconst hostname = await resolveHostname(binding, data, bindingCtx)\n\tconst base = { path, hostname, timezone: tz, scope: ctx.queryScope }\n\tconst comparisonRange =\n\t\targs.compare && runtime.comparison && adapter.capabilities.comparison\n\t\t\t? (previousWindow(dateRange, tz) ?? undefined)\n\t\t\t: undefined\n\tconst wantsSeries = args.series && supportsGranularity(adapter.capabilities, 'day')\n\tconst [result, previous, seriesResult] = await Promise.all([\n\t\truntime.engine.read(adapter, { ...base, metrics: supportedMetrics, dateRange }),\n\t\tcomparisonRange\n\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t...base,\n\t\t\t\t\tmetrics: supportedMetrics,\n\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t})\n\t\t\t: undefined,\n\t\twantsSeries\n\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t...base,\n\t\t\t\t\tmetrics: [supportedMetrics[0] as MetricKey],\n\t\t\t\t\tdateRange,\n\t\t\t\t\tgranularity: 'day',\n\t\t\t\t})\n\t\t\t: undefined,\n\t])\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tmetrics: result.totals ?? {},\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tpreviousMetrics: previous ? (previous.totals ?? {}) : undefined,\n\t\tcomparisonRange,\n\t\tpoints: seriesResult\n\t\t\t? fillDailySeries({\n\t\t\t\t\trows: seriesResult.rows,\n\t\t\t\t\tdateRange,\n\t\t\t\t\tmetric: supportedMetrics[0] as MetricKey,\n\t\t\t\t\ttz,\n\t\t\t\t})\n\t\t\t: undefined,\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmEA,MAAa,eAAe,OAAO,SAAqD;CACvF,MAAM,EAAE,KAAK,gBAAgB,MAAM,SAAS,WAAW,OAAO,WAAW,QAAQ;CACjF,IAAI,YAAY,SAAS,iBAAiB,WAAW,GAAG;CACxD,MAAM,QAAQ;EAAE,SAAS,CAAC;EAAG,kBAAkB,CAAC;EAAG,gBAAgB,CAAC;CAAE;CACtE,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB;EACA,UAAU,KAAK,YAAA;EACf,GAAG;CACJ;CAED,MAAM,UAAU,QAAQ,SAAS;CACjC,IAAI,CAAC,SACJ,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB;EACA,UAAU,KAAK,YAAA;EACf,GAAG;CACJ;CAED,MAAM,MAAM,MAAM,mBAAmB;EAAE;EAAS;EAAK;EAAW,OAAO,KAAK;CAAM,CAAC;CACnF,IAAI,CAAC,IAAI,IACR,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB;EACA,UAAU,KAAK,YAAA;EACf,GAAG;CACJ;CAED,MAAM,KAAK,KAAK,YAAa,MAAM,mBAAmB,SAAS,KAAK,IAAI,KAAK;CAC7E,YAAY,SAAS,iBAAiB,WAAW,KAAK,EAAE;CACxD,MAAM,UAA4B,IAAI;CACtC,MAA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AK,SAAS;GAAE,GAAG;GAAM,SAAS;GAAkB;EAAU,CAAC;EAC9E,kBACG,QAAQ,OAAO,KAAK,SAAS;GAC7B,GAAG;GACH,SAAS;GACT,WAAW;EACZ,CAAC,IACA,KAAA;EACH,cACG,QAAQ,OAAO,KAAK,SAAS;GAC7B,GAAG;GACH,SAAS,CAAC,iBAAiB,EAAe;GAC1C;GACA,aAAa;EACd,CAAC,IACA,KAAA;CACJ,CAAC;CACD,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,UAAU;EACV,SAAS,OAAO,UAAU,CAAC;EAC3B;EACA;EACA,iBAAiB,WAAY,SAAS,UAAU,CAAC,IAAK,KAAA;EACtD;EACA,QAAQ,eACL,gBAAgB;GAChB,MAAM,aAAa;GACnB;GACA,QAAQ,iBAAiB;GACzB;EACD,CAAC,IACA,KAAA;CACJ;AACD"}
|
|
1
|
+
{"version":3,"file":"readForDocument.js","names":[],"sources":["../../src/fields/readForDocument.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { resolveHostname, resolvePathCached } from '../binding/resolvePath'\nimport type { BindingDoc } from '../binding/types'\nimport { comparisonOf, satisfiesCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter, DateRange, MetricKey } from '../core/contract'\nimport { supportsGranularity } from '../core/granularity'\nimport { resolveReadContext } from '../core/scopedRead'\nimport { goalSlugsFor } from '../plugin/goalHint'\nimport { getRuntime, resolveTimezoneFor } from '../plugin/runtime'\nimport { resolveTimeframe, type TimeframePreset } from '../timeframe/presets'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport { previousWindow, withinLookback } from '../widgets/comparison'\nimport { fillDailySeries, type SeriesPoint } from '../widgets/readForWidgetSeries'\n\nexport type FieldReadStatus = 'ok' | 'no-path' | 'not-bound' | 'not-configured' | 'unavailable'\n\nexport interface FieldReadResult {\n\tstatus: FieldReadStatus\n\tadapterId: string\n\tdateRange: DateRange\n\t/** The reporting timezone the read resolved in; the trend axis buckets in it. */\n\ttimezone: string\n\tmetrics: Partial<Record<MetricKey, number>>\n\t/** Requested metrics the adapter supports, in request order; the set actually read. */\n\tsupportedMetrics: MetricKey[]\n\t/** Requested metrics the adapter cannot serve, dropped from the read. */\n\tdroppedMetrics: MetricKey[]\n\t/** Previous-window totals, present only when comparison was requested and supported. */\n\tpreviousMetrics?: Partial<Record<MetricKey, number>>\n\t/** The previous comparable window, present only when comparison ran. */\n\tcomparisonRange?: DateRange\n\t/** Per-day series for the first supported metric, present only when requested. */\n\tpoints?: SeriesPoint[]\n}\n\nexport interface ReadForFieldArgs {\n\treq: PayloadRequest\n\tcollectionSlug: string\n\tdata: BindingDoc\n\tmetrics: MetricKey[]\n\ttimeframe: TimeframePreset\n\t/** Overrides the preset window (custom range). */\n\trange?: DateRange\n\tadapterId?: string\n\tnow: Date\n\t/** Explicit scope override; omitted resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n\t/**\n\t * Reporting timezone the caller already resolved, reused rather than resolved again so\n\t * a caller-supplied `range` is read in the very timezone it was interpreted in.\n\t */\n\ttimezone?: string\n\t/** Also read the previous comparable window when the adapter supports comparison. */\n\tcompare?: boolean\n\t/** Also read a daily series for the first supported metric when the adapter can. */\n\tseries?: boolean\n}\n\n/**\n * Resolve a document's analytics for one display field: look up the runtime, resolve\n * the bound path, capability-gate the requested metrics against the active adapter,\n * then read through the surfacing engine. Returns a discriminated status so the\n * rendering component can show the right empty state without throwing.\n *\n * A metric the adapter does not support is dropped (with one warning per field\n * render), not fatal; `unavailable` is returned only when no requested metric\n * survives or the adapter cannot query per page at all.\n */\nexport const readForField = async (args: ReadForFieldArgs): Promise<FieldReadResult> => {\n\tconst { req, collectionSlug, data, metrics, timeframe, range, adapterId, now } = args\n\tlet dateRange = range ?? resolveTimeframe(timeframe, now)\n\tconst empty = { metrics: {}, supportedMetrics: [], droppedMetrics: [] }\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn {\n\t\t\tstatus: 'not-bound',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange,\n\t\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t\t...empty,\n\t\t}\n\t}\n\tconst binding = runtime.bindings[collectionSlug]\n\tif (!binding) {\n\t\treturn {\n\t\t\tstatus: 'not-bound',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange,\n\t\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t\t...empty,\n\t\t}\n\t}\n\tconst ctx = await resolveReadContext({ runtime, req, adapterId, scope: args.scope })\n\tif (!ctx.ok) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapterId ?? '',\n\t\t\tdateRange,\n\t\t\ttimezone: args.timezone ?? DEFAULT_TIMEZONE,\n\t\t\t...empty,\n\t\t}\n\t}\n\tconst tz = args.timezone ?? (await resolveTimezoneFor(runtime, req, ctx.scope))\n\tdateRange = range ?? resolveTimeframe(timeframe, now, tz)\n\tconst adapter: AnalyticsAdapter = ctx.adapter\n\tconst bindingCtx = { req, locale: req.locale ?? undefined }\n\tlet path: string | null\n\ttry {\n\t\tpath = await resolvePathCached(binding, data, bindingCtx)\n\t} catch {\n\t\tpath = null\n\t}\n\tif (!path) {\n\t\treturn { status: 'no-path', adapterId: adapter.id, dateRange, timezone: tz, ...empty }\n\t}\n\tif (!adapter.isConfigured()) {\n\t\treturn { status: 'not-configured', adapterId: adapter.id, dateRange, timezone: tz, ...empty }\n\t}\n\tconst supportedMetrics = metrics.filter((m) => adapter.capabilities.metrics.has(m))\n\tconst droppedMetrics = metrics.filter((m) => !adapter.capabilities.metrics.has(m))\n\tif (droppedMetrics.length > 0) {\n\t\treq.payload.logger.warn(\n\t\t\t`analytics: adapter \"${adapter.id}\" does not support metric(s) ${droppedMetrics.join(', ')}; dropped from the \"${collectionSlug}\" display field`\n\t\t)\n\t}\n\tif (\n\t\tsupportedMetrics.length === 0 ||\n\t\t!satisfiesCapabilities(adapter.capabilities, { metrics: supportedMetrics, perPageQuery: true })\n\t) {\n\t\treturn {\n\t\t\tstatus: 'unavailable',\n\t\t\tadapterId: adapter.id,\n\t\t\tdateRange,\n\t\t\ttimezone: tz,\n\t\t\tmetrics: {},\n\t\t\tsupportedMetrics: [],\n\t\t\tdroppedMetrics: metrics,\n\t\t}\n\t}\n\tconst hostname = await resolveHostname(binding, data, bindingCtx)\n\tconst goalSlugs = await goalSlugsFor({\n\t\truntime,\n\t\treq,\n\t\tscope: ctx.scope,\n\t\tmetrics: supportedMetrics,\n\t})\n\tconst base = {\n\t\tpath,\n\t\thostname,\n\t\ttimezone: tz,\n\t\tscope: ctx.queryScope,\n\t\t...(goalSlugs === undefined ? {} : { goalSlugs }),\n\t}\n\tconst previousRange =\n\t\targs.compare && runtime.comparison && comparisonOf(adapter.capabilities)\n\t\t\t? previousWindow(dateRange, tz)\n\t\t\t: null\n\tconst comparisonRange =\n\t\tpreviousRange &&\n\t\twithinLookback(previousRange, adapter.capabilities.maxLookbackDays, { tz, now })\n\t\t\t? previousRange\n\t\t\t: undefined\n\tconst wantsSeries = args.series && supportsGranularity(adapter.capabilities, 'day')\n\tconst [result, previous, seriesResult] = await Promise.all([\n\t\truntime.engine.read(adapter, { ...base, metrics: supportedMetrics, dateRange }),\n\t\tcomparisonRange\n\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t...base,\n\t\t\t\t\tmetrics: supportedMetrics,\n\t\t\t\t\tdateRange: comparisonRange,\n\t\t\t\t})\n\t\t\t: undefined,\n\t\twantsSeries\n\t\t\t? runtime.engine.read(adapter, {\n\t\t\t\t\t...base,\n\t\t\t\t\tmetrics: [supportedMetrics[0] as MetricKey],\n\t\t\t\t\tdateRange,\n\t\t\t\t\tgranularity: 'day',\n\t\t\t\t})\n\t\t\t: undefined,\n\t])\n\treturn {\n\t\tstatus: 'ok',\n\t\tadapterId: adapter.id,\n\t\tdateRange,\n\t\ttimezone: tz,\n\t\tmetrics: result.totals ?? {},\n\t\tsupportedMetrics,\n\t\tdroppedMetrics,\n\t\tpreviousMetrics: previous ? (previous.totals ?? {}) : undefined,\n\t\tcomparisonRange,\n\t\tpoints: seriesResult\n\t\t\t? fillDailySeries({\n\t\t\t\t\trows: seriesResult.rows,\n\t\t\t\t\tdateRange,\n\t\t\t\t\tmetric: supportedMetrics[0] as MetricKey,\n\t\t\t\t\ttz,\n\t\t\t\t})\n\t\t\t: undefined,\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoEA,MAAa,eAAe,OAAO,SAAqD;CACvF,MAAM,EAAE,KAAK,gBAAgB,MAAM,SAAS,WAAW,OAAO,WAAW,QAAQ;CACjF,IAAI,YAAY,SAAS,iBAAiB,WAAW,GAAG;CACxD,MAAM,QAAQ;EAAE,SAAS,CAAC;EAAG,kBAAkB,CAAC;EAAG,gBAAgB,CAAC;CAAE;CACtE,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB;EACA,UAAU,KAAK,YAAA;EACf,GAAG;CACJ;CAED,MAAM,UAAU,QAAQ,SAAS;CACjC,IAAI,CAAC,SACJ,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB;EACA,UAAU,KAAK,YAAA;EACf,GAAG;CACJ;CAED,MAAM,MAAM,MAAM,mBAAmB;EAAE;EAAS;EAAK;EAAW,OAAO,KAAK;CAAM,CAAC;CACnF,IAAI,CAAC,IAAI,IACR,OAAO;EACN,QAAQ;EACR,WAAW,aAAa;EACxB;EACA,UAAU,KAAK,YAAA;EACf,GAAG;CACJ;CAED,MAAM,KAAK,KAAK,YAAa,MAAM,mBAAmB,SAAS,KAAK,IAAI,KAAK;CAC7E,YAAY,SAAS,iBAAiB,WAAW,KAAK,EAAE;CACxD,MAAM,UAA4B,IAAI;CACtC,MAAM,aAAa;EAAE;EAAK,QAAQ,IAAI,UAAU,KAAA;CAAU;CAC1D,IAAI;CACJ,IAAI;EACH,OAAO,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,cAAc,KAAK,UAAU,oBAAoB,QAAQ,cAAc,KAAK;CAClF,MAAM,CAAC,QAAQ,UAAU,gBAAgB,MAAM,QAAQ,IAAI;EAC1D,QAAQ,OAAO,KAAK,SAAS;GAAE,GAAG;GAAM,SAAS;GAAkB;EAAU,CAAC;EAC9E,kBACG,QAAQ,OAAO,KAAK,SAAS;GAC7B,GAAG;GACH,SAAS;GACT,WAAW;EACZ,CAAC,IACA,KAAA;EACH,cACG,QAAQ,OAAO,KAAK,SAAS;GAC7B,GAAG;GACH,SAAS,CAAC,iBAAiB,EAAe;GAC1C;GACA,aAAa;EACd,CAAC,IACA,KAAA;CACJ,CAAC;CACD,OAAO;EACN,QAAQ;EACR,WAAW,QAAQ;EACnB;EACA,UAAU;EACV,SAAS,OAAO,UAAU,CAAC;EAC3B;EACA;EACA,iBAAiB,WAAY,SAAS,UAAU,CAAC,IAAK,KAAA;EACtD;EACA,QAAQ,eACL,gBAAgB;GAChB,MAAM,aAAa;GACnB;GACA,QAAQ,iBAAiB;GACzB;EACD,CAAC,IACA,KAAA;CACJ;AACD"}
|
package/dist/index.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ import { GoalFieldOptions, goalField, goalSlug } from "./goals/goalField.js";
|
|
|
13
13
|
import { GOAL_ACTION_TYPE, GoalActionDefinition, GoalActionRunArgs, TrackGoalActionOptions, trackGoalAction } from "./goals/trackGoalAction.js";
|
|
14
14
|
import { trackServerEvent } from "./native/ingest/serverTrack.js";
|
|
15
15
|
import { analyticsDefaultWidgets } from "./widgets/defaults.js";
|
|
16
|
+
import { WidgetFilter } from "./widgets/types.js";
|
|
17
|
+
import { widgetFilters } from "./widgets/filterField.js";
|
|
16
18
|
|
|
17
19
|
//#region src/index.d.ts
|
|
18
20
|
declare module 'payload' {
|
|
@@ -22,5 +24,5 @@ declare module 'payload' {
|
|
|
22
24
|
}
|
|
23
25
|
declare const analytics: (options: AnalyticsPluginOptions) => import("payload").Plugin;
|
|
24
26
|
//#endregion
|
|
25
|
-
export { type AnalyticsAccessOptions, type AnalyticsBinding, type AnalyticsCaptureOptions, type AnalyticsFieldsOptions, type AnalyticsGoalsCollectionOptions, type AnalyticsGoalsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsReadAccess, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, AnalyticsTrackError, type AnalyticsViewAccess, type AnalyticsViewOptions, type AutoCaptureOptions, type BindingContext, type CaptureConsentOption, type ConsentMode, type ConsentResolver, type CustomWidgetDef, GOAL_ACTION_TYPE, type Goal, type GoalActionDefinition, type GoalActionRunArgs, type GoalFieldOptions, type GoalMatch, type GoalsResponse, type HostnameResolver, PLATFORM_SCOPE, type PathResolver, type PlatformReadAccess, type AnalyticsPluginOptions as PluginOptions, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type QueryError, type QueryErrorCode, type QueryErrorResponse, type QueryResponse, type QuerySourceRef, type ScopeResolver, type ScopesResolver, type SerializedAnalyticsQuery, type ServerEventInput, type ServerTrack, type ServerTrackOptions, type TimeframePreset, type TimezoneResolver, type TrackGoalActionOptions, type TrackerGoal, type WireGoal, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, goalField, goalSlug, trackGoalAction, trackServerEvent };
|
|
27
|
+
export { type AnalyticsAccessOptions, type AnalyticsBinding, type AnalyticsCaptureOptions, type AnalyticsFieldsOptions, type AnalyticsGoalsCollectionOptions, type AnalyticsGoalsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsReadAccess, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, AnalyticsTrackError, type AnalyticsViewAccess, type AnalyticsViewOptions, type AutoCaptureOptions, type BindingContext, type CaptureConsentOption, type ConsentMode, type ConsentResolver, type CustomWidgetDef, GOAL_ACTION_TYPE, type Goal, type GoalActionDefinition, type GoalActionRunArgs, type GoalFieldOptions, type GoalMatch, type GoalsResponse, type HostnameResolver, PLATFORM_SCOPE, type PathResolver, type PlatformReadAccess, type AnalyticsPluginOptions as PluginOptions, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type QueryError, type QueryErrorCode, type QueryErrorResponse, type QueryResponse, type QuerySourceRef, type ScopeResolver, type ScopesResolver, type SerializedAnalyticsQuery, type ServerEventInput, type ServerTrack, type ServerTrackOptions, type TimeframePreset, type TimezoneResolver, type TrackGoalActionOptions, type TrackerGoal, type WidgetFilter, type WireGoal, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, goalField, goalSlug, trackGoalAction, trackServerEvent, widgetFilters };
|
|
26
28
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -26,6 +26,7 @@ import { createEngine } from "./surfacing/engine.js";
|
|
|
26
26
|
import { syncCollection } from "./sync/collection.js";
|
|
27
27
|
import { syncTask } from "./sync/syncTask.js";
|
|
28
28
|
import { registerView } from "./view/registerView.js";
|
|
29
|
+
import { widgetFilters } from "./widgets/filterField.js";
|
|
29
30
|
import { registerWidgets } from "./widgets/registerWidgets.js";
|
|
30
31
|
import { analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField } from "./fields/factories.js";
|
|
31
32
|
import { goalField, goalSlug } from "./goals/goalField.js";
|
|
@@ -258,6 +259,6 @@ const analytics = definePlugin({
|
|
|
258
259
|
}
|
|
259
260
|
});
|
|
260
261
|
//#endregion
|
|
261
|
-
export { AnalyticsTrackError, GOAL_ACTION_TYPE, PLATFORM_SCOPE, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, goalField, goalSlug, trackGoalAction, trackServerEvent };
|
|
262
|
+
export { AnalyticsTrackError, GOAL_ACTION_TYPE, PLATFORM_SCOPE, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField, goalField, goalSlug, trackGoalAction, trackServerEvent, widgetFilters };
|
|
262
263
|
|
|
263
264
|
//# sourceMappingURL=index.js.map
|
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 { proxyEndpoints } from './capture/proxyEndpoint'\nimport { trackerEndpoint } from './capture/trackerEndpoint'\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport { buildGoalsCollection } from './goals/collection'\nimport { GOALS_PATH, makeGoalsHandler } from './goals/goalsEndpoint'\nimport { configGoalsResolver, createGoalsResolver } from './goals/resolver'\nimport { trackServerEvent } from './native/ingest/serverTrack'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeQueryHandler, QUERY_PATH } from './plugin/queryEndpoint'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { validateScopeField } from './plugin/scopeFieldBoot'\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 { registerView } from './view/registerView'\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\t// A tenant's own runtime adapter (providers.collection or providers.resolve) has\n\t\t// capabilities unknown at config time, so it opens the widget/endpoint gates that\n\t\t// otherwise key off the config-adapter capability union.\n\t\tconst providersEnabled =\n\t\t\tresolved.providers.collection.enabled || Boolean(resolved.providers.resolve)\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\t// Config goals are install-wide; the collection resolves per scope and merges over\n\t\t// them behind the same signature, so ingest and the tracker config read one source.\n\t\tconst goalsResolver = resolved.goalsCollection.enabled\n\t\t\t? createGoalsResolver({\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tconfig: resolved.goals,\n\t\t\t\t})\n\t\t\t: configGoalsResolver(resolved.goals)\n\t\tif (resolved.goalsCollection.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tbuildGoalsCollection({\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\taccess: resolved.goalsCollection.access,\n\t\t\t\t\toverrides: resolved.goalsCollection.overrides,\n\t\t\t\t\tonChange: () => goalsResolver.invalidate(),\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\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}\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, {\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tresolveGoals: goalsResolver.resolve,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function') ||\n\t\t\tprovidersEnabled\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\t{ method: 'get', path: GOALS_PATH, handler: makeGoalsHandler() },\n\t\t\t{ method: 'get', path: QUERY_PATH, handler: makeQueryHandler() },\n\t\t]\n\t\t// A runtime provider's capture support is unknown at config time, so providers\n\t\t// alone are enough to mount the proxy; every slot is still resolved per request.\n\t\tif (resolved.adapters.some((a) => a.capture) || providersEnabled) {\n\t\t\tconfig.endpoints = [...config.endpoints, ...proxyEndpoints(), trackerEndpoint()]\n\t\t}\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider = registry.isMultiProvider() || providersEnabled\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tprovidersEnabled,\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\tcomparison: resolved.widgets.comparison,\n\t\t\t\tview:\n\t\t\t\t\tresolved.view === false\n\t\t\t\t\t\t? false\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tpath: resolved.view.path,\n\t\t\t\t\t\t\t\tdefaultRange: resolved.view.defaultRange,\n\t\t\t\t\t\t\t\tdefaultMetric: resolved.view.defaultMetric,\n\t\t\t\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tregisterView(config, { view: resolved.view, pluginOptions: options })\n\t\tif (resolved.cache.warm.enabled) {\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\twarmTask(resolved.cache.warm.cron, defaultLayout, resolved.scopes),\n\t\t\t\t],\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\tscopes: resolved.scopes,\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\t// Host-owned scope fields only exist once every plugin has run, so the collections\n\t\t\t// are checked against the assembled config rather than at config time.\n\t\t\tif (resolved.scoped && resolved.goalsCollection.enabled) {\n\t\t\t\tvalidateScopeField(payload, {\n\t\t\t\t\toption: 'goals.collection.scopeField',\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (resolved.scoped && resolved.providers.collection.enabled) {\n\t\t\t\tvalidateScopeField(payload, {\n\t\t\t\t\toption: 'providers.collection.scopeField',\n\t\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\t})\n\t\t\t}\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\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\tpayload.logger?.warn(`analytics: read failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\t\t\t},\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\tcaptureSlots: resolved.capture.slots,\n\t\t\t\tcapturePaths: resolved.capture.paths,\n\t\t\t\tcaptureProxy: resolved.capture.proxy,\n\t\t\t\tconsentFor: resolved.capture.consent,\n\t\t\t\tautoCapture: resolved.capture.autoCapture,\n\t\t\t\tgoals: resolved.goals,\n\t\t\t\tresolveGoals: goalsResolver.resolve,\n\t\t\t\tresolveGoalsDetailed: goalsResolver.resolveDetailed,\n\t\t\t\t...(resolved.goalsCollection.enabled\n\t\t\t\t\t? { goalsCollectionSlug: resolved.goalsCollection.slug }\n\t\t\t\t\t: {}),\n\t\t\t\tingestPath: resolved.adapters.find((a) => a.ingest)?.ingest?.path,\n\t\t\t\ttrack: (event, opts) => trackServerEvent(payload, event, opts),\n\t\t\t\tscoped: resolved.scoped,\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\treadAccess: resolved.access.read,\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\tAnalyticsCaptureOptions,\n\tAnalyticsGoalsCollectionOptions,\n\tAnalyticsGoalsOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tAnalyticsReadAccess,\n\tAnalyticsViewAccess,\n\tAnalyticsViewOptions,\n\tAutoCaptureOptions,\n\tCaptureConsentOption,\n\tConsentMode,\n\tConsentResolver,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tScopesResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type { ServerEventInput, ServerTrack, ServerTrackOptions } from './core/serverEvent'\nexport { AnalyticsTrackError } from './core/serverEvent'\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 { GoalFieldOptions } from './goals/goalField'\nexport { goalField, goalSlug } from './goals/goalField'\nexport type { GoalsResponse, WireGoal } from './goals/goalsEndpoint'\nexport type {\n\tGoalActionDefinition,\n\tGoalActionRunArgs,\n\tTrackGoalActionOptions,\n} from './goals/trackGoalAction'\nexport { GOAL_ACTION_TYPE, trackGoalAction } from './goals/trackGoalAction'\nexport type { Goal, GoalMatch, TrackerGoal } from './goals/types'\nexport { trackServerEvent } from './native/ingest/serverTrack'\nexport type { QueryError, QueryErrorCode } from './query/errors'\nexport type {\n\tQueryErrorResponse,\n\tQueryResponse,\n\tQuerySourceRef,\n\tSerializedAnalyticsQuery,\n} from './query/response'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,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;EAIvC,MAAM,mBACL,SAAS,UAAU,WAAW,WAAW,QAAQ,SAAS,UAAU,OAAO;EAC5E,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,QAA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AE,CAAC;IAC5D,cAAc,SAAS,OAAO;IAC9B,YAAY,SAAS,OAAO;IAC5B,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 { proxyEndpoints } from './capture/proxyEndpoint'\nimport { trackerEndpoint } from './capture/trackerEndpoint'\nimport { type AnalyticsPluginOptions, resolveOptions } from './core/options'\nimport { createRegistry, staticRegistryResolver } from './core/registry'\nimport { buildGoalsCollection } from './goals/collection'\nimport { GOALS_PATH, makeGoalsHandler } from './goals/goalsEndpoint'\nimport { configGoalsResolver, createGoalsResolver } from './goals/resolver'\nimport { trackServerEvent } from './native/ingest/serverTrack'\nimport { DOCUMENT_PATH, makeDocumentHandler } from './plugin/documentEndpoint'\nimport { isModuleNotFoundError } from './plugin/peerImportError'\nimport { makeQueryHandler, QUERY_PATH } from './plugin/queryEndpoint'\nimport { makeRealtimeHandler, REALTIME_PATH } from './plugin/realtimeEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { setRuntime } from './plugin/runtime'\nimport { validateScopeField } from './plugin/scopeFieldBoot'\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 { registerView } from './view/registerView'\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\t// A tenant's own runtime adapter (providers.collection or providers.resolve) has\n\t\t// capabilities unknown at config time, so it opens the widget/endpoint gates that\n\t\t// otherwise key off the config-adapter capability union.\n\t\tconst providersEnabled =\n\t\t\tresolved.providers.collection.enabled || Boolean(resolved.providers.resolve)\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\t// Config goals are install-wide; the collection resolves per scope and merges over\n\t\t// them behind the same signature, so ingest and the tracker config read one source.\n\t\tconst goalsResolver = resolved.goalsCollection.enabled\n\t\t\t? createGoalsResolver({\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tconfig: resolved.goals,\n\t\t\t\t})\n\t\t\t: configGoalsResolver(resolved.goals)\n\t\tif (resolved.goalsCollection.enabled) {\n\t\t\tconfig.collections = [\n\t\t\t\t...(config.collections ?? []),\n\t\t\t\tbuildGoalsCollection({\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\taccess: resolved.goalsCollection.access,\n\t\t\t\t\toverrides: resolved.goalsCollection.overrides,\n\t\t\t\t\tonChange: () => goalsResolver.invalidate(),\n\t\t\t\t\tscoped: resolved.scoped,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\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}\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, {\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tresolveScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tresolveGoals: goalsResolver.resolve,\n\t\t\t})\n\t\t}\n\t\tif (\n\t\t\tresolved.adapters.some((a) => a.capabilities.realtime && typeof a.realtime === 'function') ||\n\t\t\tprovidersEnabled\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\t{ method: 'get', path: GOALS_PATH, handler: makeGoalsHandler() },\n\t\t\t{ method: 'get', path: QUERY_PATH, handler: makeQueryHandler() },\n\t\t]\n\t\t// A runtime provider's capture support is unknown at config time, so providers\n\t\t// alone are enough to mount the proxy; every slot is still resolved per request.\n\t\tif (resolved.adapters.some((a) => a.capture) || providersEnabled) {\n\t\t\tconfig.endpoints = [...config.endpoints, ...proxyEndpoints(), trackerEndpoint()]\n\t\t}\n\t\tif (resolved.widgets.enabled) {\n\t\t\tconst multiProvider = registry.isMultiProvider() || providersEnabled\n\t\t\tregisterWidgets(config, {\n\t\t\t\tadapters: resolved.adapters,\n\t\t\t\tmultiProvider,\n\t\t\t\tprovidersEnabled,\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\tcomparison: resolved.widgets.comparison,\n\t\t\t\tview:\n\t\t\t\t\tresolved.view === false\n\t\t\t\t\t\t? false\n\t\t\t\t\t\t: {\n\t\t\t\t\t\t\t\tpath: resolved.view.path,\n\t\t\t\t\t\t\t\tdefaultRange: resolved.view.defaultRange,\n\t\t\t\t\t\t\t\tdefaultMetric: resolved.view.defaultMetric,\n\t\t\t\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tregisterView(config, { view: resolved.view, pluginOptions: options })\n\t\tif (resolved.cache.warm.enabled) {\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\twarmTask(resolved.cache.warm.cron, defaultLayout, resolved.scopes),\n\t\t\t\t],\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\tscopes: resolved.scopes,\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\t// Host-owned scope fields only exist once every plugin has run, so the collections\n\t\t\t// are checked against the assembled config rather than at config time.\n\t\t\tif (resolved.scoped && resolved.goalsCollection.enabled) {\n\t\t\t\tvalidateScopeField(payload, {\n\t\t\t\t\toption: 'goals.collection.scopeField',\n\t\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (resolved.scoped && resolved.providers.collection.enabled) {\n\t\t\t\tvalidateScopeField(payload, {\n\t\t\t\t\toption: 'providers.collection.scopeField',\n\t\t\t\t\tslug: resolved.providers.collection.slug,\n\t\t\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t\t\t})\n\t\t\t}\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\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\tpayload.logger?.warn(`analytics: read failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\t\t\t},\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\tcaptureSlots: resolved.capture.slots,\n\t\t\t\tcapturePaths: resolved.capture.paths,\n\t\t\t\tcaptureProxy: resolved.capture.proxy,\n\t\t\t\tconsentFor: resolved.capture.consent,\n\t\t\t\tautoCapture: resolved.capture.autoCapture,\n\t\t\t\tgoals: resolved.goals,\n\t\t\t\tresolveGoals: goalsResolver.resolve,\n\t\t\t\tresolveGoalsDetailed: goalsResolver.resolveDetailed,\n\t\t\t\t...(resolved.goalsCollection.enabled\n\t\t\t\t\t? { goalsCollectionSlug: resolved.goalsCollection.slug }\n\t\t\t\t\t: {}),\n\t\t\t\tingestPath: resolved.adapters.find((a) => a.ingest)?.ingest?.path,\n\t\t\t\ttrack: (event, opts) => trackServerEvent(payload, event, opts),\n\t\t\t\tscoped: resolved.scoped,\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\treadAccess: resolved.access.read,\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\tAnalyticsCaptureOptions,\n\tAnalyticsGoalsCollectionOptions,\n\tAnalyticsGoalsOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tAnalyticsReadAccess,\n\tAnalyticsViewAccess,\n\tAnalyticsViewOptions,\n\tAutoCaptureOptions,\n\tCaptureConsentOption,\n\tConsentMode,\n\tConsentResolver,\n\tPlatformReadAccess,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tScopeResolver,\n\tScopesResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type { ServerEventInput, ServerTrack, ServerTrackOptions } from './core/serverEvent'\nexport { AnalyticsTrackError } from './core/serverEvent'\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 { GoalFieldOptions } from './goals/goalField'\nexport { goalField, goalSlug } from './goals/goalField'\nexport type { GoalsResponse, WireGoal } from './goals/goalsEndpoint'\nexport type {\n\tGoalActionDefinition,\n\tGoalActionRunArgs,\n\tTrackGoalActionOptions,\n} from './goals/trackGoalAction'\nexport { GOAL_ACTION_TYPE, trackGoalAction } from './goals/trackGoalAction'\nexport type { Goal, GoalMatch, TrackerGoal } from './goals/types'\nexport { trackServerEvent } from './native/ingest/serverTrack'\nexport type { QueryError, QueryErrorCode } from './query/errors'\nexport type {\n\tQueryErrorResponse,\n\tQueryResponse,\n\tQuerySourceRef,\n\tSerializedAnalyticsQuery,\n} from './query/response'\nexport type { TimeframePreset } from './timeframe/presets'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\nexport { widgetFilters } from './widgets/filterField'\nexport type { WidgetFilter } from './widgets/types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,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;EAIvC,MAAM,mBACL,SAAS,UAAU,WAAW,WAAW,QAAQ,SAAS,UAAU,OAAO;EAC5E,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;G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OAAO,SAAS,iBAAiB,SAAS,OAAO,IAAI;IAC7D,QAAQ,SAAS;IACjB,kBAAkB,IAAI,IAAI,SAAS,SAAS,KAAK,MAAM,EAAE,EAAE,CAAC;IAC5D,cAAc,SAAS,OAAO;IAC9B,YAAY,SAAS,OAAO;IAC5B,UAAU,SAAS;IACnB;IACA,KAAK,SAAS,MAAM;IACpB,YAAY,SAAS,QAAQ;GAC9B,CAAC;GACD,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC"}
|
|
@@ -51,14 +51,46 @@ const eventsCollection = (scoped = false) => ({
|
|
|
51
51
|
name: "referrer",
|
|
52
52
|
type: "text"
|
|
53
53
|
},
|
|
54
|
+
{
|
|
55
|
+
name: "referrerHost",
|
|
56
|
+
type: "text"
|
|
57
|
+
},
|
|
54
58
|
{
|
|
55
59
|
name: "device",
|
|
56
60
|
type: "text"
|
|
57
61
|
},
|
|
62
|
+
{
|
|
63
|
+
name: "browser",
|
|
64
|
+
type: "text"
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
name: "os",
|
|
68
|
+
type: "text"
|
|
69
|
+
},
|
|
58
70
|
{
|
|
59
71
|
name: "source",
|
|
60
72
|
type: "text"
|
|
61
73
|
},
|
|
74
|
+
{
|
|
75
|
+
name: "utmSource",
|
|
76
|
+
type: "text"
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
name: "utmMedium",
|
|
80
|
+
type: "text"
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
name: "utmCampaign",
|
|
84
|
+
type: "text"
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
name: "utmContent",
|
|
88
|
+
type: "text"
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: "utmTerm",
|
|
92
|
+
type: "text"
|
|
93
|
+
},
|
|
62
94
|
{
|
|
63
95
|
name: "country",
|
|
64
96
|
type: "text"
|
|
@@ -71,6 +103,10 @@ const eventsCollection = (scoped = false) => ({
|
|
|
71
103
|
name: "city",
|
|
72
104
|
type: "text"
|
|
73
105
|
},
|
|
106
|
+
{
|
|
107
|
+
name: "language",
|
|
108
|
+
type: "text"
|
|
109
|
+
},
|
|
74
110
|
{
|
|
75
111
|
name: "visitorHash",
|
|
76
112
|
type: "text",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.js","names":[],"sources":["../../../src/native/collections/events.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const EVENTS_SLUG = 'analytics-events'\n\n/**\n * The scope column exists only for scoped installs (a configured scopeResolver);\n * enabling scope on an existing native install therefore needs a migration adding\n * the column to events and rollups.\n */\nexport const eventsCollection = (scoped = false): CollectionConfig => ({\n\tslug: EVENTS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => false, delete: () => false },\n\tfields: [\n\t\t{ name: 'timestamp', type: 'date', required: true, index: true },\n\t\t{\n\t\t\tname: 'type',\n\t\t\ttype: 'select',\n\t\t\trequired: true,\n\t\t\toptions: ['pageview', 'event', 'goal'],\n\t\t\tindex: true,\n\t\t},\n\t\t{ name: 'name', type: 'text' },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'hostname', type: 'text', required: true },\n\t\t{ name: 'referrer', type: 'text' },\n\t\t{ name: 'device', type: 'text' },\n\t\t{ name: 'source', type: 'text' },\n\t\t{ name: 'country', type: 'text' },\n\t\t{ name: 'region', type: 'text' },\n\t\t{ name: 'city', type: 'text' },\n\t\t{ name: 'visitorHash', type: 'text', required: true, index: true },\n\t\t{ name: 'sessionId', type: 'text', required: true, index: true },\n\t\t{ name: 'durationMs', type: 'number' },\n\t\t{ name: 'props', type: 'json' },\n\t\t{ name: 'value', type: 'number' },\n\t\t{ name: 'currency', type: 'text' },\n\t\t{ name: 'scrollDepth', type: 'number' },\n\t\t// The completions matched at ingest, so a raw-event read (filtered or hourly) reports\n\t\t// the same conversions the rollups hold instead of re-matching against goals that may\n\t\t// since have changed.\n\t\t{ name: 'goals', type: 'json' },\n\t\t...(scoped ? [{ name: 'scope', type: 'text', index: true } satisfies Field] : []),\n\t],\n\tindexes: [{ fields: ['path', 'timestamp'] }, { fields: ['type', 'timestamp'] }],\n})\n"],"mappings":";AAEA,MAAa,cAAc;;;;;;AAO3B,MAAa,oBAAoB,SAAS,WAA6B;CACtE,MAAM;CACN,OAAO,EAAE,QAAQ,KAAK;CACtB,QAAQ;EAAE,YAAY;EAAO,cAAc;EAAM,cAAc;EAAO,cAAc;CAAM;CAC1F,QAAQ;EACP;GAAE,MAAM;GAAa,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC/D;GACC,MAAM;GACN,MAAM;GACN,UAAU;GACV,SAAS;IAAC;IAAY;IAAS;GAAM;GACrC,OAAO;EACR;EACA;GAAE,MAAM;GAAQ,MAAM;EAAO;EAC7B;GAAE,MAAM;GAAQ,MAAM;GAAQ,UAAU;GAAM,OAAO;EAAK;EAC1D;GAAE,MAAM;GAAY,MAAM;GAAQ,UAAU;EAAK;EACjD;GAAE,MAAM;GAAY,MAAM;EAAO;
|
|
1
|
+
{"version":3,"file":"events.js","names":[],"sources":["../../../src/native/collections/events.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\nexport const EVENTS_SLUG = 'analytics-events'\n\n/**\n * The scope column exists only for scoped installs (a configured scopeResolver);\n * enabling scope on an existing native install therefore needs a migration adding\n * the column to events and rollups.\n */\nexport const eventsCollection = (scoped = false): CollectionConfig => ({\n\tslug: EVENTS_SLUG,\n\tadmin: { hidden: true },\n\taccess: { read: () => false, create: () => true, update: () => false, delete: () => false },\n\tfields: [\n\t\t{ name: 'timestamp', type: 'date', required: true, index: true },\n\t\t{\n\t\t\tname: 'type',\n\t\t\ttype: 'select',\n\t\t\trequired: true,\n\t\t\toptions: ['pageview', 'event', 'goal'],\n\t\t\tindex: true,\n\t\t},\n\t\t{ name: 'name', type: 'text' },\n\t\t{ name: 'path', type: 'text', required: true, index: true },\n\t\t{ name: 'hostname', type: 'text', required: true },\n\t\t{ name: 'referrer', type: 'text' },\n\t\t// Derived from the referrer at ingest: the `referrer` dimension groups and filters on the\n\t\t// bare host, which a read-time `where` could not compute.\n\t\t{ name: 'referrerHost', type: 'text' },\n\t\t{ name: 'device', type: 'text' },\n\t\t{ name: 'browser', type: 'text' },\n\t\t{ name: 'os', type: 'text' },\n\t\t{ name: 'source', type: 'text' },\n\t\t// Extracted from the pageview's query string at ingest; the raw query is never stored.\n\t\t{ name: 'utmSource', type: 'text' },\n\t\t{ name: 'utmMedium', type: 'text' },\n\t\t{ name: 'utmCampaign', type: 'text' },\n\t\t{ name: 'utmContent', type: 'text' },\n\t\t{ name: 'utmTerm', type: 'text' },\n\t\t{ name: 'country', type: 'text' },\n\t\t{ name: 'region', type: 'text' },\n\t\t{ name: 'city', type: 'text' },\n\t\t{ name: 'language', type: 'text' },\n\t\t{ name: 'visitorHash', type: 'text', required: true, index: true },\n\t\t{ name: 'sessionId', type: 'text', required: true, index: true },\n\t\t{ name: 'durationMs', type: 'number' },\n\t\t{ name: 'props', type: 'json' },\n\t\t{ name: 'value', type: 'number' },\n\t\t{ name: 'currency', type: 'text' },\n\t\t{ name: 'scrollDepth', type: 'number' },\n\t\t// The completions matched at ingest, so a raw-event read (filtered or hourly) reports\n\t\t// the same conversions the rollups hold instead of re-matching against goals that may\n\t\t// since have changed.\n\t\t{ name: 'goals', type: 'json' },\n\t\t...(scoped ? [{ name: 'scope', type: 'text', index: true } satisfies Field] : []),\n\t],\n\tindexes: [{ fields: ['path', 'timestamp'] }, { fields: ['type', 'timestamp'] }],\n})\n"],"mappings":";AAEA,MAAa,cAAc;;;;;;AAO3B,MAAa,oBAAoB,SAAS,WAA6B;CACtE,MAAM;CACN,OAAO,EAAE,QAAQ,KAAK;CACtB,QAAQ;EAAE,YAAY;EAAO,cAAc;EAAM,cAAc;EAAO,cAAc;CAAM;CAC1F,QAAQ;EACP;GAAE,MAAM;GAAa,MAAM;GAAQ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iB,IAAI,CAAC;CAChF;CACA,SAAS,CAAC,EAAE,QAAQ,CAAC,QAAQ,WAAW,EAAE,GAAG,EAAE,QAAQ,CAAC,QAAQ,WAAW,EAAE,CAAC;AAC/E"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/native/eventScan.ts
|
|
2
|
+
/**
|
|
3
|
+
* Hard cap on how many raw events a single read scans. Reads that cannot use the day
|
|
4
|
+
* bucketed rollups (filtered, hour granularity, realtime) walk events newest-first under
|
|
5
|
+
* this cap, so a very busy site keeps its most recent activity rather than its oldest.
|
|
6
|
+
*/
|
|
7
|
+
const EVENT_SCAN_LIMIT = 5e4;
|
|
8
|
+
/**
|
|
9
|
+
* Meta for a read that aggregated raw events under the scan cap. A scan that came back
|
|
10
|
+
* full almost certainly left events behind, so its numbers are a floor rather than a
|
|
11
|
+
* count and `sampled` tells every surface to say so.
|
|
12
|
+
*/
|
|
13
|
+
const eventScanMeta = (args) => {
|
|
14
|
+
const meta = {
|
|
15
|
+
provider: "native",
|
|
16
|
+
fetchedAt: args.fetchedAt
|
|
17
|
+
};
|
|
18
|
+
if (args.clamped) meta.clamped = true;
|
|
19
|
+
if (args.eventCount >= (args.limit ?? 5e4)) meta.sampled = true;
|
|
20
|
+
return meta;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { EVENT_SCAN_LIMIT, eventScanMeta };
|
|
24
|
+
|
|
25
|
+
//# sourceMappingURL=eventScan.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"eventScan.js","names":[],"sources":["../../src/native/eventScan.ts"],"sourcesContent":["import type { AnalyticsResult } from '../core/contract'\n\n/**\n * Hard cap on how many raw events a single read scans. Reads that cannot use the day\n * bucketed rollups (filtered, hour granularity, realtime) walk events newest-first under\n * this cap, so a very busy site keeps its most recent activity rather than its oldest.\n */\nexport const EVENT_SCAN_LIMIT = 50_000\n\nexport interface EventScanMetaArgs {\n\tfetchedAt: string\n\t/** How many events the capped scan came back with. */\n\teventCount: number\n\tclamped?: boolean\n\tlimit?: number\n}\n\n/**\n * Meta for a read that aggregated raw events under the scan cap. A scan that came back\n * full almost certainly left events behind, so its numbers are a floor rather than a\n * count and `sampled` tells every surface to say so.\n */\nexport const eventScanMeta = (args: EventScanMetaArgs): AnalyticsResult['meta'] => {\n\tconst meta: AnalyticsResult['meta'] = { provider: 'native', fetchedAt: args.fetchedAt }\n\tif (args.clamped) {\n\t\tmeta.clamped = true\n\t}\n\tif (args.eventCount >= (args.limit ?? EVENT_SCAN_LIMIT)) {\n\t\tmeta.sampled = true\n\t}\n\treturn meta\n}\n"],"mappings":";;;;;;AAOA,MAAa,mBAAmB;;;;;;AAehC,MAAa,iBAAiB,SAAqD;CAClF,MAAM,OAAgC;EAAE,UAAU;EAAU,WAAW,KAAK;CAAU;CACtF,IAAI,KAAK,SACR,KAAK,UAAU;CAEhB,IAAI,KAAK,eAAe,KAAK,SAAA,MAC5B,KAAK,UAAU;CAEhB,OAAO;AACR"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import "./device.js";
|
|
2
|
+
//#region src/native/ingest/browser.ts
|
|
3
|
+
/**
|
|
4
|
+
* Order is the whole algorithm: every Chromium fork still calls itself Chrome, and every iOS
|
|
5
|
+
* browser still calls itself Safari, so the fork has to be recognized before the engine it
|
|
6
|
+
* borrowed the token from.
|
|
7
|
+
*/
|
|
8
|
+
const BROWSERS = [
|
|
9
|
+
[/edg(?:a|ios|e)?\//, "edge"],
|
|
10
|
+
[/\bopr\/|\bopt\/|\bopera\b/, "opera"],
|
|
11
|
+
[/samsungbrowser/, "samsung"],
|
|
12
|
+
[/firefox\/|fxios\//, "firefox"],
|
|
13
|
+
[/chrome\/|crios\/|chromium\//, "chrome"],
|
|
14
|
+
[/safari\//, "safari"]
|
|
15
|
+
];
|
|
16
|
+
/**
|
|
17
|
+
* `CrOS` and `Android` both sit inside an `X11`/`Linux` UA, so they are matched ahead of it.
|
|
18
|
+
* `cros` needs its word boundaries: it is also a substring of `Microsoft`.
|
|
19
|
+
*/
|
|
20
|
+
const PLATFORMS = [
|
|
21
|
+
[/iphone|ipad|ipod/, "ios"],
|
|
22
|
+
[/android/, "android"],
|
|
23
|
+
[/\bcros\b/, "chromeos"],
|
|
24
|
+
[/windows|win64|win32/, "windows"],
|
|
25
|
+
[/macintosh|mac os x/, "macos"],
|
|
26
|
+
[/linux|x11/, "linux"]
|
|
27
|
+
];
|
|
28
|
+
const lookup = (table, ua, fallback) => {
|
|
29
|
+
if (ua === "analytics-server") return;
|
|
30
|
+
const s = ua.toLowerCase();
|
|
31
|
+
return table.find(([pattern]) => pattern.test(s))?.[1] ?? fallback;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Coarse browser family from a user-agent string, `other` for anything unrecognized (a bot,
|
|
35
|
+
* a crawler, an HTTP client), and undefined when the agent is the synthetic server one so
|
|
36
|
+
* server events abstain from the browser breakdown rather than skewing it.
|
|
37
|
+
*/
|
|
38
|
+
const classifyBrowser = (ua) => lookup(BROWSERS, ua, "other");
|
|
39
|
+
/**
|
|
40
|
+
* Operating system from a user-agent's platform tokens, on the same terms as
|
|
41
|
+
* `classifyBrowser`: `other` when nothing matches, undefined for the server agent.
|
|
42
|
+
*/
|
|
43
|
+
const classifyOs = (ua) => lookup(PLATFORMS, ua, "other");
|
|
44
|
+
//#endregion
|
|
45
|
+
export { classifyBrowser, classifyOs };
|
|
46
|
+
|
|
47
|
+
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.js","names":[],"sources":["../../../src/native/ingest/browser.ts"],"sourcesContent":["import { SERVER_USER_AGENT } from './device'\n\nexport type BrowserName = 'chrome' | 'safari' | 'firefox' | 'edge' | 'opera' | 'samsung' | 'other'\n\nexport type OsName = 'ios' | 'android' | 'windows' | 'macos' | 'linux' | 'chromeos' | 'other'\n\n/**\n * Order is the whole algorithm: every Chromium fork still calls itself Chrome, and every iOS\n * browser still calls itself Safari, so the fork has to be recognized before the engine it\n * borrowed the token from.\n */\nconst BROWSERS: ReadonlyArray<[RegExp, BrowserName]> = [\n\t[/edg(?:a|ios|e)?\\//, 'edge'],\n\t[/\\bopr\\/|\\bopt\\/|\\bopera\\b/, 'opera'],\n\t[/samsungbrowser/, 'samsung'],\n\t[/firefox\\/|fxios\\//, 'firefox'],\n\t[/chrome\\/|crios\\/|chromium\\//, 'chrome'],\n\t[/safari\\//, 'safari'],\n]\n\n/**\n * `CrOS` and `Android` both sit inside an `X11`/`Linux` UA, so they are matched ahead of it.\n * `cros` needs its word boundaries: it is also a substring of `Microsoft`.\n */\nconst PLATFORMS: ReadonlyArray<[RegExp, OsName]> = [\n\t[/iphone|ipad|ipod/, 'ios'],\n\t[/android/, 'android'],\n\t[/\\bcros\\b/, 'chromeos'],\n\t[/windows|win64|win32/, 'windows'],\n\t[/macintosh|mac os x/, 'macos'],\n\t[/linux|x11/, 'linux'],\n]\n\nconst lookup = <T>(table: ReadonlyArray<[RegExp, T]>, ua: string, fallback: T): T | undefined => {\n\tif (ua === SERVER_USER_AGENT) {\n\t\treturn undefined\n\t}\n\tconst s = ua.toLowerCase()\n\treturn table.find(([pattern]) => pattern.test(s))?.[1] ?? fallback\n}\n\n/**\n * Coarse browser family from a user-agent string, `other` for anything unrecognized (a bot,\n * a crawler, an HTTP client), and undefined when the agent is the synthetic server one so\n * server events abstain from the browser breakdown rather than skewing it.\n */\nexport const classifyBrowser = (ua: string): BrowserName | undefined =>\n\tlookup(BROWSERS, ua, 'other')\n\n/**\n * Operating system from a user-agent's platform tokens, on the same terms as\n * `classifyBrowser`: `other` when nothing matches, undefined for the server agent.\n */\nexport const classifyOs = (ua: string): OsName | undefined => lookup(PLATFORMS, ua, 'other')\n"],"mappings":";;;;;;;AAWA,MAAM,WAAiD;CACtD,CAAC,qBAAqB,MAAM;CAC5B,CAAC,6BAA6B,OAAO;CACrC,CAAC,kBAAkB,SAAS;CAC5B,CAAC,qBAAqB,SAAS;CAC/B,CAAC,+BAA+B,QAAQ;CACxC,CAAC,YAAY,QAAQ;AACtB;;;;;AAMA,MAAM,YAA6C;CAClD,CAAC,oBAAoB,KAAK;CAC1B,CAAC,WAAW,SAAS;CACrB,CAAC,YAAY,UAAU;CACvB,CAAC,uBAAuB,SAAS;CACjC,CAAC,sBAAsB,OAAO;CAC9B,CAAC,aAAa,OAAO;AACtB;AAEA,MAAM,UAAa,OAAmC,IAAY,aAA+B;CAChG,IAAI,OAAA,oBACH;CAED,MAAM,IAAI,GAAG,YAAY;CACzB,OAAO,MAAM,MAAM,CAAC,aAAa,QAAQ,KAAK,CAAC,CAAC,IAAI,MAAM;AAC3D;;;;;;AAOA,MAAa,mBAAmB,OAC/B,OAAO,UAAU,IAAI,OAAO;;;;;AAM7B,MAAa,cAAc,OAAmC,OAAO,WAAW,IAAI,OAAO"}
|
|
@@ -1,10 +1,18 @@
|
|
|
1
|
-
import "../collections/seen.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { bucketKey } from "../rollups/applyDistinctDeltas.js";
|
|
1
|
+
import { SEEN_SLUG } from "../collections/seen.js";
|
|
2
|
+
import { bucketKey } from "../rollups/bucketKey.js";
|
|
3
|
+
import { bumpRollups } from "../rollups/bumpRollups.js";
|
|
5
4
|
import { computeRollupDeltas } from "../rollups/deltas.js";
|
|
5
|
+
import { insertManyIfNew } from "../rollups/insertManyIfNew.js";
|
|
6
6
|
import { writeEvent } from "./writeEvent.js";
|
|
7
7
|
//#region src/native/ingest/flushBatch.ts
|
|
8
|
+
/**
|
|
9
|
+
* Coalesces a batch of events into the fewest writes: events insert concurrently, base rollup
|
|
10
|
+
* increments are summed per bucket, and distinct visitor / session candidates are de-duplicated
|
|
11
|
+
* within the batch before one insert-if-new decides which of them the ledger had not seen.
|
|
12
|
+
* Whatever the batch size, that is three round trips for the rollups and the ledger rather
|
|
13
|
+
* than one per bucket. Correctness matches the per-event path because the seen ledger still
|
|
14
|
+
* de-dupes across batches, and its unique index still arbitrates between concurrent writers.
|
|
15
|
+
*/
|
|
8
16
|
async function flushBatch(payload, events) {
|
|
9
17
|
if (events.length === 0) return;
|
|
10
18
|
await Promise.all(events.map((event) => writeEvent(payload, event)));
|
|
@@ -29,30 +37,22 @@ async function flushBatch(payload, events) {
|
|
|
29
37
|
value: event.sessionId
|
|
30
38
|
});
|
|
31
39
|
}
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const entry = distinct.get(dk);
|
|
44
|
-
if (entry) entry.count += 1;
|
|
45
|
-
else distinct.set(dk, {
|
|
40
|
+
await bumpRollups(payload, [...base.values()]);
|
|
41
|
+
const pending = [...candidates.values()];
|
|
42
|
+
const isNew = await insertManyIfNew(payload, SEEN_SLUG, pending.map((candidate) => ({
|
|
43
|
+
bucket: bucketKey(candidate.key),
|
|
44
|
+
kind: candidate.kind,
|
|
45
|
+
value: candidate.value,
|
|
46
|
+
period: candidate.key.period
|
|
47
|
+
})));
|
|
48
|
+
const distinct = [];
|
|
49
|
+
pending.forEach((candidate, index) => {
|
|
50
|
+
if (isNew[index]) distinct.push({
|
|
46
51
|
key: candidate.key,
|
|
47
|
-
|
|
48
|
-
count: 1
|
|
52
|
+
inc: candidate.kind === "visitor" ? { visitors: 1 } : { sessions: 1 }
|
|
49
53
|
});
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const inc = {};
|
|
53
|
-
inc[entry.metric] = entry.count;
|
|
54
|
-
await bumpRollup(payload, entry.key, inc);
|
|
55
|
-
}
|
|
54
|
+
});
|
|
55
|
+
await bumpRollups(payload, distinct);
|
|
56
56
|
}
|
|
57
57
|
//#endregion
|
|
58
58
|
export { flushBatch };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flushBatch.js","names":[],"sources":["../../../src/native/ingest/flushBatch.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { SEEN_SLUG } from '../collections/seen'\nimport { bucketKey } from '../rollups/
|
|
1
|
+
{"version":3,"file":"flushBatch.js","names":[],"sources":["../../../src/native/ingest/flushBatch.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport { SEEN_SLUG } from '../collections/seen'\nimport { bucketKey } from '../rollups/bucketKey'\nimport { bumpRollups, type RollupBump } from '../rollups/bumpRollups'\nimport { computeRollupDeltas, type RollupInc, type RollupKey } from '../rollups/deltas'\nimport { insertManyIfNew } from '../rollups/insertManyIfNew'\nimport type { StoredEvent } from './normalizeEvent'\nimport { writeEvent } from './writeEvent'\n\ninterface BaseAgg {\n\tkey: RollupKey\n\tinc: RollupInc\n}\n\ninterface DistinctCandidate {\n\tkey: RollupKey\n\tkind: 'visitor' | 'session'\n\tvalue: string\n}\n\n/**\n * Coalesces a batch of events into the fewest writes: events insert concurrently, base rollup\n * increments are summed per bucket, and distinct visitor / session candidates are de-duplicated\n * within the batch before one insert-if-new decides which of them the ledger had not seen.\n * Whatever the batch size, that is three round trips for the rollups and the ledger rather\n * than one per bucket. Correctness matches the per-event path because the seen ledger still\n * de-dupes across batches, and its unique index still arbitrates between concurrent writers.\n */\nexport async function flushBatch(payload: Payload, events: StoredEvent[]): Promise<void> {\n\tif (events.length === 0) {\n\t\treturn\n\t}\n\tawait Promise.all(events.map((event) => writeEvent(payload, event)))\n\n\tconst base = new Map<string, BaseAgg>()\n\tconst candidates = new Map<string, DistinctCandidate>()\n\tfor (const event of events) {\n\t\tfor (const delta of computeRollupDeltas(event)) {\n\t\t\tconst bk = bucketKey(delta.key)\n\t\t\tconst agg = base.get(bk)\n\t\t\tif (agg) {\n\t\t\t\tfor (const metric of Object.keys(agg.inc) as Array<keyof RollupInc>) {\n\t\t\t\t\tagg.inc[metric] += delta.inc[metric]\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbase.set(bk, { key: delta.key, inc: { ...delta.inc } })\n\t\t\t}\n\t\t\tcandidates.set(`${bk}|visitor|${event.visitorHash}`, {\n\t\t\t\tkey: delta.key,\n\t\t\t\tkind: 'visitor',\n\t\t\t\tvalue: event.visitorHash,\n\t\t\t})\n\t\t\tcandidates.set(`${bk}|session|${event.sessionId}`, {\n\t\t\t\tkey: delta.key,\n\t\t\t\tkind: 'session',\n\t\t\t\tvalue: event.sessionId,\n\t\t\t})\n\t\t}\n\t}\n\n\tawait bumpRollups(payload, [...base.values()])\n\n\tconst pending = [...candidates.values()]\n\tconst isNew = await insertManyIfNew(\n\t\tpayload,\n\t\tSEEN_SLUG,\n\t\tpending.map((candidate) => ({\n\t\t\tbucket: bucketKey(candidate.key),\n\t\t\tkind: candidate.kind,\n\t\t\tvalue: candidate.value,\n\t\t\tperiod: candidate.key.period,\n\t\t}))\n\t)\n\t// One increment per ledger row this flush actually created; bumpRollups sums the ones that\n\t// land on the same bucket.\n\tconst distinct: RollupBump[] = []\n\tpending.forEach((candidate, index) => {\n\t\tif (isNew[index]) {\n\t\t\tdistinct.push({\n\t\t\t\tkey: candidate.key,\n\t\t\t\tinc: candidate.kind === 'visitor' ? { visitors: 1 } : { sessions: 1 },\n\t\t\t})\n\t\t}\n\t})\n\tawait bumpRollups(payload, distinct)\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,eAAsB,WAAW,SAAkB,QAAsC;CACxF,IAAI,OAAO,WAAW,GACrB;CAED,MAAM,QAAQ,IAAI,OAAO,KAAK,UAAU,WAAW,SAAS,KAAK,CAAC,CAAC;CAEnE,MAAM,uBAAO,IAAI,IAAqB;CACtC,MAAM,6BAAa,IAAI,IAA+B;CACtD,KAAK,MAAM,SAAS,QACnB,KAAK,MAAM,SAAS,oBAAoB,KAAK,GAAG;EAC/C,MAAM,KAAK,UAAU,MAAM,GAAG;EAC9B,MAAM,MAAM,KAAK,IAAI,EAAE;EACvB,IAAI,KACH,KAAK,MAAM,UAAU,OAAO,KAAK,IAAI,GAAG,GACvC,IAAI,IAAI,WAAW,MAAM,IAAI;OAG9B,KAAK,IAAI,IAAI;GAAE,KAAK,MAAM;GAAK,KAAK,EAAE,GAAG,MAAM,IAAI;EAAE,CAAC;EAEvD,WAAW,IAAI,GAAG,GAAG,WAAW,MAAM,eAAe;GACpD,KAAK,MAAM;GACX,MAAM;GACN,OAAO,MAAM;EACd,CAAC;EACD,WAAW,IAAI,GAAG,GAAG,WAAW,MAAM,aAAa;GAClD,KAAK,MAAM;GACX,MAAM;GACN,OAAO,MAAM;EACd,CAAC;CACF;CAGD,MAAM,YAAY,SAAS,CAAC,GAAG,KAAK,OAAO,CAAC,CAAC;CAE7C,MAAM,UAAU,CAAC,GAAG,WAAW,OAAO,CAAC;CACvC,MAAM,QAAQ,MAAM,gBACnB,SACA,WACA,QAAQ,KAAK,eAAe;EAC3B,QAAQ,UAAU,UAAU,GAAG;EAC/B,MAAM,UAAU;EAChB,OAAO,UAAU;EACjB,QAAQ,UAAU,IAAI;CACvB,EAAE,CACH;CAGA,MAAM,WAAyB,CAAC;CAChC,QAAQ,SAAS,WAAW,UAAU;EACrC,IAAI,MAAM,QACT,SAAS,KAAK;GACb,KAAK,UAAU;GACf,KAAK,UAAU,SAAS,YAAY,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE;EACrE,CAAC;CAEH,CAAC;CACD,MAAM,YAAY,SAAS,QAAQ;AACpC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The visitor's preferred language from an `Accept-Language` header: the first tag, without
|
|
3
|
+
* its quality factor, lowercased (`de-DE,de;q=0.9` becomes `de-de`). A wildcard or an absent
|
|
4
|
+
* header states no preference, so nothing is reported.
|
|
5
|
+
*/
|
|
6
|
+
const primaryLanguage = (acceptLanguage) => {
|
|
7
|
+
const tag = acceptLanguage?.split(",")[0]?.split(";")[0]?.trim().toLowerCase();
|
|
8
|
+
if (!tag || tag === "*") return;
|
|
9
|
+
return tag.slice(0, 16);
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { primaryLanguage };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=language.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"language.js","names":[],"sources":["../../../src/native/ingest/language.ts"],"sourcesContent":["/** Long enough for any real BCP 47 tag; a longer one is junk, not a language. */\nexport const MAX_LANGUAGE_LENGTH = 16\n\n/**\n * The visitor's preferred language from an `Accept-Language` header: the first tag, without\n * its quality factor, lowercased (`de-DE,de;q=0.9` becomes `de-de`). A wildcard or an absent\n * header states no preference, so nothing is reported.\n */\nexport const primaryLanguage = (acceptLanguage: string | null): string | undefined => {\n\tconst tag = acceptLanguage?.split(',')[0]?.split(';')[0]?.trim().toLowerCase()\n\tif (!tag || tag === '*') {\n\t\treturn undefined\n\t}\n\treturn tag.slice(0, MAX_LANGUAGE_LENGTH)\n}\n"],"mappings":";;;;;AAQA,MAAa,mBAAmB,mBAAsD;CACrF,MAAM,MAAM,gBAAgB,MAAM,GAAG,EAAE,IAAI,MAAM,GAAG,EAAE,IAAI,KAAK,EAAE,YAAY;CAC7E,IAAI,CAAC,OAAO,QAAQ,KACnB;CAED,OAAO,IAAI,MAAM,GAAA,EAAsB;AACxC"}
|
|
@@ -7,6 +7,12 @@ interface RawEventInput {
|
|
|
7
7
|
path: string;
|
|
8
8
|
hostname: string;
|
|
9
9
|
referrer?: string;
|
|
10
|
+
/**
|
|
11
|
+
* The page's query string, without its leading `?`. Read for its utm keys and then
|
|
12
|
+
* discarded: it is never stored, so a session token or an email address that happens to
|
|
13
|
+
* be in the URL never lands in the events collection.
|
|
14
|
+
*/
|
|
15
|
+
query?: string;
|
|
10
16
|
durationMs?: number;
|
|
11
17
|
props?: Record<string, unknown>;
|
|
12
18
|
/** Revenue for a goal completion, in `currency`. */
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { clientIpFromHeaders } from "./clientIp.js";
|
|
2
2
|
import { classifyDevice } from "./device.js";
|
|
3
3
|
import { matchGoals } from "../../goals/match.js";
|
|
4
|
+
import { classifyBrowser, classifyOs } from "./browser.js";
|
|
5
|
+
import { primaryLanguage } from "./language.js";
|
|
6
|
+
import { referrerHost, storedReferrer } from "./referrer.js";
|
|
4
7
|
import { deriveSource } from "./source.js";
|
|
8
|
+
import { extractUtm } from "./utm.js";
|
|
5
9
|
import { dailyVisitorHash, deriveSessionId } from "./visitorHash.js";
|
|
6
10
|
//#region src/native/ingest/normalizeEvent.ts
|
|
7
11
|
const MAX_PROPS = 20;
|
|
@@ -33,6 +37,14 @@ const duration = (value) => {
|
|
|
33
37
|
};
|
|
34
38
|
/** The event name is a rollup bucket key (the `event` dimension), so it is length-capped. */
|
|
35
39
|
const eventName = (value) => typeof value === "string" ? value.slice(0, MAX_NAME_LENGTH) : void 0;
|
|
40
|
+
/**
|
|
41
|
+
* A geo value as stored. The resolver reads request headers a client can set, and each value
|
|
42
|
+
* becomes a rollup dimvalue and part of a seen-ledger key, so it is capped here rather than
|
|
43
|
+
* trusted. An empty value stays absent: '' would be a bucket of its own.
|
|
44
|
+
*/
|
|
45
|
+
const geoValue = (value) => value ? value.slice(0, 128) : void 0;
|
|
46
|
+
/** Capped before it is parsed, so a hostile query cannot make ingest do unbounded work. */
|
|
47
|
+
const queryString = (value) => typeof value === "string" ? value.slice(0, 512) : void 0;
|
|
36
48
|
const depth = (value) => {
|
|
37
49
|
const n = nonNegative(value);
|
|
38
50
|
return n === void 0 ? void 0 : Math.round(Math.min(n, 100));
|
|
@@ -70,6 +82,12 @@ async function normalizeEvent({ raw, headers, geoResolver, salt, now, scope, tim
|
|
|
70
82
|
const durationMs = duration(raw.durationMs);
|
|
71
83
|
const name = eventName(raw.name);
|
|
72
84
|
const device = classifyDevice(ua);
|
|
85
|
+
const browser = classifyBrowser(ua);
|
|
86
|
+
const os = classifyOs(ua);
|
|
87
|
+
const language = primaryLanguage(headers.get("accept-language"));
|
|
88
|
+
const refHost = referrerHost(raw.referrer, hostname);
|
|
89
|
+
const query = queryString(raw.query);
|
|
90
|
+
const utm = extractUtm(query);
|
|
73
91
|
const completions = goals?.length ? matchGoals({
|
|
74
92
|
type: raw.type,
|
|
75
93
|
name,
|
|
@@ -83,12 +101,21 @@ async function normalizeEvent({ raw, headers, geoResolver, salt, now, scope, tim
|
|
|
83
101
|
name,
|
|
84
102
|
path,
|
|
85
103
|
hostname,
|
|
86
|
-
referrer: raw.referrer,
|
|
104
|
+
referrer: storedReferrer(raw.referrer),
|
|
105
|
+
...refHost ? { referrerHost: refHost } : {},
|
|
87
106
|
...device ? { device } : {},
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
107
|
+
...browser ? { browser } : {},
|
|
108
|
+
...os ? { os } : {},
|
|
109
|
+
source: deriveSource({
|
|
110
|
+
referrerHost: refHost,
|
|
111
|
+
utmMedium: utm.utmMedium,
|
|
112
|
+
query
|
|
113
|
+
}),
|
|
114
|
+
...utm,
|
|
115
|
+
country: geoValue(geo.country),
|
|
116
|
+
region: geoValue(geo.region),
|
|
117
|
+
city: geoValue(geo.city),
|
|
118
|
+
...language ? { language } : {},
|
|
92
119
|
visitorHash,
|
|
93
120
|
sessionId: deriveSessionId(visitorHash, hourBucket),
|
|
94
121
|
props,
|