@10x-media/analytics 1.0.0-beta.14 → 1.0.0-beta.16
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 +55 -0
- package/README.md +1 -1
- package/dist/adapters/ga4/ga4.d.ts +7 -0
- package/dist/adapters/ga4/ga4.js +17 -3
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/plausible/plausible.d.ts +6 -0
- package/dist/adapters/plausible/plausible.js +6 -3
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/cloud.js +20 -0
- package/dist/adapters/posthog/cloud.js.map +1 -0
- package/dist/adapters/posthog/credentials.js +20 -0
- package/dist/adapters/posthog/credentials.js.map +1 -0
- package/dist/adapters/posthog/posthog.d.ts +10 -3
- package/dist/adapters/posthog/posthog.js +100 -27
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/posthog/projectCheck.js +56 -0
- package/dist/adapters/posthog/projectCheck.js.map +1 -0
- package/dist/adapters/umami/umami.d.ts +6 -0
- package/dist/adapters/umami/umami.js +3 -1
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/trackerConfig.js +29 -6
- package/dist/capture/trackerConfig.js.map +1 -1
- package/dist/capture/withoutConsent.js +91 -0
- package/dist/capture/withoutConsent.js.map +1 -0
- package/dist/core/capture.d.ts +41 -11
- package/dist/core/captureOptions.js +97 -8
- package/dist/core/captureOptions.js.map +1 -1
- package/dist/core/contract.d.ts +25 -0
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +24 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/sourceOptions.js +2 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +3 -3
- package/dist/exports/adapters/ga4.d.ts +4 -4
- package/dist/exports/adapters/native.d.ts +5 -5
- package/dist/exports/adapters/plausible.d.ts +4 -4
- package/dist/exports/adapters/posthog.d.ts +4 -4
- package/dist/exports/adapters/umami.d.ts +4 -4
- package/dist/exports/next.d.ts +4 -4
- package/dist/exports/react.d.ts +3 -2
- package/dist/exports/site.d.ts +2 -2
- package/dist/exports/testing.d.ts +4 -4
- package/dist/exports/tracker.d.ts +3 -2
- package/dist/exports/types.d.ts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/native/collections/hits.js +1 -0
- package/dist/native/collections/hits.js.map +1 -1
- package/dist/native/engine/engine.js +5 -1
- package/dist/native/engine/engine.js.map +1 -1
- package/dist/native/engine/planner.js +2 -1
- package/dist/native/engine/planner.js.map +1 -1
- package/dist/native/engine/toHit.js +4 -2
- package/dist/native/engine/toHit.js.map +1 -1
- package/dist/native/ingest/endpoint.js +5 -2
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.d.ts +6 -1
- package/dist/native/ingest/normalizeEvent.js +17 -7
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/serverTrack.js +2 -1
- package/dist/native/ingest/serverTrack.js.map +1 -1
- package/dist/native/ingest/validate.js +3 -0
- package/dist/native/ingest/validate.js.map +1 -1
- package/dist/native/nativeAdapter.d.ts +10 -1
- package/dist/native/nativeAdapter.js +11 -1
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/store/aggregate.js +1 -1
- package/dist/native/store/aggregate.js.map +1 -1
- package/dist/native/store/hitRow.js +3 -0
- package/dist/native/store/hitRow.js.map +1 -1
- package/dist/native/store/hits.js +3 -1
- package/dist/native/store/hits.js.map +1 -1
- package/dist/native/store/mongo/aggregatePipelines.js +10 -2
- package/dist/native/store/mongo/aggregatePipelines.js.map +1 -1
- package/dist/native/store/mongo/pipelines.js +15 -5
- package/dist/native/store/mongo/pipelines.js.map +1 -1
- package/dist/native/store/parts.js +9 -3
- package/dist/native/store/parts.js.map +1 -1
- package/dist/native/store/rawRead.js +6 -3
- package/dist/native/store/rawRead.js.map +1 -1
- package/dist/native/store/sql/aggregateSql.js +6 -2
- package/dist/native/store/sql/aggregateSql.js.map +1 -1
- package/dist/native/store/sql/columns.js +1 -0
- package/dist/native/store/sql/columns.js.map +1 -1
- package/dist/native/store/sql/compile.js +19 -7
- package/dist/native/store/sql/compile.js.map +1 -1
- package/dist/native/store/types.d.ts +7 -1
- package/dist/native/store/types.js +10 -0
- package/dist/native/store/types.js.map +1 -0
- package/dist/plugin/createRuntime.js +10 -1
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/collection.d.ts +2 -0
- package/dist/providers/collection.js +36 -9
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.d.ts +9 -1
- package/dist/providers/factory.js +14 -5
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +14 -6
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/registry.js +2 -1
- package/dist/providers/registry.js.map +1 -1
- package/dist/react/AnalyticsProvider.d.ts +6 -0
- package/dist/react/AnalyticsProvider.js.map +1 -1
- package/dist/react/useAnalytics.js +9 -5
- package/dist/react/useAnalytics.js.map +1 -1
- package/dist/site/AnalyticsScripts.d.ts +4 -3
- package/dist/site/AnalyticsScripts.js +18 -4
- package/dist/site/AnalyticsScripts.js.map +1 -1
- package/dist/surfacing/todaySplit.js +7 -1
- package/dist/surfacing/todaySplit.js.map +1 -1
- package/dist/tracker/config.d.ts +26 -1
- package/dist/tracker/config.js.map +1 -1
- package/dist/tracker/createTracker.d.ts +2 -1
- package/dist/tracker/createTracker.js +91 -59
- package/dist/tracker/createTracker.js.map +1 -1
- package/dist/tracker/gate.d.ts +8 -0
- package/dist/tracker/gate.js +61 -11
- package/dist/tracker/gate.js.map +1 -1
- package/dist/tracker/loadScript.js +2 -1
- package/dist/tracker/loadScript.js.map +1 -1
- package/dist/tracker/registry.js +14 -3
- package/dist/tracker/registry.js.map +1 -1
- package/dist/tracker/sinks/createSink.js +27 -8
- package/dist/tracker/sinks/createSink.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +38 -6
- package/dist/tracker/sinks/ga4.js.map +1 -1
- package/dist/tracker/sinks/native.js +17 -3
- package/dist/tracker/sinks/native.js.map +1 -1
- package/dist/tracker/sinks/plausible.js +8 -2
- package/dist/tracker/sinks/plausible.js.map +1 -1
- package/dist/tracker/sinks/posthog.js +108 -16
- package/dist/tracker/sinks/posthog.js.map +1 -1
- package/dist/tracker/sinks/umami.js +2 -2
- package/dist/tracker/sinks/umami.js.map +1 -1
- package/dist/tracker/sinks/vendor.js +25 -11
- package/dist/tracker/sinks/vendor.js.map +1 -1
- package/dist/tracker/types.d.ts +10 -3
- package/dist/translations/ar.js +10 -0
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +10 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +10 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +10 -0
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +10 -0
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +10 -0
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +10 -0
- package/dist/translations/keys.js +11 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +10 -0
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +10 -0
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +10 -0
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +10 -0
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +10 -0
- package/dist/translations/zh.js.map +1 -1
- package/dist/view/consentShare.js +15 -0
- package/dist/view/consentShare.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +38 -28
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/widgets/notices.js +6 -1
- package/dist/widgets/notices.js.map +1 -1
- package/dist/widgets/readMeta.d.ts +4 -0
- package/dist/widgets/readMeta.js +5 -0
- package/dist/widgets/readMeta.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Access, Payload, PayloadRequest } from 'payload'\nimport { isAdminUser } from '../access/adminUser'\nimport { decideOnce } from '../access/decideOnce'\nimport type { ResolvedBinding } from '../binding/types'\nimport { captureRequest } from '../capture/captureRequest'\nimport type { CacheKeyEpochs } from '../core/cacheKey'\nimport { type AnalyticsAdapter, type AnalyticsResult, PLATFORM_SCOPE } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type {\n\tAnalyticsCountryFlags,\n\tCaptureGatePolicy,\n\tCaptureSlotOption,\n\tCrossScopeAccess,\n\tResolvedExclusion,\n\tResolvedOptions,\n\tScopeCallSite,\n\tScopeLabelResolver,\n\tScopeListResolver,\n\tScopeMemberAccess,\n} from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ResolveRegistryArgs,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { ServerEventInput, ServerTrackOptions } from '../core/serverEvent'\nimport type { DefaultSourceRule, ResolvedSources } from '../core/sourcePolicy'\nimport { isRecord } from '../core/values'\nimport type { GoalsResolver, ResolvedGoal } from '../goals/resolver'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport type { CacheStore } from '../surfacing/cacheStore'\nimport type { CacheSweeper } from '../surfacing/cacheSweep'\nimport type { Engine } from '../surfacing/engine'\nimport { type EpochStore, epochsFor, INITIAL_EPOCH } from '../surfacing/epoch'\nimport type { Memo } from '../surfacing/memo'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport type { ResolvedAutoCapture, TrackerSkip } from '../tracker/config'\nimport { onDestroy } from './destroy'\nimport { requestMemo } from './requestMemo'\nimport { ANALYTICS_CONFIG_KEY } from './routes'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/**\n\t * Never call directly: ask {@link resolveScopeFor} or {@link resolveCaptureScopeFor}, whose\n\t * capture path strips the visitor's identity first. Absent resolves null.\n\t */\n\tresolveScope?: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\t/**\n\t * `scope.member`, set exactly when the install is scoped. A runtime without one admits nobody\n\t * to a tenant scope they did not reach through `access.crossScope`.\n\t */\n\tmember?: ScopeMemberAccess\n\t/** The plugin's reportingTimezone as a resolver; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The plugin's `revenue.currency` as a resolver; absent runtimes and installs that set\n\t * none resolve undefined, and revenue then renders as a plain number.\n\t */\n\tresolveCurrency?: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/**\n\t * `sources`: each shared config adapter whose tenants read under a policy other than `staff`.\n\t * Absent runtimes admit tenants to no shared adapter beyond `unscopedSource`.\n\t */\n\tsourcePolicies?: ResolvedSources['policies']\n\t/** `defaultSource`: how a tenant scope picks its default source; absent keeps the registry's. */\n\tdefaultSource?: DefaultSourceRule\n\t/** `capture.slots` overrides naming the adapter that fills each capture slot. */\n\tcaptureSlots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * `capture.paths` overrides for a slot's mount. Unset, the tracker config derives the\n\t * runtime proxy mount; set when the slot is served through Next rewrites instead.\n\t */\n\tcapturePaths?: { global?: string; tenant?: string }\n\t/**\n\t * `capture.gate`: whether a slot's tracker waits for the host's consent manager, evaluated\n\t * per request-resolved adapter. Absent runtimes hold every slot.\n\t */\n\tcaptureGate?: CaptureGatePolicy\n\t/** Browser auto-capture toggles handed to the tracker; absent runtimes default all on. */\n\tautoCapture?: ResolvedAutoCapture\n\t/** `capture.skip`, resolved; absent runtimes skip everything it can. */\n\tcaptureSkip?: TrackerSkip\n\t/** Config goals, and the fallback wherever the merged resolution is unavailable. */\n\tgoals?: Goal[]\n\t/** `goals.purchase`: whether the resolver adds the built-in `purchase` goal. */\n\tpurchaseGoal?: boolean\n\t/**\n\t * Config goals merged with the goals collection for a request's scope. Absent runtimes\n\t * fall back to `goals`.\n\t */\n\tresolveGoals?: GoalsResolver['resolve']\n\t/** The same merge, each goal tagged with where it came from. */\n\tresolveGoalsDetailed?: GoalsResolver['resolveDetailed']\n\t/**\n\t * The goals a reader's picker lists: collection goals as the collection's read access lets\n\t * the request's user see them. Absent runtimes list what `resolveGoalsDetailed` answers.\n\t */\n\tlistGoals?: GoalsResolver['listReadable']\n\t/** The goals a report spanning every scope names its rows by; see `goalNamesFor`. */\n\tlistGoalsAcross?: GoalsResolver['listAcross']\n\t/** Slug of the goals collection when the install enabled it; the picker links to it. */\n\tgoalsCollectionSlug?: string\n\t/**\n\t * Providers collection when enabled; it makes a scoped install's sources per tenant.\n\t * `sourceAccess` picks which documents a tenant reads through, else the collection's read access.\n\t */\n\tprovidersCollection?: { slug: string; scopeField: string; sourceAccess?: Access }\n\t/**\n\t * Fetch for adapters built from provider documents: every resolved address must be public unless\n\t * `providers.hosts.allowPrivateNetwork`.\n\t */\n\tproviderFetch?: FetchLike\n\t/**\n\t * Releases what the runtime itself holds once it is retired: the adapters built from provider\n\t * documents, then the connections they reached their vendors through.\n\t */\n\tclose?: () => Promise<void>\n\t/**\n\t * Records an event from server code, through whichever registered adapter accepts\n\t * server events. Rejects with an `AnalyticsTrackError` when none does.\n\t */\n\ttrack?: (event: ServerEventInput, opts?: ServerTrackOptions) => Promise<void>\n\t/**\n\t * Where the ingest endpoint listens, relative to `routes.api`, lifted from the adapter that\n\t * registered one. Absent runtimes fall back to the base's own ingest mount.\n\t */\n\tingestPath?: string\n\t/**\n\t * `capture.proxy` limits, separate from `cache.timeoutMs` on purpose: that is a per-read deadline\n\t * for dashboard queries, this a public request path with different traffic.\n\t */\n\tcaptureProxy?: { timeoutMs: number; maxBodyBytes: number }\n\t/** The plugin's `trustedProxyHops`, read wherever a request's client address is. */\n\ttrustedProxyHops?: number\n\t/** The plugin's `trustedPlatform`, read wherever a request's client address is. */\n\ttrustedPlatform?: TrustedPlatform\n\t/**\n\t * `capture.allowedOrigins`, normalized: the other sites whose pages may POST to the public\n\t * capture routes. Absent runtimes admit no cross-site POST at all.\n\t */\n\tallowedOrigins?: ReadonlySet<string>\n\t/** `capture.exclusion` while the link is on; absent while it is off. */\n\texclusion?: ResolvedExclusion\n\t/**\n\t * `access.view`, which also gates handing out the exclusion link the view shows. Absent\n\t * runtimes fall back to the read gate alone.\n\t */\n\tviewAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** True when the app configured `scope.resolve` (scoped install); mirrors `resolved.scoped`. */\n\tscoped?: boolean\n\t/** `scope.label`: names the resolved scope in the view's caption. */\n\tscopeLabel?: ScopeLabelResolver\n\t/** `scope.list`: the scopes a named refresh may bump. */\n\tscopeList?: ScopeListResolver\n\t/** The read cache's collection, when the install keeps its cache there rather than in `cache.store`. */\n\tcacheCollectionSlug?: string\n\t/** `countryFlags`, for the server surfaces that draw a flag outside the view. */\n\tcountryFlags?: boolean | AnalyticsCountryFlags\n\t/**\n\t * Ids of the config-time adapters shared by every scope; runtime provider adapters (from the\n\t * providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/**\n\t * `access.crossScope`, every gate filled at config time. A gate a runtime leaves out (a test\n\t * double, a half-booted install) admits the users of the admin collection.\n\t */\n\tcrossScope?: Partial<Record<ScopeDecision, CrossScopeAccess>>\n\t/**\n\t * `access.read`, asked through `readGate` by every read; absent runtimes admit the users of\n\t * the admin collection.\n\t */\n\treadAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** Each bound collection, with the field its documents carry their scope in. */\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/**\n\t * The per-scope refresh epoch the engine keys on, shared with the reads that build their\n\t * own keys. Absent runtimes key on the initial token throughout.\n\t */\n\tepoch?: EpochStore\n\t/**\n\t * Provider and goal configuration epoch every cache key carries beside the refresh epoch: a hash\n\t * of committed documents, or a token `refreshProviders()` bumps. Absent, one fixed value.\n\t */\n\tconfigEpoch?: (scope?: string | null) => Promise<string>\n\t/**\n\t * Told by the providers and goals collection hooks which scopes a save touched, so this\n\t * instance reads them again as soon as the save commits. Writes nothing.\n\t */\n\tconfigChanged?: (collection: 'providers' | 'goals', scopes: Iterable<string | null>) => void\n\t/** `refreshProviders()`: retires a scope's cached reads on every instance. */\n\trefreshProviders?: (scope: string | null) => Promise<void>\n\t/**\n\t * Whether a scope's own enabled provider documents grant an adapter, decided from their\n\t * committed rows alone: nothing is decrypted. Set on an install running the providers collection.\n\t */\n\tproviderGranted?: (scope: string | null, adapterId: string) => Promise<boolean>\n\t/** The instance's in-process memo, the only place a live count is ever kept. */\n\tmemo?: Memo<AnalyticsResult>\n\t/** Where reads are cached across instances, and what deletes the expired entries. */\n\tcache?: { store: CacheStore; sweeper: CacheSweeper }\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\n\t/** The config adapters this runtime attached to its Payload instance; retiring it closes them. */\n\tadapters?: readonly AnalyticsAdapter[]\n}\n\n/**\n * What the plugin leaves under its key in `config.custom`, which never reaches the client: how\n * to build a runtime for one Payload instance, and the boot checks its `onInit` runs.\n */\nexport interface RuntimeFactory {\n\tcreate: (payload: Payload) => AnalyticsRuntime\n\tvalidate: (payload: Payload) => Promise<void>\n\t/** The options resolved at config time, which the admin view renders with. */\n\tresolved?: ResolvedOptions\n}\n\nconst isRuntimeFactory = (value: unknown): value is RuntimeFactory =>\n\tisRecord(value) && typeof value.create === 'function' && typeof value.validate === 'function'\n\n/** The factory a config carries, absent wherever the plugin is not installed or is disabled. */\nexport const runtimeFactoryOf = (\n\tconfig: { custom?: Record<string, unknown> } | undefined\n): RuntimeFactory | undefined => {\n\tconst factory = config?.custom?.[ANALYTICS_CONFIG_KEY]\n\treturn isRuntimeFactory(factory) ? factory : undefined\n}\n\n/**\n * Stored on the Payload instance (not a module global) so the runtime survives the separate `.`\n * and `/rsc` bundles a consumer loads; `Symbol.for` resolves the same key in both.\n */\nconst RUNTIME_KEY = Symbol.for('@10x-media/analytics/runtime')\n\n/** Runtimes replaced on this instance whose adapters are still waiting out their grace period. */\nconst RETIRING_KEY = Symbol.for('@10x-media/analytics/retiring')\n\n/** How long a replaced runtime keeps serving the requests that already hold it. */\nexport const RUNTIME_RETIRE_GRACE_MS = 30_000\n\n/** A runtime and the exact config object it was built for, which is how a reload is noticed. */\ninterface RuntimeSlot {\n\tconfig: unknown\n\truntime: AnalyticsRuntime | undefined\n}\n\nconst isRuntimeSlot = (value: unknown): value is RuntimeSlot =>\n\tisRecord(value) && 'config' in value && 'runtime' in value\n\nconst slotOf = (payload: Payload): RuntimeSlot | undefined => {\n\tconst slot: unknown = Reflect.get(payload, RUNTIME_KEY)\n\treturn isRuntimeSlot(slot) ? slot : undefined\n}\n\ninterface Retirement {\n\t/** Closes the retired adapters now; later calls share the first one's promise. */\n\trun: () => Promise<void>\n}\n\nconst retiringOf = (payload: Payload): Set<Retirement> => {\n\tconst existing: unknown = Reflect.get(payload, RETIRING_KEY)\n\tif (existing instanceof Set) {\n\t\treturn existing\n\t}\n\tconst created = new Set<Retirement>()\n\tReflect.set(payload, RETIRING_KEY, created)\n\treturn created\n}\n\n/** Runs one close, warning rather than throwing so the closes beside it still run. */\nconst closeOrWarn = async (payload: Payload, what: string, close: () => unknown): Promise<void> => {\n\ttry {\n\t\tawait close()\n\t} catch (err) {\n\t\tpayload.logger?.warn(`analytics: closing ${what} failed: ${String(err)}`)\n\t}\n}\n\n/**\n * After the grace period, closes the retired runtime's resources and every adapter it attached that\n * its successor no longer uses: a shared adapter keeps its buffer and clients.\n */\nconst retire = (\n\tpayload: Payload,\n\tretired: AnalyticsRuntime | undefined,\n\tsuccessor: AnalyticsRuntime | undefined\n): void => {\n\tconst kept = new Set(successor?.adapters ?? [])\n\tconst closing = (retired?.adapters ?? []).filter((adapter) => !kept.has(adapter))\n\tconst closeRuntime = retired?.close\n\tif (closing.length === 0 && !closeRuntime) {\n\t\treturn\n\t}\n\tconst pending = retiringOf(payload)\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\tlet done: Promise<void> | undefined\n\tconst entry: Retirement = {\n\t\trun: () => {\n\t\t\tdone ??= (async () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tpending.delete(entry)\n\t\t\t\tawait Promise.all([\n\t\t\t\t\tcloseOrWarn(payload, \"a replaced runtime's connections\", () => closeRuntime?.()),\n\t\t\t\t\t...closing.map((adapter) =>\n\t\t\t\t\t\tcloseOrWarn(payload, `the \"${adapter.id}\" adapter of a replaced runtime`, () =>\n\t\t\t\t\t\t\tadapter.close?.(payload)\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t})()\n\t\t\treturn done\n\t\t},\n\t}\n\tpending.add(entry)\n\ttimer = setTimeout(() => void entry.run(), RUNTIME_RETIRE_GRACE_MS)\n\ttimer.unref?.()\n}\n\n/** Closes the instance's runtime and every runtime it replaced, at once: the instance is going away. */\nconst closeRuntimes = async (payload: Payload): Promise<void> => {\n\tconst slot = slotOf(payload)\n\tif (slot?.runtime) {\n\t\tretire(payload, slot.runtime, undefined)\n\t}\n\tawait settleRetiredRuntimes(payload)\n}\n\n/**\n * An instance's runtime, built on first use and rebuilt when `payload.config` changes identity (HMR\n * `reload`); undefined without the plugin. Building one makes `payload.destroy()` close it.\n */\nexport const getRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\tif (slot && slot.config === payload.config) {\n\t\treturn slot.runtime\n\t}\n\tconst runtime = runtimeFactoryOf(payload.config)?.create(payload)\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n\tif (slot) {\n\t\tretire(payload, slot.runtime, runtime)\n\t}\n\tif (runtime) {\n\t\tonDestroy(payload, () => closeRuntimes(payload))\n\t}\n\treturn runtime\n}\n\n/** The runtime already built for the instance's current config; unlike `getRuntime`, never builds one. */\nexport const builtRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\treturn slot && slot.config === payload.config ? slot.runtime : undefined\n}\n\n/** Installs a hand-built runtime for the instance's current config, which is what tests need. */\nexport const setRuntime = (payload: Payload, runtime: AnalyticsRuntime): void => {\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n}\n\n/** Closes every replaced runtime's adapters now rather than after the grace period. */\nexport const settleRetiredRuntimes = async (payload: Payload): Promise<void> => {\n\tawait Promise.all([...retiringOf(payload)].map((entry) => entry.run()))\n}\n\nconst scopes = requestMemo<string | null>('scopeResolutions')\nconst timezones = requestMemo<string>('timezoneResolutions')\nconst currencies = requestMemo<string | undefined>('currencyResolutions')\n\n/** A memo key per scope argument, where absent (the request's own scope) and null differ. */\nconst scopeKey = (scope: string | null | undefined): string =>\n\tscope === undefined ? 'own' : JSON.stringify(scope)\n\n/**\n * The scope a per-scope resolver answers for: no timezone, currency, goal or source belongs to the\n * cross-scope marker, so it reads as install-wide.\n */\nexport const resolvableScope = <S extends string | null | undefined>(scope: S): S | null =>\n\tscope === PLATFORM_SCOPE ? null : scope\n\n/**\n * The scope a signed-in reader's or editor's request selected: the `admin` call site, asked of\n * the host's resolver once per request and user however many reads ask.\n */\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => {\n\tconst resolve = runtime.resolveScope\n\tif (!resolve) {\n\t\treturn Promise.resolve(null)\n\t}\n\treturn scopes(req, {\n\t\towner: runtime,\n\t\tkey: 'admin',\n\t\tcompute: async () => {\n\t\t\ttry {\n\t\t\t\treturn await resolve(req, 'admin')\n\t\t\t} catch (err) {\n\t\t\t\t// Said once here rather than by every read the failure reaches.\n\t\t\t\treq.payload?.logger?.warn?.(`analytics: scope resolution failed: ${String(err)}`)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * A visitor hit's scope, asked via {@link captureRequest} so no user, cookie or auth header reaches\n * the resolver: an editor's beacon files under the site, not their admin tenant.\n */\nexport const resolveCaptureScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> =>\n\truntime.resolveScope?.(captureRequest(req), 'capture') ?? Promise.resolve(null)\n\n/** The scope's reporting timezone, asked of the host's resolver once per request, scope and user. */\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => {\n\tconst resolve = runtime.resolveTimezone\n\treturn resolve\n\t\t? timezones(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(DEFAULT_TIMEZONE)\n}\n\n/** The scope's reporting currency, asked of the host's resolver once per request, scope and user. */\nexport const resolveCurrencyFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string | undefined> => {\n\tconst resolve = runtime.resolveCurrency\n\treturn resolve\n\t\t? currencies(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(undefined)\n}\n\n/**\n * Like {@link resolveTimezoneFor} but resolving the request's scope first, for calendar days read\n * before a read begins. UTC without the plugin or when resolution throws.\n */\nexport const requestTimezone = async (req: PayloadRequest): Promise<string> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveTimezoneFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n}\n\n/**\n * A request's reporting currency, resolving its scope first. Undefined without the plugin, without\n * a configured currency, or when resolution throws: revenue then renders as a plain number.\n */\nexport const requestCurrency = async (req: PayloadRequest): Promise<string | undefined> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime?.resolveCurrency) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveCurrencyFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/** The scope's refresh epoch token, the initial one wherever the runtime carries no store. */\nexport const cacheEpochFor = (runtime: AnalyticsRuntime, scope?: string | null): Promise<string> =>\n\truntime.epoch?.get(scope) ?? Promise.resolve(INITIAL_EPOCH)\n\n/** Both epochs the scope's cache keys carry, for a read that builds its own key. */\nexport const cacheEpochsFor = (\n\truntime: AnalyticsRuntime,\n\tscope?: string | null\n): Promise<CacheKeyEpochs> =>\n\tepochsFor(\n\t\t{\n\t\t\t...(runtime.epoch ? { refresh: runtime.epoch } : {}),\n\t\t\t...(runtime.configEpoch ? { config: runtime.configEpoch } : {}),\n\t\t},\n\t\tscope\n\t)\n\n/** The scope's adapter registry; without a per-scope resolver, the config one and no grants. */\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<ScopeRegistry> =>\n\truntime.resolveRegistry?.(args) ??\n\tPromise.resolve({ registry: runtime.registry, grants: NO_GRANTS })\n\n/** The scope's goals: config goals merged with the goals collection, where the runtime can. */\nexport const resolveGoalsFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<Goal[]> => runtime.resolveGoals?.(req, scope) ?? Promise.resolve(runtime.goals ?? [])\n\n/**\n * {@link resolveGoalsFor}'s goals, each tagged with its origin. Falls back to the untagged\n * resolver, not the static config list, so the two never disagree.\n */\nexport const resolveGoalsDetailedFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<ResolvedGoal[]> => {\n\tif (runtime.resolveGoalsDetailed) {\n\t\treturn runtime.resolveGoalsDetailed(req, scope)\n\t}\n\tconst goals = runtime.resolveGoals\n\t\t? await runtime.resolveGoals(req, scope)\n\t\t: (runtime.goals ?? [])\n\treturn goals.map((goal) => ({ goal, source: 'config' as const }))\n}\n\n/**\n * Whether a read in `scope` spans every scope: the aggregate, or the install-wide read a scoped\n * install answers a platform reader who selected no tenant.\n */\nconst readsAcrossScopes = (\n\truntime: Pick<AnalyticsRuntime, 'scoped'>,\n\tscope: string | null | undefined\n): boolean => scope === PLATFORM_SCOPE || ((scope ?? null) === null && runtime.scoped === true)\n\n/**\n * Names a report in `scope` lists goal rows by. A cross-scope report draws on every scope the\n * reader may see, so a foreign goal reads by name; unnamed goals read as slugs.\n */\nexport const goalNamesFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tscope: string | null | undefined\n\t/** The scope's own goals, when the caller already resolved them. */\n\tresolved?: ResolvedGoal[]\n}): Promise<Array<{ slug: string; name: string }>> => {\n\tconst { runtime, req, scope, resolved } = args\n\tconst own = resolved ?? (await resolveGoalsDetailedFor(runtime, req, resolvableScope(scope)))\n\tif (!readsAcrossScopes(runtime, scope) || !runtime.listGoalsAcross) {\n\t\treturn own.map(({ goal }) => ({ slug: goal.slug, name: goal.name }))\n\t}\n\tconst across = await runtime.listGoalsAcross(req)\n\tconst names = new Map(own.map(({ goal }) => [goal.slug, goal.name]))\n\tfor (const { goal } of across) {\n\t\tif (!names.has(goal.slug)) {\n\t\t\tnames.set(goal.slug, goal.name)\n\t\t}\n\t}\n\treturn [...names].map(([slug, name]) => ({ slug, name }))\n}\n\n/** The three cross-scope decisions `access.crossScope` names. */\nexport type ScopeDecision = 'named' | 'aggregate' | 'unscopedSource'\n\n/** What one gate is asked about: the scope (`'*'` or null for every scope) and the adapter. */\nexport interface GateContext {\n\tscope?: string | null\n\tadapterId?: string\n}\n\n/**\n * The three cross-scope decisions for one request, each evaluated at most once per user, scope and\n * adapter however many gates and reads consult it.\n */\nexport type ScopeGates = Record<ScopeDecision, (ctx?: GateContext) => Promise<boolean>>\n\n/**\n * The request's {@link ScopeGates}; a gate `access.crossScope` leaves unset admits the users of the\n * admin collection.\n */\nexport const scopeGates = (runtime: AnalyticsRuntime, req: PayloadRequest): ScopeGates => {\n\tconst gate =\n\t\t(decision: ScopeDecision) =>\n\t\t(ctx: GateContext = {}): Promise<boolean> => {\n\t\t\tconst { scope, adapterId } = ctx\n\t\t\tconst args = {\n\t\t\t\treq,\n\t\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\t\t...(adapterId === undefined ? {} : { adapterId }),\n\t\t\t}\n\t\t\treturn decideOnce(req, {\n\t\t\t\towner: runtime,\n\t\t\t\tkey: `crossScope:${decision}:${JSON.stringify(scope)}:${adapterId ?? ''}`,\n\t\t\t\tdecide: () => runtime.crossScope?.[decision]?.(args) ?? isAdminUser({ req }),\n\t\t\t})\n\t\t}\n\treturn {\n\t\tnamed: gate('named'),\n\t\taggregate: gate('aggregate'),\n\t\tunscopedSource: gate('unscopedSource'),\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAqOA,MAAM,oBAAoB,UACzB,SAAS,KAAK,KAAK,OAAO,MAAM,WAAW,cAAc,OAAO,MAAM,aAAa;;AAGpF,MAAa,oBACZ,WACgC;CAChC,MAAM,UAAU,QAAQ,SAAS;CACjC,OAAO,iBAAiB,OAAO,IAAI,UAAU,KAAA;AAC9C;;;;;AAMA,MAAM,cAAc,OAAO,IAAI,8BAA8B;;AAG7D,MAAM,eAAe,OAAO,IAAI,+BAA+B;;AAG/D,MAAa,0BAA0B;AAQvC,MAAM,iBAAiB,UACtB,SAAS,KAAK,KAAK,YAAY,SAAS,aAAa;AAEtD,MAAM,UAAU,YAA8C;CAC7D,MAAM,OAAgB,QAAQ,IAAI,SAAS,WAAW;CACtD,OAAO,cAAc,IAAI,IAAI,OAAO,KAAA;AACrC;AAOA,MAAM,cAAc,YAA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,MAAM,EAAE,OAAO,cAAc;EAC7B,MAAM,OAAO;GACZ;GACA,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;GACvC,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;EAChD;EACA,OAAO,WAAW,KAAK;GACtB,OAAO;GACP,KAAK,cAAc,SAAS,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG,aAAa;GACrE,cAAc,QAAQ,aAAa,YAAY,IAAI,KAAK,YAAY,EAAE,IAAI,CAAC;EAC5E,CAAC;CACF;CACD,OAAO;EACN,OAAO,KAAK,OAAO;EACnB,WAAW,KAAK,WAAW;EAC3B,gBAAgB,KAAK,gBAAgB;CACtC;AACD"}
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Access, Payload, PayloadRequest } from 'payload'\nimport { isAdminUser } from '../access/adminUser'\nimport { decideOnce } from '../access/decideOnce'\nimport type { ResolvedBinding } from '../binding/types'\nimport { captureRequest } from '../capture/captureRequest'\nimport type { CacheKeyEpochs } from '../core/cacheKey'\nimport { type AnalyticsAdapter, type AnalyticsResult, PLATFORM_SCOPE } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type {\n\tAnalyticsCountryFlags,\n\tCaptureGatePolicy,\n\tCaptureSlotOption,\n\tCrossScopeAccess,\n\tResolvedExclusion,\n\tResolvedOptions,\n\tResolvedWithoutConsent,\n\tScopeCallSite,\n\tScopeLabelResolver,\n\tScopeListResolver,\n\tScopeMemberAccess,\n} from '../core/options'\nimport {\n\ttype AdapterRegistry,\n\tNO_GRANTS,\n\ttype RegistryResolver,\n\ttype ResolveRegistryArgs,\n\ttype ScopeRegistry,\n} from '../core/registry'\nimport type { ServerEventInput, ServerTrackOptions } from '../core/serverEvent'\nimport type { DefaultSourceRule, ResolvedSources } from '../core/sourcePolicy'\nimport { isRecord } from '../core/values'\nimport type { GoalsResolver, ResolvedGoal } from '../goals/resolver'\nimport type { Goal } from '../goals/types'\nimport type { TrustedPlatform } from '../net/platform'\nimport type { CacheStore } from '../surfacing/cacheStore'\nimport type { CacheSweeper } from '../surfacing/cacheSweep'\nimport type { Engine } from '../surfacing/engine'\nimport { type EpochStore, epochsFor, INITIAL_EPOCH } from '../surfacing/epoch'\nimport type { Memo } from '../surfacing/memo'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\nimport type { ResolvedAutoCapture, TrackerSkip } from '../tracker/config'\nimport { onDestroy } from './destroy'\nimport { requestMemo } from './requestMemo'\nimport { ANALYTICS_CONFIG_KEY } from './routes'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/**\n\t * Never call directly: ask {@link resolveScopeFor} or {@link resolveCaptureScopeFor}, whose\n\t * capture path strips the visitor's identity first. Absent resolves null.\n\t */\n\tresolveScope?: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\t/**\n\t * `scope.member`, set exactly when the install is scoped. A runtime without one admits nobody\n\t * to a tenant scope they did not reach through `access.crossScope`.\n\t */\n\tmember?: ScopeMemberAccess\n\t/** The plugin's reportingTimezone as a resolver; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/**\n\t * The plugin's `revenue.currency` as a resolver; absent runtimes and installs that set\n\t * none resolve undefined, and revenue then renders as a plain number.\n\t */\n\tresolveCurrency?: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/**\n\t * `sources`: each shared config adapter whose tenants read under a policy other than `staff`.\n\t * Absent runtimes admit tenants to no shared adapter beyond `unscopedSource`.\n\t */\n\tsourcePolicies?: ResolvedSources['policies']\n\t/** `defaultSource`: how a tenant scope picks its default source; absent keeps the registry's. */\n\tdefaultSource?: DefaultSourceRule\n\t/** `capture.slots` overrides naming the adapter that fills each capture slot. */\n\tcaptureSlots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * `capture.paths` overrides for a slot's mount. Unset, the tracker config derives the\n\t * runtime proxy mount; set when the slot is served through Next rewrites instead.\n\t */\n\tcapturePaths?: { global?: string; tenant?: string }\n\t/**\n\t * `capture.gate`: whether a slot's tracker waits for the host's consent manager, evaluated\n\t * per request-resolved adapter. Absent runtimes hold every slot.\n\t */\n\tcaptureGate?: CaptureGatePolicy\n\t/** `capture.withoutConsent`, resolved; absent while unset, which means `'cookieless'`. */\n\tcaptureWithoutConsent?: ResolvedWithoutConsent\n\t/** Browser auto-capture toggles handed to the tracker; absent runtimes default all on. */\n\tautoCapture?: ResolvedAutoCapture\n\t/** `capture.skip`, resolved; absent runtimes skip everything it can. */\n\tcaptureSkip?: TrackerSkip\n\t/** Config goals, and the fallback wherever the merged resolution is unavailable. */\n\tgoals?: Goal[]\n\t/** `goals.purchase`: whether the resolver adds the built-in `purchase` goal. */\n\tpurchaseGoal?: boolean\n\t/**\n\t * Config goals merged with the goals collection for a request's scope. Absent runtimes\n\t * fall back to `goals`.\n\t */\n\tresolveGoals?: GoalsResolver['resolve']\n\t/** The same merge, each goal tagged with where it came from. */\n\tresolveGoalsDetailed?: GoalsResolver['resolveDetailed']\n\t/**\n\t * The goals a reader's picker lists: collection goals as the collection's read access lets\n\t * the request's user see them. Absent runtimes list what `resolveGoalsDetailed` answers.\n\t */\n\tlistGoals?: GoalsResolver['listReadable']\n\t/** The goals a report spanning every scope names its rows by; see `goalNamesFor`. */\n\tlistGoalsAcross?: GoalsResolver['listAcross']\n\t/** Slug of the goals collection when the install enabled it; the picker links to it. */\n\tgoalsCollectionSlug?: string\n\t/**\n\t * Providers collection when enabled; it makes a scoped install's sources per tenant.\n\t * `sourceAccess` picks which documents a tenant reads through, else the collection's read access.\n\t */\n\tprovidersCollection?: { slug: string; scopeField: string; sourceAccess?: Access }\n\t/**\n\t * Fetch for adapters built from provider documents: every resolved address must be public unless\n\t * `providers.hosts.allowPrivateNetwork`.\n\t */\n\tproviderFetch?: FetchLike\n\t/**\n\t * Releases what the runtime itself holds once it is retired: the adapters built from provider\n\t * documents, then the connections they reached their vendors through.\n\t */\n\tclose?: () => Promise<void>\n\t/**\n\t * Records an event from server code, through whichever registered adapter accepts\n\t * server events. Rejects with an `AnalyticsTrackError` when none does.\n\t */\n\ttrack?: (event: ServerEventInput, opts?: ServerTrackOptions) => Promise<void>\n\t/**\n\t * Where the ingest endpoint listens, relative to `routes.api`, lifted from the adapter that\n\t * registered one. Absent runtimes fall back to the base's own ingest mount.\n\t */\n\tingestPath?: string\n\t/**\n\t * `capture.proxy` limits, separate from `cache.timeoutMs` on purpose: that is a per-read deadline\n\t * for dashboard queries, this a public request path with different traffic.\n\t */\n\tcaptureProxy?: { timeoutMs: number; maxBodyBytes: number }\n\t/** The plugin's `trustedProxyHops`, read wherever a request's client address is. */\n\ttrustedProxyHops?: number\n\t/** The plugin's `trustedPlatform`, read wherever a request's client address is. */\n\ttrustedPlatform?: TrustedPlatform\n\t/**\n\t * `capture.allowedOrigins`, normalized: the other sites whose pages may POST to the public\n\t * capture routes. Absent runtimes admit no cross-site POST at all.\n\t */\n\tallowedOrigins?: ReadonlySet<string>\n\t/** `capture.exclusion` while the link is on; absent while it is off. */\n\texclusion?: ResolvedExclusion\n\t/**\n\t * `access.view`, which also gates handing out the exclusion link the view shows. Absent\n\t * runtimes fall back to the read gate alone.\n\t */\n\tviewAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** True when the app configured `scope.resolve` (scoped install); mirrors `resolved.scoped`. */\n\tscoped?: boolean\n\t/** `scope.label`: names the resolved scope in the view's caption. */\n\tscopeLabel?: ScopeLabelResolver\n\t/** `scope.list`: the scopes a named refresh may bump. */\n\tscopeList?: ScopeListResolver\n\t/** The read cache's collection, when the install keeps its cache there rather than in `cache.store`. */\n\tcacheCollectionSlug?: string\n\t/** `countryFlags`, for the server surfaces that draw a flag outside the view. */\n\tcountryFlags?: boolean | AnalyticsCountryFlags\n\t/**\n\t * Ids of the config-time adapters shared by every scope; runtime provider adapters (from the\n\t * providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/**\n\t * `access.crossScope`, every gate filled at config time. A gate a runtime leaves out (a test\n\t * double, a half-booted install) admits the users of the admin collection.\n\t */\n\tcrossScope?: Partial<Record<ScopeDecision, CrossScopeAccess>>\n\t/**\n\t * `access.read`, asked through `readGate` by every read; absent runtimes admit the users of\n\t * the admin collection.\n\t */\n\treadAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** Each bound collection, with the field its documents carry their scope in. */\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/**\n\t * The per-scope refresh epoch the engine keys on, shared with the reads that build their\n\t * own keys. Absent runtimes key on the initial token throughout.\n\t */\n\tepoch?: EpochStore\n\t/**\n\t * Provider and goal configuration epoch every cache key carries beside the refresh epoch: a hash\n\t * of committed documents, or a token `refreshProviders()` bumps. Absent, one fixed value.\n\t */\n\tconfigEpoch?: (scope?: string | null) => Promise<string>\n\t/**\n\t * Told by the providers and goals collection hooks which scopes a save touched, so this\n\t * instance reads them again as soon as the save commits. Writes nothing.\n\t */\n\tconfigChanged?: (collection: 'providers' | 'goals', scopes: Iterable<string | null>) => void\n\t/** `refreshProviders()`: retires a scope's cached reads on every instance. */\n\trefreshProviders?: (scope: string | null) => Promise<void>\n\t/**\n\t * Whether a scope's own enabled provider documents grant an adapter, decided from their\n\t * committed rows alone: nothing is decrypted. Set on an install running the providers collection.\n\t */\n\tproviderGranted?: (scope: string | null, adapterId: string) => Promise<boolean>\n\t/** The instance's in-process memo, the only place a live count is ever kept. */\n\tmemo?: Memo<AnalyticsResult>\n\t/** Where reads are cached across instances, and what deletes the expired entries. */\n\tcache?: { store: CacheStore; sweeper: CacheSweeper }\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\n\t/** The config adapters this runtime attached to its Payload instance; retiring it closes them. */\n\tadapters?: readonly AnalyticsAdapter[]\n}\n\n/**\n * What the plugin leaves under its key in `config.custom`, which never reaches the client: how\n * to build a runtime for one Payload instance, and the boot checks its `onInit` runs.\n */\nexport interface RuntimeFactory {\n\tcreate: (payload: Payload) => AnalyticsRuntime\n\tvalidate: (payload: Payload) => Promise<void>\n\t/** The options resolved at config time, which the admin view renders with. */\n\tresolved?: ResolvedOptions\n}\n\nconst isRuntimeFactory = (value: unknown): value is RuntimeFactory =>\n\tisRecord(value) && typeof value.create === 'function' && typeof value.validate === 'function'\n\n/** The factory a config carries, absent wherever the plugin is not installed or is disabled. */\nexport const runtimeFactoryOf = (\n\tconfig: { custom?: Record<string, unknown> } | undefined\n): RuntimeFactory | undefined => {\n\tconst factory = config?.custom?.[ANALYTICS_CONFIG_KEY]\n\treturn isRuntimeFactory(factory) ? factory : undefined\n}\n\n/**\n * Stored on the Payload instance (not a module global) so the runtime survives the separate `.`\n * and `/rsc` bundles a consumer loads; `Symbol.for` resolves the same key in both.\n */\nconst RUNTIME_KEY = Symbol.for('@10x-media/analytics/runtime')\n\n/** Runtimes replaced on this instance whose adapters are still waiting out their grace period. */\nconst RETIRING_KEY = Symbol.for('@10x-media/analytics/retiring')\n\n/** How long a replaced runtime keeps serving the requests that already hold it. */\nexport const RUNTIME_RETIRE_GRACE_MS = 30_000\n\n/** A runtime and the exact config object it was built for, which is how a reload is noticed. */\ninterface RuntimeSlot {\n\tconfig: unknown\n\truntime: AnalyticsRuntime | undefined\n}\n\nconst isRuntimeSlot = (value: unknown): value is RuntimeSlot =>\n\tisRecord(value) && 'config' in value && 'runtime' in value\n\nconst slotOf = (payload: Payload): RuntimeSlot | undefined => {\n\tconst slot: unknown = Reflect.get(payload, RUNTIME_KEY)\n\treturn isRuntimeSlot(slot) ? slot : undefined\n}\n\ninterface Retirement {\n\t/** Closes the retired adapters now; later calls share the first one's promise. */\n\trun: () => Promise<void>\n}\n\nconst retiringOf = (payload: Payload): Set<Retirement> => {\n\tconst existing: unknown = Reflect.get(payload, RETIRING_KEY)\n\tif (existing instanceof Set) {\n\t\treturn existing\n\t}\n\tconst created = new Set<Retirement>()\n\tReflect.set(payload, RETIRING_KEY, created)\n\treturn created\n}\n\n/** Runs one close, warning rather than throwing so the closes beside it still run. */\nconst closeOrWarn = async (payload: Payload, what: string, close: () => unknown): Promise<void> => {\n\ttry {\n\t\tawait close()\n\t} catch (err) {\n\t\tpayload.logger?.warn(`analytics: closing ${what} failed: ${String(err)}`)\n\t}\n}\n\n/**\n * After the grace period, closes the retired runtime's resources and every adapter it attached that\n * its successor no longer uses: a shared adapter keeps its buffer and clients.\n */\nconst retire = (\n\tpayload: Payload,\n\tretired: AnalyticsRuntime | undefined,\n\tsuccessor: AnalyticsRuntime | undefined\n): void => {\n\tconst kept = new Set(successor?.adapters ?? [])\n\tconst closing = (retired?.adapters ?? []).filter((adapter) => !kept.has(adapter))\n\tconst closeRuntime = retired?.close\n\tif (closing.length === 0 && !closeRuntime) {\n\t\treturn\n\t}\n\tconst pending = retiringOf(payload)\n\tlet timer: ReturnType<typeof setTimeout> | undefined\n\tlet done: Promise<void> | undefined\n\tconst entry: Retirement = {\n\t\trun: () => {\n\t\t\tdone ??= (async () => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tpending.delete(entry)\n\t\t\t\tawait Promise.all([\n\t\t\t\t\tcloseOrWarn(payload, \"a replaced runtime's connections\", () => closeRuntime?.()),\n\t\t\t\t\t...closing.map((adapter) =>\n\t\t\t\t\t\tcloseOrWarn(payload, `the \"${adapter.id}\" adapter of a replaced runtime`, () =>\n\t\t\t\t\t\t\tadapter.close?.(payload)\n\t\t\t\t\t\t)\n\t\t\t\t\t),\n\t\t\t\t])\n\t\t\t})()\n\t\t\treturn done\n\t\t},\n\t}\n\tpending.add(entry)\n\ttimer = setTimeout(() => void entry.run(), RUNTIME_RETIRE_GRACE_MS)\n\ttimer.unref?.()\n}\n\n/** Closes the instance's runtime and every runtime it replaced, at once: the instance is going away. */\nconst closeRuntimes = async (payload: Payload): Promise<void> => {\n\tconst slot = slotOf(payload)\n\tif (slot?.runtime) {\n\t\tretire(payload, slot.runtime, undefined)\n\t}\n\tawait settleRetiredRuntimes(payload)\n}\n\n/**\n * An instance's runtime, built on first use and rebuilt when `payload.config` changes identity (HMR\n * `reload`); undefined without the plugin. Building one makes `payload.destroy()` close it.\n */\nexport const getRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\tif (slot && slot.config === payload.config) {\n\t\treturn slot.runtime\n\t}\n\tconst runtime = runtimeFactoryOf(payload.config)?.create(payload)\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n\tif (slot) {\n\t\tretire(payload, slot.runtime, runtime)\n\t}\n\tif (runtime) {\n\t\tonDestroy(payload, () => closeRuntimes(payload))\n\t}\n\treturn runtime\n}\n\n/** The runtime already built for the instance's current config; unlike `getRuntime`, never builds one. */\nexport const builtRuntime = (payload: Payload): AnalyticsRuntime | undefined => {\n\tconst slot = slotOf(payload)\n\treturn slot && slot.config === payload.config ? slot.runtime : undefined\n}\n\n/** Installs a hand-built runtime for the instance's current config, which is what tests need. */\nexport const setRuntime = (payload: Payload, runtime: AnalyticsRuntime): void => {\n\tReflect.set(payload, RUNTIME_KEY, { config: payload.config, runtime })\n}\n\n/** Closes every replaced runtime's adapters now rather than after the grace period. */\nexport const settleRetiredRuntimes = async (payload: Payload): Promise<void> => {\n\tawait Promise.all([...retiringOf(payload)].map((entry) => entry.run()))\n}\n\nconst scopes = requestMemo<string | null>('scopeResolutions')\nconst timezones = requestMemo<string>('timezoneResolutions')\nconst currencies = requestMemo<string | undefined>('currencyResolutions')\n\n/** A memo key per scope argument, where absent (the request's own scope) and null differ. */\nconst scopeKey = (scope: string | null | undefined): string =>\n\tscope === undefined ? 'own' : JSON.stringify(scope)\n\n/**\n * The scope a per-scope resolver answers for: no timezone, currency, goal or source belongs to the\n * cross-scope marker, so it reads as install-wide.\n */\nexport const resolvableScope = <S extends string | null | undefined>(scope: S): S | null =>\n\tscope === PLATFORM_SCOPE ? null : scope\n\n/**\n * The scope a signed-in reader's or editor's request selected: the `admin` call site, asked of\n * the host's resolver once per request and user however many reads ask.\n */\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => {\n\tconst resolve = runtime.resolveScope\n\tif (!resolve) {\n\t\treturn Promise.resolve(null)\n\t}\n\treturn scopes(req, {\n\t\towner: runtime,\n\t\tkey: 'admin',\n\t\tcompute: async () => {\n\t\t\ttry {\n\t\t\t\treturn await resolve(req, 'admin')\n\t\t\t} catch (err) {\n\t\t\t\t// Said once here rather than by every read the failure reaches.\n\t\t\t\treq.payload?.logger?.warn?.(`analytics: scope resolution failed: ${String(err)}`)\n\t\t\t\tthrow err\n\t\t\t}\n\t\t},\n\t})\n}\n\n/**\n * A visitor hit's scope, asked via {@link captureRequest} so no user, cookie or auth header reaches\n * the resolver: an editor's beacon files under the site, not their admin tenant.\n */\nexport const resolveCaptureScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> =>\n\truntime.resolveScope?.(captureRequest(req), 'capture') ?? Promise.resolve(null)\n\n/** The scope's reporting timezone, asked of the host's resolver once per request, scope and user. */\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => {\n\tconst resolve = runtime.resolveTimezone\n\treturn resolve\n\t\t? timezones(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(DEFAULT_TIMEZONE)\n}\n\n/** The scope's reporting currency, asked of the host's resolver once per request, scope and user. */\nexport const resolveCurrencyFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string | undefined> => {\n\tconst resolve = runtime.resolveCurrency\n\treturn resolve\n\t\t? currencies(req, { owner: runtime, key: scopeKey(scope), compute: () => resolve(req, scope) })\n\t\t: Promise.resolve(undefined)\n}\n\n/**\n * Like {@link resolveTimezoneFor} but resolving the request's scope first, for calendar days read\n * before a read begins. UTC without the plugin or when resolution throws.\n */\nexport const requestTimezone = async (req: PayloadRequest): Promise<string> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveTimezoneFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n}\n\n/**\n * A request's reporting currency, resolving its scope first. Undefined without the plugin, without\n * a configured currency, or when resolution throws: revenue then renders as a plain number.\n */\nexport const requestCurrency = async (req: PayloadRequest): Promise<string | undefined> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime?.resolveCurrency) {\n\t\treturn undefined\n\t}\n\ttry {\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveCurrencyFor(runtime, req, resolvableScope(scope))\n\t} catch {\n\t\treturn undefined\n\t}\n}\n\n/** The scope's refresh epoch token, the initial one wherever the runtime carries no store. */\nexport const cacheEpochFor = (runtime: AnalyticsRuntime, scope?: string | null): Promise<string> =>\n\truntime.epoch?.get(scope) ?? Promise.resolve(INITIAL_EPOCH)\n\n/** Both epochs the scope's cache keys carry, for a read that builds its own key. */\nexport const cacheEpochsFor = (\n\truntime: AnalyticsRuntime,\n\tscope?: string | null\n): Promise<CacheKeyEpochs> =>\n\tepochsFor(\n\t\t{\n\t\t\t...(runtime.epoch ? { refresh: runtime.epoch } : {}),\n\t\t\t...(runtime.configEpoch ? { config: runtime.configEpoch } : {}),\n\t\t},\n\t\tscope\n\t)\n\n/** The scope's adapter registry; without a per-scope resolver, the config one and no grants. */\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<ScopeRegistry> =>\n\truntime.resolveRegistry?.(args) ??\n\tPromise.resolve({ registry: runtime.registry, grants: NO_GRANTS })\n\n/** The scope's goals: config goals merged with the goals collection, where the runtime can. */\nexport const resolveGoalsFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<Goal[]> => runtime.resolveGoals?.(req, scope) ?? Promise.resolve(runtime.goals ?? [])\n\n/**\n * {@link resolveGoalsFor}'s goals, each tagged with its origin. Falls back to the untagged\n * resolver, not the static config list, so the two never disagree.\n */\nexport const resolveGoalsDetailedFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<ResolvedGoal[]> => {\n\tif (runtime.resolveGoalsDetailed) {\n\t\treturn runtime.resolveGoalsDetailed(req, scope)\n\t}\n\tconst goals = runtime.resolveGoals\n\t\t? await runtime.resolveGoals(req, scope)\n\t\t: (runtime.goals ?? [])\n\treturn goals.map((goal) => ({ goal, source: 'config' as const }))\n}\n\n/**\n * Whether a read in `scope` spans every scope: the aggregate, or the install-wide read a scoped\n * install answers a platform reader who selected no tenant.\n */\nconst readsAcrossScopes = (\n\truntime: Pick<AnalyticsRuntime, 'scoped'>,\n\tscope: string | null | undefined\n): boolean => scope === PLATFORM_SCOPE || ((scope ?? null) === null && runtime.scoped === true)\n\n/**\n * Names a report in `scope` lists goal rows by. A cross-scope report draws on every scope the\n * reader may see, so a foreign goal reads by name; unnamed goals read as slugs.\n */\nexport const goalNamesFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tscope: string | null | undefined\n\t/** The scope's own goals, when the caller already resolved them. */\n\tresolved?: ResolvedGoal[]\n}): Promise<Array<{ slug: string; name: string }>> => {\n\tconst { runtime, req, scope, resolved } = args\n\tconst own = resolved ?? (await resolveGoalsDetailedFor(runtime, req, resolvableScope(scope)))\n\tif (!readsAcrossScopes(runtime, scope) || !runtime.listGoalsAcross) {\n\t\treturn own.map(({ goal }) => ({ slug: goal.slug, name: goal.name }))\n\t}\n\tconst across = await runtime.listGoalsAcross(req)\n\tconst names = new Map(own.map(({ goal }) => [goal.slug, goal.name]))\n\tfor (const { goal } of across) {\n\t\tif (!names.has(goal.slug)) {\n\t\t\tnames.set(goal.slug, goal.name)\n\t\t}\n\t}\n\treturn [...names].map(([slug, name]) => ({ slug, name }))\n}\n\n/** The three cross-scope decisions `access.crossScope` names. */\nexport type ScopeDecision = 'named' | 'aggregate' | 'unscopedSource'\n\n/** What one gate is asked about: the scope (`'*'` or null for every scope) and the adapter. */\nexport interface GateContext {\n\tscope?: string | null\n\tadapterId?: string\n}\n\n/**\n * The three cross-scope decisions for one request, each evaluated at most once per user, scope and\n * adapter however many gates and reads consult it.\n */\nexport type ScopeGates = Record<ScopeDecision, (ctx?: GateContext) => Promise<boolean>>\n\n/**\n * The request's {@link ScopeGates}; a gate `access.crossScope` leaves unset admits the users of the\n * admin collection.\n */\nexport const scopeGates = (runtime: AnalyticsRuntime, req: PayloadRequest): ScopeGates => {\n\tconst gate =\n\t\t(decision: ScopeDecision) =>\n\t\t(ctx: GateContext = {}): Promise<boolean> => {\n\t\t\tconst { scope, adapterId } = ctx\n\t\t\tconst args = {\n\t\t\t\treq,\n\t\t\t\t...(scope === undefined ? {} : { scope }),\n\t\t\t\t...(adapterId === undefined ? {} : { adapterId }),\n\t\t\t}\n\t\t\treturn decideOnce(req, {\n\t\t\t\towner: runtime,\n\t\t\t\tkey: `crossScope:${decision}:${JSON.stringify(scope)}:${adapterId ?? ''}`,\n\t\t\t\tdecide: () => runtime.crossScope?.[decision]?.(args) ?? isAdminUser({ req }),\n\t\t\t})\n\t\t}\n\treturn {\n\t\tnamed: gate('named'),\n\t\taggregate: gate('aggregate'),\n\t\tunscopedSource: gate('unscopedSource'),\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAwOA,MAAM,oBAAoB,UACzB,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AE,MAAM,KAAK;EAAM,MAAM,KAAK;CAAK,EAAE;CAEpE,MAAM,SAAS,MAAM,QAAQ,gBAAgB,GAAG;CAChD,MAAM,QAAQ,IAAI,IAAI,IAAI,KAAK,EAAE,WAAW,CAAC,KAAK,MAAM,KAAK,IAAI,CAAC,CAAC;CACnE,KAAK,MAAM,EAAE,UAAU,QACtB,IAAI,CAAC,MAAM,IAAI,KAAK,IAAI,GACvB,MAAM,IAAI,KAAK,MAAM,KAAK,IAAI;CAGhC,OAAO,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,MAAM,WAAW;EAAE;EAAM;CAAK,EAAE;AACzD;;;;;AAqBA,MAAa,cAAc,SAA2B,QAAoC;CACzF,MAAM,QACJ,cACA,MAAmB,CAAC,MAAwB;EAC5C,MAAM,EAAE,OAAO,cAAc;EAC7B,MAAM,OAAO;GACZ;GACA,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;GACvC,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;EAChD;EACA,OAAO,WAAW,KAAK;GACtB,OAAO;GACP,KAAK,cAAc,SAAS,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG,aAAa;GACrE,cAAc,QAAQ,aAAa,YAAY,IAAI,KAAK,YAAY,EAAE,IAAI,CAAC;EAC5E,CAAC;CACF;CACD,OAAO;EACN,OAAO,KAAK,OAAO;EACnB,WAAW,KAAK,WAAW;EAC3B,gBAAgB,KAAK,gBAAgB;CACtC;AACD"}
|
|
@@ -17,6 +17,8 @@ interface ProviderCollectionFieldOverrides {
|
|
|
17
17
|
enabled?: ProviderFieldOverride;
|
|
18
18
|
/** The "Default for this site" checkbox, which only a scoped install's collection carries. */
|
|
19
19
|
isDefault?: ProviderFieldOverride;
|
|
20
|
+
/** What a vendor source does without consent; empty follows `capture.withoutConsent`. */
|
|
21
|
+
withoutConsent?: ProviderFieldOverride;
|
|
20
22
|
}
|
|
21
23
|
/** Field access on the fields that decide where a provider document connects (`CONNECTION_PATHS`). */
|
|
22
24
|
interface ConnectionFieldAccess {
|
|
@@ -6,10 +6,11 @@ import { asTranslate, labelForKey } from "../translations/server.js";
|
|
|
6
6
|
import { builtInStaticLabel } from "../translations/staticLabel.js";
|
|
7
7
|
import { validateMeasurementId } from "../adapters/ga4/measurementId.js";
|
|
8
8
|
import { validateScriptId } from "../adapters/plausible/scriptId.js";
|
|
9
|
+
import { validatePersonalApiKey, validateProjectToken } from "../adapters/posthog/credentials.js";
|
|
9
10
|
import { validateCurrency } from "../goals/currency.js";
|
|
10
11
|
import { overrideField } from "../plugin/collectionFields.js";
|
|
11
12
|
import { docScope } from "../plugin/scopeChange.js";
|
|
12
|
-
import { validateProviderHost } from "./hosts.js";
|
|
13
|
+
import { validatePosthogHost, validateProviderHost } from "./hosts.js";
|
|
13
14
|
import { PROVIDER_IDS } from "./factory.js";
|
|
14
15
|
import { retargetSecrets } from "./retarget.js";
|
|
15
16
|
import { takenInScope } from "./scopeUnique.js";
|
|
@@ -73,6 +74,7 @@ const secretField = (buildSecret, staticLabel, opts) => buildSecret({
|
|
|
73
74
|
name: opts.name,
|
|
74
75
|
type: "text",
|
|
75
76
|
label: labelForKey(opts.label),
|
|
77
|
+
...opts.validate ? { validate: opts.validate } : {},
|
|
76
78
|
admin: {
|
|
77
79
|
description: staticLabel(opts.help),
|
|
78
80
|
...opts.width ? { width: opts.width } : {}
|
|
@@ -103,11 +105,11 @@ const scopeField = (include) => include ? [{
|
|
|
103
105
|
label: labelForKey(keys.providerFieldScope),
|
|
104
106
|
admin: { hidden: true }
|
|
105
107
|
}] : [];
|
|
106
|
-
const hostField = (allowPrivateNetwork, access) => ({
|
|
108
|
+
const hostField = (allowPrivateNetwork, access, opts = {}) => ({
|
|
107
109
|
name: "host",
|
|
108
110
|
type: "text",
|
|
109
111
|
label: labelForKey(keys.providerFieldHost),
|
|
110
|
-
validate: validateProviderHost(allowPrivateNetwork),
|
|
112
|
+
validate: opts.validate ?? validateProviderHost(allowPrivateNetwork),
|
|
111
113
|
...access ? { access } : {},
|
|
112
114
|
admin: { description: labelForKey(keys.providerFieldHostHelp) }
|
|
113
115
|
});
|
|
@@ -192,6 +194,26 @@ const providerField = (access, staticLabel, types) => {
|
|
|
192
194
|
}
|
|
193
195
|
};
|
|
194
196
|
};
|
|
197
|
+
/**
|
|
198
|
+
* A vendor document's own `withoutConsent`. Unset follows `capture.withoutConsent`; no option
|
|
199
|
+
* stands for that, since an empty string is no portable enum value.
|
|
200
|
+
*/
|
|
201
|
+
const withoutConsentField = (staticLabel) => ({
|
|
202
|
+
name: "withoutConsent",
|
|
203
|
+
type: "select",
|
|
204
|
+
label: labelForKey(keys.providerFieldWithoutConsent),
|
|
205
|
+
options: [{
|
|
206
|
+
label: staticLabel(keys.providerWithoutConsentCookieless),
|
|
207
|
+
value: "cookieless"
|
|
208
|
+
}, {
|
|
209
|
+
label: staticLabel(keys.providerWithoutConsentOff),
|
|
210
|
+
value: "off"
|
|
211
|
+
}],
|
|
212
|
+
admin: {
|
|
213
|
+
condition: (data) => isOneOf(PROVIDER_IDS, data?.provider) && data?.provider !== "native",
|
|
214
|
+
description: staticLabel(keys.providerFieldWithoutConsentHelp)
|
|
215
|
+
}
|
|
216
|
+
});
|
|
195
217
|
const enabledField = () => ({
|
|
196
218
|
name: "enabled",
|
|
197
219
|
type: "checkbox",
|
|
@@ -244,11 +266,12 @@ const providerFields = (options, staticLabel, list) => {
|
|
|
244
266
|
const buildSecret = options.buildSecret ?? plainSecret;
|
|
245
267
|
const access = connectionFieldAccess("analyticsProviderFields({ connectionAccess })", options.connectionAccess);
|
|
246
268
|
const allowPrivateNetwork = options.allowPrivateNetwork === true;
|
|
247
|
-
const apiKeyField = () => secretField(buildSecret, staticLabel, {
|
|
269
|
+
const apiKeyField = (validate) => secretField(buildSecret, staticLabel, {
|
|
248
270
|
name: "apiKey",
|
|
249
271
|
label: keys.providerFieldApiKey,
|
|
250
272
|
help: keys.providerFieldApiKeyHelp,
|
|
251
|
-
width: "50%"
|
|
273
|
+
width: "50%",
|
|
274
|
+
...validate ? { validate } : {}
|
|
252
275
|
});
|
|
253
276
|
return [
|
|
254
277
|
overrideField(nameField(), options.fields?.name),
|
|
@@ -329,11 +352,14 @@ const providerFields = (options, staticLabel, list) => {
|
|
|
329
352
|
width: "50%",
|
|
330
353
|
help: keys.providerFieldProjectIdHelp,
|
|
331
354
|
access
|
|
332
|
-
}), ...apiKeyField()]
|
|
355
|
+
}), ...apiKeyField(validatePersonalApiKey)]
|
|
333
356
|
},
|
|
334
357
|
{
|
|
335
358
|
type: "row",
|
|
336
|
-
fields: [captureField("projectToken", keys.providerFieldProjectToken, {
|
|
359
|
+
fields: [captureField("projectToken", keys.providerFieldProjectToken, {
|
|
360
|
+
width: "50%",
|
|
361
|
+
validate: validateProjectToken
|
|
362
|
+
}), {
|
|
337
363
|
name: "region",
|
|
338
364
|
type: "select",
|
|
339
365
|
label: labelForKey(keys.providerFieldRegion),
|
|
@@ -355,8 +381,9 @@ const providerFields = (options, staticLabel, list) => {
|
|
|
355
381
|
help: keys.providerFieldScopePropertyHelp,
|
|
356
382
|
access
|
|
357
383
|
}),
|
|
358
|
-
hostField(allowPrivateNetwork, access)
|
|
359
|
-
])
|
|
384
|
+
hostField(allowPrivateNetwork, access, { validate: validatePosthogHost(allowPrivateNetwork) })
|
|
385
|
+
]),
|
|
386
|
+
overrideField(withoutConsentField(staticLabel), options.fields?.withoutConsent)
|
|
360
387
|
];
|
|
361
388
|
};
|
|
362
389
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"collection.js","names":[],"sources":["../../src/providers/collection.ts"],"sourcesContent":["import {\n\ttype CollectionBeforeValidateHook,\n\ttype CollectionConfig,\n\ttype Field,\n\ttype FieldAccess,\n\ttype PayloadRequest,\n\ttype SelectField,\n\ttype SelectFieldSingleValidation,\n\ttype TextareaField,\n\ttype TextField,\n\ttype TextFieldSingleValidation,\n\tValidationError,\n\tvalidations,\n} from 'payload'\nimport { validateMeasurementId } from '../adapters/ga4/measurementId'\nimport { validateScriptId } from '../adapters/plausible/scriptId'\nimport { optionsObject } from '../core/optionChecks'\nimport { isOneOf, kindOf, listOf } from '../core/values'\nimport { validateCurrency } from '../goals/currency'\nimport { type CollectionFieldOverride, overrideField } from '../plugin/collectionFields'\nimport { docScope, type ScopeChange } from '../plugin/scopeChange'\nimport { keys, type SingularKey, type TranslationKey } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { builtInStaticLabel, type StaticLabelFor } from '../translations/staticLabel'\nimport { type ProviderAccessArgs, providerCreateAccess, providerRowAccess } from './access'\nimport { PROVIDER_IDS, type ProviderId } from './factory'\nimport { validateProviderHost } from './hosts'\nimport { retargetSecrets } from './retarget'\nimport { takenInScope } from './scopeUnique'\nimport { stampScope } from './stampScope'\n\nexport const PROVIDERS_SLUG = 'analytics-providers'\n\n/** The list's note to a tenant reading the platform's source in `fallback`. */\nexport const PROVIDERS_LIST_NOTICE_COMPONENT = '@10x-media/analytics/client#ProvidersListNotice'\n\n/** Builds the sealed variant of a secret source field; injected so the fields peer stays lazy. */\nexport type BuildSecretField = (source: TextField | TextareaField) => Field[]\n\n/**\n * Replaces a default field; it receives the plugin's own field to spread and may return any field\n * type (a `row`, a `collapsible`) that still holds a field of that name.\n */\nexport type ProviderFieldOverride = CollectionFieldOverride\n\nexport interface ProviderCollectionFieldOverrides {\n\tname?: ProviderFieldOverride\n\tprovider?: ProviderFieldOverride\n\tenabled?: ProviderFieldOverride\n\t/** The \"Default for this site\" checkbox, which only a scoped install's collection carries. */\n\tisDefault?: ProviderFieldOverride\n}\n\n/** Field access on the fields that decide where a provider document connects (`CONNECTION_PATHS`). */\nexport interface ConnectionFieldAccess {\n\tcreate?: FieldAccess\n\tupdate?: FieldAccess\n}\n\n/** One field access function for create and update alike, or `{ create, update }`. */\nexport type ConnectionAccess = FieldAccess | ConnectionFieldAccess\n\n/** `connectionAccess` in its object form, checked at boot; undefined while unset. */\nexport const connectionFieldAccess = (\n\tpath: string,\n\toption: ConnectionAccess | undefined\n): ConnectionFieldAccess | undefined => {\n\tif (option === undefined) {\n\t\treturn undefined\n\t}\n\tif (typeof option === 'function') {\n\t\treturn { create: option, update: option }\n\t}\n\tconst halves = optionsObject(option, {\n\t\tpath,\n\t\tknown: ['create', 'update'],\n\t\texample: 'a function, or { create, update } with a function in each',\n\t})\n\tfor (const [half, access] of Object.entries(halves)) {\n\t\tif (access !== undefined && typeof access !== 'function') {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path}.${half} must be a field access function, got ${kindOf(access)}`\n\t\t\t)\n\t\t}\n\t}\n\tconst { create, update } = option\n\treturn { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n}\n\n/**\n * The provider types documents may be saved with: every type `available` serves, narrowed to\n * `option` in its order when given, checked at boot.\n */\nexport const servedProviderTypes = (\n\tpath: string,\n\toption: unknown,\n\tavailable: readonly ProviderId[] = PROVIDER_IDS\n): ProviderId[] => {\n\tif (option === undefined) {\n\t\treturn [...available]\n\t}\n\tif (!Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} must be a list of provider types such as ['plausible', 'umami'], got ${kindOf(option)}`\n\t\t)\n\t}\n\tconst listed: ProviderId[] = []\n\tfor (const type of option) {\n\t\tif (!isOneOf(PROVIDER_IDS, type)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path} lists ${kindOf(type)}, which is no provider type; use ${listOf(PROVIDER_IDS.map((id) => `\"${id}\"`))}`\n\t\t\t)\n\t\t}\n\t\tlisted.push(type)\n\t}\n\tconst served = [...new Set(listed)].filter((type) => available.includes(type))\n\tif (served.length === 0) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} leaves no provider type this install serves, which are ${listOf(available.map((id) => `\"${id}\"`))}; \"native\" needs native() in adapters`\n\t\t)\n\t}\n\treturn served\n}\n\nexport interface BuildProvidersCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\t/** Per-field overrides, applied before the whole-collection `overrides`. */\n\tfields?: ProviderCollectionFieldOverrides\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/**\n\t * Called after any change or delete with the scopes the write touched and the request that\n\t * wrote, so that request's own Payload instance reads those scopes again once the write commits.\n\t */\n\tonChange: (change: ScopeChange, req: PayloadRequest) => void | Promise<void>\n\tbuildSecret: BuildSecretField\n\t/** The fields plugin's test for a sealed value, which tells a resent secret from a kept one. */\n\tisSealed: (value: unknown) => boolean\n\t/** `providers.hosts.allowPrivateNetwork`: the `host` fields accept `http://` too. */\n\tallowPrivateNetwork?: boolean\n\tconnectionAccess?: ConnectionFieldAccess\n\t/** The provider types a document may be saved with; every type when absent. */\n\ttypes?: readonly ProviderId[]\n\t/** Field access on `isDefault`, which a scoped install's collection carries. */\n\tdefaultAccess?: ConnectionFieldAccess\n\t/** The install's static labels; the built-in strings alone when absent. */\n\tstaticLabel?: StaticLabelFor\n\t/** Mount the list's note on the platform fallback, for an install with a `fallback` policy. */\n\tlistNotice?: boolean\n}\n\nconst plainSecret: BuildSecretField = (source) => [source]\n\nconst textField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; help?: TranslationKey; access?: ConnectionFieldAccess } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.access ? { access: opts.access } : {}),\n\t...(opts.width || opts.help\n\t\t? {\n\t\t\t\tadmin: {\n\t\t\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t\t\t\t...(opts.help ? { description: labelForKey(opts.help) } : {}),\n\t\t\t\t},\n\t\t\t}\n\t\t: {}),\n})\n\n/**\n * A sealed credential. Its help is a string per locale: Payload drops a function description from\n * the client field, which the write-only editor renders.\n */\nconst secretField = (\n\tbuildSecret: BuildSecretField,\n\tstaticLabel: StaticLabelFor,\n\topts: { name: string; label: TranslationKey; help: SingularKey; width?: string }\n): Field[] =>\n\tbuildSecret({\n\t\tname: opts.name,\n\t\ttype: 'text',\n\t\tlabel: labelForKey(opts.label),\n\t\tadmin: {\n\t\t\tdescription: staticLabel(opts.help),\n\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t},\n\t})\n\n/**\n * Public capture config, plain text because the tracker config serves it to the browser. An adapter\n * declares `capture` only once its public field is filled.\n */\nconst captureField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; validate?: TextFieldSingleValidation; help?: TranslationKey } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.validate ? { validate: opts.validate } : {}),\n\tadmin: {\n\t\tdescription: labelForKey(opts.help ?? keys.providerFieldCaptureHelp),\n\t\t...(opts.width ? { width: opts.width } : {}),\n\t},\n})\n\n/**\n * Only when `scopeField` names the plugin's own field: a host-owned scope field is the host's to\n * register, and shadowing it would store the scope twice.\n */\nconst scopeField = (include: boolean): Field[] =>\n\tinclude\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst hostField = (\n\tallowPrivateNetwork: boolean,\n\taccess: ConnectionFieldAccess | undefined\n): Field => ({\n\tname: 'host',\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldHost),\n\tvalidate: validateProviderHost(allowPrivateNetwork),\n\t...(access ? { access } : {}),\n\tadmin: { description: labelForKey(keys.providerFieldHostHelp) },\n})\n\nconst currencyField = (name: string, help: TranslationKey): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldRevenueCurrency),\n\tvalidate: validateCurrency,\n\tadmin: { description: labelForKey(help) },\n})\n\nconst providerGroup = (provider: ProviderId, label: TranslationKey, fields: Field[]): Field => ({\n\tname: provider,\n\ttype: 'group',\n\tlabel: labelForKey(label),\n\tadmin: { condition: (data) => data?.provider === provider },\n\tfields,\n})\n\n/**\n * The native choice configures nothing, so it gets a note in place of a settings group:\n * an unnamed group stores no data and reads as the section its siblings occupy.\n */\nconst nativeNote = (): Field => ({\n\ttype: 'group',\n\tlabel: labelForKey(keys.providerNameNative),\n\tadmin: {\n\t\tcondition: (data) => data?.provider === 'native',\n\t\tdescription: labelForKey(keys.providerNameNativeHelp),\n\t},\n\tfields: [],\n})\n\nconst nameField = (): Field => ({\n\tname: 'name',\n\ttype: 'text',\n\trequired: true,\n\tlabel: labelForKey(keys.providerFieldName),\n\tadmin: { description: labelForKey(keys.providerFieldNameHelp) },\n})\n\nconst PROVIDER_NAMES: Record<ProviderId, TranslationKey> = {\n\tnative: keys.providerNameNative,\n\tplausible: keys.providerNamePlausible,\n\tumami: keys.providerNameUmami,\n\tga4: keys.providerNameGa4,\n\tposthog: keys.providerNamePosthog,\n}\n\n/**\n * Names the refusal of a stored type the install no longer serves (native() removed, `types`\n * narrowed), which the select's own check would only call an invalid selection.\n */\nconst validateServed =\n\t(types: readonly string[]): SelectFieldSingleValidation =>\n\t(value, options) =>\n\t\ttypeof value === 'string' && value !== '' && !types.includes(value)\n\t\t\t? asTranslate(options.req.t)(keys.providerErrorTypeUnserved)\n\t\t\t: validations.select(value, options)\n\n/**\n * The values a narrowed select offers: the served types, and a stored type no longer served so its\n * save is refused by name. Values only, since form state carries the result to the client, where\n * a label function cannot cross; Payload's select reads nothing else from it.\n */\nconst offeredTypes = (types: readonly ProviderId[], stored: unknown): ProviderId[] =>\n\tisOneOf(PROVIDER_IDS, stored) && !types.includes(stored) ? [...types, stored] : [...types]\n\n/**\n * Sits in the sidebar with `enabled`: every body field is conditional on the provider and\n * meaningless while `enabled` is off. The schema keeps every type (options, groups, a static\n * default while `native` leads), so narrowing the offer neither alters a column nor drops settings.\n */\nconst providerField = (\n\taccess: ConnectionFieldAccess | undefined,\n\tstaticLabel: StaticLabelFor,\n\ttypes: readonly ProviderId[]\n): SelectField => {\n\tconst [first = 'native'] = types\n\tconst narrowed = types.length < PROVIDER_IDS.length\n\treturn {\n\t\tname: 'provider',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\tlabel: labelForKey(keys.providerFieldProvider),\n\t\tdefaultValue: first === 'native' ? first : () => first,\n\t\t...(access ? { access } : {}),\n\t\t...(narrowed\n\t\t\t? {\n\t\t\t\t\tvalidate: validateServed(types),\n\t\t\t\t\tfilterOptions: ({ data }) => offeredTypes(types, data?.provider),\n\t\t\t\t}\n\t\t\t: {}),\n\t\toptions: PROVIDER_IDS.map((type) => ({\n\t\t\tlabel: labelForKey(PROVIDER_NAMES[type]),\n\t\t\tvalue: type,\n\t\t})),\n\t\t// `admin.description` on a select is read where a label function never runs.\n\t\tadmin: { position: 'sidebar', description: staticLabel(keys.providerFieldProviderHelp) },\n\t}\n}\n\nconst enabledField = (): Field => ({\n\tname: 'enabled',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.providerFieldEnabled),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldEnabledHelp) },\n})\n\nconst isDefaultField = (access: ConnectionFieldAccess | undefined): Field => ({\n\tname: 'isDefault',\n\ttype: 'checkbox',\n\tdefaultValue: false,\n\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t...(access ? { access } : {}),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldIsDefaultHelp) },\n})\n\n/**\n * At most one document per scope is the default, checked at collection level so a replaced\n * `isDefault` field keeps it. No index backs it: a unique one would also cover the unflagged rows.\n */\nconst checkSingleDefault = (args: BuildProvidersCollectionArgs): CollectionBeforeValidateHook => {\n\treturn async ({ data, originalDoc, req }) => {\n\t\tif ((data?.isDefault ?? originalDoc?.isDefault) !== true) {\n\t\t\treturn data\n\t\t}\n\t\tif (await takenInScope(args, { data, originalDoc, req }, { isDefault: { equals: true } })) {\n\t\t\tthrow new ValidationError({\n\t\t\t\tcollection: args.slug,\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t\t\t\t\t\tmessage: asTranslate(req.t)(keys.providerErrorDefaultTaken),\n\t\t\t\t\t\tpath: 'isDefault',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\treturn data\n\t}\n}\n\nexport interface ProviderFieldsOptions {\n\t/**\n\t * Seals each credential field, normally `encryptedField` from `@10x-media/fields` in write-only\n\t * mode. Left out, credentials are plain text and securing them is the host's job.\n\t */\n\tbuildSecret?: BuildSecretField\n\t/** Replaces one of the default fields, applied per field. */\n\tfields?: Omit<ProviderCollectionFieldOverrides, 'isDefault'>\n\t/** Adds the plugin's own hidden `scope` text field. Off by default. */\n\tscopeField?: boolean\n\t/**\n\t * Accepts `http://` in a `host` field, for a vendor on a private network. Set it together with\n\t * `providers.hosts.allowPrivateNetwork`, which lets the plugin connect there. Off, https only.\n\t */\n\tallowPrivateNetwork?: boolean\n\t/**\n\t * Field access on every `CONNECTION_PATHS` field except the scope field. One function for create\n\t * and update alike, or `{ create, update }`.\n\t */\n\tconnectionAccess?: ConnectionAccess\n\t/**\n\t * The provider types the select offers, the first being its default; a document saved with any\n\t * other type is refused. Default: every type, `native` first.\n\t */\n\ttypes?: ProviderId[]\n}\n\n/** What the field list takes beyond the public options. */\ninterface FieldListArgs {\n\ttypes: readonly ProviderId[]\n\t/** The `isDefault` checkbox, overridden, placed after `enabled`; only a scoped collection has it. */\n\tisDefault?: Field\n}\n\n/**\n * Provider-settings fields alone, for a host that stores them elsewhere and feeds them back through\n * `providers.resolve`; {@link adapterFromProviderDoc} reads the result as is.\n */\nexport const analyticsProviderFields = (options: ProviderFieldsOptions = {}): Field[] =>\n\tproviderFields(options, builtInStaticLabel, {\n\t\ttypes: servedProviderTypes('analyticsProviderFields({ types })', options.types),\n\t})\n\nconst providerFields = (\n\toptions: ProviderFieldsOptions,\n\tstaticLabel: StaticLabelFor,\n\tlist: FieldListArgs\n): Field[] => {\n\tconst buildSecret = options.buildSecret ?? plainSecret\n\tconst access = connectionFieldAccess(\n\t\t'analyticsProviderFields({ connectionAccess })',\n\t\toptions.connectionAccess\n\t)\n\tconst allowPrivateNetwork = options.allowPrivateNetwork === true\n\tconst apiKeyField = (): Field[] =>\n\t\tsecretField(buildSecret, staticLabel, {\n\t\t\tname: 'apiKey',\n\t\t\tlabel: keys.providerFieldApiKey,\n\t\t\thelp: keys.providerFieldApiKeyHelp,\n\t\t\twidth: '50%',\n\t\t})\n\treturn [\n\t\toverrideField(nameField(), options.fields?.name),\n\t\toverrideField(providerField(access, staticLabel, list.types), options.fields?.provider),\n\t\toverrideField(enabledField(), options.fields?.enabled),\n\t\t...(list.isDefault ? [list.isDefault] : []),\n\t\t...scopeField(options.scopeField === true),\n\t\tnativeNote(),\n\t\tproviderGroup('plausible', keys.providerNamePlausible, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('siteId', keys.providerFieldSiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldSiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('domain', keys.providerFieldDomain, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldDomainHelp,\n\t\t\t\t\t}),\n\t\t\t\t\tcaptureField('scriptId', keys.providerFieldScriptId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldScriptIdHelp,\n\t\t\t\t\t\tvalidate: validateScriptId,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\tcurrencyField('revenueCurrency', keys.providerFieldRevenueCurrencyHelp),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('umami', keys.providerNameUmami, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('websiteId', keys.providerFieldWebsiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldWebsiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t...secretField(buildSecret, staticLabel, {\n\t\t\t\tname: 'token',\n\t\t\t\tlabel: keys.providerFieldToken,\n\t\t\t\thelp: keys.providerFieldTokenHelp,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('ga4', keys.providerNameGa4, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('propertyId', keys.providerFieldPropertyId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldPropertyIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('clientEmail', keys.providerFieldClientEmail, {\n\t\t\t\thelp: keys.providerFieldClientEmailHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\tcaptureField('measurementId', keys.providerFieldMeasurementId, {\n\t\t\t\tvalidate: validateMeasurementId,\n\t\t\t}),\n\t\t\tcurrencyField('currency', keys.providerFieldGa4CurrencyHelp),\n\t\t\t...buildSecret({\n\t\t\t\tname: 'privateKey',\n\t\t\t\ttype: 'textarea',\n\t\t\t\tlabel: labelForKey(keys.providerFieldPrivateKey),\n\t\t\t\tadmin: { description: staticLabel(keys.providerFieldPrivateKeyHelp) },\n\t\t\t}),\n\t\t]),\n\t\tproviderGroup('posthog', keys.providerNamePosthog, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('projectToken', keys.providerFieldProjectToken, { width: '50%' }),\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'region',\n\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldRegion),\n\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t{ label: 'US', value: 'us' },\n\t\t\t\t\t\t\t{ label: 'EU', value: 'eu' },\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(access ? { access } : {}),\n\t\t\t\t\t\tadmin: {\n\t\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\t\tdescription: staticLabel(keys.providerFieldRegionHelp),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('scopeProperty', keys.providerFieldScopeProperty, {\n\t\t\t\thelp: keys.providerFieldScopePropertyHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t]\n}\n\n/**\n * Runtime provider-settings collection, one document per provider (and scope). Admin-only by\n * default; `access` overrides single operations, `overrides` reshapes the whole config last.\n */\nexport const buildProvidersCollection = (args: BuildProvidersCollectionArgs): CollectionConfig => {\n\tconst staticLabel = args.staticLabel ?? builtInStaticLabel\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.providersCollectionSingular),\n\t\t\tplural: labelForKey(keys.providersCollectionPlural),\n\t\t},\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'provider', 'enabled'],\n\t\t\tgroup: staticLabel(keys.adminGroup),\n\t\t\tdescription: staticLabel(keys.providersCollectionDescription),\n\t\t\t...(args.listNotice ? { components: { beforeList: [PROVIDERS_LIST_NOTICE_COMPONENT] } } : {}),\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\t...(args.scoped ? { beforeValidate: [checkSingleDefault(args)] } : {}),\n\t\t\tbeforeChange: [\n\t\t\t\tstampScope(args),\n\t\t\t\tretargetSecrets({ scopeField: args.scopeField, isSealed: args.isSealed }),\n\t\t\t],\n\t\t\tafterChange: [\n\t\t\t\tasync ({ doc, operation, previousDoc, req }) => {\n\t\t\t\t\tawait args.onChange(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tscope: docScope(doc, args.scopeField),\n\t\t\t\t\t\t\t...(operation === 'update'\n\t\t\t\t\t\t\t\t? { previousScope: docScope(previousDoc, args.scopeField) }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\treq\n\t\t\t\t\t)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\tasync ({ doc, req }) => {\n\t\t\t\t\tawait args.onChange({ scope: docScope(doc, args.scopeField) }, req)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields: providerFields(\n\t\t\t{\n\t\t\t\tbuildSecret: args.buildSecret,\n\t\t\t\t...(args.fields ? { fields: args.fields } : {}),\n\t\t\t\tscopeField: args.scopeField === 'scope',\n\t\t\t\tallowPrivateNetwork: args.allowPrivateNetwork === true,\n\t\t\t\t...(args.connectionAccess ? { connectionAccess: args.connectionAccess } : {}),\n\t\t\t},\n\t\t\tstaticLabel,\n\t\t\t{\n\t\t\t\ttypes: args.types ?? PROVIDER_IDS,\n\t\t\t\t// A default is picked per scope: an unscoped install has one site and nothing to pick.\n\t\t\t\t...(args.scoped\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tisDefault: overrideField(isDefaultField(args.defaultAccess), args.fields?.isDefault),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t}\n\t\t),\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+BA,MAAa,iBAAiB;;AAG9B,MAAa,kCAAkC;;AA6B/C,MAAa,yBACZ,MACA,WACuC;CACvC,IAAI,WAAW,KAAA,GACd;CAED,IAAI,OAAO,WAAW,YACrB,OAAO;EAAE,QAAQ;EAAQ,QAAQ;CAAO;CAEzC,MAAM,SAAS,cAAc,QAAQ;EACpC;EACA,OAAO,CAAC,UAAU,QAAQ;EAC1B,SAAS;CACV,CAAC;CACD,KAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,MAAM,GACjD,IAAI,WAAW,KAAA,KAAa,OAAO,WAAW,YAC7C,MAAM,IAAI,MACT,cAAc,KAAK,GAAG,KAAK,wCAAwC,OAAO,MAAM,GACjF;CAGF,MAAM,EAAE,QAAQ,WAAW;CAC3B,OAAO;EAAE,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAAI,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;CAAG;AACvE;;;;;AAMA,MAAa,uBACZ,MACA,QACA,YAAmC,iBACjB;CAClB,IAAI,WAAW,KAAA,GACd,OAAO,CAAC,GAAG,SAAS;CAErB,IAAI,CAAC,MAAM,QAAQ,MAAM,GACxB,MAAM,IAAI,MACT,cAAc,KAAK,wEAAwE,OAAO,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,CAAC,CACzE;GACA,aAAa,CACZ,OAAO,EAAE,KAAK,WAAW,aAAa,UAAU;IAC/C,MAAM,KAAK,SACV;KACC,OAAO,SAAS,KAAK,KAAK,UAAU;KACpC,GAAI,cAAc,WACf,EAAE,eAAe,SAAS,aAAa,KAAK,UAAU,EAAE,IACxD,CAAC;IACL,GACA,GACD;IACA,OAAO;GACR,CACD;GACA,aAAa,CACZ,OAAO,EAAE,KAAK,UAAU;IACvB,MAAM,KAAK,SAAS,EAAE,OAAO,SAAS,KAAK,KAAK,UAAU,EAAE,GAAG,GAAG;IAClE,OAAO;GACR,CACD;EACD;EACA,QAAQ,eACP;GACC,aAAa,KAAK;GAClB,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;GAC7C,YAAY,KAAK,eAAe;GAChC,qBAAqB,KAAK,wBAAwB;GAClD,GAAI,KAAK,mBAAmB,EAAE,kBAAkB,KAAK,iBAAiB,IAAI,CAAC;EAC5E,GACA,aACA;GACC,OAAO,KAAK,SAAS;GAErB,GAAI,KAAK,SACN,EACA,WAAW,cAAc,eAAe,KAAK,aAAa,GAAG,KAAK,QAAQ,SAAS,EACpF,IACC,CAAC;EACL,CACD;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
|
|
1
|
+
{"version":3,"file":"collection.js","names":[],"sources":["../../src/providers/collection.ts"],"sourcesContent":["import {\n\ttype CollectionBeforeValidateHook,\n\ttype CollectionConfig,\n\ttype Field,\n\ttype FieldAccess,\n\ttype PayloadRequest,\n\ttype SelectField,\n\ttype SelectFieldSingleValidation,\n\ttype TextareaField,\n\ttype TextField,\n\ttype TextFieldSingleValidation,\n\tValidationError,\n\tvalidations,\n} from 'payload'\nimport { validateMeasurementId } from '../adapters/ga4/measurementId'\nimport { validateScriptId } from '../adapters/plausible/scriptId'\nimport { validatePersonalApiKey, validateProjectToken } from '../adapters/posthog/credentials'\nimport { optionsObject } from '../core/optionChecks'\nimport { isOneOf, kindOf, listOf } from '../core/values'\nimport { validateCurrency } from '../goals/currency'\nimport { type CollectionFieldOverride, overrideField } from '../plugin/collectionFields'\nimport { docScope, type ScopeChange } from '../plugin/scopeChange'\nimport { keys, type SingularKey, type TranslationKey } from '../translations/keys'\nimport { asTranslate, labelForKey } from '../translations/server'\nimport { builtInStaticLabel, type StaticLabelFor } from '../translations/staticLabel'\nimport { type ProviderAccessArgs, providerCreateAccess, providerRowAccess } from './access'\nimport { PROVIDER_IDS, type ProviderId } from './factory'\nimport { validatePosthogHost, validateProviderHost } from './hosts'\nimport { retargetSecrets } from './retarget'\nimport { takenInScope } from './scopeUnique'\nimport { stampScope } from './stampScope'\n\nexport const PROVIDERS_SLUG = 'analytics-providers'\n\n/** The list's note to a tenant reading the platform's source in `fallback`. */\nexport const PROVIDERS_LIST_NOTICE_COMPONENT = '@10x-media/analytics/client#ProvidersListNotice'\n\n/** Builds the sealed variant of a secret source field; injected so the fields peer stays lazy. */\nexport type BuildSecretField = (source: TextField | TextareaField) => Field[]\n\n/**\n * Replaces a default field; it receives the plugin's own field to spread and may return any field\n * type (a `row`, a `collapsible`) that still holds a field of that name.\n */\nexport type ProviderFieldOverride = CollectionFieldOverride\n\nexport interface ProviderCollectionFieldOverrides {\n\tname?: ProviderFieldOverride\n\tprovider?: ProviderFieldOverride\n\tenabled?: ProviderFieldOverride\n\t/** The \"Default for this site\" checkbox, which only a scoped install's collection carries. */\n\tisDefault?: ProviderFieldOverride\n\t/** What a vendor source does without consent; empty follows `capture.withoutConsent`. */\n\twithoutConsent?: ProviderFieldOverride\n}\n\n/** Field access on the fields that decide where a provider document connects (`CONNECTION_PATHS`). */\nexport interface ConnectionFieldAccess {\n\tcreate?: FieldAccess\n\tupdate?: FieldAccess\n}\n\n/** One field access function for create and update alike, or `{ create, update }`. */\nexport type ConnectionAccess = FieldAccess | ConnectionFieldAccess\n\n/** `connectionAccess` in its object form, checked at boot; undefined while unset. */\nexport const connectionFieldAccess = (\n\tpath: string,\n\toption: ConnectionAccess | undefined\n): ConnectionFieldAccess | undefined => {\n\tif (option === undefined) {\n\t\treturn undefined\n\t}\n\tif (typeof option === 'function') {\n\t\treturn { create: option, update: option }\n\t}\n\tconst halves = optionsObject(option, {\n\t\tpath,\n\t\tknown: ['create', 'update'],\n\t\texample: 'a function, or { create, update } with a function in each',\n\t})\n\tfor (const [half, access] of Object.entries(halves)) {\n\t\tif (access !== undefined && typeof access !== 'function') {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path}.${half} must be a field access function, got ${kindOf(access)}`\n\t\t\t)\n\t\t}\n\t}\n\tconst { create, update } = option\n\treturn { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n}\n\n/**\n * The provider types documents may be saved with: every type `available` serves, narrowed to\n * `option` in its order when given, checked at boot.\n */\nexport const servedProviderTypes = (\n\tpath: string,\n\toption: unknown,\n\tavailable: readonly ProviderId[] = PROVIDER_IDS\n): ProviderId[] => {\n\tif (option === undefined) {\n\t\treturn [...available]\n\t}\n\tif (!Array.isArray(option)) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} must be a list of provider types such as ['plausible', 'umami'], got ${kindOf(option)}`\n\t\t)\n\t}\n\tconst listed: ProviderId[] = []\n\tfor (const type of option) {\n\t\tif (!isOneOf(PROVIDER_IDS, type)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: ${path} lists ${kindOf(type)}, which is no provider type; use ${listOf(PROVIDER_IDS.map((id) => `\"${id}\"`))}`\n\t\t\t)\n\t\t}\n\t\tlisted.push(type)\n\t}\n\tconst served = [...new Set(listed)].filter((type) => available.includes(type))\n\tif (served.length === 0) {\n\t\tthrow new Error(\n\t\t\t`analytics: ${path} leaves no provider type this install serves, which are ${listOf(available.map((id) => `\"${id}\"`))}; \"native\" needs native() in adapters`\n\t\t)\n\t}\n\treturn served\n}\n\nexport interface BuildProvidersCollectionArgs extends ProviderAccessArgs {\n\tslug: string\n\taccess?: Partial<CollectionConfig['access']>\n\t/** Per-field overrides, applied before the whole-collection `overrides`. */\n\tfields?: ProviderCollectionFieldOverrides\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t/**\n\t * Called after any change or delete with the scopes the write touched and the request that\n\t * wrote, so that request's own Payload instance reads those scopes again once the write commits.\n\t */\n\tonChange: (change: ScopeChange, req: PayloadRequest) => void | Promise<void>\n\tbuildSecret: BuildSecretField\n\t/** The fields plugin's test for a sealed value, which tells a resent secret from a kept one. */\n\tisSealed: (value: unknown) => boolean\n\t/** `providers.hosts.allowPrivateNetwork`: the `host` fields accept `http://` too. */\n\tallowPrivateNetwork?: boolean\n\tconnectionAccess?: ConnectionFieldAccess\n\t/** The provider types a document may be saved with; every type when absent. */\n\ttypes?: readonly ProviderId[]\n\t/** Field access on `isDefault`, which a scoped install's collection carries. */\n\tdefaultAccess?: ConnectionFieldAccess\n\t/** The install's static labels; the built-in strings alone when absent. */\n\tstaticLabel?: StaticLabelFor\n\t/** Mount the list's note on the platform fallback, for an install with a `fallback` policy. */\n\tlistNotice?: boolean\n}\n\nconst plainSecret: BuildSecretField = (source) => [source]\n\nconst textField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; help?: TranslationKey; access?: ConnectionFieldAccess } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.access ? { access: opts.access } : {}),\n\t...(opts.width || opts.help\n\t\t? {\n\t\t\t\tadmin: {\n\t\t\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t\t\t\t...(opts.help ? { description: labelForKey(opts.help) } : {}),\n\t\t\t\t},\n\t\t\t}\n\t\t: {}),\n})\n\n/**\n * A sealed credential. Its help is a string per locale: Payload drops a function description from\n * the client field, which the write-only editor renders.\n */\nconst secretField = (\n\tbuildSecret: BuildSecretField,\n\tstaticLabel: StaticLabelFor,\n\topts: {\n\t\tname: string\n\t\tlabel: TranslationKey\n\t\thelp: SingularKey\n\t\twidth?: string\n\t\tvalidate?: TextFieldSingleValidation\n\t}\n): Field[] =>\n\tbuildSecret({\n\t\tname: opts.name,\n\t\ttype: 'text',\n\t\tlabel: labelForKey(opts.label),\n\t\t...(opts.validate ? { validate: opts.validate } : {}),\n\t\tadmin: {\n\t\t\tdescription: staticLabel(opts.help),\n\t\t\t...(opts.width ? { width: opts.width } : {}),\n\t\t},\n\t})\n\n/**\n * Public capture config, plain text because the tracker config serves it to the browser. An adapter\n * declares `capture` only once its public field is filled.\n */\nconst captureField = (\n\tname: string,\n\tlabel: TranslationKey,\n\topts: { width?: string; validate?: TextFieldSingleValidation; help?: TranslationKey } = {}\n): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(label),\n\t...(opts.validate ? { validate: opts.validate } : {}),\n\tadmin: {\n\t\tdescription: labelForKey(opts.help ?? keys.providerFieldCaptureHelp),\n\t\t...(opts.width ? { width: opts.width } : {}),\n\t},\n})\n\n/**\n * Only when `scopeField` names the plugin's own field: a host-owned scope field is the host's to\n * register, and shadowing it would store the scope twice.\n */\nconst scopeField = (include: boolean): Field[] =>\n\tinclude\n\t\t? [\n\t\t\t\t{\n\t\t\t\t\t// Written by scoped setups; hidden because single-site installs never touch it.\n\t\t\t\t\tname: 'scope',\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\tindex: true,\n\t\t\t\t\tlabel: labelForKey(keys.providerFieldScope),\n\t\t\t\t\tadmin: { hidden: true },\n\t\t\t\t},\n\t\t\t]\n\t\t: []\n\nconst hostField = (\n\tallowPrivateNetwork: boolean,\n\taccess: ConnectionFieldAccess | undefined,\n\topts: { validate?: TextFieldSingleValidation } = {}\n): Field => ({\n\tname: 'host',\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldHost),\n\tvalidate: opts.validate ?? validateProviderHost(allowPrivateNetwork),\n\t...(access ? { access } : {}),\n\tadmin: { description: labelForKey(keys.providerFieldHostHelp) },\n})\n\nconst currencyField = (name: string, help: TranslationKey): Field => ({\n\tname,\n\ttype: 'text',\n\tlabel: labelForKey(keys.providerFieldRevenueCurrency),\n\tvalidate: validateCurrency,\n\tadmin: { description: labelForKey(help) },\n})\n\nconst providerGroup = (provider: ProviderId, label: TranslationKey, fields: Field[]): Field => ({\n\tname: provider,\n\ttype: 'group',\n\tlabel: labelForKey(label),\n\tadmin: { condition: (data) => data?.provider === provider },\n\tfields,\n})\n\n/**\n * The native choice configures nothing, so it gets a note in place of a settings group:\n * an unnamed group stores no data and reads as the section its siblings occupy.\n */\nconst nativeNote = (): Field => ({\n\ttype: 'group',\n\tlabel: labelForKey(keys.providerNameNative),\n\tadmin: {\n\t\tcondition: (data) => data?.provider === 'native',\n\t\tdescription: labelForKey(keys.providerNameNativeHelp),\n\t},\n\tfields: [],\n})\n\nconst nameField = (): Field => ({\n\tname: 'name',\n\ttype: 'text',\n\trequired: true,\n\tlabel: labelForKey(keys.providerFieldName),\n\tadmin: { description: labelForKey(keys.providerFieldNameHelp) },\n})\n\nconst PROVIDER_NAMES: Record<ProviderId, TranslationKey> = {\n\tnative: keys.providerNameNative,\n\tplausible: keys.providerNamePlausible,\n\tumami: keys.providerNameUmami,\n\tga4: keys.providerNameGa4,\n\tposthog: keys.providerNamePosthog,\n}\n\n/**\n * Names the refusal of a stored type the install no longer serves (native() removed, `types`\n * narrowed), which the select's own check would only call an invalid selection.\n */\nconst validateServed =\n\t(types: readonly string[]): SelectFieldSingleValidation =>\n\t(value, options) =>\n\t\ttypeof value === 'string' && value !== '' && !types.includes(value)\n\t\t\t? asTranslate(options.req.t)(keys.providerErrorTypeUnserved)\n\t\t\t: validations.select(value, options)\n\n/**\n * The values a narrowed select offers: the served types, and a stored type no longer served so its\n * save is refused by name. Values only, since form state carries the result to the client, where\n * a label function cannot cross; Payload's select reads nothing else from it.\n */\nconst offeredTypes = (types: readonly ProviderId[], stored: unknown): ProviderId[] =>\n\tisOneOf(PROVIDER_IDS, stored) && !types.includes(stored) ? [...types, stored] : [...types]\n\n/**\n * Sits in the sidebar with `enabled`: every body field is conditional on the provider and\n * meaningless while `enabled` is off. The schema keeps every type (options, groups, a static\n * default while `native` leads), so narrowing the offer neither alters a column nor drops settings.\n */\nconst providerField = (\n\taccess: ConnectionFieldAccess | undefined,\n\tstaticLabel: StaticLabelFor,\n\ttypes: readonly ProviderId[]\n): SelectField => {\n\tconst [first = 'native'] = types\n\tconst narrowed = types.length < PROVIDER_IDS.length\n\treturn {\n\t\tname: 'provider',\n\t\ttype: 'select',\n\t\trequired: true,\n\t\tlabel: labelForKey(keys.providerFieldProvider),\n\t\tdefaultValue: first === 'native' ? first : () => first,\n\t\t...(access ? { access } : {}),\n\t\t...(narrowed\n\t\t\t? {\n\t\t\t\t\tvalidate: validateServed(types),\n\t\t\t\t\tfilterOptions: ({ data }) => offeredTypes(types, data?.provider),\n\t\t\t\t}\n\t\t\t: {}),\n\t\toptions: PROVIDER_IDS.map((type) => ({\n\t\t\tlabel: labelForKey(PROVIDER_NAMES[type]),\n\t\t\tvalue: type,\n\t\t})),\n\t\t// `admin.description` on a select is read where a label function never runs.\n\t\tadmin: { position: 'sidebar', description: staticLabel(keys.providerFieldProviderHelp) },\n\t}\n}\n\n/**\n * A vendor document's own `withoutConsent`. Unset follows `capture.withoutConsent`; no option\n * stands for that, since an empty string is no portable enum value.\n */\nconst withoutConsentField = (staticLabel: StaticLabelFor): SelectField => ({\n\tname: 'withoutConsent',\n\ttype: 'select',\n\tlabel: labelForKey(keys.providerFieldWithoutConsent),\n\toptions: [\n\t\t{ label: staticLabel(keys.providerWithoutConsentCookieless), value: 'cookieless' },\n\t\t{ label: staticLabel(keys.providerWithoutConsentOff), value: 'off' },\n\t],\n\tadmin: {\n\t\tcondition: (data) => isOneOf(PROVIDER_IDS, data?.provider) && data?.provider !== 'native',\n\t\tdescription: staticLabel(keys.providerFieldWithoutConsentHelp),\n\t},\n})\n\nconst enabledField = (): Field => ({\n\tname: 'enabled',\n\ttype: 'checkbox',\n\tdefaultValue: true,\n\tlabel: labelForKey(keys.providerFieldEnabled),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldEnabledHelp) },\n})\n\nconst isDefaultField = (access: ConnectionFieldAccess | undefined): Field => ({\n\tname: 'isDefault',\n\ttype: 'checkbox',\n\tdefaultValue: false,\n\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t...(access ? { access } : {}),\n\tadmin: { position: 'sidebar', description: labelForKey(keys.providerFieldIsDefaultHelp) },\n})\n\n/**\n * At most one document per scope is the default, checked at collection level so a replaced\n * `isDefault` field keeps it. No index backs it: a unique one would also cover the unflagged rows.\n */\nconst checkSingleDefault = (args: BuildProvidersCollectionArgs): CollectionBeforeValidateHook => {\n\treturn async ({ data, originalDoc, req }) => {\n\t\tif ((data?.isDefault ?? originalDoc?.isDefault) !== true) {\n\t\t\treturn data\n\t\t}\n\t\tif (await takenInScope(args, { data, originalDoc, req }, { isDefault: { equals: true } })) {\n\t\t\tthrow new ValidationError({\n\t\t\t\tcollection: args.slug,\n\t\t\t\terrors: [\n\t\t\t\t\t{\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldIsDefault),\n\t\t\t\t\t\tmessage: asTranslate(req.t)(keys.providerErrorDefaultTaken),\n\t\t\t\t\t\tpath: 'isDefault',\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})\n\t\t}\n\t\treturn data\n\t}\n}\n\nexport interface ProviderFieldsOptions {\n\t/**\n\t * Seals each credential field, normally `encryptedField` from `@10x-media/fields` in write-only\n\t * mode. Left out, credentials are plain text and securing them is the host's job.\n\t */\n\tbuildSecret?: BuildSecretField\n\t/** Replaces one of the default fields, applied per field. */\n\tfields?: Omit<ProviderCollectionFieldOverrides, 'isDefault'>\n\t/** Adds the plugin's own hidden `scope` text field. Off by default. */\n\tscopeField?: boolean\n\t/**\n\t * Accepts `http://` in a `host` field, for a vendor on a private network. Set it together with\n\t * `providers.hosts.allowPrivateNetwork`, which lets the plugin connect there. Off, https only.\n\t */\n\tallowPrivateNetwork?: boolean\n\t/**\n\t * Field access on every `CONNECTION_PATHS` field except the scope field. One function for create\n\t * and update alike, or `{ create, update }`.\n\t */\n\tconnectionAccess?: ConnectionAccess\n\t/**\n\t * The provider types the select offers, the first being its default; a document saved with any\n\t * other type is refused. Default: every type, `native` first.\n\t */\n\ttypes?: ProviderId[]\n}\n\n/** What the field list takes beyond the public options. */\ninterface FieldListArgs {\n\ttypes: readonly ProviderId[]\n\t/** The `isDefault` checkbox, overridden, placed after `enabled`; only a scoped collection has it. */\n\tisDefault?: Field\n}\n\n/**\n * Provider-settings fields alone, for a host that stores them elsewhere and feeds them back through\n * `providers.resolve`; {@link adapterFromProviderDoc} reads the result as is.\n */\nexport const analyticsProviderFields = (options: ProviderFieldsOptions = {}): Field[] =>\n\tproviderFields(options, builtInStaticLabel, {\n\t\ttypes: servedProviderTypes('analyticsProviderFields({ types })', options.types),\n\t})\n\nconst providerFields = (\n\toptions: ProviderFieldsOptions,\n\tstaticLabel: StaticLabelFor,\n\tlist: FieldListArgs\n): Field[] => {\n\tconst buildSecret = options.buildSecret ?? plainSecret\n\tconst access = connectionFieldAccess(\n\t\t'analyticsProviderFields({ connectionAccess })',\n\t\toptions.connectionAccess\n\t)\n\tconst allowPrivateNetwork = options.allowPrivateNetwork === true\n\tconst apiKeyField = (validate?: TextFieldSingleValidation): Field[] =>\n\t\tsecretField(buildSecret, staticLabel, {\n\t\t\tname: 'apiKey',\n\t\t\tlabel: keys.providerFieldApiKey,\n\t\t\thelp: keys.providerFieldApiKeyHelp,\n\t\t\twidth: '50%',\n\t\t\t...(validate ? { validate } : {}),\n\t\t})\n\treturn [\n\t\toverrideField(nameField(), options.fields?.name),\n\t\toverrideField(providerField(access, staticLabel, list.types), options.fields?.provider),\n\t\toverrideField(enabledField(), options.fields?.enabled),\n\t\t...(list.isDefault ? [list.isDefault] : []),\n\t\t...scopeField(options.scopeField === true),\n\t\tnativeNote(),\n\t\tproviderGroup('plausible', keys.providerNamePlausible, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('siteId', keys.providerFieldSiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldSiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('domain', keys.providerFieldDomain, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldDomainHelp,\n\t\t\t\t\t}),\n\t\t\t\t\tcaptureField('scriptId', keys.providerFieldScriptId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldScriptIdHelp,\n\t\t\t\t\t\tvalidate: validateScriptId,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\tcurrencyField('revenueCurrency', keys.providerFieldRevenueCurrencyHelp),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('umami', keys.providerNameUmami, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('websiteId', keys.providerFieldWebsiteId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldWebsiteIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(),\n\t\t\t\t],\n\t\t\t},\n\t\t\t...secretField(buildSecret, staticLabel, {\n\t\t\t\tname: 'token',\n\t\t\t\tlabel: keys.providerFieldToken,\n\t\t\t\thelp: keys.providerFieldTokenHelp,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access),\n\t\t]),\n\t\tproviderGroup('ga4', keys.providerNameGa4, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('propertyId', keys.providerFieldPropertyId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldPropertyIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('clientEmail', keys.providerFieldClientEmail, {\n\t\t\t\thelp: keys.providerFieldClientEmailHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\tcaptureField('measurementId', keys.providerFieldMeasurementId, {\n\t\t\t\tvalidate: validateMeasurementId,\n\t\t\t}),\n\t\t\tcurrencyField('currency', keys.providerFieldGa4CurrencyHelp),\n\t\t\t...buildSecret({\n\t\t\t\tname: 'privateKey',\n\t\t\t\ttype: 'textarea',\n\t\t\t\tlabel: labelForKey(keys.providerFieldPrivateKey),\n\t\t\t\tadmin: { description: staticLabel(keys.providerFieldPrivateKeyHelp) },\n\t\t\t}),\n\t\t]),\n\t\tproviderGroup('posthog', keys.providerNamePosthog, [\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\ttextField('projectId', keys.providerFieldProjectId, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\thelp: keys.providerFieldProjectIdHelp,\n\t\t\t\t\t\taccess,\n\t\t\t\t\t}),\n\t\t\t\t\t...apiKeyField(validatePersonalApiKey),\n\t\t\t\t],\n\t\t\t},\n\t\t\t{\n\t\t\t\ttype: 'row',\n\t\t\t\tfields: [\n\t\t\t\t\tcaptureField('projectToken', keys.providerFieldProjectToken, {\n\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\tvalidate: validateProjectToken,\n\t\t\t\t\t}),\n\t\t\t\t\t{\n\t\t\t\t\t\tname: 'region',\n\t\t\t\t\t\ttype: 'select',\n\t\t\t\t\t\tlabel: labelForKey(keys.providerFieldRegion),\n\t\t\t\t\t\toptions: [\n\t\t\t\t\t\t\t{ label: 'US', value: 'us' },\n\t\t\t\t\t\t\t{ label: 'EU', value: 'eu' },\n\t\t\t\t\t\t],\n\t\t\t\t\t\t...(access ? { access } : {}),\n\t\t\t\t\t\tadmin: {\n\t\t\t\t\t\t\twidth: '50%',\n\t\t\t\t\t\t\tdescription: staticLabel(keys.providerFieldRegionHelp),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t},\n\t\t\ttextField('scopeProperty', keys.providerFieldScopeProperty, {\n\t\t\t\thelp: keys.providerFieldScopePropertyHelp,\n\t\t\t\taccess,\n\t\t\t}),\n\t\t\thostField(allowPrivateNetwork, access, {\n\t\t\t\tvalidate: validatePosthogHost(allowPrivateNetwork),\n\t\t\t}),\n\t\t]),\n\t\toverrideField(withoutConsentField(staticLabel), options.fields?.withoutConsent),\n\t]\n}\n\n/**\n * Runtime provider-settings collection, one document per provider (and scope). Admin-only by\n * default; `access` overrides single operations, `overrides` reshapes the whole config last.\n */\nexport const buildProvidersCollection = (args: BuildProvidersCollectionArgs): CollectionConfig => {\n\tconst staticLabel = args.staticLabel ?? builtInStaticLabel\n\tconst collection: CollectionConfig = {\n\t\tslug: args.slug,\n\t\tlabels: {\n\t\t\tsingular: labelForKey(keys.providersCollectionSingular),\n\t\t\tplural: labelForKey(keys.providersCollectionPlural),\n\t\t},\n\t\tdisableDuplicate: true,\n\t\tadmin: {\n\t\t\tuseAsTitle: 'name',\n\t\t\tdefaultColumns: ['name', 'provider', 'enabled'],\n\t\t\tgroup: staticLabel(keys.adminGroup),\n\t\t\tdescription: staticLabel(keys.providersCollectionDescription),\n\t\t\t...(args.listNotice ? { components: { beforeList: [PROVIDERS_LIST_NOTICE_COMPONENT] } } : {}),\n\t\t},\n\t\taccess: {\n\t\t\tread: providerRowAccess(args),\n\t\t\tcreate: providerCreateAccess(args),\n\t\t\tupdate: providerRowAccess(args),\n\t\t\tdelete: providerRowAccess(args),\n\t\t\t...args.access,\n\t\t},\n\t\thooks: {\n\t\t\t...(args.scoped ? { beforeValidate: [checkSingleDefault(args)] } : {}),\n\t\t\tbeforeChange: [\n\t\t\t\tstampScope(args),\n\t\t\t\tretargetSecrets({ scopeField: args.scopeField, isSealed: args.isSealed }),\n\t\t\t],\n\t\t\tafterChange: [\n\t\t\t\tasync ({ doc, operation, previousDoc, req }) => {\n\t\t\t\t\tawait args.onChange(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tscope: docScope(doc, args.scopeField),\n\t\t\t\t\t\t\t...(operation === 'update'\n\t\t\t\t\t\t\t\t? { previousScope: docScope(previousDoc, args.scopeField) }\n\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t},\n\t\t\t\t\t\treq\n\t\t\t\t\t)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t\tafterDelete: [\n\t\t\t\tasync ({ doc, req }) => {\n\t\t\t\t\tawait args.onChange({ scope: docScope(doc, args.scopeField) }, req)\n\t\t\t\t\treturn doc\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tfields: providerFields(\n\t\t\t{\n\t\t\t\tbuildSecret: args.buildSecret,\n\t\t\t\t...(args.fields ? { fields: args.fields } : {}),\n\t\t\t\tscopeField: args.scopeField === 'scope',\n\t\t\t\tallowPrivateNetwork: args.allowPrivateNetwork === true,\n\t\t\t\t...(args.connectionAccess ? { connectionAccess: args.connectionAccess } : {}),\n\t\t\t},\n\t\t\tstaticLabel,\n\t\t\t{\n\t\t\t\ttypes: args.types ?? PROVIDER_IDS,\n\t\t\t\t// A default is picked per scope: an unscoped install has one site and nothing to pick.\n\t\t\t\t...(args.scoped\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tisDefault: overrideField(isDefaultField(args.defaultAccess), args.fields?.isDefault),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t}\n\t\t),\n\t}\n\treturn args.overrides ? args.overrides(collection) : collection\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA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BAAmB,IAAI,CAAC,EAAE,IAAI,CAAC;GACpE,cAAc,CACb,WAAW,IAAI,GACf,gBAAgB;IAAE,YAAY,KAAK;IAAY,UAAU,KAAK;GAAS,CAAC,CACzE;GACA,aAAa,CACZ,OAAO,EAAE,KAAK,WAAW,aAAa,UAAU;IAC/C,MAAM,KAAK,SACV;KACC,OAAO,SAAS,KAAK,KAAK,UAAU;KACpC,GAAI,cAAc,WACf,EAAE,eAAe,SAAS,aAAa,KAAK,UAAU,EAAE,IACxD,CAAC;IACL,GACA,GACD;IACA,OAAO;GACR,CACD;GACA,aAAa,CACZ,OAAO,EAAE,KAAK,UAAU;IACvB,MAAM,KAAK,SAAS,EAAE,OAAO,SAAS,KAAK,KAAK,UAAU,EAAE,GAAG,GAAG;IAClE,OAAO;GACR,CACD;EACD;EACA,QAAQ,eACP;GACC,aAAa,KAAK;GAClB,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;GAC7C,YAAY,KAAK,eAAe;GAChC,qBAAqB,KAAK,wBAAwB;GAClD,GAAI,KAAK,mBAAmB,EAAE,kBAAkB,KAAK,iBAAiB,IAAI,CAAC;EAC5E,GACA,aACA;GACC,OAAO,KAAK,SAAS;GAErB,GAAI,KAAK,SACN,EACA,WAAW,cAAc,eAAe,KAAK,aAAa,GAAG,KAAK,QAAQ,SAAS,EACpF,IACC,CAAC;EACL,CACD;CACD;CACA,OAAO,KAAK,YAAY,KAAK,UAAU,UAAU,IAAI;AACtD"}
|
|
@@ -12,7 +12,8 @@ type ProviderDoc = {
|
|
|
12
12
|
name?: string | null;
|
|
13
13
|
provider?: string | null;
|
|
14
14
|
enabled?: boolean | null;
|
|
15
|
-
scope?: string | null;
|
|
15
|
+
scope?: string | null; /** A vendor document's own level without consent; unset or blank follows the install. */
|
|
16
|
+
withoutConsent?: string | null;
|
|
16
17
|
plausible?: {
|
|
17
18
|
siteId?: string | null;
|
|
18
19
|
apiKey?: string | null;
|
|
@@ -65,6 +66,13 @@ interface ProviderFactoryContext {
|
|
|
65
66
|
native?: AnalyticsAdapter;
|
|
66
67
|
/** The plugin's `sdks`: a GA4 document's adapter reads through `sdks.ga4`. */
|
|
67
68
|
sdks?: AnalyticsSdks;
|
|
69
|
+
/**
|
|
70
|
+
* False when no slot `capture.gate` holds can fall to a document's adapter: it is then off
|
|
71
|
+
* without consent, whatever the document says.
|
|
72
|
+
*/
|
|
73
|
+
heldWithoutConsent?: boolean;
|
|
74
|
+
/** False when `capture.withoutConsent` is `'off'` in both phases: a document following it is off. */
|
|
75
|
+
followingCountsWithoutConsent?: boolean;
|
|
68
76
|
}
|
|
69
77
|
/**
|
|
70
78
|
* Builds a provider document's adapter: missing credentials read as `isConfigured() === false`, an
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { isRecord } from "../core/values.js";
|
|
1
|
+
import { isOneOf, isRecord } from "../core/values.js";
|
|
2
2
|
import { HostRefusedError } from "../core/sourceErrors.js";
|
|
3
3
|
import { withFixedLabel } from "../core/sourceLabel.js";
|
|
4
|
+
import { WITHOUT_CONSENT_LEVELS } from "../capture/withoutConsent.js";
|
|
4
5
|
import { ga4 } from "../adapters/ga4/ga4.js";
|
|
5
6
|
import { plausible } from "../adapters/plausible/plausible.js";
|
|
6
7
|
import { posthog } from "../adapters/posthog/posthog.js";
|
|
@@ -16,6 +17,8 @@ const PROVIDER_IDS = [
|
|
|
16
17
|
];
|
|
17
18
|
/** A stored blank reads as unset. */
|
|
18
19
|
const orUndefined = (value) => value || void 0;
|
|
20
|
+
/** An unset or unrecognized stored level follows `capture.withoutConsent`. */
|
|
21
|
+
const documentWithoutConsent = (value) => isOneOf(WITHOUT_CONSENT_LEVELS, value) ? value : void 0;
|
|
19
22
|
/** An unset or unrecognized stored region falls back to host-derived detection. */
|
|
20
23
|
const posthogRegion = (value) => value === "us" || value === "eu" ? value : void 0;
|
|
21
24
|
/**
|
|
@@ -63,6 +66,8 @@ const onDocumentHost = (verdict, build) => {
|
|
|
63
66
|
return failingAdapter(build(void 0), () => new HostRefusedError(host, reason));
|
|
64
67
|
};
|
|
65
68
|
const buildBaseAdapter = (doc, ctx) => {
|
|
69
|
+
const withoutConsent = ctx.heldWithoutConsent === false ? "off" : documentWithoutConsent(doc.withoutConsent) ?? (ctx.followingCountsWithoutConsent === false ? "off" : void 0);
|
|
70
|
+
const consent = withoutConsent ? { withoutConsent } : {};
|
|
66
71
|
switch (doc.provider) {
|
|
67
72
|
case "native": return ctx.native ?? null;
|
|
68
73
|
case "plausible": {
|
|
@@ -74,7 +79,8 @@ const buildBaseAdapter = (doc, ctx) => {
|
|
|
74
79
|
domain: orUndefined(cfg.domain),
|
|
75
80
|
scriptId: orUndefined(cfg.scriptId),
|
|
76
81
|
revenueCurrency: orUndefined(cfg.revenueCurrency),
|
|
77
|
-
fetch: ctx.fetch
|
|
82
|
+
fetch: ctx.fetch,
|
|
83
|
+
...consent
|
|
78
84
|
}));
|
|
79
85
|
}
|
|
80
86
|
case "umami": {
|
|
@@ -84,7 +90,8 @@ const buildBaseAdapter = (doc, ctx) => {
|
|
|
84
90
|
apiKey: orUndefined(cfg.apiKey),
|
|
85
91
|
token: orUndefined(cfg.token),
|
|
86
92
|
host,
|
|
87
|
-
fetch: ctx.fetch
|
|
93
|
+
fetch: ctx.fetch,
|
|
94
|
+
...consent
|
|
88
95
|
}));
|
|
89
96
|
}
|
|
90
97
|
case "ga4": {
|
|
@@ -98,7 +105,8 @@ const buildBaseAdapter = (doc, ctx) => {
|
|
|
98
105
|
projectId: orUndefined(cfg.projectId),
|
|
99
106
|
measurementId: orUndefined(cfg.measurementId),
|
|
100
107
|
currency: orUndefined(cfg.currency),
|
|
101
|
-
...ctx.sdks?.ga4 ? { sdk: ctx.sdks.ga4 } : {}
|
|
108
|
+
...ctx.sdks?.ga4 ? { sdk: ctx.sdks.ga4 } : {},
|
|
109
|
+
...consent
|
|
102
110
|
});
|
|
103
111
|
}
|
|
104
112
|
case "posthog": {
|
|
@@ -110,7 +118,8 @@ const buildBaseAdapter = (doc, ctx) => {
|
|
|
110
118
|
projectToken: orUndefined(cfg.projectToken),
|
|
111
119
|
region: posthogRegion(cfg.region),
|
|
112
120
|
scopeProperty: orUndefined(cfg.scopeProperty?.trim()),
|
|
113
|
-
fetch: ctx.fetch
|
|
121
|
+
fetch: ctx.fetch,
|
|
122
|
+
...consent
|
|
114
123
|
}));
|
|
115
124
|
}
|
|
116
125
|
default: return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory.js","names":[],"sources":["../../src/providers/factory.ts"],"sourcesContent":["import { ga4 } from '../adapters/ga4/ga4'\nimport { plausible } from '../adapters/plausible/plausible'\nimport { posthog } from '../adapters/posthog/posthog'\nimport { umami } from '../adapters/umami/umami'\nimport type { AnalyticsAdapter, AnalyticsResult } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { HostRefusedError } from '../core/sourceErrors'\nimport { withFixedLabel } from '../core/sourceLabel'\nimport { isRecord } from '../core/values'\nimport { checkDocumentHost, type DocumentHost, type ProviderHostPolicy } from './hosts'\n\nexport type ProviderId = 'native' | 'plausible' | 'umami' | 'ga4' | 'posthog'\nexport const PROVIDER_IDS = [\n\t'native',\n\t'plausible',\n\t'umami',\n\t'ga4',\n\t'posthog',\n] as const satisfies readonly ProviderId[]\n\n/** The provider-settings document shape the adapter factory reads (depth 0, secrets revealed). */\nexport type ProviderDoc = {\n\tid?: number | string\n\tname?: string | null\n\tprovider?: string | null\n\tenabled?: boolean | null\n\tscope?: string | null\n\tplausible?: {\n\t\tsiteId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tdomain?: string | null\n\t\tscriptId?: string | null\n\t\trevenueCurrency?: string | null\n\t} | null\n\tumami?: {\n\t\twebsiteId?: string | null\n\t\tapiKey?: string | null\n\t\ttoken?: string | null\n\t\thost?: string | null\n\t} | null\n\tga4?: {\n\t\tpropertyId?: string | null\n\t\tclientEmail?: string | null\n\t\tprivateKey?: string | null\n\t\tprojectId?: string | null\n\t\tmeasurementId?: string | null\n\t\tcurrency?: string | null\n\t} | null\n\tposthog?: {\n\t\tprojectId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tprojectToken?: string | null\n\t\tregion?: string | null\n\t\tscopeProperty?: string | null\n\t} | null\n}\n\n/** A stored blank reads as unset. */\nconst orUndefined = (value: string | null | undefined): string | undefined => value || undefined\n\n/** An unset or unrecognized stored region falls back to host-derived detection. */\nconst posthogRegion = (value: string | null | undefined): 'us' | 'eu' | undefined =>\n\tvalue === 'us' || value === 'eu' ? value : undefined\n\n/**\n * Keys pasted from a service-account JSON often carry escaped newlines; the gRPC\n * client needs real ones.\n */\nexport const normalizePrivateKey = (key: string): string => key.replace(/\\\\n/g, '\\n')\n\nconst shortId = (id: number | string): string => String(id).slice(-6)\n\n/** The registry id of a provider document's adapter, which grants and stand-ins must match. */\nexport const documentAdapterId = (provider: unknown, id: unknown): string =>\n\t`${String(provider)}:${String(id)}`\n\n/** A lent `native` adapter under the document's name, so a source reads as its tenant named it. */\nconst withDocumentLabel = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter =>\n\tdoc.name ? withFixedLabel(adapter, doc.name) : adapter\n\n/** Per-document ids keep two projects of one provider type apart in a registry. */\nconst withInstanceIdentity = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter => {\n\tif (doc.id === undefined || doc.id === null || doc.id === '') {\n\t\treturn adapter\n\t}\n\treturn {\n\t\t...withFixedLabel(adapter, doc.name || `${adapter.label} ${shortId(doc.id)}`),\n\t\tid: documentAdapterId(doc.provider, doc.id),\n\t}\n}\n\n/**\n * Keeps `shape`'s identity, capabilities and `isConfigured` (configured when absent) so the source\n * still lists, but every read throws `error()` and it declares no capture, so its proxy mount 404s.\n */\nexport const failingAdapter = (\n\tshape: Pick<AnalyticsAdapter, 'id' | 'label' | 'capabilities' | 'realtime'> &\n\t\tPartial<Pick<AnalyticsAdapter, 'isConfigured'>>,\n\terror: () => Error\n): AnalyticsAdapter => {\n\tconst fail = async (): Promise<AnalyticsResult> => {\n\t\tthrow error()\n\t}\n\treturn {\n\t\tid: shape.id,\n\t\tlabel: shape.label,\n\t\tcapabilities: shape.capabilities,\n\t\tisConfigured: shape.isConfigured ?? (() => true),\n\t\tquery: fail,\n\t\t...(shape.realtime ? { realtime: fail } : {}),\n\t}\n}\n\n/**\n * Builds a hosted vendor's adapter on the address its host check allowed, none being the vendor's\n * cloud; a refused host builds one whose reads fail with a `HostRefusedError`.\n */\nconst onDocumentHost = (\n\tverdict: DocumentHost,\n\tbuild: (host: string | undefined) => AnalyticsAdapter\n): AnalyticsAdapter => {\n\tif (verdict.ok) {\n\t\treturn build(verdict.address ?? undefined)\n\t}\n\tconst { host, reason } = verdict\n\treturn failingAdapter(build(undefined), () => new HostRefusedError(host, reason))\n}\n\nconst buildBaseAdapter = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\tswitch (doc.provider) {\n\t\tcase 'native':\n\t\t\treturn ctx.native ?? null\n\t\tcase 'plausible': {\n\t\t\tconst cfg = doc.plausible ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('plausible', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tplausible({\n\t\t\t\t\tsiteId: cfg.siteId ?? '',\n\t\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\t\thost,\n\t\t\t\t\tdomain: orUndefined(cfg.domain),\n\t\t\t\t\tscriptId: orUndefined(cfg.scriptId),\n\t\t\t\t\trevenueCurrency: orUndefined(cfg.revenueCurrency),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'umami': {\n\t\t\tconst cfg = doc.umami ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('umami', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tumami({\n\t\t\t\t\twebsiteId: cfg.websiteId ?? '',\n\t\t\t\t\tapiKey: orUndefined(cfg.apiKey),\n\t\t\t\t\ttoken: orUndefined(cfg.token),\n\t\t\t\t\thost,\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'ga4': {\n\t\t\tconst cfg = doc.ga4 ?? {}\n\t\t\treturn ga4({\n\t\t\t\tpropertyId: cfg.propertyId ?? '',\n\t\t\t\tcredentials: {\n\t\t\t\t\tclient_email: cfg.clientEmail ?? '',\n\t\t\t\t\tprivate_key: normalizePrivateKey(cfg.privateKey ?? ''),\n\t\t\t\t},\n\t\t\t\tprojectId: orUndefined(cfg.projectId),\n\t\t\t\tmeasurementId: orUndefined(cfg.measurementId),\n\t\t\t\tcurrency: orUndefined(cfg.currency),\n\t\t\t\t...(ctx.sdks?.ga4 ? { sdk: ctx.sdks.ga4 } : {}),\n\t\t\t})\n\t\t}\n\t\tcase 'posthog': {\n\t\t\tconst cfg = doc.posthog ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('posthog', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tposthog({\n\t\t\t\t\tprojectId: cfg.projectId ?? '',\n\t\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\t\thost,\n\t\t\t\t\tprojectToken: orUndefined(cfg.projectToken),\n\t\t\t\t\tregion: posthogRegion(cfg.region),\n\t\t\t\t\tscopeProperty: orUndefined(cfg.scopeProperty?.trim()),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tdefault:\n\t\t\treturn null\n\t}\n}\n\n/**\n * What the factory needs to build a document's adapter: `fetch` and `hosts` keep a stored key on a\n * host the install allows.\n *\n * @beta\n */\nexport interface ProviderFactoryContext {\n\t/** The guarded fetch `providers.resolve` receives, or one from `createGuardedFetch`. */\n\tfetch: FetchLike\n\t/**\n\t * The policy `providers.resolve` receives, or one from `resolveHostPolicy`: a host outside it\n\t * builds an adapter that reads as `source_misconfigured` and captures nothing.\n\t */\n\thosts: ProviderHostPolicy\n\t/**\n\t * The install's config native adapter, which a `native` document grants rather than building a\n\t * second one.\n\t */\n\tnative?: AnalyticsAdapter\n\t/** The plugin's `sdks`: a GA4 document's adapter reads through `sdks.ga4`. */\n\tsdks?: AnalyticsSdks\n}\n\n/** Checked at runtime: a JavaScript caller can leave the guards out, which would go out unguarded. */\nconst isGuarded = (ctx: unknown): ctx is ProviderFactoryContext =>\n\tisRecord(ctx) &&\n\ttypeof ctx.fetch === 'function' &&\n\tisRecord(ctx.hosts) &&\n\tArray.isArray(ctx.hosts.allow)\n\n/**\n * Builds a provider document's adapter: missing credentials read as `isConfigured() === false`, an\n * unknown provider as null, and a `native` document lends the config adapter under its label.\n */\nexport const adapterFromProviderDoc = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\tif (!isGuarded(ctx)) {\n\t\tthrow new Error(\n\t\t\t'analytics: adapterFromProviderDoc needs { fetch, hosts }: pass the ones providers.resolve receives'\n\t\t)\n\t}\n\tconst base = buildBaseAdapter(doc, ctx)\n\tif (!base) {\n\t\treturn null\n\t}\n\treturn doc.provider === 'native' ? withDocumentLabel(base, doc) : withInstanceIdentity(base, doc)\n}\n"],"mappings":";;;;;;;;;AAaA,MAAa,eAAe;CAC3B;CACA;CACA;CACA;CACA;AACD;;AA0CA,MAAM,eAAe,UAAyD,SAAS,KAAA;;AAGvF,MAAM,iBAAiB,UACtB,UAAU,QAAQ,UAAU,OAAO,QAAQ,KAAA;;;;;AAM5C,MAAa,uBAAuB,QAAwB,IAAI,QAAQ,QAAQ,IAAI;AAEpF,MAAM,WAAW,OAAgC,OAAO,EAAE,EAAE,MAAM,EAAE;;AAGpE,MAAa,qBAAqB,UAAmB,OACpD,GAAG,OAAO,QAAQ,EAAE,GAAG,OAAO,EAAE;;AAGjC,MAAM,qBAAqB,SAA2B,QACrD,IAAI,OAAO,eAAe,SAAS,IAAI,IAAI,IAAI;;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MAAM,GAAG;AACjG"}
|
|
1
|
+
{"version":3,"file":"factory.js","names":[],"sources":["../../src/providers/factory.ts"],"sourcesContent":["import { ga4 } from '../adapters/ga4/ga4'\nimport { plausible } from '../adapters/plausible/plausible'\nimport { posthog } from '../adapters/posthog/posthog'\nimport { umami } from '../adapters/umami/umami'\nimport { WITHOUT_CONSENT_LEVELS } from '../capture/withoutConsent'\nimport type { AnalyticsAdapter, AnalyticsResult } from '../core/contract'\nimport type { FetchLike } from '../core/fetch'\nimport type { AnalyticsSdks } from '../core/sdks'\nimport { HostRefusedError } from '../core/sourceErrors'\nimport { withFixedLabel } from '../core/sourceLabel'\nimport { isOneOf, isRecord } from '../core/values'\nimport type { WithoutConsentLevel } from '../tracker/config'\nimport { checkDocumentHost, type DocumentHost, type ProviderHostPolicy } from './hosts'\n\nexport type ProviderId = 'native' | 'plausible' | 'umami' | 'ga4' | 'posthog'\nexport const PROVIDER_IDS = [\n\t'native',\n\t'plausible',\n\t'umami',\n\t'ga4',\n\t'posthog',\n] as const satisfies readonly ProviderId[]\n\n/** The provider-settings document shape the adapter factory reads (depth 0, secrets revealed). */\nexport type ProviderDoc = {\n\tid?: number | string\n\tname?: string | null\n\tprovider?: string | null\n\tenabled?: boolean | null\n\tscope?: string | null\n\t/** A vendor document's own level without consent; unset or blank follows the install. */\n\twithoutConsent?: string | null\n\tplausible?: {\n\t\tsiteId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tdomain?: string | null\n\t\tscriptId?: string | null\n\t\trevenueCurrency?: string | null\n\t} | null\n\tumami?: {\n\t\twebsiteId?: string | null\n\t\tapiKey?: string | null\n\t\ttoken?: string | null\n\t\thost?: string | null\n\t} | null\n\tga4?: {\n\t\tpropertyId?: string | null\n\t\tclientEmail?: string | null\n\t\tprivateKey?: string | null\n\t\tprojectId?: string | null\n\t\tmeasurementId?: string | null\n\t\tcurrency?: string | null\n\t} | null\n\tposthog?: {\n\t\tprojectId?: string | null\n\t\tapiKey?: string | null\n\t\thost?: string | null\n\t\tprojectToken?: string | null\n\t\tregion?: string | null\n\t\tscopeProperty?: string | null\n\t} | null\n}\n\n/** A stored blank reads as unset. */\nconst orUndefined = (value: string | null | undefined): string | undefined => value || undefined\n\n/** An unset or unrecognized stored level follows `capture.withoutConsent`. */\nconst documentWithoutConsent = (\n\tvalue: string | null | undefined\n): WithoutConsentLevel | undefined => (isOneOf(WITHOUT_CONSENT_LEVELS, value) ? value : undefined)\n\n/** An unset or unrecognized stored region falls back to host-derived detection. */\nconst posthogRegion = (value: string | null | undefined): 'us' | 'eu' | undefined =>\n\tvalue === 'us' || value === 'eu' ? value : undefined\n\n/**\n * Keys pasted from a service-account JSON often carry escaped newlines; the gRPC\n * client needs real ones.\n */\nexport const normalizePrivateKey = (key: string): string => key.replace(/\\\\n/g, '\\n')\n\nconst shortId = (id: number | string): string => String(id).slice(-6)\n\n/** The registry id of a provider document's adapter, which grants and stand-ins must match. */\nexport const documentAdapterId = (provider: unknown, id: unknown): string =>\n\t`${String(provider)}:${String(id)}`\n\n/** A lent `native` adapter under the document's name, so a source reads as its tenant named it. */\nconst withDocumentLabel = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter =>\n\tdoc.name ? withFixedLabel(adapter, doc.name) : adapter\n\n/** Per-document ids keep two projects of one provider type apart in a registry. */\nconst withInstanceIdentity = (adapter: AnalyticsAdapter, doc: ProviderDoc): AnalyticsAdapter => {\n\tif (doc.id === undefined || doc.id === null || doc.id === '') {\n\t\treturn adapter\n\t}\n\treturn {\n\t\t...withFixedLabel(adapter, doc.name || `${adapter.label} ${shortId(doc.id)}`),\n\t\tid: documentAdapterId(doc.provider, doc.id),\n\t}\n}\n\n/**\n * Keeps `shape`'s identity, capabilities and `isConfigured` (configured when absent) so the source\n * still lists, but every read throws `error()` and it declares no capture, so its proxy mount 404s.\n */\nexport const failingAdapter = (\n\tshape: Pick<AnalyticsAdapter, 'id' | 'label' | 'capabilities' | 'realtime'> &\n\t\tPartial<Pick<AnalyticsAdapter, 'isConfigured'>>,\n\terror: () => Error\n): AnalyticsAdapter => {\n\tconst fail = async (): Promise<AnalyticsResult> => {\n\t\tthrow error()\n\t}\n\treturn {\n\t\tid: shape.id,\n\t\tlabel: shape.label,\n\t\tcapabilities: shape.capabilities,\n\t\tisConfigured: shape.isConfigured ?? (() => true),\n\t\tquery: fail,\n\t\t...(shape.realtime ? { realtime: fail } : {}),\n\t}\n}\n\n/**\n * Builds a hosted vendor's adapter on the address its host check allowed, none being the vendor's\n * cloud; a refused host builds one whose reads fail with a `HostRefusedError`.\n */\nconst onDocumentHost = (\n\tverdict: DocumentHost,\n\tbuild: (host: string | undefined) => AnalyticsAdapter\n): AnalyticsAdapter => {\n\tif (verdict.ok) {\n\t\treturn build(verdict.address ?? undefined)\n\t}\n\tconst { host, reason } = verdict\n\treturn failingAdapter(build(undefined), () => new HostRefusedError(host, reason))\n}\n\nconst buildBaseAdapter = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\t// Saying off where the slot would resolve off anyway keeps the adapter from acting (or warning)\n\t// as if it might count without consent.\n\tconst withoutConsent =\n\t\tctx.heldWithoutConsent === false\n\t\t\t? 'off'\n\t\t\t: (documentWithoutConsent(doc.withoutConsent) ??\n\t\t\t\t(ctx.followingCountsWithoutConsent === false ? 'off' : undefined))\n\tconst consent = withoutConsent ? { withoutConsent } : {}\n\tswitch (doc.provider) {\n\t\tcase 'native':\n\t\t\treturn ctx.native ?? null\n\t\tcase 'plausible': {\n\t\t\tconst cfg = doc.plausible ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('plausible', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tplausible({\n\t\t\t\t\tsiteId: cfg.siteId ?? '',\n\t\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\t\thost,\n\t\t\t\t\tdomain: orUndefined(cfg.domain),\n\t\t\t\t\tscriptId: orUndefined(cfg.scriptId),\n\t\t\t\t\trevenueCurrency: orUndefined(cfg.revenueCurrency),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'umami': {\n\t\t\tconst cfg = doc.umami ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('umami', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tumami({\n\t\t\t\t\twebsiteId: cfg.websiteId ?? '',\n\t\t\t\t\tapiKey: orUndefined(cfg.apiKey),\n\t\t\t\t\ttoken: orUndefined(cfg.token),\n\t\t\t\t\thost,\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tcase 'ga4': {\n\t\t\tconst cfg = doc.ga4 ?? {}\n\t\t\treturn ga4({\n\t\t\t\tpropertyId: cfg.propertyId ?? '',\n\t\t\t\tcredentials: {\n\t\t\t\t\tclient_email: cfg.clientEmail ?? '',\n\t\t\t\t\tprivate_key: normalizePrivateKey(cfg.privateKey ?? ''),\n\t\t\t\t},\n\t\t\t\tprojectId: orUndefined(cfg.projectId),\n\t\t\t\tmeasurementId: orUndefined(cfg.measurementId),\n\t\t\t\tcurrency: orUndefined(cfg.currency),\n\t\t\t\t...(ctx.sdks?.ga4 ? { sdk: ctx.sdks.ga4 } : {}),\n\t\t\t\t...consent,\n\t\t\t})\n\t\t}\n\t\tcase 'posthog': {\n\t\t\tconst cfg = doc.posthog ?? {}\n\t\t\treturn onDocumentHost(checkDocumentHost('posthog', cfg.host, ctx.hosts), (host) =>\n\t\t\t\tposthog({\n\t\t\t\t\tprojectId: cfg.projectId ?? '',\n\t\t\t\t\tapiKey: cfg.apiKey ?? '',\n\t\t\t\t\thost,\n\t\t\t\t\tprojectToken: orUndefined(cfg.projectToken),\n\t\t\t\t\tregion: posthogRegion(cfg.region),\n\t\t\t\t\tscopeProperty: orUndefined(cfg.scopeProperty?.trim()),\n\t\t\t\t\tfetch: ctx.fetch,\n\t\t\t\t\t...consent,\n\t\t\t\t})\n\t\t\t)\n\t\t}\n\t\tdefault:\n\t\t\treturn null\n\t}\n}\n\n/**\n * What the factory needs to build a document's adapter: `fetch` and `hosts` keep a stored key on a\n * host the install allows.\n *\n * @beta\n */\nexport interface ProviderFactoryContext {\n\t/** The guarded fetch `providers.resolve` receives, or one from `createGuardedFetch`. */\n\tfetch: FetchLike\n\t/**\n\t * The policy `providers.resolve` receives, or one from `resolveHostPolicy`: a host outside it\n\t * builds an adapter that reads as `source_misconfigured` and captures nothing.\n\t */\n\thosts: ProviderHostPolicy\n\t/**\n\t * The install's config native adapter, which a `native` document grants rather than building a\n\t * second one.\n\t */\n\tnative?: AnalyticsAdapter\n\t/** The plugin's `sdks`: a GA4 document's adapter reads through `sdks.ga4`. */\n\tsdks?: AnalyticsSdks\n\t/**\n\t * False when no slot `capture.gate` holds can fall to a document's adapter: it is then off\n\t * without consent, whatever the document says.\n\t */\n\theldWithoutConsent?: boolean\n\t/** False when `capture.withoutConsent` is `'off'` in both phases: a document following it is off. */\n\tfollowingCountsWithoutConsent?: boolean\n}\n\n/** Checked at runtime: a JavaScript caller can leave the guards out, which would go out unguarded. */\nconst isGuarded = (ctx: unknown): ctx is ProviderFactoryContext =>\n\tisRecord(ctx) &&\n\ttypeof ctx.fetch === 'function' &&\n\tisRecord(ctx.hosts) &&\n\tArray.isArray(ctx.hosts.allow)\n\n/**\n * Builds a provider document's adapter: missing credentials read as `isConfigured() === false`, an\n * unknown provider as null, and a `native` document lends the config adapter under its label.\n */\nexport const adapterFromProviderDoc = (\n\tdoc: ProviderDoc,\n\tctx: ProviderFactoryContext\n): AnalyticsAdapter | null => {\n\tif (!isGuarded(ctx)) {\n\t\tthrow new Error(\n\t\t\t'analytics: adapterFromProviderDoc needs { fetch, hosts }: pass the ones providers.resolve receives'\n\t\t)\n\t}\n\tconst base = buildBaseAdapter(doc, ctx)\n\tif (!base) {\n\t\treturn null\n\t}\n\treturn doc.provider === 'native' ? withDocumentL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