@10x-media/analytics 1.0.0-beta.16 → 1.0.0-beta.17
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 +46 -0
- package/dist/adapters/ga4/ga4.js +33 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +4 -1
- package/dist/adapters/ga4/measurementId.js.map +1 -1
- package/dist/adapters/ga4/propertyId.js +17 -0
- package/dist/adapters/ga4/propertyId.js.map +1 -0
- package/dist/adapters/http/fetchJson.js +24 -1
- package/dist/adapters/http/fetchJson.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +16 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/plausible/siteId.js +31 -0
- package/dist/adapters/plausible/siteId.js.map +1 -0
- package/dist/adapters/posthog/posthog.js +17 -3
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +34 -7
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/contract.d.ts +16 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +1 -1
- package/dist/core/options.js +1 -1
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +62 -14
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceErrors.js +12 -1
- package/dist/core/sourceErrors.js.map +1 -1
- package/dist/core/sourceOptions.js +1 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +8 -1
- package/dist/core/sourcePolicy.js.map +1 -1
- package/dist/core/throttle.js +3 -1
- package/dist/core/throttle.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -2
- package/dist/exports/adapters/native.d.ts +2 -2
- package/dist/exports/adapters/plausible.d.ts +2 -2
- package/dist/exports/adapters/posthog.d.ts +2 -2
- package/dist/exports/adapters/umami.d.ts +2 -2
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/next.d.ts +2 -2
- package/dist/exports/testing.d.ts +2 -2
- package/dist/exports/types.d.ts +3 -3
- package/dist/fields/config/fetchSources.js +1 -1
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/goals/collection.js +3 -2
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +50 -4
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/nativeAdapter.js +1 -1
- package/dist/plugin/createRuntime.js +57 -13
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/pluginCollections.js +4 -1
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/providerStatusEndpoint.js +80 -0
- package/dist/plugin/providerStatusEndpoint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +4 -3
- package/dist/plugin/readContextForRequest.js +2 -2
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/refreshEndpoint.js +1 -1
- package/dist/plugin/routes.d.ts +5 -0
- package/dist/plugin/routes.js +1 -0
- package/dist/plugin/routes.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/ProviderConnection.d.ts +12 -0
- package/dist/providers/ProviderConnection.js +105 -0
- package/dist/providers/ProviderConnection.js.map +1 -0
- package/dist/providers/ProviderConnectionTest.d.ts +12 -0
- package/dist/providers/ProviderConnectionTest.js +55 -0
- package/dist/providers/ProviderConnectionTest.js.map +1 -0
- package/dist/providers/ProvidersListNotice.d.ts +1 -1
- package/dist/providers/ProvidersListNotice.js +3 -2
- package/dist/providers/ProvidersListNotice.js.map +1 -1
- package/dist/providers/collection.d.ts +1 -1
- package/dist/providers/collection.js +97 -38
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/connectionCheck.d.ts +1 -0
- package/dist/providers/connectionCheck.js +80 -0
- package/dist/providers/connectionCheck.js.map +1 -0
- package/dist/providers/connectionState.js +53 -0
- package/dist/providers/connectionState.js.map +1 -0
- package/dist/providers/factory.d.ts +1 -3
- package/dist/providers/factory.js +18 -21
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +20 -6
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/ids.d.ts +6 -0
- package/dist/providers/ids.js +32 -0
- package/dist/providers/ids.js.map +1 -0
- package/dist/providers/providerStatusClient.js +60 -0
- package/dist/providers/providerStatusClient.js.map +1 -0
- package/dist/providers/registry.js +56 -20
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/retarget.js +39 -8
- package/dist/providers/retarget.js.map +1 -1
- package/dist/providers/secrets.d.ts +1 -1
- package/dist/providers/secrets.js.map +1 -1
- package/dist/providers/status.d.ts +1 -0
- package/dist/providers/status.js +181 -0
- package/dist/providers/status.js.map +1 -0
- package/dist/surfacing/classifyError.js +37 -5
- package/dist/surfacing/classifyError.js.map +1 -1
- package/dist/surfacing/engine.js +2 -2
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/lanes.js +29 -22
- package/dist/surfacing/lanes.js.map +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/testing/settle.d.ts +2 -1
- package/dist/testing/settle.js +6 -2
- package/dist/testing/settle.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/translations/ar.js +40 -8
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +40 -8
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +40 -8
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +40 -8
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +40 -8
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +40 -8
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +32 -0
- package/dist/translations/keys.js +32 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +40 -8
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +40 -8
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +40 -8
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +40 -8
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +40 -8
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +63 -0
- package/dist/ui/components/SourcesNoticeBanner.js +4 -3
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
- package/dist/view/ViewSections.js +9 -2
- package/dist/view/ViewSections.js.map +1 -1
- package/dist/view/sections/EmptyStates.js +5 -4
- package/dist/view/sections/EmptyStates.js.map +1 -1
- package/dist/view/sections/OverviewCards.js +6 -2
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/view/sections/SourceConnectionNote.js +56 -0
- package/dist/view/sections/SourceConnectionNote.js.map +1 -0
- package/dist/view/viewProps.d.ts +2 -0
- package/dist/view/viewProps.js +2 -1
- package/dist/view/viewProps.js.map +1 -1
- package/package.json +1 -1
package/dist/core/options.js
CHANGED
|
@@ -6,12 +6,12 @@ import { flatFieldName, keysOf, optionalBoolean, optionalFunction, optionsObject
|
|
|
6
6
|
import { assertJobsFit, resolveJobs } from "./jobs.js";
|
|
7
7
|
import { resolveCountryFlags, resolveView, resolveWidgets } from "./adminOptions.js";
|
|
8
8
|
import { resolveCache, resolveHooks, resolveSync } from "./cacheOptions.js";
|
|
9
|
-
import { resolveSdks } from "./sdks.js";
|
|
10
9
|
import { assertAdapters, assertNamesAdapter, resolveProviders } from "./sourceOptions.js";
|
|
11
10
|
import { resolveCapture, resolveTrust } from "./captureOptions.js";
|
|
12
11
|
import { resolveGoals, resolveRevenue } from "./goalOptions.js";
|
|
13
12
|
import { assertNoLegacyOptions } from "./legacyOptions.js";
|
|
14
13
|
import { assertScopedOnlyOptions, resolveAccess, resolveScope } from "./scopeOptions.js";
|
|
14
|
+
import { resolveSdks } from "./sdks.js";
|
|
15
15
|
import { resolveSources } from "./sourcePolicy.js";
|
|
16
16
|
//#region src/core/options.ts
|
|
17
17
|
/** The multi-tenant plugin's own relationship field, which a scoped install almost always has. */
|
package/dist/core/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type {\n\tAccess,\n\tCollectionConfig,\n\tCollectionSlug,\n\tField,\n\tPayload,\n\tPayloadRequest,\n\tRawPayloadComponent,\n\tWidget,\n} from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport type { GoalCollectionFieldOverrides } from '../goals/collection'\nimport type { CurrencyConverter } from '../goals/currency'\nimport type { BrowserAmounts, OrderSignatureMode } from '../goals/match'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport { type RouteBase, resolveRouteBase } from '../plugin/routes'\nimport type { ScopeDecision } from '../plugin/runtime'\nimport type {\n\tConnectionAccess,\n\tConnectionFieldAccess,\n\tProviderCollectionFieldOverrides,\n} from '../providers/collection'\nimport type { ProviderId } from '../providers/factory'\nimport type { ProviderHostPolicy } from '../providers/hosts'\nimport type { AfterReadHook } from '../surfacing/afterRead'\nimport type { CacheStore } from '../surfacing/cacheStore'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { isValidTimeZone } from '../timeframe/tz'\nimport type {\n\tCaptureClientKind,\n\tCaptureSlot,\n\tConsentPhase,\n\tResolvedAutoCapture,\n\tTrackerSkip,\n\tWithoutConsentLevel,\n} from '../tracker/config'\nimport type { TranslationsOption } from '../translations'\nimport { keys, pluralKeys } from '../translations/keys'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport { resolveCountryFlags, resolveView, resolveWidgets } from './adminOptions'\nimport { resolveCache, resolveHooks, resolveSync } from './cacheOptions'\nimport { resolveCapture, resolveTrust } from './captureOptions'\nimport type {\n\tAnalyticsCollectionOptions,\n\tCollectionOverrides,\n\tResolvedCollectionOption,\n\tResolvedScopedCollection,\n} from './collectionOption'\nimport type { AnalyticsAdapter, MetricKey } from './contract'\nimport type { FetchLike } from './fetch'\nimport { resolveGoals, resolveRevenue } from './goalOptions'\nimport { type AnalyticsJobsOptions, assertJobsFit, type ResolvedJobs, resolveJobs } from './jobs'\nimport { assertNoLegacyOptions } from './legacyOptions'\nimport {\n\tflatFieldName,\n\tkeysOf,\n\toptionalBoolean,\n\toptionalFunction,\n\toptionsObject,\n} from './optionChecks'\nimport { assertScopedOnlyOptions, resolveAccess, resolveScope } from './scopeOptions'\nimport { type AnalyticsSdks, resolveSdks } from './sdks'\nimport { assertAdapters, assertNamesAdapter, resolveProviders } from './sourceOptions'\nimport {\n\ttype AnalyticsSourceOptions,\n\ttype DefaultSourceRule,\n\ttype ResolvedSources,\n\tresolveSources,\n} from './sourcePolicy'\nimport { isRecord, kindOf, listOf } from './values'\nimport type { BuiltInWidgetSlug } from './widgetSlugs'\n\nexport { DEFAULT_VIEW } from './adminOptions'\nexport {\n\tadapterCountsWithoutConsent,\n\tcookielessTrustNotice,\n\tdocumentsFillHeldTenant,\n\tfillableSlots,\n\tfollowingCountsWithoutConsent,\n\ttrackerAutoCapture,\n\tuntrustedAddressNotice,\n\twithoutConsentUnsetNotice,\n} from './captureOptions'\nexport type { AnalyticsCollectionOptions, CollectionOverrides } from './collectionOption'\nexport { revenueOffWarning } from './goalOptions'\nexport type { AnalyticsJobsOptions, AnalyticsTaskOptions } from './jobs'\nexport { allCrossScope } from './scopeOptions'\nexport type {\n\tAnalyticsSourceOptions,\n\tDefaultSourceFunction,\n\tDefaultSourceRule,\n\tOwnSource,\n\tResolvedSources,\n\tSourcePolicy,\n\tSourcePolicyFunction,\n\tSourceRef,\n} from './sourcePolicy'\nexport type { CurrencyConverter }\n\n/** The multi-tenant plugin's own relationship field, which a scoped install almost always has. */\nexport const DEFAULT_BINDING_SCOPE_FIELD = 'tenant'\n\n/**\n * Who asks for a request's scope: `capture` files a visitor's hit and carries no user or cookies,\n * so it resolves from the host; `admin` is every signed-in read or edit.\n */\nexport type ScopeCallSite = 'capture' | 'admin'\n\n/**\n * Maps a request to the scope it selected (tenant id, site key), null for the whole install;\n * whether its user may act there is `scope.member`. `'*'` is refused.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n\tcallSite: ScopeCallSite\n}) => string | null | Promise<string | null>\n\n/**\n * Lists the tenant scopes the sync task runs over, in addition to the install-wide scope it always\n * covers. Warming needs no list: it repeats the reads each scope's readers made.\n */\nexport type ScopeListResolver = (args: { payload: Payload }) => string[] | Promise<string[]>\n\n/**\n * Names a scope on screen, so a tenant admin reads a name rather than an id in the view's caption.\n * Undefined keeps the id.\n */\nexport type ScopeLabelResolver = (args: {\n\treq: PayloadRequest\n\tscope: string\n}) => string | undefined | Promise<string | undefined>\n\n/** Whether the request's user belongs to `scope`, as opposed to having merely selected it. */\nexport type ScopeMemberAccess = (args: {\n\treq: PayloadRequest\n\tscope: string\n}) => boolean | Promise<boolean>\n\n/** How the install divides its analytics into tenants. Unset, the install is one scope. */\nexport type AnalyticsScopeOptions = {\n\tresolve: ScopeResolver\n\t/**\n\t * Whether the request's user belongs to the scope `resolve` selected, asked on every read and\n\t * config write. `tenantMembership()` reads the multi-tenant plugin's tenants.\n\t */\n\tmember: ScopeMemberAccess\n\tlist?: ScopeListResolver\n\tlabel?: ScopeLabelResolver\n}\n\n/**\n * Resolves a scope's IANA reporting timezone, also asked at ingest without the user or cookies.\n * Null means UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves a scope's ISO 4217 revenue currency, so each tenant can have its own. Undefined reports\n * revenue as a plain number.\n */\nexport type CurrencyResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | undefined | Promise<string | undefined>\n\n/**\n * How the install measures money once `revenue` turns it on. Off hides every money surface but\n * keeps stored data, so turning it on later reports the history.\n */\nexport type AnalyticsRevenueOptions = {\n\t/**\n\t * ISO 4217 currency revenue is reported in, or a resolver per tenant. Unset, amounts are summed\n\t * as sent and a mix of currencies is flagged in `meta.mixedCurrencies`.\n\t */\n\tcurrency?: string | CurrencyResolver\n\t/**\n\t * FX hook native ingest calls when an event's currency differs from `currency`. Without it such\n\t * an amount stays out of revenue, though the conversion still counts.\n\t */\n\tconvert?: CurrencyConverter\n\t/**\n\t * The `currency` breakdown dimension, keyed by the currency each amount was sent in. Default: on\n\t * while no `convert` hook is set.\n\t */\n\tdimension?: boolean\n\t/**\n\t * How far native ingest trusts an amount a browser sends, which anyone can forge. `'fixed'`\n\t * (default) prefers a goal's fixed value, `'none'` ignores it, `'trust'` prefers it.\n\t */\n\tbrowserAmounts?: BrowserAmounts\n\t/**\n\t * Whether native ingest takes an order id sent without the server's `signOrderId` signature.\n\t * `'optional'` (default) takes it; `'required'` answers an unsigned one with `400`.\n\t */\n\torderSignature?: OrderSignatureMode\n}\n\n/** What `providers.resolve` is handed for one scope. */\nexport interface ProvidersResolveArgs {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n\t/**\n\t * The runtime's guarded fetch: every address a vendor's host resolves to has to be public, on\n\t * every connection and every redirect. Hand it to `adapterFromProviderDoc`.\n\t */\n\tfetch: FetchLike\n\t/**\n\t * The hosts a document may name: each vendor's own cloud, plus `providers.hosts`. Hand it to\n\t * `adapterFromProviderDoc` with `fetch`, which reaches a private network only when it allows one.\n\t */\n\thosts: ProviderHostPolicy\n\t/** The plugin's `sdks`, which a GA4 document's adapter reads through. */\n\tsdks: AnalyticsSdks\n}\n\n/**\n * Replaces the providers collection lookup with a scope's adapters, uncached. Build each with\n * `adapterFromProviderDoc(row, { fetch, hosts, sdks })` so a stored key reaches allowed hosts only.\n */\nexport type ProvidersResolve = (\n\targs: ProvidersResolveArgs\n) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\n/**\n * Where provider documents may point. Each vendor's own cloud is always allowed: Plausible, Umami\n * Cloud, and PostHog's US and EU regions.\n */\nexport type ProviderHostsOptions = {\n\t/**\n\t * Origins a document's host may name besides its vendor's cloud, such as `https://*.example.com`;\n\t * no paths. A host outside them reads as `source_misconfigured`.\n\t */\n\tallow?: string[]\n\t/**\n\t * Lets document adapters reach any address over http or https, private networks included (Umami\n\t * on the same Docker network). Default off.\n\t */\n\tallowPrivateNetwork?: boolean\n}\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers. Default `scope`;\n\t * name a tenant plugin's field (`tenant`) when that plugin scopes the collection.\n\t */\n\tscopeField?: string\n\t/**\n\t * Replaces one of the collection's own fields, each handed the plugin's default. Applied before\n\t * `overrides`.\n\t */\n\tfields?: ProviderCollectionFieldOverrides\n\t/**\n\t * Reshapes the whole config last. It may not rename the collection (`slug` does) nor turn off\n\t * its timestamps, which every instance notices a saved document by: the boot refuses both.\n\t */\n\toverrides?: CollectionOverrides\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for stored provider credentials. Unset, the fields plugin's `encrypted.keys`\n\t * applies, else a ring derived from the Payload secret, fit for dev only.\n\t */\n\tencryption?: { keys?: KeysConfig }\n\t/**\n\t * Who may set or change where a document connects (provider, host, ids); a denied value is\n\t * dropped. Default: the creator, then `access.crossScope.named` when scoped, else update access.\n\t */\n\tconnectionAccess?: ConnectionAccess\n\t/**\n\t * Who may set or change a scoped install's \"Default for this site\" checkbox; a denied value is\n\t * dropped. Default: `connectionAccess`, else its default (the creator, then `crossScope.named`).\n\t */\n\tdefaultAccess?: ConnectionAccess\n\t/**\n\t * Which provider types documents may have, the first being the select's default; the select lists\n\t * them in a fixed order. Default: every type, `native` only while `adapters` holds native().\n\t */\n\ttypes?: ProviderId[]\n\t/**\n\t * Which provider documents a reader reads analytics through, as collection access ANDed with\n\t * enabled and scope. Default: the collection's own read access.\n\t */\n\tsourceAccess?: Access\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\t/** Replaces the collection: the two cannot both be set. */\n\tresolve?: ProvidersResolve\n\t/** Where the documents of either one may point. Needs `collection` or `resolve`. */\n\thosts?: ProviderHostsOptions\n}\n\n/** Access checker for authenticated analytics reads. */\nexport type AnalyticsReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for the analytics admin view. */\nexport type AnalyticsViewAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/**\n * Access checker for one of the cross-scope gates under `access.crossScope`, told what is asked\n * where the read knows it: the scope (`'*'` or null for every scope) and, for `unscopedSource`, the adapter.\n */\nexport type CrossScopeAccess = (args: {\n\treq: PayloadRequest\n\tscope?: string | null\n\tadapterId?: string\n}) => boolean | Promise<boolean>\n\n/**\n * The three ways a reader on a scoped install reaches past their own scope, each denied by default.\n * Split so platform staff can aggregate without singling out one tenant.\n */\nexport type AnalyticsCrossScopeOptions = {\n\t/**\n\t * Reading a scope the request does not resolve to, by naming it. Also decides who manages other\n\t * tenants' provider, goal and sync documents.\n\t */\n\tnamed?: CrossScopeAccess\n\t/** Reading every scope at once: the `'*'` marker, and a scoped install's null scope. */\n\taggregate?: CrossScopeAccess\n\t/**\n\t * Reading a tenant through a shared config adapter that cannot narrow its query to one scope.\n\t * Also decides whether such an adapter is listed as a source at all.\n\t */\n\tunscopedSource?: CrossScopeAccess\n}\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates every read: endpoints, dashboard widgets and display fields. Default `isAdminUser` (the\n\t * `admin.user` collection); scope gating applies on top and is never widened by it.\n\t */\n\tread?: AnalyticsReadAccess\n\t/**\n\t * Gates the analytics admin view. Default: `read`. A denied reader still sees the nav link and\n\t * lands on the view's no-access message.\n\t */\n\tview?: AnalyticsViewAccess\n\t/**\n\t * Reads past the request's own scope, scoped installs only: a function grants all three gates,\n\t * the object form each one (unset denies). Unscoped, all three open to `isAdminUser`.\n\t */\n\tcrossScope?: CrossScopeAccess | AnalyticsCrossScopeOptions\n}\n\n/** The three cross-scope gates, each filled. */\nexport type ResolvedCrossScope = Record<ScopeDecision, CrossScopeAccess>\n\n/** What `capture.gate` is asked about one capture slot. */\nexport interface CaptureGateArgs {\n\tslot: CaptureSlot\n\t/** The adapter filling the slot for this request. */\n\tadapterId: string\n\tkind: CaptureClientKind\n}\n\n/**\n * Which capture slots wait for the host's consent manager: `'all'`, `'off'`, a list of slots, or a\n * function answering per slot (true waits).\n */\nexport type CaptureGate = 'all' | 'off' | CaptureSlot[] | ((args: CaptureGateArgs) => boolean)\n\n/** `capture.gate` resolved: whether one slot, filled by one adapter, waits. */\nexport type CaptureGatePolicy = (args: CaptureGateArgs) => boolean\n\n/** What `capture.withoutConsent` is asked about one held slot in one phase. */\nexport interface WithoutConsentArgs extends CaptureGateArgs {\n\tphase: ConsentPhase\n}\n\n/** `capture.withoutConsent` as a function: a throw, or any other answer, means `'off'`. */\nexport type WithoutConsentFunction = (args: WithoutConsentArgs) => WithoutConsentLevel\n\n/**\n * What a slot `capture.gate` holds does before an answer (`pending`) and after a refusal\n * (`refused`): one level for both, one per phase (an omitted phase is `'cookieless'`), or a\n * function answering per slot and phase.\n */\nexport type WithoutConsentOption =\n\t| WithoutConsentLevel\n\t| { pending?: WithoutConsentLevel; refused?: WithoutConsentLevel }\n\t| WithoutConsentFunction\n\n/** `capture.withoutConsent` checked: a level per phase, or the host's function. */\nexport type ResolvedWithoutConsent =\n\t| Record<ConsentPhase, WithoutConsentLevel>\n\t| WithoutConsentFunction\n\n/** An adapter id to fill a capture slot with, or `false` to leave it deliberately empty. */\nexport type CaptureSlotOption = string | false\n\n/** What the tracker and ingest do with elements marked by `itemAttributes`. */\nexport type ItemCaptureOptions = {\n\t/** Count an item as seen once at least half of it stays on screen for a second. */\n\timpressions?: boolean\n\t/** Send `item_click` for the first click on an item during a pageview. */\n\tclicks?: boolean\n\t/** Also count an item per page it appeared on, beside its own total. */\n\tpages?: boolean\n}\n\nexport type AutoCaptureOptions = {\n\tscrollDepth?: boolean\n\toutboundLinks?: boolean\n\tfileDownloads?: boolean\n\tgoalAttribute?: boolean\n\t/**\n\t * Send each pageview's query string so ingest can extract its utm keys. The raw query is\n\t * never stored, only the five campaign values; set false to stop sending it at all.\n\t */\n\tquery?: boolean\n\t/**\n\t * Content items, on by default and inert until a page marks an element with `itemAttributes`.\n\t * `false` turns them off, crediting goals to items included.\n\t */\n\titems?: false | ItemCaptureOptions\n}\n\nexport type AnalyticsGoalsCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's goals. Point it at\n\t * a tenant plugin's field (e.g. 'tenant') when that plugin manages scoping.\n\t */\n\tscopeField?: string\n\t/**\n\t * Replaces one of the collection's own fields, each handed the plugin's default; applied before\n\t * `overrides`. A `slug` replacement must keep a field named `slug` or the boot fails.\n\t */\n\tfields?: GoalCollectionFieldOverrides\n\t/**\n\t * Reshapes the whole config last. It may not rename the collection (`slug` does) nor turn off\n\t * its timestamps, which every instance notices a saved document by: the boot refuses both.\n\t */\n\toverrides?: CollectionOverrides\n\taccess?: Partial<CollectionConfig['access']>\n}\n\n/** Goals as config, plus the opt-in collection editors manage their own goals through. */\nexport type AnalyticsGoalsOptions = {\n\tdefaults?: Goal[]\n\t/** Opt-in admin collection whose goals merge over `defaults`, by slug, per scope. */\n\tcollection?: boolean | AnalyticsGoalsCollectionOptions\n\t/**\n\t * The built-in `purchase` goal sales book against, on unless a configured goal claims that slug.\n\t * `false` removes it, for an install that never sells.\n\t */\n\tpurchase?: boolean\n}\n\n/**\n * The website addresses where the scope's tracker runs, one per site, each an `http(s)` origin with\n * an optional path. May be async; scope is null on an unscoped install.\n */\nexport type ExclusionSitesResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string[] | Promise<string[]>\n\n/** The signed link staff open to leave their own browser out of the numbers. */\nexport type AnalyticsExclusionOptions = {\n\t/**\n\t * The query parameter the tracker reads. Default `analytics_exclude`. Letters, digits, `.`,\n\t * `_`, `~` and `-`, at most 64 of them.\n\t */\n\tparam?: string\n\t/**\n\t * Website addresses where the tracker runs, one per site, for the view to link to: a list, or\n\t * a per-scope function (async allowed). Unset, the view hands out only the query to append.\n\t */\n\tsites?: string[] | ExclusionSitesResolver\n}\n\nexport type AnalyticsCaptureOptions = {\n\t/**\n\t * Which capture slots wait for the host's consent manager. Required whenever a slot can fill:\n\t * whether tracking needs consent is the operator's call, so there is no default.\n\t */\n\tgate?: CaptureGate\n\t/**\n\t * What a slot `gate` holds does before an answer and after a refusal. Default `'cookieless'`:\n\t * count without storing anything on the device, at the level each adapter declares (GA4's is\n\t * `'off'`). `'off'` sends nothing until consent and nothing after a refusal. An adapter's own\n\t * `withoutConsent` beats this for its slot; a slot the gate does not hold runs in full.\n\t */\n\twithoutConsent?: WithoutConsentOption\n\t/**\n\t * Exact origins of other sites (`https://shop.example.com`, no path or wildcard) whose pages may\n\t * send to ingest and the capture proxy. Unset, only the site and its subdomains can.\n\t */\n\tallowedOrigins?: string[]\n\t/**\n\t * The signed link staff open to leave their browser out of the numbers. Off by default; `true`\n\t * turns it on as `analytics_exclude`, an object renames it through `param`.\n\t */\n\texclusion?: boolean | AnalyticsExclusionOptions\n\t/**\n\t * Which adapter fills each slot (`global`: `platformAdapter` or the only adapter; `tenant`: the\n\t * scope's default). `false` leaves a slot empty: no proxy mount, no tracker entry.\n\t */\n\tslots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * Mount each slot's snippet points at. Default: the runtime proxy endpoint; set it to a\n\t * `captureRoute` handler's path, without the Next `basePath`, which the tracker config adds.\n\t */\n\tpaths?: { global?: string; tenant?: string }\n\t/** Browser auto-capture listeners, all on by default except `scrollDepth`. */\n\tautoCapture?: AutoCaptureOptions\n\t/**\n\t * Pages the tracker leaves uncounted, each on unless false: `automation` (`navigator.webdriver`;\n\t * turn it off for e2e suites asserting on hits) and `previews` (draft mode, live preview).\n\t */\n\tskip?: { automation?: boolean; previews?: boolean }\n\t/** Limits for the public runtime capture proxy, separate from the read-path `cache`. */\n\tproxy?: {\n\t\t/**\n\t\t * Deadline for the upstream response headers, in ms. Default 10000. The body\n\t\t * download is not on the clock, so a large tracker bundle streams to completion.\n\t\t */\n\t\ttimeoutMs?: number\n\t\t/**\n\t\t * Largest proxied request body, in bytes. Default 1 MiB, which clears a PostHog\n\t\t * batch carrying session-replay data. Anything larger is refused with 413.\n\t\t */\n\t\tmaxBodyBytes?: number\n\t}\n}\n\nexport type AnalyticsViewOptions = {\n\t/** Admin path the view mounts at, under `routes.admin`. Default `/analytics`. */\n\tpath?: `/${string}`\n\t/** Timeframe the view opens on before the URL says otherwise. Default `last30days`. */\n\tdefaultRange?: TimeframePreset\n\t/** Metric the cards and the trend open on. Default `pageviews`. */\n\tdefaultMetric?: MetricKey\n\t/**\n\t * Nav link label. A string is used as-is; a map is keyed by admin language code and\n\t * falls back to `en`. Unset, the plugin's own translated label applies.\n\t */\n\tnavLabel?: string | Record<string, string>\n\t/**\n\t * Whether the view adds its link to the admin sidebar. Default true; false mounts the view\n\t * without one, for a host that links it from its own navigation.\n\t */\n\tnavLink?: boolean\n\t/**\n\t * A client component replacing the view's body under the same server shell, given\n\t * `AnalyticsViewClientProps`; compose it from the sections `@10x-media/analytics/client` exports.\n\t *\n\t * @beta\n\t */\n\tComponent?: AnalyticsComponent\n}\n\nexport interface ResolvedView {\n\tpath: `/${string}`\n\tdefaultRange: TimeframePreset\n\tdefaultMetric: MetricKey\n\tnavLabel?: string | Record<string, string>\n\tnavLink: boolean\n\tComponent?: AnalyticsComponent\n}\n\n/**\n * A component a host puts in one of the plugin's places, as Payload takes one: an import-map path\n * such as `'/components/Flag#Flag'`, or the object form with its export and props.\n *\n * @beta\n */\nexport type AnalyticsComponent = string | RawPayloadComponent\n\n/**\n * How a host changes one built-in dashboard widget.\n *\n * @beta\n */\nexport interface AnalyticsWidgetOverride {\n\t/**\n\t * Rendered in place of the plugin's own component. A server component receives the full widget\n\t * props, a client component its `clientProps` alone.\n\t */\n\tComponent?: AnalyticsComponent\n\t/** The widget's name in the dashboard's widget list. */\n\tlabel?: Widget['label']\n\t/**\n\t * The widget's settings, given the plugin's own fields as `defaultFields`, the shape Payload's\n\t * form builder and search plugins take; what it returns is the form.\n\t */\n\tfields?: (args: { defaultFields: Field[] }) => Field[]\n}\n\n/** @beta */\nexport type AnalyticsWidgetOverrides = Partial<Record<BuiltInWidgetSlug, AnalyticsWidgetOverride>>\n\n/** @beta */\nexport interface AnalyticsWidgetsOptions {\n\tdisabled?: string[]\n\tregister?: CustomWidgetDef[]\n\t/**\n\t * Marks each widget's free-text Title field `localized`. Default off; takes effect only when the\n\t * Payload config enables localization.\n\t */\n\tlocalizeText?: boolean\n\t/**\n\t * Period-over-period comparison on the metric and trend widgets. Default on, except for a source\n\t * whose adapter sets `capabilities.comparison` false; `false` skips the second read.\n\t */\n\tcomparison?: boolean\n\t/** Built-in widgets changed by slug: their component, their name, their settings. */\n\toverrides?: AnalyticsWidgetOverrides\n}\n\n/**\n * `countryFlags` with a flag of the host's own.\n *\n * @beta\n */\nexport interface AnalyticsCountryFlags {\n\t/**\n\t * A client component drawing one flag from `{ code }`, an ISO 3166-1 alpha-2 code in capitals.\n\t * Registered through `admin.dependencies`, so `payload generate:importmap` picks it up.\n\t */\n\tComponent: AnalyticsComponent\n}\n\n/** The collection the sync job persists daily metrics into: `slug` defaults to `analytics-daily`. */\nexport type AnalyticsSyncCollectionOptions = AnalyticsCollectionOptions & {\n\t/** Keeps the collection out of the admin nav. Default true. */\n\thidden?: boolean\n}\n\n/** The read cache's collection: `slug` defaults to `analytics-cache`. */\nexport type AnalyticsCacheCollectionOptions = AnalyticsCollectionOptions\n\n/** What `analytics-sync` copies; when it runs is `jobs.tasks.sync`. */\nexport type AnalyticsSyncOptions = {\n\t/** Days each run reads back, today counted. Default 3. */\n\tlookbackDays?: number\n\t/**\n\t * The sources it copies: a config adapter's id, or a provider type for every source built from\n\t * provider documents of that type. Default every vendor source.\n\t */\n\tadapters?: string[]\n\tcollection?: AnalyticsSyncCollectionOptions\n}\n\n/** How much reads may ask of their sources at once (`cache.concurrency`). */\nexport type AnalyticsConcurrencyOptions = {\n\t/** Requests in flight across every vendor source of one instance. Default 16. */\n\tglobal?: number\n\t/** Requests in flight per vendor source that declares no `rateLimit.maxConcurrent`. Default 4. */\n\tperSource?: number\n\t/** Reads with nothing cached one scope may have waiting on its sources. Default 8. */\n\tperScope?: number\n}\n\n/** How reads are cached, how long they wait for their sources, and which are kept warm. */\nexport type AnalyticsCacheOptions = {\n\t/**\n\t * Seconds an answer stays fresh; unset, each adapter's `recommendedTtl` applies. A native read\n\t * whose window reaches into today stays fresh 10 seconds at most whatever this says.\n\t */\n\tttl?: { aggregate?: number; realtime?: number }\n\t/**\n\t * Keeps recently asked reads warm: `analytics-warm` rereads each shortly before its cached answer\n\t * expires. Default off; `true` uses the defaults. Scheduled by `jobs.tasks.warm`.\n\t */\n\twarm?: boolean | AnalyticsWarmOptions\n\t/**\n\t * How long a read waits for its source, in ms, retries included. Default 15000. Only a read with\n\t * nothing cached (and sync) waits; others answer an expired entry at once.\n\t */\n\ttimeoutMs?: number\n\t/**\n\t * How much reads may ask of their sources at once; past `perScope` the query endpoint answers\n\t * 429. Native reads have a lane of their own outside these: 8, or on Postgres a third of\n\t * `pool.max`, between 1 and 8.\n\t */\n\tconcurrency?: AnalyticsConcurrencyOptions\n\t/**\n\t * Where reads are cached across requests and instances. Default: the `analytics-cache`\n\t * collection; a self-expiring store (Redis) replaces it. Live counts stay in memory.\n\t */\n\tstore?: CacheStore\n\t/** The `analytics-cache` collection of the default store; refused beside `store`. */\n\tcollection?: AnalyticsCacheCollectionOptions\n}\n\n/** Hooks into what the plugin does. */\nexport type AnalyticsHooksOptions = {\n\t/**\n\t * Runs once for every read answered to a reader, after it is cached, to observe it or answer\n\t * that one read differently. See {@link AfterReadHook} for the contract.\n\t */\n\tafterRead?: AfterReadHook\n}\n\n/** Which reads `analytics-warm` keeps warm; when it runs is `jobs.tasks.warm`. */\nexport type AnalyticsWarmOptions = {\n\t/** Reads asked for in this many hours count as recent. Default 24. */\n\twindowHours?: number\n\t/** The most reads one run refreshes, most recently read first. Default 200. */\n\tmaxReads?: number\n}\n\n/** Where the plugin's endpoints answer. */\nexport type AnalyticsRoutesOptions = {\n\t/**\n\t * The path every plugin endpoint hangs off, under `routes.api`. Default `/_x`; the boot fails\n\t * when a collection slug is its first segment, which would swallow those requests.\n\t */\n\tbase?: RouteBase\n}\n\nexport type AnalyticsPluginOptions = {\n\t/**\n\t * Switches the plugin off but keeps its schema (collections, fields, indexes, task slugs), so\n\t * nothing is dropped. No endpoint, view, widget or task work runs; options are still checked.\n\t */\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for the plugin's UI strings, keyed by `@10x-media/analytics/i18n` keys.\n\t * They win per key over built-ins; app `i18n.translations` wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics). Reading a tenant\n\t * through it needs `access.crossScope.unscopedSource` unless it supports scoped queries.\n\t */\n\tplatformAdapter?: string\n\t/** Tenancy: how a request maps to its scope. Unset, the whole install is one scope. */\n\tscope?: AnalyticsScopeOptions\n\t/**\n\t * Per shared config adapter, keyed by its id: which tenant users besides platform staff\n\t * (`access.crossScope.unscopedSource`) read their own tenant through it. Scoped installs only.\n\t */\n\tsources?: Record<string, AnalyticsSourceOptions>\n\t/**\n\t * A tenant scope's default source when none of its provider documents is flagged the default.\n\t * Unset keeps the registry's own order. Scoped installs only.\n\t */\n\tdefaultSource?: DefaultSourceRule\n\t/**\n\t * IANA timezone days are cut in. Default UTC; a resolver answers per scope. After a change,\n\t * native recounts in the new zone only days whose raw hits it still keeps.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\t/**\n\t * Money as a capability. `false` or unset measures none; `true` measures it with the\n\t * defaults; an object turns it on and says in which currency, and how.\n\t */\n\trevenue?: boolean | AnalyticsRevenueOptions\n\t/**\n\t * How many proxies to trust, counted from the right of `x-forwarded-for`, when reading a client\n\t * address. Unset keeps the leftmost entry, which the client controls. Not with `trustedPlatform`.\n\t */\n\ttrustedProxyHops?: number\n\t/**\n\t * Platform (`'vercel'` or `'cloudflare'`) whose edge headers carry the visitor's address and\n\t * location. Set it only when every request passes through it, or the headers can be forged.\n\t */\n\ttrustedPlatform?: TrustedPlatform\n\taccess?: AnalyticsAccessOptions\n\tcapture?: AnalyticsCaptureOptions\n\t/**\n\t * Conversion goals the tracker and native ingest match events against: a list, or `{ defaults,\n\t * collection, purchase }`. A goal's name never reaches the browser.\n\t */\n\tgoals?: Goal[] | AnalyticsGoalsOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tproviders?: ProvidersOptions\n\t/**\n\t * The analytics admin view and its nav link, on by default. `false` registers neither;\n\t * the read endpoints stay mounted either way, so a custom surface keeps working.\n\t */\n\tview?: false | AnalyticsViewOptions\n\t/**\n\t * Dashboard widgets, on by default. Payload's dashboard is experimental, so this option is too.\n\t *\n\t * @beta\n\t */\n\twidgets?: boolean | AnalyticsWidgetsOptions\n\t/**\n\t * Flag beside country names in the view, widgets and document panel. Default on, served by the\n\t * plugin's cached route; `false` shows none, `{ Component }` draws the host's own.\n\t *\n\t * @beta\n\t */\n\tcountryFlags?: boolean | AnalyticsCountryFlags\n\tcache?: AnalyticsCacheOptions\n\t/**\n\t * Opt-in sync tier: `analytics-sync` copies each vendor source's daily metrics into a queryable\n\t * collection, every six hours unless `jobs.tasks.sync` says otherwise.\n\t */\n\tsync?: boolean | AnalyticsSyncOptions\n\troutes?: AnalyticsRoutesOptions\n\t/**\n\t * The plugin's tasks (maintain, sync, warm) on `jobs.queue`, scheduled by `jobs.tasks`. `false`\n\t * registers none: reads and ingest then do native upkeep, and sync or warming is refused.\n\t */\n\tjobs?: false | AnalyticsJobsOptions\n\t/**\n\t * Optional packages handed in, which a standalone or serverless build then ships: GA4's\n\t * `{ BetaAnalyticsDataClient }` and MaxMind's `{ open }`. A production boot warns about one missing.\n\t */\n\tsdks?: AnalyticsSdks\n\thooks?: AnalyticsHooksOptions\n}\n\n/** `capture.exclusion` while the link is on. */\nexport interface ResolvedExclusion {\n\tparam: string\n\t/** `sites`, a list made a function answering it; absent when the install names none. */\n\tsites?: ExclusionSitesResolver\n}\n\nexport interface ResolvedCapture {\n\tslots: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\tpaths: { global?: string; tenant?: string }\n\tgate: CaptureGatePolicy\n\t/** Absent while the install leaves it unset, which means `'cookieless'` in both phases. */\n\twithoutConsent?: ResolvedWithoutConsent\n\t/** Slots the gate may hold, judged without calling host code: a function may hold either. */\n\theldSlots: ReadonlySet<CaptureSlot>\n\t/** Whether some held slot of the install may count without consent, as far as the boot can tell. */\n\tinstallCountsWithoutConsent: boolean\n\tautoCapture: ResolvedAutoCapture\n\tproxy: { timeoutMs: number; maxBodyBytes: number }\n\t/** `allowedOrigins`, each as a browser writes it in `Origin`. */\n\tallowedOrigins: ReadonlySet<string>\n\t/** The exclusion link's parameter and site addresses, or false while the link is off. */\n\texclusion: false | ResolvedExclusion\n\tskip: TrackerSkip\n}\n\nexport interface ResolvedRevenue {\n\t/** Whether the install measures money at all. Every money surface reads this one answer. */\n\tenabled: boolean\n\t/** Raw currency option; the plugin normalizes it into a resolver. */\n\tcurrency?: string | CurrencyResolver\n\tconvert?: CurrencyConverter\n\t/** Whether native declares the `currency` dimension; always false while money is off. */\n\tdimension: boolean\n\tbrowserAmounts: BrowserAmounts\n\torderSignature: OrderSignatureMode\n}\n\nexport interface ResolvedScope {\n\t/** The host's resolver with `'*'` refused; resolves null for every request when unscoped. */\n\tresolve: ScopeResolver\n\tlist?: ScopeListResolver\n\tlabel?: ScopeLabelResolver\n\t/** Present exactly when the install is scoped. */\n\tmember?: ScopeMemberAccess\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscope: ResolvedScope\n\t/** True when the app configured `scope.resolve` (scoped install). */\n\tscoped: boolean\n\t/** Raw `reportingTimezone`, a string already validated; the runtime makes it a resolver. */\n\treportingTimezone?: string | TimezoneResolver\n\trevenue: ResolvedRevenue\n\tplatformAdapter?: string\n\t/** `sources` and `defaultSource`; no policies and no rule on an unscoped install. */\n\tsources: ResolvedSources\n\t/** Raw trustedProxyHops option; undefined keeps the leftmost forwarded-for entry. */\n\ttrustedProxyHops?: number\n\t/** The platform whose edge headers are believed; undefined believes none. */\n\ttrustedPlatform?: TrustedPlatform\n\taccess: {\n\t\tread: AnalyticsReadAccess\n\t\tview: AnalyticsViewAccess\n\t\tcrossScope: ResolvedCrossScope\n\t}\n\t/** The admin view, filled with its defaults, or false when the app turned it off. */\n\tview: false | ResolvedView\n\t/** `true` the plugin's own flags, `false` none, or the host's component. */\n\tcountryFlags: boolean | AnalyticsCountryFlags\n\tcapture: ResolvedCapture\n\t/** Config goals, validated; the goals collection layers its own on top of these. */\n\tgoals: Goal[]\n\t/** `goals.purchase`: whether the resolver adds the built-in `purchase` goal. */\n\tpurchaseGoal: boolean\n\tgoalsCollection: ResolvedScopedCollection<GoalCollectionFieldOverrides>\n\tproviders: {\n\t\tcollection: ResolvedScopedCollection<ProviderCollectionFieldOverrides> & {\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t\tconnectionAccess?: ConnectionFieldAccess\n\t\t\tdefaultAccess?: ConnectionFieldAccess\n\t\t\t/** The types the install serves, `types` applied; filled whether the collection is on or not. */\n\t\t\ttypes: readonly ProviderId[]\n\t\t\tsourceAccess?: Access\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t\t/** `providers.hosts`, for the collection's documents and the rows `resolve` reads alike. */\n\t\thosts: ProviderHostPolicy\n\t}\n\t/** Each binding with its `scopeField` filled. */\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; windowHours: number; maxReads: number }\n\t\ttimeoutMs: number\n\t\tconcurrency: { global: number; perSource: number; perScope: number }\n\t\t/** The host's store; absent, the `analytics-cache` collection is the store. */\n\t\tstore?: CacheStore\n\t\t/** The default store's collection, used only while `store` is absent. */\n\t\tcollection: ResolvedCollectionOption\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t\toverrides: AnalyticsWidgetOverrides\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\tcollection: ResolvedCollectionOption & {\n\t\t\thidden: boolean\n\t\t}\n\t}\n\troutes: { base: RouteBase }\n\tjobs: ResolvedJobs\n\tsdks: AnalyticsSdks\n\thooks: { afterRead?: AfterReadHook }\n}\n\nconst PLUGIN_KEYS = keysOf<AnalyticsPluginOptions>({\n\tdisabled: true,\n\ttranslations: true,\n\tadapters: true,\n\tdefaultAdapter: true,\n\tplatformAdapter: true,\n\tscope: true,\n\tsources: true,\n\tdefaultSource: true,\n\treportingTimezone: true,\n\trevenue: true,\n\ttrustedProxyHops: true,\n\ttrustedPlatform: true,\n\taccess: true,\n\tcapture: true,\n\tgoals: true,\n\tcollections: true,\n\tproviders: true,\n\tview: true,\n\twidgets: true,\n\tcountryFlags: true,\n\tcache: true,\n\tsync: true,\n\troutes: true,\n\tjobs: true,\n\tsdks: true,\n\thooks: true,\n})\nconst ROUTES_KEYS = keysOf<AnalyticsRoutesOptions>({ base: true })\nconst BINDING_KEYS = keysOf<AnalyticsBinding>({\n\tpath: true,\n\tpathField: true,\n\thostname: true,\n\titem: true,\n\tscopeField: true,\n})\n\n/** Every key the plugin's own translations override, singular and plural forms alike. */\nconst TRANSLATION_KEYS: ReadonlySet<string> = new Set<string>([\n\t...Object.values(keys),\n\t...Object.values(pluralKeys).flatMap((forms) => Object.values(forms)),\n])\n\n/** `translations`: per language, strings keyed by the plugin's own translation keys. */\nconst assertTranslations = (option: unknown): void => {\n\tif (option === undefined) {\n\t\treturn\n\t}\n\tif (!isRecord(option) || Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: translations must be an object keyed by language, such as { de: { 'analytics:viewTitle': 'Statistik' } }, got ${kindOf(option)}`\n\t\t)\n\t}\n\tfor (const [language, strings] of Object.entries(option)) {\n\t\tif (!isRecord(strings) || Array.isArray(strings)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: translations.${language} must be an object of strings keyed by translation key, got ${kindOf(strings)}`\n\t\t\t)\n\t\t}\n\t\tfor (const [key, text] of Object.entries(strings)) {\n\t\t\tif (!TRANSLATION_KEYS.has(key)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`analytics: translations.${language}[\"${key}\"] is not one of the plugin's translation keys, which @10x-media/analytics/i18n exports as keys`\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (text !== undefined && typeof text !== 'string') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`analytics: translations.${language}[\"${key}\"] must be a string, got ${kindOf(text)}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** `reportingTimezone`: an IANA name checked at boot, or a resolver answering per scope. */\nconst assertTimezone = (option: unknown): void => {\n\tif (option !== undefined && typeof option !== 'string' && typeof option !== 'function') {\n\t\tthrow new Error(\n\t\t\t`analytics: reportingTimezone must be an IANA timezone or a function, got ${kindOf(option)}`\n\t\t)\n\t}\n\tif (typeof option === 'string' && !isValidTimeZone(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: reportingTimezone \"${option}\" is not an IANA timezone name, such as \"Europe/Berlin\"`\n\t\t)\n\t}\n}\n\n/** One `collections` entry: how a bound document's page is found, and whether it is an item. */\nconst assertBinding = (binding: unknown, slug: string): void => {\n\tconst at = `collections.${slug}`\n\tconst shaped = optionsObject(binding, {\n\t\tpath: at,\n\t\tknown: BINDING_KEYS,\n\t\texample: \"an object such as { pathField: 'slug' }\",\n\t})\n\toptionalFunction(shaped.path, `${at}.path`)\n\tif (\n\t\tshaped.pathField !== undefined &&\n\t\t(typeof shaped.pathField !== 'string' || shaped.pathField.trim() === '')\n\t) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${at}.pathField must be a field name, got ${kindOf(shaped.pathField)}`\n\t\t)\n\t}\n\tif (\n\t\tshaped.hostname !== undefined &&\n\t\ttypeof shaped.hostname !== 'string' &&\n\t\ttypeof shaped.hostname !== 'function'\n\t) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${at}.hostname must be a hostname or a function answering one, got ${kindOf(shaped.hostname)}`\n\t\t)\n\t}\n\toptionalBoolean(shaped.item, `${at}.item`)\n\tif (!shaped.path && !shaped.pathField && shaped.item !== true) {\n\t\tthrow new Error(\n\t\t\t`analytics: binding for \"${slug}\" needs a path resolver, a pathField, or item: true`\n\t\t)\n\t}\n\tif (shaped.item === true && slug.includes(':')) {\n\t\tthrow new Error(\n\t\t\t`analytics: collection \"${slug}\" cannot be bound as an item: a ref is \"<collection>:<id>\", so the slug cannot hold a colon`\n\t\t)\n\t}\n}\n\n/**\n * Each binding with its scope field filled: `'tenant'` when scoped, else `false` (the request's own\n * scope). Whether that field exists is checked at init, after every plugin adds fields.\n */\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections'],\n\tscoped: boolean\n): Record<string, ResolvedBinding> => {\n\tconst keyed: unknown = collections\n\tif (keyed !== undefined && (!isRecord(keyed) || Array.isArray(keyed))) {\n\t\tthrow new Error(\n\t\t\t`analytics: collections must be an object keyed by collection slug, such as { pages: { pathField: 'slug' } }, got ${kindOf(keyed)}`\n\t\t)\n\t}\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tassertBinding(binding, slug)\n\t\tconst declared = binding.scopeField ?? (scoped ? DEFAULT_BINDING_SCOPE_FIELD : false)\n\t\tconst scopeField =\n\t\t\tdeclared === false\n\t\t\t\t? false\n\t\t\t\t: flatFieldName(declared, {\n\t\t\t\t\t\tpath: `collections.${slug}.scopeField`,\n\t\t\t\t\t\treason: \"a document's scope is read from one of its own top-level fields\",\n\t\t\t\t\t})\n\t\t// Erases the per-slug document generic: the runtime only hands a binding its own documents.\n\t\tout[slug] = { ...(binding as AnalyticsBinding), scopeField }\n\t}\n\treturn out\n}\n\nconst resolveRoutes = (option: AnalyticsPluginOptions['routes']): ResolvedOptions['routes'] => {\n\tif (option !== undefined) {\n\t\toptionsObject(option, {\n\t\t\tpath: 'routes',\n\t\t\tknown: ROUTES_KEYS,\n\t\t\texample: \"an object such as { base: '/_x' }\",\n\t\t})\n\t}\n\treturn { base: resolveRouteBase(option?.base) }\n}\n\n/** `adapters`, and the options naming one of them by id. */\nconst assertAdapterOptions = (options: AnalyticsPluginOptions, requireAdapters: boolean): void => {\n\tassertAdapters(options.adapters)\n\tconst adapters = options.adapters ?? []\n\tif (requireAdapters && adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (adapters.length > 0) {\n\t\tassertNamesAdapter(options.defaultAdapter, 'defaultAdapter', adapters)\n\t}\n\tassertNamesAdapter(options.platformAdapter, 'platformAdapter', adapters)\n}\n\n/**\n * The options checked and filled. `requireAdapters: false` is the switched-off plugin's, which\n * reads through no adapter and only asks each for its schema.\n */\nexport function resolveOptions(\n\toptions: AnalyticsPluginOptions,\n\tsettings: { requireAdapters?: boolean } = {}\n): ResolvedOptions {\n\tassertNoLegacyOptions(options)\n\tfor (const key of Object.keys(options)) {\n\t\tif (!PLUGIN_KEYS.includes(key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${key} is not an option; analytics() takes ${listOf(PLUGIN_KEYS)}`\n\t\t\t)\n\t\t}\n\t}\n\toptionalBoolean(options.disabled, 'disabled')\n\tassertTranslations(options.translations)\n\tassertAdapterOptions(options, settings.requireAdapters !== false)\n\tconst scope = resolveScope(options.scope)\n\tconst scoped = options.scope?.resolve !== undefined\n\tif (!scoped) {\n\t\tassertScopedOnlyOptions(options)\n\t}\n\tconst capture = resolveCapture(options, scoped)\n\tconst access = resolveAccess(options.access, scoped)\n\tconst trust = resolveTrust(options)\n\tassertTimezone(options.reportingTimezone)\n\tconst countryFlags = resolveCountryFlags(options.countryFlags)\n\tconst cache = resolveCache(options.cache)\n\tconst sync = resolveSync(options.sync)\n\tconst jobs = resolveJobs(options.jobs)\n\tassertJobsFit(jobs, { sync: sync.enabled, warm: cache.warm.enabled })\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscope,\n\t\tscoped,\n\t\treportingTimezone: options.reportingTimezone,\n\t\trevenue: resolveRevenue(options.revenue),\n\t\tplatformAdapter: options.platformAdapter,\n\t\tsources: resolveSources(options),\n\t\t...trust,\n\t\taccess,\n\t\tview: resolveView(options.view),\n\t\tcountryFlags,\n\t\tcapture,\n\t\t...resolveGoals(options.goals),\n\t\tproviders: resolveProviders(options.providers, options.adapters),\n\t\tbindings: resolveBindings(options.collections, scoped),\n\t\tcache,\n\t\twidgets: resolveWidgets(options.widgets),\n\t\tsync,\n\t\troutes: resolveRoutes(options.routes),\n\t\tjobs,\n\t\tsdks: resolveSdks(options.sdks),\n\t\thooks: resolveHooks(options.hooks),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsGA,MAAa,8BAA8B;AA+0B3C,MAAM,cAAc,OAA+B;CAClD,UAAU;CACV,cAAc;CACd,UAAU;CACV,gBAAgB;CAChB,iBAAiB;CACjB,OAAO;CACP,SAAS;CACT,eAAe;CACf,mBAAmB;CACnB,S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Q,YAAY;CAC7D,MAAM,QAAQ,aAAa,QAAQ,KAAK;CACxC,MAAM,OAAO,YAAY,QAAQ,IAAI;CACrC,MAAM,OAAO,YAAY,QAAQ,IAAI;CACrC,cAAc,MAAM;EAAE,MAAM,KAAK;EAAS,MAAM,MAAM,KAAK;CAAQ,CAAC;CACpE,OAAO;EACN,UAAU,QAAQ;EAClB,gBAAgB,QAAQ;EACxB;EACA;EACA,mBAAmB,QAAQ;EAC3B,SAAS,eAAe,QAAQ,OAAO;EACvC,iBAAiB,QAAQ;EACzB,SAAS,eAAe,OAAO;EAC/B,GAAG;EACH;EACA,MAAM,YAAY,QAAQ,IAAI;EAC9B;EACA;EACA,GAAG,aAAa,QAAQ,KAAK;EAC7B,WAAW,iBAAiB,QAAQ,WAAW,QAAQ,QAAQ;EAC/D,UAAU,gBAAgB,QAAQ,aAAa,MAAM;EACrD;EACA,SAAS,eAAe,QAAQ,OAAO;EACvC;EACA,QAAQ,cAAc,QAAQ,MAAM;EACpC;EACA,MAAM,YAAY,QAAQ,IAAI;EAC9B,OAAO,aAAa,QAAQ,KAAK;CAClC;AACD"}
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type {\n\tAccess,\n\tCollectionConfig,\n\tCollectionSlug,\n\tField,\n\tPayload,\n\tPayloadRequest,\n\tRawPayloadComponent,\n\tWidget,\n} from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport type { GoalCollectionFieldOverrides } from '../goals/collection'\nimport type { CurrencyConverter } from '../goals/currency'\nimport type { BrowserAmounts, OrderSignatureMode } from '../goals/match'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport { type RouteBase, resolveRouteBase } from '../plugin/routes'\nimport type { ScopeDecision } from '../plugin/runtime'\nimport type {\n\tConnectionAccess,\n\tConnectionFieldAccess,\n\tProviderCollectionFieldOverrides,\n} from '../providers/collection'\nimport type { ProviderHostPolicy } from '../providers/hosts'\nimport type { ProviderId } from '../providers/ids'\nimport type { AfterReadHook } from '../surfacing/afterRead'\nimport type { CacheStore } from '../surfacing/cacheStore'\nimport type { TimeframePreset } from '../timeframe/presets'\nimport { isValidTimeZone } from '../timeframe/tz'\nimport type {\n\tCaptureClientKind,\n\tCaptureSlot,\n\tConsentPhase,\n\tResolvedAutoCapture,\n\tTrackerSkip,\n\tWithoutConsentLevel,\n} from '../tracker/config'\nimport type { TranslationsOption } from '../translations'\nimport { keys, pluralKeys } from '../translations/keys'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport { resolveCountryFlags, resolveView, resolveWidgets } from './adminOptions'\nimport { resolveCache, resolveHooks, resolveSync } from './cacheOptions'\nimport { resolveCapture, resolveTrust } from './captureOptions'\nimport type {\n\tAnalyticsCollectionOptions,\n\tCollectionOverrides,\n\tResolvedCollectionOption,\n\tResolvedScopedCollection,\n} from './collectionOption'\nimport type { AnalyticsAdapter, MetricKey } from './contract'\nimport type { FetchLike } from './fetch'\nimport { resolveGoals, resolveRevenue } from './goalOptions'\nimport { type AnalyticsJobsOptions, assertJobsFit, type ResolvedJobs, resolveJobs } from './jobs'\nimport { assertNoLegacyOptions } from './legacyOptions'\nimport {\n\tflatFieldName,\n\tkeysOf,\n\toptionalBoolean,\n\toptionalFunction,\n\toptionsObject,\n} from './optionChecks'\nimport { assertScopedOnlyOptions, resolveAccess, resolveScope } from './scopeOptions'\nimport { type AnalyticsSdks, resolveSdks } from './sdks'\nimport { assertAdapters, assertNamesAdapter, resolveProviders } from './sourceOptions'\nimport {\n\ttype AnalyticsSourceOptions,\n\ttype DefaultSourceRule,\n\ttype ResolvedSources,\n\tresolveSources,\n} from './sourcePolicy'\nimport { isRecord, kindOf, listOf } from './values'\nimport type { BuiltInWidgetSlug } from './widgetSlugs'\n\nexport { DEFAULT_VIEW } from './adminOptions'\nexport {\n\tadapterCountsWithoutConsent,\n\tcookielessTrustNotice,\n\tdocumentsFillHeldTenant,\n\tfillableSlots,\n\tfollowingCountsWithoutConsent,\n\ttrackerAutoCapture,\n\tuntrustedAddressNotice,\n\twithoutConsentUnsetNotice,\n} from './captureOptions'\nexport type { AnalyticsCollectionOptions, CollectionOverrides } from './collectionOption'\nexport { revenueOffWarning } from './goalOptions'\nexport type { AnalyticsJobsOptions, AnalyticsTaskOptions } from './jobs'\nexport { allCrossScope } from './scopeOptions'\nexport type {\n\tAnalyticsSourceOptions,\n\tDefaultSourceFunction,\n\tDefaultSourceRule,\n\tOwnSource,\n\tResolvedSources,\n\tSourcePolicy,\n\tSourcePolicyFunction,\n\tSourceRef,\n} from './sourcePolicy'\nexport type { CurrencyConverter }\n\n/** The multi-tenant plugin's own relationship field, which a scoped install almost always has. */\nexport const DEFAULT_BINDING_SCOPE_FIELD = 'tenant'\n\n/**\n * Who asks for a request's scope: `capture` files a visitor's hit and carries no user or cookies,\n * so it resolves from the host; `admin` is every signed-in read or edit.\n */\nexport type ScopeCallSite = 'capture' | 'admin'\n\n/**\n * Maps a request to the scope it selected (tenant id, site key), null for the whole install;\n * whether its user may act there is `scope.member`. `'*'` is refused.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n\tcallSite: ScopeCallSite\n}) => string | null | Promise<string | null>\n\n/**\n * Lists the tenant scopes the sync task runs over, in addition to the install-wide scope it always\n * covers. Warming needs no list: it repeats the reads each scope's readers made.\n */\nexport type ScopeListResolver = (args: { payload: Payload }) => string[] | Promise<string[]>\n\n/**\n * Names a scope on screen, so a tenant admin reads a name rather than an id in the view's caption.\n * Undefined keeps the id.\n */\nexport type ScopeLabelResolver = (args: {\n\treq: PayloadRequest\n\tscope: string\n}) => string | undefined | Promise<string | undefined>\n\n/** Whether the request's user belongs to `scope`, as opposed to having merely selected it. */\nexport type ScopeMemberAccess = (args: {\n\treq: PayloadRequest\n\tscope: string\n}) => boolean | Promise<boolean>\n\n/** How the install divides its analytics into tenants. Unset, the install is one scope. */\nexport type AnalyticsScopeOptions = {\n\tresolve: ScopeResolver\n\t/**\n\t * Whether the request's user belongs to the scope `resolve` selected, asked on every read and\n\t * config write. `tenantMembership()` reads the multi-tenant plugin's tenants.\n\t */\n\tmember: ScopeMemberAccess\n\tlist?: ScopeListResolver\n\tlabel?: ScopeLabelResolver\n}\n\n/**\n * Resolves a scope's IANA reporting timezone, also asked at ingest without the user or cookies.\n * Null means UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves a scope's ISO 4217 revenue currency, so each tenant can have its own. Undefined reports\n * revenue as a plain number.\n */\nexport type CurrencyResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | undefined | Promise<string | undefined>\n\n/**\n * How the install measures money once `revenue` turns it on. Off hides every money surface but\n * keeps stored data, so turning it on later reports the history.\n */\nexport type AnalyticsRevenueOptions = {\n\t/**\n\t * ISO 4217 currency revenue is reported in, or a resolver per tenant. Unset, amounts are summed\n\t * as sent and a mix of currencies is flagged in `meta.mixedCurrencies`.\n\t */\n\tcurrency?: string | CurrencyResolver\n\t/**\n\t * FX hook native ingest calls when an event's currency differs from `currency`. Without it such\n\t * an amount stays out of revenue, though the conversion still counts.\n\t */\n\tconvert?: CurrencyConverter\n\t/**\n\t * The `currency` breakdown dimension, keyed by the currency each amount was sent in. Default: on\n\t * while no `convert` hook is set.\n\t */\n\tdimension?: boolean\n\t/**\n\t * How far native ingest trusts an amount a browser sends, which anyone can forge. `'fixed'`\n\t * (default) prefers a goal's fixed value, `'none'` ignores it, `'trust'` prefers it.\n\t */\n\tbrowserAmounts?: BrowserAmounts\n\t/**\n\t * Whether native ingest takes an order id sent without the server's `signOrderId` signature.\n\t * `'optional'` (default) takes it; `'required'` answers an unsigned one with `400`.\n\t */\n\torderSignature?: OrderSignatureMode\n}\n\n/** What `providers.resolve` is handed for one scope. */\nexport interface ProvidersResolveArgs {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n\t/**\n\t * The runtime's guarded fetch: every address a vendor's host resolves to has to be public, on\n\t * every connection and every redirect. Hand it to `adapterFromProviderDoc`.\n\t */\n\tfetch: FetchLike\n\t/**\n\t * The hosts a document may name: each vendor's own cloud, plus `providers.hosts`. Hand it to\n\t * `adapterFromProviderDoc` with `fetch`, which reaches a private network only when it allows one.\n\t */\n\thosts: ProviderHostPolicy\n\t/** The plugin's `sdks`, which a GA4 document's adapter reads through. */\n\tsdks: AnalyticsSdks\n}\n\n/**\n * Replaces the providers collection lookup with a scope's adapters, uncached. Build each with\n * `adapterFromProviderDoc(row, { fetch, hosts, sdks })` so a stored key reaches allowed hosts only.\n */\nexport type ProvidersResolve = (\n\targs: ProvidersResolveArgs\n) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\n/**\n * Where provider documents may point. Each vendor's own cloud is always allowed: Plausible, Umami\n * Cloud, and PostHog's US and EU regions.\n */\nexport type ProviderHostsOptions = {\n\t/**\n\t * Origins a document's host may name besides its vendor's cloud, such as `https://*.example.com`;\n\t * no paths. A host outside them reads as `source_misconfigured`.\n\t */\n\tallow?: string[]\n\t/**\n\t * Lets document adapters reach any address over http or https, private networks included (Umami\n\t * on the same Docker network). Default off.\n\t */\n\tallowPrivateNetwork?: boolean\n}\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers. Default `scope`;\n\t * name a tenant plugin's field (`tenant`) when that plugin scopes the collection.\n\t */\n\tscopeField?: string\n\t/**\n\t * Replaces one of the collection's own fields, each handed the plugin's default. Applied before\n\t * `overrides`.\n\t */\n\tfields?: ProviderCollectionFieldOverrides\n\t/**\n\t * Reshapes the whole config last. It may not rename the collection (`slug` does) nor turn off\n\t * its timestamps, which every instance notices a saved document by: the boot refuses both.\n\t */\n\toverrides?: CollectionOverrides\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for stored provider credentials. Unset, the fields plugin's `encrypted.keys`\n\t * applies, else a ring derived from the Payload secret, fit for dev only.\n\t */\n\tencryption?: { keys?: KeysConfig }\n\t/**\n\t * Who may set or change where a document connects (provider, host, ids); a denied value is\n\t * dropped. Default: the creator, then `access.crossScope.named` when scoped, else update access.\n\t */\n\tconnectionAccess?: ConnectionAccess\n\t/**\n\t * Who may set or change a scoped install's \"Default for this site\" checkbox; a denied value is\n\t * dropped. Default: `connectionAccess`, else its default (the creator, then `crossScope.named`).\n\t */\n\tdefaultAccess?: ConnectionAccess\n\t/**\n\t * Which provider types documents may have, the first being the select's default; the select lists\n\t * them in a fixed order. Default: every type, `native` only while `adapters` holds native().\n\t */\n\ttypes?: ProviderId[]\n\t/**\n\t * Which provider documents a reader reads analytics through, as collection access ANDed with\n\t * enabled and scope. Default: the collection's own read access.\n\t */\n\tsourceAccess?: Access\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\t/** Replaces the collection: the two cannot both be set. */\n\tresolve?: ProvidersResolve\n\t/** Where the documents of either one may point. Needs `collection` or `resolve`. */\n\thosts?: ProviderHostsOptions\n}\n\n/** Access checker for authenticated analytics reads. */\nexport type AnalyticsReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/** Access checker for the analytics admin view. */\nexport type AnalyticsViewAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\n/**\n * Access checker for one of the cross-scope gates under `access.crossScope`, told what is asked\n * where the read knows it: the scope (`'*'` or null for every scope) and, for `unscopedSource`, the adapter.\n */\nexport type CrossScopeAccess = (args: {\n\treq: PayloadRequest\n\tscope?: string | null\n\tadapterId?: string\n}) => boolean | Promise<boolean>\n\n/**\n * The three ways a reader on a scoped install reaches past their own scope, each denied by default.\n * Split so platform staff can aggregate without singling out one tenant.\n */\nexport type AnalyticsCrossScopeOptions = {\n\t/**\n\t * Reading a scope the request does not resolve to, by naming it. Also decides who manages other\n\t * tenants' provider, goal and sync documents.\n\t */\n\tnamed?: CrossScopeAccess\n\t/** Reading every scope at once: the `'*'` marker, and a scoped install's null scope. */\n\taggregate?: CrossScopeAccess\n\t/**\n\t * Reading a tenant through a shared config adapter that cannot narrow its query to one scope.\n\t * Also decides whether such an adapter is listed as a source at all.\n\t */\n\tunscopedSource?: CrossScopeAccess\n}\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates every read: endpoints, dashboard widgets and display fields. Default `isAdminUser` (the\n\t * `admin.user` collection); scope gating applies on top and is never widened by it.\n\t */\n\tread?: AnalyticsReadAccess\n\t/**\n\t * Gates the analytics admin view. Default: `read`. A denied reader still sees the nav link and\n\t * lands on the view's no-access message.\n\t */\n\tview?: AnalyticsViewAccess\n\t/**\n\t * Reads past the request's own scope, scoped installs only: a function grants all three gates,\n\t * the object form each one (unset denies). Unscoped, all three open to `isAdminUser`.\n\t */\n\tcrossScope?: CrossScopeAccess | AnalyticsCrossScopeOptions\n}\n\n/** The three cross-scope gates, each filled. */\nexport type ResolvedCrossScope = Record<ScopeDecision, CrossScopeAccess>\n\n/** What `capture.gate` is asked about one capture slot. */\nexport interface CaptureGateArgs {\n\tslot: CaptureSlot\n\t/** The adapter filling the slot for this request. */\n\tadapterId: string\n\tkind: CaptureClientKind\n}\n\n/**\n * Which capture slots wait for the host's consent manager: `'all'`, `'off'`, a list of slots, or a\n * function answering per slot (true waits).\n */\nexport type CaptureGate = 'all' | 'off' | CaptureSlot[] | ((args: CaptureGateArgs) => boolean)\n\n/** `capture.gate` resolved: whether one slot, filled by one adapter, waits. */\nexport type CaptureGatePolicy = (args: CaptureGateArgs) => boolean\n\n/** What `capture.withoutConsent` is asked about one held slot in one phase. */\nexport interface WithoutConsentArgs extends CaptureGateArgs {\n\tphase: ConsentPhase\n}\n\n/** `capture.withoutConsent` as a function: a throw, or any other answer, means `'off'`. */\nexport type WithoutConsentFunction = (args: WithoutConsentArgs) => WithoutConsentLevel\n\n/**\n * What a slot `capture.gate` holds does before an answer (`pending`) and after a refusal\n * (`refused`): one level for both, one per phase (an omitted phase is `'cookieless'`), or a\n * function answering per slot and phase.\n */\nexport type WithoutConsentOption =\n\t| WithoutConsentLevel\n\t| { pending?: WithoutConsentLevel; refused?: WithoutConsentLevel }\n\t| WithoutConsentFunction\n\n/** `capture.withoutConsent` checked: a level per phase, or the host's function. */\nexport type ResolvedWithoutConsent =\n\t| Record<ConsentPhase, WithoutConsentLevel>\n\t| WithoutConsentFunction\n\n/** An adapter id to fill a capture slot with, or `false` to leave it deliberately empty. */\nexport type CaptureSlotOption = string | false\n\n/** What the tracker and ingest do with elements marked by `itemAttributes`. */\nexport type ItemCaptureOptions = {\n\t/** Count an item as seen once at least half of it stays on screen for a second. */\n\timpressions?: boolean\n\t/** Send `item_click` for the first click on an item during a pageview. */\n\tclicks?: boolean\n\t/** Also count an item per page it appeared on, beside its own total. */\n\tpages?: boolean\n}\n\nexport type AutoCaptureOptions = {\n\tscrollDepth?: boolean\n\toutboundLinks?: boolean\n\tfileDownloads?: boolean\n\tgoalAttribute?: boolean\n\t/**\n\t * Send each pageview's query string so ingest can extract its utm keys. The raw query is\n\t * never stored, only the five campaign values; set false to stop sending it at all.\n\t */\n\tquery?: boolean\n\t/**\n\t * Content items, on by default and inert until a page marks an element with `itemAttributes`.\n\t * `false` turns them off, crediting goals to items included.\n\t */\n\titems?: false | ItemCaptureOptions\n}\n\nexport type AnalyticsGoalsCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's goals. Point it at\n\t * a tenant plugin's field (e.g. 'tenant') when that plugin manages scoping.\n\t */\n\tscopeField?: string\n\t/**\n\t * Replaces one of the collection's own fields, each handed the plugin's default; applied before\n\t * `overrides`. A `slug` replacement must keep a field named `slug` or the boot fails.\n\t */\n\tfields?: GoalCollectionFieldOverrides\n\t/**\n\t * Reshapes the whole config last. It may not rename the collection (`slug` does) nor turn off\n\t * its timestamps, which every instance notices a saved document by: the boot refuses both.\n\t */\n\toverrides?: CollectionOverrides\n\taccess?: Partial<CollectionConfig['access']>\n}\n\n/** Goals as config, plus the opt-in collection editors manage their own goals through. */\nexport type AnalyticsGoalsOptions = {\n\tdefaults?: Goal[]\n\t/** Opt-in admin collection whose goals merge over `defaults`, by slug, per scope. */\n\tcollection?: boolean | AnalyticsGoalsCollectionOptions\n\t/**\n\t * The built-in `purchase` goal sales book against, on unless a configured goal claims that slug.\n\t * `false` removes it, for an install that never sells.\n\t */\n\tpurchase?: boolean\n}\n\n/**\n * The website addresses where the scope's tracker runs, one per site, each an `http(s)` origin with\n * an optional path. May be async; scope is null on an unscoped install.\n */\nexport type ExclusionSitesResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string[] | Promise<string[]>\n\n/** The signed link staff open to leave their own browser out of the numbers. */\nexport type AnalyticsExclusionOptions = {\n\t/**\n\t * The query parameter the tracker reads. Default `analytics_exclude`. Letters, digits, `.`,\n\t * `_`, `~` and `-`, at most 64 of them.\n\t */\n\tparam?: string\n\t/**\n\t * Website addresses where the tracker runs, one per site, for the view to link to: a list, or\n\t * a per-scope function (async allowed). Unset, the view hands out only the query to append.\n\t */\n\tsites?: string[] | ExclusionSitesResolver\n}\n\nexport type AnalyticsCaptureOptions = {\n\t/**\n\t * Which capture slots wait for the host's consent manager. Required whenever a slot can fill:\n\t * whether tracking needs consent is the operator's call, so there is no default.\n\t */\n\tgate?: CaptureGate\n\t/**\n\t * What a slot `gate` holds does before an answer and after a refusal. Default `'cookieless'`:\n\t * count without storing anything on the device, at the level each adapter declares (GA4's is\n\t * `'off'`). `'off'` sends nothing until consent and nothing after a refusal. An adapter's own\n\t * `withoutConsent` beats this for its slot; a slot the gate does not hold runs in full.\n\t */\n\twithoutConsent?: WithoutConsentOption\n\t/**\n\t * Exact origins of other sites (`https://shop.example.com`, no path or wildcard) whose pages may\n\t * send to ingest and the capture proxy. Unset, only the site and its subdomains can.\n\t */\n\tallowedOrigins?: string[]\n\t/**\n\t * The signed link staff open to leave their browser out of the numbers. Off by default; `true`\n\t * turns it on as `analytics_exclude`, an object renames it through `param`.\n\t */\n\texclusion?: boolean | AnalyticsExclusionOptions\n\t/**\n\t * Which adapter fills each slot (`global`: `platformAdapter` or the only adapter; `tenant`: the\n\t * scope's default). `false` leaves a slot empty: no proxy mount, no tracker entry.\n\t */\n\tslots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * Mount each slot's snippet points at. Default: the runtime proxy endpoint; set it to a\n\t * `captureRoute` handler's path, without the Next `basePath`, which the tracker config adds.\n\t */\n\tpaths?: { global?: string; tenant?: string }\n\t/** Browser auto-capture listeners, all on by default except `scrollDepth`. */\n\tautoCapture?: AutoCaptureOptions\n\t/**\n\t * Pages the tracker leaves uncounted, each on unless false: `automation` (`navigator.webdriver`;\n\t * turn it off for e2e suites asserting on hits) and `previews` (draft mode, live preview).\n\t */\n\tskip?: { automation?: boolean; previews?: boolean }\n\t/** Limits for the public runtime capture proxy, separate from the read-path `cache`. */\n\tproxy?: {\n\t\t/**\n\t\t * Deadline for the upstream response headers, in ms. Default 10000. The body\n\t\t * download is not on the clock, so a large tracker bundle streams to completion.\n\t\t */\n\t\ttimeoutMs?: number\n\t\t/**\n\t\t * Largest proxied request body, in bytes. Default 1 MiB, which clears a PostHog\n\t\t * batch carrying session-replay data. Anything larger is refused with 413.\n\t\t */\n\t\tmaxBodyBytes?: number\n\t}\n}\n\nexport type AnalyticsViewOptions = {\n\t/** Admin path the view mounts at, under `routes.admin`. Default `/analytics`. */\n\tpath?: `/${string}`\n\t/** Timeframe the view opens on before the URL says otherwise. Default `last30days`. */\n\tdefaultRange?: TimeframePreset\n\t/** Metric the cards and the trend open on. Default `pageviews`. */\n\tdefaultMetric?: MetricKey\n\t/**\n\t * Nav link label. A string is used as-is; a map is keyed by admin language code and\n\t * falls back to `en`. Unset, the plugin's own translated label applies.\n\t */\n\tnavLabel?: string | Record<string, string>\n\t/**\n\t * Whether the view adds its link to the admin sidebar. Default true; false mounts the view\n\t * without one, for a host that links it from its own navigation.\n\t */\n\tnavLink?: boolean\n\t/**\n\t * A client component replacing the view's body under the same server shell, given\n\t * `AnalyticsViewClientProps`; compose it from the sections `@10x-media/analytics/client` exports.\n\t *\n\t * @beta\n\t */\n\tComponent?: AnalyticsComponent\n}\n\nexport interface ResolvedView {\n\tpath: `/${string}`\n\tdefaultRange: TimeframePreset\n\tdefaultMetric: MetricKey\n\tnavLabel?: string | Record<string, string>\n\tnavLink: boolean\n\tComponent?: AnalyticsComponent\n}\n\n/**\n * A component a host puts in one of the plugin's places, as Payload takes one: an import-map path\n * such as `'/components/Flag#Flag'`, or the object form with its export and props.\n *\n * @beta\n */\nexport type AnalyticsComponent = string | RawPayloadComponent\n\n/**\n * How a host changes one built-in dashboard widget.\n *\n * @beta\n */\nexport interface AnalyticsWidgetOverride {\n\t/**\n\t * Rendered in place of the plugin's own component. A server component receives the full widget\n\t * props, a client component its `clientProps` alone.\n\t */\n\tComponent?: AnalyticsComponent\n\t/** The widget's name in the dashboard's widget list. */\n\tlabel?: Widget['label']\n\t/**\n\t * The widget's settings, given the plugin's own fields as `defaultFields`, the shape Payload's\n\t * form builder and search plugins take; what it returns is the form.\n\t */\n\tfields?: (args: { defaultFields: Field[] }) => Field[]\n}\n\n/** @beta */\nexport type AnalyticsWidgetOverrides = Partial<Record<BuiltInWidgetSlug, AnalyticsWidgetOverride>>\n\n/** @beta */\nexport interface AnalyticsWidgetsOptions {\n\tdisabled?: string[]\n\tregister?: CustomWidgetDef[]\n\t/**\n\t * Marks each widget's free-text Title field `localized`. Default off; takes effect only when the\n\t * Payload config enables localization.\n\t */\n\tlocalizeText?: boolean\n\t/**\n\t * Period-over-period comparison on the metric and trend widgets. Default on, except for a source\n\t * whose adapter sets `capabilities.comparison` false; `false` skips the second read.\n\t */\n\tcomparison?: boolean\n\t/** Built-in widgets changed by slug: their component, their name, their settings. */\n\toverrides?: AnalyticsWidgetOverrides\n}\n\n/**\n * `countryFlags` with a flag of the host's own.\n *\n * @beta\n */\nexport interface AnalyticsCountryFlags {\n\t/**\n\t * A client component drawing one flag from `{ code }`, an ISO 3166-1 alpha-2 code in capitals.\n\t * Registered through `admin.dependencies`, so `payload generate:importmap` picks it up.\n\t */\n\tComponent: AnalyticsComponent\n}\n\n/** The collection the sync job persists daily metrics into: `slug` defaults to `analytics-daily`. */\nexport type AnalyticsSyncCollectionOptions = AnalyticsCollectionOptions & {\n\t/** Keeps the collection out of the admin nav. Default true. */\n\thidden?: boolean\n}\n\n/** The read cache's collection: `slug` defaults to `analytics-cache`. */\nexport type AnalyticsCacheCollectionOptions = AnalyticsCollectionOptions\n\n/** What `analytics-sync` copies; when it runs is `jobs.tasks.sync`. */\nexport type AnalyticsSyncOptions = {\n\t/** Days each run reads back, today counted. Default 3. */\n\tlookbackDays?: number\n\t/**\n\t * The sources it copies: a config adapter's id, or a provider type for every source built from\n\t * provider documents of that type. Default every vendor source.\n\t */\n\tadapters?: string[]\n\tcollection?: AnalyticsSyncCollectionOptions\n}\n\n/** How much reads may ask of their sources at once (`cache.concurrency`). */\nexport type AnalyticsConcurrencyOptions = {\n\t/** Requests in flight across every vendor source of one instance. Default 16. */\n\tglobal?: number\n\t/** Requests in flight per vendor source that declares no `rateLimit.maxConcurrent`. Default 4. */\n\tperSource?: number\n\t/** Reads with nothing cached one scope may have waiting on its sources. Default 8. */\n\tperScope?: number\n}\n\n/** How reads are cached, how long they wait for their sources, and which are kept warm. */\nexport type AnalyticsCacheOptions = {\n\t/**\n\t * Seconds an answer stays fresh; unset, each adapter's `recommendedTtl` applies. A native read\n\t * whose window reaches into today stays fresh 10 seconds at most whatever this says.\n\t */\n\tttl?: { aggregate?: number; realtime?: number }\n\t/**\n\t * Keeps recently asked reads warm: `analytics-warm` rereads each shortly before its cached answer\n\t * expires. Default off; `true` uses the defaults. Scheduled by `jobs.tasks.warm`.\n\t */\n\twarm?: boolean | AnalyticsWarmOptions\n\t/**\n\t * How long a read waits for its source, in ms, retries included. Default 15000. Only a read with\n\t * nothing cached (and sync) waits; others answer an expired entry at once.\n\t */\n\ttimeoutMs?: number\n\t/**\n\t * How much reads may ask of their sources at once; past `perScope` the query endpoint answers\n\t * 429. Native reads have a lane of their own outside these: 8, or on Postgres a third of\n\t * `pool.max`, between 1 and 8.\n\t */\n\tconcurrency?: AnalyticsConcurrencyOptions\n\t/**\n\t * Where reads are cached across requests and instances. Default: the `analytics-cache`\n\t * collection; a self-expiring store (Redis) replaces it. Live counts stay in memory.\n\t */\n\tstore?: CacheStore\n\t/** The `analytics-cache` collection of the default store; refused beside `store`. */\n\tcollection?: AnalyticsCacheCollectionOptions\n}\n\n/** Hooks into what the plugin does. */\nexport type AnalyticsHooksOptions = {\n\t/**\n\t * Runs once for every read answered to a reader, after it is cached, to observe it or answer\n\t * that one read differently. See {@link AfterReadHook} for the contract.\n\t */\n\tafterRead?: AfterReadHook\n}\n\n/** Which reads `analytics-warm` keeps warm; when it runs is `jobs.tasks.warm`. */\nexport type AnalyticsWarmOptions = {\n\t/** Reads asked for in this many hours count as recent. Default 24. */\n\twindowHours?: number\n\t/** The most reads one run refreshes, most recently read first. Default 200. */\n\tmaxReads?: number\n}\n\n/** Where the plugin's endpoints answer. */\nexport type AnalyticsRoutesOptions = {\n\t/**\n\t * The path every plugin endpoint hangs off, under `routes.api`. Default `/_x`; the boot fails\n\t * when a collection slug is its first segment, which would swallow those requests.\n\t */\n\tbase?: RouteBase\n}\n\nexport type AnalyticsPluginOptions = {\n\t/**\n\t * Switches the plugin off but keeps its schema (collections, fields, indexes, task slugs), so\n\t * nothing is dropped. No endpoint, view, widget or task work runs; options are still checked.\n\t */\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for the plugin's UI strings, keyed by `@10x-media/analytics/i18n` keys.\n\t * They win per key over built-ins; app `i18n.translations` wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics). Reading a tenant\n\t * through it needs `access.crossScope.unscopedSource` unless it supports scoped queries.\n\t */\n\tplatformAdapter?: string\n\t/** Tenancy: how a request maps to its scope. Unset, the whole install is one scope. */\n\tscope?: AnalyticsScopeOptions\n\t/**\n\t * Per shared config adapter, keyed by its id: which tenant users besides platform staff\n\t * (`access.crossScope.unscopedSource`) read their own tenant through it. Scoped installs only.\n\t */\n\tsources?: Record<string, AnalyticsSourceOptions>\n\t/**\n\t * A tenant scope's default source when none of its provider documents is flagged the default.\n\t * Unset keeps the registry's own order. Scoped installs only.\n\t */\n\tdefaultSource?: DefaultSourceRule\n\t/**\n\t * IANA timezone days are cut in. Default UTC; a resolver answers per scope. After a change,\n\t * native recounts in the new zone only days whose raw hits it still keeps.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\t/**\n\t * Money as a capability. `false` or unset measures none; `true` measures it with the\n\t * defaults; an object turns it on and says in which currency, and how.\n\t */\n\trevenue?: boolean | AnalyticsRevenueOptions\n\t/**\n\t * How many proxies to trust, counted from the right of `x-forwarded-for`, when reading a client\n\t * address. Unset keeps the leftmost entry, which the client controls. Not with `trustedPlatform`.\n\t */\n\ttrustedProxyHops?: number\n\t/**\n\t * Platform (`'vercel'` or `'cloudflare'`) whose edge headers carry the visitor's address and\n\t * location. Set it only when every request passes through it, or the headers can be forged.\n\t */\n\ttrustedPlatform?: TrustedPlatform\n\taccess?: AnalyticsAccessOptions\n\tcapture?: AnalyticsCaptureOptions\n\t/**\n\t * Conversion goals the tracker and native ingest match events against: a list, or `{ defaults,\n\t * collection, purchase }`. A goal's name never reaches the browser.\n\t */\n\tgoals?: Goal[] | AnalyticsGoalsOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tproviders?: ProvidersOptions\n\t/**\n\t * The analytics admin view and its nav link, on by default. `false` registers neither;\n\t * the read endpoints stay mounted either way, so a custom surface keeps working.\n\t */\n\tview?: false | AnalyticsViewOptions\n\t/**\n\t * Dashboard widgets, on by default. Payload's dashboard is experimental, so this option is too.\n\t *\n\t * @beta\n\t */\n\twidgets?: boolean | AnalyticsWidgetsOptions\n\t/**\n\t * Flag beside country names in the view, widgets and document panel. Default on, served by the\n\t * plugin's cached route; `false` shows none, `{ Component }` draws the host's own.\n\t *\n\t * @beta\n\t */\n\tcountryFlags?: boolean | AnalyticsCountryFlags\n\tcache?: AnalyticsCacheOptions\n\t/**\n\t * Opt-in sync tier: `analytics-sync` copies each vendor source's daily metrics into a queryable\n\t * collection, every six hours unless `jobs.tasks.sync` says otherwise.\n\t */\n\tsync?: boolean | AnalyticsSyncOptions\n\troutes?: AnalyticsRoutesOptions\n\t/**\n\t * The plugin's tasks (maintain, sync, warm) on `jobs.queue`, scheduled by `jobs.tasks`. `false`\n\t * registers none: reads and ingest then do native upkeep, and sync or warming is refused.\n\t */\n\tjobs?: false | AnalyticsJobsOptions\n\t/**\n\t * Optional packages handed in, which a standalone or serverless build then ships: GA4's\n\t * `{ BetaAnalyticsDataClient }` and MaxMind's `{ open }`. A production boot warns about one missing.\n\t */\n\tsdks?: AnalyticsSdks\n\thooks?: AnalyticsHooksOptions\n}\n\n/** `capture.exclusion` while the link is on. */\nexport interface ResolvedExclusion {\n\tparam: string\n\t/** `sites`, a list made a function answering it; absent when the install names none. */\n\tsites?: ExclusionSitesResolver\n}\n\nexport interface ResolvedCapture {\n\tslots: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\tpaths: { global?: string; tenant?: string }\n\tgate: CaptureGatePolicy\n\t/** Absent while the install leaves it unset, which means `'cookieless'` in both phases. */\n\twithoutConsent?: ResolvedWithoutConsent\n\t/** Slots the gate may hold, judged without calling host code: a function may hold either. */\n\theldSlots: ReadonlySet<CaptureSlot>\n\t/** Whether some held slot of the install may count without consent, as far as the boot can tell. */\n\tinstallCountsWithoutConsent: boolean\n\tautoCapture: ResolvedAutoCapture\n\tproxy: { timeoutMs: number; maxBodyBytes: number }\n\t/** `allowedOrigins`, each as a browser writes it in `Origin`. */\n\tallowedOrigins: ReadonlySet<string>\n\t/** The exclusion link's parameter and site addresses, or false while the link is off. */\n\texclusion: false | ResolvedExclusion\n\tskip: TrackerSkip\n}\n\nexport interface ResolvedRevenue {\n\t/** Whether the install measures money at all. Every money surface reads this one answer. */\n\tenabled: boolean\n\t/** Raw currency option; the plugin normalizes it into a resolver. */\n\tcurrency?: string | CurrencyResolver\n\tconvert?: CurrencyConverter\n\t/** Whether native declares the `currency` dimension; always false while money is off. */\n\tdimension: boolean\n\tbrowserAmounts: BrowserAmounts\n\torderSignature: OrderSignatureMode\n}\n\nexport interface ResolvedScope {\n\t/** The host's resolver with `'*'` refused; resolves null for every request when unscoped. */\n\tresolve: ScopeResolver\n\tlist?: ScopeListResolver\n\tlabel?: ScopeLabelResolver\n\t/** Present exactly when the install is scoped. */\n\tmember?: ScopeMemberAccess\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscope: ResolvedScope\n\t/** True when the app configured `scope.resolve` (scoped install). */\n\tscoped: boolean\n\t/** Raw `reportingTimezone`, a string already validated; the runtime makes it a resolver. */\n\treportingTimezone?: string | TimezoneResolver\n\trevenue: ResolvedRevenue\n\tplatformAdapter?: string\n\t/** `sources` and `defaultSource`; no policies and no rule on an unscoped install. */\n\tsources: ResolvedSources\n\t/** Raw trustedProxyHops option; undefined keeps the leftmost forwarded-for entry. */\n\ttrustedProxyHops?: number\n\t/** The platform whose edge headers are believed; undefined believes none. */\n\ttrustedPlatform?: TrustedPlatform\n\taccess: {\n\t\tread: AnalyticsReadAccess\n\t\tview: AnalyticsViewAccess\n\t\tcrossScope: ResolvedCrossScope\n\t}\n\t/** The admin view, filled with its defaults, or false when the app turned it off. */\n\tview: false | ResolvedView\n\t/** `true` the plugin's own flags, `false` none, or the host's component. */\n\tcountryFlags: boolean | AnalyticsCountryFlags\n\tcapture: ResolvedCapture\n\t/** Config goals, validated; the goals collection layers its own on top of these. */\n\tgoals: Goal[]\n\t/** `goals.purchase`: whether the resolver adds the built-in `purchase` goal. */\n\tpurchaseGoal: boolean\n\tgoalsCollection: ResolvedScopedCollection<GoalCollectionFieldOverrides>\n\tproviders: {\n\t\tcollection: ResolvedScopedCollection<ProviderCollectionFieldOverrides> & {\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t\tconnectionAccess?: ConnectionFieldAccess\n\t\t\tdefaultAccess?: ConnectionFieldAccess\n\t\t\t/** The types the install serves, `types` applied; filled whether the collection is on or not. */\n\t\t\ttypes: readonly ProviderId[]\n\t\t\tsourceAccess?: Access\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t\t/** `providers.hosts`, for the collection's documents and the rows `resolve` reads alike. */\n\t\thosts: ProviderHostPolicy\n\t}\n\t/** Each binding with its `scopeField` filled. */\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; windowHours: number; maxReads: number }\n\t\ttimeoutMs: number\n\t\tconcurrency: { global: number; perSource: number; perScope: number }\n\t\t/** The host's store; absent, the `analytics-cache` collection is the store. */\n\t\tstore?: CacheStore\n\t\t/** The default store's collection, used only while `store` is absent. */\n\t\tcollection: ResolvedCollectionOption\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t\toverrides: AnalyticsWidgetOverrides\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\tcollection: ResolvedCollectionOption & {\n\t\t\thidden: boolean\n\t\t}\n\t}\n\troutes: { base: RouteBase }\n\tjobs: ResolvedJobs\n\tsdks: AnalyticsSdks\n\thooks: { afterRead?: AfterReadHook }\n}\n\nconst PLUGIN_KEYS = keysOf<AnalyticsPluginOptions>({\n\tdisabled: true,\n\ttranslations: true,\n\tadapters: true,\n\tdefaultAdapter: true,\n\tplatformAdapter: true,\n\tscope: true,\n\tsources: true,\n\tdefaultSource: true,\n\treportingTimezone: true,\n\trevenue: true,\n\ttrustedProxyHops: true,\n\ttrustedPlatform: true,\n\taccess: true,\n\tcapture: true,\n\tgoals: true,\n\tcollections: true,\n\tproviders: true,\n\tview: true,\n\twidgets: true,\n\tcountryFlags: true,\n\tcache: true,\n\tsync: true,\n\troutes: true,\n\tjobs: true,\n\tsdks: true,\n\thooks: true,\n})\nconst ROUTES_KEYS = keysOf<AnalyticsRoutesOptions>({ base: true })\nconst BINDING_KEYS = keysOf<AnalyticsBinding>({\n\tpath: true,\n\tpathField: true,\n\thostname: true,\n\titem: true,\n\tscopeField: true,\n})\n\n/** Every key the plugin's own translations override, singular and plural forms alike. */\nconst TRANSLATION_KEYS: ReadonlySet<string> = new Set<string>([\n\t...Object.values(keys),\n\t...Object.values(pluralKeys).flatMap((forms) => Object.values(forms)),\n])\n\n/** `translations`: per language, strings keyed by the plugin's own translation keys. */\nconst assertTranslations = (option: unknown): void => {\n\tif (option === undefined) {\n\t\treturn\n\t}\n\tif (!isRecord(option) || Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: translations must be an object keyed by language, such as { de: { 'analytics:viewTitle': 'Statistik' } }, got ${kindOf(option)}`\n\t\t)\n\t}\n\tfor (const [language, strings] of Object.entries(option)) {\n\t\tif (!isRecord(strings) || Array.isArray(strings)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: translations.${language} must be an object of strings keyed by translation key, got ${kindOf(strings)}`\n\t\t\t)\n\t\t}\n\t\tfor (const [key, text] of Object.entries(strings)) {\n\t\t\tif (!TRANSLATION_KEYS.has(key)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`analytics: translations.${language}[\"${key}\"] is not one of the plugin's translation keys, which @10x-media/analytics/i18n exports as keys`\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (text !== undefined && typeof text !== 'string') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`analytics: translations.${language}[\"${key}\"] must be a string, got ${kindOf(text)}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** `reportingTimezone`: an IANA name checked at boot, or a resolver answering per scope. */\nconst assertTimezone = (option: unknown): void => {\n\tif (option !== undefined && typeof option !== 'string' && typeof option !== 'function') {\n\t\tthrow new Error(\n\t\t\t`analytics: reportingTimezone must be an IANA timezone or a function, got ${kindOf(option)}`\n\t\t)\n\t}\n\tif (typeof option === 'string' && !isValidTimeZone(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: reportingTimezone \"${option}\" is not an IANA timezone name, such as \"Europe/Berlin\"`\n\t\t)\n\t}\n}\n\n/** One `collections` entry: how a bound document's page is found, and whether it is an item. */\nconst assertBinding = (binding: unknown, slug: string): void => {\n\tconst at = `collections.${slug}`\n\tconst shaped = optionsObject(binding, {\n\t\tpath: at,\n\t\tknown: BINDING_KEYS,\n\t\texample: \"an object such as { pathField: 'slug' }\",\n\t})\n\toptionalFunction(shaped.path, `${at}.path`)\n\tif (\n\t\tshaped.pathField !== undefined &&\n\t\t(typeof shaped.pathField !== 'string' || shaped.pathField.trim() === '')\n\t) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${at}.pathField must be a field name, got ${kindOf(shaped.pathField)}`\n\t\t)\n\t}\n\tif (\n\t\tshaped.hostname !== undefined &&\n\t\ttypeof shaped.hostname !== 'string' &&\n\t\ttypeof shaped.hostname !== 'function'\n\t) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${at}.hostname must be a hostname or a function answering one, got ${kindOf(shaped.hostname)}`\n\t\t)\n\t}\n\toptionalBoolean(shaped.item, `${at}.item`)\n\tif (!shaped.path && !shaped.pathField && shaped.item !== true) {\n\t\tthrow new Error(\n\t\t\t`analytics: binding for \"${slug}\" needs a path resolver, a pathField, or item: true`\n\t\t)\n\t}\n\tif (shaped.item === true && slug.includes(':')) {\n\t\tthrow new Error(\n\t\t\t`analytics: collection \"${slug}\" cannot be bound as an item: a ref is \"<collection>:<id>\", so the slug cannot hold a colon`\n\t\t)\n\t}\n}\n\n/**\n * Each binding with its scope field filled: `'tenant'` when scoped, else `false` (the request's own\n * scope). Whether that field exists is checked at init, after every plugin adds fields.\n */\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections'],\n\tscoped: boolean\n): Record<string, ResolvedBinding> => {\n\tconst keyed: unknown = collections\n\tif (keyed !== undefined && (!isRecord(keyed) || Array.isArray(keyed))) {\n\t\tthrow new Error(\n\t\t\t`analytics: collections must be an object keyed by collection slug, such as { pages: { pathField: 'slug' } }, got ${kindOf(keyed)}`\n\t\t)\n\t}\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tassertBinding(binding, slug)\n\t\tconst declared = binding.scopeField ?? (scoped ? DEFAULT_BINDING_SCOPE_FIELD : false)\n\t\tconst scopeField =\n\t\t\tdeclared === false\n\t\t\t\t? false\n\t\t\t\t: flatFieldName(declared, {\n\t\t\t\t\t\tpath: `collections.${slug}.scopeField`,\n\t\t\t\t\t\treason: \"a document's scope is read from one of its own top-level fields\",\n\t\t\t\t\t})\n\t\t// Erases the per-slug document generic: the runtime only hands a binding its own documents.\n\t\tout[slug] = { ...(binding as AnalyticsBinding), scopeField }\n\t}\n\treturn out\n}\n\nconst resolveRoutes = (option: AnalyticsPluginOptions['routes']): ResolvedOptions['routes'] => {\n\tif (option !== undefined) {\n\t\toptionsObject(option, {\n\t\t\tpath: 'routes',\n\t\t\tknown: ROUTES_KEYS,\n\t\t\texample: \"an object such as { base: '/_x' }\",\n\t\t})\n\t}\n\treturn { base: resolveRouteBase(option?.base) }\n}\n\n/** `adapters`, and the options naming one of them by id. */\nconst assertAdapterOptions = (options: AnalyticsPluginOptions, requireAdapters: boolean): void => {\n\tassertAdapters(options.adapters)\n\tconst adapters = options.adapters ?? []\n\tif (requireAdapters && adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (adapters.length > 0) {\n\t\tassertNamesAdapter(options.defaultAdapter, 'defaultAdapter', adapters)\n\t}\n\tassertNamesAdapter(options.platformAdapter, 'platformAdapter', adapters)\n}\n\n/**\n * The options checked and filled. `requireAdapters: false` is the switched-off plugin's, which\n * reads through no adapter and only asks each for its schema.\n */\nexport function resolveOptions(\n\toptions: AnalyticsPluginOptions,\n\tsettings: { requireAdapters?: boolean } = {}\n): ResolvedOptions {\n\tassertNoLegacyOptions(options)\n\tfor (const key of Object.keys(options)) {\n\t\tif (!PLUGIN_KEYS.includes(key)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${key} is not an option; analytics() takes ${listOf(PLUGIN_KEYS)}`\n\t\t\t)\n\t\t}\n\t}\n\toptionalBoolean(options.disabled, 'disabled')\n\tassertTranslations(options.translations)\n\tassertAdapterOptions(options, settings.requireAdapters !== false)\n\tconst scope = resolveScope(options.scope)\n\tconst scoped = options.scope?.resolve !== undefined\n\tif (!scoped) {\n\t\tassertScopedOnlyOptions(options)\n\t}\n\tconst capture = resolveCapture(options, scoped)\n\tconst access = resolveAccess(options.access, scoped)\n\tconst trust = resolveTrust(options)\n\tassertTimezone(options.reportingTimezone)\n\tconst countryFlags = resolveCountryFlags(options.countryFlags)\n\tconst cache = resolveCache(options.cache)\n\tconst sync = resolveSync(options.sync)\n\tconst jobs = resolveJobs(options.jobs)\n\tassertJobsFit(jobs, { sync: sync.enabled, warm: cache.warm.enabled })\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscope,\n\t\tscoped,\n\t\treportingTimezone: options.reportingTimezone,\n\t\trevenue: resolveRevenue(options.revenue),\n\t\tplatformAdapter: options.platformAdapter,\n\t\tsources: resolveSources(options),\n\t\t...trust,\n\t\taccess,\n\t\tview: resolveView(options.view),\n\t\tcountryFlags,\n\t\tcapture,\n\t\t...resolveGoals(options.goals),\n\t\tproviders: resolveProviders(options.providers, options.adapters),\n\t\tbindings: resolveBindings(options.collections, scoped),\n\t\tcache,\n\t\twidgets: resolveWidgets(options.widgets),\n\t\tsync,\n\t\troutes: resolveRoutes(options.routes),\n\t\tjobs,\n\t\tsdks: resolveSdks(options.sdks),\n\t\thooks: resolveHooks(options.hooks),\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsGA,MAAa,8BAA8B;AA+0B3C,MAAM,cAAc,OAA+B;CAClD,UAAU;CACV,cAAc;CACd,UAAU;CACV,gBAAgB;CAChB,iBAAiB;CACjB,OAAO;CACP,SAAS;CACT,eAAe;CACf,mBAAmB;CACnB,SAAS;CACT,kBAAkB;CAClB,iBAAiB;CACjB,QAAQ;CACR,SAAS;CACT,OAAO;CACP,aAAa;CACb,WAAW;CACX,MAAM;CACN,SAAS;CACT,cAAc;CACd,OAAO;CACP,MAAM;CACN,QAAQ;CACR,MAAM;CACN,MAAM;CACN,OAAO;AACR,CAAC;AACD,MAAM,cAAc,OAA+B,EAAE,MAAM,KAAK,CAAC;AACjE,MAAM,eAAe,OAAyB;CAC7C,MAAM;CACN,WAAW;CACX,UAAU;CACV,MAAM;CACN,YAAY;AACb,CAAC;;AAGD,MAAM,mBAAwC,IAAI,IAAY,CAC7D,GAAG,OAAO,OAAO,IAAI,GACrB,GAAG,OAAO,OAAO,UAAU,EAAE,SAAS,UAAU,OAAO,OAAO,KAAK,CAAC,CACrE,CAAC;;AAGD,MAAM,sBAAsB,WAA0B;CACrD,IAAI,WAAW,KAAA,GACd;CAED,IAAI,CAAC,SAAS,MAAM,KAAK,MAAM,QAAQ,MAAM,GAC5C,MAAM,IAAI,MACT,4HAA4H,OAAO,MAAM,GAC1I;CAED,KAAK,MAAM,CAAC,UAAU,YAAY,OAAO,QAAQ,MAAM,GAAG;EACzD,IAAI,CAAC,SAAS,OAAO,KAAK,MAAM,QAAQ,OAAO,GAC9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|
6
6
|
import { SYSTEM, isGatedScope, mintGatedScope } from "../access/principal.js";
|
|
7
7
|
import { createRegistry, filterRegistry } from "./registry.js";
|
|
8
8
|
import { readableProviderDocIds } from "../plugin/readableProviders.js";
|
|
9
|
+
import { currentDate } from "./clock.js";
|
|
9
10
|
import { resolvableScope, resolveRegistryFor, resolveScopeFor, scopeGates } from "../plugin/runtime.js";
|
|
11
|
+
import { isFailingConnection } from "../providers/connectionState.js";
|
|
12
|
+
import "../surfacing/breaker.js";
|
|
10
13
|
import { sourceLabelFor, sourceRefFor } from "./sourceLabel.js";
|
|
11
14
|
//#region src/core/scopedRead.ts
|
|
12
15
|
const cleared = (scope) => ({
|
|
@@ -77,11 +80,39 @@ const SYSTEM_GATES = {
|
|
|
77
80
|
};
|
|
78
81
|
const NONE_ADMITTED = /* @__PURE__ */ new Set();
|
|
79
82
|
/**
|
|
83
|
+
* The scope's own documents whose source is failing (`isFailingConnection`), which a `fallback`
|
|
84
|
+
* policy stands in for and a policy function reads as `failing`; empty unless the install has
|
|
85
|
+
* either. A document failing for longer than the breaker's longest rest is checked again in the
|
|
86
|
+
* background, since nothing else reads a source its scope no longer opens on. Rows that cannot be
|
|
87
|
+
* read count as no failure, so the reads go on.
|
|
88
|
+
*/
|
|
89
|
+
const failingOwnDocs = async (runtime, own) => {
|
|
90
|
+
const store = runtime.providerStatus;
|
|
91
|
+
if (!store || own.length === 0 || ![...runtime.sourcePolicies?.values() ?? []].some((policy) => policy === "fallback" || typeof policy === "function")) return NONE_ADMITTED;
|
|
92
|
+
let statuses;
|
|
93
|
+
try {
|
|
94
|
+
const checked = own.filter((granted) => !runtime.configAdapterIds.has(granted.adapter.id));
|
|
95
|
+
const versions = new Map(checked.map((granted) => [granted.docId, runtime.providerVersionOf?.(granted.adapter)]));
|
|
96
|
+
statuses = await store.readMany(checked.map((granted) => granted.docId), (docId) => versions.get(docId));
|
|
97
|
+
} catch (err) {
|
|
98
|
+
runtime.providerStatusWarning?.(`analytics: provider connection statuses could not be read, so no source counts as failing: ${String(err)}`);
|
|
99
|
+
return NONE_ADMITTED;
|
|
100
|
+
}
|
|
101
|
+
const at = currentDate().getTime();
|
|
102
|
+
const failing = /* @__PURE__ */ new Set();
|
|
103
|
+
for (const [docId, status] of statuses) {
|
|
104
|
+
if (!isFailingConnection(status, at)) continue;
|
|
105
|
+
failing.add(docId);
|
|
106
|
+
if (at - Date.parse(status.lastErrorAt ?? "") >= 6e5) runtime.providerRecheck?.request(docId);
|
|
107
|
+
}
|
|
108
|
+
return failing;
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
80
111
|
* Whether `sources.<id>.tenants` lets this member of `scope` read through a shared adapter none
|
|
81
112
|
* of its documents grants; asked once per request, scope and adapter. A policy that throws denies.
|
|
82
113
|
*/
|
|
83
114
|
const policyAdmits = async (args) => {
|
|
84
|
-
const { runtime, req, scope, adapter, own } = args;
|
|
115
|
+
const { runtime, req, scope, adapter, own, failing } = args;
|
|
85
116
|
const policy = runtime.sourcePolicies?.get(adapter.id);
|
|
86
117
|
if (policy === void 0 || !runtime.configAdapterIds.has(adapter.id) || adapter.capabilities.scopedQueries !== true || !await isScopeMember(runtime.member, req, scope)) return false;
|
|
87
118
|
return decideOnce(req, {
|
|
@@ -89,7 +120,10 @@ const policyAdmits = async (args) => {
|
|
|
89
120
|
key: `sourcePolicy:${JSON.stringify(scope)}:${adapter.id}`,
|
|
90
121
|
decide: async () => {
|
|
91
122
|
if (policy === "tenant") return true;
|
|
92
|
-
if (policy === "fallback")
|
|
123
|
+
if (policy === "fallback") {
|
|
124
|
+
const failed = await failing();
|
|
125
|
+
return own.every((granted) => failed.has(granted.docId));
|
|
126
|
+
}
|
|
93
127
|
try {
|
|
94
128
|
const ownSources = await Promise.all(own.map(async (granted) => ({
|
|
95
129
|
id: granted.adapter.id,
|
|
@@ -97,7 +131,8 @@ const policyAdmits = async (args) => {
|
|
|
97
131
|
req,
|
|
98
132
|
scope
|
|
99
133
|
}),
|
|
100
|
-
docId: granted.docId
|
|
134
|
+
docId: granted.docId,
|
|
135
|
+
failing: async () => (await failing()).has(granted.docId)
|
|
101
136
|
})));
|
|
102
137
|
return await policy({
|
|
103
138
|
req,
|
|
@@ -177,7 +212,8 @@ const visibleSourcesFor = async (args) => {
|
|
|
177
212
|
const { registry, grants } = resolved;
|
|
178
213
|
if (runtime.scoped !== true || scope === null || scope === "*") return {
|
|
179
214
|
registry,
|
|
180
|
-
fallbackAdmitted: NONE_ADMITTED
|
|
215
|
+
fallbackAdmitted: NONE_ADMITTED,
|
|
216
|
+
ownFailing: false
|
|
181
217
|
};
|
|
182
218
|
if (args.principal === SYSTEM) return {
|
|
183
219
|
registry: await withScopeDefault({
|
|
@@ -187,7 +223,8 @@ const visibleSourcesFor = async (args) => {
|
|
|
187
223
|
scope,
|
|
188
224
|
visible: filterRegistry(registry, (adapter) => grants.has(adapter.id) || !needsUnscopedSourceAccess(runtime, adapter, scope))
|
|
189
225
|
}),
|
|
190
|
-
fallbackAdmitted: NONE_ADMITTED
|
|
226
|
+
fallbackAdmitted: NONE_ADMITTED,
|
|
227
|
+
ownFailing: false
|
|
191
228
|
};
|
|
192
229
|
const gates = args.gates ?? scopeGates(runtime, req);
|
|
193
230
|
const readable = await readableProviderDocIds(runtime, req, scope);
|
|
@@ -200,6 +237,11 @@ const visibleSourcesFor = async (args) => {
|
|
|
200
237
|
});
|
|
201
238
|
}
|
|
202
239
|
const keep = new Set(own.map((granted) => granted.adapter.id));
|
|
240
|
+
let failingRead;
|
|
241
|
+
const failing = () => {
|
|
242
|
+
failingRead ??= failingOwnDocs(runtime, own);
|
|
243
|
+
return failingRead;
|
|
244
|
+
};
|
|
203
245
|
const fallbackAdmitted = /* @__PURE__ */ new Set();
|
|
204
246
|
for (const adapter of registry.all()) {
|
|
205
247
|
if (grants.has(adapter.id)) continue;
|
|
@@ -219,21 +261,27 @@ const visibleSourcesFor = async (args) => {
|
|
|
219
261
|
req,
|
|
220
262
|
scope,
|
|
221
263
|
adapter,
|
|
222
|
-
own
|
|
264
|
+
own,
|
|
265
|
+
failing
|
|
223
266
|
})) {
|
|
224
267
|
keep.add(adapter.id);
|
|
225
268
|
if (runtime.sourcePolicies?.get(adapter.id) === "fallback") fallbackAdmitted.add(adapter.id);
|
|
226
269
|
}
|
|
227
270
|
}
|
|
271
|
+
const scoped = await withScopeDefault({
|
|
272
|
+
runtime,
|
|
273
|
+
req,
|
|
274
|
+
resolved,
|
|
275
|
+
scope,
|
|
276
|
+
visible: filterRegistry(registry, (adapter) => keep.has(adapter.id))
|
|
277
|
+
});
|
|
278
|
+
const ownFailing = own.length > 0 && fallbackAdmitted.size > 0;
|
|
279
|
+
const defaultDoc = scoped ? resolved.grants.get(scoped.default().id) : void 0;
|
|
280
|
+
const standIn = ownFailing && defaultDoc !== void 0 && (await failing()).has(defaultDoc) ? [...fallbackAdmitted][0] : void 0;
|
|
228
281
|
return {
|
|
229
|
-
registry:
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
resolved,
|
|
233
|
-
scope,
|
|
234
|
-
visible: filterRegistry(registry, (adapter) => keep.has(adapter.id))
|
|
235
|
-
}),
|
|
236
|
-
fallbackAdmitted
|
|
282
|
+
registry: scoped && standIn !== void 0 ? createRegistry(scoped.all(), standIn) : scoped,
|
|
283
|
+
fallbackAdmitted,
|
|
284
|
+
ownFailing
|
|
237
285
|
};
|
|
238
286
|
};
|
|
239
287
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { decideOnce } from '../access/decideOnce'\nimport { isScopeMember } from '../access/membership'\nimport {\n\ttype GatedScope,\n\tisGatedScope,\n\tmintGatedScope,\n\ttype ReadPrincipal,\n\tSYSTEM,\n} from '../access/principal'\nimport { readGate } from '../access/readGate'\nimport { readableProviderDocIds } from '../plugin/readableProviders'\nimport { requestMemo } from '../plugin/requestMemo'\nimport {\n\ttype AnalyticsRuntime,\n\tresolvableScope,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n\ttype ScopeGates,\n\tscopeGates,\n} from '../plugin/runtime'\nimport { MAX_SCOPE_LENGTH } from '../query/limits'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\nimport {\n\ttype AdapterRegistry,\n\tcreateRegistry,\n\tfilterRegistry,\n\ttype ScopeRegistry,\n} from './registry'\nimport { sourceLabelFor, sourceRefFor } from './sourceLabel'\nimport type { DefaultSourceFunction, SourceRef } from './sourcePolicy'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t\t\t/**\n\t\t\t * The read's principal and scope, for the reads it makes on its behalf: handing this on\n\t\t\t * keeps every one of them on exactly this scope without deciding it again.\n\t\t\t */\n\t\t\tpin: ReadPrincipal\n\t\t\t/** The source asked for, which this reader cannot read, when the scope default read instead. */\n\t\t\tsubstitutedFrom?: string\n\t }\n\t| {\n\t\t\tok: false\n\t\t\t/**\n\t\t\t * Why the read was refused: `no-sources` (nothing this reader may read), `no-access`,\n\t\t\t * `not-member`, or `no-scope` (no single scope resolved, no cross-scope read).\n\t\t\t */\n\t\t\treason?: 'no-sources' | 'no-access' | 'not-member' | 'no-scope'\n\t }\n\ntype ResolveReadContextArgs = {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/**\n\t * Without an `adapterId`, the source to read through is the scope's default when this accepts\n\t * it, else the first visible source it accepts, else the default all the same.\n\t */\n\tprefer?: (adapter: AnalyticsAdapter) => boolean\n\t/**\n\t * An `adapterId` this reader cannot read is read as if none were named, the substitution\n\t * reported as `substitutedFrom`: for a stored choice, never a caller's explicit one.\n\t */\n\tfallbackWhenUnreadable?: boolean\n} & ReadPrincipal\n\ninterface QueryScopeArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The read's resolved scope; `'*'` is the explicit cross-scope marker. */\n\tscope: string | null\n\tadapter: AnalyticsAdapter\n\t/** Shared cross-scope decisions; one set is created per call when omitted. */\n\tgates?: ScopeGates\n}\n\n/**\n * A scope a request may act on, or why not: `named` and `unresolved` are denied cross-scope gates,\n * `failed` a throwing `scope.resolve`, `not-member` a scope its user does not belong to.\n */\nexport type RequestedScope =\n\t| {\n\t\t\tok: true\n\t\t\tscope: string | null\n\t\t\t/** The same scope as a token the reads below accept without deciding it again. */\n\t\t\tgated: GatedScope\n\t }\n\t| { ok: false; reason: 'named' | 'unresolved' | 'failed' | 'not-member' }\n\ninterface RequestedScopeArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The `scope` the request carried, untrimmed; null or undefined when it carried none. */\n\traw?: string | null\n\t/** Shared cross-scope decisions; one set is created per call when omitted. */\n\tgates?: ScopeGates\n}\n\nconst cleared = (scope: string | null): RequestedScope => ({\n\tok: true,\n\tscope,\n\tgated: mintGatedScope(scope),\n})\n\n/**\n * The scope one request may act on, for every endpoint taking a caller's `scope`, and the only\n * place a {@link GatedScope} is minted. A scoped install's null, no tenant selected, fails closed.\n */\nexport const resolveRequestedScope = async (args: RequestedScopeArgs): Promise<RequestedScope> => {\n\tconst { runtime, req } = args\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tconst named = typeof args.raw === 'string' ? args.raw.trim() : ''\n\tif (named !== '') {\n\t\t// The wildcard is never the request's own scope in this sense: it names every scope,\n\t\t// whatever the resolver answered, and stays behind the aggregate gate.\n\t\tif (named === PLATFORM_SCOPE) {\n\t\t\treturn (await gates.aggregate({ scope: PLATFORM_SCOPE }))\n\t\t\t\t? cleared(named)\n\t\t\t\t: { ok: false, reason: 'named' }\n\t\t}\n\t\t// An install without tenants has no scope to name, and no tenant id runs this long.\n\t\tif (runtime.scoped !== true || named.length > MAX_SCOPE_LENGTH) {\n\t\t\treturn { ok: false, reason: 'named' }\n\t\t}\n\t\tif (await gates.named({ scope: named })) {\n\t\t\treturn cleared(named)\n\t\t}\n\t\t// Only after the gate has said no, so a platform reader still costs one resolution.\n\t\tconst own = await resolveScopeFor(runtime, req).catch(() => null)\n\t\tif (own === null || own === PLATFORM_SCOPE || own !== named) {\n\t\t\treturn { ok: false, reason: 'named' }\n\t\t}\n\t\treturn (await isScopeMember(runtime.member, req, own))\n\t\t\t? cleared(own)\n\t\t\t: { ok: false, reason: 'not-member' }\n\t}\n\tlet scope: string | null\n\ttry {\n\t\tscope = await resolveScopeFor(runtime, req)\n\t} catch {\n\t\treturn { ok: false, reason: 'failed' }\n\t}\n\tif (scope === PLATFORM_SCOPE || scope === null) {\n\t\tconst crossScope = scope === PLATFORM_SCOPE || runtime.scoped === true\n\t\treturn crossScope && !(await gates.aggregate({ scope }))\n\t\t\t? { ok: false, reason: 'unresolved' }\n\t\t\t: cleared(scope)\n\t}\n\tif ((await isScopeMember(runtime.member, req, scope)) || (await gates.named({ scope }))) {\n\t\treturn cleared(scope)\n\t}\n\treturn { ok: false, reason: 'not-member' }\n}\n\n/**\n * True for a shared config adapter that cannot narrow its query, read under a tenant scope: it\n * would answer with every scope's data, so reading or listing it takes `unscopedSource`.\n */\nexport const needsUnscopedSourceAccess = (\n\truntime: AnalyticsRuntime,\n\tadapter: AnalyticsAdapter,\n\tscope: string | null\n): boolean =>\n\tscope !== null &&\n\tscope !== PLATFORM_SCOPE &&\n\truntime.configAdapterIds.has(adapter.id) &&\n\t!adapter.capabilities.scopedQueries\n\n/**\n * {@link SYSTEM} reads any scope, but never a tenant through a shared adapter that cannot narrow\n * to it: a job would store that adapter's install-wide numbers as the tenant's own.\n */\nconst SYSTEM_GATES: ScopeGates = {\n\tnamed: () => Promise.resolve(true),\n\taggregate: () => Promise.resolve(true),\n\tunscopedSource: () => Promise.resolve(false),\n}\n\ninterface VisibleArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tresolved: ScopeRegistry\n\tscope: string | null\n\tgates?: ScopeGates\n\tprincipal?: typeof SYSTEM\n}\n\n/** The adapters one reader sees in a scope, and which of them a `fallback` policy alone admitted. */\nexport interface VisibleSources {\n\tregistry: AdapterRegistry | null\n\t/** Shared adapters listed only because a `fallback` policy let a member of the scope in. */\n\tfallbackAdmitted: ReadonlySet<string>\n}\n\nconst NONE_ADMITTED: ReadonlySet<string> = new Set()\n\n/** A source the reader reads a scope through by one of the scope's own provider documents. */\ninterface Granted {\n\tadapter: AnalyticsAdapter\n\tdocId: string\n}\n\n/**\n * Whether `sources.<id>.tenants` lets this member of `scope` read through a shared adapter none\n * of its documents grants; asked once per request, scope and adapter. A policy that throws denies.\n */\nconst policyAdmits = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tscope: string\n\tadapter: AnalyticsAdapter\n\town: readonly Granted[]\n}): Promise<boolean> => {\n\tconst { runtime, req, scope, adapter, own } = args\n\tconst policy = runtime.sourcePolicies?.get(adapter.id)\n\t// The boot refuses a policy on an adapter that cannot narrow; a tenant must never read totals\n\t// spanning every tenant, so a runtime built any other way is held to it too.\n\tif (\n\t\tpolicy === undefined ||\n\t\t!runtime.configAdapterIds.has(adapter.id) ||\n\t\tadapter.capabilities.scopedQueries !== true ||\n\t\t!(await isScopeMember(runtime.member, req, scope))\n\t) {\n\t\treturn false\n\t}\n\treturn decideOnce(req, {\n\t\towner: runtime,\n\t\tkey: `sourcePolicy:${JSON.stringify(scope)}:${adapter.id}`,\n\t\tdecide: async () => {\n\t\t\tif (policy === 'tenant') {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (policy === 'fallback') {\n\t\t\t\treturn own.length === 0\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst ownSources = await Promise.all(\n\t\t\t\t\town.map(async (granted) => ({\n\t\t\t\t\t\tid: granted.adapter.id,\n\t\t\t\t\t\tlabel: await sourceLabelFor(granted.adapter, { req, scope }),\n\t\t\t\t\t\tdocId: granted.docId,\n\t\t\t\t\t}))\n\t\t\t\t)\n\t\t\t\treturn (await policy({ req, scope, adapterId: adapter.id, ownSources })) === true\n\t\t\t} catch (err) {\n\t\t\t\treq.payload.logger?.warn(\n\t\t\t\t\t`analytics: sources.${adapter.id}.tenants threw for scope \"${scope}\", which counts as no: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn false\n\t\t\t}\n\t\t},\n\t})\n}\n\nconst pickedDefaults = requestMemo<string | undefined>('defaultSources')\n\n/** The `defaultSource` function's pick, asked once per request, scope and set of sources. */\nconst pickDefault = (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tresolved: ScopeRegistry\n\tscope: string\n\tvisible: AdapterRegistry\n\tpick: DefaultSourceFunction\n}): Promise<string | undefined> => {\n\tconst { runtime, req, resolved, scope, visible, pick } = args\n\tconst listed = visible.all()\n\treturn pickedDefaults(req, {\n\t\towner: pick,\n\t\tkey: `${JSON.stringify(scope)}:${listed.map((adapter) => adapter.id).join(',')}`,\n\t\tcompute: async () => {\n\t\t\ttry {\n\t\t\t\tconst sources: SourceRef[] = await Promise.all(\n\t\t\t\t\tlisted.map((adapter) =>\n\t\t\t\t\t\tsourceRefFor(adapter, {\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tscope,\n\t\t\t\t\t\t\tconfigIds: runtime.configAdapterIds,\n\t\t\t\t\t\t\tdocId: resolved.grants.get(adapter.id),\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\treturn await pick({ req, scope, sources })\n\t\t\t} catch (err) {\n\t\t\t\treq.payload.logger?.warn(\n\t\t\t\t\t`analytics: defaultSource threw for scope \"${scope}\", which keeps the default: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t},\n\t})\n}\n\ninterface ScopeDefaultArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tresolved: ScopeRegistry\n\tscope: string\n\tvisible: AdapterRegistry\n}\n\n/**\n * A tenant scope's default among the sources a reader sees: its document flagged the default, else\n * the `defaultSource` rule's pick, else undefined for the registry's own.\n */\nconst scopeDefaultId = async (args: ScopeDefaultArgs): Promise<string | undefined> => {\n\tconst { runtime, resolved, visible } = args\n\tconst all = visible.all()\n\tconst sees = (id: string | undefined): id is string =>\n\t\tid !== undefined && all.some((adapter) => adapter.id === id)\n\tif (sees(resolved.defaultGrant)) {\n\t\treturn resolved.defaultGrant\n\t}\n\tconst rule = runtime.defaultSource\n\tif (rule === undefined) {\n\t\treturn undefined\n\t}\n\tif (rule === 'tenantFirst') {\n\t\treturn all.find((adapter) => resolved.grants.has(adapter.id))?.id\n\t}\n\tif (rule === 'platformFirst') {\n\t\treturn sees(runtime.platformAdapterId) ? runtime.platformAdapterId : undefined\n\t}\n\tconst picked = await pickDefault({ ...args, pick: rule })\n\treturn sees(picked) ? picked : undefined\n}\n\n/** `visible` reading through the scope's chosen default; the very registry when it already does. */\nconst withScopeDefault = async (\n\targs: Omit<ScopeDefaultArgs, 'visible'> & { visible: AdapterRegistry | null }\n): Promise<AdapterRegistry | null> => {\n\tconst { visible } = args\n\tif (!visible) {\n\t\treturn null\n\t}\n\tconst chosen = await scopeDefaultId({ ...args, visible })\n\treturn chosen === undefined || chosen === visible.default().id\n\t\t? visible\n\t\t: createRegistry(visible.all(), chosen)\n}\n\n/**\n * {@link visibleRegistryFor}, also naming the shared adapters only a `fallback` policy admitted,\n * which a listing says so about.\n */\nexport const visibleSourcesFor = async (args: VisibleArgs): Promise<VisibleSources> => {\n\tconst { runtime, req, resolved, scope } = args\n\tconst { registry, grants } = resolved\n\tif (runtime.scoped !== true || scope === null || scope === PLATFORM_SCOPE) {\n\t\treturn { registry, fallbackAdmitted: NONE_ADMITTED }\n\t}\n\tif (args.principal === SYSTEM) {\n\t\tconst visible = filterRegistry(\n\t\t\tregistry,\n\t\t\t(adapter) => grants.has(adapter.id) || !needsUnscopedSourceAccess(runtime, adapter, scope)\n\t\t)\n\t\treturn {\n\t\t\tregistry: await withScopeDefault({ runtime, req, resolved, scope, visible }),\n\t\t\tfallbackAdmitted: NONE_ADMITTED,\n\t\t}\n\t}\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tconst readable = await readableProviderDocIds(runtime, req, scope)\n\tconst own: Granted[] = []\n\tfor (const adapter of registry.all()) {\n\t\tconst docId = grants.get(adapter.id)\n\t\tif (docId !== undefined && (readable === null || readable.has(docId))) {\n\t\t\town.push({ adapter, docId })\n\t\t}\n\t}\n\tconst keep = new Set(own.map((granted) => granted.adapter.id))\n\tconst fallbackAdmitted = new Set<string>()\n\tfor (const adapter of registry.all()) {\n\t\tif (grants.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!runtime.providersCollection && adapter.capabilities.scopedQueries) {\n\t\t\tkeep.add(adapter.id)\n\t\t\tcontinue\n\t\t}\n\t\tif (await gates.unscopedSource({ scope, adapterId: adapter.id })) {\n\t\t\tkeep.add(adapter.id)\n\t\t\tcontinue\n\t\t}\n\t\tif (await policyAdmits({ runtime, req, scope, adapter, own })) {\n\t\t\tkeep.add(adapter.id)\n\t\t\tif (runtime.sourcePolicies?.get(adapter.id) === 'fallback') {\n\t\t\t\tfallbackAdmitted.add(adapter.id)\n\t\t\t}\n\t\t}\n\t}\n\tconst visible = filterRegistry(registry, (adapter) => keep.has(adapter.id))\n\treturn {\n\t\tregistry: await withScopeDefault({ runtime, req, resolved, scope, visible }),\n\t\tfallbackAdmitted,\n\t}\n}\n\n/**\n * The adapters a request may read through in one tenant scope, or null for none: the scope's own\n * sources follow the providers' read access (`sourceAccess`), a config adapter `unscopedSource` or\n * its `sources` policy. A tenant scope reads through its chosen default (see `defaultSource`).\n */\nexport const visibleRegistryFor = async (args: VisibleArgs): Promise<AdapterRegistry | null> =>\n\t(await visibleSourcesFor(args)).registry\n\n/**\n * The sources a job reads one scope through as {@link SYSTEM}, or null when the scope holds\n * none: exactly what `resolveReadContext` lets a system read choose from.\n */\nexport const systemRegistryFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<AdapterRegistry | null> => {\n\tconst resolved = await resolveRegistryFor(runtime, {\n\t\tpayload: req.payload,\n\t\treq,\n\t\tscope: resolvableScope(scope),\n\t})\n\treturn visibleRegistryFor({ runtime, req, resolved, scope, principal: SYSTEM })\n}\n\n/**\n * The scope to stamp on one adapter query, or a refusal. Every read path decides it here, so\n * widgets and the query endpoint cannot drift on what counts as cross-scope.\n */\nexport const resolveQueryScope = async (\n\targs: QueryScopeArgs\n): Promise<{ ok: true; queryScope?: string } | { ok: false }> => {\n\tconst { runtime, req, scope, adapter } = args\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tif (scope === PLATFORM_SCOPE) {\n\t\treturn (await gates.aggregate({ scope })) ? { ok: true } : { ok: false }\n\t}\n\tif (scope === null) {\n\t\treturn { ok: true }\n\t}\n\tif (needsUnscopedSourceAccess(runtime, adapter, scope)) {\n\t\treturn (await gates.unscopedSource({ scope, adapterId: adapter.id }))\n\t\t\t? { ok: true }\n\t\t\t: { ok: false }\n\t}\n\treturn { ok: true, queryScope: scope }\n}\n\ntype PrincipalScope =\n\t| { ok: true; scope: string | null; pin: ReadPrincipal }\n\t| Extract<ReadContext, { ok: false }>\n\n/**\n * The read's scope: the system's own, one already cleared, or the one the request asks for. Checked\n * at runtime, since a JavaScript caller or a cast can pass anything; anything else is refused.\n */\nconst principalScope = async (\n\targs: ResolveReadContextArgs,\n\tgates: ScopeGates\n): Promise<PrincipalScope> => {\n\tconst { scope } = args\n\tif (args.principal === SYSTEM) {\n\t\treturn typeof scope === 'string' || scope === null\n\t\t\t? { ok: true, scope, pin: { principal: SYSTEM, scope } }\n\t\t\t: { ok: false }\n\t}\n\tif (isGatedScope(scope)) {\n\t\treturn { ok: true, scope: scope.value, pin: { scope } }\n\t}\n\tif (scope !== undefined && scope !== null && typeof scope !== 'string') {\n\t\treturn { ok: false }\n\t}\n\tconst requested = await resolveRequestedScope({\n\t\truntime: args.runtime,\n\t\treq: args.req,\n\t\tgates,\n\t\traw: scope,\n\t})\n\tif (!requested.ok) {\n\t\tswitch (requested.reason) {\n\t\t\tcase 'not-member':\n\t\t\t\treturn { ok: false, reason: 'not-member' }\n\t\t\tcase 'named':\n\t\t\t\treturn { ok: false, reason: 'no-access' }\n\t\t\tcase 'unresolved':\n\t\t\t\treturn { ok: false, reason: 'no-scope' }\n\t\t\tcase 'failed':\n\t\t\t\treturn { ok: false }\n\t\t}\n\t}\n\treturn { ok: true, scope: requested.scope, pin: { scope: requested.gated } }\n}\n\n/**\n * One read's scope and adapter, behind `access.read` and `resolveRequestedScope` unless the\n * principal is {@link SYSTEM}. Any failure answers `{ ok: false }`, so a surface never throws.\n */\nexport const resolveReadContext = async (args: ResolveReadContextArgs): Promise<ReadContext> => {\n\tconst { runtime, req, adapterId } = args\n\tconst system = args.principal === SYSTEM\n\tconst gates = system ? SYSTEM_GATES : scopeGates(runtime, req)\n\ttry {\n\t\tif (!system && !(await readGate(runtime, req))) {\n\t\t\treturn { ok: false, reason: 'no-access' }\n\t\t}\n\t\tconst decided = await principalScope(args, gates)\n\t\tif (!decided.ok) {\n\t\t\treturn decided\n\t\t}\n\t\tconst { scope, pin } = decided\n\t\tconst registryScope = resolvableScope(scope)\n\t\tconst resolved = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: registryScope,\n\t\t})\n\t\t// The default is picked out of what this reader may actually read, so a scope whose\n\t\t// leading source is the platform's own shared one still serves a tenant admin.\n\t\tconst registry = await visibleRegistryFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tresolved,\n\t\t\tscope,\n\t\t\tgates,\n\t\t\t...(system ? { principal: SYSTEM } : {}),\n\t\t})\n\t\tif (!registry) {\n\t\t\treturn { ok: false, reason: 'no-sources' }\n\t\t}\n\t\tconst fallback = registry.default()\n\t\tconst preferred =\n\t\t\targs.prefer && !args.prefer(fallback) ? registry.all().find(args.prefer) : undefined\n\t\tconst substitutedFrom =\n\t\t\tadapterId && args.fallbackWhenUnreadable && !registry.all().some((a) => a.id === adapterId)\n\t\t\t\t? adapterId\n\t\t\t\t: undefined\n\t\tconst adapter =\n\t\t\tadapterId && substitutedFrom === undefined ? registry.get(adapterId) : (preferred ?? fallback)\n\t\tconst decision = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope,\n\t\t\tadapter,\n\t\t\tgates,\n\t\t})\n\t\tif (!decision.ok) {\n\t\t\treturn { ok: false }\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tadapter,\n\t\t\tscope: registryScope,\n\t\t\tqueryScope: decision.queryScope,\n\t\t\tpin,\n\t\t\t...(substitutedFrom === undefined ? {} : { substitutedFrom }),\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: read context resolution failed: ${String(err)}`)\n\t\treturn { ok: false }\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAwGA,MAAM,WAAW,WAA0C;CAC1D,IAAI;CACJ;CACA,OAAO,eAAe,KAAK;AAC5B;;;;;AAMA,MAAa,wBAAwB,OAAO,SAAsD;CACjG,MAAM,EAAE,SAAS,QAAQ;CACzB,MAAM,QAAQ,KAAK,SAAS,WAAW,SAAS,GAAG;CACnD,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,KAAK,IAAI,KAAK,IAAI;CAC/D,IAAI,UAAU,IAAI;EAGjB,IAAI,UAAA,KACH,OAAQ,MAAM,MAAM,UAAU,EAAE,OAAA,IAAsB,CAAC,IACpD,QAAQ,KAAK,IACb;GAAE,IAAI;GAAO,QAAQ;EAAQ;EAGjC,IAAI,QAAQ,WAAW,QAAQ,MAAM,SAAA,KACpC,OAAO;GAAE,IAAI;GAAO,QAAQ;EAAQ;EAErC,IAAI,MAAM,MAAM,MAAM,EAAE,OAAO,MAAM,CAAC,GACrC,OAAO,QAAQ,KAAK;EAGrB,MAAM,MAAM,MAAM,gBAAgB,SAAS,GAAG,EAAE,YAAY,IAAI;EAChE,IAAI,QAAQ,QAAQ,QA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,KAAA,IAAY,SAAS,IAAI,SAAS,IAAK,aAAa;EACtF,MAAM,WAAW,MAAM,kBAAkB;GACxC;GACA;GACA;GACA;GACA;EACD,CAAC;EACD,IAAI,CAAC,SAAS,IACb,OAAO,EAAE,IAAI,MAAM;EAEpB,OAAO;GACN,IAAI;GACJ;GACA,OAAO;GACP,YAAY,SAAS;GACrB;GACA,GAAI,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB;EAC5D;CACD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,EAAE,IAAI,MAAM;CACpB;AACD"}
|
|
1
|
+
{"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { decideOnce } from '../access/decideOnce'\nimport { isScopeMember } from '../access/membership'\nimport {\n\ttype GatedScope,\n\tisGatedScope,\n\tmintGatedScope,\n\ttype ReadPrincipal,\n\tSYSTEM,\n} from '../access/principal'\nimport { readGate } from '../access/readGate'\nimport { readableProviderDocIds } from '../plugin/readableProviders'\nimport { requestMemo } from '../plugin/requestMemo'\nimport {\n\ttype AnalyticsRuntime,\n\tresolvableScope,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n\ttype ScopeGates,\n\tscopeGates,\n} from '../plugin/runtime'\nimport { isFailingConnection, type ProviderStatus } from '../providers/connectionState'\nimport { MAX_SCOPE_LENGTH } from '../query/limits'\nimport { BREAKER_MAX_MS } from '../surfacing/breaker'\nimport { currentDate } from './clock'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\nimport {\n\ttype AdapterRegistry,\n\tcreateRegistry,\n\tfilterRegistry,\n\ttype ScopeRegistry,\n} from './registry'\nimport { sourceLabelFor, sourceRefFor } from './sourceLabel'\nimport type { DefaultSourceFunction, SourceRef } from './sourcePolicy'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t\t\t/**\n\t\t\t * The read's principal and scope, for the reads it makes on its behalf: handing this on\n\t\t\t * keeps every one of them on exactly this scope without deciding it again.\n\t\t\t */\n\t\t\tpin: ReadPrincipal\n\t\t\t/** The source asked for, which this reader cannot read, when the scope default read instead. */\n\t\t\tsubstitutedFrom?: string\n\t }\n\t| {\n\t\t\tok: false\n\t\t\t/**\n\t\t\t * Why the read was refused: `no-sources` (nothing this reader may read), `no-access`,\n\t\t\t * `not-member`, or `no-scope` (no single scope resolved, no cross-scope read).\n\t\t\t */\n\t\t\treason?: 'no-sources' | 'no-access' | 'not-member' | 'no-scope'\n\t }\n\ntype ResolveReadContextArgs = {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/**\n\t * Without an `adapterId`, the source to read through is the scope's default when this accepts\n\t * it, else the first visible source it accepts, else the default all the same.\n\t */\n\tprefer?: (adapter: AnalyticsAdapter) => boolean\n\t/**\n\t * An `adapterId` this reader cannot read is read as if none were named, the substitution\n\t * reported as `substitutedFrom`: for a stored choice, never a caller's explicit one.\n\t */\n\tfallbackWhenUnreadable?: boolean\n} & ReadPrincipal\n\ninterface QueryScopeArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The read's resolved scope; `'*'` is the explicit cross-scope marker. */\n\tscope: string | null\n\tadapter: AnalyticsAdapter\n\t/** Shared cross-scope decisions; one set is created per call when omitted. */\n\tgates?: ScopeGates\n}\n\n/**\n * A scope a request may act on, or why not: `named` and `unresolved` are denied cross-scope gates,\n * `failed` a throwing `scope.resolve`, `not-member` a scope its user does not belong to.\n */\nexport type RequestedScope =\n\t| {\n\t\t\tok: true\n\t\t\tscope: string | null\n\t\t\t/** The same scope as a token the reads below accept without deciding it again. */\n\t\t\tgated: GatedScope\n\t }\n\t| { ok: false; reason: 'named' | 'unresolved' | 'failed' | 'not-member' }\n\ninterface RequestedScopeArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\t/** The `scope` the request carried, untrimmed; null or undefined when it carried none. */\n\traw?: string | null\n\t/** Shared cross-scope decisions; one set is created per call when omitted. */\n\tgates?: ScopeGates\n}\n\nconst cleared = (scope: string | null): RequestedScope => ({\n\tok: true,\n\tscope,\n\tgated: mintGatedScope(scope),\n})\n\n/**\n * The scope one request may act on, for every endpoint taking a caller's `scope`, and the only\n * place a {@link GatedScope} is minted. A scoped install's null, no tenant selected, fails closed.\n */\nexport const resolveRequestedScope = async (args: RequestedScopeArgs): Promise<RequestedScope> => {\n\tconst { runtime, req } = args\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tconst named = typeof args.raw === 'string' ? args.raw.trim() : ''\n\tif (named !== '') {\n\t\t// The wildcard is never the request's own scope in this sense: it names every scope,\n\t\t// whatever the resolver answered, and stays behind the aggregate gate.\n\t\tif (named === PLATFORM_SCOPE) {\n\t\t\treturn (await gates.aggregate({ scope: PLATFORM_SCOPE }))\n\t\t\t\t? cleared(named)\n\t\t\t\t: { ok: false, reason: 'named' }\n\t\t}\n\t\t// An install without tenants has no scope to name, and no tenant id runs this long.\n\t\tif (runtime.scoped !== true || named.length > MAX_SCOPE_LENGTH) {\n\t\t\treturn { ok: false, reason: 'named' }\n\t\t}\n\t\tif (await gates.named({ scope: named })) {\n\t\t\treturn cleared(named)\n\t\t}\n\t\t// Only after the gate has said no, so a platform reader still costs one resolution.\n\t\tconst own = await resolveScopeFor(runtime, req).catch(() => null)\n\t\tif (own === null || own === PLATFORM_SCOPE || own !== named) {\n\t\t\treturn { ok: false, reason: 'named' }\n\t\t}\n\t\treturn (await isScopeMember(runtime.member, req, own))\n\t\t\t? cleared(own)\n\t\t\t: { ok: false, reason: 'not-member' }\n\t}\n\tlet scope: string | null\n\ttry {\n\t\tscope = await resolveScopeFor(runtime, req)\n\t} catch {\n\t\treturn { ok: false, reason: 'failed' }\n\t}\n\tif (scope === PLATFORM_SCOPE || scope === null) {\n\t\tconst crossScope = scope === PLATFORM_SCOPE || runtime.scoped === true\n\t\treturn crossScope && !(await gates.aggregate({ scope }))\n\t\t\t? { ok: false, reason: 'unresolved' }\n\t\t\t: cleared(scope)\n\t}\n\tif ((await isScopeMember(runtime.member, req, scope)) || (await gates.named({ scope }))) {\n\t\treturn cleared(scope)\n\t}\n\treturn { ok: false, reason: 'not-member' }\n}\n\n/**\n * True for a shared config adapter that cannot narrow its query, read under a tenant scope: it\n * would answer with every scope's data, so reading or listing it takes `unscopedSource`.\n */\nexport const needsUnscopedSourceAccess = (\n\truntime: AnalyticsRuntime,\n\tadapter: AnalyticsAdapter,\n\tscope: string | null\n): boolean =>\n\tscope !== null &&\n\tscope !== PLATFORM_SCOPE &&\n\truntime.configAdapterIds.has(adapter.id) &&\n\t!adapter.capabilities.scopedQueries\n\n/**\n * {@link SYSTEM} reads any scope, but never a tenant through a shared adapter that cannot narrow\n * to it: a job would store that adapter's install-wide numbers as the tenant's own.\n */\nconst SYSTEM_GATES: ScopeGates = {\n\tnamed: () => Promise.resolve(true),\n\taggregate: () => Promise.resolve(true),\n\tunscopedSource: () => Promise.resolve(false),\n}\n\ninterface VisibleArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tresolved: ScopeRegistry\n\tscope: string | null\n\tgates?: ScopeGates\n\tprincipal?: typeof SYSTEM\n}\n\n/** The adapters one reader sees in a scope, and which of them a `fallback` policy alone admitted. */\nexport interface VisibleSources {\n\tregistry: AdapterRegistry | null\n\t/** Shared adapters listed only because a `fallback` policy let a member of the scope in. */\n\tfallbackAdmitted: ReadonlySet<string>\n\t/** True when the scope has sources of its own, all failing, so a `fallback` policy stands in for them. */\n\townFailing: boolean\n}\n\nconst NONE_ADMITTED: ReadonlySet<string> = new Set()\n\n/** A source the reader reads a scope through by one of the scope's own provider documents. */\ninterface Granted {\n\tadapter: AnalyticsAdapter\n\tdocId: string\n}\n\n/**\n * The scope's own documents whose source is failing (`isFailingConnection`), which a `fallback`\n * policy stands in for and a policy function reads as `failing`; empty unless the install has\n * either. A document failing for longer than the breaker's longest rest is checked again in the\n * background, since nothing else reads a source its scope no longer opens on. Rows that cannot be\n * read count as no failure, so the reads go on.\n */\nconst failingOwnDocs = async (\n\truntime: AnalyticsRuntime,\n\town: readonly Granted[]\n): Promise<ReadonlySet<string>> => {\n\tconst store = runtime.providerStatus\n\tif (\n\t\t!store ||\n\t\town.length === 0 ||\n\t\t![...(runtime.sourcePolicies?.values() ?? [])].some(\n\t\t\t(policy) => policy === 'fallback' || typeof policy === 'function'\n\t\t)\n\t) {\n\t\treturn NONE_ADMITTED\n\t}\n\tlet statuses: Map<string, ProviderStatus>\n\ttry {\n\t\t// A config adapter lent to a document (native) writes no status: any row it has is stale.\n\t\tconst checked = own.filter((granted) => !runtime.configAdapterIds.has(granted.adapter.id))\n\t\tconst versions = new Map(\n\t\t\tchecked.map((granted) => [granted.docId, runtime.providerVersionOf?.(granted.adapter)])\n\t\t)\n\t\tstatuses = await store.readMany(\n\t\t\tchecked.map((granted) => granted.docId),\n\t\t\t(docId) => versions.get(docId)\n\t\t)\n\t} catch (err) {\n\t\truntime.providerStatusWarning?.(\n\t\t\t`analytics: provider connection statuses could not be read, so no source counts as failing: ${String(err)}`\n\t\t)\n\t\treturn NONE_ADMITTED\n\t}\n\tconst at = currentDate().getTime()\n\tconst failing = new Set<string>()\n\tfor (const [docId, status] of statuses) {\n\t\tif (!isFailingConnection(status, at)) {\n\t\t\tcontinue\n\t\t}\n\t\tfailing.add(docId)\n\t\tif (at - Date.parse(status.lastErrorAt ?? '') >= BREAKER_MAX_MS) {\n\t\t\truntime.providerRecheck?.request(docId)\n\t\t}\n\t}\n\treturn failing\n}\n\n/**\n * Whether `sources.<id>.tenants` lets this member of `scope` read through a shared adapter none\n * of its documents grants; asked once per request, scope and adapter. A policy that throws denies.\n */\nconst policyAdmits = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tscope: string\n\tadapter: AnalyticsAdapter\n\town: readonly Granted[]\n\t/** The ids of `own`'s documents whose connection is failing, read when a policy asks. */\n\tfailing: () => Promise<ReadonlySet<string>>\n}): Promise<boolean> => {\n\tconst { runtime, req, scope, adapter, own, failing } = args\n\tconst policy = runtime.sourcePolicies?.get(adapter.id)\n\t// The boot refuses a policy on an adapter that cannot narrow; a tenant must never read totals\n\t// spanning every tenant, so a runtime built any other way is held to it too.\n\tif (\n\t\tpolicy === undefined ||\n\t\t!runtime.configAdapterIds.has(adapter.id) ||\n\t\tadapter.capabilities.scopedQueries !== true ||\n\t\t!(await isScopeMember(runtime.member, req, scope))\n\t) {\n\t\treturn false\n\t}\n\treturn decideOnce(req, {\n\t\towner: runtime,\n\t\tkey: `sourcePolicy:${JSON.stringify(scope)}:${adapter.id}`,\n\t\tdecide: async () => {\n\t\t\tif (policy === 'tenant') {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (policy === 'fallback') {\n\t\t\t\tconst failed = await failing()\n\t\t\t\treturn own.every((granted) => failed.has(granted.docId))\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst ownSources = await Promise.all(\n\t\t\t\t\town.map(async (granted) => ({\n\t\t\t\t\t\tid: granted.adapter.id,\n\t\t\t\t\t\tlabel: await sourceLabelFor(granted.adapter, { req, scope }),\n\t\t\t\t\t\tdocId: granted.docId,\n\t\t\t\t\t\tfailing: async () => (await failing()).has(granted.docId),\n\t\t\t\t\t}))\n\t\t\t\t)\n\t\t\t\treturn (await policy({ req, scope, adapterId: adapter.id, ownSources })) === true\n\t\t\t} catch (err) {\n\t\t\t\treq.payload.logger?.warn(\n\t\t\t\t\t`analytics: sources.${adapter.id}.tenants threw for scope \"${scope}\", which counts as no: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn false\n\t\t\t}\n\t\t},\n\t})\n}\n\nconst pickedDefaults = requestMemo<string | undefined>('defaultSources')\n\n/** The `defaultSource` function's pick, asked once per request, scope and set of sources. */\nconst pickDefault = (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tresolved: ScopeRegistry\n\tscope: string\n\tvisible: AdapterRegistry\n\tpick: DefaultSourceFunction\n}): Promise<string | undefined> => {\n\tconst { runtime, req, resolved, scope, visible, pick } = args\n\tconst listed = visible.all()\n\treturn pickedDefaults(req, {\n\t\towner: pick,\n\t\tkey: `${JSON.stringify(scope)}:${listed.map((adapter) => adapter.id).join(',')}`,\n\t\tcompute: async () => {\n\t\t\ttry {\n\t\t\t\tconst sources: SourceRef[] = await Promise.all(\n\t\t\t\t\tlisted.map((adapter) =>\n\t\t\t\t\t\tsourceRefFor(adapter, {\n\t\t\t\t\t\t\treq,\n\t\t\t\t\t\t\tscope,\n\t\t\t\t\t\t\tconfigIds: runtime.configAdapterIds,\n\t\t\t\t\t\t\tdocId: resolved.grants.get(adapter.id),\n\t\t\t\t\t\t})\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\treturn await pick({ req, scope, sources })\n\t\t\t} catch (err) {\n\t\t\t\treq.payload.logger?.warn(\n\t\t\t\t\t`analytics: defaultSource threw for scope \"${scope}\", which keeps the default: ${String(err)}`\n\t\t\t\t)\n\t\t\t\treturn undefined\n\t\t\t}\n\t\t},\n\t})\n}\n\ninterface ScopeDefaultArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tresolved: ScopeRegistry\n\tscope: string\n\tvisible: AdapterRegistry\n}\n\n/**\n * A tenant scope's default among the sources a reader sees: its document flagged the default, else\n * the `defaultSource` rule's pick, else undefined for the registry's own.\n */\nconst scopeDefaultId = async (args: ScopeDefaultArgs): Promise<string | undefined> => {\n\tconst { runtime, resolved, visible } = args\n\tconst all = visible.all()\n\tconst sees = (id: string | undefined): id is string =>\n\t\tid !== undefined && all.some((adapter) => adapter.id === id)\n\tif (sees(resolved.defaultGrant)) {\n\t\treturn resolved.defaultGrant\n\t}\n\tconst rule = runtime.defaultSource\n\tif (rule === undefined) {\n\t\treturn undefined\n\t}\n\tif (rule === 'tenantFirst') {\n\t\treturn all.find((adapter) => resolved.grants.has(adapter.id))?.id\n\t}\n\tif (rule === 'platformFirst') {\n\t\treturn sees(runtime.platformAdapterId) ? runtime.platformAdapterId : undefined\n\t}\n\tconst picked = await pickDefault({ ...args, pick: rule })\n\treturn sees(picked) ? picked : undefined\n}\n\n/** `visible` reading through the scope's chosen default; the very registry when it already does. */\nconst withScopeDefault = async (\n\targs: Omit<ScopeDefaultArgs, 'visible'> & { visible: AdapterRegistry | null }\n): Promise<AdapterRegistry | null> => {\n\tconst { visible } = args\n\tif (!visible) {\n\t\treturn null\n\t}\n\tconst chosen = await scopeDefaultId({ ...args, visible })\n\treturn chosen === undefined || chosen === visible.default().id\n\t\t? visible\n\t\t: createRegistry(visible.all(), chosen)\n}\n\n/**\n * {@link visibleRegistryFor}, also naming the shared adapters only a `fallback` policy admitted,\n * which a listing says so about.\n */\nexport const visibleSourcesFor = async (args: VisibleArgs): Promise<VisibleSources> => {\n\tconst { runtime, req, resolved, scope } = args\n\tconst { registry, grants } = resolved\n\tif (runtime.scoped !== true || scope === null || scope === PLATFORM_SCOPE) {\n\t\treturn { registry, fallbackAdmitted: NONE_ADMITTED, ownFailing: false }\n\t}\n\tif (args.principal === SYSTEM) {\n\t\tconst visible = filterRegistry(\n\t\t\tregistry,\n\t\t\t(adapter) => grants.has(adapter.id) || !needsUnscopedSourceAccess(runtime, adapter, scope)\n\t\t)\n\t\treturn {\n\t\t\tregistry: await withScopeDefault({ runtime, req, resolved, scope, visible }),\n\t\t\tfallbackAdmitted: NONE_ADMITTED,\n\t\t\townFailing: false,\n\t\t}\n\t}\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tconst readable = await readableProviderDocIds(runtime, req, scope)\n\tconst own: Granted[] = []\n\tfor (const adapter of registry.all()) {\n\t\tconst docId = grants.get(adapter.id)\n\t\tif (docId !== undefined && (readable === null || readable.has(docId))) {\n\t\t\town.push({ adapter, docId })\n\t\t}\n\t}\n\tconst keep = new Set(own.map((granted) => granted.adapter.id))\n\tlet failingRead: Promise<ReadonlySet<string>> | undefined\n\tconst failing = () => {\n\t\tfailingRead ??= failingOwnDocs(runtime, own)\n\t\treturn failingRead\n\t}\n\tconst fallbackAdmitted = new Set<string>()\n\tfor (const adapter of registry.all()) {\n\t\tif (grants.has(adapter.id)) {\n\t\t\tcontinue\n\t\t}\n\t\tif (!runtime.providersCollection && adapter.capabilities.scopedQueries) {\n\t\t\tkeep.add(adapter.id)\n\t\t\tcontinue\n\t\t}\n\t\tif (await gates.unscopedSource({ scope, adapterId: adapter.id })) {\n\t\t\tkeep.add(adapter.id)\n\t\t\tcontinue\n\t\t}\n\t\tif (await policyAdmits({ runtime, req, scope, adapter, own, failing })) {\n\t\t\tkeep.add(adapter.id)\n\t\t\tif (runtime.sourcePolicies?.get(adapter.id) === 'fallback') {\n\t\t\t\tfallbackAdmitted.add(adapter.id)\n\t\t\t}\n\t\t}\n\t}\n\tconst visible = filterRegistry(registry, (adapter) => keep.has(adapter.id))\n\tconst scoped = await withScopeDefault({ runtime, req, resolved, scope, visible })\n\tconst ownFailing = own.length > 0 && fallbackAdmitted.size > 0\n\tconst defaultDoc = scoped ? resolved.grants.get(scoped.default().id) : undefined\n\tconst standIn =\n\t\townFailing && defaultDoc !== undefined && (await failing()).has(defaultDoc)\n\t\t\t? [...fallbackAdmitted][0]\n\t\t\t: undefined\n\treturn {\n\t\tregistry: scoped && standIn !== undefined ? createRegistry(scoped.all(), standIn) : scoped,\n\t\tfallbackAdmitted,\n\t\townFailing,\n\t}\n}\n\n/**\n * The adapters a request may read through in one tenant scope, or null for none: the scope's own\n * sources follow the providers' read access (`sourceAccess`), a config adapter `unscopedSource` or\n * its `sources` policy. A tenant scope reads through its chosen default (see `defaultSource`).\n */\nexport const visibleRegistryFor = async (args: VisibleArgs): Promise<AdapterRegistry | null> =>\n\t(await visibleSourcesFor(args)).registry\n\n/**\n * The sources a job reads one scope through as {@link SYSTEM}, or null when the scope holds\n * none: exactly what `resolveReadContext` lets a system read choose from.\n */\nexport const systemRegistryFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope: string | null\n): Promise<AdapterRegistry | null> => {\n\tconst resolved = await resolveRegistryFor(runtime, {\n\t\tpayload: req.payload,\n\t\treq,\n\t\tscope: resolvableScope(scope),\n\t})\n\treturn visibleRegistryFor({ runtime, req, resolved, scope, principal: SYSTEM })\n}\n\n/**\n * The scope to stamp on one adapter query, or a refusal. Every read path decides it here, so\n * widgets and the query endpoint cannot drift on what counts as cross-scope.\n */\nexport const resolveQueryScope = async (\n\targs: QueryScopeArgs\n): Promise<{ ok: true; queryScope?: string } | { ok: false }> => {\n\tconst { runtime, req, scope, adapter } = args\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tif (scope === PLATFORM_SCOPE) {\n\t\treturn (await gates.aggregate({ scope })) ? { ok: true } : { ok: false }\n\t}\n\tif (scope === null) {\n\t\treturn { ok: true }\n\t}\n\tif (needsUnscopedSourceAccess(runtime, adapter, scope)) {\n\t\treturn (await gates.unscopedSource({ scope, adapterId: adapter.id }))\n\t\t\t? { ok: true }\n\t\t\t: { ok: false }\n\t}\n\treturn { ok: true, queryScope: scope }\n}\n\ntype PrincipalScope =\n\t| { ok: true; scope: string | null; pin: ReadPrincipal }\n\t| Extract<ReadContext, { ok: false }>\n\n/**\n * The read's scope: the system's own, one already cleared, or the one the request asks for. Checked\n * at runtime, since a JavaScript caller or a cast can pass anything; anything else is refused.\n */\nconst principalScope = async (\n\targs: ResolveReadContextArgs,\n\tgates: ScopeGates\n): Promise<PrincipalScope> => {\n\tconst { scope } = args\n\tif (args.principal === SYSTEM) {\n\t\treturn typeof scope === 'string' || scope === null\n\t\t\t? { ok: true, scope, pin: { principal: SYSTEM, scope } }\n\t\t\t: { ok: false }\n\t}\n\tif (isGatedScope(scope)) {\n\t\treturn { ok: true, scope: scope.value, pin: { scope } }\n\t}\n\tif (scope !== undefined && scope !== null && typeof scope !== 'string') {\n\t\treturn { ok: false }\n\t}\n\tconst requested = await resolveRequestedScope({\n\t\truntime: args.runtime,\n\t\treq: args.req,\n\t\tgates,\n\t\traw: scope,\n\t})\n\tif (!requested.ok) {\n\t\tswitch (requested.reason) {\n\t\t\tcase 'not-member':\n\t\t\t\treturn { ok: false, reason: 'not-member' }\n\t\t\tcase 'named':\n\t\t\t\treturn { ok: false, reason: 'no-access' }\n\t\t\tcase 'unresolved':\n\t\t\t\treturn { ok: false, reason: 'no-scope' }\n\t\t\tcase 'failed':\n\t\t\t\treturn { ok: false }\n\t\t}\n\t}\n\treturn { ok: true, scope: requested.scope, pin: { scope: requested.gated } }\n}\n\n/**\n * One read's scope and adapter, behind `access.read` and `resolveRequestedScope` unless the\n * principal is {@link SYSTEM}. Any failure answers `{ ok: false }`, so a surface never throws.\n */\nexport const resolveReadContext = async (args: ResolveReadContextArgs): Promise<ReadContext> => {\n\tconst { runtime, req, adapterId } = args\n\tconst system = args.principal === SYSTEM\n\tconst gates = system ? SYSTEM_GATES : scopeGates(runtime, req)\n\ttry {\n\t\tif (!system && !(await readGate(runtime, req))) {\n\t\t\treturn { ok: false, reason: 'no-access' }\n\t\t}\n\t\tconst decided = await principalScope(args, gates)\n\t\tif (!decided.ok) {\n\t\t\treturn decided\n\t\t}\n\t\tconst { scope, pin } = decided\n\t\tconst registryScope = resolvableScope(scope)\n\t\tconst resolved = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: registryScope,\n\t\t})\n\t\t// The default is picked out of what this reader may actually read, so a scope whose\n\t\t// leading source is the platform's own shared one still serves a tenant admin.\n\t\tconst registry = await visibleRegistryFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tresolved,\n\t\t\tscope,\n\t\t\tgates,\n\t\t\t...(system ? { principal: SYSTEM } : {}),\n\t\t})\n\t\tif (!registry) {\n\t\t\treturn { ok: false, reason: 'no-sources' }\n\t\t}\n\t\tconst fallback = registry.default()\n\t\tconst preferred =\n\t\t\targs.prefer && !args.prefer(fallback) ? registry.all().find(args.prefer) : undefined\n\t\tconst substitutedFrom =\n\t\t\tadapterId && args.fallbackWhenUnreadable && !registry.all().some((a) => a.id === adapterId)\n\t\t\t\t? adapterId\n\t\t\t\t: undefined\n\t\tconst adapter =\n\t\t\tadapterId && substitutedFrom === undefined ? registry.get(adapterId) : (preferred ?? fallback)\n\t\tconst decision = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope,\n\t\t\tadapter,\n\t\t\tgates,\n\t\t})\n\t\tif (!decision.ok) {\n\t\t\treturn { ok: false }\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tadapter,\n\t\t\tscope: registryScope,\n\t\t\tqueryScope: decision.queryScope,\n\t\t\tpin,\n\t\t\t...(substitutedFrom === undefined ? {} : { substitutedFrom }),\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: read context resolution failed: ${String(err)}`)\n\t\treturn { ok: false }\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;AA2GA,MAAM,WAAW,WAA0C;CAC1D,IAAI;CACJ;CACA,OAAO,eAAe,KAAK;AAC5B;;;;;AAMA,MAAa,wBAAwB,OAAO,SAAsD;CACjG,MAAM,EAAE,SAAS,QAAQ;CACzB,MAAM,QAAQ,KAAK,SAAS,WAAW,SAAS,GAAG;CACnD,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,KAAK,IAAI,KAAK,IAAI;CAC/D,IAAI,UAAU,IAAI;EAGjB,IAAI,UAAA,KACH,OAAQ,MAAM,MAAM,UAAU,EAAE,OAAA,IAAsB,CAAC,IACpD,QAAQ,KAAK,IACb;GAAE,IAAI;GAAO,QAAQ;EAAQ;EAGjC,IAAI,QAAQ,WAAW,QAAQ,MAAM,SAAA,KACpC,OAAO;GAAE,IAAI;GAAO,QAAQ;EAAQ;EAErC,IAAI,MAAM,MAAM,MAAM,EAAE,OAAO,MAAM,CAAC,GACrC,OAAO,QAAQ,KAAK;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AAI,CAAC;EACvC,CAAC;EACD,IAAI,CAAC,UACJ,OAAO;GAAE,IAAI;GAAO,QAAQ;EAAa;EAE1C,MAAM,WAAW,SAAS,QAAQ;EAClC,MAAM,YACL,KAAK,UAAU,CAAC,KAAK,OAAO,QAAQ,IAAI,SAAS,IAAI,EAAE,KAAK,KAAK,MAAM,IAAI,KAAA;EAC5E,MAAM,kBACL,aAAa,KAAK,0BAA0B,CAAC,SAAS,IAAI,EAAE,MAAM,MAAM,EAAE,OAAO,SAAS,IACvF,YACA,KAAA;EACJ,MAAM,UACL,aAAa,oBAAoB,KAAA,IAAY,SAAS,IAAI,SAAS,IAAK,aAAa;EACtF,MAAM,WAAW,MAAM,kBAAkB;GACxC;GACA;GACA;GACA;GACA;EACD,CAAC;EACD,IAAI,CAAC,SAAS,IACb,OAAO,EAAE,IAAI,MAAM;EAEpB,OAAO;GACN,IAAI;GACJ;GACA,OAAO;GACP,YAAY,SAAS;GACrB;GACA,GAAI,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,gBAAgB;EAC5D;CACD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,EAAE,IAAI,MAAM;CACpB;AACD"}
|
|
@@ -3,6 +3,7 @@ import { isDimensionKey, isFilterOperator } from "./guards.js";
|
|
|
3
3
|
/** `Symbol.for`, so an error thrown in one of the package's bundles is recognized in another. */
|
|
4
4
|
const MISCONFIGURED = Symbol.for("@10x-media/analytics/sourceMisconfigured");
|
|
5
5
|
const HOST_REFUSED = Symbol.for("@10x-media/analytics/hostRefused");
|
|
6
|
+
const UNKNOWN_SITE = Symbol.for("@10x-media/analytics/unknownSite");
|
|
6
7
|
const UNSUPPORTED_FILTER = Symbol.for("@10x-media/analytics/unsupportedFilter");
|
|
7
8
|
const INVALID_QUERY = Symbol.for("@10x-media/analytics/invalidQuery");
|
|
8
9
|
/**
|
|
@@ -26,6 +27,14 @@ var HostRefusedError = class extends SourceMisconfiguredError {
|
|
|
26
27
|
this.host = host;
|
|
27
28
|
}
|
|
28
29
|
};
|
|
30
|
+
/** A site ID the vendor answered it does not know, such as self-hosted Umami's Website ID. */
|
|
31
|
+
var UnknownSiteError = class extends SourceMisconfiguredError {
|
|
32
|
+
[UNKNOWN_SITE] = true;
|
|
33
|
+
constructor(message) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "UnknownSiteError";
|
|
36
|
+
}
|
|
37
|
+
};
|
|
29
38
|
/** How deep a cause chain is searched; a cyclic or runaway chain ends here. */
|
|
30
39
|
const MAX_CAUSE_DEPTH = 5;
|
|
31
40
|
/** The first error in `err`'s cause chain carrying `brand`, or undefined. */
|
|
@@ -41,6 +50,8 @@ const brandedCause = (err, brand) => {
|
|
|
41
50
|
const isSourceMisconfigured = (err) => brandedCause(err, MISCONFIGURED) !== void 0;
|
|
42
51
|
/** True for a {@link HostRefusedError} anywhere in an error's cause chain. */
|
|
43
52
|
const isHostRefused = (err) => brandedCause(err, HOST_REFUSED) !== void 0;
|
|
53
|
+
/** True for an {@link UnknownSiteError} anywhere in an error's cause chain. */
|
|
54
|
+
const isUnknownSite = (err) => brandedCause(err, UNKNOWN_SITE) !== void 0;
|
|
44
55
|
/**
|
|
45
56
|
* A read carrying a filter its source does not apply. The source would answer without it, and
|
|
46
57
|
* its numbers would read as filtered when they are not, so the read is refused before it is made.
|
|
@@ -104,6 +115,6 @@ const invalidQuery = (err) => {
|
|
|
104
115
|
} : void 0;
|
|
105
116
|
};
|
|
106
117
|
//#endregion
|
|
107
|
-
export { HostRefusedError, InvalidQueryError, SourceMisconfiguredError, UnsupportedFilterError, describeWithCauses, invalidQuery, isHostRefused, isSourceMisconfigured, refusedFilter };
|
|
118
|
+
export { HostRefusedError, InvalidQueryError, SourceMisconfiguredError, UnknownSiteError, UnsupportedFilterError, describeWithCauses, invalidQuery, isHostRefused, isSourceMisconfigured, isUnknownSite, refusedFilter };
|
|
108
119
|
|
|
109
120
|
//# sourceMappingURL=sourceErrors.js.map
|