@10x-media/analytics 1.0.0-beta.16 → 1.0.0-beta.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/dist/adapters/ga4/ga4.js +33 -2
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +4 -1
- package/dist/adapters/ga4/measurementId.js.map +1 -1
- package/dist/adapters/ga4/propertyId.js +17 -0
- package/dist/adapters/ga4/propertyId.js.map +1 -0
- package/dist/adapters/http/fetchJson.js +24 -1
- package/dist/adapters/http/fetchJson.js.map +1 -1
- package/dist/adapters/plausible/plausible.js +16 -1
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/plausible/siteId.js +31 -0
- package/dist/adapters/plausible/siteId.js.map +1 -0
- package/dist/adapters/posthog/posthog.js +17 -3
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/umami/umami.js +34 -7
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/charts/series.js +1 -1
- package/dist/core/contract.d.ts +16 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +1 -1
- package/dist/core/options.js +1 -1
- package/dist/core/options.js.map +1 -1
- package/dist/core/scopedRead.js +62 -14
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/sourceErrors.js +12 -1
- package/dist/core/sourceErrors.js.map +1 -1
- package/dist/core/sourceOptions.js +1 -1
- package/dist/core/sourceOptions.js.map +1 -1
- package/dist/core/sourcePolicy.d.ts +8 -1
- package/dist/core/sourcePolicy.js.map +1 -1
- package/dist/core/throttle.js +3 -1
- package/dist/core/throttle.js.map +1 -1
- package/dist/exports/adapters/contract.d.ts +1 -1
- package/dist/exports/adapters/ga4.d.ts +2 -2
- package/dist/exports/adapters/native.d.ts +2 -2
- package/dist/exports/adapters/plausible.d.ts +2 -2
- package/dist/exports/adapters/posthog.d.ts +2 -2
- package/dist/exports/adapters/umami.d.ts +2 -2
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/next.d.ts +2 -2
- package/dist/exports/testing.d.ts +2 -2
- package/dist/exports/types.d.ts +3 -3
- package/dist/fields/config/fetchSources.js +1 -1
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/goals/collection.js +3 -2
- package/dist/goals/collection.js.map +1 -1
- package/dist/goals/resolver.js +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +50 -4
- package/dist/index.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +1 -1
- package/dist/native/nativeAdapter.js +1 -1
- package/dist/plugin/createRuntime.js +57 -13
- package/dist/plugin/createRuntime.js.map +1 -1
- package/dist/plugin/pluginCollections.js +4 -1
- package/dist/plugin/pluginCollections.js.map +1 -1
- package/dist/plugin/providerStatusEndpoint.js +80 -0
- package/dist/plugin/providerStatusEndpoint.js.map +1 -0
- package/dist/plugin/queryEndpoint.js +1 -1
- package/dist/plugin/queryEndpoint.js.map +1 -1
- package/dist/plugin/readContextForRequest.d.ts +4 -3
- package/dist/plugin/readContextForRequest.js +2 -2
- package/dist/plugin/readContextForRequest.js.map +1 -1
- package/dist/plugin/refreshEndpoint.js +1 -1
- package/dist/plugin/routes.d.ts +5 -0
- package/dist/plugin/routes.js +1 -0
- package/dist/plugin/routes.js.map +1 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/providers/ProviderConnection.d.ts +12 -0
- package/dist/providers/ProviderConnection.js +105 -0
- package/dist/providers/ProviderConnection.js.map +1 -0
- package/dist/providers/ProviderConnectionTest.d.ts +12 -0
- package/dist/providers/ProviderConnectionTest.js +55 -0
- package/dist/providers/ProviderConnectionTest.js.map +1 -0
- package/dist/providers/ProvidersListNotice.d.ts +1 -1
- package/dist/providers/ProvidersListNotice.js +3 -2
- package/dist/providers/ProvidersListNotice.js.map +1 -1
- package/dist/providers/collection.d.ts +1 -1
- package/dist/providers/collection.js +97 -38
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/connectionCheck.d.ts +1 -0
- package/dist/providers/connectionCheck.js +80 -0
- package/dist/providers/connectionCheck.js.map +1 -0
- package/dist/providers/connectionState.js +53 -0
- package/dist/providers/connectionState.js.map +1 -0
- package/dist/providers/factory.d.ts +1 -3
- package/dist/providers/factory.js +18 -21
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/hosts.js +20 -6
- package/dist/providers/hosts.js.map +1 -1
- package/dist/providers/ids.d.ts +6 -0
- package/dist/providers/ids.js +32 -0
- package/dist/providers/ids.js.map +1 -0
- package/dist/providers/providerStatusClient.js +60 -0
- package/dist/providers/providerStatusClient.js.map +1 -0
- package/dist/providers/registry.js +56 -20
- package/dist/providers/registry.js.map +1 -1
- package/dist/providers/retarget.js +39 -8
- package/dist/providers/retarget.js.map +1 -1
- package/dist/providers/secrets.d.ts +1 -1
- package/dist/providers/secrets.js.map +1 -1
- package/dist/providers/status.d.ts +1 -0
- package/dist/providers/status.js +181 -0
- package/dist/providers/status.js.map +1 -0
- package/dist/surfacing/classifyError.js +37 -5
- package/dist/surfacing/classifyError.js.map +1 -1
- package/dist/surfacing/engine.js +2 -2
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/lanes.js +29 -22
- package/dist/surfacing/lanes.js.map +1 -1
- package/dist/surfacing/rebucket.js +1 -1
- package/dist/testing/settle.d.ts +2 -1
- package/dist/testing/settle.js +6 -2
- package/dist/testing/settle.js.map +1 -1
- package/dist/tracker/sinks/ga4.js +2 -2
- package/dist/translations/ar.js +40 -8
- package/dist/translations/ar.js.map +1 -1
- package/dist/translations/de.js +40 -8
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +40 -8
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +40 -8
- package/dist/translations/es.js.map +1 -1
- package/dist/translations/fr.js +40 -8
- package/dist/translations/fr.js.map +1 -1
- package/dist/translations/id.js +40 -8
- package/dist/translations/id.js.map +1 -1
- package/dist/translations/keys.d.ts +32 -0
- package/dist/translations/keys.js +32 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +40 -8
- package/dist/translations/ko.js.map +1 -1
- package/dist/translations/pt.js +40 -8
- package/dist/translations/pt.js.map +1 -1
- package/dist/translations/ru.js +40 -8
- package/dist/translations/ru.js.map +1 -1
- package/dist/translations/uk.js +40 -8
- package/dist/translations/uk.js.map +1 -1
- package/dist/translations/zh.js +40 -8
- package/dist/translations/zh.js.map +1 -1
- package/dist/ui/analytics.css +63 -0
- package/dist/ui/components/SourcesNoticeBanner.js +4 -3
- package/dist/ui/components/SourcesNoticeBanner.js.map +1 -1
- package/dist/view/ViewSections.js +9 -2
- package/dist/view/ViewSections.js.map +1 -1
- package/dist/view/sections/EmptyStates.js +5 -4
- package/dist/view/sections/EmptyStates.js.map +1 -1
- package/dist/view/sections/OverviewCards.js +6 -2
- package/dist/view/sections/OverviewCards.js.map +1 -1
- package/dist/view/sections/SourceConnectionNote.js +56 -0
- package/dist/view/sections/SourceConnectionNote.js.map +1 -0
- package/dist/view/viewProps.d.ts +2 -0
- package/dist/view/viewProps.js +2 -1
- package/dist/view/viewProps.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createRuntime.js","names":[],"sources":["../../src/plugin/createRuntime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { itemCollectionsOf } from '../binding/report'\nimport { resolveTrackerConfig } from '../capture/trackerConfig'\nimport { currentDate, currentTime } from '../core/clock'\nimport type { AnalyticsResult } from '../core/contract'\nimport { TASK_SLUGS } from '../core/jobs'\nimport { monotonicMs } from '../core/monotonic'\nimport {\n\tcookielessTrustNotice,\n\tDEFAULT_BINDING_SCOPE_FIELD,\n\tdocumentsFillHeldTenant,\n\tfollowingCountsWithoutConsent,\n\ttype ResolvedOptions,\n\trevenueOffWarning,\n\ttype ScopeCallSite,\n\ttrackerAutoCapture,\n\tuntrustedAddressNotice,\n\twithoutConsentUnsetNotice,\n} from '../core/options'\nimport { type AdapterRegistry, withoutRevenue } from '../core/registry'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { throttled } from '../core/throttle'\nimport { isRecord } from '../core/values'\nimport { hostHoldsWriteLock, sqliteTransactionsNotice } from '../db/detachedWrite'\nimport { configGoalsResolver, createGoalsResolver, type GoalsResolver } from '../goals/resolver'\nimport { createHeartbeatWatch } from '../maintenance/heartbeat'\nimport { stateLease, stateStoreOf } from '../maintenance/lease'\nimport { trackServerEvent } from '../native/ingest/serverTrack'\nimport { NATIVE_ADAPTER_ID } from '../native/nativeAdapter'\nimport { createGuardedFetch } from '../net/guardedFetch'\nimport { configTokenBackend } from '../providers/refresh'\nimport { createProviderRegistry, type ProviderPlan } from '../providers/registry'\nimport { emptyTrackerConfig, type TrackerConfigSource } from '../site/getTrackerConfig'\nimport { createCacheSweeper, SWEEP_LEASE, SWEEP_LEASE_MS } from '../surfacing/cacheSweep'\nimport { collectionCacheStore } from '../surfacing/collectionCacheStore'\nimport { type CacheOperation, createEngine } from '../surfacing/engine'\nimport { createEpochStore } from '../surfacing/epoch'\nimport { ABANDON_AFTER_MS, createLanes, pooledConcurrency } from '../surfacing/lanes'\nimport { createMemo } from '../surfacing/memo'\nimport { collectingPageData } from './buildPhase'\nimport { type ExpectedCollection, recheckCollections } from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport { narrowStatsGlobal } from './jobsAccess'\nimport { createKeepAlive } from './keepAlive'\nimport { isProductionBuild } from './peers'\nimport { assertRoutesReachable } from './routeChecks'\nimport { type AnalyticsRuntime, getRuntime, type RuntimeFactory } from './runtime'\nimport { validateScopeField } from './scopeFieldBoot'\n\n/** How often a failing read cache, or a throwing `hooks.afterRead`, is reported, at most. */\nconst CACHE_WARN_EVERY_MS = 60_000\n\n/** node-postgres' own default for the pool's `max`. */\nconst PG_DEFAULT_POOL_MAX = 10\n\n/** The host's node-postgres pool size, or undefined on another database. */\nconst postgresPoolMax = (payload: Payload): number | undefined => {\n\tconst db: unknown = payload.db\n\tif (!isRecord(db) || db.name !== 'postgres') {\n\t\treturn undefined\n\t}\n\tconst pool = db.pool\n\tconst options = isRecord(pool) && isRecord(pool.options) ? pool.options : db.poolOptions\n\tconst max = isRecord(options) ? options.max : undefined\n\treturn typeof max === 'number' && Number.isFinite(max) && max > 0 ? max : PG_DEFAULT_POOL_MAX\n}\n\ninterface RuntimeFactoryArgs {\n\tresolved: ResolvedOptions\n\t/** What the collection checks found worth a warning, said once at init. */\n\tnotices: readonly string[]\n\t/** The plugin's collections as the boot checked them, held to that again in the assembled config. */\n\tcollections: readonly ExpectedCollection[]\n\t/** The config registry, with revenue already removed where the install measures no money. */\n\tregistry: AdapterRegistry\n\tresolveScope: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\tresolveCurrency: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n}\n\n/** Where the install's runtime provider adapters come from. */\nconst providerPlanOf = (resolved: ResolvedOptions): ProviderPlan => {\n\tconst { resolve, collection } = resolved.providers\n\tif (resolve) {\n\t\treturn { kind: 'resolve', resolve }\n\t}\n\tif (!collection.enabled) {\n\t\treturn { kind: 'static' }\n\t}\n\tconst nativeAdapter = resolved.adapters.find((adapter) => adapter.id === NATIVE_ADAPTER_ID)\n\treturn {\n\t\tkind: 'collection',\n\t\tslug: collection.slug,\n\t\tscopeField: collection.scopeField,\n\t\ttypes: collection.types,\n\t\t...(nativeAdapter ? { nativeAdapter } : {}),\n\t}\n}\n\n/** Config goals merged with the goals collection of one instance, when the install runs it. */\nconst goalsResolverFor = (\n\tpayload: Payload,\n\tresolved: ResolvedOptions,\n\tnow: () => number\n): GoalsResolver =>\n\tresolved.goalsCollection.enabled\n\t\t? createGoalsResolver({\n\t\t\t\tpayload,\n\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tconfig: resolved.goals,\n\t\t\t\tpurchase: resolved.purchaseGoal,\n\t\t\t\tnow,\n\t\t\t})\n\t\t: configGoalsResolver(resolved.goals, resolved.purchaseGoal)\n\n/**\n * Native reads stay out of the global cap, so a slow vendor never queues them; on a scoped install\n * every config adapter serves all scopes, so one scope holds at most half of its lane.\n */\nconst lanesFor = (payload: Payload, resolved: ResolvedOptions, plan: ProviderPlan) => {\n\tconst { concurrency } = resolved.cache\n\tconst configAdapters = new Set(resolved.adapters)\n\tconst poolMax = postgresPoolMax(payload)\n\treturn createLanes({\n\t\tglobal: concurrency.global,\n\t\tperSource: concurrency.perSource,\n\t\tlocal: {\n\t\t\tis: (adapter) => adapter.id === NATIVE_ADAPTER_ID,\n\t\t\t...(poolMax === undefined ? {} : { capacity: pooledConcurrency(poolMax) }),\n\t\t},\n\t\t...(resolved.scoped ? { shared: (adapter) => configAdapters.has(adapter) } : {}),\n\t\t...(plan.kind === 'resolve' ? { rebuilt: (adapter) => !configAdapters.has(adapter) } : {}),\n\t\tonAbandon: (adapter) =>\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: a request to the \"${adapter.id}\" source ignored its abort signal and was still out ${ABANDON_AFTER_MS / 1000} seconds after its read gave up, so its slot was given back and it counts as a timeout. An adapter must pass ctx.signal (or the signal ctx.upstream hands it) to every request it sends; this is said once per source.`\n\t\t\t),\n\t})\n}\n\n/** The runtime fields config time settled outright, alike for every instance. */\nconst settledFieldsOf = (args: RuntimeFactoryArgs) => {\n\tconst { resolved } = args\n\tconst providers = resolved.providers.collection\n\treturn {\n\t\tregistry: args.registry,\n\t\tresolveScope: args.resolveScope,\n\t\t...(resolved.scope.member ? { member: resolved.scope.member } : {}),\n\t\tresolveTimezone: args.resolveTimezone,\n\t\t// Only when the install configured one: absent, every read path skips the scope\n\t\t// resolution the lookup would have needed and revenue stays a plain number.\n\t\t...(resolved.revenue.enabled && resolved.revenue.currency !== undefined\n\t\t\t? { resolveCurrency: args.resolveCurrency }\n\t\t\t: {}),\n\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t...(resolved.sources.policies.size > 0 ? { sourcePolicies: resolved.sources.policies } : {}),\n\t\t...(resolved.sources.defaultSource ? { defaultSource: resolved.sources.defaultSource } : {}),\n\t\tcaptureSlots: resolved.capture.slots,\n\t\tcapturePaths: resolved.capture.paths,\n\t\tcaptureProxy: resolved.capture.proxy,\n\t\ttrustedProxyHops: resolved.trustedProxyHops,\n\t\ttrustedPlatform: resolved.trustedPlatform,\n\t\tallowedOrigins: resolved.capture.allowedOrigins,\n\t\t...(resolved.capture.exclusion ? { exclusion: resolved.capture.exclusion } : {}),\n\t\tcaptureGate: resolved.capture.gate,\n\t\t...(resolved.capture.withoutConsent\n\t\t\t? { captureWithoutConsent: resolved.capture.withoutConsent }\n\t\t\t: {}),\n\t\tautoCapture: trackerAutoCapture(\n\t\t\tresolved.capture.autoCapture,\n\t\t\titemCollectionsOf(resolved.bindings).size > 0\n\t\t),\n\t\tcaptureSkip: resolved.capture.skip,\n\t\tgoals: resolved.goals,\n\t\tpurchaseGoal: resolved.purchaseGoal,\n\t\t...(resolved.goalsCollection.enabled\n\t\t\t? { goalsCollectionSlug: resolved.goalsCollection.slug }\n\t\t\t: {}),\n\t\t...(providers.enabled\n\t\t\t? {\n\t\t\t\t\tprovidersCollection: {\n\t\t\t\t\t\tslug: providers.slug,\n\t\t\t\t\t\tscopeField: providers.scopeField,\n\t\t\t\t\t\t...(providers.sourceAccess ? { sourceAccess: providers.sourceAccess } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tingestPath: resolved.adapters.find((adapter) => adapter.ingest)?.ingest?.path,\n\t\tscoped: resolved.scoped,\n\t\tcountryFlags: resolved.countryFlags,\n\t\t...(resolved.scope.label ? { scopeLabel: resolved.scope.label } : {}),\n\t\t...(resolved.scope.list ? { scopeList: resolved.scope.list } : {}),\n\t\t...(resolved.cache.store ? {} : { cacheCollectionSlug: resolved.cache.collection.slug }),\n\t\tconfigAdapterIds: new Set(resolved.adapters.map((adapter) => adapter.id)),\n\t\tcrossScope: resolved.access.crossScope,\n\t\treadAccess: resolved.access.read,\n\t\tviewAccess: resolved.access.view,\n\t\tbindings: resolved.bindings,\n\t\tttl: resolved.cache.ttl,\n\t\tcomparison: resolved.widgets.comparison,\n\t\tadapters: resolved.adapters,\n\t} satisfies Partial<AnalyticsRuntime>\n}\n\nconst BINDING_SCOPE_FIELD_REMEDY =\n\t\"name the field this collection's documents carry their tenant in, or set it to false to read the request's own scope\"\n\n/** Fails boot on a `scopeField` the assembled config lacks, for every collection naming one. */\nconst validateScopeFields = (payload: Payload, resolved: ResolvedOptions): void => {\n\tif (resolved.scoped && resolved.goalsCollection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'goals.collection.scopeField',\n\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t})\n\t}\n\tif (resolved.scoped && resolved.providers.collection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'providers.collection.scopeField',\n\t\t\tslug: resolved.providers.collection.slug,\n\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t})\n\t}\n\tfor (const [slug, binding] of Object.entries(resolved.bindings)) {\n\t\tif (binding.scopeField === false) {\n\t\t\tcontinue\n\t\t}\n\t\tvalidateScopeField(payload, {\n\t\t\toption: `collections.${slug}.scopeField`,\n\t\t\tslug,\n\t\t\tscopeField: binding.scopeField,\n\t\t\tremedy:\n\t\t\t\tbinding.scopeField === DEFAULT_BINDING_SCOPE_FIELD\n\t\t\t\t\t? `\"${DEFAULT_BINDING_SCOPE_FIELD}\" is the default on a scoped install when scopeField is not set, so ${BINDING_SCOPE_FIELD_REMEDY}`\n\t\t\t\t\t: BINDING_SCOPE_FIELD_REMEDY,\n\t\t})\n\t}\n}\n\n/**\n * Everything config time settled, turned into a runtime per Payload instance on demand, plus the\n * checks that need the assembled config: other plugins add collections and fields after this one.\n */\nexport const createRuntimeFactory = (\n\targs: RuntimeFactoryArgs\n): RuntimeFactory & TrackerConfigSource => {\n\tconst { resolved } = args\n\tconst money = resolved.revenue.enabled\n\tconst providers = resolved.providers.collection\n\tconst plan = providerPlanOf(resolved)\n\tconst rechecked = new WeakSet<object>()\n\t/** The checks only the assembled config can answer, once per config. */\n\tconst checkAssembled = (payload: Payload): void => {\n\t\tif (rechecked.has(payload.config)) {\n\t\t\treturn\n\t\t}\n\t\tassertRoutesReachable(resolved.routes.base, payload.config)\n\t\trecheckCollections(payload.config.collections ?? [], args.collections, payload.db?.name)\n\t\tnarrowStatsGlobal(payload)\n\t\trechecked.add(payload.config)\n\t}\n\treturn {\n\t\tcreate: (payload) => {\n\t\t\t// Here rather than in onInit alone: a worker booted without onInit and an HMR reload build\n\t\t\t// their runtime on first use, from a config other plugins may have changed.\n\t\t\tcheckAssembled(payload)\n\t\t\tfor (const adapter of resolved.adapters) {\n\t\t\t\tadapter.attach?.(payload)\n\t\t\t}\n\t\t\t// The adapters a `providers.resolve` builds from editor-written settings need the same\n\t\t\t// guarded connection the collection's own documents get.\n\t\t\tconst providerConnections =\n\t\t\t\tproviders.enabled || resolved.providers.resolve\n\t\t\t\t\t? createGuardedFetch({\n\t\t\t\t\t\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\t\t\t\t\t\twarn: (message) => payload.logger?.warn(message),\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst epoch = createEpochStore(payload)\n\t\t\tconst now = currentTime\n\t\t\tconst warn = (message: string) => payload.logger?.warn(message)\n\t\t\tconst registry = createProviderRegistry({\n\t\t\t\tpayload,\n\t\t\t\tplan,\n\t\t\t\tbase: { adapters: resolved.adapters, defaultId: resolved.defaultAdapter },\n\t\t\t\tregistry: args.registry,\n\t\t\t\tnarrow: money ? (scoped) => scoped : withoutRevenue,\n\t\t\t\thosts: resolved.providers.hosts,\n\t\t\t\tfetch: providerConnections?.fetch,\n\t\t\t\tsdks: resolved.sdks,\n\t\t\t\twithoutConsent: {\n\t\t\t\t\theldWithoutConsent: documentsFillHeldTenant(resolved, true),\n\t\t\t\t\tfollowingCountsWithoutConsent: followingCountsWithoutConsent(\n\t\t\t\t\t\tresolved.capture.withoutConsent\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t...(plan.kind === 'resolve'\n\t\t\t\t\t? { tokens: createEpochStore(payload, { now, backend: configTokenBackend(payload) }) }\n\t\t\t\t\t: {}),\n\t\t\t\tnow,\n\t\t\t})\n\t\t\tconst goals = goalsResolverFor(payload, resolved, now)\n\t\t\t// Only where something can change at runtime; an install configured in code keys every read\n\t\t\t// on the fixed epoch.\n\t\t\tconst configEpoch =\n\t\t\t\tplan.kind === 'static' && !resolved.goalsCollection.enabled\n\t\t\t\t\t? undefined\n\t\t\t\t\t: async (scope?: string | null): Promise<string> => {\n\t\t\t\t\t\t\tconst [providerEpoch, goalsEpoch] = await Promise.all([\n\t\t\t\t\t\t\t\tregistry.epoch(scope ?? null),\n\t\t\t\t\t\t\t\tgoals.epoch(scope),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\treturn `${providerEpoch}.${goalsEpoch}`\n\t\t\t\t\t\t}\n\t\t\tconst store =\n\t\t\t\tresolved.cache.store ??\n\t\t\t\tcollectionCacheStore(payload, { slug: resolved.cache.collection.slug })\n\t\t\tconst memo = createMemo<AnalyticsResult>({ now })\n\t\t\tconst sweeper = createCacheSweeper({\n\t\t\t\tstore,\n\t\t\t\tlease: () => stateLease(payload, SWEEP_LEASE, SWEEP_LEASE_MS),\n\t\t\t\tnow: currentDate,\n\t\t\t\twarn,\n\t\t\t\tdeferred: () => hostHoldsWriteLock(payload),\n\t\t\t})\n\t\t\t// Sync has no fallback: a runner that stopped is only noticed here, by the reads it leaves stale.\n\t\t\tconst { jobs } = resolved\n\t\t\tconst syncWatch =\n\t\t\t\tresolved.sync.enabled && jobs !== false\n\t\t\t\t\t? createHeartbeatWatch({\n\t\t\t\t\t\t\ttask: TASK_SLUGS.sync,\n\t\t\t\t\t\t\tschedule: jobs.sync,\n\t\t\t\t\t\t\tstate: () => stateStoreOf(payload),\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\twarn,\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst cacheWarning = throttled(warn, { now: monotonicMs, intervalMs: CACHE_WARN_EVERY_MS })\n\t\t\tconst onStoreError = (err: unknown, operation: CacheOperation) => {\n\t\t\t\tcacheWarning(\n\t\t\t\t\t`analytics: the read cache failed to ${operation}, reads go on without it: ${String(err)}`\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst keepAlive = createKeepAlive({\n\t\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next marks the processes serving its requests, the only ones `after()` works in\n\t\t\t\tenv: process.env,\n\t\t\t\twarn,\n\t\t\t})\n\t\t\tconst afterRead = resolved.hooks.afterRead\n\t\t\tconst hookWarning = throttled(warn, { now: monotonicMs, intervalMs: CACHE_WARN_EVERY_MS })\n\t\t\tconst engine = createEngine({\n\t\t\t\tpayload,\n\t\t\t\tstore,\n\t\t\t\tmemo,\n\t\t\t\tlanes: lanesFor(payload, resolved, plan),\n\t\t\t\tcoldReadsPerScope: resolved.cache.concurrency.perScope,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tepoch,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tnow,\n\t\t\t\tonError: (err, adapterId) => {\n\t\t\t\t\twarn(`analytics: read failed for adapter \"${adapterId}\": ${describeWithCauses(err)}`)\n\t\t\t\t},\n\t\t\t\tonStoreError,\n\t\t\t\tonWrite: () => sweeper.maybeSweep(),\n\t\t\t\t...(syncWatch ? { onRead: () => syncWatch.maybeCheck() } : {}),\n\t\t\t\tkeepAlive,\n\t\t\t\t...(afterRead\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tafterRead,\n\t\t\t\t\t\t\tonHookError: (err: unknown) =>\n\t\t\t\t\t\t\t\thookWarning(\n\t\t\t\t\t\t\t\t\t`analytics: hooks.afterRead threw, reads are answered without it: ${String(err)}`\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...settledFieldsOf(args),\n\t\t\t\tresolveRegistry: registry.resolve,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tconfigChanged: (collection, scopes) =>\n\t\t\t\t\tcollection === 'providers' ? registry.changed(scopes) : goals.changed(scopes),\n\t\t\t\trefreshProviders: registry.refresh,\n\t\t\t\t...(registry.granted ? { providerGranted: registry.granted } : {}),\n\t\t\t\tresolveGoals: goals.resolve,\n\t\t\t\tresolveGoalsDetailed: goals.resolveDetailed,\n\t\t\t\tlistGoals: goals.listReadable,\n\t\t\t\tlistGoalsAcross: goals.listAcross,\n\t\t\t\t...(providerConnections ? { providerFetch: providerConnections.fetch } : {}),\n\t\t\t\t// Refreshes and sweeps still running write to the database, which closes after this.\n\t\t\t\tclose: async () => {\n\t\t\t\t\tawait Promise.all([engine.close(), sweeper.idle(), syncWatch?.idle()])\n\t\t\t\t\tawait registry.close()\n\t\t\t\t\tawait providerConnections?.close()\n\t\t\t\t},\n\t\t\t\ttrack: (event, opts) => trackServerEvent(payload, event, opts),\n\t\t\t\tengine,\n\t\t\t\tepoch,\n\t\t\t\tmemo,\n\t\t\t\tcache: { store, sweeper },\n\t\t\t}\n\t\t},\n\t\tresolved,\n\t\ttrackerConfig: async (payload, req, draft) => {\n\t\t\tconst runtime = getRuntime(payload)\n\t\t\treturn runtime ? resolveTrackerConfig({ runtime, req, draft }) : emptyTrackerConfig(req)\n\t\t},\n\t\tvalidate: async (payload) => {\n\t\t\tcheckAssembled(payload)\n\t\t\t// `next build` boots once per worker and serves nothing; the server that does says these.\n\t\t\tconst warn = collectingPageData()\n\t\t\t\t? () => undefined\n\t\t\t\t: (message: string) => payload.logger?.warn(message)\n\t\t\tfor (const notice of args.notices) {\n\t\t\t\twarn(notice)\n\t\t\t}\n\t\t\tif (!resolved.cache.store) {\n\t\t\t\tawait collectionCacheStore(payload, { slug: resolved.cache.collection.slug }).prepare()\n\t\t\t}\n\t\t\tvalidateScopeFields(payload, resolved)\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await loadEncrypted()\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst moneyOff = revenueOffWarning(resolved)\n\t\t\tif (moneyOff) {\n\t\t\t\twarn(moneyOff)\n\t\t\t}\n\t\t\tconst spoofable = untrustedAddressNotice(resolved, isProductionBuild())\n\t\t\tif (spoofable) {\n\t\t\t\twarn(spoofable)\n\t\t\t}\n\t\t\tconst collapsing = cookielessTrustNotice(resolved, isProductionBuild())\n\t\t\tif (collapsing) {\n\t\t\t\twarn(collapsing)\n\t\t\t}\n\t\t\tconst withoutConsent = withoutConsentUnsetNotice(resolved)\n\t\t\tif (withoutConsent) {\n\t\t\t\twarn(withoutConsent)\n\t\t\t}\n\t\t\tconst transactions = sqliteTransactionsNotice(payload)\n\t\t\tif (transactions) {\n\t\t\t\twarn(transactions)\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAM,sBAAsB;;AAG5B,MAAM,sBAAsB;;AAG5B,MAAM,mBAAmB,YAAyC;CACjE,MAAM,KAAc,QAAQ;CAC5B,IAAI,CAAC,SAAS,EAAE,KAAK,GAAG,SAAS,YAChC;CAED,MAAM,OAAO,GAAG;CAChB,MAAM,UAAU,SAAS,IAAI,KAAK,SAAS,KAAK,OAAO,IAAI,KAAK,UAAU,GAAG;CAC7E,MAAM,MAAM,SAAS,OAAO,IAAI,QAAQ,MAAM,KAAA;CAC9C,OAAO,OAAO,QAAQ,YAAY,O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AK,SACzB,KAAK,MAAM;GAEZ,IAAI,CAAC,SAAS,MAAM,OACnB,MAAM,qBAAqB,SAAS,EAAE,MAAM,SAAS,MAAM,WAAW,KAAK,CAAC,EAAE,QAAQ;GAEvF,oBAAoB,SAAS,QAAQ;GACrC,IAAI,SAAS,UAAU,WAAW,SAAS;IAC1C,MAAM,EAAE,0BAA0B,MAAM,cAAc;IACtD,MAAM,sBAAsB,SAAS,SAAS,UAAU,WAAW,YAAY,IAAI;GACpF;GACA,MAAM,WAAW,kBAAkB,QAAQ;GAC3C,IAAI,UACH,KAAK,QAAQ;GAEd,MAAM,YAAY,uBAAuB,UAAU,kBAAkB,CAAC;GACtE,IAAI,WACH,KAAK,SAAS;GAEf,MAAM,aAAa,sBAAsB,UAAU,kBAAkB,CAAC;GACtE,IAAI,YACH,KAAK,UAAU;GAEhB,MAAM,iBAAiB,0BAA0B,QAAQ;GACzD,IAAI,gBACH,KAAK,cAAc;GAEpB,MAAM,eAAe,yBAAyB,OAAO;GACrD,IAAI,cACH,KAAK,YAAY;EAEnB;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"createRuntime.js","names":[],"sources":["../../src/plugin/createRuntime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { itemCollectionsOf } from '../binding/report'\nimport { resolveTrackerConfig } from '../capture/trackerConfig'\nimport { currentDate, currentTime } from '../core/clock'\nimport type { AnalyticsAdapter, AnalyticsResult } from '../core/contract'\nimport { TASK_SLUGS } from '../core/jobs'\nimport { monotonicMs } from '../core/monotonic'\nimport {\n\tcookielessTrustNotice,\n\tDEFAULT_BINDING_SCOPE_FIELD,\n\tdocumentsFillHeldTenant,\n\tfollowingCountsWithoutConsent,\n\ttype ResolvedOptions,\n\trevenueOffWarning,\n\ttype ScopeCallSite,\n\ttrackerAutoCapture,\n\tuntrustedAddressNotice,\n\twithoutConsentUnsetNotice,\n} from '../core/options'\nimport { type AdapterRegistry, withoutRevenue } from '../core/registry'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { throttled, WARN_EVERY_MS } from '../core/throttle'\nimport { isRecord } from '../core/values'\nimport { hostHoldsWriteLock, sqliteTransactionsNotice } from '../db/detachedWrite'\nimport { configGoalsResolver, createGoalsResolver, type GoalsResolver } from '../goals/resolver'\nimport { createHeartbeatWatch } from '../maintenance/heartbeat'\nimport { stateLease, stateStoreOf } from '../maintenance/lease'\nimport { trackServerEvent } from '../native/ingest/serverTrack'\nimport { NATIVE_ADAPTER_ID } from '../native/nativeAdapter'\nimport { createGuardedFetch } from '../net/guardedFetch'\nimport { createConnectionRecheck } from '../providers/connectionCheck'\nimport { documentIdOf } from '../providers/ids'\nimport { configTokenBackend } from '../providers/refresh'\nimport { createProviderRegistry, type ProviderPlan } from '../providers/registry'\nimport {\n\tconnectionOutcomeOf,\n\ttype ProviderStatusStore,\n\tproviderStatusStore,\n} from '../providers/status'\nimport { emptyTrackerConfig, type TrackerConfigSource } from '../site/getTrackerConfig'\nimport { BREAKER_MAX_MS } from '../surfacing/breaker'\nimport { createCacheSweeper, SWEEP_LEASE, SWEEP_LEASE_MS } from '../surfacing/cacheSweep'\nimport { collectionCacheStore } from '../surfacing/collectionCacheStore'\nimport { type CacheOperation, createEngine } from '../surfacing/engine'\nimport { createEpochStore } from '../surfacing/epoch'\nimport { ABANDON_AFTER_MS, createLanes, pooledConcurrency } from '../surfacing/lanes'\nimport { createMemo } from '../surfacing/memo'\nimport { collectingPageData } from './buildPhase'\nimport { type ExpectedCollection, recheckCollections } from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport { narrowStatsGlobal } from './jobsAccess'\nimport { createKeepAlive } from './keepAlive'\nimport { isProductionBuild } from './peers'\nimport { assertRoutesReachable } from './routeChecks'\nimport { type AnalyticsRuntime, getRuntime, type RuntimeFactory } from './runtime'\nimport { validateScopeField } from './scopeFieldBoot'\n\n/** node-postgres' own default for the pool's `max`. */\nconst PG_DEFAULT_POOL_MAX = 10\n\n/** The host's node-postgres pool size, or undefined on another database. */\nconst postgresPoolMax = (payload: Payload): number | undefined => {\n\tconst db: unknown = payload.db\n\tif (!isRecord(db) || db.name !== 'postgres') {\n\t\treturn undefined\n\t}\n\tconst pool = db.pool\n\tconst options = isRecord(pool) && isRecord(pool.options) ? pool.options : db.poolOptions\n\tconst max = isRecord(options) ? options.max : undefined\n\treturn typeof max === 'number' && Number.isFinite(max) && max > 0 ? max : PG_DEFAULT_POOL_MAX\n}\n\ninterface RuntimeFactoryArgs {\n\tresolved: ResolvedOptions\n\t/** What the collection checks found worth a warning, said once at init. */\n\tnotices: readonly string[]\n\t/** The plugin's collections as the boot checked them, held to that again in the assembled config. */\n\tcollections: readonly ExpectedCollection[]\n\t/** The config registry, with revenue already removed where the install measures no money. */\n\tregistry: AdapterRegistry\n\tresolveScope: (req: PayloadRequest, callSite: ScopeCallSite) => Promise<string | null>\n\tresolveTimezone: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\tresolveCurrency: (req: PayloadRequest, scope?: string | null) => Promise<string | undefined>\n}\n\n/** Where the install's runtime provider adapters come from. */\nconst providerPlanOf = (resolved: ResolvedOptions): ProviderPlan => {\n\tconst { resolve, collection } = resolved.providers\n\tif (resolve) {\n\t\treturn { kind: 'resolve', resolve }\n\t}\n\tif (!collection.enabled) {\n\t\treturn { kind: 'static' }\n\t}\n\tconst nativeAdapter = resolved.adapters.find((adapter) => adapter.id === NATIVE_ADAPTER_ID)\n\treturn {\n\t\tkind: 'collection',\n\t\tslug: collection.slug,\n\t\tscopeField: collection.scopeField,\n\t\ttypes: collection.types,\n\t\t...(nativeAdapter ? { nativeAdapter } : {}),\n\t}\n}\n\n/** Config goals merged with the goals collection of one instance, when the install runs it. */\nconst goalsResolverFor = (\n\tpayload: Payload,\n\tresolved: ResolvedOptions,\n\tnow: () => number\n): GoalsResolver =>\n\tresolved.goalsCollection.enabled\n\t\t? createGoalsResolver({\n\t\t\t\tpayload,\n\t\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t\t\tscoped: resolved.scoped,\n\t\t\t\tconfig: resolved.goals,\n\t\t\t\tpurchase: resolved.purchaseGoal,\n\t\t\t\tnow,\n\t\t\t})\n\t\t: configGoalsResolver(resolved.goals, resolved.purchaseGoal)\n\n/**\n * Native reads stay out of the global cap, so a slow vendor never queues them; on a scoped install\n * every config adapter serves all scopes, so one scope holds at most half of its lane.\n */\nconst lanesFor = (\n\tpayload: Payload,\n\tresolved: ResolvedOptions,\n\t{\n\t\tplan,\n\t\tstatus,\n\t\tstatusWarning,\n\t\tversionOf,\n\t}: {\n\t\tplan: ProviderPlan\n\t\tstatus: ProviderStatusStore | undefined\n\t\tstatusWarning: (message: string) => void\n\t\t/** The saved version of the provider document a pooled adapter was built from. */\n\t\tversionOf: ((adapter: AnalyticsAdapter) => string | undefined) | undefined\n\t}\n) => {\n\tconst { concurrency } = resolved.cache\n\tconst configAdapters = new Set(resolved.adapters)\n\tconst configIds = new Set(resolved.adapters.map((adapter) => adapter.id))\n\tconst poolMax = postgresPoolMax(payload)\n\treturn createLanes({\n\t\tglobal: concurrency.global,\n\t\tperSource: concurrency.perSource,\n\t\tlocal: {\n\t\t\tis: (adapter) => adapter.id === NATIVE_ADAPTER_ID,\n\t\t\t...(poolMax === undefined ? {} : { capacity: pooledConcurrency(poolMax) }),\n\t\t},\n\t\t...(resolved.scoped ? { shared: (adapter) => configAdapters.has(adapter) } : {}),\n\t\t...(plan.kind === 'resolve' ? { rebuilt: (adapter) => !configAdapters.has(adapter) } : {}),\n\t\tonAbandon: (adapter) =>\n\t\t\tpayload.logger?.warn(\n\t\t\t\t`analytics: a request to the \"${adapter.id}\" source ignored its abort signal and was still out ${ABANDON_AFTER_MS / 1000} seconds after its read gave up, so its slot was given back and it counts as a timeout. An adapter must pass ctx.signal (or the signal ctx.upstream hands it) to every request it sends; this is said once per source.`\n\t\t\t),\n\t\t...(status\n\t\t\t? {\n\t\t\t\t\tonOutcome: (adapter, outcome, health) => {\n\t\t\t\t\t\tconst docId = configIds.has(adapter.id) ? undefined : documentIdOf(adapter.id)\n\t\t\t\t\t\tconst told = connectionOutcomeOf(outcome, health)\n\t\t\t\t\t\tif (docId === undefined || told === undefined) {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst version = versionOf?.(adapter)\n\t\t\t\t\t\tconst options = version === undefined ? { throttle: true } : { throttle: true, version }\n\t\t\t\t\t\tstatus.record(docId, told, options).catch((err: unknown) => {\n\t\t\t\t\t\t\tstatusWarning(\n\t\t\t\t\t\t\t\t`analytics: the connection status of provider document \"${docId}\" could not be saved, reads go on without it: ${String(err)}`\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t})\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t})\n}\n\n/** The runtime fields config time settled outright, alike for every instance. */\nconst settledFieldsOf = (args: RuntimeFactoryArgs) => {\n\tconst { resolved } = args\n\tconst providers = resolved.providers.collection\n\treturn {\n\t\tregistry: args.registry,\n\t\tresolveScope: args.resolveScope,\n\t\t...(resolved.scope.member ? { member: resolved.scope.member } : {}),\n\t\tresolveTimezone: args.resolveTimezone,\n\t\t// Only when the install configured one: absent, every read path skips the scope\n\t\t// resolution the lookup would have needed and revenue stays a plain number.\n\t\t...(resolved.revenue.enabled && resolved.revenue.currency !== undefined\n\t\t\t? { resolveCurrency: args.resolveCurrency }\n\t\t\t: {}),\n\t\tplatformAdapterId: resolved.platformAdapter,\n\t\t...(resolved.sources.policies.size > 0 ? { sourcePolicies: resolved.sources.policies } : {}),\n\t\t...(resolved.sources.defaultSource ? { defaultSource: resolved.sources.defaultSource } : {}),\n\t\tcaptureSlots: resolved.capture.slots,\n\t\tcapturePaths: resolved.capture.paths,\n\t\tcaptureProxy: resolved.capture.proxy,\n\t\ttrustedProxyHops: resolved.trustedProxyHops,\n\t\ttrustedPlatform: resolved.trustedPlatform,\n\t\tallowedOrigins: resolved.capture.allowedOrigins,\n\t\t...(resolved.capture.exclusion ? { exclusion: resolved.capture.exclusion } : {}),\n\t\tcaptureGate: resolved.capture.gate,\n\t\t...(resolved.capture.withoutConsent\n\t\t\t? { captureWithoutConsent: resolved.capture.withoutConsent }\n\t\t\t: {}),\n\t\tautoCapture: trackerAutoCapture(\n\t\t\tresolved.capture.autoCapture,\n\t\t\titemCollectionsOf(resolved.bindings).size > 0\n\t\t),\n\t\tcaptureSkip: resolved.capture.skip,\n\t\tgoals: resolved.goals,\n\t\tpurchaseGoal: resolved.purchaseGoal,\n\t\t...(resolved.goalsCollection.enabled\n\t\t\t? { goalsCollectionSlug: resolved.goalsCollection.slug }\n\t\t\t: {}),\n\t\t...(providers.enabled\n\t\t\t? {\n\t\t\t\t\tprovidersCollection: {\n\t\t\t\t\t\tslug: providers.slug,\n\t\t\t\t\t\tscopeField: providers.scopeField,\n\t\t\t\t\t\t...(providers.sourceAccess ? { sourceAccess: providers.sourceAccess } : {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tingestPath: resolved.adapters.find((adapter) => adapter.ingest)?.ingest?.path,\n\t\tscoped: resolved.scoped,\n\t\tcountryFlags: resolved.countryFlags,\n\t\t...(resolved.scope.label ? { scopeLabel: resolved.scope.label } : {}),\n\t\t...(resolved.scope.list ? { scopeList: resolved.scope.list } : {}),\n\t\t...(resolved.cache.store ? {} : { cacheCollectionSlug: resolved.cache.collection.slug }),\n\t\tconfigAdapterIds: new Set(resolved.adapters.map((adapter) => adapter.id)),\n\t\tcrossScope: resolved.access.crossScope,\n\t\treadAccess: resolved.access.read,\n\t\tviewAccess: resolved.access.view,\n\t\tbindings: resolved.bindings,\n\t\tttl: resolved.cache.ttl,\n\t\tcomparison: resolved.widgets.comparison,\n\t\tadapters: resolved.adapters,\n\t} satisfies Partial<AnalyticsRuntime>\n}\n\nconst BINDING_SCOPE_FIELD_REMEDY =\n\t\"name the field this collection's documents carry their tenant in, or set it to false to read the request's own scope\"\n\n/** Fails boot on a `scopeField` the assembled config lacks, for every collection naming one. */\nconst validateScopeFields = (payload: Payload, resolved: ResolvedOptions): void => {\n\tif (resolved.scoped && resolved.goalsCollection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'goals.collection.scopeField',\n\t\t\tslug: resolved.goalsCollection.slug,\n\t\t\tscopeField: resolved.goalsCollection.scopeField,\n\t\t})\n\t}\n\tif (resolved.scoped && resolved.providers.collection.enabled) {\n\t\tvalidateScopeField(payload, {\n\t\t\toption: 'providers.collection.scopeField',\n\t\t\tslug: resolved.providers.collection.slug,\n\t\t\tscopeField: resolved.providers.collection.scopeField,\n\t\t})\n\t}\n\tfor (const [slug, binding] of Object.entries(resolved.bindings)) {\n\t\tif (binding.scopeField === false) {\n\t\t\tcontinue\n\t\t}\n\t\tvalidateScopeField(payload, {\n\t\t\toption: `collections.${slug}.scopeField`,\n\t\t\tslug,\n\t\t\tscopeField: binding.scopeField,\n\t\t\tremedy:\n\t\t\t\tbinding.scopeField === DEFAULT_BINDING_SCOPE_FIELD\n\t\t\t\t\t? `\"${DEFAULT_BINDING_SCOPE_FIELD}\" is the default on a scoped install when scopeField is not set, so ${BINDING_SCOPE_FIELD_REMEDY}`\n\t\t\t\t\t: BINDING_SCOPE_FIELD_REMEDY,\n\t\t})\n\t}\n}\n\n/**\n * Everything config time settled, turned into a runtime per Payload instance on demand, plus the\n * checks that need the assembled config: other plugins add collections and fields after this one.\n */\nexport const createRuntimeFactory = (\n\targs: RuntimeFactoryArgs\n): RuntimeFactory & TrackerConfigSource => {\n\tconst { resolved } = args\n\tconst money = resolved.revenue.enabled\n\tconst providers = resolved.providers.collection\n\tconst plan = providerPlanOf(resolved)\n\tconst rechecked = new WeakSet<object>()\n\t/** The checks only the assembled config can answer, once per config. */\n\tconst checkAssembled = (payload: Payload): void => {\n\t\tif (rechecked.has(payload.config)) {\n\t\t\treturn\n\t\t}\n\t\tassertRoutesReachable(resolved.routes.base, payload.config)\n\t\trecheckCollections(payload.config.collections ?? [], args.collections, payload.db?.name)\n\t\tnarrowStatsGlobal(payload)\n\t\trechecked.add(payload.config)\n\t}\n\treturn {\n\t\tcreate: (payload) => {\n\t\t\t// Here rather than in onInit alone: a worker booted without onInit and an HMR reload build\n\t\t\t// their runtime on first use, from a config other plugins may have changed.\n\t\t\tcheckAssembled(payload)\n\t\t\tfor (const adapter of resolved.adapters) {\n\t\t\t\tadapter.attach?.(payload)\n\t\t\t}\n\t\t\t// The adapters a `providers.resolve` builds from editor-written settings need the same\n\t\t\t// guarded connection the collection's own documents get.\n\t\t\tconst providerConnections =\n\t\t\t\tproviders.enabled || resolved.providers.resolve\n\t\t\t\t\t? createGuardedFetch({\n\t\t\t\t\t\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\t\t\t\t\t\twarn: (message) => payload.logger?.warn(message),\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst epoch = createEpochStore(payload)\n\t\t\tconst providerStatus = plan.kind === 'collection' ? providerStatusStore(payload) : undefined\n\t\t\tconst now = currentTime\n\t\t\tconst warn = (message: string) => payload.logger?.warn(message)\n\t\t\tconst providerStatusWarning = throttled(warn, { now: monotonicMs, intervalMs: WARN_EVERY_MS })\n\t\t\tconst registry = createProviderRegistry({\n\t\t\t\tpayload,\n\t\t\t\tplan,\n\t\t\t\tbase: { adapters: resolved.adapters, defaultId: resolved.defaultAdapter },\n\t\t\t\tregistry: args.registry,\n\t\t\t\tnarrow: money ? (scoped) => scoped : withoutRevenue,\n\t\t\t\thosts: resolved.providers.hosts,\n\t\t\t\tfetch: providerConnections?.fetch,\n\t\t\t\tsdks: resolved.sdks,\n\t\t\t\twithoutConsent: {\n\t\t\t\t\theldWithoutConsent: documentsFillHeldTenant(resolved, true),\n\t\t\t\t\tfollowingCountsWithoutConsent: followingCountsWithoutConsent(\n\t\t\t\t\t\tresolved.capture.withoutConsent\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t...(plan.kind === 'resolve'\n\t\t\t\t\t? { tokens: createEpochStore(payload, { now, backend: configTokenBackend(payload) }) }\n\t\t\t\t\t: {}),\n\t\t\t\tnow,\n\t\t\t})\n\t\t\tconst providerRecheck =\n\t\t\t\tproviderStatus && registry.documentAdapter\n\t\t\t\t\t? createConnectionRecheck({\n\t\t\t\t\t\t\tpayload,\n\t\t\t\t\t\t\tstore: providerStatus,\n\t\t\t\t\t\t\tadapterFor: registry.documentAdapter,\n\t\t\t\t\t\t\t...(registry.versionOf ? { versionOf: registry.versionOf } : {}),\n\t\t\t\t\t\t\tnow: monotonicMs,\n\t\t\t\t\t\t\tcooldownMs: BREAKER_MAX_MS,\n\t\t\t\t\t\t\twarn,\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst goals = goalsResolverFor(payload, resolved, now)\n\t\t\t// Only where something can change at runtime; an install configured in code keys every read\n\t\t\t// on the fixed epoch.\n\t\t\tconst configEpoch =\n\t\t\t\tplan.kind === 'static' && !resolved.goalsCollection.enabled\n\t\t\t\t\t? undefined\n\t\t\t\t\t: async (scope?: string | null): Promise<string> => {\n\t\t\t\t\t\t\tconst [providerEpoch, goalsEpoch] = await Promise.all([\n\t\t\t\t\t\t\t\tregistry.epoch(scope ?? null),\n\t\t\t\t\t\t\t\tgoals.epoch(scope),\n\t\t\t\t\t\t\t])\n\t\t\t\t\t\t\treturn `${providerEpoch}.${goalsEpoch}`\n\t\t\t\t\t\t}\n\t\t\tconst store =\n\t\t\t\tresolved.cache.store ??\n\t\t\t\tcollectionCacheStore(payload, { slug: resolved.cache.collection.slug })\n\t\t\tconst memo = createMemo<AnalyticsResult>({ now })\n\t\t\tconst sweeper = createCacheSweeper({\n\t\t\t\tstore,\n\t\t\t\tlease: () => stateLease(payload, SWEEP_LEASE, SWEEP_LEASE_MS),\n\t\t\t\tnow: currentDate,\n\t\t\t\twarn,\n\t\t\t\tdeferred: () => hostHoldsWriteLock(payload),\n\t\t\t})\n\t\t\t// Sync has no fallback: a runner that stopped is only noticed here, by the reads it leaves stale.\n\t\t\tconst { jobs } = resolved\n\t\t\tconst syncWatch =\n\t\t\t\tresolved.sync.enabled && jobs !== false\n\t\t\t\t\t? createHeartbeatWatch({\n\t\t\t\t\t\t\ttask: TASK_SLUGS.sync,\n\t\t\t\t\t\t\tschedule: jobs.sync,\n\t\t\t\t\t\t\tstate: () => stateStoreOf(payload),\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\twarn,\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined\n\t\t\tconst cacheWarning = throttled(warn, { now: monotonicMs, intervalMs: WARN_EVERY_MS })\n\t\t\tconst onStoreError = (err: unknown, operation: CacheOperation) => {\n\t\t\t\tcacheWarning(\n\t\t\t\t\t`analytics: the read cache failed to ${operation}, reads go on without it: ${String(err)}`\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst keepAlive = createKeepAlive({\n\t\t\t\t// biome-ignore lint/plugin/noProcessEnv: Next marks the processes serving its requests, the only ones `after()` works in\n\t\t\t\tenv: process.env,\n\t\t\t\twarn,\n\t\t\t})\n\t\t\tconst afterRead = resolved.hooks.afterRead\n\t\t\tconst hookWarning = throttled(warn, { now: monotonicMs, intervalMs: WARN_EVERY_MS })\n\t\t\tconst engine = createEngine({\n\t\t\t\tpayload,\n\t\t\t\tstore,\n\t\t\t\tmemo,\n\t\t\t\tlanes: lanesFor(payload, resolved, {\n\t\t\t\t\tplan,\n\t\t\t\t\tstatus: providerStatus,\n\t\t\t\t\tstatusWarning: providerStatusWarning,\n\t\t\t\t\tversionOf: registry.versionOf,\n\t\t\t\t}),\n\t\t\t\tcoldReadsPerScope: resolved.cache.concurrency.perScope,\n\t\t\t\tttl: resolved.cache.ttl,\n\t\t\t\ttimeoutMs: resolved.cache.timeoutMs,\n\t\t\t\tepoch,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tnow,\n\t\t\t\tonError: (err, adapterId, scope) => {\n\t\t\t\t\twarn(\n\t\t\t\t\t\t`analytics: read failed for adapter \"${adapterId}\" (${scope === null ? 'install-wide' : `scope \"${scope}\"`}): ${describeWithCauses(err)}`\n\t\t\t\t\t)\n\t\t\t\t},\n\t\t\t\tonStoreError,\n\t\t\t\tonWrite: () => sweeper.maybeSweep(),\n\t\t\t\t...(syncWatch ? { onRead: () => syncWatch.maybeCheck() } : {}),\n\t\t\t\tkeepAlive,\n\t\t\t\t...(afterRead\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tafterRead,\n\t\t\t\t\t\t\tonHookError: (err: unknown) =>\n\t\t\t\t\t\t\t\thookWarning(\n\t\t\t\t\t\t\t\t\t`analytics: hooks.afterRead threw, reads are answered without it: ${String(err)}`\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t})\n\t\t\treturn {\n\t\t\t\t...settledFieldsOf(args),\n\t\t\t\tresolveRegistry: registry.resolve,\n\t\t\t\t...(configEpoch ? { configEpoch } : {}),\n\t\t\t\tconfigChanged: (collection, scopes) =>\n\t\t\t\t\tcollection === 'providers' ? registry.changed(scopes) : goals.changed(scopes),\n\t\t\t\trefreshProviders: registry.refresh,\n\t\t\t\t...(registry.granted ? { providerGranted: registry.granted } : {}),\n\t\t\t\tresolveGoals: goals.resolve,\n\t\t\t\tresolveGoalsDetailed: goals.resolveDetailed,\n\t\t\t\tlistGoals: goals.listReadable,\n\t\t\t\tlistGoalsAcross: goals.listAcross,\n\t\t\t\t...(providerConnections ? { providerFetch: providerConnections.fetch } : {}),\n\t\t\t\t...(providerStatus ? { providerStatus, providerStatusWarning } : {}),\n\t\t\t\t...(registry.documentAdapter ? { providerAdapter: registry.documentAdapter } : {}),\n\t\t\t\t...(registry.versionOf ? { providerVersionOf: registry.versionOf } : {}),\n\t\t\t\t...(providerRecheck ? { providerRecheck } : {}),\n\t\t\t\t// Refreshes and sweeps still running write to the database, which closes after this.\n\t\t\t\tclose: async () => {\n\t\t\t\t\tawait Promise.all([\n\t\t\t\t\t\tengine.close(),\n\t\t\t\t\t\tsweeper.idle(),\n\t\t\t\t\t\tsyncWatch?.idle(),\n\t\t\t\t\t\tproviderRecheck?.idle(),\n\t\t\t\t\t])\n\t\t\t\t\tawait providerStatus?.idle()\n\t\t\t\t\tawait registry.close()\n\t\t\t\t\tawait providerConnections?.close()\n\t\t\t\t},\n\t\t\t\ttrack: (event, opts) => trackServerEvent(payload, event, opts),\n\t\t\t\tengine,\n\t\t\t\tepoch,\n\t\t\t\tmemo,\n\t\t\t\tcache: { store, sweeper },\n\t\t\t}\n\t\t},\n\t\tresolved,\n\t\ttrackerConfig: async (payload, req, draft) => {\n\t\t\tconst runtime = getRuntime(payload)\n\t\t\treturn runtime ? resolveTrackerConfig({ runtime, req, draft }) : emptyTrackerConfig(req)\n\t\t},\n\t\tvalidate: async (payload) => {\n\t\t\tcheckAssembled(payload)\n\t\t\t// `next build` boots once per worker and serves nothing; the server that does says these.\n\t\t\tconst warn = collectingPageData()\n\t\t\t\t? () => undefined\n\t\t\t\t: (message: string) => payload.logger?.warn(message)\n\t\t\tfor (const notice of args.notices) {\n\t\t\t\twarn(notice)\n\t\t\t}\n\t\t\tif (!resolved.cache.store) {\n\t\t\t\tawait collectionCacheStore(payload, { slug: resolved.cache.collection.slug }).prepare()\n\t\t\t}\n\t\t\tvalidateScopeFields(payload, resolved)\n\t\t\tif (resolved.providers.collection.enabled) {\n\t\t\t\tconst { validateEncryptedBoot } = await loadEncrypted()\n\t\t\t\tawait validateEncryptedBoot(payload, resolved.providers.collection.encryption?.keys)\n\t\t\t}\n\t\t\tconst moneyOff = revenueOffWarning(resolved)\n\t\t\tif (moneyOff) {\n\t\t\t\twarn(moneyOff)\n\t\t\t}\n\t\t\tconst spoofable = untrustedAddressNotice(resolved, isProductionBuild())\n\t\t\tif (spoofable) {\n\t\t\t\twarn(spoofable)\n\t\t\t}\n\t\t\tconst collapsing = cookielessTrustNotice(resolved, isProductionBuild())\n\t\t\tif (collapsing) {\n\t\t\t\twarn(collapsing)\n\t\t\t}\n\t\t\tconst withoutConsent = withoutConsentUnsetNotice(resolved)\n\t\t\tif (withoutConsent) {\n\t\t\t\twarn(withoutConsent)\n\t\t\t}\n\t\t\tconst transactions = sqliteTransactionsNotice(payload)\n\t\t\tif (transactions) {\n\t\t\t\twarn(transactions)\n\t\t\t}\n\t\t},\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,MAAM,sBAAsB;;AAG5B,MAAM,mBAAmB,YAAyC;CACjE,MAAM,KAAc,QAAQ;CAC5B,IAAI,CAAC,SAAS,EAAE,KAAK,GAAG,SAAS,YAChC;CAED,MAAM,OAAO,GAAG;CAChB,MAAM,UAAU,SAAS,IAAI,KAAK,SAAS,KAAK,OAAO,IAAI,KAAK,UAAU,GAAG;CAC7E,MAAM,MAAM,SAAS,OAAO,IAAI,QAAQ,MAAM,KAAA;CAC9C,OAAO,OAAO,QAAQ,YAAY,OAAO,SAAS,GAAG,KAAK,MAAM,IAAI,MAAM;AAC3E;;AAgBA,MAAM,kBAAkB,aAA4C;CACnE,MAAM,EAAE,SAAS,eAAe,SAAS;CACzC,IAAI,SACH,OAAO;EAAE,MAAM;EAAW;CAAQ;CAEnC,IAAI,CAAC,WAAW,SACf,OAAO,EAAE,MAAM,SAAS;CAEzB,MAAM,gBAAgB,SAAS,SAAS,MAAM,YAAY,QAAQ,OAAO,iBAAiB;CAC1F,OAAO;EACN,MAAM;EACN,MAAM,WAAW;EACjB,YAAY,WAAW;EACvB,OAAO,WAAW;EAClB,GAAI,gBAAgB,EAAE,cAAc,IAAI,CAAC;CAC1C;AACD;;AAGA,MAAM,oBACL,SACA,UACA,QAEA,SAAS,gBAAgB,UACtB,oBAAoB;CACpB;CACA,MAAM,SAAS,gBAAgB;CAC/B,YAAY,SAAS,gBAAgB;CACrC,QAAQ,SAAS;CACjB,QAAQ,SAAS;CACjB,UAAU,SAAS;CACnB;AACD,CAAC,IACA,oBAAoB,SAAS,OAAO,SAAS,YAAY;;;;;AA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AAK,YAAY;EAEnB;CACD;AACD"}
|
|
@@ -50,11 +50,14 @@ const providersCollectionOf = async (resolved, callbacks, context) => {
|
|
|
50
50
|
buildSecret,
|
|
51
51
|
isSealed,
|
|
52
52
|
allowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,
|
|
53
|
+
allow: resolved.providers.hosts.allow,
|
|
53
54
|
...connectionAccess ? { connectionAccess } : {},
|
|
54
55
|
...defaultAccess ? { defaultAccess } : {},
|
|
55
56
|
types: providers.types,
|
|
56
57
|
staticLabel: context.staticLabel,
|
|
57
|
-
listNotice: [...resolved.sources.policies.values()].includes("fallback")
|
|
58
|
+
listNotice: [...resolved.sources.policies.values()].includes("fallback"),
|
|
59
|
+
forgetStatus: callbacks.forgetProviderStatus,
|
|
60
|
+
carryStatus: callbacks.carryProviderStatus
|
|
58
61
|
}), {
|
|
59
62
|
role: "providers",
|
|
60
63
|
option: "providers.collection",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pluginCollections.js","names":[],"sources":["../../src/plugin/pluginCollections.ts"],"sourcesContent":["import type { CollectionConfig, Config, PayloadRequest } from 'payload'\nimport type { ResolvedOptions } from '../core/options'\nimport { buildGoalsCollection } from '../goals/collection'\nimport { STATE_SLUG } from '../native/collections/slugs'\nimport { stateCollection } from '../native/collections/state'\nimport type { BuildSecretField, ConnectionFieldAccess } from '../providers/collection'\nimport { buildProvidersCollection } from '../providers/collection'\nimport { cacheCollection } from '../surfacing/cacheCollection'\nimport { syncCollection } from '../sync/collection'\nimport type { StaticLabelFor } from '../translations/staticLabel'\nimport {\n\tcheckEditorCollection,\n\ttype ShapedCollection,\n\tshapeCollection,\n\tslugOfRole,\n} from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport type { ScopeChange } from './scopeChange'\n\n/** What the plugin's collections are registered against. */\nexport interface CollectionContext {\n\t/** `config.db.name`, which decides whether Postgres' identifier limit applies. */\n\tdb: string | undefined\n\t/** Keeps what the boot warns about until the instance can log it. */\n\tnotice: (message: string) => void\n\t/** The install's static labels, its own strings over the built-in ones. */\n\tstaticLabel: StaticLabelFor\n}\n\n/** The collection a shaping produced, its notices handed on. */\nconst noticed = (shaped: ShapedCollection, context: CollectionContext): CollectionConfig => {\n\tfor (const message of shaped.notices) {\n\t\tcontext.notice(message)\n\t}\n\treturn shaped.collection\n}\n\n/** What the providers and goals collections call back into, the same whether the plugin runs or not. */\ninterface CollectionCallbacks {\n\tresolveAdminScope: (req: PayloadRequest) => Promise<string | null>\n\t/** Told what a save to either collection changed; a switched-off install's runtime is absent. */\n\tonChange: (\n\t\tcollection: 'providers' | 'goals'\n\t) => (change: ScopeChange, req: PayloadRequest) => void\n}\n\n/**\n * Who may write a guarded provider field (the connection fields, `isDefault`), when anything\n * narrows the field's own access.\n */\nconst guardedFieldAccessOf = (\n\tresolved: ResolvedOptions,\n\town: ConnectionFieldAccess | undefined\n): ConnectionFieldAccess | undefined => {\n\t// A new document has no stored key to redirect, so only a host's own option gates create; an\n\t// update on a scoped install takes the named cross-scope gate.\n\tconst update = own?.update ?? (resolved.scoped ? resolved.access.crossScope.named : undefined)\n\tconst create = own?.create\n\treturn create || update\n\t\t? { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n\t\t: undefined\n}\n\nconst providersCollectionOf = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig> => {\n\tconst { encryptedField, isSealed, withEncryptedQueryRewrite } = await loadEncrypted()\n\tconst providers = resolved.providers.collection\n\tconst keys = providers.encryption?.keys\n\tconst buildSecret: BuildSecretField = (source) =>\n\t\tencryptedField(source, {\n\t\t\tprotection: 'writeOnly',\n\t\t\taadScope: '10x-analytics:providers',\n\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t...(keys ? { keys } : {}),\n\t\t})\n\tconst connectionAccess = guardedFieldAccessOf(resolved, providers.connectionAccess)\n\tconst defaultAccess = guardedFieldAccessOf(\n\t\tresolved,\n\t\tproviders.defaultAccess ?? providers.connectionAccess\n\t)\n\tconst built = buildProvidersCollection({\n\t\tslug: providers.slug,\n\t\taccess: providers.access,\n\t\tfields: providers.fields,\n\t\toverrides: providers.overrides,\n\t\tonChange: callbacks.onChange('providers'),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: providers.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tbuildSecret,\n\t\tisSealed,\n\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\t...(connectionAccess ? { connectionAccess } : {}),\n\t\t...(defaultAccess ? { defaultAccess } : {}),\n\t\ttypes: providers.types,\n\t\tstaticLabel: context.staticLabel,\n\t\tlistNotice: [...resolved.sources.policies.values()].includes('fallback'),\n\t})\n\tconst checked = checkEditorCollection(built, {\n\t\trole: 'providers',\n\t\toption: 'providers.collection',\n\t\tslug: providers.slug,\n\t\tdb: context.db,\n\t})\n\t// Always wrapped: a second wrap by the host's fields plugin is inert (writeOnly has no blind\n\t// index), while skipping leaks ciphertext when fields() runs before this collection exists.\n\treturn withEncryptedQueryRewrite(checked)\n}\n\nconst goalsCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): CollectionConfig => {\n\tconst goals = resolved.goalsCollection\n\tconst built = buildGoalsCollection({\n\t\tslug: goals.slug,\n\t\taccess: goals.access,\n\t\tfields: goals.fields,\n\t\toverrides: goals.overrides,\n\t\tonChange: callbacks.onChange('goals'),\n\t\trevenue: resolved.revenue.enabled,\n\t\t// A per-scope resolver has no request to answer for here, so only a fixed code is\n\t\t// offered as the default.\n\t\t...(typeof resolved.revenue.currency === 'string'\n\t\t\t? { defaultCurrency: resolved.revenue.currency }\n\t\t\t: {}),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: goals.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn checkEditorCollection(built, {\n\t\trole: 'goals',\n\t\toption: 'goals.collection',\n\t\tslug: goals.slug,\n\t\tdb: context.db,\n\t})\n}\n\n/**\n * The providers and goals collections an install turned on, built exactly alike whether the plugin\n * runs or only keeps its schema (`disabled: true`), so neither drops a field or an index.\n */\nexport const configCollections = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig[]> => [\n\t...(resolved.providers.collection.enabled\n\t\t? [await providersCollectionOf(resolved, callbacks, context)]\n\t\t: []),\n\t...(resolved.goalsCollection.enabled ? [goalsCollectionOf(resolved, callbacks, context)] : []),\n]\n\n/**\n * The sync collection when sync is on, after the host's overrides, built alike whether the plugin\n * runs or not.\n */\nexport const syncCollectionOf = (\n\tresolved: ResolvedOptions,\n\tresolveAdminScope: CollectionCallbacks['resolveAdminScope'],\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (!resolved.sync.enabled) {\n\t\treturn undefined\n\t}\n\tconst { slug, hidden, overrides } = resolved.sync.collection\n\tconst built = syncCollection(slug, {\n\t\thidden,\n\t\taccess: {\n\t\t\tscoped: resolved.scoped,\n\t\t\tscopeField: 'scope',\n\t\t\tresolveScope: resolveAdminScope,\n\t\t\tmember: resolved.scope.member,\n\t\t\tcrossScope: resolved.access.crossScope.named,\n\t\t},\n\t\tread: resolved.access.read,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'sync',\n\t\t\toption: 'sync.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/** The read cache collection after the host's overrides, unless a `cache.store` replaces it. */\nexport const cacheCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (resolved.cache.store) {\n\t\treturn undefined\n\t}\n\tconst { slug, overrides } = resolved.cache.collection\n\tconst built = cacheCollection({ slug, mongo: context.db === 'mongoose' })\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'cache',\n\t\t\toption: 'cache.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/**\n * Whether the install registers a task that takes a lease and stamps a heartbeat, which live in\n * `analytics-state`: sync or warming, while `jobs` registers tasks.\n */\nconst needsStateCollection = (resolved: ResolvedOptions): boolean =>\n\tresolved.jobs !== false && (resolved.sync.enabled || resolved.cache.warm.enabled)\n\n/**\n * `analytics-state` for the sync and warm tasks, after `jobs.state`, unless an adapter (the native\n * engine) registered its own. Refuses `jobs.state` wherever it would shape nothing.\n */\nexport const addStateCollection = (\n\tconfig: Config,\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): void => {\n\tconst option = resolved.jobs === false ? undefined : resolved.jobs.state\n\tconst registered = slugOfRole(config.collections, 'state')\n\tif (option && registered !== undefined) {\n\t\tthrow new Error(\n\t\t\t`analytics: jobs.state shapes the analytics-state collection of an install without native(), but native() registers its own (\"${registered}\"). Rename or reshape it with native({ collections: { state } }) instead.`\n\t\t)\n\t}\n\tif (!needsStateCollection(resolved)) {\n\t\tif (option) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: jobs.state shapes the collection the sync and warm tasks keep their leases in, and this install runs neither. Turn sync or cache.warm on, or remove it.'\n\t\t\t)\n\t\t}\n\t\treturn\n\t}\n\tif (registered !== undefined) {\n\t\treturn\n\t}\n\tconst state = noticed(\n\t\tshapeCollection(stateCollection(option?.slug ?? STATE_SLUG), {\n\t\t\trole: 'state',\n\t\t\toption: 'jobs.state',\n\t\t\tdb: context.db,\n\t\t\t...(option?.overrides ? { overrides: option.overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n\tconfig.collections = [...(config.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":3,"file":"pluginCollections.js","names":[],"sources":["../../src/plugin/pluginCollections.ts"],"sourcesContent":["import type { CollectionConfig, Config, PayloadRequest } from 'payload'\nimport type { ResolvedOptions } from '../core/options'\nimport { buildGoalsCollection } from '../goals/collection'\nimport { STATE_SLUG } from '../native/collections/slugs'\nimport { stateCollection } from '../native/collections/state'\nimport type { BuildSecretField, ConnectionFieldAccess } from '../providers/collection'\nimport { buildProvidersCollection } from '../providers/collection'\nimport { cacheCollection } from '../surfacing/cacheCollection'\nimport { syncCollection } from '../sync/collection'\nimport type { StaticLabelFor } from '../translations/staticLabel'\nimport {\n\tcheckEditorCollection,\n\ttype ShapedCollection,\n\tshapeCollection,\n\tslugOfRole,\n} from './collectionChecks'\nimport { loadEncrypted } from './encrypted'\nimport type { ScopeChange } from './scopeChange'\n\n/** What the plugin's collections are registered against. */\nexport interface CollectionContext {\n\t/** `config.db.name`, which decides whether Postgres' identifier limit applies. */\n\tdb: string | undefined\n\t/** Keeps what the boot warns about until the instance can log it. */\n\tnotice: (message: string) => void\n\t/** The install's static labels, its own strings over the built-in ones. */\n\tstaticLabel: StaticLabelFor\n}\n\n/** The collection a shaping produced, its notices handed on. */\nconst noticed = (shaped: ShapedCollection, context: CollectionContext): CollectionConfig => {\n\tfor (const message of shaped.notices) {\n\t\tcontext.notice(message)\n\t}\n\treturn shaped.collection\n}\n\n/** What the providers and goals collections call back into, the same whether the plugin runs or not. */\ninterface CollectionCallbacks {\n\tresolveAdminScope: (req: PayloadRequest) => Promise<string | null>\n\t/** Told what a save to either collection changed; a switched-off install's runtime is absent. */\n\tonChange: (\n\t\tcollection: 'providers' | 'goals'\n\t) => (change: ScopeChange, req: PayloadRequest) => void\n\t/** Forgets a provider document's last connection result; a switched-off install keeps none. */\n\tforgetProviderStatus: (docId: string, req: PayloadRequest) => Promise<void>\n\t/** Moves a provider document's last connection result to the version a save gave it. */\n\tcarryProviderStatus: (\n\t\tdocId: string,\n\t\tversions: { from: string; to: string },\n\t\treq: PayloadRequest\n\t) => Promise<void>\n}\n\n/**\n * Who may write a guarded provider field (the connection fields, `isDefault`), when anything\n * narrows the field's own access.\n */\nconst guardedFieldAccessOf = (\n\tresolved: ResolvedOptions,\n\town: ConnectionFieldAccess | undefined\n): ConnectionFieldAccess | undefined => {\n\t// A new document has no stored key to redirect, so only a host's own option gates create; an\n\t// update on a scoped install takes the named cross-scope gate.\n\tconst update = own?.update ?? (resolved.scoped ? resolved.access.crossScope.named : undefined)\n\tconst create = own?.create\n\treturn create || update\n\t\t? { ...(create ? { create } : {}), ...(update ? { update } : {}) }\n\t\t: undefined\n}\n\nconst providersCollectionOf = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig> => {\n\tconst { encryptedField, isSealed, withEncryptedQueryRewrite } = await loadEncrypted()\n\tconst providers = resolved.providers.collection\n\tconst keys = providers.encryption?.keys\n\tconst buildSecret: BuildSecretField = (source) =>\n\t\tencryptedField(source, {\n\t\t\tprotection: 'writeOnly',\n\t\t\taadScope: '10x-analytics:providers',\n\t\t\t...(source.type === 'text' ? { hint: { suffix: 4 } } : {}),\n\t\t\t...(keys ? { keys } : {}),\n\t\t})\n\tconst connectionAccess = guardedFieldAccessOf(resolved, providers.connectionAccess)\n\tconst defaultAccess = guardedFieldAccessOf(\n\t\tresolved,\n\t\tproviders.defaultAccess ?? providers.connectionAccess\n\t)\n\tconst built = buildProvidersCollection({\n\t\tslug: providers.slug,\n\t\taccess: providers.access,\n\t\tfields: providers.fields,\n\t\toverrides: providers.overrides,\n\t\tonChange: callbacks.onChange('providers'),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: providers.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tbuildSecret,\n\t\tisSealed,\n\t\tallowPrivateNetwork: resolved.providers.hosts.allowPrivateNetwork,\n\t\tallow: resolved.providers.hosts.allow,\n\t\t...(connectionAccess ? { connectionAccess } : {}),\n\t\t...(defaultAccess ? { defaultAccess } : {}),\n\t\ttypes: providers.types,\n\t\tstaticLabel: context.staticLabel,\n\t\tlistNotice: [...resolved.sources.policies.values()].includes('fallback'),\n\t\tforgetStatus: callbacks.forgetProviderStatus,\n\t\tcarryStatus: callbacks.carryProviderStatus,\n\t})\n\tconst checked = checkEditorCollection(built, {\n\t\trole: 'providers',\n\t\toption: 'providers.collection',\n\t\tslug: providers.slug,\n\t\tdb: context.db,\n\t})\n\t// Always wrapped: a second wrap by the host's fields plugin is inert (writeOnly has no blind\n\t// index), while skipping leaks ciphertext when fields() runs before this collection exists.\n\treturn withEncryptedQueryRewrite(checked)\n}\n\nconst goalsCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): CollectionConfig => {\n\tconst goals = resolved.goalsCollection\n\tconst built = buildGoalsCollection({\n\t\tslug: goals.slug,\n\t\taccess: goals.access,\n\t\tfields: goals.fields,\n\t\toverrides: goals.overrides,\n\t\tonChange: callbacks.onChange('goals'),\n\t\trevenue: resolved.revenue.enabled,\n\t\t// A per-scope resolver has no request to answer for here, so only a fixed code is\n\t\t// offered as the default.\n\t\t...(typeof resolved.revenue.currency === 'string'\n\t\t\t? { defaultCurrency: resolved.revenue.currency }\n\t\t\t: {}),\n\t\tscoped: resolved.scoped,\n\t\tscopeField: goals.scopeField,\n\t\tresolveScope: callbacks.resolveAdminScope,\n\t\tmember: resolved.scope.member,\n\t\tcrossScope: resolved.access.crossScope.named,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn checkEditorCollection(built, {\n\t\trole: 'goals',\n\t\toption: 'goals.collection',\n\t\tslug: goals.slug,\n\t\tdb: context.db,\n\t})\n}\n\n/**\n * The providers and goals collections an install turned on, built exactly alike whether the plugin\n * runs or only keeps its schema (`disabled: true`), so neither drops a field or an index.\n */\nexport const configCollections = async (\n\tresolved: ResolvedOptions,\n\tcallbacks: CollectionCallbacks,\n\tcontext: CollectionContext\n): Promise<CollectionConfig[]> => [\n\t...(resolved.providers.collection.enabled\n\t\t? [await providersCollectionOf(resolved, callbacks, context)]\n\t\t: []),\n\t...(resolved.goalsCollection.enabled ? [goalsCollectionOf(resolved, callbacks, context)] : []),\n]\n\n/**\n * The sync collection when sync is on, after the host's overrides, built alike whether the plugin\n * runs or not.\n */\nexport const syncCollectionOf = (\n\tresolved: ResolvedOptions,\n\tresolveAdminScope: CollectionCallbacks['resolveAdminScope'],\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (!resolved.sync.enabled) {\n\t\treturn undefined\n\t}\n\tconst { slug, hidden, overrides } = resolved.sync.collection\n\tconst built = syncCollection(slug, {\n\t\thidden,\n\t\taccess: {\n\t\t\tscoped: resolved.scoped,\n\t\t\tscopeField: 'scope',\n\t\t\tresolveScope: resolveAdminScope,\n\t\t\tmember: resolved.scope.member,\n\t\t\tcrossScope: resolved.access.crossScope.named,\n\t\t},\n\t\tread: resolved.access.read,\n\t\tstaticLabel: context.staticLabel,\n\t})\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'sync',\n\t\t\toption: 'sync.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/** The read cache collection after the host's overrides, unless a `cache.store` replaces it. */\nexport const cacheCollectionOf = (\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): CollectionConfig | undefined => {\n\tif (resolved.cache.store) {\n\t\treturn undefined\n\t}\n\tconst { slug, overrides } = resolved.cache.collection\n\tconst built = cacheCollection({ slug, mongo: context.db === 'mongoose' })\n\treturn noticed(\n\t\tshapeCollection(built, {\n\t\t\trole: 'cache',\n\t\t\toption: 'cache.collection',\n\t\t\tdb: context.db,\n\t\t\t...(overrides ? { overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n}\n\n/**\n * Whether the install registers a task that takes a lease and stamps a heartbeat, which live in\n * `analytics-state`: sync or warming, while `jobs` registers tasks.\n */\nconst needsStateCollection = (resolved: ResolvedOptions): boolean =>\n\tresolved.jobs !== false && (resolved.sync.enabled || resolved.cache.warm.enabled)\n\n/**\n * `analytics-state` for the sync and warm tasks, after `jobs.state`, unless an adapter (the native\n * engine) registered its own. Refuses `jobs.state` wherever it would shape nothing.\n */\nexport const addStateCollection = (\n\tconfig: Config,\n\tresolved: ResolvedOptions,\n\tcontext: CollectionContext\n): void => {\n\tconst option = resolved.jobs === false ? undefined : resolved.jobs.state\n\tconst registered = slugOfRole(config.collections, 'state')\n\tif (option && registered !== undefined) {\n\t\tthrow new Error(\n\t\t\t`analytics: jobs.state shapes the analytics-state collection of an install without native(), but native() registers its own (\"${registered}\"). Rename or reshape it with native({ collections: { state } }) instead.`\n\t\t)\n\t}\n\tif (!needsStateCollection(resolved)) {\n\t\tif (option) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: jobs.state shapes the collection the sync and warm tasks keep their leases in, and this install runs neither. Turn sync or cache.warm on, or remove it.'\n\t\t\t)\n\t\t}\n\t\treturn\n\t}\n\tif (registered !== undefined) {\n\t\treturn\n\t}\n\tconst state = noticed(\n\t\tshapeCollection(stateCollection(option?.slug ?? STATE_SLUG), {\n\t\t\trole: 'state',\n\t\t\toption: 'jobs.state',\n\t\t\tdb: context.db,\n\t\t\t...(option?.overrides ? { overrides: option.overrides } : {}),\n\t\t}),\n\t\tcontext\n\t)\n\tconfig.collections = [...(config.collections ?? []), state]\n}\n"],"mappings":";;;;;;;;;;AA8BA,MAAM,WAAW,QAA0B,YAAiD;CAC3F,KAAK,MAAM,WAAW,OAAO,SAC5B,QAAQ,OAAO,OAAO;CAEvB,OAAO,OAAO;AACf;;;;;AAuBA,MAAM,wBACL,UACA,QACuC;CAGvC,MAAM,SAAS,KAAK,WAAW,SAAS,SAAS,SAAS,OAAO,WAAW,QAAQ,KAAA;CACpF,MAAM,SAAS,KAAK;CACpB,OAAO,UAAU,SACd;E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MAAa,qBACZ,UACA,YACkC;CAClC,IAAI,SAAS,MAAM,OAClB;CAED,MAAM,EAAE,MAAM,cAAc,SAAS,MAAM;CAE3C,OAAO,QACN,gBAFa,gBAAgB;EAAE;EAAM,OAAO,QAAQ,OAAO;CAAW,CAElD,GAAG;EACtB,MAAM;EACN,QAAQ;EACR,IAAI,QAAQ;EACZ,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;CAClC,CAAC,GACD,OACD;AACD;;;;;AAMA,MAAM,wBAAwB,aAC7B,SAAS,SAAS,UAAU,SAAS,KAAK,WAAW,SAAS,MAAM,KAAK;;;;;AAM1E,MAAa,sBACZ,QACA,UACA,YACU;CACV,MAAM,SAAS,SAAS,SAAS,QAAQ,KAAA,IAAY,SAAS,KAAK;CACnE,MAAM,aAAa,WAAW,OAAO,aAAa,OAAO;CACzD,IAAI,UAAU,eAAe,KAAA,GAC5B,MAAM,IAAI,MACT,gIAAgI,WAAW,0EAC5I;CAED,IAAI,CAAC,qBAAqB,QAAQ,GAAG;EACpC,IAAI,QACH,MAAM,IAAI,MACT,oKACD;EAED;CACD;CACA,IAAI,eAAe,KAAA,GAClB;CAED,MAAM,QAAQ,QACb,gBAAgB,gBAAgB,QAAQ,QAAA,iBAAkB,GAAG;EAC5D,MAAM;EACN,QAAQ;EACR,IAAI,QAAQ;EACZ,GAAI,QAAQ,YAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;CAC5D,CAAC,GACD,OACD;CACA,OAAO,cAAc,CAAC,GAAI,OAAO,eAAe,CAAC,GAAI,KAAK;AAC3D"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { isRecord } from "../core/values.js";
|
|
2
|
+
import { getRuntime } from "./runtime.js";
|
|
3
|
+
import { NO_STORE, analyticsError, errorResponse, notAvailableResponse, unauthorizedResponse } from "./errors.js";
|
|
4
|
+
import { monotonicMs } from "../core/monotonic.js";
|
|
5
|
+
import { isCollectionSlug } from "../core/collectionSlug.js";
|
|
6
|
+
import { versionOf } from "../providers/probe.js";
|
|
7
|
+
import { checkConnectionOf } from "../providers/connectionCheck.js";
|
|
8
|
+
import { createRefreshDebounce } from "./refreshEndpoint.js";
|
|
9
|
+
import { docAccessOperation } from "payload";
|
|
10
|
+
//#region src/plugin/providerStatusEndpoint.ts
|
|
11
|
+
/** A second check of one saved document this soon answers the first one's result, asking nothing. */
|
|
12
|
+
const CONNECTION_CHECK_DEBOUNCE_MS = 5e3;
|
|
13
|
+
const notFound = () => errorResponse(404, analyticsError("not_found", "analytics: no such provider document", "id"));
|
|
14
|
+
/**
|
|
15
|
+
* GET answers one provider document's last connection result, POST checks the connection first.
|
|
16
|
+
* Both take the document as `?id=`: a GET needs read access to it, a POST update access, each
|
|
17
|
+
* asked of Payload with the caller's own user, so a tenant reaches only its own documents.
|
|
18
|
+
*/
|
|
19
|
+
const makeProviderStatusHandler = (opts = {}) => {
|
|
20
|
+
const debounce = createRefreshDebounce(opts.now ?? monotonicMs, CONNECTION_CHECK_DEBOUNCE_MS);
|
|
21
|
+
return async (req) => {
|
|
22
|
+
if (!req.user) return unauthorizedResponse();
|
|
23
|
+
const runtime = getRuntime(req.payload);
|
|
24
|
+
const slug = runtime?.providersCollection?.slug;
|
|
25
|
+
const store = runtime?.providerStatus;
|
|
26
|
+
if (!runtime || !store || slug === void 0 || !isCollectionSlug(req.payload, slug)) return notAvailableResponse();
|
|
27
|
+
const id = new URL(req.url ?? "", "http://localhost").searchParams.get("id")?.trim();
|
|
28
|
+
if (!id) return errorResponse(400, analyticsError("invalid_param", "analytics: id names the provider document", "id"));
|
|
29
|
+
try {
|
|
30
|
+
const readable = await req.payload.findByID({
|
|
31
|
+
collection: slug,
|
|
32
|
+
id,
|
|
33
|
+
depth: 0,
|
|
34
|
+
disableErrors: true,
|
|
35
|
+
overrideAccess: false,
|
|
36
|
+
user: req.user,
|
|
37
|
+
req
|
|
38
|
+
});
|
|
39
|
+
if (!isRecord(readable)) return notFound();
|
|
40
|
+
const saved = versionOf(readable.updatedAt);
|
|
41
|
+
const version = `${id}@${saved}`;
|
|
42
|
+
const stored = async () => {
|
|
43
|
+
const answer = { status: await store.read(id, saved) ?? {} };
|
|
44
|
+
return Response.json(answer, { headers: NO_STORE });
|
|
45
|
+
};
|
|
46
|
+
if (req.method !== "POST" || !debounce.allows(version)) return stored();
|
|
47
|
+
const collection = req.payload.collections[slug];
|
|
48
|
+
if (!(collection ? await docAccessOperation({
|
|
49
|
+
collection,
|
|
50
|
+
id,
|
|
51
|
+
req
|
|
52
|
+
}) : void 0)?.update) return errorResponse(403, analyticsError("forbidden", "analytics: checking a connection needs update access"));
|
|
53
|
+
if (!debounce.allows(version)) return stored();
|
|
54
|
+
debounce.record(version);
|
|
55
|
+
const adapter = await runtime.providerAdapter?.(id);
|
|
56
|
+
if (!adapter?.checkConnection) return errorResponse(400, analyticsError("invalid_param", "analytics: this provider has no connection to check", "id"));
|
|
57
|
+
const checked = await checkConnectionOf(req.payload, adapter);
|
|
58
|
+
const logged = (failed) => (err) => {
|
|
59
|
+
runtime.providerStatusWarning?.(`analytics: the connection status of provider document "${id}" could not be ${failed}: ${String(err)}`);
|
|
60
|
+
};
|
|
61
|
+
try {
|
|
62
|
+
await store.record(id, checked, { version: saved }).catch(logged("saved"));
|
|
63
|
+
} finally {
|
|
64
|
+
await adapter.close?.(req.payload);
|
|
65
|
+
}
|
|
66
|
+
const answer = {
|
|
67
|
+
status: await store.read(id, saved).catch(logged("read")) ?? {},
|
|
68
|
+
checked
|
|
69
|
+
};
|
|
70
|
+
return Response.json(answer, { headers: NO_STORE });
|
|
71
|
+
} catch (err) {
|
|
72
|
+
req.payload.logger?.error(`analytics: the status of provider document "${id}" could not be answered: ${String(err)}`);
|
|
73
|
+
return errorResponse(500, analyticsError("internal", "analytics: provider status failed"));
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
//#endregion
|
|
78
|
+
export { makeProviderStatusHandler };
|
|
79
|
+
|
|
80
|
+
//# sourceMappingURL=providerStatusEndpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"providerStatusEndpoint.js","names":[],"sources":["../../src/plugin/providerStatusEndpoint.ts"],"sourcesContent":["import { docAccessOperation, type PayloadHandler, type PayloadRequest } from 'payload'\nimport { isCollectionSlug } from '../core/collectionSlug'\nimport { monotonicMs } from '../core/monotonic'\nimport { isRecord } from '../core/values'\nimport { checkConnectionOf } from '../providers/connectionCheck'\nimport type { ProviderStatusResponse } from '../providers/connectionState'\nimport { versionOf } from '../providers/probe'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\tnotAvailableResponse,\n\tunauthorizedResponse,\n} from './errors'\nimport { createRefreshDebounce } from './refreshEndpoint'\nimport { getRuntime } from './runtime'\n\n/** A second check of one saved document this soon answers the first one's result, asking nothing. */\nconst CONNECTION_CHECK_DEBOUNCE_MS = 5_000\n\ninterface ProviderStatusHandlerOptions {\n\t/** Clock behind the debounce window; `monotonicMs` unless a test injects one. */\n\tnow?: () => number\n}\n\nconst notFound = (): Response =>\n\terrorResponse(404, analyticsError('not_found', 'analytics: no such provider document', 'id'))\n\n/**\n * GET answers one provider document's last connection result, POST checks the connection first.\n * Both take the document as `?id=`: a GET needs read access to it, a POST update access, each\n * asked of Payload with the caller's own user, so a tenant reaches only its own documents.\n */\nexport const makeProviderStatusHandler = (\n\topts: ProviderStatusHandlerOptions = {}\n): PayloadHandler => {\n\tconst debounce = createRefreshDebounce(opts.now ?? monotonicMs, CONNECTION_CHECK_DEBOUNCE_MS)\n\n\treturn async (req: PayloadRequest) => {\n\t\tif (!req.user) {\n\t\t\treturn unauthorizedResponse()\n\t\t}\n\t\tconst runtime = getRuntime(req.payload)\n\t\tconst slug = runtime?.providersCollection?.slug\n\t\tconst store = runtime?.providerStatus\n\t\tif (!runtime || !store || slug === undefined || !isCollectionSlug(req.payload, slug)) {\n\t\t\treturn notAvailableResponse()\n\t\t}\n\t\tconst id = new URL(req.url ?? '', 'http://localhost').searchParams.get('id')?.trim()\n\t\tif (!id) {\n\t\t\treturn errorResponse(\n\t\t\t\t400,\n\t\t\t\tanalyticsError('invalid_param', 'analytics: id names the provider document', 'id')\n\t\t\t)\n\t\t}\n\t\ttry {\n\t\t\tconst readable: unknown = await req.payload.findByID({\n\t\t\t\tcollection: slug,\n\t\t\t\tid,\n\t\t\t\tdepth: 0,\n\t\t\t\tdisableErrors: true,\n\t\t\t\toverrideAccess: false,\n\t\t\t\tuser: req.user,\n\t\t\t\treq,\n\t\t\t})\n\t\t\tif (!isRecord(readable)) {\n\t\t\t\treturn notFound()\n\t\t\t}\n\t\t\t// Per saved version, so a check right after a save asks about the new settings, and a result\n\t\t\t// about the settings before it reads as none.\n\t\t\tconst saved = versionOf(readable.updatedAt)\n\t\t\tconst version = `${id}@${saved}`\n\t\t\tconst stored = async (): Promise<Response> => {\n\t\t\t\tconst answer: ProviderStatusResponse = { status: (await store.read(id, saved)) ?? {} }\n\t\t\t\treturn Response.json(answer, { headers: NO_STORE })\n\t\t\t}\n\t\t\tif (req.method !== 'POST' || !debounce.allows(version)) {\n\t\t\t\treturn stored()\n\t\t\t}\n\t\t\tconst collection = req.payload.collections[slug]\n\t\t\tconst permissions = collection ? await docAccessOperation({ collection, id, req }) : undefined\n\t\t\tif (!permissions?.update) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t403,\n\t\t\t\t\tanalyticsError('forbidden', 'analytics: checking a connection needs update access')\n\t\t\t\t)\n\t\t\t}\n\t\t\t// No await between this check and `record`, so concurrent checks ask the vendor once.\n\t\t\tif (!debounce.allows(version)) {\n\t\t\t\treturn stored()\n\t\t\t}\n\t\t\tdebounce.record(version)\n\t\t\tconst adapter = await runtime.providerAdapter?.(id)\n\t\t\tif (!adapter?.checkConnection) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tanalyticsError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: this provider has no connection to check',\n\t\t\t\t\t\t'id'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst checked = await checkConnectionOf(req.payload, adapter)\n\t\t\t// A status that could not be saved or read is logged; the check's result is still answered.\n\t\t\tconst logged =\n\t\t\t\t(failed: string) =>\n\t\t\t\t(err: unknown): undefined => {\n\t\t\t\t\truntime.providerStatusWarning?.(\n\t\t\t\t\t\t`analytics: the connection status of provider document \"${id}\" could not be ${failed}: ${String(err)}`\n\t\t\t\t\t)\n\t\t\t\t\treturn undefined\n\t\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait store.record(id, checked, { version: saved }).catch(logged('saved'))\n\t\t\t} finally {\n\t\t\t\tawait adapter.close?.(req.payload)\n\t\t\t}\n\t\t\tconst status = await store.read(id, saved).catch(logged('read'))\n\t\t\tconst answer: ProviderStatusResponse = { status: status ?? {}, checked }\n\t\t\treturn Response.json(answer, { headers: NO_STORE })\n\t\t} catch (err) {\n\t\t\treq.payload.logger?.error(\n\t\t\t\t`analytics: the status of provider document \"${id}\" could not be answered: ${String(err)}`\n\t\t\t)\n\t\t\treturn errorResponse(500, analyticsError('internal', 'analytics: provider status failed'))\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAM,+BAA+B;AAOrC,MAAM,iBACL,cAAc,KAAK,eAAe,aAAa,wCAAwC,IAAI,CAAC;;;;;;AAO7F,MAAa,6BACZ,OAAqC,CAAC,MAClB;CACpB,MAAM,WAAW,sBAAsB,KAAK,OAAO,aAAa,4BAA4B;CAE5F,OAAO,OAAO,QAAwB;EACrC,IAAI,CAAC,IAAI,MACR,OAAO,qBAAqB;EAE7B,MAAM,UAAU,WAAW,IAAI,OAAO;EACtC,MAAM,OAAO,SAAS,qBAAqB;EAC3C,MAAM,QAAQ,SAAS;EACvB,IAAI,CAAC,WAAW,CAAC,SAAS,SAAS,KAAA,KAAa,CAAC,iBAAiB,IAAI,SAAS,IAAI,GAClF,OAAO,qBAAqB;EAE7B,MAAM,KAAK,IA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AAS,MAAM,CAAC,EAAE,MAAM,OAAO,OAAO,CAAC;GAC1E,UAAU;IACT,MAAM,QAAQ,QAAQ,IAAI,OAAO;GAClC;GAEA,MAAM,SAAiC;IAAE,QAAQ,MAD5B,MAAM,KAAK,IAAI,KAAK,EAAE,MAAM,OAAO,MAAM,CAAC,KACJ,CAAC;IAAG;GAAQ;GACvE,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;EACnD,SAAS,KAAK;GACb,IAAI,QAAQ,QAAQ,MACnB,+CAA+C,GAAG,2BAA2B,OAAO,GAAG,GACxF;GACA,OAAO,cAAc,KAAK,eAAe,YAAY,mCAAmC,CAAC;EAC1F;CACD;AACD"}
|
|
@@ -109,7 +109,7 @@ const makeQueryHandler = () => async (req) => {
|
|
|
109
109
|
result = askedResult(read, aliased);
|
|
110
110
|
comparison = previous && askedResult(previous, aliased);
|
|
111
111
|
} catch (err) {
|
|
112
|
-
req.payload.logger?.warn(`analytics: query read failed for adapter "${adapter.id}": ${describeWithCauses(err)}`);
|
|
112
|
+
req.payload.logger?.warn(`analytics: query read failed for adapter "${adapter.id}" (${ownScope === null ? "install-wide" : `scope "${ownScope}"`}): ${describeWithCauses(err)}`);
|
|
113
113
|
return readFailureResponse(err);
|
|
114
114
|
}
|
|
115
115
|
const reporting = revenueCurrencyOf(query.filters, await resolveCurrencyFor(runtime, req, ownScope));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { serializeCapabilities } from '../core/capabilities'\nimport { currentDate } from '../core/clock'\nimport type { AnalyticsQuery, AnalyticsResult, DateRange } from '../core/contract'\nimport { aliasMetrics, askedResult, servedQuery } from '../core/metricAliases'\nimport { resolveQueryScope, resolveRequestedScope } from '../core/scopedRead'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { revenueCurrencyOf } from '../goals/currency'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport type { ReadOptions } from '../surfacing/engine'\nimport { previousWindow, withinLookback } from '../timeframe/comparison'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\tnotAvailableResponse,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { goalHintFor } from './goalHint'\nimport { itemRefsOf, resolveItemLabels } from './itemLabels'\nimport { queryParams } from './queryParams'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { readFailureResponse } from './readFailure'\nimport {\n\tgetRuntime,\n\tresolvableScope,\n\tresolveCurrencyFor,\n\tresolveTimezoneFor,\n\tscopeGates,\n} from './runtime'\n\n/**\n * The query as the response echoes it, the range as ISO strings. `goalSlugs` rides along: the\n * scope's slugs, `[]` for no goals, or `'unresolved'` when the resolver failed.\n */\nexport const serializeQuery = (query: AnalyticsQuery): SerializedAnalyticsQuery => ({\n\t...query,\n\tdateRange: {\n\t\tstart: query.dateRange.start.toISOString(),\n\t\tend: query.dateRange.end.toISOString(),\n\t},\n})\n\nconst noSourceResponse = (): Response =>\n\terrorResponse(\n\t\t404,\n\t\tanalyticsError('unknown_source', 'analytics: no source is available for this request')\n\t)\n\n/**\n * Authenticated GET over the surfacing engine, gated in order (auth, `access.read`, scope, source,\n * capabilities) so no answer leaks past the caller's entitlement. Upstream error text never leaks.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn notAvailableResponse()\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readGate(runtime, req))) {\n\t\t\treturn readDeniedResponse()\n\t\t}\n\t\tconst params = queryParams(req)\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst requested = await resolveRequestedScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\traw: params.get('scope'),\n\t\t\tgates,\n\t\t})\n\t\tif (!requested.ok) {\n\t\t\t// A request whose own scope will not resolve answers like a scope with no sources.\n\t\t\t// A scope the caller named, or one its user does not belong to, is refused as such.\n\t\t\treturn requested.reason === 'named' || requested.reason === 'not-member'\n\t\t\t\t? untrustedScopeResponse('scope')\n\t\t\t\t: noSourceResponse()\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, { gates, scope: requested.gated })\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn noSourceResponse()\n\t\t}\n\t\tconst requestedSource = readParam(params, 'source')\n\t\tconst adapter = context.adapters.get(requestedSource ?? context.defaultId ?? '')\n\t\tif (!adapter) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tanalyticsError('unknown_source', 'analytics: unknown source', 'source')\n\t\t\t)\n\t\t}\n\t\tadapterId = adapter.id\n\t\tconst queryScope = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope,\n\t\t\tadapter,\n\t\t\tgates,\n\t\t})\n\t\tif (!queryScope.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t403,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'forbidden',\n\t\t\t\t\t'analytics: this source cannot be read for your scope',\n\t\t\t\t\t'source'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tconst capabilities = serializeCapabilities(adapter.capabilities)\n\t\tconst ownScope = resolvableScope(context.scope)\n\t\tconst timezone = await resolveTimezoneFor(runtime, req, ownScope)\n\t\tconst parsed = parseQueryParams(params, { capabilities, timezone })\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(400, parsed.error)\n\t\t}\n\t\tconst hint = await goalHintFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: ownScope,\n\t\t\tmetrics: parsed.value.query.metrics,\n\t\t\tdimensions: parsed.value.query.dimensions,\n\t\t})\n\t\tconst query: AnalyticsQuery = {\n\t\t\t...parsed.value.query,\n\t\t\t...(queryScope.queryScope === undefined ? {} : { scope: queryScope.queryScope }),\n\t\t\t...(hint === undefined ? {} : { goalSlugs: hint.slugs }),\n\t\t}\n\t\tlet comparisonRange: DateRange | null = null\n\t\tif (parsed.value.compare === 'previous') {\n\t\t\tcomparisonRange = previousWindow(query.dateRange, query.timezone)\n\t\t\tif (!comparisonRange) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tanalyticsError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: the range is too long to compare against a previous period',\n\t\t\t\t\t\t'compare'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\t// The view decides this same predicate on the browser clock, so a client near the\n\t\t\t// floor or with a skewed clock must lose only its delta, never the whole read.\n\t\t\tif (\n\t\t\t\t!withinLookback(comparisonRange, adapter.capabilities.maxLookbackDays, {\n\t\t\t\t\ttz: query.timezone,\n\t\t\t\t\tnow: currentDate(),\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tcomparisonRange = null\n\t\t\t}\n\t\t}\n\t\t// The view names the preset its days came from, so the engine can store the read for the warm\n\t\t// task when those days are the preset's today; any other window stores nothing.\n\t\tconst readOptions: ReadOptions = {\n\t\t\twhenBusy: 'refuse',\n\t\t\tpriority: 'interactive',\n\t\t\t...(parsed.value.timeframe === null ? {} : { timeframe: parsed.value.timeframe }),\n\t\t}\n\t\t// Read under the source's own names and answered under the caller's: `visits` from native.\n\t\tconst aliased = aliasMetrics(query.metrics, adapter.capabilities.metrics)\n\t\tconst served = servedQuery(query, aliased)\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\tconst [read, previous] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, served, readOptions),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...served, dateRange: comparisonRange }, readOptions)\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t\tresult = askedResult(read, aliased)\n\t\t\tcomparison = previous && askedResult(previous, aliased)\n\t\t} catch (err) {\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\": ${describeWithCauses(err)}`\n\t\t\t)\n\t\t\treturn readFailureResponse(err)\n\t\t}\n\t\t// A shallow copy, since the cached entry is shared between requests and reporting currency\n\t\t// resolves per scope. A source naming its own revenue currency keeps it.\n\t\tconst reporting = revenueCurrencyOf(\n\t\t\tquery.filters,\n\t\t\tawait resolveCurrencyFor(runtime, req, ownScope)\n\t\t)\n\t\tconst withCurrency = (read: AnalyticsResult): AnalyticsResult =>\n\t\t\treporting && read.meta.currency === undefined\n\t\t\t\t? { ...read, meta: { ...read.meta, currency: reporting } }\n\t\t\t\t: read\n\t\tconst currency = result.meta.currency ?? reporting\n\t\t// Resolved per request rather than cached with the read: a title is whatever this reader\n\t\t// may see of the document, and the cached rows are shared by every reader of the scope.\n\t\tconst refs = itemRefsOf(query, [result, comparison])\n\t\tconst itemLabels = refs.length > 0 ? await resolveItemLabels(req, refs) : undefined\n\t\tconst body: QueryResponse = {\n\t\t\tresult: withCurrency(result),\n\t\t\t...(comparison ? { comparison: withCurrency(comparison) } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: context.sources.find((source) => source.id === adapter.id)?.label ?? adapter.label,\n\t\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? 'config' : 'runtime',\n\t\t\t},\n\t\t\tcapabilities,\n\t\t\tquery: serializeQuery(query),\n\t\t\t...(hint && hint.builtin.length > 0 ? { builtinGoalSlugs: hint.builtin } : {}),\n\t\t\t...(itemLabels ? { itemLabels } : {}),\n\t\t}\n\t\treturn Response.json(body, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: query failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\treturn errorResponse(500, analy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,QAAQ,MAAM,wCAAwC,UAAU,KAAK,OAAO,GAAG,GAAG;EAC9F,OAAO,cAAc,KAAK,eAAe,YAAY,yBAAyB,CAAC;CAChF;AACD"}
|
|
1
|
+
{"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { readGate } from '../access/readGate'\nimport { serializeCapabilities } from '../core/capabilities'\nimport { currentDate } from '../core/clock'\nimport type { AnalyticsQuery, AnalyticsResult, DateRange } from '../core/contract'\nimport { aliasMetrics, askedResult, servedQuery } from '../core/metricAliases'\nimport { resolveQueryScope, resolveRequestedScope } from '../core/scopedRead'\nimport { describeWithCauses } from '../core/sourceErrors'\nimport { revenueCurrencyOf } from '../goals/currency'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport type { ReadOptions } from '../surfacing/engine'\nimport { previousWindow, withinLookback } from '../timeframe/comparison'\nimport {\n\tanalyticsError,\n\terrorResponse,\n\tNO_STORE,\n\tnotAvailableResponse,\n\treadDeniedResponse,\n\tunauthorizedResponse,\n\tuntrustedScopeResponse,\n} from './errors'\nimport { goalHintFor } from './goalHint'\nimport { itemRefsOf, resolveItemLabels } from './itemLabels'\nimport { queryParams } from './queryParams'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { readFailureResponse } from './readFailure'\nimport {\n\tgetRuntime,\n\tresolvableScope,\n\tresolveCurrencyFor,\n\tresolveTimezoneFor,\n\tscopeGates,\n} from './runtime'\n\n/**\n * The query as the response echoes it, the range as ISO strings. `goalSlugs` rides along: the\n * scope's slugs, `[]` for no goals, or `'unresolved'` when the resolver failed.\n */\nexport const serializeQuery = (query: AnalyticsQuery): SerializedAnalyticsQuery => ({\n\t...query,\n\tdateRange: {\n\t\tstart: query.dateRange.start.toISOString(),\n\t\tend: query.dateRange.end.toISOString(),\n\t},\n})\n\nconst noSourceResponse = (): Response =>\n\terrorResponse(\n\t\t404,\n\t\tanalyticsError('unknown_source', 'analytics: no source is available for this request')\n\t)\n\n/**\n * Authenticated GET over the surfacing engine, gated in order (auth, `access.read`, scope, source,\n * capabilities) so no answer leaks past the caller's entitlement. Upstream error text never leaks.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn unauthorizedResponse()\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn notAvailableResponse()\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readGate(runtime, req))) {\n\t\t\treturn readDeniedResponse()\n\t\t}\n\t\tconst params = queryParams(req)\n\t\tconst gates = scopeGates(runtime, req)\n\t\tconst requested = await resolveRequestedScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\traw: params.get('scope'),\n\t\t\tgates,\n\t\t})\n\t\tif (!requested.ok) {\n\t\t\t// A request whose own scope will not resolve answers like a scope with no sources.\n\t\t\t// A scope the caller named, or one its user does not belong to, is refused as such.\n\t\t\treturn requested.reason === 'named' || requested.reason === 'not-member'\n\t\t\t\t? untrustedScopeResponse('scope')\n\t\t\t\t: noSourceResponse()\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, { gates, scope: requested.gated })\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn noSourceResponse()\n\t\t}\n\t\tconst requestedSource = readParam(params, 'source')\n\t\tconst adapter = context.adapters.get(requestedSource ?? context.defaultId ?? '')\n\t\tif (!adapter) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tanalyticsError('unknown_source', 'analytics: unknown source', 'source')\n\t\t\t)\n\t\t}\n\t\tadapterId = adapter.id\n\t\tconst queryScope = await resolveQueryScope({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope,\n\t\t\tadapter,\n\t\t\tgates,\n\t\t})\n\t\tif (!queryScope.ok) {\n\t\t\treturn errorResponse(\n\t\t\t\t403,\n\t\t\t\tanalyticsError(\n\t\t\t\t\t'forbidden',\n\t\t\t\t\t'analytics: this source cannot be read for your scope',\n\t\t\t\t\t'source'\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tconst capabilities = serializeCapabilities(adapter.capabilities)\n\t\tconst ownScope = resolvableScope(context.scope)\n\t\tconst timezone = await resolveTimezoneFor(runtime, req, ownScope)\n\t\tconst parsed = parseQueryParams(params, { capabilities, timezone })\n\t\tif (!parsed.ok) {\n\t\t\treturn errorResponse(400, parsed.error)\n\t\t}\n\t\tconst hint = await goalHintFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: ownScope,\n\t\t\tmetrics: parsed.value.query.metrics,\n\t\t\tdimensions: parsed.value.query.dimensions,\n\t\t})\n\t\tconst query: AnalyticsQuery = {\n\t\t\t...parsed.value.query,\n\t\t\t...(queryScope.queryScope === undefined ? {} : { scope: queryScope.queryScope }),\n\t\t\t...(hint === undefined ? {} : { goalSlugs: hint.slugs }),\n\t\t}\n\t\tlet comparisonRange: DateRange | null = null\n\t\tif (parsed.value.compare === 'previous') {\n\t\t\tcomparisonRange = previousWindow(query.dateRange, query.timezone)\n\t\t\tif (!comparisonRange) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tanalyticsError(\n\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t'analytics: the range is too long to compare against a previous period',\n\t\t\t\t\t\t'compare'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\t// The view decides this same predicate on the browser clock, so a client near the\n\t\t\t// floor or with a skewed clock must lose only its delta, never the whole read.\n\t\t\tif (\n\t\t\t\t!withinLookback(comparisonRange, adapter.capabilities.maxLookbackDays, {\n\t\t\t\t\ttz: query.timezone,\n\t\t\t\t\tnow: currentDate(),\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\tcomparisonRange = null\n\t\t\t}\n\t\t}\n\t\t// The view names the preset its days came from, so the engine can store the read for the warm\n\t\t// task when those days are the preset's today; any other window stores nothing.\n\t\tconst readOptions: ReadOptions = {\n\t\t\twhenBusy: 'refuse',\n\t\t\tpriority: 'interactive',\n\t\t\t...(parsed.value.timeframe === null ? {} : { timeframe: parsed.value.timeframe }),\n\t\t}\n\t\t// Read under the source's own names and answered under the caller's: `visits` from native.\n\t\tconst aliased = aliasMetrics(query.metrics, adapter.capabilities.metrics)\n\t\tconst served = servedQuery(query, aliased)\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\tconst [read, previous] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, served, readOptions),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...served, dateRange: comparisonRange }, readOptions)\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t\tresult = askedResult(read, aliased)\n\t\t\tcomparison = previous && askedResult(previous, aliased)\n\t\t} catch (err) {\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\" (${ownScope === null ? 'install-wide' : `scope \"${ownScope}\"`}): ${describeWithCauses(err)}`\n\t\t\t)\n\t\t\treturn readFailureResponse(err)\n\t\t}\n\t\t// A shallow copy, since the cached entry is shared between requests and reporting currency\n\t\t// resolves per scope. A source naming its own revenue currency keeps it.\n\t\tconst reporting = revenueCurrencyOf(\n\t\t\tquery.filters,\n\t\t\tawait resolveCurrencyFor(runtime, req, ownScope)\n\t\t)\n\t\tconst withCurrency = (read: AnalyticsResult): AnalyticsResult =>\n\t\t\treporting && read.meta.currency === undefined\n\t\t\t\t? { ...read, meta: { ...read.meta, currency: reporting } }\n\t\t\t\t: read\n\t\tconst currency = result.meta.currency ?? reporting\n\t\t// Resolved per request rather than cached with the read: a title is whatever this reader\n\t\t// may see of the document, and the cached rows are shared by every reader of the scope.\n\t\tconst refs = itemRefsOf(query, [result, comparison])\n\t\tconst itemLabels = refs.length > 0 ? await resolveItemLabels(req, refs) : undefined\n\t\tconst body: QueryResponse = {\n\t\t\tresult: withCurrency(result),\n\t\t\t...(comparison ? { comparison: withCurrency(comparison) } : {}),\n\t\t\t...(currency ? { currency } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: context.sources.find((source) => source.id === adapter.id)?.label ?? adapter.label,\n\t\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? 'config' : 'runtime',\n\t\t\t},\n\t\t\tcapabilities,\n\t\t\tquery: serializeQuery(query),\n\t\t\t...(hint && hint.builtin.length > 0 ? { builtinGoalSlugs: hint.builtin } : {}),\n\t\t\t...(itemLabels ? { itemLabels } : {}),\n\t\t}\n\t\treturn Response.json(body, { headers: NO_STORE })\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: query failed for adapter \"${adapterId}\": ${String(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: query failed'))\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,kBAAkB,WAAqD;CACnF,GAAG;CACH,WAAW;EACV,OAAO,MAAM,UAAU,MAAM,YAAY;EACzC,KAAK,MAAM,UAAU,IAAI,YAAY;CACtC;AACD;AAEA,MAAM,yBACL,cACC,KACA,eAAe,kBAAkB,oDAAoD,CACtF;;;;;AAMD,MAAa,yBAAyC,OAAO,QAAQ;CACpE,IAAI,CAAC,IAAI,MACR,OAAO,qBAAqB;CAE7B,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,qBAAqB;CAE7B,IAAI,YAAY;CAChB,IAAI;EACH,IAAI,CAAE,MAAM,SAAS,SAAS,GAAG,GAChC,OAAO,mBAAmB;EAE3B,MAAM,SAAS,YAAY,GAAG;EAC9B,MAAM,QAAQ,WAAW,SAAS,GAAG;EACrC,MAAM,YAAY,MAAM,sBAAsB;GAC7C;GACA;GACA,KAAK,OAAO,IAAI,OAAO;GACvB;EACD,CAAC;EACD,IAAI,CAAC,UAAU,IAGd,OAAO,UAAU,WAAW,WAAW,UAA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AQ,aAAa,MAAM;GAC3B,GAAI,aAAa,EAAE,YAAY,aAAa,UAAU,EAAE,IAAI,CAAC;GAC7D,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;GAC/B,QAAQ;IACP,IAAI,QAAQ;IACZ,OAAO,QAAQ,QAAQ,MAAM,WAAW,OAAO,OAAO,QAAQ,EAAE,GAAG,SAAS,QAAQ;IACpF,MAAM,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,IAAI,WAAW;GAC7D;GACA;GACA,OAAO,eAAe,KAAK;GAC3B,GAAI,QAAQ,KAAK,QAAQ,SAAS,IAAI,EAAE,kBAAkB,KAAK,QAAQ,IAAI,CAAC;GAC5E,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACpC;EACA,OAAO,SAAS,KAAK,MAAM,EAAE,SAAS,SAAS,CAAC;CACjD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,MAAM,wCAAwC,UAAU,KAAK,OAAO,GAAG,GAAG;EAC9F,OAAO,cAAc,KAAK,eAAe,YAAY,yBAAyB,CAAC;CAChF;AACD"}
|
|
@@ -2,10 +2,11 @@ import { PayloadRequest } from "payload";
|
|
|
2
2
|
|
|
3
3
|
//#region src/plugin/readContextForRequest.d.ts
|
|
4
4
|
/**
|
|
5
|
-
* What a listing tells its reader about itself
|
|
6
|
-
*
|
|
5
|
+
* What a listing tells its reader about itself, when a shared source is listed only by
|
|
6
|
+
* `sources.<id>.tenants: 'fallback'`: `platformFallback` because the scope has no source of its own
|
|
7
|
+
* yet, `ownSourceFailing` because every one it has is failing.
|
|
7
8
|
*/
|
|
8
|
-
type SourcesNotice = 'platformFallback';
|
|
9
|
+
type SourcesNotice = 'platformFallback' | 'ownSourceFailing';
|
|
9
10
|
//#endregion
|
|
10
11
|
export { SourcesNotice };
|
|
11
12
|
//# sourceMappingURL=readContextForRequest.d.ts.map
|
|
@@ -82,7 +82,7 @@ const resolveSourcesForRequest = async (req, args = {}) => {
|
|
|
82
82
|
if (!requested.ok) return requested.reason === "failed" ? degrade() : empty();
|
|
83
83
|
scope = requested.scope;
|
|
84
84
|
}
|
|
85
|
-
const { registry, fallbackAdmitted } = await visibleSourcesFor({
|
|
85
|
+
const { registry, fallbackAdmitted, ownFailing } = await visibleSourcesFor({
|
|
86
86
|
runtime,
|
|
87
87
|
req,
|
|
88
88
|
resolved: await resolveRegistryFor(runtime, {
|
|
@@ -105,7 +105,7 @@ const resolveSourcesForRequest = async (req, args = {}) => {
|
|
|
105
105
|
}));
|
|
106
106
|
return listed.sources.some((source) => fallbackAdmitted.has(source.id)) ? {
|
|
107
107
|
...listed,
|
|
108
|
-
notice: "platformFallback"
|
|
108
|
+
notice: ownFailing ? "ownSourceFailing" : "platformFallback"
|
|
109
109
|
} : listed;
|
|
110
110
|
} catch (err) {
|
|
111
111
|
req.payload.logger?.warn(`analytics: source resolution failed: ${String(err)}`);
|
|
@@ -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;CA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;EAC5F,OAAO,MAAM;CACd;CACA,MAAM,QAAQ,KAAK,SAAS,WAAW,SAAS,GAAG;CACnD,MAAM,UAAU,YACf,QAAQ,SACL,MAAM,IACN,aAAa;EAAE;EAAS;EAAK,UAAU,QAAQ;EAAU,OAAO;CAAK,CAAC;CAC1E,IAAI;EACH,IAAI;EACJ,IAAI,KAAK,UAAU,KAAA,GAAW;GAC7B,IAAI,CAAC,aAAa,KAAK,KAAK,GAC3B,OAAO,MAAM;GAEd,QAAQ,KAAK,MAAM;EACpB,OAAO;GACN,MAAM,YAAY,MAAM,sBAAsB;IAAE;IAAS;IAAK;GAAM,CAAC;GACrE,IAAI,CAAC,UAAU,IACd,OAAO,UAAU,WAAW,WAAW,QAAQ,IAAI,MAAM;GAE1D,QAAQ,UAAU;EACnB;EAMA,MAAM,EAAE,UAAU,kBAAkB,eAAe,MAAM,kBAAkB;GAC1E;GACA;GACA,UAAA,MARsB,mBAAmB,SAAS;IAClD,SAAS,IAAI;IACb;IACA,OAAO,gBAAgB,KAAK;GAC7B,CAAC;GAKA;GACA;EACD,CAAC;EACD,IAAI,CAAC,UACJ,OAAO;GAAE,GAAG,MAAM;GAAG;EAAM;EAE5B,MAAM,SAAS,cAAc,SAAS,MAAM,aAAa;GAAE;GAAS;GAAK;GAAU;EAAM,CAAC,CAAC;EAC3F,OAAO,OAAO,QAAQ,MAAM,WAAW,iBAAiB,IAAI,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":";;;;;;;AAWA,MAAa,qBAAgC;;;;;AAM7C,MAAa,uBAAuB;AAqCpC,MAAa,cAAc,UAAiC;CAC3D;CACA,OAAO,GAAG,KAAK;CACf,UAAU,GAAG,KAAK;CAClB,SAAS,GAAG,KAAK;CACjB,OAAO,GAAG,KAAK;CACf,SAAS,GAAG,KAAK;CACjB,gBAAgB,GAAG,KAAK;CACxB,MAAM,GAAG,KAAK;CACd,WAAW,GAAG,KAAK;CACnB,QAAQ,GAAG,KAAK;CAChB,QAAQ,GAAG,KAAK;CAChB,OAAO,GAAG,KAAK;CACf,cAAc,GAAG,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