@10x-media/analytics 1.0.0-beta.12 → 1.0.0-beta.14
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 +75 -0
- package/dist/adapters/ga4/ga4.d.ts +6 -0
- package/dist/adapters/ga4/ga4.js +3 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.d.ts +6 -0
- package/dist/adapters/plausible/plausible.js +2 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +6 -0
- package/dist/adapters/posthog/posthog.js +21 -8
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +6 -0
- package/dist/adapters/umami/umami.js +2 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/exclusionEndpoint.js +1 -1
- package/dist/capture/exclusionEndpoint.js.map +1 -1
- package/dist/capture/slots.js +3 -3
- package/dist/capture/slots.js.map +1 -1
- package/dist/capture/trackerConfig.js +11 -3
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/adminOptions.js +6 -1
- package/dist/core/adminOptions.js.map +1 -1
- package/dist/core/capture.d.ts +3 -1
- package/dist/core/contract.d.ts +13 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +37 -5
- package/dist/core/options.js +6 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/registry.js.map +1 -1
- package/dist/core/scopeOptions.js +2 -0
- package/dist/core/scopeOptions.js.map +1 -1
- package/dist/core/scopedRead.js +170 -21
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceLabel.d.ts +10 -0
- package/dist/core/sourceLabel.js +63 -0
- package/dist/core/sourceLabel.js.map +1 -0
- package/dist/core/sourceOptions.js +18 -6
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +55 -0
- package/dist/core/sourcePolicy.js +51 -0
- package/dist/core/sourcePolicy.js.map +1 -0
- package/dist/exports/adapters/contract.d.ts +2 -1
- package/dist/exports/adapters/ga4.d.ts +3 -2
- package/dist/exports/adapters/native.d.ts +3 -2
- package/dist/exports/adapters/plausible.d.ts +3 -2
- package/dist/exports/adapters/posthog.d.ts +3 -2
- package/dist/exports/adapters/umami.d.ts +3 -2
- package/dist/exports/client.d.ts +7 -5
- package/dist/exports/client.js +2 -1
- package/dist/exports/next.d.ts +3 -2
- package/dist/exports/rsc.d.ts +7 -6
- package/dist/exports/testing.d.ts +3 -2
- package/dist/exports/types.d.ts +12 -8
- package/dist/fields/AnalyticsPanelClient.js.map +1 -1
- package/dist/fields/AnalyticsPanelField.d.ts +1 -1
- package/dist/fields/AnalyticsPanelField.js +3 -1
- package/dist/fields/AnalyticsPanelField.js.map +1 -1
- package/dist/fields/AnalyticsStatField.d.ts +1 -1
- package/dist/fields/AnalyticsStatField.js +1 -1
- package/dist/fields/PanelContent.js +6 -1
- package/dist/fields/PanelContent.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +3 -0
- package/dist/fields/config/fetchSources.js +5 -3
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/fields/readForDocument.d.ts +5 -4
- package/dist/fields/readForDocument.js +6 -2
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/collection.js +4 -31
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +2 -2
- package/dist/goals/trackGoalAction.js +1 -1
- package/dist/index.d.ts +14 -11
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/ingest/normalizeEvent.js +1 -1
- package/dist/native/nativeAdapter.d.ts +6 -0
- package/dist/native/nativeAdapter.js +3 -2
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/plugin/createRuntime.js +6 -3
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +1 -0
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/pluginCollections.js +11 -5
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +11 -0
- package/dist/plugin/readContextForRequest.js +25 -15
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/runtime.js +13 -5
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +8 -9
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/providers/ProvidersListNotice.d.ts +11 -0
- package/dist/providers/ProvidersListNotice.js +36 -0
- package/dist/providers/ProvidersListNotice.js.map +1 -0
- package/dist/providers/collection.d.ts +9 -1
- package/dist/providers/collection.js +111 -42
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.d.ts +1 -1
- package/dist/providers/factory.js +8 -11
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/probe.js +5 -1
- package/dist/providers/probe.js.map +1 -1
- package/dist/providers/registry.js +49 -39
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/resolver.js +6 -3
- package/dist/providers/resolver.js.map +1 -1
- package/dist/providers/scopeUnique.js +41 -0
- package/dist/providers/scopeUnique.js.map +1 -0
- package/dist/query/fetchQuery.d.ts +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/tracker/config.d.ts +5 -0
- package/dist/tracker/config.js.map +1 -1
- package/dist/tracker/sinks/createSink.js +4 -1
- package/dist/tracker/sinks/createSink.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/tracker/sinks/posthog.js +30 -2
- package/dist/tracker/sinks/posthog.js.map +1 -1
- package/dist/tracker/sinks/vendor.js +2 -2
- package/dist/tracker/sinks/vendor.js.map +1 -1
- package/dist/translations/ar.js +6 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +6 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +6 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +6 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +6 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +6 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +6 -0
- package/dist/translations/keys.js +7 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +6 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +6 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +6 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +6 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +6 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +5 -0
- package/dist/ui/components/SourcesNoticeBanner.js +20 -0
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -0
- package/dist/view/ViewRoot.js +2 -0
- package/dist/view/ViewRoot.js.map +1 -1
- package/dist/view/registerView.js +5 -4
- package/dist/view/registerView.js.map +1 -1
- package/dist/view/viewContext.d.ts +1 -1
- package/dist/view/viewProps.d.ts +1 -1
- package/dist/view/viewProps.js +3 -2
- package/dist/view/viewProps.js.map +1 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.js +1 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -1
- package/dist/widgets/AnalyticsMetricWidget.js +1 -0
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +15 -7
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.js +1 -0
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/defaultLayout.d.ts +26 -0
- package/dist/widgets/defaultLayout.js +51 -0
- package/dist/widgets/defaultLayout.js.map +1 -0
- package/dist/widgets/notices.js +1 -0
- package/dist/widgets/notices.js.map +1 -1
- package/dist/widgets/prepareWidgetRead.d.ts +14 -1
- package/dist/widgets/prepareWidgetRead.js +6 -2
- package/dist/widgets/prepareWidgetRead.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +4 -4
- package/dist/widgets/readForWidget.js +3 -1
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +4 -4
- package/dist/widgets/readForWidgetBreakdown.js +3 -1
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +4 -4
- package/dist/widgets/readForWidgetGoals.js +3 -1
- package/dist/widgets/readForWidgetGoals.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.d.ts +4 -3
- package/dist/widgets/readForWidgetRealtime.js +3 -1
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +4 -4
- package/dist/widgets/readForWidgetSeries.js +3 -1
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +3 -1
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/package.json +2 -2
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 Endpoint, type PayloadRequest } from 'payload'\n\nimport { itemCollectionsOf } from './binding/report'\nimport { captureRequest } from './capture/captureRequest'\nimport { makeExclusionHandler } from './capture/exclusionEndpoint'\nimport { proxyEndpoints } from './capture/proxyEndpoint'\nimport { trackerEndpoint } from './capture/trackerEndpoint'\nimport { assertMaintainRegistered, TASK_SLUGS } from './core/jobs'\nimport { type AnalyticsPluginOptions, resolveOptions, type ScopeCallSite } from './core/options'\nimport { createRegistry, withoutRevenue } from './core/registry'\nimport { CURRENCY_PATTERN } from './goals/currency'\nimport { makeGoalsHandler } from './goals/goalsEndpoint'\nimport { applyConfigRevenueVisibility } from './goals/moneyFields'\nimport { configGoalsResolver } from './goals/resolver'\nimport type { Goal } from './goals/types'\nimport { addComponentDependency, FLAG_DEPENDENCY } from './plugin/adminDependencies'\nimport { expectedCollections } from './plugin/collectionChecks'\nimport { createRuntimeFactory } from './plugin/createRuntime'\nimport { makeDocumentHandler } from './plugin/documentEndpoint'\nimport { makeFlagsHandler } from './plugin/flagsEndpoint'\nimport { restrictJobControls } from './plugin/jobsAccess'\nimport {\n\taddStateCollection,\n\ttype CollectionContext,\n\tcacheCollectionOf,\n\tconfigCollections,\n\tsyncCollectionOf,\n} from './plugin/pluginCollections'\nimport { makeQueryHandler } from './plugin/queryEndpoint'\nimport { makeRealtimeHandler } from './plugin/realtimeEndpoint'\nimport { makeRefreshHandler } from './plugin/refreshEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { relabelFactoryFields } from './plugin/relabelFields'\nimport { assertRoutesReachable } from './plugin/routeChecks'\nimport {\n\tANALYTICS_CONFIG_KEY,\n\ttype AnalyticsAdminCustom,\n\tpluginEndpoint,\n\troutePaths,\n} from './plugin/routes'\nimport { getRuntime, resolveGoalsFor, resolveRegistryFor, runtimeFactoryOf } from './plugin/runtime'\nimport { addTask, schemaOnly } from './plugin/schemaOnly'\nimport { changedScopes, type ScopeChange } from './plugin/scopeChange'\nimport { makeSourcesHandler } from './plugin/sourcesEndpoint'\nimport { fillUnbundledLanguages, unbundledLanguages } from './plugin/unbundledLanguages'\nimport { warmTask } from './plugin/warmTask'\nimport { syncTask } from './sync/syncTask'\nimport { createStrictTimezoneResolver, createTimezoneResolver } from './timeframe/reportingTimezone'\nimport { keys } from './translations/keys'\nimport { createStaticLabels } from './translations/staticLabel'\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\n/**\n * Rereads the scopes a providers or goals save touched, on the instance that wrote; every other\n * instance catches up through its own probe.\n */\nconst configChanged =\n\t(collection: 'providers' | 'goals') =>\n\t(change: ScopeChange, req: PayloadRequest): void => {\n\t\tgetRuntime(req.payload)?.configChanged?.(collection, changedScopes(change))\n\t}\n\nconst addEndpoints = (config: Config, ...endpoints: Endpoint[]): void => {\n\tconfig.endpoints = [...(config.endpoints ?? []), ...endpoints]\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tconst disabled = options.disabled === true\n\t\t// Switched off, nothing reads through the adapters: they are only asked for their schema.\n\t\tconst resolved = resolveOptions(options, { requireAdapters: !disabled })\n\t\tconst resolveScope = async (req: PayloadRequest, callSite: ScopeCallSite) =>\n\t\t\tresolved.scope.resolve({ req, callSite })\n\t\tconst resolveAdminScope = (req: PayloadRequest) => resolveScope(req, 'admin')\n\t\t// What the collection checks warn about waits for the instance's logger, at init.\n\t\tconst notices: string[] = []\n\t\t// Read before the plugin merges its own strings in, so the app's own still win.\n\t\tconst staticLabel = createStaticLabels({\n\t\t\tapp: config.i18n?.translations,\n\t\t\tplugin: options.translations,\n\t\t\tunbundled: unbundledLanguages(config),\n\t\t})\n\t\tconst context: CollectionContext = {\n\t\t\tdb: config.db?.name,\n\t\t\tnotice: (message) => {\n\t\t\t\tnotices.push(message)\n\t\t\t},\n\t\t\tstaticLabel,\n\t\t}\n\t\tconst collections = await configCollections(\n\t\t\tresolved,\n\t\t\t{ resolveAdminScope, onChange: configChanged },\n\t\t\tcontext\n\t\t)\n\t\tconst sync = syncCollectionOf(resolved, resolveAdminScope, context)\n\t\tif (disabled) {\n\t\t\treturn schemaOnly(config, {\n\t\t\t\tresolved,\n\t\t\t\tcollections,\n\t\t\t\tcontext,\n\t\t\t\t...(sync ? { sync } : {}),\n\t\t\t\t...(options.translations ? { translations: options.translations } : {}),\n\t\t\t})\n\t\t}\n\t\tconst routes = routePaths(resolved.routes.base)\n\t\t// Whatever is mounted before the plugin runs belongs to the host or an earlier plugin.\n\t\tconst earlierEndpoints = new Set(config.endpoints ?? [])\n\t\tconst money = resolved.revenue.enabled\n\t\t// A runtime provider's capabilities are unknown at config time, so providers open the\n\t\t// widget and endpoint gates that otherwise follow the config adapters' capabilities.\n\t\tconst providersEnabled =\n\t\t\tresolved.providers.collection.enabled || Boolean(resolved.providers.resolve)\n\t\t// Read before the adapters register: only a host that turned it on may carry concurrency keys.\n\t\tconst jobsConcurrency = config.jobs?.enableConcurrencyControl === true\n\t\tregisterTranslations(config, options.translations)\n\t\tfillUnbundledLanguages(config)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\t// Adapters ask for a scope to stamp a visitor's hit with, so theirs is the capture call\n\t\t// site, asked without the signed-in user or their cookies.\n\t\tconst resolveCaptureScope = (req: PayloadRequest) =>\n\t\t\tresolveScope(captureRequest(req), 'capture')\n\t\t/**\n\t\t * Whether a scope's own committed provider documents grant it this adapter (a beacon decrypts\n\t\t * nothing). Handed to adapters only when `scope.resolve` and the providers collection both run.\n\t\t */\n\t\tconst adapterGrantedForScope = async (\n\t\t\treq: PayloadRequest,\n\t\t\tscope: string | null,\n\t\t\tadapterId: string\n\t\t): Promise<boolean> => {\n\t\t\tconst runtime = getRuntime(req.payload)\n\t\t\tif (!runtime) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (runtime.providerGranted) {\n\t\t\t\treturn runtime.providerGranted(scope, adapterId)\n\t\t\t}\n\t\t\tconst { grants } = await resolveRegistryFor(runtime, { payload: req.payload, req, scope })\n\t\t\treturn grants.has(adapterId)\n\t\t}\n\t\tconst configGoals = configGoalsResolver(resolved.goals, resolved.purchaseGoal)\n\t\t/** The goals of the instance a request reached, which adapters resolve at ingest. */\n\t\tconst resolveGoals = (req: PayloadRequest, scope?: string | null): Promise<Goal[]> => {\n\t\t\tconst runtime = getRuntime(req.payload)\n\t\t\treturn runtime ? resolveGoalsFor(runtime, req, scope) : configGoals.resolve(req, scope)\n\t\t}\n\t\tconfig.collections = [...(config.collections ?? []), ...collections]\n\t\tconst timezoneArgs = { option: resolved.reportingTimezone, resolveScope: resolveAdminScope }\n\t\tconst resolveTimezone = createTimezoneResolver(timezoneArgs)\n\t\tconst resolveTimezoneStrict = createStrictTimezoneResolver(timezoneArgs)\n\t\tconst resolveCurrency = async (\n\t\t\treq: PayloadRequest,\n\t\t\tscope?: string | null\n\t\t): Promise<string | undefined> => {\n\t\t\tconst opt = resolved.revenue.currency\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst code =\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 resolveAdminScope(req) })\n\t\t\t\treturn code && CURRENCY_PATTERN.test(code) ? code : undefined\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: revenue.currency resolution failed, reporting revenue unformatted: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tconst itemCollections = itemCollectionsOf(resolved.bindings)\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: resolveCaptureScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tresolveTimezoneStrict,\n\t\t\t\trevenue: {\n\t\t\t\t\tenabled: money,\n\t\t\t\t\tdimension: resolved.revenue.dimension,\n\t\t\t\t\tcurrency: resolveCurrency,\n\t\t\t\t\tconvert: resolved.revenue.convert,\n\t\t\t\t\tbrowserAmounts: resolved.revenue.browserAmounts,\n\t\t\t\t\torderSignature: resolved.revenue.orderSignature,\n\t\t\t\t},\n\t\t\t\tresolveGoals,\n\t\t\t\t...(resolved.scoped && resolved.providers.collection.enabled\n\t\t\t\t\t? { adapterGrantedForScope }\n\t\t\t\t\t: {}),\n\t\t\t\ttrustedProxyHops: resolved.trustedProxyHops,\n\t\t\t\ttrustedPlatform: resolved.trustedPlatform,\n\t\t\t\tallowedOrigins: resolved.capture.allowedOrigins,\n\t\t\t\t...(itemCollections.size > 0\n\t\t\t\t\t? {\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\tcollections: itemCollections,\n\t\t\t\t\t\t\t\tpages: resolved.capture.autoCapture.items.pages,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\troutes,\n\t\t\t\tsdks: resolved.sdks,\n\t\t\t\tjobs: resolved.jobs,\n\t\t\t\tjobsConcurrency,\n\t\t\t\tnotice: context.notice,\n\t\t\t})\n\t\t}\n\t\tassertMaintainRegistered(\n\t\t\tresolved.jobs,\n\t\t\t(config.jobs?.tasks ?? []).some((task) => task.slug === TASK_SLUGS.maintain)\n\t\t)\n\t\t// After registration: an adapter declares what the install measures once it is registered,\n\t\t// and one that declares no revenue then is read as it is rather than as a copy.\n\t\tconst readRegistry = money ? registry : withoutRevenue(registry)\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\taddEndpoints(config, { method: 'get', path: routes.live, handler: makeRealtimeHandler() })\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\taddEndpoints(config, { method: 'get', path: routes.document, handler: makeDocumentHandler() })\n\t\t}\n\t\taddEndpoints(\n\t\t\tconfig,\n\t\t\t{ method: 'get', path: routes.sources, handler: makeSourcesHandler() },\n\t\t\t{ method: 'get', path: routes.goals, handler: makeGoalsHandler() },\n\t\t\t{ method: 'get', path: routes.query, handler: makeQueryHandler() },\n\t\t\t{ method: 'post', path: routes.refresh, handler: makeRefreshHandler() }\n\t\t)\n\t\tif (resolved.capture.exclusion) {\n\t\t\taddEndpoints(config, {\n\t\t\t\tmethod: 'get',\n\t\t\t\tpath: routes.exclusion,\n\t\t\t\thandler: makeExclusionHandler(),\n\t\t\t})\n\t\t}\n\t\t// One answer serves the view, the widgets and the route, so the flags an install draws and\n\t\t// the route serving them cannot diverge. A host's own flag needs no route, only the import map.\n\t\tconst countryFlags = resolved.countryFlags\n\t\tif (countryFlags === true) {\n\t\t\taddEndpoints(config, {\n\t\t\t\tmethod: 'get',\n\t\t\t\tpath: routes.flagsPattern,\n\t\t\t\thandler: makeFlagsHandler(),\n\t\t\t})\n\t\t} else if (countryFlags !== false) {\n\t\t\taddComponentDependency(config, FLAG_DEPENDENCY, countryFlags.Component)\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\taddEndpoints(config, ...proxyEndpoints(routes), trackerEndpoint(routes))\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\trevenue: money,\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\tcountryFlags,\n\t\t\t\tstaticLabel,\n\t\t\t\toverrides: resolved.widgets.overrides,\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, title: staticLabel(keys.viewTitle) })\n\t\tconst { jobs } = resolved\n\t\tif (jobs !== false && resolved.cache.warm.enabled) {\n\t\t\taddTask(\n\t\t\t\tconfig,\n\t\t\t\twarmTask({\n\t\t\t\t\tschedule: jobs.warm,\n\t\t\t\t\twindowHours: resolved.cache.warm.windowHours,\n\t\t\t\t\tmaxReads: resolved.cache.warm.maxReads,\n\t\t\t\t\tconcurrency: jobsConcurrency,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tif (sync) {\n\t\t\tconfig.collections = [...(config.collections ?? []), sync]\n\t\t\tif (jobs !== false) {\n\t\t\t\taddTask(\n\t\t\t\t\tconfig,\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tschedule: jobs.sync,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collection.slug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t\tscopes: resolved.scope.list,\n\t\t\t\t\t\tconcurrency: jobsConcurrency,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tconst cache = cacheCollectionOf(resolved, context)\n\t\tif (cache) {\n\t\t\tconfig.collections = [...(config.collections ?? []), cache]\n\t\t}\n\t\taddStateCollection(config, resolved, context)\n\t\trestrictJobControls(config)\n\t\t// Hidden per config rather than per process, so two instances answer for themselves; a later\n\t\t// plugin's fields (form-builder's action blocks) take their factory's own `revenue` option.\n\t\tapplyConfigRevenueVisibility(config, money)\n\t\trelabelFactoryFields(config, staticLabel)\n\t\tconfig.endpoints = (config.endpoints ?? []).map((endpoint) =>\n\t\t\tearlierEndpoints.has(endpoint) ? endpoint : pluginEndpoint(endpoint)\n\t\t)\n\t\t// Checked against everything registered so far, the plugin's own collections included; what a\n\t\t// later plugin adds is caught when a runtime is built from the assembled config.\n\t\tassertRoutesReachable(resolved.routes.base, {\n\t\t\tcollections: config.collections ?? [],\n\t\t\tendpoints: config.endpoints,\n\t\t})\n\t\tconst factory = createRuntimeFactory({\n\t\t\tresolved,\n\t\t\tnotices,\n\t\t\tcollections: expectedCollections(config.collections),\n\t\t\tregistry: readRegistry,\n\t\t\tresolveScope,\n\t\t\tresolveTimezone,\n\t\t\tresolveCurrency,\n\t\t})\n\t\tconst adminCustom: AnalyticsAdminCustom = { routes: { base: resolved.routes.base } }\n\t\tconfig.custom = { ...config.custom, [ANALYTICS_CONFIG_KEY]: factory }\n\t\tconfig.admin = {\n\t\t\t...config.admin,\n\t\t\tcustom: { ...config.admin?.custom, [ANALYTICS_CONFIG_KEY]: adminCustom },\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// Validation only: the runtime builds on first use either way, and is built here so consumer\n\t\t// init code (seeding, cache warming, sync passes) runs against a warm one.\n\t\tconfig.onInit = async (payload) => {\n\t\t\t// Without the factory every endpoint answers 503; a boot error names the cause instead.\n\t\t\tif (runtimeFactoryOf(payload.config) !== factory) {\n\t\t\t\tthrow new Error(RUNTIME_FACTORY_LOST)\n\t\t\t}\n\t\t\tawait factory.validate(payload)\n\t\t\tgetRuntime(payload)\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\n/** Said at boot when a step after the plugin dropped its runtime from `config.custom`. */\nconst RUNTIME_FACTORY_LOST = `analytics: config.custom[\"${ANALYTICS_CONFIG_KEY}\"] no longer holds the analytics runtime: a plugin or config step that runs after analytics replaced config.custom instead of spreading it. Spread the existing value there ({ ...config.custom, ... }), or list analytics after that plugin.`\n\nexport { isAdminUser } from './access/adminUser'\nexport { type TenantMembershipOptions, tenantMembership } from './access/membership'\nexport { type GatedScope, type ReadPrincipal, SYSTEM } from './access/principal'\nexport { ProviderHttpError, parseRetryAfter } from './adapters/http/fetchJson'\nexport type { ReportMode, ReportOption } from './binding/report'\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tBindingDoc,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport type { CapabilityRequirement, FilterPair, SerializedCapabilities } from './core/capabilities'\nexport {\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\tPLATFORM_SCOPE,\n} from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsCacheCollectionOptions,\n\tAnalyticsCacheOptions,\n\tAnalyticsCaptureOptions,\n\tAnalyticsCollectionOptions,\n\tAnalyticsComponent,\n\tAnalyticsConcurrencyOptions,\n\tAnalyticsCountryFlags,\n\tAnalyticsCrossScopeOptions,\n\tAnalyticsExclusionOptions,\n\tAnalyticsGoalsCollectionOptions,\n\tAnalyticsGoalsOptions,\n\tAnalyticsHooksOptions,\n\tAnalyticsJobsOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tAnalyticsReadAccess,\n\tAnalyticsRevenueOptions,\n\tAnalyticsRoutesOptions,\n\tAnalyticsScopeOptions,\n\tAnalyticsSyncCollectionOptions,\n\tAnalyticsSyncOptions,\n\tAnalyticsTaskOptions,\n\tAnalyticsViewAccess,\n\tAnalyticsViewOptions,\n\tAnalyticsWarmOptions,\n\tAnalyticsWidgetOverride,\n\tAnalyticsWidgetOverrides,\n\tAnalyticsWidgetsOptions,\n\tAutoCaptureOptions,\n\tCaptureGate,\n\tCaptureGateArgs,\n\tCaptureSlotOption,\n\tCollectionOverrides,\n\tCrossScopeAccess,\n\tCurrencyConverter,\n\tCurrencyResolver,\n\tExclusionSitesResolver,\n\tItemCaptureOptions,\n\tProviderHostsOptions,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tProvidersResolveArgs,\n\tScopeCallSite,\n\tScopeLabelResolver,\n\tScopeListResolver,\n\tScopeMemberAccess,\n\tScopeResolver,\n\tTimezoneResolver,\n} from './core/options'\nexport type {\n\tAnalyticsSdks,\n\tGa4Client,\n\tGa4ClientOptions,\n\tGa4ReportResponse,\n\tGa4ReportRow,\n\tGa4Sdk,\n\tMaxmindReader,\n\tMaxmindSdk,\n} from './core/sdks'\nexport type {\n\tServerEventInput,\n\tServerTrack,\n\tServerTrackIdentity,\n\tServerTrackOptions,\n} from './core/serverEvent'\nexport { AnalyticsTrackError } from './core/serverEvent'\nexport { BUILT_IN_WIDGET_SLUGS, type BuiltInWidgetSlug } from './core/widgetSlugs'\nexport type * from './exports/adapters/contract'\nexport type { AnalyticsAttributes } from './exports/attributes'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatBaseOptions,\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 {\n\tFieldBreakdown,\n\tFieldBreakdownRow,\n\tFieldReadResult,\n\tFieldReadStatus,\n\tReadForFieldArgs,\n} from './fields/readForDocument'\nexport { readForField } from './fields/readForDocument'\nexport type {\n\tGoalCollectionFieldOverrides,\n\tGoalFieldOverride,\n} from './goals/collection'\nexport { GOALS_SLUG } from './goals/collection'\nexport {\n\tCURRENCY_ATTRIBUTE,\n\tEVENT_ATTRIBUTE,\n\tEVENT_PROP_PREFIX,\n\tGOAL_ATTRIBUTE,\n\tITEM_ATTRIBUTE,\n\tITEM_CLICK_EVENT,\n\tITEM_NAME_ATTRIBUTE,\n\tMAX_ITEMS_PER_BEACON,\n\tPURCHASE_GOAL_SLUG,\n\tVALUE_ATTRIBUTE,\n} from './goals/constants'\nexport type { GoalFieldOptions } from './goals/goalField'\nexport { goalField, goalSlug } from './goals/goalField'\nexport type { GoalsResponse, WireGoal } from './goals/goalsEndpoint'\nexport type { AnalyticsLinkFieldsOptions } from './goals/linkFields'\nexport { analyticsLinkFields } from './goals/linkFields'\nexport type { BrowserAmounts, OrderSignatureMode } from './goals/match'\nexport type { GoalSource } from './goals/resolver'\nexport type {\n\tPurchaseInput as ServerPurchaseInput,\n\tRefundInput as ServerRefundInput,\n} from './goals/serverRevenue'\nexport { purchase, refund } from './goals/serverRevenue'\nexport type {\n\tGoalActionDefinition,\n\tGoalActionRunArgs,\n\tTrackGoalActionOptions,\n} from './goals/trackGoalAction'\nexport { GOAL_ACTION_TYPE, trackGoalAction } from './goals/trackGoalAction'\nexport type { Goal } from './goals/types'\nexport { STATE_SLUG } from './native/collections/slugs'\nexport type { RebuildDaysInput, RebuildDaysReport } from './native/engine/rebuild'\nexport {\n\ttype ItemSignatureMode,\n\titemAttributesFor,\n\tsignItemRef,\n} from './native/ingest/itemSignature'\nexport { signOrderId } from './native/ingest/orderSignature'\nexport { trackServerEvent } from './native/ingest/serverTrack'\nexport { rebuildDays } from './native/rebuildDays'\nexport {\n\tcreateGuardedFetch,\n\ttype GuardedFetch,\n\ttype GuardedFetchOptions,\n} from './net/guardedFetch'\nexport type { TrustedPlatform } from './net/platform'\nexport type { CollectionFieldOverride } from './plugin/collectionFields'\nexport {\n\tANALYTICS_ERROR_CODES,\n\ttype AnalyticsError,\n\ttype AnalyticsErrorCode,\n\tanalyticsError,\n\treadErrorCode,\n} from './plugin/errors'\nexport type { RoutesConfigSource } from './plugin/routes'\nexport {\n\tanalyticsRoutes,\n\tDEFAULT_ROUTE_BASE,\n\ttype RouteBase,\n\ttype RoutePaths,\n\troutePaths,\n} from './plugin/routes'\nexport type {\n\tBuildSecretField,\n\tConnectionAccess,\n\tConnectionFieldAccess,\n\tProviderCollectionFieldOverrides,\n\tProviderFieldOverride,\n\tProviderFieldsOptions,\n} from './providers/collection'\nexport { analyticsProviderFields, PROVIDERS_SLUG } from './providers/collection'\nexport type { ProviderDoc, ProviderFactoryContext, ProviderId } from './providers/factory'\nexport { adapterFromProviderDoc, PROVIDER_IDS } from './providers/factory'\nexport type { HostPattern } from './providers/hosts'\nexport { type ProviderHostPolicy, resolveHostPolicy } from './providers/hosts'\nexport { type RefreshProvidersOptions, refreshProviders } from './providers/refresh'\nexport { CONNECTION_PATHS, SECRET_PATHS } from './providers/secrets'\nexport type { QueryError, QueryErrorCode } from './query/errors'\nexport type {\n\tItemLabels,\n\tQueryErrorResponse,\n\tQueryResponse,\n\tQuerySourceRef,\n\tSerializedAnalyticsQuery,\n} from './query/response'\nexport type {\n\tAfterReadAnswer,\n\tAfterReadArgs,\n\tAfterReadHook,\n\tReadOrigin,\n} from './surfacing/afterRead'\nexport { CACHE_SLUG } from './surfacing/cacheCollection'\nexport type {\n\tCacheEntry,\n\tCacheSetOptions,\n\tCacheStore,\n\tReadRecipe,\n\tRecipeWindow,\n} from './surfacing/cacheStore'\nexport { SYNC_SLUG } from './sync/collection'\nexport { TIMEFRAME_PRESETS, type TimeframePreset } from './timeframe/presets'\nexport type { GoalMatch, RevenueItem, TrackerGoal } from './tracker/config'\nexport type { TranslationsOption } from './translations'\nexport {\n\tkeys,\n\ttype PluralCategory,\n\ttype PluralName,\n\ttype PluralVariant,\n\tpluralKeys,\n\ttype SingularKey,\n\ttype TranslationKey,\n} from './translations/keys'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\nexport { widgetFilters } from './widgets/filterField'\nexport type {\n\tReadForWidgetArgs,\n\tWidgetReadResult,\n\tWidgetReadStatus,\n} from './widgets/readForWidget'\nexport { readForWidget } from './widgets/readForWidget'\nexport type {\n\tBreakdownRow,\n\tReadForWidgetBreakdownArgs,\n\tWidgetBreakdownResult,\n} from './widgets/readForWidgetBreakdown'\nexport { readForWidgetBreakdown } from './widgets/readForWidgetBreakdown'\nexport type {\n\tGoalRow,\n\tReadForWidgetGoalsArgs,\n\tWidgetGoalsResult,\n} from './widgets/readForWidgetGoals'\nexport { readForWidgetGoals } from './widgets/readForWidgetGoals'\nexport type {\n\tReadForWidgetRealtimeArgs,\n\tRealtimePoint,\n\tWidgetRealtimeResult,\n\tWidgetRealtimeStatus,\n} from './widgets/readForWidgetRealtime'\nexport { readForWidgetRealtime } from './widgets/readForWidgetRealtime'\nexport type {\n\tReadForWidgetSeriesArgs,\n\tSeriesGranularity,\n\tSeriesPoint,\n\tWidgetSeriesResult,\n} from './widgets/readForWidgetSeries'\nexport { readForWidgetSeries } from './widgets/readForWidgetSeries'\nexport type { ReadNotices } from './widgets/readMeta'\nexport type { WidgetFilter } from './widgets/types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,MAAM,iBACJ,gBACA,QAAqB,QAA8B;CACnD,WAAW,IAAI,OAAO,GAAG,gBAAgB,YAAY,cAAc,MAAM,CAAC;AAC3E;AAED,MAAM,gBAAgB,QAAgB,GAAG,cAAgC;CACxE,OAAO,YAAY,CAAC,GAAI,OAAO,aAAa,CAAC,GAAI,GAAG,SAAS;AAC9D;AAEA,MAAa,YAAY,aAAqC;CAC7D,MAAM;CACN,QAAQ,OAAO,EAAE,QAAQ,SAAS,UAAU,GAAG,cAA+B;EAC7E,MAAM,WAAW,QAAQ,aAAa;EAEtC,MAAM,WAAW,eAAe,SAAS,EAAE,iBAAiB,CAAC,SAAS,CAAC;EACvE,MAAM,eAAe,OAAO,KAAqB,aAChD,SAAS,MAAM,QAAQ;GAAE;GAAK;EAAS,CAAC;EACzC,MAAM,qBAAqB,QAAwB,aAAa,KAAK,OAAO;EAE5E,MAAM,UAAoB,CAAC;EAE3B,MAAM,cAAc,mBAAmB;GACtC,KAAK,OAAO,MAAM;GAClB,QAAQ,QAAQ;GAChB,WAAW,mBAAmB,MAAM;EACrC,CAAC;EACD,MAAM,UAA6B;GAClC,IAAI,OAAO,IAAI;GACf,SAAS,YAAY;IACpB,QAAQ,KAAK,OAAO;GACrB;GACA;EACD;EACA,MAAM,cAAc,MAAM,kBACzB,UACA;GAAE;GAAmB,UAAU;EAAc,GAC7C,OACD;EACA,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U;GACV;GACA;GACA;EACD,CAAC;EACD,MAAM,cAAoC,EAAE,QAAQ,EAAE,MAAM,SAAS,OAAO,KAAK,EAAE;EACnF,OAAO,SAAS;GAAE,GAAG,OAAO;IAAS,uBAAuB;EAAQ;EACpE,OAAO,QAAQ;GACd,GAAG,OAAO;GACV,QAAQ;IAAE,GAAG,OAAO,OAAO;KAAS,uBAAuB;GAAY;EACxE;EACA,MAAM,aAAa,OAAO;EAG1B,OAAO,SAAS,OAAO,YAAY;GAElC,IAAI,iBAAiB,QAAQ,MAAM,MAAM,SACxC,MAAM,IAAI,MAAM,oBAAoB;GAErC,MAAM,QAAQ,SAAS,OAAO;GAC9B,WAAW,OAAO;GAClB,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC;;AAGD,MAAM,uBAAuB,6BAA6B,qBAAqB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { type Config, definePlugin, type Endpoint, type PayloadRequest } from 'payload'\n\nimport { itemCollectionsOf } from './binding/report'\nimport { captureRequest } from './capture/captureRequest'\nimport { makeExclusionHandler } from './capture/exclusionEndpoint'\nimport { proxyEndpoints } from './capture/proxyEndpoint'\nimport { trackerEndpoint } from './capture/trackerEndpoint'\nimport { assertMaintainRegistered, TASK_SLUGS } from './core/jobs'\nimport { type AnalyticsPluginOptions, resolveOptions, type ScopeCallSite } from './core/options'\nimport { createRegistry, withoutRevenue } from './core/registry'\nimport { CURRENCY_PATTERN } from './goals/currency'\nimport { makeGoalsHandler } from './goals/goalsEndpoint'\nimport { applyConfigRevenueVisibility } from './goals/moneyFields'\nimport { configGoalsResolver } from './goals/resolver'\nimport type { Goal } from './goals/types'\nimport { addComponentDependency, FLAG_DEPENDENCY } from './plugin/adminDependencies'\nimport { expectedCollections } from './plugin/collectionChecks'\nimport { createRuntimeFactory } from './plugin/createRuntime'\nimport { makeDocumentHandler } from './plugin/documentEndpoint'\nimport { makeFlagsHandler } from './plugin/flagsEndpoint'\nimport { restrictJobControls } from './plugin/jobsAccess'\nimport {\n\taddStateCollection,\n\ttype CollectionContext,\n\tcacheCollectionOf,\n\tconfigCollections,\n\tsyncCollectionOf,\n} from './plugin/pluginCollections'\nimport { makeQueryHandler } from './plugin/queryEndpoint'\nimport { makeRealtimeHandler } from './plugin/realtimeEndpoint'\nimport { makeRefreshHandler } from './plugin/refreshEndpoint'\nimport { registerTranslations } from './plugin/registerTranslations'\nimport { relabelFactoryFields } from './plugin/relabelFields'\nimport { assertRoutesReachable } from './plugin/routeChecks'\nimport {\n\tANALYTICS_CONFIG_KEY,\n\ttype AnalyticsAdminCustom,\n\tpluginEndpoint,\n\troutePaths,\n} from './plugin/routes'\nimport { getRuntime, resolveGoalsFor, resolveRegistryFor, runtimeFactoryOf } from './plugin/runtime'\nimport { addTask, schemaOnly } from './plugin/schemaOnly'\nimport { changedScopes, type ScopeChange } from './plugin/scopeChange'\nimport { makeSourcesHandler } from './plugin/sourcesEndpoint'\nimport { fillUnbundledLanguages, unbundledLanguages } from './plugin/unbundledLanguages'\nimport { warmTask } from './plugin/warmTask'\nimport { syncTask } from './sync/syncTask'\nimport { createStrictTimezoneResolver, createTimezoneResolver } from './timeframe/reportingTimezone'\nimport { keys } from './translations/keys'\nimport { createStaticLabels } from './translations/staticLabel'\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\n/**\n * Rereads the scopes a providers or goals save touched, on the instance that wrote; every other\n * instance catches up through its own probe.\n */\nconst configChanged =\n\t(collection: 'providers' | 'goals') =>\n\t(change: ScopeChange, req: PayloadRequest): void => {\n\t\tgetRuntime(req.payload)?.configChanged?.(collection, changedScopes(change))\n\t}\n\nconst addEndpoints = (config: Config, ...endpoints: Endpoint[]): void => {\n\tconfig.endpoints = [...(config.endpoints ?? []), ...endpoints]\n}\n\nexport const analytics = definePlugin<AnalyticsPluginOptions>({\n\tslug: '@10x-media/analytics',\n\tplugin: async ({ config, plugins: _plugins, ...options }): Promise<Config> => {\n\t\tconst disabled = options.disabled === true\n\t\t// Switched off, nothing reads through the adapters: they are only asked for their schema.\n\t\tconst resolved = resolveOptions(options, { requireAdapters: !disabled })\n\t\tconst resolveScope = async (req: PayloadRequest, callSite: ScopeCallSite) =>\n\t\t\tresolved.scope.resolve({ req, callSite })\n\t\tconst resolveAdminScope = (req: PayloadRequest) => resolveScope(req, 'admin')\n\t\t// What the collection checks warn about waits for the instance's logger, at init.\n\t\tconst notices: string[] = []\n\t\t// Read before the plugin merges its own strings in, so the app's own still win.\n\t\tconst staticLabel = createStaticLabels({\n\t\t\tapp: config.i18n?.translations,\n\t\t\tplugin: options.translations,\n\t\t\tunbundled: unbundledLanguages(config),\n\t\t})\n\t\tconst context: CollectionContext = {\n\t\t\tdb: config.db?.name,\n\t\t\tnotice: (message) => {\n\t\t\t\tnotices.push(message)\n\t\t\t},\n\t\t\tstaticLabel,\n\t\t}\n\t\tconst collections = await configCollections(\n\t\t\tresolved,\n\t\t\t{ resolveAdminScope, onChange: configChanged },\n\t\t\tcontext\n\t\t)\n\t\tconst sync = syncCollectionOf(resolved, resolveAdminScope, context)\n\t\tif (disabled) {\n\t\t\treturn schemaOnly(config, {\n\t\t\t\tresolved,\n\t\t\t\tcollections,\n\t\t\t\tcontext,\n\t\t\t\t...(sync ? { sync } : {}),\n\t\t\t\t...(options.translations ? { translations: options.translations } : {}),\n\t\t\t})\n\t\t}\n\t\tconst routes = routePaths(resolved.routes.base)\n\t\t// Whatever is mounted before the plugin runs belongs to the host or an earlier plugin.\n\t\tconst earlierEndpoints = new Set(config.endpoints ?? [])\n\t\tconst money = resolved.revenue.enabled\n\t\t// A runtime provider's capabilities are unknown at config time, so providers open the\n\t\t// widget and endpoint gates that otherwise follow the config adapters' capabilities.\n\t\tconst providersEnabled =\n\t\t\tresolved.providers.collection.enabled || Boolean(resolved.providers.resolve)\n\t\t// Read before the adapters register: only a host that turned it on may carry concurrency keys.\n\t\tconst jobsConcurrency = config.jobs?.enableConcurrencyControl === true\n\t\tregisterTranslations(config, options.translations)\n\t\tfillUnbundledLanguages(config)\n\t\tconst registry = createRegistry(resolved.adapters, resolved.defaultAdapter)\n\t\t// Adapters ask for a scope to stamp a visitor's hit with, so theirs is the capture call\n\t\t// site, asked without the signed-in user or their cookies.\n\t\tconst resolveCaptureScope = (req: PayloadRequest) =>\n\t\t\tresolveScope(captureRequest(req), 'capture')\n\t\t/**\n\t\t * Whether a scope's own committed provider documents grant it this adapter (a beacon decrypts\n\t\t * nothing). Handed to adapters only when `scope.resolve` and the providers collection both run.\n\t\t */\n\t\tconst adapterGrantedForScope = async (\n\t\t\treq: PayloadRequest,\n\t\t\tscope: string | null,\n\t\t\tadapterId: string\n\t\t): Promise<boolean> => {\n\t\t\tconst runtime = getRuntime(req.payload)\n\t\t\tif (!runtime) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (runtime.providerGranted) {\n\t\t\t\treturn runtime.providerGranted(scope, adapterId)\n\t\t\t}\n\t\t\tconst { grants } = await resolveRegistryFor(runtime, { payload: req.payload, req, scope })\n\t\t\treturn grants.has(adapterId)\n\t\t}\n\t\tconst configGoals = configGoalsResolver(resolved.goals, resolved.purchaseGoal)\n\t\t/** The goals of the instance a request reached, which adapters resolve at ingest. */\n\t\tconst resolveGoals = (req: PayloadRequest, scope?: string | null): Promise<Goal[]> => {\n\t\t\tconst runtime = getRuntime(req.payload)\n\t\t\treturn runtime ? resolveGoalsFor(runtime, req, scope) : configGoals.resolve(req, scope)\n\t\t}\n\t\tconfig.collections = [...(config.collections ?? []), ...collections]\n\t\tconst timezoneArgs = { option: resolved.reportingTimezone, resolveScope: resolveAdminScope }\n\t\tconst resolveTimezone = createTimezoneResolver(timezoneArgs)\n\t\tconst resolveTimezoneStrict = createStrictTimezoneResolver(timezoneArgs)\n\t\tconst resolveCurrency = async (\n\t\t\treq: PayloadRequest,\n\t\t\tscope?: string | null\n\t\t): Promise<string | undefined> => {\n\t\t\tconst opt = resolved.revenue.currency\n\t\t\tif (opt === undefined) {\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst code =\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 resolveAdminScope(req) })\n\t\t\t\treturn code && CURRENCY_PATTERN.test(code) ? code : undefined\n\t\t\t} catch (err) {\n\t\t\t\treq.payload?.logger?.warn?.(\n\t\t\t\t\t`analytics: revenue.currency resolution failed, reporting revenue unformatted: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t}\n\t\tconst itemCollections = itemCollectionsOf(resolved.bindings)\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: resolveCaptureScope,\n\t\t\t\tresolveTimezone,\n\t\t\t\tresolveTimezoneStrict,\n\t\t\t\trevenue: {\n\t\t\t\t\tenabled: money,\n\t\t\t\t\tdimension: resolved.revenue.dimension,\n\t\t\t\t\tcurrency: resolveCurrency,\n\t\t\t\t\tconvert: resolved.revenue.convert,\n\t\t\t\t\tbrowserAmounts: resolved.revenue.browserAmounts,\n\t\t\t\t\torderSignature: resolved.revenue.orderSignature,\n\t\t\t\t},\n\t\t\t\tresolveGoals,\n\t\t\t\t...(resolved.scoped && resolved.providers.collection.enabled\n\t\t\t\t\t? { adapterGrantedForScope }\n\t\t\t\t\t: {}),\n\t\t\t\ttrustedProxyHops: resolved.trustedProxyHops,\n\t\t\t\ttrustedPlatform: resolved.trustedPlatform,\n\t\t\t\tallowedOrigins: resolved.capture.allowedOrigins,\n\t\t\t\t...(itemCollections.size > 0\n\t\t\t\t\t? {\n\t\t\t\t\t\t\titems: {\n\t\t\t\t\t\t\t\tcollections: itemCollections,\n\t\t\t\t\t\t\t\tpages: resolved.capture.autoCapture.items.pages,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\troutes,\n\t\t\t\tsdks: resolved.sdks,\n\t\t\t\tjobs: resolved.jobs,\n\t\t\t\tjobsConcurrency,\n\t\t\t\tnotice: context.notice,\n\t\t\t})\n\t\t}\n\t\tassertMaintainRegistered(\n\t\t\tresolved.jobs,\n\t\t\t(config.jobs?.tasks ?? []).some((task) => task.slug === TASK_SLUGS.maintain)\n\t\t)\n\t\t// After registration: an adapter declares what the install measures once it is registered,\n\t\t// and one that declares no revenue then is read as it is rather than as a copy.\n\t\tconst readRegistry = money ? registry : withoutRevenue(registry)\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\taddEndpoints(config, { method: 'get', path: routes.live, handler: makeRealtimeHandler() })\n\t\t}\n\t\tif (Object.keys(resolved.bindings).length > 0) {\n\t\t\taddEndpoints(config, { method: 'get', path: routes.document, handler: makeDocumentHandler() })\n\t\t}\n\t\taddEndpoints(\n\t\t\tconfig,\n\t\t\t{ method: 'get', path: routes.sources, handler: makeSourcesHandler() },\n\t\t\t{ method: 'get', path: routes.goals, handler: makeGoalsHandler() },\n\t\t\t{ method: 'get', path: routes.query, handler: makeQueryHandler() },\n\t\t\t{ method: 'post', path: routes.refresh, handler: makeRefreshHandler() }\n\t\t)\n\t\tif (resolved.capture.exclusion) {\n\t\t\taddEndpoints(config, {\n\t\t\t\tmethod: 'get',\n\t\t\t\tpath: routes.exclusion,\n\t\t\t\thandler: makeExclusionHandler(),\n\t\t\t})\n\t\t}\n\t\t// One answer serves the view, the widgets and the route, so the flags an install draws and\n\t\t// the route serving them cannot diverge. A host's own flag needs no route, only the import map.\n\t\tconst countryFlags = resolved.countryFlags\n\t\tif (countryFlags === true) {\n\t\t\taddEndpoints(config, {\n\t\t\t\tmethod: 'get',\n\t\t\t\tpath: routes.flagsPattern,\n\t\t\t\thandler: makeFlagsHandler(),\n\t\t\t})\n\t\t} else if (countryFlags !== false) {\n\t\t\taddComponentDependency(config, FLAG_DEPENDENCY, countryFlags.Component)\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\taddEndpoints(config, ...proxyEndpoints(routes), trackerEndpoint(routes))\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\trevenue: money,\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\tcountryFlags,\n\t\t\t\tstaticLabel,\n\t\t\t\toverrides: resolved.widgets.overrides,\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, title: staticLabel(keys.viewTitle) })\n\t\tconst { jobs } = resolved\n\t\tif (jobs !== false && resolved.cache.warm.enabled) {\n\t\t\taddTask(\n\t\t\t\tconfig,\n\t\t\t\twarmTask({\n\t\t\t\t\tschedule: jobs.warm,\n\t\t\t\t\twindowHours: resolved.cache.warm.windowHours,\n\t\t\t\t\tmaxReads: resolved.cache.warm.maxReads,\n\t\t\t\t\tconcurrency: jobsConcurrency,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tif (sync) {\n\t\t\tconfig.collections = [...(config.collections ?? []), sync]\n\t\t\tif (jobs !== false) {\n\t\t\t\taddTask(\n\t\t\t\t\tconfig,\n\t\t\t\t\tsyncTask({\n\t\t\t\t\t\tschedule: jobs.sync,\n\t\t\t\t\t\tlookbackDays: resolved.sync.lookbackDays,\n\t\t\t\t\t\tcollectionSlug: resolved.sync.collection.slug,\n\t\t\t\t\t\tadapterIds: resolved.sync.adapters,\n\t\t\t\t\t\tscopes: resolved.scope.list,\n\t\t\t\t\t\tconcurrency: jobsConcurrency,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tconst cache = cacheCollectionOf(resolved, context)\n\t\tif (cache) {\n\t\t\tconfig.collections = [...(config.collections ?? []), cache]\n\t\t}\n\t\taddStateCollection(config, resolved, context)\n\t\trestrictJobControls(config)\n\t\t// Hidden per config rather than per process, so two instances answer for themselves; a later\n\t\t// plugin's fields (form-builder's action blocks) take their factory's own `revenue` option.\n\t\tapplyConfigRevenueVisibility(config, money)\n\t\trelabelFactoryFields(config, staticLabel)\n\t\tconfig.endpoints = (config.endpoints ?? []).map((endpoint) =>\n\t\t\tearlierEndpoints.has(endpoint) ? endpoint : pluginEndpoint(endpoint)\n\t\t)\n\t\t// Checked against everything registered so far, the plugin's own collections included; what a\n\t\t// later plugin adds is caught when a runtime is built from the assembled config.\n\t\tassertRoutesReachable(resolved.routes.base, {\n\t\t\tcollections: config.collections ?? [],\n\t\t\tendpoints: config.endpoints,\n\t\t})\n\t\tconst factory = createRuntimeFactory({\n\t\t\tresolved,\n\t\t\tnotices,\n\t\t\tcollections: expectedCollections(config.collections),\n\t\t\tregistry: readRegistry,\n\t\t\tresolveScope,\n\t\t\tresolveTimezone,\n\t\t\tresolveCurrency,\n\t\t})\n\t\tconst adminCustom: AnalyticsAdminCustom = { routes: { base: resolved.routes.base } }\n\t\tconfig.custom = { ...config.custom, [ANALYTICS_CONFIG_KEY]: factory }\n\t\tconfig.admin = {\n\t\t\t...config.admin,\n\t\t\tcustom: { ...config.admin?.custom, [ANALYTICS_CONFIG_KEY]: adminCustom },\n\t\t}\n\t\tconst prevOnInit = config.onInit\n\t\t// Validation only: the runtime builds on first use either way, and is built here so consumer\n\t\t// init code (seeding, cache warming, sync passes) runs against a warm one.\n\t\tconfig.onInit = async (payload) => {\n\t\t\t// Without the factory every endpoint answers 503; a boot error names the cause instead.\n\t\t\tif (runtimeFactoryOf(payload.config) !== factory) {\n\t\t\t\tthrow new Error(RUNTIME_FACTORY_LOST)\n\t\t\t}\n\t\t\tawait factory.validate(payload)\n\t\t\tgetRuntime(payload)\n\t\t\tawait prevOnInit?.(payload)\n\t\t}\n\t\treturn config\n\t},\n})\n\n/** Said at boot when a step after the plugin dropped its runtime from `config.custom`. */\nconst RUNTIME_FACTORY_LOST = `analytics: config.custom[\"${ANALYTICS_CONFIG_KEY}\"] no longer holds the analytics runtime: a plugin or config step that runs after analytics replaced config.custom instead of spreading it. Spread the existing value there ({ ...config.custom, ... }), or list analytics after that plugin.`\n\nexport { isAdminUser } from './access/adminUser'\nexport { type TenantMembershipOptions, tenantMembership } from './access/membership'\nexport { type GatedScope, type ReadPrincipal, SYSTEM } from './access/principal'\nexport { ProviderHttpError, parseRetryAfter } from './adapters/http/fetchJson'\nexport type { ReportMode, ReportOption } from './binding/report'\nexport type {\n\tAnalyticsBinding,\n\tBindingContext,\n\tBindingDoc,\n\tHostnameResolver,\n\tPathResolver,\n} from './binding/types'\nexport type { CapabilityRequirement, FilterPair, SerializedCapabilities } from './core/capabilities'\nexport {\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\tPLATFORM_SCOPE,\n} from './core/contract'\nexport type {\n\tAnalyticsAccessOptions,\n\tAnalyticsCacheCollectionOptions,\n\tAnalyticsCacheOptions,\n\tAnalyticsCaptureOptions,\n\tAnalyticsCollectionOptions,\n\tAnalyticsComponent,\n\tAnalyticsConcurrencyOptions,\n\tAnalyticsCountryFlags,\n\tAnalyticsCrossScopeOptions,\n\tAnalyticsExclusionOptions,\n\tAnalyticsGoalsCollectionOptions,\n\tAnalyticsGoalsOptions,\n\tAnalyticsHooksOptions,\n\tAnalyticsJobsOptions,\n\tAnalyticsPluginOptions,\n\tAnalyticsPluginOptions as PluginOptions,\n\tAnalyticsReadAccess,\n\tAnalyticsRevenueOptions,\n\tAnalyticsRoutesOptions,\n\tAnalyticsScopeOptions,\n\tAnalyticsSourceOptions,\n\tAnalyticsSyncCollectionOptions,\n\tAnalyticsSyncOptions,\n\tAnalyticsTaskOptions,\n\tAnalyticsViewAccess,\n\tAnalyticsViewOptions,\n\tAnalyticsWarmOptions,\n\tAnalyticsWidgetOverride,\n\tAnalyticsWidgetOverrides,\n\tAnalyticsWidgetsOptions,\n\tAutoCaptureOptions,\n\tCaptureGate,\n\tCaptureGateArgs,\n\tCaptureSlotOption,\n\tCollectionOverrides,\n\tCrossScopeAccess,\n\tCurrencyConverter,\n\tCurrencyResolver,\n\tDefaultSourceFunction,\n\tDefaultSourceRule,\n\tExclusionSitesResolver,\n\tItemCaptureOptions,\n\tOwnSource,\n\tProviderHostsOptions,\n\tProvidersCollectionOptions,\n\tProvidersOptions,\n\tProvidersResolve,\n\tProvidersResolveArgs,\n\tScopeCallSite,\n\tScopeLabelResolver,\n\tScopeListResolver,\n\tScopeMemberAccess,\n\tScopeResolver,\n\tSourcePolicy,\n\tSourcePolicyFunction,\n\tSourceRef,\n\tTimezoneResolver,\n} from './core/options'\nexport type {\n\tAnalyticsSdks,\n\tGa4Client,\n\tGa4ClientOptions,\n\tGa4ReportResponse,\n\tGa4ReportRow,\n\tGa4Sdk,\n\tMaxmindReader,\n\tMaxmindSdk,\n} from './core/sdks'\nexport type {\n\tServerEventInput,\n\tServerTrack,\n\tServerTrackIdentity,\n\tServerTrackOptions,\n} from './core/serverEvent'\nexport { AnalyticsTrackError } from './core/serverEvent'\nexport { BUILT_IN_WIDGET_SLUGS, type BuiltInWidgetSlug } from './core/widgetSlugs'\nexport type * from './exports/adapters/contract'\nexport type { AnalyticsAttributes } from './exports/attributes'\nexport type {\n\tAnalyticsFieldsOptions,\n\tAnalyticsMetricLabel,\n\tAnalyticsMetricLabels,\n\tAnalyticsStatBaseOptions,\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 {\n\tFieldBreakdown,\n\tFieldBreakdownRow,\n\tFieldReadResult,\n\tFieldReadStatus,\n\tReadForFieldArgs,\n} from './fields/readForDocument'\nexport { readForField } from './fields/readForDocument'\nexport type {\n\tGoalCollectionFieldOverrides,\n\tGoalFieldOverride,\n} from './goals/collection'\nexport { GOALS_SLUG } from './goals/collection'\nexport {\n\tCURRENCY_ATTRIBUTE,\n\tEVENT_ATTRIBUTE,\n\tEVENT_PROP_PREFIX,\n\tGOAL_ATTRIBUTE,\n\tITEM_ATTRIBUTE,\n\tITEM_CLICK_EVENT,\n\tITEM_NAME_ATTRIBUTE,\n\tMAX_ITEMS_PER_BEACON,\n\tPURCHASE_GOAL_SLUG,\n\tVALUE_ATTRIBUTE,\n} from './goals/constants'\nexport type { GoalFieldOptions } from './goals/goalField'\nexport { goalField, goalSlug } from './goals/goalField'\nexport type { GoalsResponse, WireGoal } from './goals/goalsEndpoint'\nexport type { AnalyticsLinkFieldsOptions } from './goals/linkFields'\nexport { analyticsLinkFields } from './goals/linkFields'\nexport type { BrowserAmounts, OrderSignatureMode } from './goals/match'\nexport type { GoalSource } from './goals/resolver'\nexport type {\n\tPurchaseInput as ServerPurchaseInput,\n\tRefundInput as ServerRefundInput,\n} from './goals/serverRevenue'\nexport { purchase, refund } from './goals/serverRevenue'\nexport type {\n\tGoalActionDefinition,\n\tGoalActionRunArgs,\n\tTrackGoalActionOptions,\n} from './goals/trackGoalAction'\nexport { GOAL_ACTION_TYPE, trackGoalAction } from './goals/trackGoalAction'\nexport type { Goal } from './goals/types'\nexport { STATE_SLUG } from './native/collections/slugs'\nexport type { RebuildDaysInput, RebuildDaysReport } from './native/engine/rebuild'\nexport {\n\ttype ItemSignatureMode,\n\titemAttributesFor,\n\tsignItemRef,\n} from './native/ingest/itemSignature'\nexport { signOrderId } from './native/ingest/orderSignature'\nexport { trackServerEvent } from './native/ingest/serverTrack'\nexport { rebuildDays } from './native/rebuildDays'\nexport {\n\tcreateGuardedFetch,\n\ttype GuardedFetch,\n\ttype GuardedFetchOptions,\n} from './net/guardedFetch'\nexport type { TrustedPlatform } from './net/platform'\nexport type { CollectionFieldOverride } from './plugin/collectionFields'\nexport {\n\tANALYTICS_ERROR_CODES,\n\ttype AnalyticsError,\n\ttype AnalyticsErrorCode,\n\tanalyticsError,\n\treadErrorCode,\n} from './plugin/errors'\nexport type { RoutesConfigSource } from './plugin/routes'\nexport {\n\tanalyticsRoutes,\n\tDEFAULT_ROUTE_BASE,\n\ttype RouteBase,\n\ttype RoutePaths,\n\troutePaths,\n} from './plugin/routes'\nexport type {\n\tBuildSecretField,\n\tConnectionAccess,\n\tConnectionFieldAccess,\n\tProviderCollectionFieldOverrides,\n\tProviderFieldOverride,\n\tProviderFieldsOptions,\n} from './providers/collection'\nexport { analyticsProviderFields, PROVIDERS_SLUG } from './providers/collection'\nexport type { ProviderDoc, ProviderFactoryContext, ProviderId } from './providers/factory'\nexport { adapterFromProviderDoc, PROVIDER_IDS } from './providers/factory'\nexport type { HostPattern } from './providers/hosts'\nexport { type ProviderHostPolicy, resolveHostPolicy } from './providers/hosts'\nexport { type RefreshProvidersOptions, refreshProviders } from './providers/refresh'\nexport { CONNECTION_PATHS, SECRET_PATHS } from './providers/secrets'\nexport type { QueryError, QueryErrorCode } from './query/errors'\nexport type {\n\tItemLabels,\n\tQueryErrorResponse,\n\tQueryResponse,\n\tQuerySourceRef,\n\tSerializedAnalyticsQuery,\n} from './query/response'\nexport type {\n\tAfterReadAnswer,\n\tAfterReadArgs,\n\tAfterReadHook,\n\tReadOrigin,\n} from './surfacing/afterRead'\nexport { CACHE_SLUG } from './surfacing/cacheCollection'\nexport type {\n\tCacheEntry,\n\tCacheSetOptions,\n\tCacheStore,\n\tReadRecipe,\n\tRecipeWindow,\n} from './surfacing/cacheStore'\nexport { SYNC_SLUG } from './sync/collection'\nexport { TIMEFRAME_PRESETS, type TimeframePreset } from './timeframe/presets'\nexport type { GoalMatch, RevenueItem, TrackerGoal } from './tracker/config'\nexport type { TranslationsOption } from './translations'\nexport {\n\tkeys,\n\ttype PluralCategory,\n\ttype PluralName,\n\ttype PluralVariant,\n\tpluralKeys,\n\ttype SingularKey,\n\ttype TranslationKey,\n} from './translations/keys'\nexport type { CustomWidgetDef } from './widgets/customWidget'\nexport {\n\ttype AnalyticsDefaultLayoutOptions,\n\tanalyticsDefaultLayout,\n} from './widgets/defaultLayout'\nexport { analyticsDefaultWidgets } from './widgets/defaults'\nexport { widgetFilters } from './widgets/filterField'\nexport type { StoredSourceRead, SubstitutedSource } from './widgets/prepareWidgetRead'\nexport type {\n\tReadForWidgetArgs,\n\tWidgetReadResult,\n\tWidgetReadStatus,\n} from './widgets/readForWidget'\nexport { readForWidget } from './widgets/readForWidget'\nexport type {\n\tBreakdownRow,\n\tReadForWidgetBreakdownArgs,\n\tWidgetBreakdownResult,\n} from './widgets/readForWidgetBreakdown'\nexport { readForWidgetBreakdown } from './widgets/readForWidgetBreakdown'\nexport type {\n\tGoalRow,\n\tReadForWidgetGoalsArgs,\n\tWidgetGoalsResult,\n} from './widgets/readForWidgetGoals'\nexport { readForWidgetGoals } from './widgets/readForWidgetGoals'\nexport type {\n\tReadForWidgetRealtimeArgs,\n\tRealtimePoint,\n\tWidgetRealtimeResult,\n\tWidgetRealtimeStatus,\n} from './widgets/readForWidgetRealtime'\nexport { readForWidgetRealtime } from './widgets/readForWidgetRealtime'\nexport type {\n\tReadForWidgetSeriesArgs,\n\tSeriesGranularity,\n\tSeriesPoint,\n\tWidgetSeriesResult,\n} from './widgets/readForWidgetSeries'\nexport { readForWidgetSeries } from './widgets/readForWidgetSeries'\nexport type { ReadNotices } from './widgets/readMeta'\nexport type { WidgetFilter } from './widgets/types'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,MAAM,iBACJ,gBACA,QAAqB,QAA8B;CACnD,WAAW,IAAI,OAAO,GAAG,gBAAgB,YAAY,cAAc,MAAM,CAAC;AAC3E;AAED,MAAM,gBAAgB,QAAgB,GAAG,cAAgC;CACxE,OAAO,YAAY,CAAC,GAAI,OAAO,aAAa,CAAC,GAAI,GAAG,SAAS;AAC9D;AAEA,MAAa,YAAY,aAAqC;CAC7D,MAAM;CACN,QAAQ,OAAO,EAAE,QAAQ,SAAS,UAAU,GAAG,cAA+B;EAC7E,MAAM,WAAW,QAAQ,aAAa;EAEtC,MAAM,WAAW,eAAe,SAAS,EAAE,iBAAiB,CAAC,SAAS,CAAC;EACvE,MAAM,eAAe,OAAO,KAAqB,aAChD,SAAS,MAAM,QAAQ;GAAE;GAAK;EAAS,CAAC;EACzC,MAAM,qBAAqB,QAAwB,aAAa,KAAK,OAAO;EAE5E,MAAM,UAAoB,CAAC;EAE3B,MAAM,cAAc,mBAAmB;GACtC,KAAK,OAAO,MAAM;GAClB,QAAQ,QAAQ;GAChB,WAAW,mBAAmB,MAAM;EACrC,CAAC;EACD,MAAM,UAA6B;GAClC,IAAI,OAAO,IAAI;GACf,SAAS,YAAY;IACpB,QAAQ,KAAK,OAAO;GACrB;GACA;EACD;EACA,MAAM,cAAc,MAAM,kBACzB,UACA;GAAE;GAAmB,UAAU;EAAc,GAC7C,OACD;EACA,MAAM,OAAO,iBAAiB,UAAU,mBAAmB,OAAO;EAClE,IAAI,UACH,OAAO,WAAW,QAAQ;GAC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AO,KAAK,EAAE;EACnF,OAAO,SAAS;GAAE,GAAG,OAAO;IAAS,uBAAuB;EAAQ;EACpE,OAAO,QAAQ;GACd,GAAG,OAAO;GACV,QAAQ;IAAE,GAAG,OAAO,OAAO;KAAS,uBAAuB;GAAY;EACxE;EACA,MAAM,aAAa,OAAO;EAG1B,OAAO,SAAS,OAAO,YAAY;GAElC,IAAI,iBAAiB,QAAQ,MAAM,MAAM,SACxC,MAAM,IAAI,MAAM,oBAAoB;GAErC,MAAM,QAAQ,SAAS,OAAO;GAC9B,WAAW,OAAO;GAClB,MAAM,aAAa,OAAO;EAC3B;EACA,OAAO;CACR;AACD,CAAC;;AAGD,MAAM,uBAAuB,6BAA6B,qBAAqB"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { valueAt } from "../../core/values.js";
|
|
2
2
|
import { clientIpFromHeaders } from "../ingest/clientIp.js";
|
|
3
|
-
import { geoOf, loadsMaxmindAtRuntime } from "./geoResolver.js";
|
|
4
3
|
import { loadMaxmind } from "../../plugin/peers.js";
|
|
4
|
+
import { geoOf, loadsMaxmindAtRuntime } from "./geoResolver.js";
|
|
5
5
|
//#region src/native/geo/maxmindResolver.ts
|
|
6
6
|
/**
|
|
7
7
|
* MaxMind GeoLite2 resolver, opened on first use. Any failure degrades to empty geo after one
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { isRecord } from "../../core/values.js";
|
|
2
2
|
import { clientIpFromHeaders } from "./clientIp.js";
|
|
3
|
-
import { MAX_SINCE_MS } from "../../goals/constants.js";
|
|
4
3
|
import { DEFAULT_BROWSER_AMOUNTS, completionAmounts } from "../../goals/match.js";
|
|
4
|
+
import { MAX_SINCE_MS } from "../../goals/constants.js";
|
|
5
5
|
import { boundedValue, dedupeKeyFor, isRefund, reconcileMoney, sanitizeOrderId } from "./revenue.js";
|
|
6
6
|
import { extractUtm } from "./utm.js";
|
|
7
7
|
import { clickIdOf } from "./source.js";
|
|
@@ -3,6 +3,7 @@ import { GeoResolver } from "./geo/geoResolver.js";
|
|
|
3
3
|
import { CapsOption } from "./store/caps.js";
|
|
4
4
|
import { ItemSignatureMode } from "./ingest/itemSignature.js";
|
|
5
5
|
import { AnalyticsAdapter } from "../core/contract.js";
|
|
6
|
+
import { AdapterLabelOption } from "../core/sourceLabel.js";
|
|
6
7
|
import { RebuildDaysInput, RebuildDaysReport } from "./engine/rebuild.js";
|
|
7
8
|
import { WriteBufferOption } from "./engine/writeBuffer.js";
|
|
8
9
|
import { BotFilter } from "./ingest/bots.js";
|
|
@@ -38,6 +39,11 @@ interface NativeToday {
|
|
|
38
39
|
maxAgeMs?: number;
|
|
39
40
|
}
|
|
40
41
|
interface NativeOptions {
|
|
42
|
+
/**
|
|
43
|
+
* The source's name in pickers and listings: a string, a map by admin language (read like
|
|
44
|
+
* `view.navLabel`), or a function naming it per reader and scope. Default `'Payload'`.
|
|
45
|
+
*/
|
|
46
|
+
label?: AdapterLabelOption;
|
|
41
47
|
/**
|
|
42
48
|
* Where each event's country, region and city come from. One that throws costs the event its
|
|
43
49
|
* location, never the event, and is logged at most once an hour while it fails.
|
|
@@ -4,9 +4,11 @@ import { currentDate } from "../core/clock.js";
|
|
|
4
4
|
import { isDestroyed } from "../plugin/destroy.js";
|
|
5
5
|
import { routePaths } from "../plugin/routes.js";
|
|
6
6
|
import { getRuntime } from "../plugin/runtime.js";
|
|
7
|
+
import { adapterLabel } from "../core/sourceLabel.js";
|
|
7
8
|
import { DEFAULT_STORE_SLUGS } from "./collections/slugs.js";
|
|
8
9
|
import { resolveCollectionOption } from "../core/collectionOption.js";
|
|
9
10
|
import { DEFAULT_JOBS } from "../core/jobs.js";
|
|
11
|
+
import { MAXMIND_SDK_WARNING, isProductionBuild } from "../plugin/peers.js";
|
|
10
12
|
import "../goals/match.js";
|
|
11
13
|
import { LEGACY_NATIVE_OPTIONS, assertNoLegacyOptions } from "../core/legacyOptions.js";
|
|
12
14
|
import { dbKind, isD1 } from "../db/kind.js";
|
|
@@ -27,7 +29,6 @@ import { itemIdTypes } from "../items/collectionIdType.js";
|
|
|
27
29
|
import { itemRefKey } from "./ingest/itemSignature.js";
|
|
28
30
|
import { makeServerTrack } from "./ingest/serverTrack.js";
|
|
29
31
|
import { createKeepAlive } from "../plugin/keepAlive.js";
|
|
30
|
-
import { MAXMIND_SDK_WARNING, isProductionBuild } from "../plugin/peers.js";
|
|
31
32
|
import { stateCollection } from "./collections/state.js";
|
|
32
33
|
import { addTask, schemaOnlyTask } from "../plugin/schemaOnly.js";
|
|
33
34
|
import { aggregatesCollection } from "./collections/aggregates.js";
|
|
@@ -364,7 +365,7 @@ function native(options = {}) {
|
|
|
364
365
|
};
|
|
365
366
|
return {
|
|
366
367
|
id: NATIVE_ADAPTER_ID,
|
|
367
|
-
label
|
|
368
|
+
...adapterLabel(options.label, "Payload", "native({ label })"),
|
|
368
369
|
get capabilities() {
|
|
369
370
|
return capabilities;
|
|
370
371
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nativeAdapter.js","names":[],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcreateLocalReq,\n\ttype Payload,\n\ttype PayloadHandler,\n\ttype PayloadRequest,\n} from 'payload'\nimport { captureRequest } from '../capture/captureRequest'\nimport type { CaptureSupport } from '../core/capture'\nimport { currentDate } from '../core/clock'\nimport {\n\ttype AnalyticsCollectionOptions,\n\ttype ResolvedCollectionOption,\n\tresolveCollectionOption,\n} from '../core/collectionOption'\nimport type {\n\tAdapterContext,\n\tAdapterRegisterContext,\n\tAdapterSchemaContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n} from '../core/contract'\nimport { type AdapterJobs, DEFAULT_JOBS } from '../core/jobs'\nimport { assertNoLegacyOptions, LEGACY_NATIVE_OPTIONS } from '../core/legacyOptions'\nimport type { MaxmindSdk } from '../core/sdks'\nimport type { IngestHostnameResolver } from '../core/serverEvent'\nimport { isRecord, kindOf } from '../core/values'\nimport { dbKind, isD1 } from '../db/kind'\nimport { DEFAULT_ORDER_SIGNATURE } from '../goals/match'\nimport { itemIdTypes } from '../items/collectionIdType'\nimport { shapeCollection } from '../plugin/collectionChecks'\nimport { isDestroyed } from '../plugin/destroy'\nimport { createKeepAlive } from '../plugin/keepAlive'\nimport { isProductionBuild, MAXMIND_SDK_WARNING } from '../plugin/peers'\nimport { DEFAULT_ROUTE_BASE, routePaths } from '../plugin/routes'\nimport { getRuntime } from '../plugin/runtime'\nimport { addTask, schemaOnlyTask } from '../plugin/schemaOnly'\nimport { TASK_SWEEP_BATCHES } from '../surfacing/cacheSweep'\nimport { aggregatesCollection } from './collections/aggregates'\nimport { hitsCollection } from './collections/hits'\nimport { DEFAULT_STORE_SLUGS, type StoreSlugs } from './collections/slugs'\nimport { stateCollection } from './collections/state'\nimport { DEFAULT_RAW_DAYS, nativeCapabilities } from './engine/capabilities'\nimport { createEngine } from './engine/engine'\nimport { closeNativeInstance, type NativeInstance, nativeInstanceFor } from './engine/instance'\nimport type { RebuildDaysInput, RebuildDaysReport } from './engine/rebuild'\nimport { createDailySalts } from './engine/salt'\nimport { createSiteHosts } from './engine/siteHosts'\nimport { createHitWriter, resolveWriteBuffer, type WriteBufferOption } from './engine/writeBuffer'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, needsMaxmindSdk, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { type BotFilter, resolveBotFilter } from './ingest/bots'\nimport { type IngestAttribution, type IngestResolvers, makeIngestHandler } from './ingest/endpoint'\nimport { type ItemSignatureMode, itemRefKey } from './ingest/itemSignature'\nimport type { ItemIngestOptions } from './ingest/normalizeEvent'\nimport { orderRefKey } from './ingest/orderSignature'\nimport {\n\ttype HostnameOption,\n\thostnameSet,\n\tresolveEventHostname,\n\tresolveHostnameOption,\n} from './ingest/resolveHostname'\nimport { makeServerTrack } from './ingest/serverTrack'\nimport { type CapsOption, resolveCaps } from './store/caps'\nimport { createEventStore } from './store/eventStore'\nimport { TWIN_WINDOW_MS } from './store/hits'\nimport { rawFilterMap } from './store/rawRead'\nimport { createSqlExecutor } from './store/sql/executor'\nimport { isSqliteThread, SQLITE_THREADS, type SqliteThread } from './store/sql/sqliteThread'\nimport { createStateStore } from './store/stateStore'\nimport {\n\tMAINTAIN_TASK_BUDGET_MS,\n\tMAINTAIN_TASK_SLUG,\n\ttype MaintainTaskOutput,\n\tmaintainTask,\n} from './tasks/maintainTask'\n\nexport type { EventHostnameResolver, HostnameOption } from './ingest/resolveHostname'\n\n/** How long the native engine keeps what it stores. */\nexport interface NativeRetention {\n\t/**\n\t * Days of raw hits kept, today counted: how far back filtered and hourly reads reach. `null`\n\t * keeps every hit. Default 90.\n\t */\n\trawDays?: number | null\n\t/**\n\t * Days of daily totals kept, today counted; at least `rawDays`, which must then be set too.\n\t * `null` keeps every day's. Default null.\n\t */\n\taggregateDays?: number | null\n}\n\n/** How the native engine reads the day still running. */\nexport interface NativeToday {\n\t/**\n\t * Hits up to which today is read live; above it, from a background snapshot of its totals.\n\t * Default 5,000 on Postgres, 2,000 on SQLite and MongoDB; 0 always reads a snapshot.\n\t */\n\tsnapshotAboveHits?: number\n\t/**\n\t * Ms a snapshot is served before a background refresh. Default grows with the day's hits (one\n\t * minute up to 50,000, five at 500,000) and with its counting cost. At least 1,000.\n\t */\n\tmaxAgeMs?: number\n}\n\nexport interface NativeOptions {\n\t/**\n\t * Where each event's country, region and city come from. One that throws costs the event its\n\t * location, never the event, and is logged at most once an hour while it fails.\n\t */\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\t/** Where the beacon endpoint listens, under `routes.api`. Default `<routes.base>/e`. */\n\tingestPath?: string\n\t/**\n\t * `true` batches hits in memory (200 hits or one second, at most 5,000 held); an object sets\n\t * `maxSize`, `maxAgeMs` or `maxPending`. Unset writes each as it arrives. Orders are never held.\n\t */\n\tbuffer?: WriteBufferOption\n\t/**\n\t * `'request'` (default) stores the request's host and ignores the body's claim; a list stores it\n\t * only when listed; a resolver decides per event, and null drops it.\n\t */\n\thostname?: HostnameOption\n\t/**\n\t * Platform domains that ingest under the null scope when the request resolves none. Tenant\n\t * domains need no entry: `scope.resolve` already answers for them.\n\t */\n\tplatformHostnames?: string[]\n\t/**\n\t * Drops crawlers, monitors and headless clients by user agent, on by default. A function receives\n\t * the raw agent; `false` counts every beacon. `trackServerEvent` is never filtered.\n\t */\n\tfilterBots?: boolean | BotFilter\n\t/**\n\t * `signature: 'required'` (default) keeps a page's item only when the server signed its ref\n\t * (`signItemRef`, `itemAttributesFor`); `'optional'` also keeps unsigned refs.\n\t */\n\titems?: { signature?: ItemSignatureMode }\n\t/**\n\t * Values each kind of daily total keeps per scope, day and hostname, the rest folded into one\n\t * `(other)` row; null keeps all. Kinds left out keep the defaults (`DEFAULT_CAPS`).\n\t */\n\tcaps?: CapsOption\n\tretention?: NativeRetention\n\t/** Today: read live while small, else from a snapshot (see `NativeToday`). */\n\ttoday?: NativeToday\n\t/** SQLite on a local file: where the engine's statements run (see `NativeSqlite`). */\n\tsqlite?: NativeSqlite\n\t/**\n\t * The engine's collections, renamed with `slug` and reshaped with `overrides`. An override may\n\t * change admin settings, access and `dbName`, but no field: the boot checks it.\n\t */\n\tcollections?: NativeCollections\n}\n\n/** The engine's collections, by what they hold; each defaults to its `analytics-` slug. */\nexport interface NativeCollections {\n\t/** `analytics-hits`, one row per hit. */\n\thits?: AnalyticsCollectionOptions\n\t/** `analytics-aggregates`, the daily totals. */\n\taggregates?: AnalyticsCollectionOptions\n\t/** `analytics-state`: the daily salts, day markers, leases and heartbeats. */\n\tstate?: AnalyticsCollectionOptions\n}\n\n/** Where the engine runs its statements on a local SQLite file. Remote libsql never blocks. */\nexport interface NativeSqlite {\n\t/**\n\t * `'auto'` (default) uses worker threads in WAL mode with `busyTimeout` >= 5,000 ms, else the main\n\t * thread, warning once. `ANALYTICS_SQLITE_THREAD` sets it where this does not.\n\t */\n\tthread?: SqliteThread\n}\n\n/** The config native adapter's id, which a `native` provider document grants to a scope. */\nexport const NATIVE_ADAPTER_ID = 'native'\n\nconst D1_REFUSAL =\n\t'analytics: native() does not support Cloudflare D1 (@payloadcms/db-d1-sqlite) yet. The vendor adapters (Plausible, Umami, GA4, PostHog) work on D1: drop native() from adapters, or run the app on MongoDB, Postgres or SQLite.'\n\nexport interface NativeAdapter extends AnalyticsAdapter {\n\t/**\n\t * Writes out what one instance holds back: its write buffer, and the server events that waited\n\t * on a transaction which has since ended.\n\t */\n\tflush(payload: Payload): Promise<void>\n\t/**\n\t * Takes one beacon as the ingest endpoint does, for a request built outside Payload's own\n\t * routing: what `ingestRoute` from `@10x-media/analytics/next` calls.\n\t */\n\treceive(req: PayloadRequest): Promise<Response>\n\t/** Counts a stretch of one instance's days again, as `rebuildDays` asks. */\n\trebuild(payload: Payload, input: RebuildDaysInput): Promise<RebuildDaysReport>\n}\n\n/** The native adapter among a runtime's adapters, recognized by its own seam. */\nexport const isNativeAdapter = (adapter: AnalyticsAdapter): adapter is NativeAdapter =>\n\tadapter.id === NATIVE_ADAPTER_ID &&\n\ttypeof Reflect.get(adapter, 'receive') === 'function' &&\n\ttypeof Reflect.get(adapter, 'flush') === 'function' &&\n\ttypeof Reflect.get(adapter, 'rebuild') === 'function'\n\n// The tracker itself is the client (`AnalyticsScripts` boots it), so there is nothing to\n// proxy or inject; the ingest path is carried by the tracker config resolver instead.\nconst nativeCapture: CaptureSupport = {\n\tproxy: { routes: [] },\n\tsnippet: () => ({ scripts: [] }),\n\tclient: { kind: 'native' },\n}\n\n/** What every store filters with, which is what is declared before a store exists. */\nconst ANY_STORE_FILTERS = rawFilterMap(['eq', 'contains'])\n\n/** Config-time check, so a mistyped mode fails the boot rather than every item at ingest. */\nconst itemSignatureMode = (value: unknown): ItemSignatureMode => {\n\tif (value === undefined || value === 'required') {\n\t\treturn 'required'\n\t}\n\tif (value === 'optional') {\n\t\treturn 'optional'\n\t}\n\tthrow new Error(\n\t\t`analytics: native items.signature must be 'required' or 'optional', got ${String(value)}`\n\t)\n}\n\n/** A `retention` option as given, refused unless it is unset, null or a whole number of days. */\nconst retentionDays = (\n\tretention: NativeRetention | undefined,\n\tname: keyof NativeRetention\n): number | null | undefined => {\n\tconst value = retention?.[name]\n\tif (value !== undefined && value !== null && (!Number.isInteger(value) || value < 1)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.${name} must be a whole number of days of at least 1, or null, got ${String(value)}`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `retention.rawDays`, so a window no read can start from fails the boot. */\nconst rawDaysOf = (retention: NativeRetention | undefined): number | null => {\n\tconst value = retentionDays(retention, 'rawDays')\n\treturn value === undefined ? DEFAULT_RAW_DAYS : value\n}\n\n/**\n * Config-time check of `retention.aggregateDays`: daily totals deleted while a day's raw hits are\n * still kept would be counted again on the next read, and deleted again after.\n */\nconst aggregateDaysOf = (\n\tretention: NativeRetention | undefined,\n\trawDays: number | null\n): number | null => {\n\tconst value = retentionDays(retention, 'aggregateDays') ?? null\n\tif (value === null) {\n\t\treturn null\n\t}\n\tif (rawDays === null || value < rawDays) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.aggregateDays (${value}) must be at least retention.rawDays (${rawDays ?? 'null, every hit kept'}): daily totals deleted while their raw hits are kept would be counted again`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `today`, so a value no read could use fails the boot. */\nconst todayOf = (today: NativeToday | undefined): NativeToday => {\n\tconst check = (name: keyof NativeToday, value: number | undefined, min: number): void => {\n\t\tif (value !== undefined && (!Number.isInteger(value) || value < min)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native today.${name} must be a whole number of at least ${min.toLocaleString('en-US')}, got ${String(value)}`\n\t\t\t)\n\t\t}\n\t}\n\tcheck('snapshotAboveHits', today?.snapshotAboveHits, 0)\n\tcheck('maxAgeMs', today?.maxAgeMs, 1_000)\n\treturn {\n\t\t...(today?.snapshotAboveHits === undefined\n\t\t\t? {}\n\t\t\t: { snapshotAboveHits: today.snapshotAboveHits }),\n\t\t...(today?.maxAgeMs === undefined ? {} : { maxAgeMs: today.maxAgeMs }),\n\t}\n}\n\nconst STORE_KEYS = ['hits', 'aggregates', 'state'] as const satisfies ReadonlyArray<\n\tkeyof StoreSlugs\n>\n\ntype StoreCollections = Readonly<Record<keyof StoreSlugs, ResolvedCollectionOption>>\n\n/** Config-time check of `collections`, so an unknown key, a bad slug or two alike fail the boot. */\nconst storeCollectionsOf = (value: unknown): StoreCollections => {\n\tconst given = value ?? {}\n\tif (!isRecord(given) || Array.isArray(given)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections must be an object such as { hits: { slug: 'site-hits' } }, got ${kindOf(value)}`\n\t\t)\n\t}\n\tfor (const key of Object.keys(given)) {\n\t\tif (!STORE_KEYS.some((known) => known === key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native() collections.${key} is not a collection of the engine; it has ${STORE_KEYS.join(', ')}`\n\t\t\t)\n\t\t}\n\t}\n\tconst of = (key: keyof StoreSlugs): ResolvedCollectionOption =>\n\t\tresolveCollectionOption(given[key], {\n\t\t\tpath: `native() collections.${key}`,\n\t\t\tfallback: DEFAULT_STORE_SLUGS[key],\n\t\t})\n\tconst collections = { hits: of('hits'), aggregates: of('aggregates'), state: of('state') }\n\tconst slugs = STORE_KEYS.map((key) => collections[key].slug)\n\tif (new Set(slugs).size !== slugs.length) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections name one slug twice (${slugs.join(', ')}); each of the engine's collections needs its own`\n\t\t)\n\t}\n\treturn collections\n}\n\n/** Config-time check of `sqlite.thread`, so a mistyped mode fails the boot. */\nconst sqliteThreadOf = (sqlite: NativeSqlite | undefined): SqliteThread | undefined => {\n\tconst value = sqlite?.thread\n\tif (value === undefined || isSqliteThread(value)) {\n\t\treturn value\n\t}\n\tthrow new Error(\n\t\t`analytics: native sqlite.thread must be one of ${SQLITE_THREADS.map((each) => `'${each}'`).join(', ')}, got ${kindOf(value)}`\n\t)\n}\n\n/** What one `register()` call handed the adapter, which every instance built after it uses. */\ninterface Registration {\n\tscoped: boolean\n\tmaxmind?: MaxmindSdk\n\tresolvers: IngestResolvers\n\tattribution: IngestAttribution\n\t/** The collections bound as items and whether they are counted per page, when any are bound. */\n\titems?: { collections: ReadonlySet<string>; pages: boolean }\n\trevenue?: AdapterRegisterContext['revenue']\n\t/** The maintenance task's queue and schedule, or false when the install registers none. */\n\tjobs: AdapterJobs\n\t/** Whether the task may carry a concurrency key: the host's `jobs.enableConcurrencyControl`. */\n\tjobsConcurrency: boolean\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tassertNoLegacyOptions(options, { legacy: LEGACY_NATIVE_OPTIONS, owner: 'native() option ' })\n\t// Validated here so a bad value fails the boot rather than the first beacon or read.\n\tconst hostname = resolveHostnameOption(options.hostname)\n\tconst filterBots = resolveBotFilter(options.filterBots)\n\tconst signatureMode = itemSignatureMode(options.items?.signature)\n\tconst caps = resolveCaps(options.caps)\n\tresolveWriteBuffer(options.buffer)\n\tconst rawDays = rawDaysOf(options.retention)\n\tconst aggregateDays = aggregateDaysOf(options.retention, rawDays)\n\tconst today = todayOf(options.today)\n\tconst sqliteThread = sqliteThreadOf(options.sqlite)\n\tconst platformHostnames = hostnameSet(options.platformHostnames, 'platformHostnames')\n\tconst collections = storeCollectionsOf(options.collections)\n\tconst slugs: StoreSlugs = {\n\t\thits: collections.hits.slug,\n\t\taggregates: collections.aggregates.slug,\n\t\tstate: collections.state.slug,\n\t}\n\tconst configuredGeo =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\tlet warnedMaxmind = false\n\tlet mountedIngestPath = routePaths(DEFAULT_ROUTE_BASE).ingest\n\n\tconst registrationOf = (context: AdapterRegisterContext | undefined): Registration => {\n\t\tconst scoped = context?.scoped ?? false\n\t\tconst grantedForScope = context?.adapterGrantedForScope\n\t\treturn {\n\t\t\tscoped,\n\t\t\t...(context?.sdks?.maxmind ? { maxmind: context.sdks.maxmind } : {}),\n\t\t\tresolvers: {\n\t\t\t\t...(scoped && context ? { scope: context.resolveScope } : {}),\n\t\t\t\t...(context ? { timezone: context.resolveTimezoneStrict } : {}),\n\t\t\t\t...(context ? { currency: context.revenue.currency } : {}),\n\t\t\t\t...(context?.revenue.convert ? { convertCurrency: context.revenue.convert } : {}),\n\t\t\t\t...(context ? { goals: context.resolveGoals } : {}),\n\t\t\t\t...(scoped && grantedForScope\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranted: (req: PayloadRequest, scope: string | null) =>\n\t\t\t\t\t\t\t\tgrantedForScope(req, scope, NATIVE_ADAPTER_ID),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tattribution: {\n\t\t\t\ttrustedProxyHops: context?.trustedProxyHops,\n\t\t\t\ttrustedPlatform: context?.trustedPlatform,\n\t\t\t\t...(context?.allowedOrigins ? { allowedOrigins: context.allowedOrigins } : {}),\n\t\t\t\thostname,\n\t\t\t\tplatformHostnames,\n\t\t\t},\n\t\t\t...(context?.items && context.items.collections.size > 0 ? { items: context.items } : {}),\n\t\t\t...(context?.revenue ? { revenue: context.revenue } : {}),\n\t\t\tjobs: context?.jobs ?? DEFAULT_JOBS,\n\t\t\tjobsConcurrency: context?.jobsConcurrency === true,\n\t\t}\n\t}\n\n\t/** What the adapter declares for a registration, with the filters its store applies. */\n\tconst capabilitiesOf = (\n\t\tregistration: Registration,\n\t\tfilters: AnalyticsCapabilities['filters']\n\t): AnalyticsCapabilities =>\n\t\tnativeCapabilities({\n\t\t\tfilters: filters ?? ANY_STORE_FILTERS,\n\t\t\trawDays,\n\t\t\tscoped: registration.scoped,\n\t\t\t...(registration.revenue ? { revenue: registration.revenue } : {}),\n\t\t\titems: registration.items !== undefined,\n\t\t})\n\n\t/** Each collection checked after the host's overrides; boot warnings go to `notice`. */\n\tconst addStoreCollections = (\n\t\tconfig: Config,\n\t\tnotice: ((message: string) => void) | undefined\n\t): void => {\n\t\tconst built = {\n\t\t\thits: hitsCollection(slugs.hits),\n\t\t\taggregates: aggregatesCollection(slugs.aggregates),\n\t\t\tstate: stateCollection(slugs.state),\n\t\t}\n\t\tconst shaped = STORE_KEYS.map((key) => {\n\t\t\tconst { overrides } = collections[key]\n\t\t\treturn shapeCollection(built[key], {\n\t\t\t\trole: key,\n\t\t\t\toption: `native() collections.${key}`,\n\t\t\t\tdb: config.db?.name,\n\t\t\t\t...(overrides ? { overrides } : {}),\n\t\t\t})\n\t\t})\n\t\tfor (const message of shaped.flatMap((each) => each.notices)) {\n\t\t\tnotice?.(message)\n\t\t}\n\t\tconfig.collections = [...(config.collections ?? []), ...shaped.map((each) => each.collection)]\n\t}\n\n\tlet registration = registrationOf(undefined)\n\tlet capabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\n\tconst geoResolver: GeoResolver = (headers, opts) => {\n\t\tconst maxmind = registration.maxmind\n\t\treturn configuredGeo(headers, maxmind ? { ...opts, maxmind } : opts)\n\t}\n\n\tconst build = (payload: Payload, built: Registration): NativeInstance => {\n\t\tif (isD1(payload)) {\n\t\t\tthrow new Error(D1_REFUSAL)\n\t\t}\n\t\tconst executor =\n\t\t\tdbKind(payload) === 'mongo'\n\t\t\t\t? undefined\n\t\t\t\t: createSqlExecutor(payload, sqliteThread === undefined ? {} : { thread: sqliteThread })\n\t\t// Every browser record is the server's own when signatures are required: none is forged, so\n\t\t// the two records of an order are one sale however far apart they lie.\n\t\tconst ordersSigned = built.revenue?.orderSignature === 'required'\n\t\tconst twinWindowMs = ordersSigned ? null : TWIN_WINDOW_MS\n\t\tconst store = createEventStore(payload, {\n\t\t\tslugs,\n\t\t\ttwinWindowMs,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst state = createStateStore(payload, {\n\t\t\tslug: slugs.state,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst declared = capabilitiesOf(built, store.features.filters)\n\t\tcapabilities = declared\n\t\t// A request of its own per call: one kept would hold its dataloader's documents and its\n\t\t// context for the life of the process.\n\t\tconst localRequest = (): Promise<PayloadRequest> => createLocalReq({}, payload)\n\t\tconst zoneOf = built.resolvers.timezone\n\t\tconst currencyOf = built.resolvers.currency\n\t\tconst engine = createEngine({\n\t\t\tpayload,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\toptions: {\n\t\t\t\tscoped: built.scoped,\n\t\t\t\t...(zoneOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttimezone: async (scope: string, req?: PayloadRequest) =>\n\t\t\t\t\t\t\t\tzoneOf(req ?? (await localRequest()), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(currencyOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcurrency: async (scope: string) =>\n\t\t\t\t\t\t\t\tcurrencyOf(await localRequest(), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tdimensions: declared.dimensions,\n\t\t\t\t...(declared.filters ? { filters: declared.filters } : {}),\n\t\t\t\tcaps,\n\t\t\t\titemPages: built.items?.pages ?? true,\n\t\t\t\trawDays,\n\t\t\t\taggregateDays,\n\t\t\t\ttoday,\n\t\t\t\tmaintenance:\n\t\t\t\t\tbuilt.jobs === false\n\t\t\t\t\t\t? { runner: false }\n\t\t\t\t\t\t: { runner: true, intervalMs: built.jobs.maintain.intervalMs },\n\t\t\t\ttwinWindowMs,\n\t\t\t},\n\t\t})\n\t\tconst secret: unknown = payload.secret\n\t\tconst keyed = typeof secret === 'string' && secret !== ''\n\t\tconst items: ItemIngestOptions | undefined = built.items\n\t\t\t? {\n\t\t\t\t\tcollections: built.items.collections,\n\t\t\t\t\tidTypes: itemIdTypes(payload, built.items.collections),\n\t\t\t\t\t// Without a secret no signature a page sends can be checked: only server items are kept.\n\t\t\t\t\t...(keyed ? { signature: { mode: signatureMode, key: itemRefKey(secret) } } : {}),\n\t\t\t\t}\n\t\t\t: undefined\n\t\tconst warn = (message: string) => payload.logger.warn(message)\n\t\tconst keepAlive = createKeepAlive({\n\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next's marker for processes where `after()` works\n\t\t\tenv: process.env,\n\t\t\twarn,\n\t\t})\n\t\treturn {\n\t\t\tregistration: built,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\tengine,\n\t\t\t// Without a secret no order signature can be checked: with signatures required, none passes.\n\t\t\torders: {\n\t\t\t\tmode: built.revenue?.orderSignature ?? DEFAULT_ORDER_SIGNATURE,\n\t\t\t\t...(keyed ? { key: orderRefKey(secret) } : {}),\n\t\t\t},\n\t\t\tkeepAlive: (work: Promise<unknown>) => {\n\t\t\t\tkeepAlive(work).catch(() => undefined)\n\t\t\t},\n\t\t\tsalts: createDailySalts({ state, warn, recorded: (scope) => state.lastZone(scope) }),\n\t\t\twriter: createHitWriter({\n\t\t\t\tstore,\n\t\t\t\t...(options.buffer === undefined ? {} : { buffer: options.buffer }),\n\t\t\t\tlogger: payload.logger,\n\t\t\t}),\n\t\t\titems,\n\t\t\tsqlite: dbKind(payload) === 'sqlite',\n\t\t\tnudge: () => engine.nudge(),\n\t\t\tsiteHosts: createSiteHosts({ store, now: currentDate, warn }),\n\t\t\t...(executor ? { release: () => executor.close() } : {}),\n\t\t}\n\t}\n\n\t/** The instance's engine, built on first use and again after the adapter is registered anew. */\n\tconst instanceOf = (payload: Payload): NativeInstance => {\n\t\tif (isDestroyed(payload)) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: this Payload instance was destroyed, so its native engine is closed'\n\t\t\t)\n\t\t}\n\t\tconst current = registration\n\t\treturn nativeInstanceFor(payload, current, () => build(payload, current))\n\t}\n\n\tconst payloadOf = (ctx: AdapterContext | undefined): Payload => {\n\t\tif (!ctx?.payload) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: the native adapter reads through the Payload instance in its context, and none was given'\n\t\t\t)\n\t\t}\n\t\treturn ctx.payload\n\t}\n\n\tconst beaconHandler = (): PayloadHandler =>\n\t\tmakeIngestHandler({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tresolvers: registration.resolvers,\n\t\t\tattribution: registration.attribution,\n\t\t\tfilterBots,\n\t\t\t...(registration.revenue?.browserAmounts\n\t\t\t\t? { browserAmounts: registration.revenue.browserAmounts }\n\t\t\t\t: {}),\n\t\t})\n\n\t// One handler per registration, so its once-a-process warnings are said once, not per beacon.\n\tlet receiveBeacon = beaconHandler()\n\tconst receive = async (req: PayloadRequest): Promise<Response> => {\n\t\t// A beacon can be the first thing an instance serves (a worker booted without onInit, a\n\t\t// fresh HMR config): the runtime attaches the adapter to it first.\n\t\tgetRuntime(req.payload)\n\t\treturn receiveBeacon(req)\n\t}\n\n\t/**\n\t * One run of `analytics-maintain`, on whichever instance the job runner took it on: the engine's\n\t * upkeep, then the read cache's expired entries, under the sweep's own lease.\n\t */\n\tconst maintainOnTask = async (\n\t\treq: PayloadRequest,\n\t\tinput: { rebuild?: RebuildDaysInput }\n\t): Promise<MaintainTaskOutput> => {\n\t\t// A worker booted without onInit may run the task before anything else built its runtime.\n\t\tconst runtime = getRuntime(req.payload)\n\t\tconst report = await instanceOf(req.payload).engine.maintain({\n\t\t\tbudgetMs: MAINTAIN_TASK_BUDGET_MS,\n\t\t\treq,\n\t\t\theartbeat: true,\n\t\t\t...(input.rebuild ? { rebuild: input.rebuild } : {}),\n\t\t})\n\t\tlet sweptCache = 0\n\t\ttry {\n\t\t\tsweptCache = (await runtime?.cache?.sweeper.sweep(TASK_SWEEP_BATCHES))?.swept ?? 0\n\t\t} catch (err) {\n\t\t\treq.payload.logger.warn(`analytics: sweeping expired cache entries failed: ${String(err)}`)\n\t\t}\n\t\treturn { ...report, sweptCache }\n\t}\n\n\tconst ingest = {\n\t\t// Read late: the plugin's base arrives with the register context.\n\t\tget path() {\n\t\t\treturn options.ingestPath ?? mountedIngestPath\n\t\t},\n\t\ttrack: makeServerTrack({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tgetResolvers: () => registration.resolvers,\n\t\t\tgetAttribution: () => registration.attribution,\n\t\t}),\n\t\t// The endpoint's hostname policy without the scoped drop rule (this caller knows its\n\t\t// boundary); a capture call site, so the host's resolver sees the visit, not the user.\n\t\thostname: (args: Parameters<IngestHostnameResolver>[0]) =>\n\t\t\tresolveEventHostname({\n\t\t\t\toption: hostname,\n\t\t\t\tclaimed: args.claimed,\n\t\t\t\treq: captureRequest(args.req),\n\t\t\t\tscope: args.scope ?? null,\n\t\t\t\ttrustedProxyHops: registration.attribution.trustedProxyHops,\n\t\t\t}),\n\t}\n\n\treturn {\n\t\tid: NATIVE_ADAPTER_ID,\n\t\tlabel: 'Payload',\n\t\tget capabilities() {\n\t\t\treturn capabilities\n\t\t},\n\t\tcapture: nativeCapture,\n\t\tingest,\n\t\tisConfigured: () => true,\n\t\tflush: async (payload) => {\n\t\t\tawait instanceOf(payload).writer.flush()\n\t\t},\n\t\trebuild: (payload, input) => {\n\t\t\tgetRuntime(payload)\n\t\t\treturn instanceOf(payload).engine.rebuild(input)\n\t\t},\n\t\treceive,\n\t\tregister(config: Config, context) {\n\t\t\tif (isD1({ db: { name: config.db?.name ?? '' } })) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tregistration = registrationOf(context)\n\t\t\tcapabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\t\t\tif (context?.routes) {\n\t\t\t\tmountedIngestPath = context.routes.ingest\n\t\t\t}\n\t\t\treceiveBeacon = beaconHandler()\n\t\t\taddStoreCollections(config, context?.notice)\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'post', path: ingest.path, handler: receive },\n\t\t\t]\n\t\t\tconst { jobs } = registration\n\t\t\tif (jobs !== false) {\n\t\t\t\taddTask(\n\t\t\t\t\tconfig,\n\t\t\t\t\tmaintainTask({\n\t\t\t\t\t\tschedule: jobs.maintain,\n\t\t\t\t\t\trun: maintainOnTask,\n\t\t\t\t\t\tconcurrency: registration.jobsConcurrency,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t\tregisterSchema(config: Config, context: AdapterSchemaContext) {\n\t\t\taddStoreCollections(config, context.notice)\n\t\t\tif (context.jobs !== false) {\n\t\t\t\taddTask(config, schemaOnlyTask(MAINTAIN_TASK_SLUG, context.jobs.maintain))\n\t\t\t}\n\t\t},\n\t\tattach(payload: Payload) {\n\t\t\tif (isD1(payload)) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tif (\n\t\t\t\t!warnedMaxmind &&\n\t\t\t\tregistration.maxmind === undefined &&\n\t\t\t\tneedsMaxmindSdk(configuredGeo) &&\n\t\t\t\tisProductionBuild()\n\t\t\t) {\n\t\t\t\twarnedMaxmind = true\n\t\t\t\tpayload.logger?.warn(MAXMIND_SDK_WARNING)\n\t\t\t}\n\t\t\tinstanceOf(payload)\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tawait closeNativeInstance(payload, registration)\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.read(q, ctx)\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.realtime(q, ctx)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqLA,MAAa,oBAAoB;AAEjC,MAAM,aACL;;AAkBD,MAAa,mBAAmB,YAC/B,QAAQ,OAAA,YACR,OAAO,QAAQ,IAAI,SAAS,SAAS,MAAM,cAC3C,OAAO,QAAQ,IAAI,SAAS,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MAAM,SAAkB;GAC7B,MAAM,oBAAoB,SAAS,YAAY;EAChD;EACA,MAAM,MAAM,GAAmB,KAAgD;GAC9E,OAAO,WAAW,UAAU,GAAG,CAAC,EAAE,OAAO,KAAK,GAAG,GAAG;EACrD;EACA,MAAM,SAAS,GAAmB,KAAgD;GACjF,OAAO,WAAW,UAAU,GAAG,CAAC,EAAE,OAAO,SAAS,GAAG,GAAG;EACzD;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"nativeAdapter.js","names":[],"sources":["../../src/native/nativeAdapter.ts"],"sourcesContent":["import {\n\ttype Config,\n\tcreateLocalReq,\n\ttype Payload,\n\ttype PayloadHandler,\n\ttype PayloadRequest,\n} from 'payload'\nimport { captureRequest } from '../capture/captureRequest'\nimport type { CaptureSupport } from '../core/capture'\nimport { currentDate } from '../core/clock'\nimport {\n\ttype AnalyticsCollectionOptions,\n\ttype ResolvedCollectionOption,\n\tresolveCollectionOption,\n} from '../core/collectionOption'\nimport type {\n\tAdapterContext,\n\tAdapterRegisterContext,\n\tAdapterSchemaContext,\n\tAnalyticsAdapter,\n\tAnalyticsCapabilities,\n\tAnalyticsQuery,\n\tAnalyticsResult,\n} from '../core/contract'\nimport { type AdapterJobs, DEFAULT_JOBS } from '../core/jobs'\nimport { assertNoLegacyOptions, LEGACY_NATIVE_OPTIONS } from '../core/legacyOptions'\nimport type { MaxmindSdk } from '../core/sdks'\nimport type { IngestHostnameResolver } from '../core/serverEvent'\nimport { type AdapterLabelOption, adapterLabel } from '../core/sourceLabel'\nimport { isRecord, kindOf } from '../core/values'\nimport { dbKind, isD1 } from '../db/kind'\nimport { DEFAULT_ORDER_SIGNATURE } from '../goals/match'\nimport { itemIdTypes } from '../items/collectionIdType'\nimport { shapeCollection } from '../plugin/collectionChecks'\nimport { isDestroyed } from '../plugin/destroy'\nimport { createKeepAlive } from '../plugin/keepAlive'\nimport { isProductionBuild, MAXMIND_SDK_WARNING } from '../plugin/peers'\nimport { DEFAULT_ROUTE_BASE, routePaths } from '../plugin/routes'\nimport { getRuntime } from '../plugin/runtime'\nimport { addTask, schemaOnlyTask } from '../plugin/schemaOnly'\nimport { TASK_SWEEP_BATCHES } from '../surfacing/cacheSweep'\nimport { aggregatesCollection } from './collections/aggregates'\nimport { hitsCollection } from './collections/hits'\nimport { DEFAULT_STORE_SLUGS, type StoreSlugs } from './collections/slugs'\nimport { stateCollection } from './collections/state'\nimport { DEFAULT_RAW_DAYS, nativeCapabilities } from './engine/capabilities'\nimport { createEngine } from './engine/engine'\nimport { closeNativeInstance, type NativeInstance, nativeInstanceFor } from './engine/instance'\nimport type { RebuildDaysInput, RebuildDaysReport } from './engine/rebuild'\nimport { createDailySalts } from './engine/salt'\nimport { createSiteHosts } from './engine/siteHosts'\nimport { createHitWriter, resolveWriteBuffer, type WriteBufferOption } from './engine/writeBuffer'\nimport { composeGeoResolvers } from './geo/composeGeoResolvers'\nimport { type GeoResolver, needsMaxmindSdk, platformHeaderResolver } from './geo/geoResolver'\nimport { maxmindResolver } from './geo/maxmindResolver'\nimport { type BotFilter, resolveBotFilter } from './ingest/bots'\nimport { type IngestAttribution, type IngestResolvers, makeIngestHandler } from './ingest/endpoint'\nimport { type ItemSignatureMode, itemRefKey } from './ingest/itemSignature'\nimport type { ItemIngestOptions } from './ingest/normalizeEvent'\nimport { orderRefKey } from './ingest/orderSignature'\nimport {\n\ttype HostnameOption,\n\thostnameSet,\n\tresolveEventHostname,\n\tresolveHostnameOption,\n} from './ingest/resolveHostname'\nimport { makeServerTrack } from './ingest/serverTrack'\nimport { type CapsOption, resolveCaps } from './store/caps'\nimport { createEventStore } from './store/eventStore'\nimport { TWIN_WINDOW_MS } from './store/hits'\nimport { rawFilterMap } from './store/rawRead'\nimport { createSqlExecutor } from './store/sql/executor'\nimport { isSqliteThread, SQLITE_THREADS, type SqliteThread } from './store/sql/sqliteThread'\nimport { createStateStore } from './store/stateStore'\nimport {\n\tMAINTAIN_TASK_BUDGET_MS,\n\tMAINTAIN_TASK_SLUG,\n\ttype MaintainTaskOutput,\n\tmaintainTask,\n} from './tasks/maintainTask'\n\nexport type { EventHostnameResolver, HostnameOption } from './ingest/resolveHostname'\n\n/** How long the native engine keeps what it stores. */\nexport interface NativeRetention {\n\t/**\n\t * Days of raw hits kept, today counted: how far back filtered and hourly reads reach. `null`\n\t * keeps every hit. Default 90.\n\t */\n\trawDays?: number | null\n\t/**\n\t * Days of daily totals kept, today counted; at least `rawDays`, which must then be set too.\n\t * `null` keeps every day's. Default null.\n\t */\n\taggregateDays?: number | null\n}\n\n/** How the native engine reads the day still running. */\nexport interface NativeToday {\n\t/**\n\t * Hits up to which today is read live; above it, from a background snapshot of its totals.\n\t * Default 5,000 on Postgres, 2,000 on SQLite and MongoDB; 0 always reads a snapshot.\n\t */\n\tsnapshotAboveHits?: number\n\t/**\n\t * Ms a snapshot is served before a background refresh. Default grows with the day's hits (one\n\t * minute up to 50,000, five at 500,000) and with its counting cost. At least 1,000.\n\t */\n\tmaxAgeMs?: number\n}\n\nexport interface NativeOptions {\n\t/**\n\t * The source's name in pickers and listings: a string, a map by admin language (read like\n\t * `view.navLabel`), or a function naming it per reader and scope. Default `'Payload'`.\n\t */\n\tlabel?: AdapterLabelOption\n\t/**\n\t * Where each event's country, region and city come from. One that throws costs the event its\n\t * location, never the event, and is logged at most once an hour while it fails.\n\t */\n\tgeoResolver?: GeoResolver\n\tgeoDbPath?: string\n\t/** Where the beacon endpoint listens, under `routes.api`. Default `<routes.base>/e`. */\n\tingestPath?: string\n\t/**\n\t * `true` batches hits in memory (200 hits or one second, at most 5,000 held); an object sets\n\t * `maxSize`, `maxAgeMs` or `maxPending`. Unset writes each as it arrives. Orders are never held.\n\t */\n\tbuffer?: WriteBufferOption\n\t/**\n\t * `'request'` (default) stores the request's host and ignores the body's claim; a list stores it\n\t * only when listed; a resolver decides per event, and null drops it.\n\t */\n\thostname?: HostnameOption\n\t/**\n\t * Platform domains that ingest under the null scope when the request resolves none. Tenant\n\t * domains need no entry: `scope.resolve` already answers for them.\n\t */\n\tplatformHostnames?: string[]\n\t/**\n\t * Drops crawlers, monitors and headless clients by user agent, on by default. A function receives\n\t * the raw agent; `false` counts every beacon. `trackServerEvent` is never filtered.\n\t */\n\tfilterBots?: boolean | BotFilter\n\t/**\n\t * `signature: 'required'` (default) keeps a page's item only when the server signed its ref\n\t * (`signItemRef`, `itemAttributesFor`); `'optional'` also keeps unsigned refs.\n\t */\n\titems?: { signature?: ItemSignatureMode }\n\t/**\n\t * Values each kind of daily total keeps per scope, day and hostname, the rest folded into one\n\t * `(other)` row; null keeps all. Kinds left out keep the defaults (`DEFAULT_CAPS`).\n\t */\n\tcaps?: CapsOption\n\tretention?: NativeRetention\n\t/** Today: read live while small, else from a snapshot (see `NativeToday`). */\n\ttoday?: NativeToday\n\t/** SQLite on a local file: where the engine's statements run (see `NativeSqlite`). */\n\tsqlite?: NativeSqlite\n\t/**\n\t * The engine's collections, renamed with `slug` and reshaped with `overrides`. An override may\n\t * change admin settings, access and `dbName`, but no field: the boot checks it.\n\t */\n\tcollections?: NativeCollections\n}\n\n/** The engine's collections, by what they hold; each defaults to its `analytics-` slug. */\nexport interface NativeCollections {\n\t/** `analytics-hits`, one row per hit. */\n\thits?: AnalyticsCollectionOptions\n\t/** `analytics-aggregates`, the daily totals. */\n\taggregates?: AnalyticsCollectionOptions\n\t/** `analytics-state`: the daily salts, day markers, leases and heartbeats. */\n\tstate?: AnalyticsCollectionOptions\n}\n\n/** Where the engine runs its statements on a local SQLite file. Remote libsql never blocks. */\nexport interface NativeSqlite {\n\t/**\n\t * `'auto'` (default) uses worker threads in WAL mode with `busyTimeout` >= 5,000 ms, else the main\n\t * thread, warning once. `ANALYTICS_SQLITE_THREAD` sets it where this does not.\n\t */\n\tthread?: SqliteThread\n}\n\n/** The config native adapter's id, which a `native` provider document grants to a scope. */\nexport const NATIVE_ADAPTER_ID = 'native'\n\nconst D1_REFUSAL =\n\t'analytics: native() does not support Cloudflare D1 (@payloadcms/db-d1-sqlite) yet. The vendor adapters (Plausible, Umami, GA4, PostHog) work on D1: drop native() from adapters, or run the app on MongoDB, Postgres or SQLite.'\n\nexport interface NativeAdapter extends AnalyticsAdapter {\n\t/**\n\t * Writes out what one instance holds back: its write buffer, and the server events that waited\n\t * on a transaction which has since ended.\n\t */\n\tflush(payload: Payload): Promise<void>\n\t/**\n\t * Takes one beacon as the ingest endpoint does, for a request built outside Payload's own\n\t * routing: what `ingestRoute` from `@10x-media/analytics/next` calls.\n\t */\n\treceive(req: PayloadRequest): Promise<Response>\n\t/** Counts a stretch of one instance's days again, as `rebuildDays` asks. */\n\trebuild(payload: Payload, input: RebuildDaysInput): Promise<RebuildDaysReport>\n}\n\n/** The native adapter among a runtime's adapters, recognized by its own seam. */\nexport const isNativeAdapter = (adapter: AnalyticsAdapter): adapter is NativeAdapter =>\n\tadapter.id === NATIVE_ADAPTER_ID &&\n\ttypeof Reflect.get(adapter, 'receive') === 'function' &&\n\ttypeof Reflect.get(adapter, 'flush') === 'function' &&\n\ttypeof Reflect.get(adapter, 'rebuild') === 'function'\n\n// The tracker itself is the client (`AnalyticsScripts` boots it), so there is nothing to\n// proxy or inject; the ingest path is carried by the tracker config resolver instead.\nconst nativeCapture: CaptureSupport = {\n\tproxy: { routes: [] },\n\tsnippet: () => ({ scripts: [] }),\n\tclient: { kind: 'native' },\n}\n\n/** What every store filters with, which is what is declared before a store exists. */\nconst ANY_STORE_FILTERS = rawFilterMap(['eq', 'contains'])\n\n/** Config-time check, so a mistyped mode fails the boot rather than every item at ingest. */\nconst itemSignatureMode = (value: unknown): ItemSignatureMode => {\n\tif (value === undefined || value === 'required') {\n\t\treturn 'required'\n\t}\n\tif (value === 'optional') {\n\t\treturn 'optional'\n\t}\n\tthrow new Error(\n\t\t`analytics: native items.signature must be 'required' or 'optional', got ${String(value)}`\n\t)\n}\n\n/** A `retention` option as given, refused unless it is unset, null or a whole number of days. */\nconst retentionDays = (\n\tretention: NativeRetention | undefined,\n\tname: keyof NativeRetention\n): number | null | undefined => {\n\tconst value = retention?.[name]\n\tif (value !== undefined && value !== null && (!Number.isInteger(value) || value < 1)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.${name} must be a whole number of days of at least 1, or null, got ${String(value)}`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `retention.rawDays`, so a window no read can start from fails the boot. */\nconst rawDaysOf = (retention: NativeRetention | undefined): number | null => {\n\tconst value = retentionDays(retention, 'rawDays')\n\treturn value === undefined ? DEFAULT_RAW_DAYS : value\n}\n\n/**\n * Config-time check of `retention.aggregateDays`: daily totals deleted while a day's raw hits are\n * still kept would be counted again on the next read, and deleted again after.\n */\nconst aggregateDaysOf = (\n\tretention: NativeRetention | undefined,\n\trawDays: number | null\n): number | null => {\n\tconst value = retentionDays(retention, 'aggregateDays') ?? null\n\tif (value === null) {\n\t\treturn null\n\t}\n\tif (rawDays === null || value < rawDays) {\n\t\tthrow new Error(\n\t\t\t`analytics: native retention.aggregateDays (${value}) must be at least retention.rawDays (${rawDays ?? 'null, every hit kept'}): daily totals deleted while their raw hits are kept would be counted again`\n\t\t)\n\t}\n\treturn value\n}\n\n/** Config-time check of `today`, so a value no read could use fails the boot. */\nconst todayOf = (today: NativeToday | undefined): NativeToday => {\n\tconst check = (name: keyof NativeToday, value: number | undefined, min: number): void => {\n\t\tif (value !== undefined && (!Number.isInteger(value) || value < min)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native today.${name} must be a whole number of at least ${min.toLocaleString('en-US')}, got ${String(value)}`\n\t\t\t)\n\t\t}\n\t}\n\tcheck('snapshotAboveHits', today?.snapshotAboveHits, 0)\n\tcheck('maxAgeMs', today?.maxAgeMs, 1_000)\n\treturn {\n\t\t...(today?.snapshotAboveHits === undefined\n\t\t\t? {}\n\t\t\t: { snapshotAboveHits: today.snapshotAboveHits }),\n\t\t...(today?.maxAgeMs === undefined ? {} : { maxAgeMs: today.maxAgeMs }),\n\t}\n}\n\nconst STORE_KEYS = ['hits', 'aggregates', 'state'] as const satisfies ReadonlyArray<\n\tkeyof StoreSlugs\n>\n\ntype StoreCollections = Readonly<Record<keyof StoreSlugs, ResolvedCollectionOption>>\n\n/** Config-time check of `collections`, so an unknown key, a bad slug or two alike fail the boot. */\nconst storeCollectionsOf = (value: unknown): StoreCollections => {\n\tconst given = value ?? {}\n\tif (!isRecord(given) || Array.isArray(given)) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections must be an object such as { hits: { slug: 'site-hits' } }, got ${kindOf(value)}`\n\t\t)\n\t}\n\tfor (const key of Object.keys(given)) {\n\t\tif (!STORE_KEYS.some((known) => known === key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: native() collections.${key} is not a collection of the engine; it has ${STORE_KEYS.join(', ')}`\n\t\t\t)\n\t\t}\n\t}\n\tconst of = (key: keyof StoreSlugs): ResolvedCollectionOption =>\n\t\tresolveCollectionOption(given[key], {\n\t\t\tpath: `native() collections.${key}`,\n\t\t\tfallback: DEFAULT_STORE_SLUGS[key],\n\t\t})\n\tconst collections = { hits: of('hits'), aggregates: of('aggregates'), state: of('state') }\n\tconst slugs = STORE_KEYS.map((key) => collections[key].slug)\n\tif (new Set(slugs).size !== slugs.length) {\n\t\tthrow new Error(\n\t\t\t`analytics: native() collections name one slug twice (${slugs.join(', ')}); each of the engine's collections needs its own`\n\t\t)\n\t}\n\treturn collections\n}\n\n/** Config-time check of `sqlite.thread`, so a mistyped mode fails the boot. */\nconst sqliteThreadOf = (sqlite: NativeSqlite | undefined): SqliteThread | undefined => {\n\tconst value = sqlite?.thread\n\tif (value === undefined || isSqliteThread(value)) {\n\t\treturn value\n\t}\n\tthrow new Error(\n\t\t`analytics: native sqlite.thread must be one of ${SQLITE_THREADS.map((each) => `'${each}'`).join(', ')}, got ${kindOf(value)}`\n\t)\n}\n\n/** What one `register()` call handed the adapter, which every instance built after it uses. */\ninterface Registration {\n\tscoped: boolean\n\tmaxmind?: MaxmindSdk\n\tresolvers: IngestResolvers\n\tattribution: IngestAttribution\n\t/** The collections bound as items and whether they are counted per page, when any are bound. */\n\titems?: { collections: ReadonlySet<string>; pages: boolean }\n\trevenue?: AdapterRegisterContext['revenue']\n\t/** The maintenance task's queue and schedule, or false when the install registers none. */\n\tjobs: AdapterJobs\n\t/** Whether the task may carry a concurrency key: the host's `jobs.enableConcurrencyControl`. */\n\tjobsConcurrency: boolean\n}\n\nexport function native(options: NativeOptions = {}): NativeAdapter {\n\tassertNoLegacyOptions(options, { legacy: LEGACY_NATIVE_OPTIONS, owner: 'native() option ' })\n\t// Validated here so a bad value fails the boot rather than the first beacon or read.\n\tconst hostname = resolveHostnameOption(options.hostname)\n\tconst filterBots = resolveBotFilter(options.filterBots)\n\tconst signatureMode = itemSignatureMode(options.items?.signature)\n\tconst caps = resolveCaps(options.caps)\n\tresolveWriteBuffer(options.buffer)\n\tconst rawDays = rawDaysOf(options.retention)\n\tconst aggregateDays = aggregateDaysOf(options.retention, rawDays)\n\tconst today = todayOf(options.today)\n\tconst sqliteThread = sqliteThreadOf(options.sqlite)\n\tconst platformHostnames = hostnameSet(options.platformHostnames, 'platformHostnames')\n\tconst collections = storeCollectionsOf(options.collections)\n\tconst slugs: StoreSlugs = {\n\t\thits: collections.hits.slug,\n\t\taggregates: collections.aggregates.slug,\n\t\tstate: collections.state.slug,\n\t}\n\tconst configuredGeo =\n\t\toptions.geoResolver ??\n\t\t(options.geoDbPath\n\t\t\t? composeGeoResolvers(platformHeaderResolver, maxmindResolver({ dbPath: options.geoDbPath }))\n\t\t\t: platformHeaderResolver)\n\tlet warnedMaxmind = false\n\tlet mountedIngestPath = routePaths(DEFAULT_ROUTE_BASE).ingest\n\n\tconst registrationOf = (context: AdapterRegisterContext | undefined): Registration => {\n\t\tconst scoped = context?.scoped ?? false\n\t\tconst grantedForScope = context?.adapterGrantedForScope\n\t\treturn {\n\t\t\tscoped,\n\t\t\t...(context?.sdks?.maxmind ? { maxmind: context.sdks.maxmind } : {}),\n\t\t\tresolvers: {\n\t\t\t\t...(scoped && context ? { scope: context.resolveScope } : {}),\n\t\t\t\t...(context ? { timezone: context.resolveTimezoneStrict } : {}),\n\t\t\t\t...(context ? { currency: context.revenue.currency } : {}),\n\t\t\t\t...(context?.revenue.convert ? { convertCurrency: context.revenue.convert } : {}),\n\t\t\t\t...(context ? { goals: context.resolveGoals } : {}),\n\t\t\t\t...(scoped && grantedForScope\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tgranted: (req: PayloadRequest, scope: string | null) =>\n\t\t\t\t\t\t\t\tgrantedForScope(req, scope, NATIVE_ADAPTER_ID),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tattribution: {\n\t\t\t\ttrustedProxyHops: context?.trustedProxyHops,\n\t\t\t\ttrustedPlatform: context?.trustedPlatform,\n\t\t\t\t...(context?.allowedOrigins ? { allowedOrigins: context.allowedOrigins } : {}),\n\t\t\t\thostname,\n\t\t\t\tplatformHostnames,\n\t\t\t},\n\t\t\t...(context?.items && context.items.collections.size > 0 ? { items: context.items } : {}),\n\t\t\t...(context?.revenue ? { revenue: context.revenue } : {}),\n\t\t\tjobs: context?.jobs ?? DEFAULT_JOBS,\n\t\t\tjobsConcurrency: context?.jobsConcurrency === true,\n\t\t}\n\t}\n\n\t/** What the adapter declares for a registration, with the filters its store applies. */\n\tconst capabilitiesOf = (\n\t\tregistration: Registration,\n\t\tfilters: AnalyticsCapabilities['filters']\n\t): AnalyticsCapabilities =>\n\t\tnativeCapabilities({\n\t\t\tfilters: filters ?? ANY_STORE_FILTERS,\n\t\t\trawDays,\n\t\t\tscoped: registration.scoped,\n\t\t\t...(registration.revenue ? { revenue: registration.revenue } : {}),\n\t\t\titems: registration.items !== undefined,\n\t\t})\n\n\t/** Each collection checked after the host's overrides; boot warnings go to `notice`. */\n\tconst addStoreCollections = (\n\t\tconfig: Config,\n\t\tnotice: ((message: string) => void) | undefined\n\t): void => {\n\t\tconst built = {\n\t\t\thits: hitsCollection(slugs.hits),\n\t\t\taggregates: aggregatesCollection(slugs.aggregates),\n\t\t\tstate: stateCollection(slugs.state),\n\t\t}\n\t\tconst shaped = STORE_KEYS.map((key) => {\n\t\t\tconst { overrides } = collections[key]\n\t\t\treturn shapeCollection(built[key], {\n\t\t\t\trole: key,\n\t\t\t\toption: `native() collections.${key}`,\n\t\t\t\tdb: config.db?.name,\n\t\t\t\t...(overrides ? { overrides } : {}),\n\t\t\t})\n\t\t})\n\t\tfor (const message of shaped.flatMap((each) => each.notices)) {\n\t\t\tnotice?.(message)\n\t\t}\n\t\tconfig.collections = [...(config.collections ?? []), ...shaped.map((each) => each.collection)]\n\t}\n\n\tlet registration = registrationOf(undefined)\n\tlet capabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\n\tconst geoResolver: GeoResolver = (headers, opts) => {\n\t\tconst maxmind = registration.maxmind\n\t\treturn configuredGeo(headers, maxmind ? { ...opts, maxmind } : opts)\n\t}\n\n\tconst build = (payload: Payload, built: Registration): NativeInstance => {\n\t\tif (isD1(payload)) {\n\t\t\tthrow new Error(D1_REFUSAL)\n\t\t}\n\t\tconst executor =\n\t\t\tdbKind(payload) === 'mongo'\n\t\t\t\t? undefined\n\t\t\t\t: createSqlExecutor(payload, sqliteThread === undefined ? {} : { thread: sqliteThread })\n\t\t// Every browser record is the server's own when signatures are required: none is forged, so\n\t\t// the two records of an order are one sale however far apart they lie.\n\t\tconst ordersSigned = built.revenue?.orderSignature === 'required'\n\t\tconst twinWindowMs = ordersSigned ? null : TWIN_WINDOW_MS\n\t\tconst store = createEventStore(payload, {\n\t\t\tslugs,\n\t\t\ttwinWindowMs,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst state = createStateStore(payload, {\n\t\t\tslug: slugs.state,\n\t\t\t...(executor ? { executor } : {}),\n\t\t})\n\t\tconst declared = capabilitiesOf(built, store.features.filters)\n\t\tcapabilities = declared\n\t\t// A request of its own per call: one kept would hold its dataloader's documents and its\n\t\t// context for the life of the process.\n\t\tconst localRequest = (): Promise<PayloadRequest> => createLocalReq({}, payload)\n\t\tconst zoneOf = built.resolvers.timezone\n\t\tconst currencyOf = built.resolvers.currency\n\t\tconst engine = createEngine({\n\t\t\tpayload,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\toptions: {\n\t\t\t\tscoped: built.scoped,\n\t\t\t\t...(zoneOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\ttimezone: async (scope: string, req?: PayloadRequest) =>\n\t\t\t\t\t\t\t\tzoneOf(req ?? (await localRequest()), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\t...(currencyOf\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tcurrency: async (scope: string) =>\n\t\t\t\t\t\t\t\tcurrencyOf(await localRequest(), scope === '' ? null : scope),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tdimensions: declared.dimensions,\n\t\t\t\t...(declared.filters ? { filters: declared.filters } : {}),\n\t\t\t\tcaps,\n\t\t\t\titemPages: built.items?.pages ?? true,\n\t\t\t\trawDays,\n\t\t\t\taggregateDays,\n\t\t\t\ttoday,\n\t\t\t\tmaintenance:\n\t\t\t\t\tbuilt.jobs === false\n\t\t\t\t\t\t? { runner: false }\n\t\t\t\t\t\t: { runner: true, intervalMs: built.jobs.maintain.intervalMs },\n\t\t\t\ttwinWindowMs,\n\t\t\t},\n\t\t})\n\t\tconst secret: unknown = payload.secret\n\t\tconst keyed = typeof secret === 'string' && secret !== ''\n\t\tconst items: ItemIngestOptions | undefined = built.items\n\t\t\t? {\n\t\t\t\t\tcollections: built.items.collections,\n\t\t\t\t\tidTypes: itemIdTypes(payload, built.items.collections),\n\t\t\t\t\t// Without a secret no signature a page sends can be checked: only server items are kept.\n\t\t\t\t\t...(keyed ? { signature: { mode: signatureMode, key: itemRefKey(secret) } } : {}),\n\t\t\t\t}\n\t\t\t: undefined\n\t\tconst warn = (message: string) => payload.logger.warn(message)\n\t\tconst keepAlive = createKeepAlive({\n\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next's marker for processes where `after()` works\n\t\t\tenv: process.env,\n\t\t\twarn,\n\t\t})\n\t\treturn {\n\t\t\tregistration: built,\n\t\t\tstore,\n\t\t\tstate,\n\t\t\tengine,\n\t\t\t// Without a secret no order signature can be checked: with signatures required, none passes.\n\t\t\torders: {\n\t\t\t\tmode: built.revenue?.orderSignature ?? DEFAULT_ORDER_SIGNATURE,\n\t\t\t\t...(keyed ? { key: orderRefKey(secret) } : {}),\n\t\t\t},\n\t\t\tkeepAlive: (work: Promise<unknown>) => {\n\t\t\t\tkeepAlive(work).catch(() => undefined)\n\t\t\t},\n\t\t\tsalts: createDailySalts({ state, warn, recorded: (scope) => state.lastZone(scope) }),\n\t\t\twriter: createHitWriter({\n\t\t\t\tstore,\n\t\t\t\t...(options.buffer === undefined ? {} : { buffer: options.buffer }),\n\t\t\t\tlogger: payload.logger,\n\t\t\t}),\n\t\t\titems,\n\t\t\tsqlite: dbKind(payload) === 'sqlite',\n\t\t\tnudge: () => engine.nudge(),\n\t\t\tsiteHosts: createSiteHosts({ store, now: currentDate, warn }),\n\t\t\t...(executor ? { release: () => executor.close() } : {}),\n\t\t}\n\t}\n\n\t/** The instance's engine, built on first use and again after the adapter is registered anew. */\n\tconst instanceOf = (payload: Payload): NativeInstance => {\n\t\tif (isDestroyed(payload)) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: this Payload instance was destroyed, so its native engine is closed'\n\t\t\t)\n\t\t}\n\t\tconst current = registration\n\t\treturn nativeInstanceFor(payload, current, () => build(payload, current))\n\t}\n\n\tconst payloadOf = (ctx: AdapterContext | undefined): Payload => {\n\t\tif (!ctx?.payload) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: the native adapter reads through the Payload instance in its context, and none was given'\n\t\t\t)\n\t\t}\n\t\treturn ctx.payload\n\t}\n\n\tconst beaconHandler = (): PayloadHandler =>\n\t\tmakeIngestHandler({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tresolvers: registration.resolvers,\n\t\t\tattribution: registration.attribution,\n\t\t\tfilterBots,\n\t\t\t...(registration.revenue?.browserAmounts\n\t\t\t\t? { browserAmounts: registration.revenue.browserAmounts }\n\t\t\t\t: {}),\n\t\t})\n\n\t// One handler per registration, so its once-a-process warnings are said once, not per beacon.\n\tlet receiveBeacon = beaconHandler()\n\tconst receive = async (req: PayloadRequest): Promise<Response> => {\n\t\t// A beacon can be the first thing an instance serves (a worker booted without onInit, a\n\t\t// fresh HMR config): the runtime attaches the adapter to it first.\n\t\tgetRuntime(req.payload)\n\t\treturn receiveBeacon(req)\n\t}\n\n\t/**\n\t * One run of `analytics-maintain`, on whichever instance the job runner took it on: the engine's\n\t * upkeep, then the read cache's expired entries, under the sweep's own lease.\n\t */\n\tconst maintainOnTask = async (\n\t\treq: PayloadRequest,\n\t\tinput: { rebuild?: RebuildDaysInput }\n\t): Promise<MaintainTaskOutput> => {\n\t\t// A worker booted without onInit may run the task before anything else built its runtime.\n\t\tconst runtime = getRuntime(req.payload)\n\t\tconst report = await instanceOf(req.payload).engine.maintain({\n\t\t\tbudgetMs: MAINTAIN_TASK_BUDGET_MS,\n\t\t\treq,\n\t\t\theartbeat: true,\n\t\t\t...(input.rebuild ? { rebuild: input.rebuild } : {}),\n\t\t})\n\t\tlet sweptCache = 0\n\t\ttry {\n\t\t\tsweptCache = (await runtime?.cache?.sweeper.sweep(TASK_SWEEP_BATCHES))?.swept ?? 0\n\t\t} catch (err) {\n\t\t\treq.payload.logger.warn(`analytics: sweeping expired cache entries failed: ${String(err)}`)\n\t\t}\n\t\treturn { ...report, sweptCache }\n\t}\n\n\tconst ingest = {\n\t\t// Read late: the plugin's base arrives with the register context.\n\t\tget path() {\n\t\t\treturn options.ingestPath ?? mountedIngestPath\n\t\t},\n\t\ttrack: makeServerTrack({\n\t\t\tgeoResolver,\n\t\t\ttarget: instanceOf,\n\t\t\tgetResolvers: () => registration.resolvers,\n\t\t\tgetAttribution: () => registration.attribution,\n\t\t}),\n\t\t// The endpoint's hostname policy without the scoped drop rule (this caller knows its\n\t\t// boundary); a capture call site, so the host's resolver sees the visit, not the user.\n\t\thostname: (args: Parameters<IngestHostnameResolver>[0]) =>\n\t\t\tresolveEventHostname({\n\t\t\t\toption: hostname,\n\t\t\t\tclaimed: args.claimed,\n\t\t\t\treq: captureRequest(args.req),\n\t\t\t\tscope: args.scope ?? null,\n\t\t\t\ttrustedProxyHops: registration.attribution.trustedProxyHops,\n\t\t\t}),\n\t}\n\n\treturn {\n\t\tid: NATIVE_ADAPTER_ID,\n\t\t...adapterLabel(options.label, 'Payload', 'native({ label })'),\n\t\tget capabilities() {\n\t\t\treturn capabilities\n\t\t},\n\t\tcapture: nativeCapture,\n\t\tingest,\n\t\tisConfigured: () => true,\n\t\tflush: async (payload) => {\n\t\t\tawait instanceOf(payload).writer.flush()\n\t\t},\n\t\trebuild: (payload, input) => {\n\t\t\tgetRuntime(payload)\n\t\t\treturn instanceOf(payload).engine.rebuild(input)\n\t\t},\n\t\treceive,\n\t\tregister(config: Config, context) {\n\t\t\tif (isD1({ db: { name: config.db?.name ?? '' } })) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tregistration = registrationOf(context)\n\t\t\tcapabilities = capabilitiesOf(registration, ANY_STORE_FILTERS)\n\t\t\tif (context?.routes) {\n\t\t\t\tmountedIngestPath = context.routes.ingest\n\t\t\t}\n\t\t\treceiveBeacon = beaconHandler()\n\t\t\taddStoreCollections(config, context?.notice)\n\t\t\tconfig.endpoints = [\n\t\t\t\t...(config.endpoints ?? []),\n\t\t\t\t{ method: 'post', path: ingest.path, handler: receive },\n\t\t\t]\n\t\t\tconst { jobs } = registration\n\t\t\tif (jobs !== false) {\n\t\t\t\taddTask(\n\t\t\t\t\tconfig,\n\t\t\t\t\tmaintainTask({\n\t\t\t\t\t\tschedule: jobs.maintain,\n\t\t\t\t\t\trun: maintainOnTask,\n\t\t\t\t\t\tconcurrency: registration.jobsConcurrency,\n\t\t\t\t\t})\n\t\t\t\t)\n\t\t\t}\n\t\t},\n\t\tregisterSchema(config: Config, context: AdapterSchemaContext) {\n\t\t\taddStoreCollections(config, context.notice)\n\t\t\tif (context.jobs !== false) {\n\t\t\t\taddTask(config, schemaOnlyTask(MAINTAIN_TASK_SLUG, context.jobs.maintain))\n\t\t\t}\n\t\t},\n\t\tattach(payload: Payload) {\n\t\t\tif (isD1(payload)) {\n\t\t\t\tthrow new Error(D1_REFUSAL)\n\t\t\t}\n\t\t\tif (\n\t\t\t\t!warnedMaxmind &&\n\t\t\t\tregistration.maxmind === undefined &&\n\t\t\t\tneedsMaxmindSdk(configuredGeo) &&\n\t\t\t\tisProductionBuild()\n\t\t\t) {\n\t\t\t\twarnedMaxmind = true\n\t\t\t\tpayload.logger?.warn(MAXMIND_SDK_WARNING)\n\t\t\t}\n\t\t\tinstanceOf(payload)\n\t\t},\n\t\tasync close(payload: Payload) {\n\t\t\tawait closeNativeInstance(payload, registration)\n\t\t},\n\t\tasync query(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.read(q, ctx)\n\t\t},\n\t\tasync realtime(q: AnalyticsQuery, ctx?: AdapterContext): Promise<AnalyticsResult> {\n\t\t\treturn instanceOf(payloadOf(ctx)).engine.realtime(q, ctx)\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2LA,MAAa,oBAAoB;AAEjC,MAAM,aACL;;AAkBD,MAAa,mBAAmB,YAC/B,QAAQ,OAAA,YACR,OAAO,QAAQ,IAAI,SAAS,SAAS,MAAM,cAC3C,OAAO,QAAQ,IAAI,SAAS,OAAO,MAAM,cACzC,OAAO,QAAQ,IAAI,SAAS,SAAS,MAAM;AAI5C,MAAM,gBAAgC;CACrC,OAAO,EAAE,QAAQ,CAAC,EAAE;CACpB,gBAAgB,EAAE,SAAS,CAAC,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AAG,CAAC,EAAE,OAAO,KAAK,GAAG,GAAG;EACrD;EACA,MAAM,SAAS,GAAmB,KAAgD;GACjF,OAAO,WAAW,UAAU,GAAG,CAAC,EAAE,OAAO,SAAS,GAAG,GAAG;EACzD;CACD;AACD"}
|
|
@@ -10,10 +10,12 @@ import { resolveTrackerConfig } from "../capture/trackerConfig.js";
|
|
|
10
10
|
import { TASK_SLUGS } from "../core/jobs.js";
|
|
11
11
|
import { monotonicMs } from "../core/monotonic.js";
|
|
12
12
|
import { ABANDON_AFTER_MS, createLanes, pooledConcurrency } from "../surfacing/lanes.js";
|
|
13
|
+
import { collectingPageData } from "./buildPhase.js";
|
|
14
|
+
import { isProductionBuild } from "./peers.js";
|
|
13
15
|
import { trackerAutoCapture, untrustedAddressNotice } from "../core/captureOptions.js";
|
|
14
|
-
import { configGoalsResolver, createGoalsResolver } from "../goals/resolver.js";
|
|
15
16
|
import { revenueOffWarning } from "../core/goalOptions.js";
|
|
16
17
|
import { DEFAULT_BINDING_SCOPE_FIELD } from "../core/options.js";
|
|
18
|
+
import { configGoalsResolver, createGoalsResolver } from "../goals/resolver.js";
|
|
17
19
|
import { recheckCollections } from "./collectionChecks.js";
|
|
18
20
|
import { throttled } from "../core/throttle.js";
|
|
19
21
|
import { hostHoldsWriteLock, sqliteTransactionsNotice } from "../db/detachedWrite.js";
|
|
@@ -21,8 +23,6 @@ import { createHeartbeatWatch } from "../maintenance/heartbeat.js";
|
|
|
21
23
|
import { stateLease, stateStoreOf } from "../maintenance/lease.js";
|
|
22
24
|
import { trackServerEvent } from "../native/ingest/serverTrack.js";
|
|
23
25
|
import { createKeepAlive } from "./keepAlive.js";
|
|
24
|
-
import { collectingPageData } from "./buildPhase.js";
|
|
25
|
-
import { isProductionBuild } from "./peers.js";
|
|
26
26
|
import { narrowStatsGlobal } from "./jobsAccess.js";
|
|
27
27
|
import { loadEncrypted } from "./encrypted.js";
|
|
28
28
|
import { SWEEP_LEASE, SWEEP_LEASE_MS, createCacheSweeper } from "../surfacing/cacheSweep.js";
|
|
@@ -62,6 +62,7 @@ const providerPlanOf = (resolved) => {
|
|
|
62
62
|
kind: "collection",
|
|
63
63
|
slug: collection.slug,
|
|
64
64
|
scopeField: collection.scopeField,
|
|
65
|
+
types: collection.types,
|
|
65
66
|
...nativeAdapter ? { nativeAdapter } : {}
|
|
66
67
|
};
|
|
67
68
|
};
|
|
@@ -106,6 +107,8 @@ const settledFieldsOf = (args) => {
|
|
|
106
107
|
resolveTimezone: args.resolveTimezone,
|
|
107
108
|
...resolved.revenue.enabled && resolved.revenue.currency !== void 0 ? { resolveCurrency: args.resolveCurrency } : {},
|
|
108
109
|
platformAdapterId: resolved.platformAdapter,
|
|
110
|
+
...resolved.sources.policies.size > 0 ? { sourcePolicies: resolved.sources.policies } : {},
|
|
111
|
+
...resolved.sources.defaultSource ? { defaultSource: resolved.sources.defaultSource } : {},
|
|
109
112
|
captureSlots: resolved.capture.slots,
|
|
110
113
|
capturePaths: resolved.capture.paths,
|
|
111
114
|
captureProxy: resolved.capture.proxy,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRuntime.js","names":[],"sources":["../../src/plugin/createRuntime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { itemCollectionsOf } from '../binding/report'\nimport { resolveTrackerConfig } from '../capture/trackerConfig'\nimport { currentDate, currentTime } from '../core/clock'\nimport type { AnalyticsResult } from '../core/contract'\nimport { TASK_SLUGS } from '../core/jobs'\nimport { monotonicMs } from '../core/monotonic'\nimport {\n\tDEFAULT_BINDING_SCOPE_FIELD,\n\ttype ResolvedOptions,\n\trevenueOffWarning,\n\ttype ScopeCallSite,\n\ttrackerAutoCapture,\n\tuntrustedAddressNotice,\n} from '../core/options'\nimport { type AdapterRegistry, withoutRevenue } from '../core/registry'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { throttled } from '../core/throttle'\nimport { isRecord } from '../core/values'\nimport { hostHoldsWriteLock, sqliteTransactionsNotice } from '../db/detachedWrite'\nimport { configGoalsResolver, createGoalsResolver, type GoalsResolver } from '../goals/resolver'\nimport { createHeartbeatWatch } from '../maintenance/heartbeat'\nimport { stateLease, stateStoreOf } from '../maintenance/lease'\nimport { trackServerEvent } from '../native/ingest/serverTrack'\nimport { NATIVE_ADAPTER_ID } from '../native/nativeAdapter'\nimport { createGuardedFetch } from '../net/guardedFetch'\nimport { configTokenBackend } from '../providers/refresh'\nimport { createProviderRegistry, type ProviderPlan } from '../providers/registry'\nimport { emptyTrackerConfig, type TrackerConfigSource } from '../site/getTrackerConfig'\nimport { createCacheSweeper, SWEEP_LEASE, SWEEP_LEASE_MS } from '../surfacing/cacheSweep'\nimport { collectionCacheStore } from '../surfacing/collectionCacheStore'\nimport { type CacheOperation, createEngine } from '../surfacing/engine'\nimport { createEpochStore } from '../surfacing/epoch'\nimport { ABANDON_AFTER_MS, createLanes, pooledConcurrency } from '../surfacing/lanes'\nimport { createMemo } from '../surfacing/memo'\nimport { collectingPageData } from './buildPhase'\nimport { type ExpectedCollection, recheckCollections } from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport { narrowStatsGlobal } from './jobsAccess'\nimport { createKeepAlive } from './keepAlive'\nimport { isProductionBuild } from './peers'\nimport { assertRoutesReachable } from './routeChecks'\nimport { type AnalyticsRuntime, getRuntime, type RuntimeFactory } from './runtime'\nimport { validateScopeField } from './scopeFieldBoot'\n\n/** How often a failing read cache, or a throwing `hooks.afterRead`, is reported, at most. */\nconst CACHE_WARN_EVERY_MS = 60_000\n\n/** node-postgres' own default for the pool's `max`. */\nconst PG_DEFAULT_POOL_MAX = 10\n\n/** The host's node-postgres pool size, or undefined on another database. */\nconst postgresPoolMax = (payload: Payload): number | undefined => {\n\tconst db: unknown = payload.db\n\tif (!isRecord(db) || db.name !== 'postgres') {\n\t\treturn undefined\n\t}\n\tconst pool = db.pool\n\tconst options = isRecord(pool) && isRecord(pool.options) ? pool.options : db.poolOptions\n\tconst max = isRecord(options) ? options.max : undefined\n\treturn typeof max === 'number' && Number.isFinite(max) && max > 0 ? max : PG_DEFAULT_POOL_MAX\n}\n\ninterface RuntimeFactoryArgs {\n\tresolved: ResolvedOptions\n\t/** What the collection checks found worth a warning, said once at init. */\n\tnotices: readonly string[]\n\t/** The plugin's collections as the boot checked them, held to that again in the assembled config. */\n\tcollections: readonly ExpectedCollection[]\n\t/** The config registry, with revenue already removed where the install measures no money. */\n\tregistry: AdapterRegistry\n\tresolveScope: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\tresolveCurrency: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n}\n\n/** Where the install's runtime provider adapters come from. */\nconst providerPlanOf = (resolved: ResolvedOptions): ProviderPlan => {\n\tconst { resolve, collection } = resolved.providers\n\tif (resolve) {\n\t\treturn { kind: 'resolve', resolve }\n\t}\n\tif (!collection.enabled) {\n\t\treturn { kind: 'static' }\n\t}\n\tconst nativeAdapter = resolved.adapters.find((adapter) => adapter.id === NATIVE_ADAPTER_ID)\n\treturn {\n\t\tkind: 'collection',\n\t\tslug: collection.slug,\n\t\tscopeField: collection.scopeField,\n\t\t...(nativeAdapter ? { nativeAdapter } : {}),\n\t}\n}\n\n/** Config goals merged with the goals collection of one instance, when the install runs it. */\nconst goalsResolverFor = (\n\tpayload: Payload,\n\tresolved: ResolvedOptions,\n\tnow: () => number\n): GoalsResolver =>\n\tresolved.goalsCollection.enabled\n\t\t? createGoalsResolver({\n\t\t\t\tpayload,\n\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tconfig: resolved.goals,\n\t\t\t\tpurchase: resolved.purchaseGoal,\n\t\t\t\tnow,\n\t\t\t})\n\t\t: configGoalsResolver(resolved.goals, resolved.purchaseGoal)\n\n/**\n * Native reads stay out of the global cap, so a slow vendor never queues them; on a scoped install\n * every config adapter serves all scopes, so one scope holds at most half of its lane.\n */\nconst lanesFor = (payload: Payload, resolved: ResolvedOptions, plan: ProviderPlan) => {\n\tconst { concurrency } = resolved.cache\n\tconst configAdapters = new Set(resolved.adapters)\n\tconst poolMax = postgresPoolMax(payload)\n\treturn createLanes({\n\t\tglobal: concurrency.global,\n\t\tperSource: concurrency.perSource,\n\t\tlocal: {\n\t\t\tis: (adapter) => adapter.id === NATIVE_ADAPTER_ID,\n\t\t\t...(poolMax === undefined ? {} : { capacity: pooledConcurrency(poolMax) }),\n\t\t},\n\t\t...(resolved.scoped ? { shared: (adapter) => configAdapters.has(adapter) } : {}),\n\t\t...(plan.kind === 'resolve' ? { rebuilt: (adapter) => !configAdapters.has(adapter) } : {}),\n\t\tonAbandon: (adapter) =>\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: a request to the \"${adapter.id}\" source ignored its abort signal and was still out ${ABANDON_AFTER_MS / 1000} seconds after its read gave up, so its slot was given back and it counts as a timeout. An adapter must pass ctx.signal (or the signal ctx.upstream hands it) to every request it sends; this is said once per source.`\n\t\t\t),\n\t})\n}\n\n/** The runtime fields config time settled outright, alike for every instance. */\nconst settledFieldsOf = (args: RuntimeFactoryArgs) => {\n\tconst { resolved } = args\n\tconst providers = resolved.providers.collection\n\treturn {\n\t\tregistry: args.registry,\n\t\tresolveScope: args.resolveScope,\n\t\t...(resolved.scope.member ? { member: resolved.scope.member } : {}),\n\t\tresolveTimezone: args.resolveTimezone,\n\t\t// Only when the install configured one: absent, every read path skips the scope\n\t\t// resolution the lookup would have needed and revenue stays a plain number.\n\t\t...(resolved.revenue.enabled && resolved.revenue.currency !== undefined\n\t\t\t? { resolveCurrency: args.resolveCurrency }\n\t\t\t: {}),\n\t\tplatformAdapterId: resolved.platformAdapter,\n\t\tcaptureSlots: resolved.capture.slots,\n\t\tcapturePaths: resolved.capture.paths,\n\t\tcaptureProxy: resolved.capture.proxy,\n\t\ttrustedProxyHops: resolved.trustedProxyHops,\n\t\ttrustedPlatform: resolved.trustedPlatform,\n\t\tallowedOrigins: resolved.capture.allowedOrigins,\n\t\t...(resolved.capture.exclusion ? { exclusion: resolved.capture.exclusion } : {}),\n\t\tcaptureGate: resolved.capture.gate,\n\t\tautoCapture: trackerAutoCapture(\n\t\t\tresolved.capture.autoCapture,\n\t\t\titemCollectionsOf(resolved.bindings).size > 0\n\t\t),\n\t\tcaptureSkip: resolved.capture.skip,\n\t\tgoals: resolved.goals,\n\t\tpurchaseGoal: resolved.purchaseGoal,\n\t\t...(resolved.goalsCollection.enabled\n\t\t\t? { goalsCollectionSlug: resolved.goalsCollection.slug }\n\t\t\t: {}),\n\t\t...(providers.enabled\n\t\t\t? {\n\t\t\t\t\tprovidersCollection: {\n\t\t\t\t\t\tslug: providers.slug,\n\t\t\t\t\t\tscopeField: providers.scopeField,\n\t\t\t\t\t\t...(providers.sourceAccess ? { sourceAccess: providers.sourceAccess } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tingestPath: resolved.adapters.find((adapter) => adapter.ingest)?.ingest?.path,\n\t\tscoped: resolved.scoped,\n\t\tcountryFlags: resolved.countryFlags,\n\t\t...(resolved.scope.label ? { scopeLabel: resolved.scope.label } : {}),\n\t\t...(resolved.scope.list ? { scopeList: resolved.scope.list } : {}),\n\t\t...(resolved.cache.store ? {} : { cacheCollectionSlug: resolved.cache.collection.slug }),\n\t\tconfigAdapterIds: new Set(resolved.adapters.map((adapter) => adapter.id)),\n\t\tcrossScope: resolved.access.crossScope,\n\t\treadAccess: resolved.access.read,\n\t\tviewAccess: resolved.access.view,\n\t\tbindings: resolved.bindings,\n\t\tttl: resolved.cache.ttl,\n\t\tcomparison: resolved.widgets.comparison,\n\t\tadapters: resolved.adapters,\n\t} satisfies Partial<AnalyticsRuntime>\n}\n\nconst BINDING_SCOPE_FIELD_REMEDY =\n\t\"name the field this collection's documents carry their tenant in, or set it to false to read the request's own scope\"\n\n/** Fails boot on a `scopeField` the assembled config lacks, for every collection naming one. */\nconst validateScopeFields = (payload: Payload, resolved: ResolvedOptions): void => {\n\tif (resolved.scoped && resolved.goalsCollection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'goals.collection.scopeField',\n\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t})\n\t}\n\tif (resolved.scoped && resolved.providers.collection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'providers.collection.scopeField',\n\t\t\tslug: resolved.providers.collection.slug,\n\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t})\n\t}\n\tfor (const [slug, binding] of Object.entries(resolved.bindings)) {\n\t\tif (binding.scopeField === false) {\n\t\t\tcontinue\n\t\t}\n\t\tvalidateScopeField(payload, {\n\t\t\toption: `collections.${slug}.scopeField`,\n\t\t\tslug,\n\t\t\tscopeField: binding.scopeField,\n\t\t\tremedy:\n\t\t\t\tbinding.scopeField === DEFAULT_BINDING_SCOPE_FIELD\n\t\t\t\t\t? `\"${DEFAULT_BINDING_SCOPE_FIELD}\" is the default on a scoped install when scopeField is not set, so ${BINDING_SCOPE_FIELD_REMEDY}`\n\t\t\t\t\t: BINDING_SCOPE_FIELD_REMEDY,\n\t\t})\n\t}\n}\n\n/**\n * Everything config time settled, turned into a runtime per Payload instance on demand, plus the\n * checks that need the assembled config: other plugins add collections and fields after this one.\n */\nexport const createRuntimeFactory = (\n\targs: RuntimeFactoryArgs\n): RuntimeFactory & TrackerConfigSource => {\n\tconst { resolved } = args\n\tconst money = resolved.revenue.enabled\n\tconst providers = resolved.providers.collection\n\tconst plan = providerPlanOf(resolved)\n\tconst rechecked = new WeakSet<object>()\n\t/** The checks only the assembled config can answer, once per config. */\n\tconst checkAssembled = (payload: Payload): void => {\n\t\tif (rechecked.has(payload.config)) {\n\t\t\treturn\n\t\t}\n\t\tassertRoutesReachable(resolved.routes.base, payload.config)\n\t\trecheckCollections(payload.config.collections ?? [], args.collections, payload.db?.name)\n\t\tnarrowStatsGlobal(payload)\n\t\trechecked.add(payload.config)\n\t}\n\treturn {\n\t\tcreate: (payload) => {\n\t\t\t// Here rather than in onInit alone: a worker booted without onInit and an HMR reload build\n\t\t\t// their runtime on first use, from a config other plugins may have changed.\n\t\t\tcheckAssembled(payload)\n\t\t\tfor (const adapter of resolved.adapters) {\n\t\t\t\tadapter.attach?.(payload)\n\t\t\t}\n\t\t\t// The adapters a `providers.resolve` builds from editor-written settings need the same\n\t\t\t// guarded connection the collection's own documents get.\n\t\t\tconst providerConnections =\n\t\t\t\tproviders.enabled || resolved.providers.resolve\n\t\t\t\t\t? createGuardedFetch({\n\t\t\t\t\t\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\t\t\t\t\t\twarn: (message) => payload.logger?.warn(message),\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst epoch = createEpochStore(payload)\n\t\t\tconst now = currentTime\n\t\t\tconst warn = (message: string) => payload.logger?.warn(message)\n\t\t\tconst registry = createProviderRegistry({\n\t\t\t\tpayload,\n\t\t\t\tplan,\n\t\t\t\tbase: { adapters: resolved.adapters, defaultId: resolved.defaultAdapter },\n\t\t\t\tregistry: args.registry,\n\t\t\t\tnarrow: money ? (scoped) => scoped : withoutRevenue,\n\t\t\t\thosts: resolved.providers.hosts,\n\t\t\t\tfetch: providerConnections?.fetch,\n\t\t\t\tsdks: resolved.sdks,\n\t\t\t\t...(plan.kind === 'resolve'\n\t\t\t\t\t? { tokens: createEpochStore(payload, { now, backend: configTokenBackend(payload) }) }\n\t\t\t\t\t: {}),\n\t\t\t\tnow,\n\t\t\t})\n\t\t\tconst goals = goalsResolverFor(payload, resolved, now)\n\t\t\t// Only where something can change at runtime; an install configured in code keys every read\n\t\t\t// on the fixed epoch.\n\t\t\tconst configEpoch =\n\t\t\t\tplan.kind === 'static' && !resolved.goalsCollection.enabled\n\t\t\t\t\t? undefined\n\t\t\t\t\t: async (scope?: string | null): Promise<string> => {\n\t\t\t\t\t\t\tconst [providerEpoch, goalsEpoch] = await Promise.all([\n\t\t\t\t\t\t\t\tregistry.epoch(scope ?? null),\n\t\t\t\t\t\t\t\tgoals.epoch(scope),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\treturn `${providerEpoch}.${goalsEpoch}`\n\t\t\t\t\t\t}\n\t\t\tconst store =\n\t\t\t\tresolved.cache.store ??\n\t\t\t\tcollectionCacheStore(payload, { slug: resolved.cache.collection.slug })\n\t\t\tconst memo = createMemo<AnalyticsResult>({ now })\n\t\t\tconst sweeper = createCacheSweeper({\n\t\t\t\tstore,\n\t\t\t\tlease: () => stateLease(payload, SWEEP_LEASE, SWEEP_LEASE_MS),\n\t\t\t\tnow: currentDate,\n\t\t\t\twarn,\n\t\t\t\tdeferred: () => hostHoldsWriteLock(payload),\n\t\t\t})\n\t\t\t// Sync has no fallback: a runner that stopped is only noticed here, by the reads it leaves stale.\n\t\t\tconst { jobs } = resolved\n\t\t\tconst syncWatch =\n\t\t\t\tresolved.sync.enabled && jobs !== false\n\t\t\t\t\t? createHeartbeatWatch({\n\t\t\t\t\t\t\ttask: TASK_SLUGS.sync,\n\t\t\t\t\t\t\tschedule: jobs.sync,\n\t\t\t\t\t\t\tstate: () => stateStoreOf(payload),\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\twarn,\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst cacheWarning = throttled(warn, { now: monotonicMs, intervalMs: CACHE_WARN_EVERY_MS })\n\t\t\tconst onStoreError = (err: unknown, operation: CacheOperation) => {\n\t\t\t\tcacheWarning(\n\t\t\t\t\t`analytics: the read cache failed to ${operation}, reads go on without it: ${String(err)}`\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst keepAlive = createKeepAlive({\n\t\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next marks the processes serving its requests, the only ones `after()` works in\n\t\t\t\tenv: process.env,\n\t\t\t\twarn,\n\t\t\t})\n\t\t\tconst afterRead = resolved.hooks.afterRead\n\t\t\tconst hookWarning = throttled(warn, { now: monotonicMs, intervalMs: CACHE_WARN_EVERY_MS })\n\t\t\tconst engine = createEngine({\n\t\t\t\tpayload,\n\t\t\t\tstore,\n\t\t\t\tmemo,\n\t\t\t\tlanes: lanesFor(payload, resolved, plan),\n\t\t\t\tcoldReadsPerScope: resolved.cache.concurrency.perScope,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tepoch,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tnow,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\twarn(`analytics: read failed for adapter \"${adapterId}\": ${describeWithCauses(err)}`)\n\t\t\t\t},\n\t\t\t\tonStoreError,\n\t\t\t\tonWrite: () => sweeper.maybeSweep(),\n\t\t\t\t...(syncWatch ? { onRead: () => syncWatch.maybeCheck() } : {}),\n\t\t\t\tkeepAlive,\n\t\t\t\t...(afterRead\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tafterRead,\n\t\t\t\t\t\t\tonHookError: (err: unknown) =>\n\t\t\t\t\t\t\t\thookWarning(\n\t\t\t\t\t\t\t\t\t`analytics: hooks.afterRead threw, reads are answered without it: ${String(err)}`\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...settledFieldsOf(args),\n\t\t\t\tresolveRegistry: registry.resolve,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tconfigChanged: (collection, scopes) =>\n\t\t\t\t\tcollection === 'providers' ? registry.changed(scopes) : goals.changed(scopes),\n\t\t\t\trefreshProviders: registry.refresh,\n\t\t\t\t...(registry.granted ? { providerGranted: registry.granted } : {}),\n\t\t\t\tresolveGoals: goals.resolve,\n\t\t\t\tresolveGoalsDetailed: goals.resolveDetailed,\n\t\t\t\tlistGoals: goals.listReadable,\n\t\t\t\tlistGoalsAcross: goals.listAcross,\n\t\t\t\t...(providerConnections ? { providerFetch: providerConnections.fetch } : {}),\n\t\t\t\t// Refreshes and sweeps still running write to the database, which closes after this.\n\t\t\t\tclose: async () => {\n\t\t\t\t\tawait Promise.all([engine.close(), sweeper.idle(), syncWatch?.idle()])\n\t\t\t\t\tawait registry.close()\n\t\t\t\t\tawait providerConnections?.close()\n\t\t\t\t},\n\t\t\t\ttrack: (event, opts) => trackServerEvent(payload, event, opts),\n\t\t\t\tengine,\n\t\t\t\tepoch,\n\t\t\t\tmemo,\n\t\t\t\tcache: { store, sweeper },\n\t\t\t}\n\t\t},\n\t\tresolved,\n\t\ttrackerConfig: async (payload, req, draft) => {\n\t\t\tconst runtime = getRuntime(payload)\n\t\t\treturn runtime ? resolveTrackerConfig({ runtime, req, draft }) : emptyTrackerConfig(req)\n\t\t},\n\t\tvalidate: async (payload) => {\n\t\t\tcheckAssembled(payload)\n\t\t\t// `next build` boots once per worker and serves nothing; the server that does says these.\n\t\t\tconst warn = collectingPageData()\n\t\t\t\t? () => undefined\n\t\t\t\t: (message: string) => payload.logger?.warn(message)\n\t\t\tfor (const notice of args.notices) {\n\t\t\t\twarn(notice)\n\t\t\t}\n\t\t\tif (!resolved.cache.store) {\n\t\t\t\tawait collectionCacheStore(payload, { slug: resolved.cache.collection.slug }).prepare()\n\t\t\t}\n\t\t\tvalidateScopeFields(payload, resolved)\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await loadEncrypted()\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst moneyOff = revenueOffWarning(resolved)\n\t\t\tif (moneyOff) {\n\t\t\t\twarn(moneyOff)\n\t\t\t}\n\t\t\tconst spoofable = untrustedAddressNotice(resolved, isProductionBuild())\n\t\t\tif (spoofable) {\n\t\t\t\twarn(spoofable)\n\t\t\t}\n\t\t\tconst transactions = sqliteTransactionsNotice(pay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Ae,OAAO;GAEtB,MAAM,OAAO,mBAAmB,UACvB,KAAA,KACL,YAAoB,QAAQ,QAAQ,KAAK,OAAO;GACpD,KAAK,MAAM,UAAU,KAAK,SACzB,KAAK,MAAM;GAEZ,IAAI,CAAC,SAAS,MAAM,OACnB,MAAM,qBAAqB,SAAS,EAAE,MAAM,SAAS,MAAM,WAAW,KAAK,CAAC,EAAE,QAAQ;GAEvF,oBAAoB,SAAS,QAAQ;GACrC,IAAI,SAAS,UAAU,WAAW,SAAS;IAC1C,MAAM,EAAE,0BAA0B,MAAM,cAAc;IACtD,MAAM,sBAAsB,SAAS,SAAS,UAAU,WAAW,YAAY,IAAI;GACpF;GACA,MAAM,WAAW,kBAAkB,QAAQ;GAC3C,IAAI,UACH,KAAK,QAAQ;GAEd,MAAM,YAAY,uBAAuB,UAAU,kBAAkB,CAAC;GACtE,IAAI,WACH,KAAK,SAAS;GAEf,MAAM,eAAe,yBAAyB,OAAO;GACrD,IAAI,cACH,KAAK,YAAY;EAEnB;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"createRuntime.js","names":[],"sources":["../../src/plugin/createRuntime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { itemCollectionsOf } from '../binding/report'\nimport { resolveTrackerConfig } from '../capture/trackerConfig'\nimport { currentDate, currentTime } from '../core/clock'\nimport type { AnalyticsResult } from '../core/contract'\nimport { TASK_SLUGS } from '../core/jobs'\nimport { monotonicMs } from '../core/monotonic'\nimport {\n\tDEFAULT_BINDING_SCOPE_FIELD,\n\ttype ResolvedOptions,\n\trevenueOffWarning,\n\ttype ScopeCallSite,\n\ttrackerAutoCapture,\n\tuntrustedAddressNotice,\n} from '../core/options'\nimport { type AdapterRegistry, withoutRevenue } from '../core/registry'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { throttled } from '../core/throttle'\nimport { isRecord } from '../core/values'\nimport { hostHoldsWriteLock, sqliteTransactionsNotice } from '../db/detachedWrite'\nimport { configGoalsResolver, createGoalsResolver, type GoalsResolver } from '../goals/resolver'\nimport { createHeartbeatWatch } from '../maintenance/heartbeat'\nimport { stateLease, stateStoreOf } from '../maintenance/lease'\nimport { trackServerEvent } from '../native/ingest/serverTrack'\nimport { NATIVE_ADAPTER_ID } from '../native/nativeAdapter'\nimport { createGuardedFetch } from '../net/guardedFetch'\nimport { configTokenBackend } from '../providers/refresh'\nimport { createProviderRegistry, type ProviderPlan } from '../providers/registry'\nimport { emptyTrackerConfig, type TrackerConfigSource } from '../site/getTrackerConfig'\nimport { createCacheSweeper, SWEEP_LEASE, SWEEP_LEASE_MS } from '../surfacing/cacheSweep'\nimport { collectionCacheStore } from '../surfacing/collectionCacheStore'\nimport { type CacheOperation, createEngine } from '../surfacing/engine'\nimport { createEpochStore } from '../surfacing/epoch'\nimport { ABANDON_AFTER_MS, createLanes, pooledConcurrency } from '../surfacing/lanes'\nimport { createMemo } from '../surfacing/memo'\nimport { collectingPageData } from './buildPhase'\nimport { type ExpectedCollection, recheckCollections } from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport { narrowStatsGlobal } from './jobsAccess'\nimport { createKeepAlive } from './keepAlive'\nimport { isProductionBuild } from './peers'\nimport { assertRoutesReachable } from './routeChecks'\nimport { type AnalyticsRuntime, getRuntime, type RuntimeFactory } from './runtime'\nimport { validateScopeField } from './scopeFieldBoot'\n\n/** How often a failing read cache, or a throwing `hooks.afterRead`, is reported, at most. */\nconst CACHE_WARN_EVERY_MS = 60_000\n\n/** node-postgres' own default for the pool's `max`. */\nconst PG_DEFAULT_POOL_MAX = 10\n\n/** The host's node-postgres pool size, or undefined on another database. */\nconst postgresPoolMax = (payload: Payload): number | undefined => {\n\tconst db: unknown = payload.db\n\tif (!isRecord(db) || db.name !== 'postgres') {\n\t\treturn undefined\n\t}\n\tconst pool = db.pool\n\tconst options = isRecord(pool) && isRecord(pool.options) ? pool.options : db.poolOptions\n\tconst max = isRecord(options) ? options.max : undefined\n\treturn typeof max === 'number' && Number.isFinite(max) && max > 0 ? max : PG_DEFAULT_POOL_MAX\n}\n\ninterface RuntimeFactoryArgs {\n\tresolved: ResolvedOptions\n\t/** What the collection checks found worth a warning, said once at init. */\n\tnotices: readonly string[]\n\t/** The plugin's collections as the boot checked them, held to that again in the assembled config. */\n\tcollections: readonly ExpectedCollection[]\n\t/** The config registry, with revenue already removed where the install measures no money. */\n\tregistry: AdapterRegistry\n\tresolveScope: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\tresolveCurrency: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n}\n\n/** Where the install's runtime provider adapters come from. */\nconst providerPlanOf = (resolved: ResolvedOptions): ProviderPlan => {\n\tconst { resolve, collection } = resolved.providers\n\tif (resolve) {\n\t\treturn { kind: 'resolve', resolve }\n\t}\n\tif (!collection.enabled) {\n\t\treturn { kind: 'static' }\n\t}\n\tconst nativeAdapter = resolved.adapters.find((adapter) => adapter.id === NATIVE_ADAPTER_ID)\n\treturn {\n\t\tkind: 'collection',\n\t\tslug: collection.slug,\n\t\tscopeField: collection.scopeField,\n\t\ttypes: collection.types,\n\t\t...(nativeAdapter ? { nativeAdapter } : {}),\n\t}\n}\n\n/** Config goals merged with the goals collection of one instance, when the install runs it. */\nconst goalsResolverFor = (\n\tpayload: Payload,\n\tresolved: ResolvedOptions,\n\tnow: () => number\n): GoalsResolver =>\n\tresolved.goalsCollection.enabled\n\t\t? createGoalsResolver({\n\t\t\t\tpayload,\n\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tconfig: resolved.goals,\n\t\t\t\tpurchase: resolved.purchaseGoal,\n\t\t\t\tnow,\n\t\t\t})\n\t\t: configGoalsResolver(resolved.goals, resolved.purchaseGoal)\n\n/**\n * Native reads stay out of the global cap, so a slow vendor never queues them; on a scoped install\n * every config adapter serves all scopes, so one scope holds at most half of its lane.\n */\nconst lanesFor = (payload: Payload, resolved: ResolvedOptions, plan: ProviderPlan) => {\n\tconst { concurrency } = resolved.cache\n\tconst configAdapters = new Set(resolved.adapters)\n\tconst poolMax = postgresPoolMax(payload)\n\treturn createLanes({\n\t\tglobal: concurrency.global,\n\t\tperSource: concurrency.perSource,\n\t\tlocal: {\n\t\t\tis: (adapter) => adapter.id === NATIVE_ADAPTER_ID,\n\t\t\t...(poolMax === undefined ? {} : { capacity: pooledConcurrency(poolMax) }),\n\t\t},\n\t\t...(resolved.scoped ? { shared: (adapter) => configAdapters.has(adapter) } : {}),\n\t\t...(plan.kind === 'resolve' ? { rebuilt: (adapter) => !configAdapters.has(adapter) } : {}),\n\t\tonAbandon: (adapter) =>\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: a request to the \"${adapter.id}\" source ignored its abort signal and was still out ${ABANDON_AFTER_MS / 1000} seconds after its read gave up, so its slot was given back and it counts as a timeout. An adapter must pass ctx.signal (or the signal ctx.upstream hands it) to every request it sends; this is said once per source.`\n\t\t\t),\n\t})\n}\n\n/** The runtime fields config time settled outright, alike for every instance. */\nconst settledFieldsOf = (args: RuntimeFactoryArgs) => {\n\tconst { resolved } = args\n\tconst providers = resolved.providers.collection\n\treturn {\n\t\tregistry: args.registry,\n\t\tresolveScope: args.resolveScope,\n\t\t...(resolved.scope.member ? { member: resolved.scope.member } : {}),\n\t\tresolveTimezone: args.resolveTimezone,\n\t\t// Only when the install configured one: absent, every read path skips the scope\n\t\t// resolution the lookup would have needed and revenue stays a plain number.\n\t\t...(resolved.revenue.enabled && resolved.revenue.currency !== undefined\n\t\t\t? { resolveCurrency: args.resolveCurrency }\n\t\t\t: {}),\n\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t...(resolved.sources.policies.size > 0 ? { sourcePolicies: resolved.sources.policies } : {}),\n\t\t...(resolved.sources.defaultSource ? { defaultSource: resolved.sources.defaultSource } : {}),\n\t\tcaptureSlots: resolved.capture.slots,\n\t\tcapturePaths: resolved.capture.paths,\n\t\tcaptureProxy: resolved.capture.proxy,\n\t\ttrustedProxyHops: resolved.trustedProxyHops,\n\t\ttrustedPlatform: resolved.trustedPlatform,\n\t\tallowedOrigins: resolved.capture.allowedOrigins,\n\t\t...(resolved.capture.exclusion ? { exclusion: resolved.capture.exclusion } : {}),\n\t\tcaptureGate: resolved.capture.gate,\n\t\tautoCapture: trackerAutoCapture(\n\t\t\tresolved.capture.autoCapture,\n\t\t\titemCollectionsOf(resolved.bindings).size > 0\n\t\t),\n\t\tcaptureSkip: resolved.capture.skip,\n\t\tgoals: resolved.goals,\n\t\tpurchaseGoal: resolved.purchaseGoal,\n\t\t...(resolved.goalsCollection.enabled\n\t\t\t? { goalsCollectionSlug: resolved.goalsCollection.slug }\n\t\t\t: {}),\n\t\t...(providers.enabled\n\t\t\t? {\n\t\t\t\t\tprovidersCollection: {\n\t\t\t\t\t\tslug: providers.slug,\n\t\t\t\t\t\tscopeField: providers.scopeField,\n\t\t\t\t\t\t...(providers.sourceAccess ? { sourceAccess: providers.sourceAccess } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tingestPath: resolved.adapters.find((adapter) => adapter.ingest)?.ingest?.path,\n\t\tscoped: resolved.scoped,\n\t\tcountryFlags: resolved.countryFlags,\n\t\t...(resolved.scope.label ? { scopeLabel: resolved.scope.label } : {}),\n\t\t...(resolved.scope.list ? { scopeList: resolved.scope.list } : {}),\n\t\t...(resolved.cache.store ? {} : { cacheCollectionSlug: resolved.cache.collection.slug }),\n\t\tconfigAdapterIds: new Set(resolved.adapters.map((adapter) => adapter.id)),\n\t\tcrossScope: resolved.access.crossScope,\n\t\treadAccess: resolved.access.read,\n\t\tviewAccess: resolved.access.view,\n\t\tbindings: resolved.bindings,\n\t\tttl: resolved.cache.ttl,\n\t\tcomparison: resolved.widgets.comparison,\n\t\tadapters: resolved.adapters,\n\t} satisfies Partial<AnalyticsRuntime>\n}\n\nconst BINDING_SCOPE_FIELD_REMEDY =\n\t\"name the field this collection's documents carry their tenant in, or set it to false to read the request's own scope\"\n\n/** Fails boot on a `scopeField` the assembled config lacks, for every collection naming one. */\nconst validateScopeFields = (payload: Payload, resolved: ResolvedOptions): void => {\n\tif (resolved.scoped && resolved.goalsCollection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'goals.collection.scopeField',\n\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t})\n\t}\n\tif (resolved.scoped && resolved.providers.collection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'providers.collection.scopeField',\n\t\t\tslug: resolved.providers.collection.slug,\n\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t})\n\t}\n\tfor (const [slug, binding] of Object.entries(resolved.bindings)) {\n\t\tif (binding.scopeField === false) {\n\t\t\tcontinue\n\t\t}\n\t\tvalidateScopeField(payload, {\n\t\t\toption: `collections.${slug}.scopeField`,\n\t\t\tslug,\n\t\t\tscopeField: binding.scopeField,\n\t\t\tremedy:\n\t\t\t\tbinding.scopeField === DEFAULT_BINDING_SCOPE_FIELD\n\t\t\t\t\t? `\"${DEFAULT_BINDING_SCOPE_FIELD}\" is the default on a scoped install when scopeField is not set, so ${BINDING_SCOPE_FIELD_REMEDY}`\n\t\t\t\t\t: BINDING_SCOPE_FIELD_REMEDY,\n\t\t})\n\t}\n}\n\n/**\n * Everything config time settled, turned into a runtime per Payload instance on demand, plus the\n * checks that need the assembled config: other plugins add collections and fields after this one.\n */\nexport const createRuntimeFactory = (\n\targs: RuntimeFactoryArgs\n): RuntimeFactory & TrackerConfigSource => {\n\tconst { resolved } = args\n\tconst money = resolved.revenue.enabled\n\tconst providers = resolved.providers.collection\n\tconst plan = providerPlanOf(resolved)\n\tconst rechecked = new WeakSet<object>()\n\t/** The checks only the assembled config can answer, once per config. */\n\tconst checkAssembled = (payload: Payload): void => {\n\t\tif (rechecked.has(payload.config)) {\n\t\t\treturn\n\t\t}\n\t\tassertRoutesReachable(resolved.routes.base, payload.config)\n\t\trecheckCollections(payload.config.collections ?? [], args.collections, payload.db?.name)\n\t\tnarrowStatsGlobal(payload)\n\t\trechecked.add(payload.config)\n\t}\n\treturn {\n\t\tcreate: (payload) => {\n\t\t\t// Here rather than in onInit alone: a worker booted without onInit and an HMR reload build\n\t\t\t// their runtime on first use, from a config other plugins may have changed.\n\t\t\tcheckAssembled(payload)\n\t\t\tfor (const adapter of resolved.adapters) {\n\t\t\t\tadapter.attach?.(payload)\n\t\t\t}\n\t\t\t// The adapters a `providers.resolve` builds from editor-written settings need the same\n\t\t\t// guarded connection the collection's own documents get.\n\t\t\tconst providerConnections =\n\t\t\t\tproviders.enabled || resolved.providers.resolve\n\t\t\t\t\t? createGuardedFetch({\n\t\t\t\t\t\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\t\t\t\t\t\twarn: (message) => payload.logger?.warn(message),\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst epoch = createEpochStore(payload)\n\t\t\tconst now = currentTime\n\t\t\tconst warn = (message: string) => payload.logger?.warn(message)\n\t\t\tconst registry = createProviderRegistry({\n\t\t\t\tpayload,\n\t\t\t\tplan,\n\t\t\t\tbase: { adapters: resolved.adapters, defaultId: resolved.defaultAdapter },\n\t\t\t\tregistry: args.registry,\n\t\t\t\tnarrow: money ? (scoped) => scoped : withoutRevenue,\n\t\t\t\thosts: resolved.providers.hosts,\n\t\t\t\tfetch: providerConnections?.fetch,\n\t\t\t\tsdks: resolved.sdks,\n\t\t\t\t...(plan.kind === 'resolve'\n\t\t\t\t\t? { tokens: createEpochStore(payload, { now, backend: configTokenBackend(payload) }) }\n\t\t\t\t\t: {}),\n\t\t\t\tnow,\n\t\t\t})\n\t\t\tconst goals = goalsResolverFor(payload, resolved, now)\n\t\t\t// Only where something can change at runtime; an install configured in code keys every read\n\t\t\t// on the fixed epoch.\n\t\t\tconst configEpoch =\n\t\t\t\tplan.kind === 'static' && !resolved.goalsCollection.enabled\n\t\t\t\t\t? undefined\n\t\t\t\t\t: async (scope?: string | null): Promise<string> => {\n\t\t\t\t\t\t\tconst [providerEpoch, goalsEpoch] = await Promise.all([\n\t\t\t\t\t\t\t\tregistry.epoch(scope ?? null),\n\t\t\t\t\t\t\t\tgoals.epoch(scope),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\treturn `${providerEpoch}.${goalsEpoch}`\n\t\t\t\t\t\t}\n\t\t\tconst store =\n\t\t\t\tresolved.cache.store ??\n\t\t\t\tcollectionCacheStore(payload, { slug: resolved.cache.collection.slug })\n\t\t\tconst memo = createMemo<AnalyticsResult>({ now })\n\t\t\tconst sweeper = createCacheSweeper({\n\t\t\t\tstore,\n\t\t\t\tlease: () => stateLease(payload, SWEEP_LEASE, SWEEP_LEASE_MS),\n\t\t\t\tnow: currentDate,\n\t\t\t\twarn,\n\t\t\t\tdeferred: () => hostHoldsWriteLock(payload),\n\t\t\t})\n\t\t\t// Sync has no fallback: a runner that stopped is only noticed here, by the reads it leaves stale.\n\t\t\tconst { jobs } = resolved\n\t\t\tconst syncWatch =\n\t\t\t\tresolved.sync.enabled && jobs !== false\n\t\t\t\t\t? createHeartbeatWatch({\n\t\t\t\t\t\t\ttask: TASK_SLUGS.sync,\n\t\t\t\t\t\t\tschedule: jobs.sync,\n\t\t\t\t\t\t\tstate: () => stateStoreOf(payload),\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\twarn,\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst cacheWarning = throttled(warn, { now: monotonicMs, intervalMs: CACHE_WARN_EVERY_MS })\n\t\t\tconst onStoreError = (err: unknown, operation: CacheOperation) => {\n\t\t\t\tcacheWarning(\n\t\t\t\t\t`analytics: the read cache failed to ${operation}, reads go on without it: ${String(err)}`\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst keepAlive = createKeepAlive({\n\t\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next marks the processes serving its requests, the only ones `after()` works in\n\t\t\t\tenv: process.env,\n\t\t\t\twarn,\n\t\t\t})\n\t\t\tconst afterRead = resolved.hooks.afterRead\n\t\t\tconst hookWarning = throttled(warn, { now: monotonicMs, intervalMs: CACHE_WARN_EVERY_MS })\n\t\t\tconst engine = createEngine({\n\t\t\t\tpayload,\n\t\t\t\tstore,\n\t\t\t\tmemo,\n\t\t\t\tlanes: lanesFor(payload, resolved, plan),\n\t\t\t\tcoldReadsPerScope: resolved.cache.concurrency.perScope,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tepoch,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tnow,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\twarn(`analytics: read failed for adapter \"${adapterId}\": ${describeWithCauses(err)}`)\n\t\t\t\t},\n\t\t\t\tonStoreError,\n\t\t\t\tonWrite: () => sweeper.maybeSweep(),\n\t\t\t\t...(syncWatch ? { onRead: () => syncWatch.maybeCheck() } : {}),\n\t\t\t\tkeepAlive,\n\t\t\t\t...(afterRead\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tafterRead,\n\t\t\t\t\t\t\tonHookError: (err: unknown) =>\n\t\t\t\t\t\t\t\thookWarning(\n\t\t\t\t\t\t\t\t\t`analytics: hooks.afterRead threw, reads are answered without it: ${String(err)}`\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...settledFieldsOf(args),\n\t\t\t\tresolveRegistry: registry.resolve,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tconfigChanged: (collection, scopes) =>\n\t\t\t\t\tcollection === 'providers' ? registry.changed(scopes) : goals.changed(scopes),\n\t\t\t\trefreshProviders: registry.refresh,\n\t\t\t\t...(registry.granted ? { providerGranted: registry.granted } : {}),\n\t\t\t\tresolveGoals: goals.resolve,\n\t\t\t\tresolveGoalsDetailed: goals.resolveDetailed,\n\t\t\t\tlistGoals: goals.listReadable,\n\t\t\t\tlistGoalsAcross: goals.listAcross,\n\t\t\t\t...(providerConnections ? { providerFetch: providerConnections.fetch } : {}),\n\t\t\t\t// Refreshes and sweeps still running write to the database, which closes after this.\n\t\t\t\tclose: async () => {\n\t\t\t\t\tawait Promise.all([engine.close(), sweeper.idle(), syncWatch?.idle()])\n\t\t\t\t\tawait registry.close()\n\t\t\t\t\tawait providerConnections?.close()\n\t\t\t\t},\n\t\t\t\ttrack: (event, opts) => trackServerEvent(payload, event, opts),\n\t\t\t\tengine,\n\t\t\t\tepoch,\n\t\t\t\tmemo,\n\t\t\t\tcache: { store, sweeper },\n\t\t\t}\n\t\t},\n\t\tresolved,\n\t\ttrackerConfig: async (payload, req, draft) => {\n\t\t\tconst runtime = getRuntime(payload)\n\t\t\treturn runtime ? resolveTrackerConfig({ runtime, req, draft }) : emptyTrackerConfig(req)\n\t\t},\n\t\tvalidate: async (payload) => {\n\t\t\tcheckAssembled(payload)\n\t\t\t// `next build` boots once per worker and serves nothing; the server that does says these.\n\t\t\tconst warn = collectingPageData()\n\t\t\t\t? () => undefined\n\t\t\t\t: (message: string) => payload.logger?.warn(message)\n\t\t\tfor (const notice of args.notices) {\n\t\t\t\twarn(notice)\n\t\t\t}\n\t\t\tif (!resolved.cache.store) {\n\t\t\t\tawait collectionCacheStore(payload, { slug: resolved.cache.collection.slug }).prepare()\n\t\t\t}\n\t\t\tvalidateScopeFields(payload, resolved)\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await loadEncrypted()\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst moneyOff = revenueOffWarning(resolved)\n\t\t\tif (moneyOff) {\n\t\t\t\twarn(moneyOff)\n\t\t\t}\n\t\t\tconst spoofable = untrustedAddressNotice(resolved, isProductionBuild())\n\t\t\tif (spoofable) {\n\t\t\t\twarn(spoofable)\n\t\t\t}\n\t\t\tconst transactions = sqliteTransactionsNotice(payload)\n\t\t\tif (transactions) {\n\t\t\t\twarn(transactions)\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,sBAAsB;;AAG5B,MAAM,sBAAsB;;AAG5B,MAAM,mBAAmB,YAAyC;CACjE,MAAM,KAAc,QAAQ;CAC5B,IAAI,CAAC,SAAS,EAAE,KAAK,GAAG,SAAS,YAChC;CAED,MAAM,OAAO,GAAG;CAChB,MAAM,UAAU,SAAS,IAAI,KAAK,SAAS,KAAK,OAAO,IAAI,KAAK,UAAU,GAAG;CAC7E,MAAM,MAAM,SAAS,OAAO,IAAI,QAAQ,MAAM,KAAA;CAC9C,OAAO,OAAO,QAAQ,YAAY,OAAO,SAAS,GAAG,KAAK,MAAM,IAAI,MAAM;AAC3E;;AAgBA,MAAM,kBAAkB,aAA4C;CACnE,MAAM,EAAE,SAAS,eAAe,SAAS;CACzC,IAAI,SACH,OAAO;EAAE,MAAM;EAAW;CAAQ;CAEnC,IAAI,CAAC,WAAW,SACf,OAAO,EAAE,MAAM,SAAS;CAEzB,MAAM,gBAAgB,SAAS,SAAS,MAAM,YAAY,QAAQ,OAAO,iBAAiB;CAC1F,OAAO;EACN,MAAM;EACN,MAAM,WAAW;EACjB,YAAY,WAAW;EACvB,OAAO,WAAW;EAClB,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;CAC1C;AACD;;AAGA,MAAM,oBACL,SACA,UACA,QAEA,SAAS,gBAAgB,UACtB,oBAAoB;CACpB;CACA,MAAM,SAAS,gBAAgB;CAC/B,YAAY,SAAS,gBAAgB;CACrC,QAAQ,SAAS;CACjB,QAAQ,SAAS;CACjB,UAAU,SAAS;CACnB;AACD,CAAC,IACA,oBAAoB,SAAS,OAAO,SAAS,YAAY;;;;;AAM7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,OAAO,SAAS,iBAAiB,SAAS,OAAO,IAAI;IAC7D;IACA;IACA;IACA,OAAO;KAAE;KAAO;IAAQ;GACzB;EACD;EACA;EACA,eAAe,OAAO,SAAS,KAAK,UAAU;GAC7C,MAAM,UAAU,WAAW,OAAO;GAClC,OAAO,UAAU,qBAAqB;IAAE;IAAS;IAAK;GAAM,CAAC,IAAI,mBAAmB,GAAG;EACxF;EACA,UAAU,OAAO,YAAY;GAC5B,eAAe,OAAO;GAEtB,MAAM,OAAO,mBAAmB,UACvB,KAAA,KACL,YAAoB,QAAQ,QAAQ,KAAK,OAAO;GACpD,KAAK,MAAM,UAAU,KAAK,SACzB,KAAK,MAAM;GAEZ,IAAI,CAAC,SAAS,MAAM,OACnB,MAAM,qBAAqB,SAAS,EAAE,MAAM,SAAS,MAAM,WAAW,KAAK,CAAC,EAAE,QAAQ;GAEvF,oBAAoB,SAAS,QAAQ;GACrC,IAAI,SAAS,UAAU,WAAW,SAAS;IAC1C,MAAM,EAAE,0BAA0B,MAAM,cAAc;IACtD,MAAM,sBAAsB,SAAS,SAAS,UAAU,WAAW,YAAY,IAAI;GACpF;GACA,MAAM,WAAW,kBAAkB,QAAQ;GAC3C,IAAI,UACH,KAAK,QAAQ;GAEd,MAAM,YAAY,uBAAuB,UAAU,kBAAkB,CAAC;GACtE,IAAI,WACH,KAAK,SAAS;GAEf,MAAM,eAAe,yBAAyB,OAAO;GACrD,IAAI,cACH,KAAK,YAAY;EAEnB;CACD;AACD"}
|
|
@@ -136,6 +136,7 @@ const answerDocument = async (req, runtime) => {
|
|
|
136
136
|
...dimensions.length > 0 ? { dimensions } : {},
|
|
137
137
|
...limit === void 0 ? {} : { limit },
|
|
138
138
|
adapterId: params.get("dataSource") ?? void 0,
|
|
139
|
+
fallbackWhenUnreadable: true,
|
|
139
140
|
now: currentDate(),
|
|
140
141
|
compare: params.get("compare") === "1",
|
|
141
142
|
series: params.get("series") === "1",
|