@10x-media/analytics 1.0.0-beta.15 → 1.0.0-beta.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/README.md +1 -1
- package/dist/adapters/ga4/ga4.js +33 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +4 -1
- package/dist/adapters/ga4/measurementId.js.map +1 -1
- package/dist/adapters/ga4/propertyId.js +17 -0
- package/dist/adapters/ga4/propertyId.js.map +1 -0
- package/dist/adapters/http/fetchJson.js +24 -1
- package/dist/adapters/http/fetchJson.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +16 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/plausible/siteId.js +31 -0
- package/dist/adapters/plausible/siteId.js.map +1 -0
- package/dist/adapters/posthog/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 +3 -3
- package/dist/adapters/posthog/posthog.js +24 -10
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +34 -7
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/contract.d.ts +16 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +1 -1
- package/dist/core/options.js +1 -1
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +62 -14
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceErrors.js +12 -1
- package/dist/core/sourceErrors.js.map +1 -1
- package/dist/core/sourceOptions.js +1 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +8 -1
- package/dist/core/sourcePolicy.js.map +1 -1
- package/dist/core/throttle.js +3 -1
- package/dist/core/throttle.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -2
- package/dist/exports/adapters/native.d.ts +2 -2
- package/dist/exports/adapters/plausible.d.ts +2 -2
- package/dist/exports/adapters/posthog.d.ts +2 -2
- package/dist/exports/adapters/umami.d.ts +2 -2
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/next.d.ts +2 -2
- package/dist/exports/testing.d.ts +2 -2
- package/dist/exports/types.d.ts +3 -3
- package/dist/fields/config/fetchSources.js +1 -1
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/goals/collection.js +3 -2
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +50 -4
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/nativeAdapter.js +1 -1
- package/dist/plugin/createRuntime.js +57 -13
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/pluginCollections.js +4 -1
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/providerStatusEndpoint.js +80 -0
- package/dist/plugin/providerStatusEndpoint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +4 -3
- package/dist/plugin/readContextForRequest.js +2 -2
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/refreshEndpoint.js +1 -1
- package/dist/plugin/routes.d.ts +5 -0
- package/dist/plugin/routes.js +1 -0
- package/dist/plugin/routes.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/ProviderConnection.d.ts +12 -0
- package/dist/providers/ProviderConnection.js +105 -0
- package/dist/providers/ProviderConnection.js.map +1 -0
- package/dist/providers/ProviderConnectionTest.d.ts +12 -0
- package/dist/providers/ProviderConnectionTest.js +55 -0
- package/dist/providers/ProviderConnectionTest.js.map +1 -0
- package/dist/providers/ProvidersListNotice.d.ts +1 -1
- package/dist/providers/ProvidersListNotice.js +3 -2
- package/dist/providers/ProvidersListNotice.js.map +1 -1
- package/dist/providers/collection.d.ts +1 -1
- package/dist/providers/collection.js +106 -41
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/connectionCheck.d.ts +1 -0
- package/dist/providers/connectionCheck.js +80 -0
- package/dist/providers/connectionCheck.js.map +1 -0
- package/dist/providers/connectionState.js +53 -0
- package/dist/providers/connectionState.js.map +1 -0
- package/dist/providers/factory.d.ts +1 -3
- package/dist/providers/factory.js +18 -21
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +31 -9
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/ids.d.ts +6 -0
- package/dist/providers/ids.js +32 -0
- package/dist/providers/ids.js.map +1 -0
- package/dist/providers/providerStatusClient.js +60 -0
- package/dist/providers/providerStatusClient.js.map +1 -0
- package/dist/providers/registry.js +56 -20
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/retarget.js +39 -8
- package/dist/providers/retarget.js.map +1 -1
- package/dist/providers/secrets.d.ts +1 -1
- package/dist/providers/secrets.js.map +1 -1
- package/dist/providers/status.d.ts +1 -0
- package/dist/providers/status.js +181 -0
- package/dist/providers/status.js.map +1 -0
- package/dist/surfacing/classifyError.js +37 -5
- package/dist/surfacing/classifyError.js.map +1 -1
- package/dist/surfacing/engine.js +2 -2
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/lanes.js +29 -22
- package/dist/surfacing/lanes.js.map +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/testing/settle.d.ts +2 -1
- package/dist/testing/settle.js +6 -2
- package/dist/testing/settle.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/translations/ar.js +43 -8
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +43 -8
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +43 -8
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +43 -8
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +43 -8
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +43 -8
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +35 -0
- package/dist/translations/keys.js +35 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +43 -8
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +43 -8
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +43 -8
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +43 -8
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +43 -8
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +63 -0
- package/dist/ui/components/SourcesNoticeBanner.js +4 -3
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
- package/dist/view/ViewSections.js +9 -2
- package/dist/view/ViewSections.js.map +1 -1
- package/dist/view/sections/EmptyStates.js +5 -4
- package/dist/view/sections/EmptyStates.js.map +1 -1
- package/dist/view/sections/OverviewCards.js +6 -2
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/view/sections/SourceConnectionNote.js +56 -0
- package/dist/view/sections/SourceConnectionNote.js.map +1 -0
- package/dist/view/viewProps.d.ts +2 -0
- package/dist/view/viewProps.js +2 -1
- package/dist/view/viewProps.js.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readContextForRequest.js","names":[],"sources":["../../src/plugin/readContextForRequest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type GatedScope, isGatedScope } from '../access/principal'\nimport { readGate } from '../access/readGate'\nimport { type SerializedCapabilities, serializeCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { AdapterRegistry } from '../core/registry'\nimport {\n\tneedsUnscopedSourceAccess,\n\tresolveRequestedScope,\n\tvisibleSourcesFor,\n} from '../core/scopedRead'\nimport { sourceRefFor } from '../core/sourceLabel'\nimport type { QuerySourceRef } from '../query/response'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\tresolvableScope,\n\tresolveRegistryFor,\n\ttype ScopeGates,\n\tscopeGates,\n} from './runtime'\n\n/** One readable source on the wire: its identity plus the capabilities a client gates on. */\nexport interface RequestSource extends QuerySourceRef {\n\tcapabilities: SerializedCapabilities\n}\n\n/**\n * What a listing tells its reader about itself
|
|
1
|
+
{"version":3,"file":"readContextForRequest.js","names":[],"sources":["../../src/plugin/readContextForRequest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type GatedScope, isGatedScope } from '../access/principal'\nimport { readGate } from '../access/readGate'\nimport { type SerializedCapabilities, serializeCapabilities } from '../core/capabilities'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport type { AdapterRegistry } from '../core/registry'\nimport {\n\tneedsUnscopedSourceAccess,\n\tresolveRequestedScope,\n\tvisibleSourcesFor,\n} from '../core/scopedRead'\nimport { sourceRefFor } from '../core/sourceLabel'\nimport type { QuerySourceRef } from '../query/response'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\tresolvableScope,\n\tresolveRegistryFor,\n\ttype ScopeGates,\n\tscopeGates,\n} from './runtime'\n\n/** One readable source on the wire: its identity plus the capabilities a client gates on. */\nexport interface RequestSource extends QuerySourceRef {\n\tcapabilities: SerializedCapabilities\n}\n\n/**\n * What a listing tells its reader about itself, when a shared source is listed only by\n * `sources.<id>.tenants: 'fallback'`: `platformFallback` because the scope has no source of its own\n * yet, `ownSourceFailing` because every one it has is failing.\n */\nexport type SourcesNotice = 'platformFallback' | 'ownSourceFailing'\n\ninterface RequestSources {\n\t/** Wire rows for the resolved scope, in registry order; empty when none resolve. */\n\tsources: RequestSource[]\n\tdefaultId: string | null\n\tnotice?: SourcesNotice\n\t/** The adapters behind `sources`, for callers that read through them. */\n\tadapters: ReadonlyMap<string, AnalyticsAdapter>\n\t/** Scope the sources were resolved for; null is install-wide, `*` is cross-scope. */\n\tscope: string | null\n}\n\ninterface ResolveSourcesArgs {\n\t/**\n\t * A scope {@link resolveRequestedScope} already cleared for this request, which replaces this\n\t * call's own resolution. Only that helper mints one.\n\t */\n\tscope?: GatedScope\n\t/** Shared cross-scope decisions; one set is created per call when omitted. */\n\tgates?: ScopeGates\n}\n\nconst empty = (): RequestSources => ({\n\tsources: [],\n\tdefaultId: null,\n\tadapters: new Map(),\n\tscope: null,\n})\n\nconst fromRegistry = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tregistry: AdapterRegistry\n\tscope: string | null\n}): Promise<RequestSources> => {\n\tconst { runtime, req, registry, scope } = args\n\tconst adapters = registry.all()\n\treturn {\n\t\tsources: await Promise.all(\n\t\t\tadapters.map(async (adapter) => ({\n\t\t\t\t...(await sourceRefFor(adapter, { req, scope, configIds: runtime.configAdapterIds })),\n\t\t\t\tcapabilities: serializeCapabilities(adapter.capabilities),\n\t\t\t}))\n\t\t),\n\t\tdefaultId: registry.default().id,\n\t\tadapters: new Map(adapters.map((adapter) => [adapter.id, adapter])),\n\t\tscope,\n\t}\n}\n\n/**\n * Sources that can answer about one scope. Under a tenant scope a shared adapter unable to narrow\n * would report every tenant's numbers, so it is dropped however privileged the reader.\n */\nconst narrowToScope = (runtime: AnalyticsRuntime, resolved: RequestSources): RequestSources => {\n\tconst scope = resolved.scope\n\tif (scope === null) {\n\t\treturn resolved\n\t}\n\tconst narrowable = resolved.sources.filter((source) => {\n\t\tconst adapter = resolved.adapters.get(source.id)\n\t\treturn adapter !== undefined && !needsUnscopedSourceAccess(runtime, adapter, scope)\n\t})\n\tif (narrowable.length === resolved.sources.length) {\n\t\treturn resolved\n\t}\n\tconst kept = new Set(narrowable.map((source) => source.id))\n\treturn {\n\t\tsources: narrowable,\n\t\tdefaultId:\n\t\t\tresolved.defaultId !== null && kept.has(resolved.defaultId)\n\t\t\t\t? resolved.defaultId\n\t\t\t\t: (narrowable[0]?.id ?? null),\n\t\tadapters: new Map([...resolved.adapters].filter(([id]) => kept.has(id))),\n\t\tscope,\n\t}\n}\n\n/**\n * Sources a request may read, shared by every listing surface. A denied, cross-scope or non-member\n * read lists nothing; a failed resolution lists nothing when scoped, else the config registry.\n */\nexport const resolveSourcesForRequest = async (\n\treq: PayloadRequest,\n\targs: ResolveSourcesArgs = {}\n): Promise<RequestSources> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn empty()\n\t}\n\ttry {\n\t\tif (!(await readGate(runtime, req))) {\n\t\t\treturn empty()\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: access.read failed, listing no sources: ${String(err)}`)\n\t\treturn empty()\n\t}\n\tconst gates = args.gates ?? scopeGates(runtime, req)\n\tconst degrade = async (): Promise<RequestSources> =>\n\t\truntime.scoped\n\t\t\t? empty()\n\t\t\t: fromRegistry({ runtime, req, registry: runtime.registry, scope: null })\n\ttry {\n\t\tlet scope: string | null\n\t\tif (args.scope !== undefined) {\n\t\t\tif (!isGatedScope(args.scope)) {\n\t\t\t\treturn empty()\n\t\t\t}\n\t\t\tscope = args.scope.value\n\t\t} else {\n\t\t\tconst requested = await resolveRequestedScope({ runtime, req, gates })\n\t\t\tif (!requested.ok) {\n\t\t\t\treturn requested.reason === 'failed' ? degrade() : empty()\n\t\t\t}\n\t\t\tscope = requested.scope\n\t\t}\n\t\tconst resolved = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: resolvableScope(scope),\n\t\t})\n\t\tconst { registry, fallbackAdmitted, ownFailing } = await visibleSourcesFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tresolved,\n\t\t\tscope,\n\t\t\tgates,\n\t\t})\n\t\tif (!registry) {\n\t\t\treturn { ...empty(), scope }\n\t\t}\n\t\tconst listed = narrowToScope(runtime, await fromRegistry({ runtime, req, registry, scope }))\n\t\treturn listed.sources.some((source) => fallbackAdmitted.has(source.id))\n\t\t\t? { ...listed, notice: ownFailing ? 'ownSourceFailing' : 'platformFallback' }\n\t\t\t: listed\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: source resolution failed: ${String(err)}`)\n\t\treturn degrade()\n\t}\n}\n"],"mappings":";;;;;;;AAuDA,MAAM,eAA+B;CACpC,SAAS,CAAC;CACV,WAAW;CACX,0BAAU,IAAI,IAAI;CAClB,OAAO;AACR;AAEA,MAAM,eAAe,OAAO,SAKG;CAC9B,MAAM,EAAE,SAAS,KAAK,UAAU,UAAU;CAC1C,MAAM,WAAW,SAAS,IAAI;CAC9B,OAAO;EACN,SAAS,MAAM,QAAQ,IACtB,SAAS,IAAI,OAAO,aAAa;GAChC,GAAI,MAAM,aAAa,SAAS;IAAE;IAAK;IAAO,WAAW,QAAQ;GAAiB,CAAC;GACnF,cAAc,sBAAsB,QAAQ,YAAY;EACzD,EAAE,CACH;EACA,WAAW,SAAS,QAAQ,EAAE;EAC9B,UAAU,IAAI,IAAI,SAAS,KAAK,YAAY,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC;EAClE;CACD;AACD;;;;;AAMA,MAAM,iBAAiB,SAA2B,aAA6C;CAC9F,MAAM,QAAQ,SAAS;CACvB,IAAI,UAAU,MACb,OAAO;CAER,MAAM,aAAa,SAAS,QAAQ,QAAQ,WAAW;EACtD,MAAM,UAAU,SAAS,SAAS,IAAI,OAAO,EAAE;EAC/C,OAAO,YAAY,KAAA,KAAa,CAAC,0BAA0B,SAAS,SAAS,KAAK;CACnF,CAAC;CACD,IAAI,WAAW,WAAW,SAAS,QAAQ,QAC1C,OAAO;CAER,MAAM,OAAO,IAAI,IAAI,WAAW,KAAK,WAAW,OAAO,EAAE,CAAC;CAC1D,OAAO;EACN,SAAS;EACT,WACC,SAAS,cAAc,QAAQ,KAAK,IAAI,SAAS,SAAS,IACvD,SAAS,YACR,WAAW,IAAI,MAAM;EAC1B,UAAU,IAAI,IAAI,CAAC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AAI,OAAO,EAAE,CAAC,IACnE;GAAE,GAAG;GAAQ,QAAQ,aAAa,qBAAqB;EAAmB,IAC1E;CACJ,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,wCAAwC,OAAO,GAAG,GAAG;EAC9E,OAAO,QAAQ;CAChB;AACD"}
|
package/dist/plugin/routes.d.ts
CHANGED
|
@@ -19,6 +19,11 @@ interface RoutePaths {
|
|
|
19
19
|
goals: string;
|
|
20
20
|
/** Authenticated POST retiring a scope's cached reads. */
|
|
21
21
|
refresh: string;
|
|
22
|
+
/**
|
|
23
|
+
* Authenticated GET of one provider document's connection status, POST checking it first;
|
|
24
|
+
* mounted while `providers.collection` is on.
|
|
25
|
+
*/
|
|
26
|
+
providerStatus: string;
|
|
22
27
|
/** Authenticated realtime read the live counters poll. */
|
|
23
28
|
live: string;
|
|
24
29
|
/** Authenticated exclusion link for the selected scope; mounted while `capture.exclusion` is on. */
|
package/dist/plugin/routes.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","names":[],"sources":["../../src/plugin/routes.ts"],"sourcesContent":["/**\n * Every mount the plugin registers under `routes.api`, all off one base. Free of server code, so\n * client components and the browser tracker import it.\n */\n\nimport { isRecord } from '../core/values'\n\n/** A path under `routes.api`, with its leading slash and without a trailing one. */\nexport type RouteBase = `/${string}`\n\n/** Short, and no word an ad blocker's filter list would match. */\nexport const DEFAULT_ROUTE_BASE: RouteBase = '/_x'\n\n/**\n * The plugin's key in `config.custom`, which holds its server-only runtime factory, and in\n * `config.admin.custom`, which reaches the client config and carries the resolved base.\n */\nexport const ANALYTICS_CONFIG_KEY = '@10x-media/analytics'\n\nexport interface RoutePaths {\n\tbase: RouteBase\n\t/** Authenticated read over the surfacing engine. */\n\tquery: string\n\t/** Authenticated read behind a document's analytics panel. */\n\tdocument: string\n\t/** Authenticated list of the sources a request may read. */\n\tsources: string\n\t/** Authenticated goal list for the admin goal picker. */\n\tgoals: string\n\t/** Authenticated POST retiring a scope's cached reads. */\n\trefresh: string\n\t/** Authenticated realtime read the live counters poll. */\n\tlive: string\n\t/** Authenticated exclusion link for the selected scope; mounted while `capture.exclusion` is on. */\n\texclusion: string\n\t/** Public native ingest, and the default `native({ ingestPath })`. */\n\tingest: string\n\t/** Public tracker config. */\n\tconfig: string\n\t/** Mount of the public capture proxy; a slot answers under `${proxy}/<slot>`. */\n\tproxy: string\n\t/** The capture proxy's registered pattern. */\n\tproxyPattern: string\n\t/** Mount of the public flag route; one flag answers under `${flags}/<code>.svg`. */\n\tflags: string\n\t/** The flag route's registered pattern. */\n\tflagsPattern: string\n}\n\nexport const routePaths = (base: RouteBase): RoutePaths => ({\n\tbase,\n\tquery: `${base}/query`,\n\tdocument: `${base}/document`,\n\tsources: `${base}/sources`,\n\tgoals: `${base}/goals`,\n\trefresh: `${base}/refresh`,\n\tlive: `${base}/live`,\n\texclusion: `${base}/exclusion`,\n\tingest: `${base}/e`,\n\tconfig: `${base}/config`,\n\tproxy: `${base}/p`,\n\tproxyPattern: `${base}/p/:slot/:path*`,\n\tflags: `${base}/flags`,\n\tflagsPattern: `${base}/flags/:code`,\n})\n\n/** Plain segments of URL-safe characters, none starting with a dot. */\nconst BASE_PATTERN = /^(?:\\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/\n\n/**\n * Payload strips a leading `/globals` from every API path before it routes, so a base starting\n * with it would be read as a global's route instead.\n */\nconst GLOBALS_PREFIX = '/globals'\n\n/**\n * Payload looks a request's first segment up on `payload.collections`, a plain object, so one of\n * `Object.prototype`'s keys finds something there and every request fails before any endpoint runs.\n */\nconst INHERITED_KEYS: ReadonlySet<string> = new Set(Object.getOwnPropertyNames(Object.prototype))\n\nconst firstSegment = (path: string): string => path.split('/')[1] ?? ''\n\nexport const isRouteBase = (value: unknown): value is RouteBase =>\n\ttypeof value === 'string' &&\n\tBASE_PATTERN.test(value) &&\n\t!value.startsWith(GLOBALS_PREFIX) &&\n\t!INHERITED_KEYS.has(firstSegment(value))\n\n/** A `routes.base` option checked for a path Payload can route, or the default when unset. */\nexport const resolveRouteBase = (value: unknown): RouteBase => {\n\tif (value === undefined) {\n\t\treturn DEFAULT_ROUTE_BASE\n\t}\n\tif (typeof value === 'string' && value.startsWith(GLOBALS_PREFIX)) {\n\t\tthrow new Error(\n\t\t\t`analytics: routes.base \"${value}\" starts with \"${GLOBALS_PREFIX}\", which Payload routes to its globals; choose another first segment`\n\t\t)\n\t}\n\tif (typeof value === 'string' && INHERITED_KEYS.has(firstSegment(value))) {\n\t\tthrow new Error(\n\t\t\t`analytics: routes.base \"${value}\" starts with \"${firstSegment(value)}\", a name every JavaScript object carries, which Payload would take for a collection; choose another first segment`\n\t\t)\n\t}\n\tif (!isRouteBase(value)) {\n\t\tthrow new Error(\n\t\t\t`analytics: routes.base must be a path of plain segments such as \"${DEFAULT_ROUTE_BASE}\" (letters, digits, \"-\", \"_\", \".\" and \"~\", no trailing slash), got ${typeof value === 'string' ? `\"${value}\"` : typeof value}`\n\t\t)\n\t}\n\treturn value\n}\n\n/** The base's first segment, which Payload compares against every collection slug. */\nexport const routeBaseSegment = (base: RouteBase): string => firstSegment(base)\n\n/**\n * The collection that would take every request under the base: Payload hands `<api>/<segment>/...`\n * to the collection slugged `<segment>` before it tries a root endpoint.\n */\nexport const shadowingCollection = (\n\tbase: RouteBase,\n\tslugs: Iterable<string>\n): string | undefined => {\n\tconst segment = routeBaseSegment(base)\n\tfor (const slug of slugs) {\n\t\tif (slug === segment) {\n\t\t\treturn slug\n\t\t}\n\t}\n\treturn undefined\n}\n\n/** Refuses a base some collection would shadow, naming that collection and the option to change. */\nexport const assertRouteBaseUnshadowed = (base: RouteBase, slugs: Iterable<string>): void => {\n\tconst slug = shadowingCollection(base, slugs)\n\tif (slug !== undefined) {\n\t\tthrow new Error(\n\t\t\t`analytics: the \"${slug}\" collection's slug is the first segment of routes.base \"${base}\", so Payload would hand every analytics request to that collection. Set routes.base to a path whose first segment is no collection's slug.`\n\t\t)\n\t}\n}\n\n/** What the plugin leaves under its key in `config.admin.custom`. */\nexport interface AnalyticsAdminCustom {\n\troutes: { base: RouteBase }\n}\n\n/** The slice of a root endpoint the route checks read. */\nexport interface RootEndpointShape {\n\tmethod: string\n\tpath: string\n\tcustom?: Record<string, unknown> | undefined\n}\n\n/**\n * The endpoint with the plugin's mark in its `custom`, which is how the route checks tell the\n * plugin's own root endpoints from those registered before it.\n */\nexport const pluginEndpoint = <T extends RootEndpointShape>(endpoint: T): T => ({\n\t...endpoint,\n\tcustom: { ...endpoint.custom, [ANALYTICS_CONFIG_KEY]: true },\n})\n\nexport const isPluginEndpoint = (endpoint: RootEndpointShape): boolean =>\n\tendpoint.custom?.[ANALYTICS_CONFIG_KEY] === true\n\n/** The slice of a Payload config, server or client, the base is read from. */\nexport interface RoutesConfigSource {\n\tadmin?: { custom?: Record<string, unknown> } | undefined\n}\n\n/**\n * The mounts one Payload config resolved, read from `config.admin.custom` by server and client\n * code alike. A config the plugin never touched answers the default base.\n */\nexport const analyticsRoutes = (config: RoutesConfigSource | null | undefined): RoutePaths => {\n\tconst entry = config?.admin?.custom?.[ANALYTICS_CONFIG_KEY]\n\tconst routes = isRecord(entry) ? entry.routes : undefined\n\tconst base = isRecord(routes) ? routes.base : undefined\n\treturn routePaths(isRouteBase(base) ? base : DEFAULT_ROUTE_BASE)\n}\n"],"mappings":";;;;;;;AAWA,MAAa,qBAAgC;;;;;AAM7C,MAAa,uBAAuB;
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../src/plugin/routes.ts"],"sourcesContent":["/**\n * Every mount the plugin registers under `routes.api`, all off one base. Free of server code, so\n * client components and the browser tracker import it.\n */\n\nimport { isRecord } from '../core/values'\n\n/** A path under `routes.api`, with its leading slash and without a trailing one. */\nexport type RouteBase = `/${string}`\n\n/** Short, and no word an ad blocker's filter list would match. */\nexport const DEFAULT_ROUTE_BASE: RouteBase = '/_x'\n\n/**\n * The plugin's key in `config.custom`, which holds its server-only runtime factory, and in\n * `config.admin.custom`, which reaches the client config and carries the resolved base.\n */\nexport const ANALYTICS_CONFIG_KEY = '@10x-media/analytics'\n\nexport interface RoutePaths {\n\tbase: RouteBase\n\t/** Authenticated read over the surfacing engine. */\n\tquery: string\n\t/** Authenticated read behind a document's analytics panel. */\n\tdocument: string\n\t/** Authenticated list of the sources a request may read. */\n\tsources: string\n\t/** Authenticated goal list for the admin goal picker. */\n\tgoals: string\n\t/** Authenticated POST retiring a scope's cached reads. */\n\trefresh: string\n\t/**\n\t * Authenticated GET of one provider document's connection status, POST checking it first;\n\t * mounted while `providers.collection` is on.\n\t */\n\tproviderStatus: string\n\t/** Authenticated realtime read the live counters poll. */\n\tlive: string\n\t/** Authenticated exclusion link for the selected scope; mounted while `capture.exclusion` is on. */\n\texclusion: string\n\t/** Public native ingest, and the default `native({ ingestPath })`. */\n\tingest: string\n\t/** Public tracker config. */\n\tconfig: string\n\t/** Mount of the public capture proxy; a slot answers under `${proxy}/<slot>`. */\n\tproxy: string\n\t/** The capture proxy's registered pattern. */\n\tproxyPattern: string\n\t/** Mount of the public flag route; one flag answers under `${flags}/<code>.svg`. */\n\tflags: string\n\t/** The flag route's registered pattern. */\n\tflagsPattern: string\n}\n\nexport const routePaths = (base: RouteBase): RoutePaths => ({\n\tbase,\n\tquery: `${base}/query`,\n\tdocument: `${base}/document`,\n\tsources: `${base}/sources`,\n\tgoals: `${base}/goals`,\n\trefresh: `${base}/refresh`,\n\tproviderStatus: `${base}/provider-status`,\n\tlive: `${base}/live`,\n\texclusion: `${base}/exclusion`,\n\tingest: `${base}/e`,\n\tconfig: `${base}/config`,\n\tproxy: `${base}/p`,\n\tproxyPattern: `${base}/p/:slot/:path*`,\n\tflags: `${base}/flags`,\n\tflagsPattern: `${base}/flags/:code`,\n})\n\n/** Plain segments of URL-safe characters, none starting with a dot. */\nconst BASE_PATTERN = /^(?:\\/[A-Za-z0-9_~-][A-Za-z0-9._~-]*)+$/\n\n/**\n * Payload strips a leading `/globals` from every API path before it routes, so a base starting\n * with it would be read as a global's route instead.\n */\nconst GLOBALS_PREFIX = '/globals'\n\n/**\n * Payload looks a request's first segment up on `payload.collections`, a plain object, so one of\n * `Object.prototype`'s keys finds something there and every request fails before any endpoint runs.\n */\nconst INHERITED_KEYS: ReadonlySet<string> = new Set(Object.getOwnPropertyNames(Object.prototype))\n\nconst firstSegment = (path: string): string => path.split('/')[1] ?? ''\n\nexport const isRouteBase = (value: unknown): value is RouteBase =>\n\ttypeof value === 'string' &&\n\tBASE_PATTERN.test(value) &&\n\t!value.startsWith(GLOBALS_PREFIX) &&\n\t!INHERITED_KEYS.has(firstSegment(value))\n\n/** A `routes.base` option checked for a path Payload can route, or the default when unset. */\nexport const resolveRouteBase = (value: unknown): RouteBase => {\n\tif (value === undefined) {\n\t\treturn DEFAULT_ROUTE_BASE\n\t}\n\tif (typeof value === 'string' && value.startsWith(GLOBALS_PREFIX)) {\n\t\tthrow new Error(\n\t\t\t`analytics: routes.base \"${value}\" starts with \"${GLOBALS_PREFIX}\", which Payload routes to its globals; choose another first segment`\n\t\t)\n\t}\n\tif (typeof value === 'string' && INHERITED_KEYS.has(firstSegment(value))) {\n\t\tthrow new Error(\n\t\t\t`analytics: routes.base \"${value}\" starts with \"${firstSegment(value)}\", a name every JavaScript object carries, which Payload would take for a collection; choose another first segment`\n\t\t)\n\t}\n\tif (!isRouteBase(value)) {\n\t\tthrow new Error(\n\t\t\t`analytics: routes.base must be a path of plain segments such as \"${DEFAULT_ROUTE_BASE}\" (letters, digits, \"-\", \"_\", \".\" and \"~\", no trailing slash), got ${typeof value === 'string' ? `\"${value}\"` : typeof value}`\n\t\t)\n\t}\n\treturn value\n}\n\n/** The base's first segment, which Payload compares against every collection slug. */\nexport const routeBaseSegment = (base: RouteBase): string => firstSegment(base)\n\n/**\n * The collection that would take every request under the base: Payload hands `<api>/<segment>/...`\n * to the collection slugged `<segment>` before it tries a root endpoint.\n */\nexport const shadowingCollection = (\n\tbase: RouteBase,\n\tslugs: Iterable<string>\n): string | undefined => {\n\tconst segment = routeBaseSegment(base)\n\tfor (const slug of slugs) {\n\t\tif (slug === segment) {\n\t\t\treturn slug\n\t\t}\n\t}\n\treturn undefined\n}\n\n/** Refuses a base some collection would shadow, naming that collection and the option to change. */\nexport const assertRouteBaseUnshadowed = (base: RouteBase, slugs: Iterable<string>): void => {\n\tconst slug = shadowingCollection(base, slugs)\n\tif (slug !== undefined) {\n\t\tthrow new Error(\n\t\t\t`analytics: the \"${slug}\" collection's slug is the first segment of routes.base \"${base}\", so Payload would hand every analytics request to that collection. Set routes.base to a path whose first segment is no collection's slug.`\n\t\t)\n\t}\n}\n\n/** What the plugin leaves under its key in `config.admin.custom`. */\nexport interface AnalyticsAdminCustom {\n\troutes: { base: RouteBase }\n}\n\n/** The slice of a root endpoint the route checks read. */\nexport interface RootEndpointShape {\n\tmethod: string\n\tpath: string\n\tcustom?: Record<string, unknown> | undefined\n}\n\n/**\n * The endpoint with the plugin's mark in its `custom`, which is how the route checks tell the\n * plugin's own root endpoints from those registered before it.\n */\nexport const pluginEndpoint = <T extends RootEndpointShape>(endpoint: T): T => ({\n\t...endpoint,\n\tcustom: { ...endpoint.custom, [ANALYTICS_CONFIG_KEY]: true },\n})\n\nexport const isPluginEndpoint = (endpoint: RootEndpointShape): boolean =>\n\tendpoint.custom?.[ANALYTICS_CONFIG_KEY] === true\n\n/** The slice of a Payload config, server or client, the base is read from. */\nexport interface RoutesConfigSource {\n\tadmin?: { custom?: Record<string, unknown> } | undefined\n}\n\n/**\n * The mounts one Payload config resolved, read from `config.admin.custom` by server and client\n * code alike. A config the plugin never touched answers the default base.\n */\nexport const analyticsRoutes = (config: RoutesConfigSource | null | undefined): RoutePaths => {\n\tconst entry = config?.admin?.custom?.[ANALYTICS_CONFIG_KEY]\n\tconst routes = isRecord(entry) ? entry.routes : undefined\n\tconst base = isRecord(routes) ? routes.base : undefined\n\treturn routePaths(isRouteBase(base) ? base : DEFAULT_ROUTE_BASE)\n}\n"],"mappings":";;;;;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,UACwB;CACxB,MAAM,UAAU,iBAAiB,IAAI;CACrC,KAAK,MAAM,QAAQ,OAClB,IAAI,SAAS,SACZ,OAAO;AAIV;;AAGA,MAAa,6BAA6B,MAAiB,UAAkC;CAC5F,MAAM,OAAO,oBAAoB,MAAM,KAAK;CAC5C,IAAI,SAAS,KAAA,GACZ,MAAM,IAAI,MACT,mBAAmB,KAAK,2DAA2D,KAAK,4IACzF;AAEF;;;;;AAkBA,MAAa,kBAA+C,cAAoB;CAC/E,GAAG;CACH,QAAQ;EAAE,GAAG,SAAS;GAAS,uBAAuB;CAAK;AAC5D;AAEA,MAAa,oBAAoB,aAChC,SAAS,SAAS,0BAA0B;;;;;AAW7C,MAAa,mBAAmB,WAA8D;CAC7F,MAAM,QAAQ,QAAQ,OAAO,SAAS;CACtC,MAAM,SAAS,SAAS,KAAK,IAAI,MAAM,SAAS,KAAA;CAChD,MAAM,OAAO,SAAS,MAAM,IAAI,OAAO,OAAO,KAAA;CAC9C,OAAO,WAAW,YAAY,IAAI,IAAI,OAAA,KAAyB;AAChE"}
|
|
@@ -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\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,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,YAAsC;CACzD,MAAM,WAAoB,QAAQ,IAAI,SAAS,YAAY;CAC3D,IAAI,oBAAoB,KACvB,OAAO;CAER,MAAM,0BAAU,IAAI,IAAgB;CACpC,QAAQ,IAAI,SAAS,cAAc,OAAO;CAC1C,OAAO;AACR;;AAGA,MAAM,cAAc,OAAO,SAAkB,MAAc,UAAwC;CAClG,IAAI;EACH,MAAM,MAAM;CACb,SAAS,KAAK;EACb,QAAQ,QAAQ,KAAK,sBAAsB,KAAK,WAAW,OAAO,GAAG,GAAG;CACzE;AACD;;;;;AAMA,MAAM,UACL,SACA,SACA,cACU;CACV,MAAM,OAAO,IAAI,IAAI,WAAW,YAAY,CAAC,CAAC;CAC9C,MAAM,WAAW,SAAS,YAAY,CAAC,GAAG,QAAQ,YAAY,CAAC,KAAK,IAAI,OAAO,CAAC;CAChF,M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Content":["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 { ConnectionRecheck } from '../providers/connectionCheck'\nimport type { ProviderStatusStore } from '../providers/status'\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/** Each provider document's last connection result, kept while the providers collection runs. */\n\tproviderStatus?: ProviderStatusStore\n\t/** A fresh adapter of one stored provider document, for its Test connection button. */\n\tproviderAdapter?: (id: string) => Promise<AnalyticsAdapter | null>\n\t/** The saved version of the provider document an adapter was built from, if it was. */\n\tproviderVersionOf?: (adapter: AnalyticsAdapter) => string | undefined\n\t/**\n\t * Background checks of a scope's failing provider documents, under a `fallback` policy or a\n\t * policy function.\n\t */\n\tproviderRecheck?: ConnectionRecheck\n\t/** Reports a provider status row that could not be read, written or cleared, at most once a minute. */\n\tproviderStatusWarning?: (message: string) => void\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":";;;;;;;;;;;AAuPA,MAAM,oBAAoB,UACzB,SAAS,KAAK,KAAK,OAAO,MAAM,WAAW,cAAc,OAAO,MAAM,aAAa;;AAGpF,MAAa,oBACZ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AAgB,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"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { UIFieldClientProps } from "payload";
|
|
2
|
+
//#region src/providers/ProviderConnection.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* The provider form's Connection panel: what the document's connection last came to. Its Test
|
|
5
|
+
* connection button sits beside Save (`ProviderConnectionTest`) and hands the panel its result.
|
|
6
|
+
*
|
|
7
|
+
* @beta
|
|
8
|
+
*/
|
|
9
|
+
declare function ProviderConnection(_props: UIFieldClientProps): import("react/jsx-runtime").JSX.Element;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { ProviderConnection };
|
|
12
|
+
//# sourceMappingURL=ProviderConnection.d.ts.map
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { keys } from "../translations/keys.js";
|
|
3
|
+
import { PROVIDER_NAMES } from "./ids.js";
|
|
4
|
+
import { connectionStateOf, vendorWordsOf } from "./connectionState.js";
|
|
5
|
+
import { useTranslation as useTranslation$1 } from "../translations/useTranslation.js";
|
|
6
|
+
import { viewerNow } from "../ui/viewerClock.js";
|
|
7
|
+
import { useProviderStatus, useProviderStatusUrl } from "./providerStatusClient.js";
|
|
8
|
+
import "../ui/analytics.css";
|
|
9
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
10
|
+
import { Banner, FieldLabel, Pill, ShimmerEffect, fieldBaseClass, useConfig, useFormFields } from "@payloadcms/ui";
|
|
11
|
+
import { formatDate } from "@payloadcms/ui/shared";
|
|
12
|
+
//#region src/providers/ProviderConnection.tsx
|
|
13
|
+
const STATE_LABEL = {
|
|
14
|
+
works: keys.providerConnectionConnected,
|
|
15
|
+
refused: keys.providerConnectionNotConnected,
|
|
16
|
+
unreachable: keys.providerConnectionNoAnswer,
|
|
17
|
+
unchecked: keys.providerConnectionUnchecked
|
|
18
|
+
};
|
|
19
|
+
/** The status pill's tone: green works, red refused, yellow no answer, gray not checked yet. */
|
|
20
|
+
const STATE_PILL = {
|
|
21
|
+
works: "success",
|
|
22
|
+
refused: "error",
|
|
23
|
+
unreachable: "warning",
|
|
24
|
+
unchecked: "light-gray"
|
|
25
|
+
};
|
|
26
|
+
const HELP = {
|
|
27
|
+
refused: keys.providerConnectionRefusedHelp,
|
|
28
|
+
unreachable: keys.providerConnectionUnreachableHelp
|
|
29
|
+
};
|
|
30
|
+
const REASON_HELP = {
|
|
31
|
+
incomplete: keys.providerConnectionIncompleteHelp,
|
|
32
|
+
unknownSite: keys.providerConnectionUnknownSiteHelp
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* The provider form's Connection panel: what the document's connection last came to. Its Test
|
|
36
|
+
* connection button sits beside Save (`ProviderConnectionTest`) and hands the panel its result.
|
|
37
|
+
*
|
|
38
|
+
* @beta
|
|
39
|
+
*/
|
|
40
|
+
function ProviderConnection(_props) {
|
|
41
|
+
const { config } = useConfig();
|
|
42
|
+
const provider = useFormFields(([fields]) => fields.provider?.value);
|
|
43
|
+
const { i18n, t } = useTranslation$1();
|
|
44
|
+
const url = useProviderStatusUrl();
|
|
45
|
+
const status = useProviderStatus(url);
|
|
46
|
+
const state = url === void 0 ? "unchecked" : status ? connectionStateOf(status) : void 0;
|
|
47
|
+
const when = (iso) => iso ? formatDate({
|
|
48
|
+
date: iso,
|
|
49
|
+
i18n,
|
|
50
|
+
pattern: config.admin.dateFormat
|
|
51
|
+
}) : void 0;
|
|
52
|
+
const failed = state === "refused" || state === "unreachable";
|
|
53
|
+
const pausedUntil = status?.pausedUntil && Date.parse(status.pausedUntil) > viewerNow().getTime() ? when(status.pausedUntil) : void 0;
|
|
54
|
+
const shown = [
|
|
55
|
+
[keys.providerConnectionLastSuccess, when(status?.lastSuccessAt)],
|
|
56
|
+
[keys.providerConnectionLastError, failed ? when(status?.lastErrorAt) : void 0],
|
|
57
|
+
[keys.providerConnectionResumes, pausedUntil]
|
|
58
|
+
].filter((fact) => fact[1] !== void 0);
|
|
59
|
+
const words = failed && status?.errorDetail ? vendorWordsOf(status.errorDetail) : void 0;
|
|
60
|
+
const help = (state === "refused" && status?.errorReason ? REASON_HELP[status.errorReason] : void 0) ?? (state === "refused" && provider === "posthog" ? keys.providerConnectionRefusedHelpPosthog : state === "refused" && provider === "ga4" ? keys.providerConnectionRefusedHelpGa4 : state ? HELP[state] : void 0);
|
|
61
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
62
|
+
className: `${fieldBaseClass} analytics-provider-connection`,
|
|
63
|
+
children: [/* @__PURE__ */ jsx(FieldLabel, {
|
|
64
|
+
as: "span",
|
|
65
|
+
label: t(keys.providerConnectionLabel)
|
|
66
|
+
}), /* @__PURE__ */ jsxs("div", {
|
|
67
|
+
className: "analytics-provider-connection__body",
|
|
68
|
+
children: [/* @__PURE__ */ jsxs("ul", {
|
|
69
|
+
"aria-live": "polite",
|
|
70
|
+
className: "analytics-provider-connection__facts",
|
|
71
|
+
children: [/* @__PURE__ */ jsxs("li", { children: [/* @__PURE__ */ jsx("span", {
|
|
72
|
+
className: "analytics-provider-connection__fact-label",
|
|
73
|
+
children: `${t(keys.providerConnectionStatus)}:\u00a0`
|
|
74
|
+
}), state ? /* @__PURE__ */ jsx(Pill, {
|
|
75
|
+
className: "analytics-provider-connection__status",
|
|
76
|
+
pillStyle: STATE_PILL[state],
|
|
77
|
+
size: "small",
|
|
78
|
+
children: t(STATE_LABEL[state])
|
|
79
|
+
}) : /* @__PURE__ */ jsx(ShimmerEffect, {
|
|
80
|
+
height: "calc(var(--base) * 0.8)",
|
|
81
|
+
width: "calc(var(--base) * 5)"
|
|
82
|
+
})] }), shown.map(([label, value]) => /* @__PURE__ */ jsxs("li", { children: [/* @__PURE__ */ jsx("span", {
|
|
83
|
+
className: "analytics-provider-connection__fact-label",
|
|
84
|
+
children: `${t(label)}:\u00a0`
|
|
85
|
+
}), /* @__PURE__ */ jsx("span", {
|
|
86
|
+
className: "analytics-provider-connection__fact-value",
|
|
87
|
+
children: value
|
|
88
|
+
})] }, label))]
|
|
89
|
+
}), failed && help ? /* @__PURE__ */ jsxs(Banner, {
|
|
90
|
+
type: state === "refused" ? "error" : "default",
|
|
91
|
+
children: [/* @__PURE__ */ jsx("strong", {
|
|
92
|
+
className: "analytics-provider-connection__help",
|
|
93
|
+
children: t(help)
|
|
94
|
+
}), words ? /* @__PURE__ */ jsxs("span", {
|
|
95
|
+
className: "analytics-provider-connection__words",
|
|
96
|
+
children: [words.provider ? `${t(PROVIDER_NAMES[words.provider])}: ` : null, words.message]
|
|
97
|
+
}) : null]
|
|
98
|
+
}) : null]
|
|
99
|
+
})]
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
//#endregion
|
|
103
|
+
export { ProviderConnection };
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=ProviderConnection.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProviderConnection.js","names":["useTranslation"],"sources":["../../src/providers/ProviderConnection.tsx"],"sourcesContent":["'use client'\n\nimport {\n\tBanner,\n\tFieldLabel,\n\tfieldBaseClass,\n\tPill,\n\tShimmerEffect,\n\tuseConfig,\n\tuseFormFields,\n} from '@payloadcms/ui'\nimport { formatDate } from '@payloadcms/ui/shared'\nimport type { UIFieldClientProps } from 'payload'\nimport { keys, type TranslationKey } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { viewerNow } from '../ui/viewerClock'\nimport {\n\ttype ConnectionFailureReason,\n\ttype ConnectionState,\n\tconnectionStateOf,\n\tvendorWordsOf,\n} from './connectionState'\nimport { PROVIDER_NAMES } from './ids'\nimport { useProviderStatus, useProviderStatusUrl } from './providerStatusClient'\nimport '../ui/analytics.css'\n\nconst STATE_LABEL: Readonly<Record<ConnectionState, TranslationKey>> = {\n\tworks: keys.providerConnectionConnected,\n\trefused: keys.providerConnectionNotConnected,\n\tunreachable: keys.providerConnectionNoAnswer,\n\tunchecked: keys.providerConnectionUnchecked,\n}\n\n/** The status pill's tone: green works, red refused, yellow no answer, gray not checked yet. */\nconst STATE_PILL: Readonly<\n\tRecord<ConnectionState, 'success' | 'error' | 'warning' | 'light-gray'>\n> = {\n\tworks: 'success',\n\trefused: 'error',\n\tunreachable: 'warning',\n\tunchecked: 'light-gray',\n}\n\nconst HELP: Partial<Record<ConnectionState, TranslationKey>> = {\n\trefused: keys.providerConnectionRefusedHelp,\n\tunreachable: keys.providerConnectionUnreachableHelp,\n}\n\nconst REASON_HELP: Record<ConnectionFailureReason, TranslationKey> = {\n\tincomplete: keys.providerConnectionIncompleteHelp,\n\tunknownSite: keys.providerConnectionUnknownSiteHelp,\n}\n\n/**\n * The provider form's Connection panel: what the document's connection last came to. Its Test\n * connection button sits beside Save (`ProviderConnectionTest`) and hands the panel its result.\n *\n * @beta\n */\nexport function ProviderConnection(_props: UIFieldClientProps) {\n\tconst { config } = useConfig()\n\tconst provider = useFormFields(([fields]) => fields.provider?.value)\n\tconst { i18n, t } = useTranslation()\n\tconst url = useProviderStatusUrl()\n\tconst status = useProviderStatus(url)\n\n\t// A document not saved yet has nothing checked; its button asks for the save.\n\tconst state: ConnectionState | undefined =\n\t\turl === undefined ? 'unchecked' : status ? connectionStateOf(status) : undefined\n\tconst when = (iso: string | undefined) =>\n\t\tiso ? formatDate({ date: iso, i18n, pattern: config.admin.dateFormat }) : undefined\n\tconst failed = state === 'refused' || state === 'unreachable'\n\tconst pausedUntil =\n\t\tstatus?.pausedUntil && Date.parse(status.pausedUntil) > viewerNow().getTime()\n\t\t\t? when(status.pausedUntil)\n\t\t\t: undefined\n\tconst facts: Array<[TranslationKey, string | undefined]> = [\n\t\t[keys.providerConnectionLastSuccess, when(status?.lastSuccessAt)],\n\t\t[keys.providerConnectionLastError, failed ? when(status?.lastErrorAt) : undefined],\n\t\t[keys.providerConnectionResumes, pausedUntil],\n\t]\n\tconst shown = facts.filter((fact): fact is [TranslationKey, string] => fact[1] !== undefined)\n\tconst words = failed && status?.errorDetail ? vendorWordsOf(status.errorDetail) : undefined\n\tconst reasonHelp =\n\t\tstate === 'refused' && status?.errorReason ? REASON_HELP[status.errorReason] : undefined\n\tconst help =\n\t\treasonHelp ??\n\t\t(state === 'refused' && provider === 'posthog'\n\t\t\t? keys.providerConnectionRefusedHelpPosthog\n\t\t\t: state === 'refused' && provider === 'ga4'\n\t\t\t\t? keys.providerConnectionRefusedHelpGa4\n\t\t\t\t: state\n\t\t\t\t\t? HELP[state]\n\t\t\t\t\t: undefined)\n\n\treturn (\n\t\t<div className={`${fieldBaseClass} analytics-provider-connection`}>\n\t\t\t<FieldLabel as=\"span\" label={t(keys.providerConnectionLabel)} />\n\t\t\t<div className=\"analytics-provider-connection__body\">\n\t\t\t\t<ul aria-live=\"polite\" className=\"analytics-provider-connection__facts\">\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<span className=\"analytics-provider-connection__fact-label\">\n\t\t\t\t\t\t\t{`${t(keys.providerConnectionStatus)}:\\u00a0`}\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t{state ? (\n\t\t\t\t\t\t\t<Pill\n\t\t\t\t\t\t\t\tclassName=\"analytics-provider-connection__status\"\n\t\t\t\t\t\t\t\tpillStyle={STATE_PILL[state]}\n\t\t\t\t\t\t\t\tsize=\"small\"\n\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t{t(STATE_LABEL[state])}\n\t\t\t\t\t\t\t</Pill>\n\t\t\t\t\t\t) : (\n\t\t\t\t\t\t\t<ShimmerEffect height=\"calc(var(--base) * 0.8)\" width=\"calc(var(--base) * 5)\" />\n\t\t\t\t\t\t)}\n\t\t\t\t\t</li>\n\t\t\t\t\t{shown.map(([label, value]) => (\n\t\t\t\t\t\t<li key={label}>\n\t\t\t\t\t\t\t<span className=\"analytics-provider-connection__fact-label\">{`${t(label)}:\\u00a0`}</span>\n\t\t\t\t\t\t\t<span className=\"analytics-provider-connection__fact-value\">{value}</span>\n\t\t\t\t\t\t</li>\n\t\t\t\t\t))}\n\t\t\t\t</ul>\n\t\t\t\t{failed && help ? (\n\t\t\t\t\t<Banner type={state === 'refused' ? 'error' : 'default'}>\n\t\t\t\t\t\t<strong className=\"analytics-provider-connection__help\">{t(help)}</strong>\n\t\t\t\t\t\t{words ? (\n\t\t\t\t\t\t\t<span className=\"analytics-provider-connection__words\">\n\t\t\t\t\t\t\t\t{words.provider ? `${t(PROVIDER_NAMES[words.provider])}: ` : null}\n\t\t\t\t\t\t\t\t{words.message}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t) : null}\n\t\t\t\t\t</Banner>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAM,cAAiE;CACtE,OAAO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,QACnC,KAAK,mCACL,QACC,KAAK,SACL,KAAA;CAEN,OACC,qBAAC,OAAD;EAAK,WAAW,GAAG,eAAe;YAAlC,CACC,oBAAC,YAAD;GAAY,IAAG;GAAO,OAAO,EAAE,KAAK,uBAAuB;EAAI,CAAA,GAC/D,qBAAC,OAAD;GAAK,WAAU;aAAf,CACC,qBAAC,MAAD;IAAI,aAAU;IAAS,WAAU;cAAjC,CACC,qBAAC,MAAD,EAAA,UAAA,CACC,oBAAC,QAAD;KAAM,WAAU;eACd,GAAG,EAAE,KAAK,wBAAwB,EAAE;IAChC,CAAA,GACL,QACA,oBAAC,MAAD;KACC,WAAU;KACV,WAAW,WAAW;KACtB,MAAK;eAEJ,EAAE,YAAY,MAAM;IAChB,CAAA,IAEN,oBAAC,eAAD;KAAe,QAAO;KAA0B,OAAM;IAAyB,CAAA,CAE7E,EAAA,CAAA,GACH,MAAM,KAAK,CAAC,OAAO,WACnB,qBAAC,MAAD,EAAA,UAAA,CACC,oBAAC,QAAD;KAAM,WAAU;eAA6C,GAAG,EAAE,KAAK,EAAE;IAAe,CAAA,GACxF,oBAAC,QAAD;KAAM,WAAU;eAA6C;IAAY,CAAA,CACtE,EAAA,GAHK,KAGL,CACJ,CACE;OACH,UAAU,OACV,qBAAC,QAAD;IAAQ,MAAM,UAAU,YAAY,UAAU;cAA9C,CACC,oBAAC,UAAD;KAAQ,WAAU;eAAuC,EAAE,IAAI;IAAU,CAAA,GACxE,QACA,qBAAC,QAAD;KAAM,WAAU;eAAhB,CACE,MAAM,WAAW,GAAG,EAAE,eAAe,MAAM,SAAS,EAAE,MAAM,MAC5D,MAAM,OACF;SACH,IACG;QACL,IACA;IACD;;AAEP"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/providers/ProviderConnectionTest.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The Test connection button beside a provider document's Save, which checks the saved settings
|
|
4
|
+
* with the vendor's cheapest read and hands the result to the Connection panel. Disabled, it says
|
|
5
|
+
* why in its tooltip; a `native` document has nothing to check and shows none.
|
|
6
|
+
*
|
|
7
|
+
* @beta
|
|
8
|
+
*/
|
|
9
|
+
declare function ProviderConnectionTest(): import("react/jsx-runtime").JSX.Element | null;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { ProviderConnectionTest };
|
|
12
|
+
//# sourceMappingURL=ProviderConnectionTest.d.ts.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { keys } from "../translations/keys.js";
|
|
3
|
+
import { connectionStateOf, isProviderStatusResponse } from "./connectionState.js";
|
|
4
|
+
import { useTranslation as useTranslation$1 } from "../translations/useTranslation.js";
|
|
5
|
+
import { requestShaped } from "../ui/data/request.js";
|
|
6
|
+
import { hasConnection, publishProviderStatus, useProviderStatusUrl } from "./providerStatusClient.js";
|
|
7
|
+
import { useCallback, useState } from "react";
|
|
8
|
+
import { jsx } from "react/jsx-runtime";
|
|
9
|
+
import { Button, toast, useDocumentInfo, useFormFields, useFormModified } from "@payloadcms/ui";
|
|
10
|
+
//#region src/providers/ProviderConnectionTest.tsx
|
|
11
|
+
/**
|
|
12
|
+
* The Test connection button beside a provider document's Save, which checks the saved settings
|
|
13
|
+
* with the vendor's cheapest read and hands the result to the Connection panel. Disabled, it says
|
|
14
|
+
* why in its tooltip; a `native` document has nothing to check and shows none.
|
|
15
|
+
*
|
|
16
|
+
* @beta
|
|
17
|
+
*/
|
|
18
|
+
function ProviderConnectionTest() {
|
|
19
|
+
const { hasSavePermission } = useDocumentInfo();
|
|
20
|
+
const modified = useFormModified();
|
|
21
|
+
const provider = useFormFields(([fields]) => fields.provider?.value);
|
|
22
|
+
const { t } = useTranslation$1();
|
|
23
|
+
const url = useProviderStatusUrl();
|
|
24
|
+
const [checking, setChecking] = useState(false);
|
|
25
|
+
const check = useCallback(async () => {
|
|
26
|
+
if (url === void 0) return;
|
|
27
|
+
setChecking(true);
|
|
28
|
+
try {
|
|
29
|
+
const answer = await requestShaped(url, isProviderStatusResponse, { method: "POST" });
|
|
30
|
+
publishProviderStatus(url, answer.status);
|
|
31
|
+
const state = connectionStateOf(answer.status);
|
|
32
|
+
if (answer.checked ? answer.checked.ok : state === "works") toast.success(t(keys.providerConnectionChecked));
|
|
33
|
+
else if (answer.checked || state !== "unchecked") toast.error(t(keys.providerConnectionFailed));
|
|
34
|
+
else toast.info(t(keys.providerConnectionCheckRunning));
|
|
35
|
+
} catch {
|
|
36
|
+
toast.error(t(keys.providerConnectionFailed));
|
|
37
|
+
} finally {
|
|
38
|
+
setChecking(false);
|
|
39
|
+
}
|
|
40
|
+
}, [t, url]);
|
|
41
|
+
if (!hasConnection(provider)) return null;
|
|
42
|
+
const blocked = url === void 0 ? keys.providerConnectionSaveFirst : hasSavePermission === false ? keys.providerConnectionNoPermission : modified ? keys.providerConnectionUnsaved : void 0;
|
|
43
|
+
return /* @__PURE__ */ jsx(Button, {
|
|
44
|
+
buttonStyle: "subtle",
|
|
45
|
+
disabled: blocked !== void 0 || checking,
|
|
46
|
+
margin: false,
|
|
47
|
+
onClick: check,
|
|
48
|
+
...blocked ? { tooltip: t(blocked) } : {},
|
|
49
|
+
children: t(keys.providerConnectionTest)
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { ProviderConnectionTest };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=ProviderConnectionTest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProviderConnectionTest.js","names":["useTranslation"],"sources":["../../src/providers/ProviderConnectionTest.tsx"],"sourcesContent":["'use client'\n\nimport { Button, toast, useDocumentInfo, useFormFields, useFormModified } from '@payloadcms/ui'\nimport { useCallback, useState } from 'react'\nimport { keys } from '../translations/keys'\nimport { useTranslation } from '../translations/useTranslation'\nimport { requestShaped } from '../ui/data/request'\nimport { connectionStateOf, isProviderStatusResponse } from './connectionState'\nimport { hasConnection, publishProviderStatus, useProviderStatusUrl } from './providerStatusClient'\n\n/**\n * The Test connection button beside a provider document's Save, which checks the saved settings\n * with the vendor's cheapest read and hands the result to the Connection panel. Disabled, it says\n * why in its tooltip; a `native` document has nothing to check and shows none.\n *\n * @beta\n */\nexport function ProviderConnectionTest() {\n\tconst { hasSavePermission } = useDocumentInfo()\n\tconst modified = useFormModified()\n\tconst provider = useFormFields(([fields]) => fields.provider?.value)\n\tconst { t } = useTranslation()\n\tconst url = useProviderStatusUrl()\n\tconst [checking, setChecking] = useState(false)\n\n\tconst check = useCallback(async () => {\n\t\tif (url === undefined) {\n\t\t\treturn\n\t\t}\n\t\tsetChecking(true)\n\t\ttry {\n\t\t\tconst answer = await requestShaped(url, isProviderStatusResponse, { method: 'POST' })\n\t\t\tpublishProviderStatus(url, answer.status)\n\t\t\t// A check sent seconds after another is answered from that one, without `checked`.\n\t\t\tconst state = connectionStateOf(answer.status)\n\t\t\tconst works = answer.checked ? answer.checked.ok : state === 'works'\n\t\t\tif (works) {\n\t\t\t\ttoast.success(t(keys.providerConnectionChecked))\n\t\t\t} else if (answer.checked || state !== 'unchecked') {\n\t\t\t\ttoast.error(t(keys.providerConnectionFailed))\n\t\t\t} else {\n\t\t\t\ttoast.info(t(keys.providerConnectionCheckRunning))\n\t\t\t}\n\t\t} catch {\n\t\t\ttoast.error(t(keys.providerConnectionFailed))\n\t\t} finally {\n\t\t\tsetChecking(false)\n\t\t}\n\t}, [t, url])\n\n\tif (!hasConnection(provider)) {\n\t\treturn null\n\t}\n\tconst blocked =\n\t\turl === undefined\n\t\t\t? keys.providerConnectionSaveFirst\n\t\t\t: hasSavePermission === false\n\t\t\t\t? keys.providerConnectionNoPermission\n\t\t\t\t: modified\n\t\t\t\t\t? keys.providerConnectionUnsaved\n\t\t\t\t\t: undefined\n\n\treturn (\n\t\t<Button\n\t\t\tbuttonStyle=\"subtle\"\n\t\t\tdisabled={blocked !== undefined || checking}\n\t\t\tmargin={false}\n\t\t\tonClick={check}\n\t\t\t{...(blocked ? { tooltip: t(blocked) } : {})}\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AA;AAEV"}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*
|
|
6
6
|
* @beta
|
|
7
7
|
*/
|
|
8
|
-
declare function ProvidersListNotice(): import("react/jsx-runtime").JSX.Element;
|
|
8
|
+
declare function ProvidersListNotice(): import("react/jsx-runtime").JSX.Element | null;
|
|
9
9
|
//#endregion
|
|
10
10
|
export { ProvidersListNotice };
|
|
11
11
|
//# sourceMappingURL=ProvidersListNotice.d.ts.map
|
|
@@ -6,7 +6,7 @@ import { requestSources } from "../fields/config/fetchSources.js";
|
|
|
6
6
|
import { SourcesNoticeBanner } from "../ui/components/SourcesNoticeBanner.js";
|
|
7
7
|
import { useEffect, useState } from "react";
|
|
8
8
|
import { jsx } from "react/jsx-runtime";
|
|
9
|
-
import { useConfig } from "@payloadcms/ui";
|
|
9
|
+
import { Gutter, useConfig } from "@payloadcms/ui";
|
|
10
10
|
//#region src/providers/ProvidersListNotice.tsx
|
|
11
11
|
/**
|
|
12
12
|
* The providers list's note to a tenant reading the platform's source until it adds its own. Read
|
|
@@ -28,7 +28,8 @@ function ProvidersListNotice() {
|
|
|
28
28
|
}), () => {});
|
|
29
29
|
return () => controller.abort();
|
|
30
30
|
}, [url, scope]);
|
|
31
|
-
|
|
31
|
+
const notice = read?.scope === scope ? read.notice : void 0;
|
|
32
|
+
return notice ? /* @__PURE__ */ jsx(Gutter, { children: /* @__PURE__ */ jsx(SourcesNoticeBanner, { notice }) }) : null;
|
|
32
33
|
}
|
|
33
34
|
//#endregion
|
|
34
35
|
export { ProvidersListNotice };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ProvidersListNotice.js","names":[],"sources":["../../src/providers/ProvidersListNotice.tsx"],"sourcesContent":["'use client'\n\nimport { useConfig } from '@payloadcms/ui'\nimport { useEffect, useState } from 'react'\nimport { requestSources, type SourcesNotice } from '../fields/config/fetchSources'\nimport { apiPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport { SourcesNoticeBanner } from '../ui/components/SourcesNoticeBanner'\nimport { useRequestScope } from '../ui/data/useRequestScope'\n\n/**\n * The providers list's note to a tenant reading the platform's source until it adds its own. Read\n * past the shared cache: this list is where a source is added, and a cached listing outlives that.\n *\n * @beta\n */\nexport function ProvidersListNotice() {\n\tconst { config } = useConfig()\n\tconst url = apiPath(config, analyticsRoutes(config).sources)\n\tconst scope = useRequestScope()\n\tconst [read, setRead] = useState<{ scope: string; notice: SourcesNotice | undefined }>()\n\n\tuseEffect(() => {\n\t\tif (!scope) {\n\t\t\treturn\n\t\t}\n\t\tconst controller = new AbortController()\n\t\t// A listing that fails says nothing here: the list itself works without the note.\n\t\trequestSources(url, controller.signal).then(\n\t\t\t(listing) => setRead({ scope, notice: listing.notice }),\n\t\t\t() => {}\n\t\t)\n\t\treturn () => controller.abort()\n\t}, [url, scope])\n\n\
|
|
1
|
+
{"version":3,"file":"ProvidersListNotice.js","names":[],"sources":["../../src/providers/ProvidersListNotice.tsx"],"sourcesContent":["'use client'\n\nimport { Gutter, useConfig } from '@payloadcms/ui'\nimport { useEffect, useState } from 'react'\nimport { requestSources, type SourcesNotice } from '../fields/config/fetchSources'\nimport { apiPath } from '../plugin/apiPath'\nimport { analyticsRoutes } from '../plugin/routes'\nimport { SourcesNoticeBanner } from '../ui/components/SourcesNoticeBanner'\nimport { useRequestScope } from '../ui/data/useRequestScope'\n\n/**\n * The providers list's note to a tenant reading the platform's source until it adds its own. Read\n * past the shared cache: this list is where a source is added, and a cached listing outlives that.\n *\n * @beta\n */\nexport function ProvidersListNotice() {\n\tconst { config } = useConfig()\n\tconst url = apiPath(config, analyticsRoutes(config).sources)\n\tconst scope = useRequestScope()\n\tconst [read, setRead] = useState<{ scope: string; notice: SourcesNotice | undefined }>()\n\n\tuseEffect(() => {\n\t\tif (!scope) {\n\t\t\treturn\n\t\t}\n\t\tconst controller = new AbortController()\n\t\t// A listing that fails says nothing here: the list itself works without the note.\n\t\trequestSources(url, controller.signal).then(\n\t\t\t(listing) => setRead({ scope, notice: listing.notice }),\n\t\t\t() => {}\n\t\t)\n\t\treturn () => controller.abort()\n\t}, [url, scope])\n\n\tconst notice = read?.scope === scope ? read.notice : undefined\n\t// Payload renders `beforeList` outside the list's Gutter, so the note brings its own.\n\treturn notice ? (\n\t\t<Gutter>\n\t\t\t<SourcesNoticeBanner notice={notice} />\n\t\t</Gutter>\n\t) : null\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,SAAgB,sBAAsB;CACrC,MAAM,EAAE,WAAW,UAAU;CAC7B,MAAM,MAAM,QAAQ,QAAQ,gBAAgB,MAAM,EAAE,OAAO;CAC3D,MAAM,QAAQ,gBAAgB;CAC9B,MAAM,CAAC,MAAM,WAAW,SAA+D;CAEvF,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,aAAa,IAAI,gBAAgB;EAEvC,eAAe,KAAK,WAAW,MAAM,EAAE,MACrC,YAAY,QAAQ;GAAE;GAAO,QAAQ,QAAQ;EAAO,CAAC,SAChD,CAAC,CACR;EACA,aAAa,WAAW,MAAM;CAC/B,GAAG,CAAC,KAAK,KAAK,CAAC;CAEf,MAAM,SAAS,MAAM,UAAU,QAAQ,KAAK,SAAS,KAAA;CAErD,OAAO,SACN,oBAAC,QAAD,EAAA,UACC,oBAAC,qBAAD,EAA6B,OAAS,CAAA,EAC/B,CAAA,IACL;AACL"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CollectionFieldOverride } from "../plugin/collectionFields.js";
|
|
2
|
-
import { ProviderId } from "./
|
|
2
|
+
import { ProviderId } from "./ids.js";
|
|
3
3
|
import { CollectionConfig, Field, FieldAccess, PayloadRequest, TextField, TextareaField } from "payload";
|
|
4
4
|
|
|
5
5
|
//#region src/providers/collection.d.ts
|