@10x-media/analytics 0.1.0-beta.5 → 1.0.0-beta.7
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 +40 -0
- package/LICENSE +21 -21
- package/README.md +5 -1
- package/dist/adapters/ga4/ga4.js +13 -0
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/http/fetchJson.js +1 -1
- package/dist/adapters/plausible/plausible.d.ts +10 -0
- package/dist/adapters/plausible/plausible.js +51 -0
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +10 -1
- package/dist/adapters/posthog/posthog.js +84 -3
- package/dist/adapters/posthog/posthog.js.map +1 -1
- package/dist/adapters/series.js +11 -1
- package/dist/adapters/series.js.map +1 -1
- package/dist/adapters/umami/umami.d.ts +5 -1
- package/dist/adapters/umami/umami.js +28 -0
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/capture/getTrackerConfig.d.ts +20 -0
- package/dist/capture/getTrackerConfig.js +31 -0
- package/dist/capture/getTrackerConfig.js.map +1 -0
- package/dist/capture/mountPath.js +14 -0
- package/dist/capture/mountPath.js.map +1 -0
- package/dist/capture/proxyEndpoint.js +123 -0
- package/dist/capture/proxyEndpoint.js.map +1 -0
- package/dist/capture/proxyRoutes.js +108 -0
- package/dist/capture/proxyRoutes.js.map +1 -0
- package/dist/capture/requestBody.js +68 -0
- package/dist/capture/requestBody.js.map +1 -0
- package/dist/capture/slots.d.ts +8 -0
- package/dist/capture/slots.js +43 -0
- package/dist/capture/slots.js.map +1 -0
- package/dist/capture/trackerConfig.d.ts +32 -0
- package/dist/capture/trackerConfig.js +70 -0
- package/dist/capture/trackerConfig.js.map +1 -0
- package/dist/capture/trackerEndpoint.js +35 -0
- package/dist/capture/trackerEndpoint.js.map +1 -0
- package/dist/core/capabilities.d.ts +5 -1
- package/dist/core/capabilities.js +4 -0
- package/dist/core/capabilities.js.map +1 -1
- package/dist/core/capture.d.ts +49 -0
- package/dist/core/contract.d.ts +33 -4
- package/dist/core/contract.js.map +1 -1
- package/dist/core/options.d.ts +97 -2
- package/dist/core/options.js +63 -2
- package/dist/core/options.js.map +1 -1
- package/dist/core/registry.d.ts +1 -0
- package/dist/core/scopeList.js +32 -0
- package/dist/core/scopeList.js.map +1 -0
- package/dist/core/scopedRead.js +13 -6
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/exports/next.d.ts +2 -1
- package/dist/exports/next.js +2 -1
- package/dist/exports/react.d.ts +4 -0
- package/dist/exports/react.js +5 -0
- package/dist/exports/rsc.d.ts +5 -2
- package/dist/exports/rsc.js +3 -1
- package/dist/exports/tracker.d.ts +18 -0
- package/dist/exports/tracker.js +12 -0
- package/dist/exports/types.d.ts +6 -3
- package/dist/fields/AnalyticsPanelClient.js +1 -1
- package/dist/fields/config/narrow.js +2 -0
- package/dist/fields/config/narrow.js.map +1 -1
- package/dist/fields/readForDocument.js +1 -1
- package/dist/goals/match.js +64 -0
- package/dist/goals/match.js.map +1 -0
- package/dist/goals/types.d.ts +33 -0
- package/dist/goals/types.js +7 -0
- package/dist/goals/types.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +39 -10
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +21 -1
- package/dist/native/collections/events.js.map +1 -1
- package/dist/native/collections/rollups.js +39 -3
- package/dist/native/collections/rollups.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +2 -4
- package/dist/native/geo/maxmindResolver.js.map +1 -1
- package/dist/native/ingest/clientIp.js +15 -0
- package/dist/native/ingest/clientIp.js.map +1 -0
- package/dist/native/ingest/endpoint.js +40 -4
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/flushBatch.js +4 -13
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/normalizeEvent.js +76 -9
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/nativeAdapter.js +100 -5
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +161 -0
- package/dist/native/query/eventAgg.js.map +1 -0
- package/dist/native/rollupAcc.js +12 -1
- package/dist/native/rollupAcc.js.map +1 -1
- package/dist/native/rollups/applyDistinctDeltas.js +1 -1
- package/dist/native/rollups/applyDistinctDeltas.js.map +1 -1
- package/dist/native/rollups/bumpRollup.js +7 -2
- package/dist/native/rollups/bumpRollup.js.map +1 -1
- package/dist/native/rollups/deltas.js +70 -11
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/next/captureRewrites.d.ts +41 -0
- package/dist/next/captureRewrites.js +56 -0
- package/dist/next/captureRewrites.js.map +1 -0
- package/dist/next/posthogProxyRewrites.d.ts +5 -0
- package/dist/next/posthogProxyRewrites.js +16 -21
- package/dist/next/posthogProxyRewrites.js.map +1 -1
- package/dist/plugin/documentEndpoint.js +1 -1
- package/dist/plugin/paths.js +11 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/runtime.d.ts +1 -0
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/sourcesEndpoint.js +16 -4
- package/dist/plugin/sourcesEndpoint.js.map +1 -1
- package/dist/plugin/warmTask.js +0 -0
- package/dist/plugin/warmTask.js.map +1 -1
- package/dist/providers/collection.js +56 -16
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +8 -2
- package/dist/providers/factory.js.map +1 -1
- package/dist/react/AnalyticsProvider.d.ts +43 -0
- package/dist/react/AnalyticsProvider.js +66 -0
- package/dist/react/AnalyticsProvider.js.map +1 -0
- package/dist/react/TrackerBoot.d.ts +22 -0
- package/dist/react/TrackerBoot.js +30 -0
- package/dist/react/TrackerBoot.js.map +1 -0
- package/dist/react/useAnalytics.d.ts +17 -0
- package/dist/react/useAnalytics.js +36 -0
- package/dist/react/useAnalytics.js.map +1 -0
- package/dist/rsc/AnalyticsScripts.d.ts +30 -0
- package/dist/rsc/AnalyticsScripts.js +41 -0
- package/dist/rsc/AnalyticsScripts.js.map +1 -0
- package/dist/surfacing/cacheStore.d.ts +1 -0
- package/dist/surfacing/cacheStore.js +18 -2
- package/dist/surfacing/cacheStore.js.map +1 -1
- package/dist/surfacing/engine.d.ts +1 -0
- package/dist/surfacing/engine.js +44 -4
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/queue.js +22 -6
- package/dist/surfacing/queue.js.map +1 -1
- package/dist/surfacing/rateLimiter.js +130 -0
- package/dist/surfacing/rateLimiter.js.map +1 -0
- package/dist/surfacing/retryPolicy.js +15 -0
- package/dist/surfacing/retryPolicy.js.map +1 -0
- package/dist/sync/collection.js +23 -7
- package/dist/sync/collection.js.map +1 -1
- package/dist/sync/syncTask.js +68 -33
- package/dist/sync/syncTask.js.map +1 -1
- package/dist/testing/memoryAdapter.d.ts +2 -0
- package/dist/testing/memoryAdapter.js +17 -0
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/tracker/autoCapture.d.ts +48 -0
- package/dist/tracker/autoCapture.js +129 -0
- package/dist/tracker/autoCapture.js.map +1 -0
- package/dist/tracker/consent.d.ts +24 -0
- package/dist/tracker/consent.js +48 -0
- package/dist/tracker/consent.js.map +1 -0
- package/dist/tracker/createTracker.d.ts +18 -0
- package/dist/tracker/createTracker.js +163 -0
- package/dist/tracker/createTracker.js.map +1 -0
- package/dist/tracker/initTracker.d.ts +22 -0
- package/dist/tracker/initTracker.js +33 -0
- package/dist/tracker/initTracker.js.map +1 -0
- package/dist/tracker/loadScript.d.ts +14 -0
- package/dist/tracker/loadScript.js +41 -0
- package/dist/tracker/loadScript.js.map +1 -0
- package/dist/tracker/pageTracking.d.ts +17 -0
- package/dist/tracker/pageTracking.js +38 -0
- package/dist/tracker/pageTracking.js.map +1 -0
- package/dist/tracker/registry.d.ts +27 -0
- package/dist/tracker/registry.js +73 -0
- package/dist/tracker/registry.js.map +1 -0
- package/dist/tracker/sinks/native.d.ts +22 -0
- package/dist/tracker/sinks/native.js +56 -0
- package/dist/tracker/sinks/native.js.map +1 -0
- package/dist/tracker/sinks/plausible.d.ts +14 -0
- package/dist/tracker/sinks/plausible.js +25 -0
- package/dist/tracker/sinks/plausible.js.map +1 -0
- package/dist/tracker/sinks/posthog.d.ts +14 -0
- package/dist/tracker/sinks/posthog.js +18 -0
- package/dist/tracker/sinks/posthog.js.map +1 -0
- package/dist/tracker/sinks/umami.d.ts +13 -0
- package/dist/tracker/sinks/umami.js +17 -0
- package/dist/tracker/sinks/umami.js.map +1 -0
- package/dist/tracker/sinks/vendor.d.ts +14 -0
- package/dist/tracker/sinks/vendor.js +66 -0
- package/dist/tracker/sinks/vendor.js.map +1 -0
- package/dist/tracker/transport.js +28 -0
- package/dist/tracker/transport.js.map +1 -0
- package/dist/tracker/types.d.ts +66 -0
- package/dist/translations/ar.js +83 -0
- package/dist/translations/ar.js.map +1 -0
- package/dist/translations/de.js +6 -0
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +6 -0
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +83 -0
- package/dist/translations/es.js.map +1 -0
- package/dist/translations/fr.js +83 -0
- package/dist/translations/fr.js.map +1 -0
- package/dist/translations/id.js +83 -0
- package/dist/translations/id.js.map +1 -0
- package/dist/translations/index.d.ts +10 -1
- package/dist/translations/index.js +19 -1
- package/dist/translations/index.js.map +1 -1
- package/dist/translations/keys.d.ts +6 -0
- package/dist/translations/keys.js +6 -0
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +83 -0
- package/dist/translations/ko.js.map +1 -0
- package/dist/translations/pt.js +83 -0
- package/dist/translations/pt.js.map +1 -0
- package/dist/translations/ru.js +83 -0
- package/dist/translations/ru.js.map +1 -0
- package/dist/translations/uk.js +83 -0
- package/dist/translations/uk.js.map +1 -0
- package/dist/translations/zh.js +83 -0
- package/dist/translations/zh.js.map +1 -0
- package/dist/widgets/breakdownTypes.js +5 -0
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +2 -1
- package/dist/widgets/readForWidget.js +32 -14
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +2 -1
- package/dist/widgets/readForWidgetBreakdown.js +29 -15
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetRealtime.js +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +2 -1
- package/dist/widgets/readForWidgetSeries.js +34 -16
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/registerWidgets.js +10 -4
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.js +4 -1
- package/dist/widgets/types.js.map +1 -1
- package/package.json +20 -5
package/dist/core/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport type { TranslationsOption } from '../translations'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { AnalyticsAdapter } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: { ttl?: { aggregate?: number; realtime?: number }; warm?: boolean | { cron?: string } }\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: { platformRead: PlatformReadAccess }\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t},\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t},\n\t\twidgets,\n\t\tsync,\n\t}\n}\n"],"mappings":";;AAQA,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,M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AQ,OAAO,KAAK;GAC/B;GACA;EACD;EACA;EACA;CACD;AACD"}
|
|
1
|
+
{"version":3,"file":"options.js","names":[],"sources":["../../src/core/options.ts"],"sourcesContent":["import type { KeysConfig } from '@10x-media/fields/encrypted'\nimport type { CollectionConfig, CollectionSlug, Payload, PayloadRequest } from 'payload'\nimport type { AnalyticsBinding, ResolvedBinding } from '../binding/types'\nimport { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS } from '../capture/proxyEndpoint'\nimport type { CaptureSlot } from '../capture/slots'\nimport { GOAL_SLUG_PATTERN, type Goal } from '../goals/types'\nimport { PROVIDERS_SLUG } from '../providers/collection'\nimport type { TranslationsOption } from '../translations'\nimport type { CustomWidgetDef } from '../widgets/customWidget'\nimport type { CaptureClientKind } from './capture'\nimport type { AnalyticsAdapter } from './contract'\n\nconst DEFAULT_WARM_CRON = '*/30 * * * *'\nconst DEFAULT_SYNC_CRON = '0 */6 * * *'\nconst DEFAULT_SYNC_COLLECTION = 'analytics-daily'\nconst DEFAULT_SYNC_LOOKBACK = 3\nconst DEFAULT_SCOPE_FIELD = 'scope'\nconst DEFAULT_TIMEOUT_MS = 15_000\n\n/**\n * Maps a request to its analytics boundary (tenant id, site key). Null means the\n * whole install, which is the default single-site behavior. With a multi-tenant\n * plugin, return the request's tenant id here.\n */\nexport type ScopeResolver = (args: {\n\treq: PayloadRequest\n}) => string | null | Promise<string | null>\n\n/**\n * Resolves the IANA reporting timezone a read's (or ingest's) day boundaries align\n * to. Receives the request and its already-resolved scope, so per-tenant, per-user\n * (`req.user`), and selector (cookie/preference) strategies are all expressible.\n * Return `null` to fall back to UTC.\n */\nexport type TimezoneResolver = (args: {\n\treq: PayloadRequest\n\tscope: string | null\n}) => string | null | Promise<string | null>\n\n/**\n * Enumerates the tenant scopes the cron tiers (cache warming, sync) fan out over.\n * Absent, each tier runs once for the install-wide scope.\n */\nexport type ScopesResolver = (args: { payload: Payload }) => string[] | Promise<string[]>\n\n/**\n * Escape hatch replacing the provider-collection lookup: return the runtime\n * adapters for a scope yourself (any store, any shape). Results are layered onto\n * the static config adapters exactly like collection-resolved ones, but are not\n * cached; memoize inside the function if lookups are expensive.\n */\nexport type ProvidersResolve = (args: {\n\tpayload: Payload\n\treq?: PayloadRequest\n\tscope: string | null\n}) => AnalyticsAdapter[] | Promise<AnalyticsAdapter[]>\n\nexport type ProvidersCollectionOptions = {\n\tslug?: string\n\t/**\n\t * Field matched against the resolved scope when looking up a scope's providers.\n\t * Point it at a tenant plugin's field (e.g. 'tenant') when that plugin manages\n\t * scoping for the collection.\n\t */\n\tscopeField?: string\n\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\taccess?: Partial<CollectionConfig['access']>\n\t/**\n\t * Dedicated key ring for the stored provider credentials. Unset, the\n\t * fields plugin's global `encrypted.keys` applies, and with neither the\n\t * ring derives from the Payload secret. Configure a dedicated key for\n\t * anything beyond a dev install.\n\t */\n\tencryption?: { keys?: KeysConfig }\n}\n\nexport type ProvidersOptions = {\n\t/** Opt-in admin collection storing runtime provider configurations. */\n\tcollection?: boolean | ProvidersCollectionOptions\n\tresolve?: ProvidersResolve\n}\n\n/** Access checker for cross-scope (platform) analytics reads. */\nexport type PlatformReadAccess = (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\nexport type AnalyticsAccessOptions = {\n\t/**\n\t * Gates cross-scope reads: explicit `scope: '*'` reads, and scoped reads through\n\t * a shared config adapter that cannot filter by scope. Scoped installs\n\t * (`scopeResolver` configured) default to deny; configure it, for example a role\n\t * check, so platform admins can read cross-scope and manage every tenant's\n\t * providers. Unscoped installs default to any authenticated admin-panel user.\n\t */\n\tplatformRead?: PlatformReadAccess\n}\n\nexport type ConsentMode = 'none' | 'required'\n\n/** Per-slot consent decision, evaluated against the slot's resolved adapter. */\nexport type ConsentResolver = (args: { slot: CaptureSlot; adapterId: string }) => ConsentMode\n\n/** An adapter id to fill a capture slot with, or `false` to leave it deliberately empty. */\nexport type CaptureSlotOption = string | false\n\n/**\n * A bare mode applies to every slot; a resolver decides per request-resolved adapter; the\n * object form maps ids and slots, with an adapter entry winning over a slot entry. Every\n * form overrides the default, which is `none` for the cookieless native tracker and\n * `required` for a vendor's.\n */\nexport type CaptureConsentOption =\n\t| ConsentMode\n\t| ConsentResolver\n\t| {\n\t\t\tslots?: Partial<Record<CaptureSlot, ConsentMode>>\n\t\t\t/**\n\t\t\t * Keyed by adapter id. A bare id must name a config adapter; a runtime provider\n\t\t\t * instance id (`<provider>:<instance>`) is taken on trust, since the providers it\n\t\t\t * comes from are only resolved per request.\n\t\t\t */\n\t\t\tadapters?: Record<string, ConsentMode>\n\t }\n\n/** The normalized policy the runtime evaluates; `kind` carries the adapter's tracker family. */\nexport type ConsentPolicy = (\n\tslot: CaptureSlot,\n\tadapterId: string,\n\tkind: CaptureClientKind\n) => ConsentMode\n\nexport type AutoCaptureOptions = {\n\tscrollDepth?: boolean\n\toutboundLinks?: boolean\n\tfileDownloads?: boolean\n\tgoalAttribute?: boolean\n}\n\nexport type ResolvedAutoCapture = Required<AutoCaptureOptions>\n\n/** Goals as config: the array form, or the object form 1b grows a collection source on. */\nexport type AnalyticsGoalsOptions = { defaults?: Goal[] }\n\nexport type AnalyticsCaptureOptions = {\n\t/**\n\t * Which adapter fills each capture slot, overriding the defaults: `global` is the\n\t * designated `platformAdapter`, or the single config adapter when only one is\n\t * configured; `tenant` is the resolved scope's default adapter. A `global` id must\n\t * name a config adapter; a `tenant` id may also name a runtime provider instance,\n\t * so it is resolved per request rather than validated at config time.\n\t *\n\t * `false` disables a slot outright: it fills with nothing, its proxy mount 404s, and\n\t * the tracker config omits it. Use it to keep a default from filling a slot at all.\n\t */\n\tslots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * Mount each slot's snippet points at. Defaults to the runtime proxy endpoint\n\t * (`<routes.api>/analytics/p/<slot>`); set it when the slot is served through Next\n\t * rewrites instead, passing the same path `captureRewrites` was mounted at.\n\t */\n\tpaths?: { global?: string; tenant?: string }\n\t/** Whether a slot's tracker waits for consent. Native defaults to no gate, vendors to one. */\n\tconsent?: CaptureConsentOption\n\t/** Browser auto-capture listeners, all on by default except `scrollDepth`. */\n\tautoCapture?: AutoCaptureOptions\n\t/** Limits for the public runtime capture proxy, separate from the read-path `cache`. */\n\tproxy?: {\n\t\t/**\n\t\t * Deadline for the upstream response headers, in ms. Default 10000. The body\n\t\t * download is not on the clock, so a large tracker bundle streams to completion.\n\t\t */\n\t\ttimeoutMs?: number\n\t\t/**\n\t\t * Largest proxied request body, in bytes. Default 1 MiB, which clears a PostHog\n\t\t * batch carrying session-replay data. Anything larger is refused with 413.\n\t\t */\n\t\tmaxBodyBytes?: number\n\t}\n}\n\nexport type AnalyticsPluginOptions = {\n\tdisabled?: boolean\n\t/**\n\t * Per-locale overrides for this plugin's UI strings, keyed by the typed\n\t * translation keys exported from `@10x-media/analytics/i18n`. Values win over\n\t * the built-in locales key-by-key; locales the plugin does not ship are added\n\t * whole. App-level `i18n.translations` still wins over both.\n\t */\n\ttranslations?: TranslationsOption\n\tadapters?: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver?: ScopeResolver\n\t/**\n\t * Enumerates the tenant scopes the cache-warming and sync cron tiers fan out\n\t * over, in addition to the install-wide (null) scope every tier already runs.\n\t * Unset, those tiers run once for the whole install, same as before.\n\t */\n\tscopes?: ScopesResolver\n\t/**\n\t * IANA reporting timezone that day boundaries (timeframe windows, series axes,\n\t * native rollup buckets) align to. Defaults to UTC. A string forces one timezone\n\t * (the single-tenant / no-multi-tenancy case); a resolver derives it per request\n\t * from the scope, user, or a selector. Native rollups bucket at ingest in the\n\t * resolved timezone, so changing it does not re-bucket existing history.\n\t */\n\treportingTimezone?: string | TimezoneResolver\n\tproviders?: ProvidersOptions\n\t/**\n\t * Id of one config adapter shared by every scope (the platform's own analytics,\n\t * e.g. a PostHog project capturing all tenants). Included in each scope's\n\t * registry like any config adapter; reads through it are scope-filtered only\n\t * when the adapter supports scoped queries, otherwise they are cross-scope and\n\t * require `access.platformRead`.\n\t */\n\tplatformAdapter?: string\n\taccess?: AnalyticsAccessOptions\n\tcapture?: AnalyticsCaptureOptions\n\t/**\n\t * Conversion goals the tracker and the native ingest match events against. Slugs must\n\t * be unique and kebab-case; only the slug and its match reach the browser.\n\t */\n\tgoals?: Goal[] | AnalyticsGoalsOptions\n\t/**\n\t * Per-collection bindings, keyed by collection slug. With generated types\n\t * augmented, each slug's resolvers receive that collection's typed document.\n\t */\n\tcollections?: { [TSlug in CollectionSlug]?: AnalyticsBinding<TSlug> }\n\tcache?: {\n\t\tttl?: { aggregate?: number; realtime?: number }\n\t\twarm?: boolean | { cron?: string }\n\t\t/** Per-read provider timeout in ms, spanning retries and limiter waits. Default 15000. */\n\t\ttimeoutMs?: number\n\t}\n\twidgets?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tdisabled?: string[]\n\t\t\t\tregister?: CustomWidgetDef[]\n\t\t\t\t/**\n\t\t\t\t * Marks the free-text widget config fields (each widget's Title) as\n\t\t\t\t * `localized`. Off by default; takes effect only when the Payload config\n\t\t\t\t * enables localization (Payload strips the flag otherwise).\n\t\t\t\t */\n\t\t\t\tlocalizeText?: boolean\n\t\t\t\t/**\n\t\t\t\t * Period-over-period comparison on the metric and trend widgets. On by\n\t\t\t\t * default for adapters that declare `capabilities.comparison`; set false\n\t\t\t\t * to skip the second (previous-window) read entirely.\n\t\t\t\t */\n\t\t\t\tcomparison?: boolean\n\t\t }\n\t/**\n\t * Opt-in sync tier: a cron job that persists each provider's daily metrics into a\n\t * queryable collection. Reads go through the surfacing cache, so persisted rows reflect\n\t * cached values up to `cache.ttl.aggregate` old; keep that TTL below the sync interval\n\t * for the freshest data.\n\t */\n\tsync?:\n\t\t| boolean\n\t\t| {\n\t\t\t\tcollectionSlug?: CollectionSlug\n\t\t\t\tcron?: string\n\t\t\t\tlookbackDays?: number\n\t\t\t\tadapters?: string[]\n\t\t\t\t/** Surface the analytics-daily collection in the admin nav. Default false (hidden). */\n\t\t\t\thidden?: boolean\n\t\t }\n}\n\nexport interface ResolvedCapture {\n\tslots: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\tpaths: { global?: string; tenant?: string }\n\tconsent: ConsentPolicy\n\tautoCapture: ResolvedAutoCapture\n\tproxy: { timeoutMs: number; maxBodyBytes: number }\n}\n\nexport interface ResolvedOptions {\n\tadapters: AnalyticsAdapter[]\n\tdefaultAdapter?: string\n\tscopeResolver: ScopeResolver\n\t/** True when the app configured a scopeResolver (scoped install). */\n\tscoped: boolean\n\t/** Raw scopes option; undefined runs the cron tiers install-wide only. */\n\tscopes?: ScopesResolver\n\t/** Raw reportingTimezone option; normalized into a resolver at init. */\n\treportingTimezone?: string | TimezoneResolver\n\tplatformAdapter?: string\n\taccess: { platformRead: PlatformReadAccess }\n\tcapture: ResolvedCapture\n\t/** Config goals, validated; 1b layers collection-sourced goals on top of these. */\n\tgoals: Goal[]\n\tproviders: {\n\t\tcollection: {\n\t\t\tenabled: boolean\n\t\t\tslug: string\n\t\t\tscopeField: string\n\t\t\toverrides?: (collection: CollectionConfig) => CollectionConfig\n\t\t\taccess?: Partial<CollectionConfig['access']>\n\t\t\tencryption?: { keys?: KeysConfig }\n\t\t}\n\t\tresolve?: ProvidersResolve\n\t}\n\tbindings: Record<string, ResolvedBinding>\n\tcache: {\n\t\t/** Undefined when unset: adapter recommendedTtl is the fallback, an explicit value wins. */\n\t\tttl: { aggregate?: number; realtime?: number }\n\t\twarm: { enabled: boolean; cron: string }\n\t\ttimeoutMs: number\n\t}\n\twidgets: {\n\t\tenabled: boolean\n\t\tdisabled: string[]\n\t\tregister: CustomWidgetDef[]\n\t\tlocalizeText: boolean\n\t\tcomparison: boolean\n\t}\n\tsync: {\n\t\tenabled: boolean\n\t\tcollectionSlug: string\n\t\tcron: string\n\t\tlookbackDays: number\n\t\tadapters?: string[]\n\t\t/** True hides the analytics-daily collection from the admin nav (default). */\n\t\thidden: boolean\n\t}\n}\n\n/** Scroll depth is the one listener off by default: it fires on every page, for every visitor. */\nexport const DEFAULT_AUTO_CAPTURE: ResolvedAutoCapture = {\n\tscrollDepth: false,\n\toutboundLinks: true,\n\tfileDownloads: true,\n\tgoalAttribute: true,\n}\n\nconst resolveAutoCapture = (option: AutoCaptureOptions | undefined): ResolvedAutoCapture => ({\n\tscrollDepth: option?.scrollDepth ?? DEFAULT_AUTO_CAPTURE.scrollDepth,\n\toutboundLinks: option?.outboundLinks ?? DEFAULT_AUTO_CAPTURE.outboundLinks,\n\tfileDownloads: option?.fileDownloads ?? DEFAULT_AUTO_CAPTURE.fileDownloads,\n\tgoalAttribute: option?.goalAttribute ?? DEFAULT_AUTO_CAPTURE.goalAttribute,\n})\n\n/** Cookieless native capture needs no consent gate; a vendor's tracker does. */\nexport const defaultConsentFor = (kind: CaptureClientKind): ConsentMode =>\n\tkind === 'native' ? 'none' : 'required'\n\nconst resolveConsent = (\n\toption: CaptureConsentOption | undefined,\n\tadapters: AnalyticsAdapter[]\n): ConsentPolicy => {\n\tif (option === 'none' || option === 'required') {\n\t\treturn () => option\n\t}\n\tif (typeof option === 'function') {\n\t\treturn (slot, adapterId) => option({ slot, adapterId })\n\t}\n\tfor (const id of Object.keys(option?.adapters ?? {})) {\n\t\t// A runtime provider instance id is `<provider>:<instance>` and only exists once a\n\t\t// scope resolves, so it cannot be checked here; a bare id must name a config adapter.\n\t\tif (!id.includes(':') && !adapters.some((a) => a.id === id)) {\n\t\t\tthrow new Error(`analytics: unknown consent adapter \"${id}\"`)\n\t\t}\n\t}\n\treturn (slot, adapterId, kind) =>\n\t\toption?.adapters?.[adapterId] ?? option?.slots?.[slot] ?? defaultConsentFor(kind)\n}\n\nconst resolveGoals = (option: AnalyticsPluginOptions['goals']): Goal[] => {\n\tconst goals = Array.isArray(option) ? option : (option?.defaults ?? [])\n\tconst seen = new Set<string>()\n\tfor (const goal of goals) {\n\t\tif (!GOAL_SLUG_PATTERN.test(goal.slug)) {\n\t\t\tthrow new Error(`analytics: goal slug \"${goal.slug}\" must be kebab-case`)\n\t\t}\n\t\tif (seen.has(goal.slug)) {\n\t\t\tthrow new Error(`analytics: duplicate goal slug \"${goal.slug}\"`)\n\t\t}\n\t\tconst fixed = goal.value?.fixed\n\t\t// Revenue is money: a negative or non-finite fixed value would be silently ignored at\n\t\t// ingest, so it fails the boot instead.\n\t\tif (fixed !== undefined && (!Number.isFinite(fixed) || fixed < 0)) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: goal \"${goal.slug}\" value.fixed must be a finite number >= 0, got ${String(fixed)}`\n\t\t\t)\n\t\t}\n\t\tseen.add(goal.slug)\n\t}\n\treturn goals\n}\n\nconst resolveBindings = (\n\tcollections: AnalyticsPluginOptions['collections']\n): Record<string, ResolvedBinding> => {\n\tconst out: Record<string, ResolvedBinding> = {}\n\tfor (const [slug, binding] of Object.entries(collections ?? {})) {\n\t\tif (!binding) continue\n\t\tif (!binding.path && !binding.pathField) {\n\t\t\tthrow new Error(`analytics: binding for \"${slug}\" needs a path resolver or a pathField`)\n\t\t}\n\t\t// Erases the per-slug doc generic; safe because the runtime only ever hands\n\t\t// a binding documents from its own collection.\n\t\tout[slug] = binding as ResolvedBinding\n\t}\n\treturn out\n}\n\nexport function resolveOptions(options: AnalyticsPluginOptions): ResolvedOptions {\n\tif (!options.adapters || options.adapters.length === 0) {\n\t\tthrow new Error('analytics: at least one adapter is required')\n\t}\n\tif (\n\t\toptions.platformAdapter !== undefined &&\n\t\t!options.adapters.some((a) => a.id === options.platformAdapter)\n\t) {\n\t\tthrow new Error(`analytics: unknown platform adapter \"${options.platformAdapter}\"`)\n\t}\n\tfor (const [slot, value] of Object.entries(options.capture?.slots ?? {})) {\n\t\tif (value !== false && typeof value !== 'string' && value !== undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`analytics: capture slot \"${slot}\" must be an adapter id or false, got ${typeof value}`\n\t\t\t)\n\t\t}\n\t}\n\tconst globalSlot = options.capture?.slots?.global\n\t// A tenant id may name a runtime provider instance, which only exists once a scope\n\t// resolves; a global one can only come from the config registry, so it is checked here.\n\tif (typeof globalSlot === 'string' && !options.adapters.some((a) => a.id === globalSlot)) {\n\t\tthrow new Error(`analytics: unknown global capture slot adapter \"${globalSlot}\"`)\n\t}\n\tconst widgets =\n\t\toptions.widgets === false\n\t\t\t? {\n\t\t\t\t\tenabled: false,\n\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\tcomparison: true,\n\t\t\t\t}\n\t\t\t: options.widgets === undefined || options.widgets === true\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: [] as string[],\n\t\t\t\t\t\tregister: [] as CustomWidgetDef[],\n\t\t\t\t\t\tlocalizeText: false,\n\t\t\t\t\t\tcomparison: true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tdisabled: options.widgets.disabled ?? [],\n\t\t\t\t\t\tregister: options.widgets.register ?? [],\n\t\t\t\t\t\tlocalizeText: options.widgets.localizeText ?? false,\n\t\t\t\t\t\tcomparison: options.widgets.comparison ?? true,\n\t\t\t\t\t}\n\tconst warmOpt = options.cache?.warm\n\tconst warm =\n\t\twarmOpt === true\n\t\t\t? { enabled: true, cron: DEFAULT_WARM_CRON }\n\t\t\t: warmOpt && typeof warmOpt === 'object'\n\t\t\t\t? { enabled: true, cron: warmOpt.cron ?? DEFAULT_WARM_CRON }\n\t\t\t\t: { enabled: false, cron: DEFAULT_WARM_CRON }\n\tconst collectionOpt = options.providers?.collection\n\tconst providers = {\n\t\tcollection:\n\t\t\tcollectionOpt === true\n\t\t\t\t? { enabled: true, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD }\n\t\t\t\t: collectionOpt && typeof collectionOpt === 'object'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\t\tslug: collectionOpt.slug ?? PROVIDERS_SLUG,\n\t\t\t\t\t\t\tscopeField: collectionOpt.scopeField ?? DEFAULT_SCOPE_FIELD,\n\t\t\t\t\t\t\toverrides: collectionOpt.overrides,\n\t\t\t\t\t\t\taccess: collectionOpt.access,\n\t\t\t\t\t\t\tencryption: collectionOpt.encryption,\n\t\t\t\t\t\t}\n\t\t\t\t\t: { enabled: false, slug: PROVIDERS_SLUG, scopeField: DEFAULT_SCOPE_FIELD },\n\t\tresolve: options.providers?.resolve,\n\t}\n\tif (providers.collection.enabled) {\n\t\tif (providers.collection.scopeField.trim() === '') {\n\t\t\tthrow new Error('analytics: providers.collection.scopeField must be a non-empty field name')\n\t\t}\n\t\tif (providers.collection.scopeField.includes('.')) {\n\t\t\tthrow new Error(\n\t\t\t\t'analytics: providers.collection.scopeField must be a top-level field name (no dots); the scope stamp writes it as a flat key'\n\t\t\t)\n\t\t}\n\t}\n\tconst syncOpt = options.sync\n\tconst sync =\n\t\tsyncOpt === true\n\t\t\t? {\n\t\t\t\t\tenabled: true,\n\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\thidden: true,\n\t\t\t\t}\n\t\t\t: syncOpt && typeof syncOpt === 'object'\n\t\t\t\t? {\n\t\t\t\t\t\tenabled: true,\n\t\t\t\t\t\tcollectionSlug: syncOpt.collectionSlug ?? DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: syncOpt.cron ?? DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: syncOpt.lookbackDays ?? DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\tadapters: syncOpt.adapters,\n\t\t\t\t\t\thidden: syncOpt.hidden ?? true,\n\t\t\t\t\t}\n\t\t\t\t: {\n\t\t\t\t\t\tenabled: false,\n\t\t\t\t\t\tcollectionSlug: DEFAULT_SYNC_COLLECTION,\n\t\t\t\t\t\tcron: DEFAULT_SYNC_CRON,\n\t\t\t\t\t\tlookbackDays: DEFAULT_SYNC_LOOKBACK,\n\t\t\t\t\t\thidden: true,\n\t\t\t\t\t}\n\tconst scoped = options.scopeResolver !== undefined\n\treturn {\n\t\tadapters: options.adapters,\n\t\tdefaultAdapter: options.defaultAdapter,\n\t\tscopeResolver: options.scopeResolver ?? (() => null),\n\t\tscoped,\n\t\tscopes: options.scopes,\n\t\treportingTimezone: options.reportingTimezone,\n\t\tplatformAdapter: options.platformAdapter,\n\t\taccess: {\n\t\t\tplatformRead:\n\t\t\t\toptions.access?.platformRead ?? (scoped ? () => false : ({ req }) => Boolean(req.user)),\n\t\t},\n\t\tcapture: {\n\t\t\tslots: {\n\t\t\t\tglobal: options.capture?.slots?.global,\n\t\t\t\ttenant: options.capture?.slots?.tenant,\n\t\t\t},\n\t\t\tpaths: {\n\t\t\t\tglobal: options.capture?.paths?.global,\n\t\t\t\ttenant: options.capture?.paths?.tenant,\n\t\t\t},\n\t\t\tconsent: resolveConsent(options.capture?.consent, options.adapters),\n\t\t\tautoCapture: resolveAutoCapture(options.capture?.autoCapture),\n\t\t\tproxy: {\n\t\t\t\ttimeoutMs: options.capture?.proxy?.timeoutMs ?? DEFAULT_PROXY_TIMEOUT_MS,\n\t\t\t\tmaxBodyBytes: options.capture?.proxy?.maxBodyBytes ?? DEFAULT_PROXY_MAX_BODY_BYTES,\n\t\t\t},\n\t\t},\n\t\tgoals: resolveGoals(options.goals),\n\t\tproviders,\n\t\tbindings: resolveBindings(options.collections),\n\t\tcache: {\n\t\t\t// Left undefined when the app did not set them so the adapter's recommendedTtl\n\t\t\t// applies as the default; an explicit value overrides the adapter recommendation.\n\t\t\tttl: {\n\t\t\t\taggregate: options.cache?.ttl?.aggregate,\n\t\t\t\trealtime: options.cache?.ttl?.realtime,\n\t\t\t},\n\t\t\twarm,\n\t\t\ttimeoutMs: options.cache?.timeoutMs ?? DEFAULT_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|
+
* Resolves the scopes a cron tier (warm, sync) fans out over: the install-wide
|
|
4
|
+
* null scope first, then each tenant scope from `scopes()`, deduplicated (an
|
|
5
|
+
* empty string folds into null). A throwing or rejecting resolver degrades to
|
|
6
|
+
* the null-only pass so one tenant-enumeration bug does not block the whole run.
|
|
7
|
+
*/
|
|
8
|
+
const resolveScopeList = async (scopes, payload) => {
|
|
9
|
+
if (!scopes) return [null];
|
|
10
|
+
let raw;
|
|
11
|
+
try {
|
|
12
|
+
const result = await scopes({ payload });
|
|
13
|
+
if (!Array.isArray(result)) throw new Error("scopes() must resolve to an array of scope ids");
|
|
14
|
+
raw = result;
|
|
15
|
+
} catch (err) {
|
|
16
|
+
payload.logger.warn(`analytics: scopes() failed, falling back to the install-wide scope: ${String(err)}`);
|
|
17
|
+
return [null];
|
|
18
|
+
}
|
|
19
|
+
const out = [null];
|
|
20
|
+
const seen = new Set([null]);
|
|
21
|
+
for (const value of raw) {
|
|
22
|
+
const scope = value === "" ? null : value;
|
|
23
|
+
if (seen.has(scope)) continue;
|
|
24
|
+
seen.add(scope);
|
|
25
|
+
out.push(scope);
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
};
|
|
29
|
+
//#endregion
|
|
30
|
+
export { resolveScopeList };
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=scopeList.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scopeList.js","names":[],"sources":["../../src/core/scopeList.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport type { ScopesResolver } from './options'\n\n/**\n * Resolves the scopes a cron tier (warm, sync) fans out over: the install-wide\n * null scope first, then each tenant scope from `scopes()`, deduplicated (an\n * empty string folds into null). A throwing or rejecting resolver degrades to\n * the null-only pass so one tenant-enumeration bug does not block the whole run.\n */\nexport const resolveScopeList = async (\n\tscopes: ScopesResolver | undefined,\n\tpayload: Payload\n): Promise<Array<string | null>> => {\n\tif (!scopes) {\n\t\treturn [null]\n\t}\n\tlet raw: string[]\n\ttry {\n\t\tconst result = await scopes({ payload })\n\t\tif (!Array.isArray(result)) {\n\t\t\tthrow new Error('scopes() must resolve to an array of scope ids')\n\t\t}\n\t\traw = result\n\t} catch (err) {\n\t\tpayload.logger.warn(\n\t\t\t`analytics: scopes() failed, falling back to the install-wide scope: ${String(err)}`\n\t\t)\n\t\treturn [null]\n\t}\n\tconst out: Array<string | null> = [null]\n\tconst seen = new Set<string | null>([null])\n\tfor (const value of raw) {\n\t\tconst scope = value === '' ? null : value\n\t\tif (seen.has(scope)) {\n\t\t\tcontinue\n\t\t}\n\t\tseen.add(scope)\n\t\tout.push(scope)\n\t}\n\treturn out\n}\n"],"mappings":";;;;;;;AASA,MAAa,mBAAmB,OAC/B,QACA,YACmC;CACnC,IAAI,CAAC,QACJ,OAAO,CAAC,IAAI;CAEb,IAAI;CACJ,IAAI;EACH,MAAM,SAAS,MAAM,OAAO,EAAE,QAAQ,CAAC;EACvC,IAAI,CAAC,MAAM,QAAQ,MAAM,GACxB,MAAM,IAAI,MAAM,gDAAgD;EAEjE,MAAM;CACP,SAAS,KAAK;EACb,QAAQ,OAAO,KACd,uEAAuE,OAAO,GAAG,GAClF;EACA,OAAO,CAAC,IAAI;CACb;CACA,MAAM,MAA4B,CAAC,IAAI;CACvC,MAAM,OAAO,IAAI,IAAmB,CAAC,IAAI,CAAC;CAC1C,KAAK,MAAM,SAAS,KAAK;EACxB,MAAM,QAAQ,UAAU,KAAK,OAAO;EACpC,IAAI,KAAK,IAAI,KAAK,GACjB;EAED,KAAK,IAAI,KAAK;EACd,IAAI,KAAK,KAAK;CACf;CACA,OAAO;AACR"}
|
package/dist/core/scopedRead.js
CHANGED
|
@@ -5,17 +5,24 @@ import "./contract.js";
|
|
|
5
5
|
* Resolve one read's scope and adapter: explicit scope wins over the request's
|
|
6
6
|
* resolved scope, the registry is resolved per scope, then the adapter is picked
|
|
7
7
|
* by id (or the registry default). Cross-scope reads fail closed behind
|
|
8
|
-
* `platformRead`: an explicit `'*'` scope always,
|
|
9
|
-
* shared config adapter that cannot narrow the query to one scope
|
|
10
|
-
* not it is the designated platform adapter
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
8
|
+
* `platformRead`: an explicit `'*'` scope always, any scoped read through a
|
|
9
|
+
* shared config adapter that cannot narrow the query to one scope (whether or
|
|
10
|
+
* not it is the designated platform adapter), and, on a scoped install, a
|
|
11
|
+
* request that resolves no scope at all. That last case is ambiguous rather
|
|
12
|
+
* than intentionally install-wide (a tenant's scopeResolver returning null
|
|
13
|
+
* usually means "no tenant selected", not "read everything"), so it fails
|
|
14
|
+
* closed the same way. An explicit `scope: null` override bypasses that gate:
|
|
15
|
+
* it is the trusted server-side caller's path (cron passes, tests), never a
|
|
16
|
+
* request's own resolution. A tenant's own runtime adapters are never gated.
|
|
17
|
+
* Any resolution failure (unknown adapter id, a throwing scopeResolver or
|
|
18
|
+
* provider lookup) degrades to `{ ok: false }` so read paths render their
|
|
19
|
+
* unavailable state instead of throwing.
|
|
14
20
|
*/
|
|
15
21
|
const resolveReadContext = async (args) => {
|
|
16
22
|
const { runtime, req, adapterId } = args;
|
|
17
23
|
try {
|
|
18
24
|
const scope = args.scope !== void 0 ? args.scope : await resolveScopeFor(runtime, req);
|
|
25
|
+
if (runtime.scoped && args.scope === void 0 && scope === null && !await platformReadFor(runtime, req)) return { ok: false };
|
|
19
26
|
const registryScope = scope === "*" ? null : scope;
|
|
20
27
|
const registry = await resolveRegistryFor(runtime, {
|
|
21
28
|
payload: req.payload,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport {\n\ttype AnalyticsRuntime,\n\tplatformReadFor,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t }\n\t| { ok: false }\n\nexport interface ResolveReadContextArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/** Explicit scope override; undefined resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Resolve one read's scope and adapter: explicit scope wins over the request's\n * resolved scope, the registry is resolved per scope, then the adapter is picked\n * by id (or the registry default). Cross-scope reads fail closed behind\n * `platformRead`: an explicit `'*'` scope always,
|
|
1
|
+
{"version":3,"file":"scopedRead.js","names":[],"sources":["../../src/core/scopedRead.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport {\n\ttype AnalyticsRuntime,\n\tplatformReadFor,\n\tresolveRegistryFor,\n\tresolveScopeFor,\n} from '../plugin/runtime'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from './contract'\n\nexport type ReadContext =\n\t| {\n\t\t\tok: true\n\t\t\tadapter: AnalyticsAdapter\n\t\t\tscope: string | null\n\t\t\t/** The scope to stamp on the adapter query; undefined for install-wide reads. */\n\t\t\tqueryScope?: string\n\t }\n\t| { ok: false }\n\nexport interface ResolveReadContextArgs {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tadapterId?: string\n\t/** Explicit scope override; undefined resolves via the plugin's scopeResolver. */\n\tscope?: string | null\n}\n\n/**\n * Resolve one read's scope and adapter: explicit scope wins over the request's\n * resolved scope, the registry is resolved per scope, then the adapter is picked\n * by id (or the registry default). Cross-scope reads fail closed behind\n * `platformRead`: an explicit `'*'` scope always, any scoped read through a\n * shared config adapter that cannot narrow the query to one scope (whether or\n * not it is the designated platform adapter), and, on a scoped install, a\n * request that resolves no scope at all. That last case is ambiguous rather\n * than intentionally install-wide (a tenant's scopeResolver returning null\n * usually means \"no tenant selected\", not \"read everything\"), so it fails\n * closed the same way. An explicit `scope: null` override bypasses that gate:\n * it is the trusted server-side caller's path (cron passes, tests), never a\n * request's own resolution. A tenant's own runtime adapters are never gated.\n * Any resolution failure (unknown adapter id, a throwing scopeResolver or\n * provider lookup) degrades to `{ ok: false }` so read paths render their\n * unavailable state instead of throwing.\n */\nexport const resolveReadContext = async (args: ResolveReadContextArgs): Promise<ReadContext> => {\n\tconst { runtime, req, adapterId } = args\n\ttry {\n\t\tconst scope = args.scope !== undefined ? args.scope : await resolveScopeFor(runtime, req)\n\t\tif (\n\t\t\truntime.scoped &&\n\t\t\targs.scope === undefined &&\n\t\t\tscope === null &&\n\t\t\t!(await platformReadFor(runtime, req))\n\t\t) {\n\t\t\treturn { ok: false }\n\t\t}\n\t\tconst registryScope = scope === PLATFORM_SCOPE ? null : scope\n\t\tconst registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: registryScope,\n\t\t})\n\t\tconst adapter = adapterId ? registry.get(adapterId) : registry.default()\n\t\tif (scope === PLATFORM_SCOPE) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope: null, queryScope: undefined }\n\t\t}\n\t\tif (\n\t\t\tscope !== null &&\n\t\t\truntime.configAdapterIds.has(adapter.id) &&\n\t\t\t!adapter.capabilities.scopedQueries\n\t\t) {\n\t\t\tif (!(await platformReadFor(runtime, req))) {\n\t\t\t\treturn { ok: false }\n\t\t\t}\n\t\t\treturn { ok: true, adapter, scope, queryScope: undefined }\n\t\t}\n\t\treturn { ok: true, adapter, scope, queryScope: scope ?? undefined }\n\t} catch (err) {\n\t\treq.payload.logger?.warn(`analytics: read context resolution failed: ${String(err)}`)\n\t\treturn { ok: false }\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4CA,MAAa,qBAAqB,OAAO,SAAuD;CAC/F,MAAM,EAAE,SAAS,KAAK,cAAc;CACpC,IAAI;EACH,MAAM,QAAQ,KAAK,UAAU,KAAA,IAAY,KAAK,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EACxF,IACC,QAAQ,UACR,KAAK,UAAU,KAAA,KACf,UAAU,QACV,CAAE,MAAM,gBAAgB,SAAS,GAAG,GAEpC,OAAO,EAAE,IAAI,MAAM;EAEpB,MAAM,gBAAgB,UAAA,MAA2B,OAAO;EACxD,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAClD,SAAS,IAAI;GACb;GACA,OAAO;EACR,CAAC;EACD,MAAM,UAAU,YAAY,SAAS,IAAI,SAAS,IAAI,SAAS,QAAQ;EACvE,IAAI,UAAA,KAA0B;GAC7B,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS,OAAO;IAAM,YAAY,KAAA;GAAU;EAChE;EACA,IACC,UAAU,QACV,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,KACvC,CAAC,QAAQ,aAAa,eACrB;GACD,IAAI,CAAE,MAAM,gBAAgB,SAAS,GAAG,GACvC,OAAO,EAAE,IAAI,MAAM;GAEpB,OAAO;IAAE,IAAI;IAAM;IAAS;IAAO,YAAY,KAAA;GAAU;EAC1D;EACA,OAAO;GAAE,IAAI;GAAM;GAAS;GAAO,YAAY,SAAS,KAAA;EAAU;CACnE,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,8CAA8C,OAAO,GAAG,GAAG;EACpF,OAAO,EAAE,IAAI,MAAM;CACpB;AACD"}
|
package/dist/exports/next.d.ts
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
1
|
+
import { CaptureRewrite, CaptureRewriteMount, captureRewrites } from "../next/captureRewrites.js";
|
|
1
2
|
import { PosthogProxyRegion, PosthogProxyRewrite, PosthogProxyRewritesOptions, posthogProxyRewrites } from "../next/posthogProxyRewrites.js";
|
|
2
|
-
export { type PosthogProxyRegion, type PosthogProxyRewrite, type PosthogProxyRewritesOptions, posthogProxyRewrites };
|
|
3
|
+
export { type CaptureRewrite, type CaptureRewriteMount, type PosthogProxyRegion, type PosthogProxyRewrite, type PosthogProxyRewritesOptions, captureRewrites, posthogProxyRewrites };
|
package/dist/exports/next.js
CHANGED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { AnalyticsApi, AnalyticsProvider, AnalyticsProviderProps } from "../react/AnalyticsProvider.js";
|
|
2
|
+
import { TrackerBoot, TrackerBootProps } from "../react/TrackerBoot.js";
|
|
3
|
+
import { useAnalytics } from "../react/useAnalytics.js";
|
|
4
|
+
export { type AnalyticsApi, AnalyticsProvider, type AnalyticsProviderProps, TrackerBoot, type TrackerBootProps, useAnalytics };
|
package/dist/exports/rsc.d.ts
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
1
|
-
import { DateRange, DimensionKey, MetricKey } from "../core/contract.js";
|
|
1
|
+
import { AnalyticsFilter, DateRange, DimensionKey, MetricKey } from "../core/contract.js";
|
|
2
2
|
import { CapabilityRequirement } from "../core/capabilities.js";
|
|
3
3
|
import { ReadForWidgetRealtimeArgs, RealtimePoint, WidgetRealtimeResult, WidgetRealtimeStatus, readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
|
|
4
|
+
import { TrackerConfig, TrackerSlotConfig } from "../capture/trackerConfig.js";
|
|
5
|
+
import { getTrackerConfig } from "../capture/getTrackerConfig.js";
|
|
4
6
|
import { AnalyticsStatField } from "../fields/AnalyticsStatField.js";
|
|
5
7
|
import { AnalyticsPanelField } from "../fields/AnalyticsPanelField.js";
|
|
6
8
|
import { formatMetricValue } from "../fields/format.js";
|
|
7
9
|
import { ReadForWidgetArgs, WidgetReadResult, WidgetReadStatus, readForWidget } from "../widgets/readForWidget.js";
|
|
8
10
|
import { ReadForWidgetSeriesArgs, SeriesPoint, WidgetSeriesResult, readForWidgetSeries } from "../widgets/readForWidgetSeries.js";
|
|
9
11
|
import { FieldReadResult, FieldReadStatus, ReadForFieldArgs, readForField } from "../fields/readForDocument.js";
|
|
12
|
+
import { AnalyticsScripts, AnalyticsScriptsProps } from "../rsc/AnalyticsScripts.js";
|
|
10
13
|
import { AnalyticsBreakdownWidget } from "../widgets/AnalyticsBreakdownWidget.js";
|
|
11
14
|
import { AnalyticsMetricWidget } from "../widgets/AnalyticsMetricWidget.js";
|
|
12
15
|
import { AnalyticsRealtimeWidget } from "../widgets/AnalyticsRealtimeWidget.js";
|
|
13
16
|
import { AnalyticsTrendWidget } from "../widgets/AnalyticsTrendWidget.js";
|
|
14
17
|
import { cardStyle, labelStyle } from "../widgets/cardChrome.js";
|
|
15
18
|
import { BreakdownRow, ReadForWidgetBreakdownArgs, WidgetBreakdownResult, readForWidgetBreakdown } from "../widgets/readForWidgetBreakdown.js";
|
|
16
|
-
export { AnalyticsBreakdownWidget, AnalyticsMetricWidget, AnalyticsPanelField, AnalyticsRealtimeWidget, AnalyticsStatField, AnalyticsTrendWidget, type BreakdownRow, type CapabilityRequirement, type DateRange, type DimensionKey, type FieldReadResult, type FieldReadStatus, type MetricKey, type ReadForFieldArgs, type ReadForWidgetArgs, type ReadForWidgetBreakdownArgs, type ReadForWidgetRealtimeArgs, type ReadForWidgetSeriesArgs, type RealtimePoint, type SeriesPoint, type WidgetBreakdownResult, type WidgetReadResult, type WidgetReadStatus, type WidgetRealtimeResult, type WidgetRealtimeStatus, type WidgetSeriesResult, formatMetricValue, readForField, readForWidget, readForWidgetBreakdown, readForWidgetRealtime, readForWidgetSeries, cardStyle as widgetCardStyle, labelStyle as widgetLabelStyle };
|
|
19
|
+
export { AnalyticsBreakdownWidget, type AnalyticsFilter, AnalyticsMetricWidget, AnalyticsPanelField, AnalyticsRealtimeWidget, AnalyticsScripts, type AnalyticsScriptsProps, AnalyticsStatField, AnalyticsTrendWidget, type BreakdownRow, type CapabilityRequirement, type DateRange, type DimensionKey, type FieldReadResult, type FieldReadStatus, type MetricKey, type ReadForFieldArgs, type ReadForWidgetArgs, type ReadForWidgetBreakdownArgs, type ReadForWidgetRealtimeArgs, type ReadForWidgetSeriesArgs, type RealtimePoint, type SeriesPoint, type TrackerConfig, type TrackerSlotConfig, type WidgetBreakdownResult, type WidgetReadResult, type WidgetReadStatus, type WidgetRealtimeResult, type WidgetRealtimeStatus, type WidgetSeriesResult, formatMetricValue, getTrackerConfig, readForField, readForWidget, readForWidgetBreakdown, readForWidgetRealtime, readForWidgetSeries, cardStyle as widgetCardStyle, labelStyle as widgetLabelStyle };
|
package/dist/exports/rsc.js
CHANGED
|
@@ -3,12 +3,14 @@ import { readForField } from "../fields/readForDocument.js";
|
|
|
3
3
|
import { readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
|
|
4
4
|
import { readForWidget } from "../widgets/readForWidget.js";
|
|
5
5
|
import { readForWidgetBreakdown } from "../widgets/readForWidgetBreakdown.js";
|
|
6
|
+
import { getTrackerConfig } from "../capture/getTrackerConfig.js";
|
|
6
7
|
import { formatMetricValue } from "../fields/format.js";
|
|
7
8
|
import { AnalyticsStatField } from "../fields/AnalyticsStatField.js";
|
|
8
9
|
import { AnalyticsPanelField } from "../fields/AnalyticsPanelField.js";
|
|
10
|
+
import { AnalyticsScripts } from "../rsc/AnalyticsScripts.js";
|
|
9
11
|
import { cardStyle, labelStyle } from "../widgets/cardChrome.js";
|
|
10
12
|
import AnalyticsBreakdownWidget from "../widgets/AnalyticsBreakdownWidget.js";
|
|
11
13
|
import AnalyticsMetricWidget from "../widgets/AnalyticsMetricWidget.js";
|
|
12
14
|
import AnalyticsRealtimeWidget from "../widgets/AnalyticsRealtimeWidget.js";
|
|
13
15
|
import AnalyticsTrendWidget from "../widgets/AnalyticsTrendWidget.js";
|
|
14
|
-
export { AnalyticsBreakdownWidget, AnalyticsMetricWidget, AnalyticsPanelField, AnalyticsRealtimeWidget, AnalyticsStatField, AnalyticsTrendWidget, formatMetricValue, readForField, readForWidget, readForWidgetBreakdown, readForWidgetRealtime, readForWidgetSeries, cardStyle as widgetCardStyle, labelStyle as widgetLabelStyle };
|
|
16
|
+
export { AnalyticsBreakdownWidget, AnalyticsMetricWidget, AnalyticsPanelField, AnalyticsRealtimeWidget, AnalyticsScripts, AnalyticsStatField, AnalyticsTrendWidget, formatMetricValue, getTrackerConfig, readForField, readForWidget, readForWidgetBreakdown, readForWidgetRealtime, readForWidgetSeries, cardStyle as widgetCardStyle, labelStyle as widgetLabelStyle };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { TrackerGoal } from "../goals/types.js";
|
|
2
|
+
import { CaptureSnippet, SnippetScript } from "../core/capture.js";
|
|
3
|
+
import { ResolvedAutoCapture } from "../core/options.js";
|
|
4
|
+
import { TrackerConfig, TrackerSlotConfig } from "../capture/trackerConfig.js";
|
|
5
|
+
import { ConsentState, LoadScript, Sink, Tracker, TrackerEvent, TrackerOptions, TrackerWindow } from "../tracker/types.js";
|
|
6
|
+
import { AutoCapture, AutoCaptureHandlers, DOWNLOAD_EVENT, GOAL_ATTRIBUTE, OUTBOUND_EVENT, SCROLL_EVENT, createAutoCapture } from "../tracker/autoCapture.js";
|
|
7
|
+
import { CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, createConsentQueue, readConsent, writeConsent } from "../tracker/consent.js";
|
|
8
|
+
import { createNoopTracker, createTracker } from "../tracker/createTracker.js";
|
|
9
|
+
import { DEFAULT_TRACKER_ENDPOINT, InitTrackerArgs, initTracker } from "../tracker/initTracker.js";
|
|
10
|
+
import { createScriptLoader } from "../tracker/loadScript.js";
|
|
11
|
+
import { PageTracking, createPageTracking } from "../tracker/pageTracking.js";
|
|
12
|
+
import { TrackerLease, acquireTracker } from "../tracker/registry.js";
|
|
13
|
+
import { PAGEVIEW_BUFFER_MS, createNativeSink } from "../tracker/sinks/native.js";
|
|
14
|
+
import { VendorSinkArgs } from "../tracker/sinks/vendor.js";
|
|
15
|
+
import { createPlausibleSink } from "../tracker/sinks/plausible.js";
|
|
16
|
+
import { createPosthogSink } from "../tracker/sinks/posthog.js";
|
|
17
|
+
import { createUmamiSink } from "../tracker/sinks/umami.js";
|
|
18
|
+
export { type AutoCapture, type AutoCaptureHandlers, CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, type CaptureSnippet, type ConsentState, DEFAULT_TRACKER_ENDPOINT, DOWNLOAD_EVENT, GOAL_ATTRIBUTE, type InitTrackerArgs, type LoadScript, OUTBOUND_EVENT, PAGEVIEW_BUFFER_MS, type PageTracking, type ResolvedAutoCapture, SCROLL_EVENT, type Sink, type SnippetScript, type Tracker, type TrackerConfig, type TrackerEvent, type TrackerGoal, type TrackerLease, type TrackerOptions, type TrackerSlotConfig, type TrackerWindow, type VendorSinkArgs, acquireTracker, createAutoCapture, createConsentQueue, createNativeSink, createNoopTracker, createPageTracking, createPlausibleSink, createPosthogSink, createScriptLoader, createTracker, createUmamiSink, initTracker, readConsent, writeConsent };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { DOWNLOAD_EVENT, GOAL_ATTRIBUTE, OUTBOUND_EVENT, SCROLL_EVENT, createAutoCapture } from "../tracker/autoCapture.js";
|
|
2
|
+
import { CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, createConsentQueue, readConsent, writeConsent } from "../tracker/consent.js";
|
|
3
|
+
import { createScriptLoader } from "../tracker/loadScript.js";
|
|
4
|
+
import { createPageTracking } from "../tracker/pageTracking.js";
|
|
5
|
+
import { PAGEVIEW_BUFFER_MS, createNativeSink } from "../tracker/sinks/native.js";
|
|
6
|
+
import { createPlausibleSink } from "../tracker/sinks/plausible.js";
|
|
7
|
+
import { createPosthogSink } from "../tracker/sinks/posthog.js";
|
|
8
|
+
import { createUmamiSink } from "../tracker/sinks/umami.js";
|
|
9
|
+
import { createNoopTracker, createTracker } from "../tracker/createTracker.js";
|
|
10
|
+
import { acquireTracker } from "../tracker/registry.js";
|
|
11
|
+
import { DEFAULT_TRACKER_ENDPOINT, initTracker } from "../tracker/initTracker.js";
|
|
12
|
+
export { CONSENT_QUEUE_LIMIT, CONSENT_STORAGE_KEY, DEFAULT_TRACKER_ENDPOINT, DOWNLOAD_EVENT, GOAL_ATTRIBUTE, OUTBOUND_EVENT, PAGEVIEW_BUFFER_MS, SCROLL_EVENT, acquireTracker, createAutoCapture, createConsentQueue, createNativeSink, createNoopTracker, createPageTracking, createPlausibleSink, createPosthogSink, createScriptLoader, createTracker, createUmamiSink, initTracker, readConsent, writeConsent };
|
package/dist/exports/types.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Goal, GoalMatch, TrackerGoal } from "../goals/types.js";
|
|
2
|
+
import { CaptureClientKind, CaptureSnippet, CaptureSupport, ProxyDescriptor, ProxyRoute, SnippetScript } from "../core/capture.js";
|
|
3
|
+
import { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, AnalyticsCapabilities, AnalyticsFilter, AnalyticsQuery, AnalyticsResult, AnalyticsRow, DateRange, DimensionKey, FilterOperator, Granularity, MetricKey, PLATFORM_SCOPE, RateLimitDescriptor } from "../core/contract.js";
|
|
2
4
|
import { SerializedCapabilities } from "../core/capabilities.js";
|
|
3
5
|
import { AnalyticsBinding, BindingContext, HostnameResolver, PathResolver } from "../binding/types.js";
|
|
6
|
+
import { AnalyticsPluginOptions, ResolvedAutoCapture } from "../core/options.js";
|
|
7
|
+
import { TrackerConfig, TrackerSlotConfig } from "../capture/trackerConfig.js";
|
|
4
8
|
import { TimeframePreset } from "../timeframe/presets.js";
|
|
5
9
|
import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions } from "../fields/factories.js";
|
|
6
|
-
|
|
7
|
-
export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, DateRange, DimensionKey, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, RateLimitDescriptor, type SerializedCapabilities, type TimeframePreset };
|
|
10
|
+
export { AdapterContext, AdapterRegisterContext, AnalyticsAdapter, AnalyticsAdapterFactory, type AnalyticsBinding, AnalyticsCapabilities, type AnalyticsFieldsOptions, AnalyticsFilter, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, AnalyticsQuery, AnalyticsResult, AnalyticsRow, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, CaptureClientKind, CaptureSnippet, CaptureSupport, DateRange, DimensionKey, FilterOperator, type Goal, type GoalMatch, Granularity, type HostnameResolver, MetricKey, PLATFORM_SCOPE, type PathResolver, ProxyDescriptor, ProxyRoute, RateLimitDescriptor, type ResolvedAutoCapture, type SerializedCapabilities, SnippetScript, type TimeframePreset, type TrackerConfig, type TrackerGoal, type TrackerSlotConfig };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { DOCUMENT_PATH } from "../plugin/paths.js";
|
|
2
3
|
import { keys } from "../translations/keys.js";
|
|
3
4
|
import { TIMEFRAME_PRESETS } from "../timeframe/presets.js";
|
|
4
5
|
import { METRIC_KEYS, TIMEFRAME_KEYS } from "../translations/metricKeys.js";
|
|
5
|
-
import { DOCUMENT_PATH } from "../plugin/paths.js";
|
|
6
6
|
import { TrendChart } from "../charts/TrendChart.js";
|
|
7
7
|
import { useTranslation as useTranslation$1 } from "../translations/useTranslation.js";
|
|
8
8
|
import { AnalyticsEmptyState, isNewDocumentAnalytics } from "./emptyState.js";
|
|
@@ -5,6 +5,8 @@ const satisfiesSerialized = (caps, req) => {
|
|
|
5
5
|
if (req.perPageQuery && !caps.perPageQuery) return false;
|
|
6
6
|
if (req.metrics?.some((m) => !caps.metrics.includes(m))) return false;
|
|
7
7
|
if (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false;
|
|
8
|
+
if (req.filters?.some((d) => !caps.filters.includes(d))) return false;
|
|
9
|
+
if (req.filterOperators?.some((op) => !caps.filterOperators.includes(op))) return false;
|
|
8
10
|
return true;
|
|
9
11
|
};
|
|
10
12
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"narrow.js","names":[],"sources":["../../../src/fields/config/narrow.ts"],"sourcesContent":["import type { CapabilityRequirement, SerializedCapabilities } from '../../core/capabilities'\nimport type { WireSource } from './fetchSources'\n\nexport interface SelectOption {\n\tvalue: string\n\tlabel: unknown\n}\n\n/** satisfiesCapabilities over the wire form (arrays instead of Sets). */\nexport const satisfiesSerialized = (\n\tcaps: SerializedCapabilities,\n\treq: CapabilityRequirement\n): boolean => {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.includes(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false\n\treturn true\n}\n\n/**\n * Options for the metric picker, narrowed to what the selected source can\n * serve. An unknown source id (a stale value, a source the endpoint could not\n * list) keeps the full static list, mirroring the server-side filterOptions\n * fallback, and a source that cannot meet the widget's extra requirements at\n * all falls back to the full list rather than an empty picker.\n */\nexport const narrowMetricOptions = (args: {\n\toptions: SelectOption[]\n\tsources: WireSource[]\n\tsourceId: string | undefined\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n}): SelectOption[] => {\n\tconst src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : undefined\n\tif (!src) return args.options\n\tif (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) {\n\t\treturn args.options\n\t}\n\tconst narrowed = args.options.filter((o) =>\n\t\tsatisfiesSerialized(src.capabilities, { ...args.requires, metrics: [o.value as never] })\n\t)\n\treturn narrowed.length > 0 ? narrowed : args.options\n}\n"],"mappings":";;AASA,MAAa,uBACZ,MACA,QACa;CACb,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,SAAS,CAAC,CAAC,GAAG,OAAO;CACtE,OAAO;AACR;;;;;;;;AASA,MAAa,uBAAuB,SAKd;CACrB,MAAM,MAAM,KAAK,WAAW,KAAK,QAAQ,MAAM,MAAM,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAA;CAC/E,IAAI,CAAC,KAAK,OAAO,KAAK;CACtB,IAAI,KAAK,YAAY,CAAC,oBAAoB,IAAI,cAAc,KAAK,QAAQ,GACxE,OAAO,KAAK;CAEb,MAAM,WAAW,KAAK,QAAQ,QAAQ,MACrC,oBAAoB,IAAI,cAAc;EAAE,GAAG,KAAK;EAAU,SAAS,CAAC,EAAE,KAAc;CAAE,CAAC,CACxF;CACA,OAAO,SAAS,SAAS,IAAI,WAAW,KAAK;AAC9C"}
|
|
1
|
+
{"version":3,"file":"narrow.js","names":[],"sources":["../../../src/fields/config/narrow.ts"],"sourcesContent":["import type { CapabilityRequirement, SerializedCapabilities } from '../../core/capabilities'\nimport type { WireSource } from './fetchSources'\n\nexport interface SelectOption {\n\tvalue: string\n\tlabel: unknown\n}\n\n/** satisfiesCapabilities over the wire form (arrays instead of Sets). */\nexport const satisfiesSerialized = (\n\tcaps: SerializedCapabilities,\n\treq: CapabilityRequirement\n): boolean => {\n\tif (req.realtime && !caps.realtime) return false\n\tif (req.perPageQuery && !caps.perPageQuery) return false\n\tif (req.metrics?.some((m) => !caps.metrics.includes(m))) return false\n\tif (req.dimensions?.some((d) => !caps.dimensions.includes(d))) return false\n\tif (req.filters?.some((d) => !caps.filters.includes(d))) return false\n\tif (req.filterOperators?.some((op) => !caps.filterOperators.includes(op))) return false\n\treturn true\n}\n\n/**\n * Options for the metric picker, narrowed to what the selected source can\n * serve. An unknown source id (a stale value, a source the endpoint could not\n * list) keeps the full static list, mirroring the server-side filterOptions\n * fallback, and a source that cannot meet the widget's extra requirements at\n * all falls back to the full list rather than an empty picker.\n */\nexport const narrowMetricOptions = (args: {\n\toptions: SelectOption[]\n\tsources: WireSource[]\n\tsourceId: string | undefined\n\trequires?: Omit<CapabilityRequirement, 'metrics'>\n}): SelectOption[] => {\n\tconst src = args.sourceId ? args.sources.find((s) => s.id === args.sourceId) : undefined\n\tif (!src) return args.options\n\tif (args.requires && !satisfiesSerialized(src.capabilities, args.requires)) {\n\t\treturn args.options\n\t}\n\tconst narrowed = args.options.filter((o) =>\n\t\tsatisfiesSerialized(src.capabilities, { ...args.requires, metrics: [o.value as never] })\n\t)\n\treturn narrowed.length > 0 ? narrowed : args.options\n}\n"],"mappings":";;AASA,MAAa,uBACZ,MACA,QACa;CACb,IAAI,IAAI,YAAY,CAAC,KAAK,UAAU,OAAO;CAC3C,IAAI,IAAI,gBAAgB,CAAC,KAAK,cAAc,OAAO;CACnD,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,YAAY,MAAM,MAAM,CAAC,KAAK,WAAW,SAAS,CAAC,CAAC,GAAG,OAAO;CACtE,IAAI,IAAI,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,SAAS,CAAC,CAAC,GAAG,OAAO;CAChE,IAAI,IAAI,iBAAiB,MAAM,OAAO,CAAC,KAAK,gBAAgB,SAAS,EAAE,CAAC,GAAG,OAAO;CAClF,OAAO;AACR;;;;;;;;AASA,MAAa,uBAAuB,SAKd;CACrB,MAAM,MAAM,KAAK,WAAW,KAAK,QAAQ,MAAM,MAAM,EAAE,OAAO,KAAK,QAAQ,IAAI,KAAA;CAC/E,IAAI,CAAC,KAAK,OAAO,KAAK;CACtB,IAAI,KAAK,YAAY,CAAC,oBAAoB,IAAI,cAAc,KAAK,QAAQ,GACxE,OAAO,KAAK;CAEb,MAAM,WAAW,KAAK,QAAQ,QAAQ,MACrC,oBAAoB,IAAI,cAAc;EAAE,GAAG,KAAK;EAAU,SAAS,CAAC,EAAE,KAAc;CAAE,CAAC,CACxF;CACA,OAAO,SAAS,SAAS,IAAI,WAAW,KAAK;AAC9C"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
|
|
1
2
|
import { resolveHostname, resolvePathCached } from "../binding/resolvePath.js";
|
|
2
3
|
import { satisfiesCapabilities } from "../core/capabilities.js";
|
|
3
4
|
import { supportsGranularity } from "../core/granularity.js";
|
|
4
|
-
import { getRuntime, resolveTimezoneFor } from "../plugin/runtime.js";
|
|
5
5
|
import { resolveReadContext } from "../core/scopedRead.js";
|
|
6
6
|
import { resolveTimeframe } from "../timeframe/presets.js";
|
|
7
7
|
import { previousWindow } from "../widgets/comparison.js";
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
//#region src/goals/match.ts
|
|
2
|
+
const trimTrailingSlash = (path) => path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
|
|
3
|
+
/** Query and hash are not part of the path a pattern is matched against. */
|
|
4
|
+
const pathOnly = (path) => {
|
|
5
|
+
const cut = path.search(/[?#]/);
|
|
6
|
+
return trimTrailingSlash(cut === -1 ? path : path.slice(0, cut));
|
|
7
|
+
};
|
|
8
|
+
/** Every regex metacharacter except `*`, the one glob token this translates itself. */
|
|
9
|
+
const ESCAPE = /[.+?^${}()|[\]\\]/g;
|
|
10
|
+
/**
|
|
11
|
+
* Anchored, case-sensitive glob: `*` is exactly one non-empty path segment and `**` is one
|
|
12
|
+
* or more segments at any depth, so `/docs/**` covers everything below `/docs` but not
|
|
13
|
+
* `/docs` itself. A trailing slash is insignificant on both sides, and a pattern pasted
|
|
14
|
+
* from a URL gets the same query/hash cut as the path it is matched against.
|
|
15
|
+
*/
|
|
16
|
+
const patternToRegExp = (pattern) => {
|
|
17
|
+
const body = pathOnly(pattern).replace(ESCAPE, "\\$&").split("**").map((part) => part.replace(/\*/g, "[^/]+")).join(".+");
|
|
18
|
+
return new RegExp(`^${body}$`);
|
|
19
|
+
};
|
|
20
|
+
const cache = /* @__PURE__ */ new Map();
|
|
21
|
+
const matchesPath = (pattern, path) => {
|
|
22
|
+
let re = cache.get(pattern);
|
|
23
|
+
if (!re) {
|
|
24
|
+
re = patternToRegExp(pattern);
|
|
25
|
+
cache.set(pattern, re);
|
|
26
|
+
}
|
|
27
|
+
return re.test(pathOnly(path));
|
|
28
|
+
};
|
|
29
|
+
/** Revenue is money: a source only counts when it is a finite, non-negative number. */
|
|
30
|
+
const amount = (value) => {
|
|
31
|
+
const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
|
|
32
|
+
return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : void 0;
|
|
33
|
+
};
|
|
34
|
+
const completionValue = (event, goal) => {
|
|
35
|
+
const fromEvent = amount(event.value);
|
|
36
|
+
if (fromEvent !== void 0) return fromEvent;
|
|
37
|
+
const fixed = amount(goal.value?.fixed);
|
|
38
|
+
if (fixed !== void 0) return fixed;
|
|
39
|
+
const prop = goal.value?.prop;
|
|
40
|
+
return (prop ? amount(event.props?.[prop]) : void 0) ?? 0;
|
|
41
|
+
};
|
|
42
|
+
const completes = (event, goal) => {
|
|
43
|
+
switch (goal.match.kind) {
|
|
44
|
+
case "goal": return event.type === "goal" && event.name === goal.slug;
|
|
45
|
+
case "event": return event.type === "event" && event.name === goal.match.name;
|
|
46
|
+
case "path": return event.type === "pageview" && matchesPath(goal.match.pattern, event.path);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Every goal the event completes, in config order. Pure: the same event and goals always
|
|
51
|
+
* produce the same completions, which is what lets a read re-derive them from a stored event.
|
|
52
|
+
*/
|
|
53
|
+
const matchGoals = (event, goals) => {
|
|
54
|
+
const out = [];
|
|
55
|
+
for (const goal of goals) if (completes(event, goal)) out.push({
|
|
56
|
+
slug: goal.slug,
|
|
57
|
+
value: completionValue(event, goal)
|
|
58
|
+
});
|
|
59
|
+
return out;
|
|
60
|
+
};
|
|
61
|
+
//#endregion
|
|
62
|
+
export { matchGoals };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=match.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"match.js","names":[],"sources":["../../src/goals/match.ts"],"sourcesContent":["import type { Goal } from './types'\n\n/** The event fields goal matching reads. Satisfied by both the wire payload and StoredEvent. */\nexport interface MatchableEvent {\n\ttype: string\n\tname?: string\n\tpath: string\n\tprops?: Record<string, unknown>\n\tvalue?: number\n}\n\n/** One goal completion: the goal's slug and the revenue this completion is worth. */\nexport interface GoalCompletion {\n\tslug: string\n\tvalue: number\n}\n\nconst trimTrailingSlash = (path: string): string =>\n\tpath.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path\n\n/** Query and hash are not part of the path a pattern is matched against. */\nconst pathOnly = (path: string): string => {\n\tconst cut = path.search(/[?#]/)\n\treturn trimTrailingSlash(cut === -1 ? path : path.slice(0, cut))\n}\n\n/** Every regex metacharacter except `*`, the one glob token this translates itself. */\nconst ESCAPE = /[.+?^${}()|[\\]\\\\]/g\n\n/**\n * Anchored, case-sensitive glob: `*` is exactly one non-empty path segment and `**` is one\n * or more segments at any depth, so `/docs/**` covers everything below `/docs` but not\n * `/docs` itself. A trailing slash is insignificant on both sides, and a pattern pasted\n * from a URL gets the same query/hash cut as the path it is matched against.\n */\nconst patternToRegExp = (pattern: string): RegExp => {\n\tconst body = pathOnly(pattern)\n\t\t.replace(ESCAPE, '\\\\$&')\n\t\t.split('**')\n\t\t.map((part) => part.replace(/\\*/g, '[^/]+'))\n\t\t.join('.+')\n\treturn new RegExp(`^${body}$`)\n}\n\nconst cache = new Map<string, RegExp>()\n\nconst matchesPath = (pattern: string, path: string): boolean => {\n\tlet re = cache.get(pattern)\n\tif (!re) {\n\t\tre = patternToRegExp(pattern)\n\t\tcache.set(pattern, re)\n\t}\n\treturn re.test(pathOnly(path))\n}\n\n/** Revenue is money: a source only counts when it is a finite, non-negative number. */\nconst amount = (value: unknown): number | undefined => {\n\tconst n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value\n\treturn typeof n === 'number' && Number.isFinite(n) && n >= 0 ? n : undefined\n}\n\nconst completionValue = (event: MatchableEvent, goal: Goal): number => {\n\tconst fromEvent = amount(event.value)\n\tif (fromEvent !== undefined) {\n\t\treturn fromEvent\n\t}\n\tconst fixed = amount(goal.value?.fixed)\n\tif (fixed !== undefined) {\n\t\treturn fixed\n\t}\n\tconst prop = goal.value?.prop\n\treturn (prop ? amount(event.props?.[prop]) : undefined) ?? 0\n}\n\nconst completes = (event: MatchableEvent, goal: Goal): boolean => {\n\tswitch (goal.match.kind) {\n\t\tcase 'goal':\n\t\t\treturn event.type === 'goal' && event.name === goal.slug\n\t\tcase 'event':\n\t\t\treturn event.type === 'event' && event.name === goal.match.name\n\t\tcase 'path':\n\t\t\treturn event.type === 'pageview' && matchesPath(goal.match.pattern, event.path)\n\t}\n}\n\n/**\n * Every goal the event completes, in config order. Pure: the same event and goals always\n * produce the same completions, which is what lets a read re-derive them from a stored event.\n */\nexport const matchGoals = (event: MatchableEvent, goals: Goal[]): GoalCompletion[] => {\n\tconst out: GoalCompletion[] = []\n\tfor (const goal of goals) {\n\t\tif (completes(event, goal)) {\n\t\t\tout.push({ slug: goal.slug, value: completionValue(event, goal) })\n\t\t}\n\t}\n\treturn out\n}\n"],"mappings":";AAiBA,MAAM,qBAAqB,SAC1B,KAAK,SAAS,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;;AAG7D,MAAM,YAAY,SAAyB;CAC1C,MAAM,MAAM,KAAK,OAAO,MAAM;CAC9B,OAAO,kBAAkB,QAAQ,KAAK,OAAO,KAAK,MAAM,GAAG,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S,MAAM,IAAI;CAChF;AACD;;;;;AAMA,MAAa,cAAc,OAAuB,UAAoC;CACrF,MAAM,MAAwB,CAAC;CAC/B,KAAK,MAAM,QAAQ,OAClB,IAAI,UAAU,OAAO,IAAI,GACxB,IAAI,KAAK;EAAE,MAAM,KAAK;EAAM,OAAO,gBAAgB,OAAO,IAAI;CAAE,CAAC;CAGnE,OAAO;AACR"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
//#region src/goals/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* How an incoming event is recognized as a completion of this goal. `goal` matches an
|
|
4
|
+
* explicit `trackGoal(slug)` call, which is what the attribute and action hookups emit.
|
|
5
|
+
*/
|
|
6
|
+
type GoalMatch = {
|
|
7
|
+
kind: 'event';
|
|
8
|
+
name: string;
|
|
9
|
+
} | {
|
|
10
|
+
kind: 'path';
|
|
11
|
+
pattern: string;
|
|
12
|
+
} | {
|
|
13
|
+
kind: 'goal';
|
|
14
|
+
};
|
|
15
|
+
interface Goal {
|
|
16
|
+
/** Stable identifier, kebab-case; unique across the install's goals. */
|
|
17
|
+
slug: string;
|
|
18
|
+
/** Admin-facing label. Never leaves the server: the tracker config carries slugs only. */
|
|
19
|
+
name: string;
|
|
20
|
+
match: GoalMatch;
|
|
21
|
+
/** Revenue for one completion: a fixed amount, or read from an event property. */
|
|
22
|
+
value?: {
|
|
23
|
+
fixed?: number;
|
|
24
|
+
prop?: string;
|
|
25
|
+
};
|
|
26
|
+
/** ISO 4217 code the goal's value is denominated in. */
|
|
27
|
+
currency?: string;
|
|
28
|
+
}
|
|
29
|
+
/** The goal fields the browser tracker needs; `name` is admin-facing only. */
|
|
30
|
+
type TrackerGoal = Pick<Goal, 'slug' | 'match' | 'value' | 'currency'>;
|
|
31
|
+
//#endregion
|
|
32
|
+
export { Goal, GoalMatch, TrackerGoal };
|
|
33
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../src/goals/types.ts"],"sourcesContent":["/**\n * How an incoming event is recognized as a completion of this goal. `goal` matches an\n * explicit `trackGoal(slug)` call, which is what the attribute and action hookups emit.\n */\nexport type GoalMatch =\n\t| { kind: 'event'; name: string }\n\t| { kind: 'path'; pattern: string }\n\t| { kind: 'goal' }\n\nexport interface Goal {\n\t/** Stable identifier, kebab-case; unique across the install's goals. */\n\tslug: string\n\t/** Admin-facing label. Never leaves the server: the tracker config carries slugs only. */\n\tname: string\n\tmatch: GoalMatch\n\t/** Revenue for one completion: a fixed amount, or read from an event property. */\n\tvalue?: { fixed?: number; prop?: string }\n\t/** ISO 4217 code the goal's value is denominated in. */\n\tcurrency?: string\n}\n\n/** The goal fields the browser tracker needs; `name` is admin-facing only. */\nexport type TrackerGoal = Pick<Goal, 'slug' | 'match' | 'value' | 'currency'>\n\n/** Kebab-case, so a slug is safe in a URL, a data attribute, and a rollup bucket key. */\nexport const GOAL_SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\n"],"mappings":";;AAyBA,MAAa,oBAAoB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
+
import { Goal, GoalMatch, TrackerGoal } from "./goals/types.js";
|
|
1
2
|
import { PLATFORM_SCOPE } from "./core/contract.js";
|
|
2
3
|
import { AnalyticsBinding, BindingContext, HostnameResolver, PathResolver } from "./binding/types.js";
|
|
4
|
+
import { CustomWidgetDef } from "./widgets/customWidget.js";
|
|
5
|
+
import { AnalyticsAccessOptions, AnalyticsCaptureOptions, AnalyticsGoalsOptions, AnalyticsPluginOptions, AutoCaptureOptions, CaptureConsentOption, ConsentMode, ConsentResolver, PlatformReadAccess, ProvidersCollectionOptions, ProvidersOptions, ProvidersResolve, ScopeResolver, ScopesResolver, TimezoneResolver } from "./core/options.js";
|
|
3
6
|
import { TimeframePreset } from "./timeframe/presets.js";
|
|
4
7
|
import { AnalyticsFieldsOptions, AnalyticsMetricLabel, AnalyticsMetricLabels, AnalyticsStatOptions, AnalyticsStatRowOptions, AnalyticsTabOptions, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField } from "./fields/factories.js";
|
|
5
|
-
import { CustomWidgetDef } from "./widgets/customWidget.js";
|
|
6
|
-
import { AnalyticsAccessOptions, AnalyticsPluginOptions, PlatformReadAccess, ProvidersCollectionOptions, ProvidersOptions, ProvidersResolve, ScopeResolver, TimezoneResolver } from "./core/options.js";
|
|
7
8
|
import { analyticsDefaultWidgets } from "./widgets/defaults.js";
|
|
8
9
|
|
|
9
10
|
//#region src/index.d.ts
|
|
@@ -14,5 +15,5 @@ declare module 'payload' {
|
|
|
14
15
|
}
|
|
15
16
|
declare const analytics: (options: AnalyticsPluginOptions) => import("payload").Plugin;
|
|
16
17
|
//#endregion
|
|
17
|
-
export { type AnalyticsAccessOptions, type AnalyticsBinding, type AnalyticsFieldsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type BindingContext, type CustomWidgetDef, type HostnameResolver, PLATFORM_SCOPE, type PathResolver, type PlatformReadAccess, type AnalyticsPluginOptions as PluginOptions, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type ScopeResolver, type TimeframePreset, type TimezoneResolver, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField };
|
|
18
|
+
export { type AnalyticsAccessOptions, type AnalyticsBinding, type AnalyticsCaptureOptions, type AnalyticsFieldsOptions, type AnalyticsGoalsOptions, type AnalyticsMetricLabel, type AnalyticsMetricLabels, type AnalyticsPluginOptions, type AnalyticsStatOptions, type AnalyticsStatRowOptions, type AnalyticsTabOptions, type AutoCaptureOptions, type BindingContext, type CaptureConsentOption, type ConsentMode, type ConsentResolver, type CustomWidgetDef, type Goal, type GoalMatch, type HostnameResolver, PLATFORM_SCOPE, type PathResolver, type PlatformReadAccess, type AnalyticsPluginOptions as PluginOptions, type ProvidersCollectionOptions, type ProvidersOptions, type ProvidersResolve, type ScopeResolver, type ScopesResolver, type TimeframePreset, type TimezoneResolver, type TrackerGoal, analytics, analyticsDefaultWidgets, analyticsFields, analyticsStat, analyticsStatRow, analyticsTab, analyticsTabsField };
|
|
18
19
|
//# sourceMappingURL=index.d.ts.map
|