@10x-media/analytics 0.1.0-beta.5 → 1.0.0-beta.11
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 +277 -0
- package/README.md +15 -4
- package/dist/adapters/ga4/disableKey.d.ts +9 -0
- package/dist/adapters/ga4/disableKey.js +21 -0
- package/dist/adapters/ga4/disableKey.js.map +1 -0
- package/dist/adapters/ga4/eventName.d.ts +15 -0
- package/dist/adapters/ga4/eventName.js +19 -0
- package/dist/adapters/ga4/eventName.js.map +1 -0
- package/dist/adapters/ga4/ga4.d.ts +5 -0
- package/dist/adapters/ga4/ga4.js +186 -58
- package/dist/adapters/ga4/ga4.js.map +1 -1
- package/dist/adapters/ga4/measurementId.js +15 -0
- package/dist/adapters/ga4/measurementId.js.map +1 -0
- package/dist/adapters/goalRead.js +126 -0
- package/dist/adapters/goalRead.js.map +1 -0
- package/dist/adapters/http/fetchJson.js +1 -1
- package/dist/adapters/plausible/plausible.d.ts +25 -0
- package/dist/adapters/plausible/plausible.js +159 -38
- package/dist/adapters/plausible/plausible.js.map +1 -1
- package/dist/adapters/posthog/posthog.d.ts +10 -1
- package/dist/adapters/posthog/posthog.js +130 -21
- 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 +13 -1
- package/dist/adapters/umami/umami.js +278 -26
- package/dist/adapters/umami/umami.js.map +1 -1
- package/dist/binding/resolvePath.js +18 -2
- package/dist/binding/resolvePath.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 +127 -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 +54 -0
- package/dist/capture/slots.js.map +1 -0
- package/dist/capture/trackerConfig.d.ts +33 -0
- package/dist/capture/trackerConfig.js +95 -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/charts/BarList.d.ts +16 -1
- package/dist/charts/BarList.js +41 -19
- package/dist/charts/BarList.js.map +1 -1
- package/dist/charts/TrendChart.d.ts +16 -3
- package/dist/charts/TrendChart.js +172 -106
- package/dist/charts/TrendChart.js.map +1 -1
- package/dist/charts/bars.d.ts +4 -0
- package/dist/charts/bars.js +3 -1
- package/dist/charts/bars.js.map +1 -1
- package/dist/charts/bucket.js +10 -1
- package/dist/charts/bucket.js.map +1 -1
- package/dist/charts/spline.js +2 -2
- package/dist/charts/spline.js.map +1 -1
- package/dist/charts/styles.js +18 -1
- package/dist/charts/styles.js.map +1 -1
- package/dist/core/cacheKey.js +26 -3
- package/dist/core/cacheKey.js.map +1 -1
- package/dist/core/capabilities.d.ts +5 -1
- package/dist/core/capabilities.js +11 -2
- package/dist/core/capabilities.js.map +1 -1
- package/dist/core/capture.d.ts +49 -0
- package/dist/core/contract.d.ts +74 -5
- package/dist/core/contract.js +30 -1
- package/dist/core/contract.js.map +1 -1
- package/dist/core/granularity.js +1 -1
- package/dist/core/options.d.ts +164 -6
- package/dist/core/options.js +126 -3
- 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 +101 -30
- package/dist/core/scopedRead.js.map +1 -1
- package/dist/core/serverEvent.d.ts +60 -0
- package/dist/core/serverEvent.js +12 -0
- package/dist/core/serverEvent.js.map +1 -0
- package/dist/exports/adapters/ga4.d.ts +2 -1
- package/dist/exports/adapters/ga4.js +2 -1
- package/dist/exports/adapters/native.d.ts +3 -1
- package/dist/exports/adapters/native.js +2 -1
- package/dist/exports/client.d.ts +13 -3
- package/dist/exports/client.js +10 -1
- package/dist/exports/geo.d.ts +2 -2
- 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 +11 -3
- package/dist/exports/rsc.js +7 -2
- package/dist/exports/tracker.d.ts +21 -0
- package/dist/exports/tracker.js +15 -0
- package/dist/exports/types.d.ts +16 -3
- package/dist/exports/types.js +4 -2
- package/dist/fields/AnalyticsPanelClient.js +2 -2
- package/dist/fields/AnalyticsPanelField.js +1 -1
- package/dist/fields/AnalyticsStatField.js +2 -2
- package/dist/fields/config/FilterDimensionSelectField.d.ts +14 -0
- package/dist/fields/config/FilterDimensionSelectField.js +77 -0
- package/dist/fields/config/FilterDimensionSelectField.js.map +1 -0
- package/dist/fields/config/FilterOperatorSelectField.d.ts +14 -0
- package/dist/fields/config/FilterOperatorSelectField.js +75 -0
- package/dist/fields/config/FilterOperatorSelectField.js.map +1 -0
- package/dist/fields/config/MetricSelectField.js +3 -3
- package/dist/fields/config/MetricSelectField.js.map +1 -1
- package/dist/fields/config/SourceSelectField.js +3 -3
- package/dist/fields/config/SourceSelectField.js.map +1 -1
- package/dist/fields/config/fetchSources.d.ts +5 -1
- package/dist/fields/config/fetchSources.js +7 -3
- package/dist/fields/config/fetchSources.js.map +1 -1
- package/dist/fields/config/narrow.js +2 -0
- package/dist/fields/config/narrow.js.map +1 -1
- package/dist/fields/config/sourcesState.js +19 -3
- package/dist/fields/config/sourcesState.js.map +1 -1
- package/dist/fields/config/useAnalyticsSources.d.ts +8 -3
- package/dist/fields/config/useAnalyticsSources.js +9 -6
- package/dist/fields/config/useAnalyticsSources.js.map +1 -1
- package/dist/fields/config/useFilterCapabilities.d.ts +28 -0
- package/dist/fields/config/useFilterCapabilities.js +52 -0
- package/dist/fields/config/useFilterCapabilities.js.map +1 -0
- package/dist/fields/readForDocument.d.ts +5 -0
- package/dist/fields/readForDocument.js +22 -10
- package/dist/fields/readForDocument.js.map +1 -1
- package/dist/goals/GoalSelectField.d.ts +7 -0
- package/dist/goals/GoalSelectField.js +77 -0
- package/dist/goals/GoalSelectField.js.map +1 -0
- package/dist/goals/collection.js +254 -0
- package/dist/goals/collection.js.map +1 -0
- package/dist/goals/currency.js +14 -0
- package/dist/goals/currency.js.map +1 -0
- package/dist/goals/fetchGoals.d.ts +18 -0
- package/dist/goals/fetchGoals.js +33 -0
- package/dist/goals/fetchGoals.js.map +1 -0
- package/dist/goals/goalField.d.ts +31 -0
- package/dist/goals/goalField.js +56 -0
- package/dist/goals/goalField.js.map +1 -0
- package/dist/goals/goalsEndpoint.d.ts +1 -0
- package/dist/goals/goalsEndpoint.js +58 -0
- package/dist/goals/goalsEndpoint.js.map +1 -0
- package/dist/goals/match.js +64 -0
- package/dist/goals/match.js.map +1 -0
- package/dist/goals/resolver.d.ts +8 -0
- package/dist/goals/resolver.js +147 -0
- package/dist/goals/resolver.js.map +1 -0
- package/dist/goals/trackGoalAction.d.ts +76 -0
- package/dist/goals/trackGoalAction.js +158 -0
- package/dist/goals/trackGoalAction.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/goals/useAnalyticsGoals.d.ts +20 -0
- package/dist/goals/useAnalyticsGoals.js +67 -0
- package/dist/goals/useAnalyticsGoals.js.map +1 -0
- package/dist/index.d.ts +14 -3
- package/dist/index.js +174 -19
- package/dist/index.js.map +1 -1
- package/dist/native/collections/events.js +65 -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/eventScan.js +25 -0
- package/dist/native/eventScan.js.map +1 -0
- package/dist/native/geo/composeGeoResolvers.js +2 -2
- package/dist/native/geo/composeGeoResolvers.js.map +1 -1
- package/dist/native/geo/geoResolver.d.ts +9 -2
- package/dist/native/geo/geoResolver.js.map +1 -1
- package/dist/native/geo/maxmindResolver.js +3 -5
- package/dist/native/geo/maxmindResolver.js.map +1 -1
- package/dist/native/ingest/bots.d.ts +11 -0
- package/dist/native/ingest/bots.js +71 -0
- package/dist/native/ingest/bots.js.map +1 -0
- package/dist/native/ingest/browser.js +47 -0
- package/dist/native/ingest/browser.js.map +1 -0
- package/dist/native/ingest/clientIp.js +20 -0
- package/dist/native/ingest/clientIp.js.map +1 -0
- package/dist/native/ingest/device.js +11 -3
- package/dist/native/ingest/device.js.map +1 -1
- package/dist/native/ingest/endpoint.d.ts +1 -0
- package/dist/native/ingest/endpoint.js +107 -21
- package/dist/native/ingest/endpoint.js.map +1 -1
- package/dist/native/ingest/flushBatch.js +29 -38
- package/dist/native/ingest/flushBatch.js.map +1 -1
- package/dist/native/ingest/language.js +14 -0
- package/dist/native/ingest/language.js.map +1 -0
- package/dist/native/ingest/normalizeEvent.d.ts +30 -0
- package/dist/native/ingest/normalizeEvent.js +115 -16
- package/dist/native/ingest/normalizeEvent.js.map +1 -1
- package/dist/native/ingest/referrer.js +48 -0
- package/dist/native/ingest/referrer.js.map +1 -0
- package/dist/native/ingest/requestHost.js +57 -0
- package/dist/native/ingest/requestHost.js.map +1 -0
- package/dist/native/ingest/resolveHostname.d.ts +29 -0
- package/dist/native/ingest/resolveHostname.js +52 -0
- package/dist/native/ingest/resolveHostname.js.map +1 -0
- package/dist/native/ingest/salt.js +27 -2
- package/dist/native/ingest/salt.js.map +1 -1
- package/dist/native/ingest/serverTrack.d.ts +20 -0
- package/dist/native/ingest/serverTrack.js +109 -0
- package/dist/native/ingest/serverTrack.js.map +1 -0
- package/dist/native/ingest/source.d.ts +11 -0
- package/dist/native/ingest/source.js +264 -16
- package/dist/native/ingest/source.js.map +1 -1
- package/dist/native/ingest/utm.js +33 -0
- package/dist/native/ingest/utm.js.map +1 -0
- package/dist/native/ingest/validate.js +26 -0
- package/dist/native/ingest/validate.js.map +1 -0
- package/dist/native/nativeAdapter.d.ts +37 -1
- package/dist/native/nativeAdapter.js +175 -22
- package/dist/native/nativeAdapter.js.map +1 -1
- package/dist/native/query/eventAgg.js +175 -0
- package/dist/native/query/eventAgg.js.map +1 -0
- package/dist/native/retention/pruneTask.js +53 -13
- package/dist/native/retention/pruneTask.js.map +1 -1
- package/dist/native/rollupAcc.js +12 -1
- package/dist/native/rollupAcc.js.map +1 -1
- package/dist/native/rollups/bucketKey.js +15 -0
- package/dist/native/rollups/bucketKey.js.map +1 -0
- package/dist/native/rollups/bumpRollups.js +116 -0
- package/dist/native/rollups/bumpRollups.js.map +1 -0
- package/dist/native/rollups/deltas.js +86 -11
- package/dist/native/rollups/deltas.js.map +1 -1
- package/dist/native/rollups/insertManyIfNew.js +93 -0
- package/dist/native/rollups/insertManyIfNew.js.map +1 -0
- package/dist/next/captureRewrites.d.ts +42 -0
- package/dist/next/captureRewrites.js +57 -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 +71 -24
- package/dist/plugin/documentEndpoint.js.map +1 -1
- package/dist/plugin/errors.d.ts +31 -0
- package/dist/plugin/errors.js +79 -0
- package/dist/plugin/errors.js.map +1 -0
- package/dist/plugin/goalHint.d.ts +1 -0
- package/dist/plugin/goalHint.js +24 -0
- package/dist/plugin/goalHint.js.map +1 -0
- package/dist/plugin/paths.js +17 -1
- package/dist/plugin/paths.js.map +1 -1
- package/dist/plugin/queryEndpoint.js +124 -0
- package/dist/plugin/queryEndpoint.js.map +1 -0
- package/dist/plugin/readContextForRequest.js +73 -0
- package/dist/plugin/readContextForRequest.js.map +1 -0
- package/dist/plugin/realtimeEndpoint.js +37 -16
- package/dist/plugin/realtimeEndpoint.js.map +1 -1
- package/dist/plugin/refreshEndpoint.js +113 -0
- package/dist/plugin/refreshEndpoint.js.map +1 -0
- package/dist/plugin/runtime.d.ts +1 -0
- package/dist/plugin/runtime.js +33 -1
- package/dist/plugin/runtime.js.map +1 -1
- package/dist/plugin/scopeChange.js +22 -0
- package/dist/plugin/scopeChange.js.map +1 -0
- package/dist/plugin/scopeFieldBoot.js +22 -0
- package/dist/plugin/scopeFieldBoot.js.map +1 -0
- package/dist/plugin/sourcesEndpoint.js +16 -41
- 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 +89 -29
- package/dist/providers/collection.js.map +1 -1
- package/dist/providers/factory.js +11 -3
- package/dist/providers/factory.js.map +1 -1
- package/dist/providers/resolver.js.map +1 -1
- package/dist/query/dates.js +64 -0
- package/dist/query/dates.js.map +1 -0
- package/dist/query/errors.d.ts +14 -0
- package/dist/query/fetchQuery.d.ts +79 -0
- package/dist/query/fetchQuery.js +117 -0
- package/dist/query/fetchQuery.js.map +1 -0
- package/dist/query/parse.d.ts +22 -0
- package/dist/query/parse.js +168 -0
- package/dist/query/parse.js.map +1 -0
- package/dist/query/response.d.ts +39 -0
- package/dist/query/response.js +11 -0
- package/dist/query/response.js.map +1 -0
- package/dist/react/AnalyticsProvider.d.ts +50 -0
- package/dist/react/AnalyticsProvider.js +67 -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 +20 -0
- package/dist/react/useAnalytics.js +52 -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 +47 -6
- package/dist/surfacing/engine.js.map +1 -1
- package/dist/surfacing/epoch.d.ts +1 -0
- package/dist/surfacing/epoch.js +72 -0
- package/dist/surfacing/epoch.js.map +1 -0
- 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 -1
- package/dist/testing/memoryAdapter.js.map +1 -1
- package/dist/timeframe/tz.js +17 -6
- package/dist/timeframe/tz.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 +215 -0
- package/dist/tracker/createTracker.js.map +1 -0
- package/dist/tracker/exclusion.d.ts +28 -0
- package/dist/tracker/exclusion.js +50 -0
- package/dist/tracker/exclusion.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/ga4.d.ts +29 -0
- package/dist/tracker/sinks/ga4.js +30 -0
- package/dist/tracker/sinks/ga4.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 +20 -0
- package/dist/tracker/sinks/plausible.js +32 -0
- package/dist/tracker/sinks/plausible.js.map +1 -0
- package/dist/tracker/sinks/posthog.d.ts +18 -0
- package/dist/tracker/sinks/posthog.js +30 -0
- package/dist/tracker/sinks/posthog.js.map +1 -0
- package/dist/tracker/sinks/umami.d.ts +18 -0
- package/dist/tracker/sinks/umami.js +23 -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 +81 -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 +91 -0
- package/dist/translations/ar.js +221 -0
- package/dist/translations/ar.js.map +1 -0
- package/dist/translations/de.js +145 -1
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +145 -1
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.js +221 -0
- package/dist/translations/es.js.map +1 -0
- package/dist/translations/fr.js +221 -0
- package/dist/translations/fr.js.map +1 -0
- package/dist/translations/id.js +221 -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 +144 -0
- package/dist/translations/keys.js +145 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.js +221 -0
- package/dist/translations/ko.js.map +1 -0
- package/dist/translations/metricKeys.js +8 -2
- package/dist/translations/metricKeys.js.map +1 -1
- package/dist/translations/pt.js +221 -0
- package/dist/translations/pt.js.map +1 -0
- package/dist/translations/ru.js +221 -0
- package/dist/translations/ru.js.map +1 -0
- package/dist/translations/server.js.map +1 -1
- package/dist/translations/uk.js +221 -0
- package/dist/translations/uk.js.map +1 -0
- package/dist/translations/zh.js +221 -0
- package/dist/translations/zh.js.map +1 -0
- package/dist/view/AnalyticsNavLink.d.ts +19 -0
- package/dist/view/AnalyticsNavLink.js +40 -0
- package/dist/view/AnalyticsNavLink.js.map +1 -0
- package/dist/view/AnalyticsView.d.ts +23 -0
- package/dist/view/AnalyticsView.js +45 -0
- package/dist/view/AnalyticsView.js.map +1 -0
- package/dist/view/AnalyticsViewClient.d.ts +15 -0
- package/dist/view/AnalyticsViewClient.js +244 -0
- package/dist/view/AnalyticsViewClient.js.map +1 -0
- package/dist/view/authRedirect.js +32 -0
- package/dist/view/authRedirect.js.map +1 -0
- package/dist/view/conversionRate.js +18 -0
- package/dist/view/conversionRate.js.map +1 -0
- package/dist/view/dayRange.js +68 -0
- package/dist/view/dayRange.js.map +1 -0
- package/dist/view/gating.d.ts +1 -0
- package/dist/view/gating.js +142 -0
- package/dist/view/gating.js.map +1 -0
- package/dist/view/labels.js +76 -0
- package/dist/view/labels.js.map +1 -0
- package/dist/view/registerView.js +48 -0
- package/dist/view/registerView.js.map +1 -0
- package/dist/view/sections/Breakdowns.js +198 -0
- package/dist/view/sections/Breakdowns.js.map +1 -0
- package/dist/view/sections/EmptyStates.js +92 -0
- package/dist/view/sections/EmptyStates.js.map +1 -0
- package/dist/view/sections/FilterChips.js +46 -0
- package/dist/view/sections/FilterChips.js.map +1 -0
- package/dist/view/sections/GoalsPanel.js +82 -0
- package/dist/view/sections/GoalsPanel.js.map +1 -0
- package/dist/view/sections/OverviewCards.js +65 -0
- package/dist/view/sections/OverviewCards.js.map +1 -0
- package/dist/view/sections/RealtimeStrip.js +80 -0
- package/dist/view/sections/RealtimeStrip.js.map +1 -0
- package/dist/view/sections/Toolbar.js +207 -0
- package/dist/view/sections/Toolbar.js.map +1 -0
- package/dist/view/sections/Trend.js +125 -0
- package/dist/view/sections/Trend.js.map +1 -0
- package/dist/view/sections/styles.js +76 -0
- package/dist/view/sections/styles.js.map +1 -0
- package/dist/view/state.js +211 -0
- package/dist/view/state.js.map +1 -0
- package/dist/view/useViewQueries.js +153 -0
- package/dist/view/useViewQueries.js.map +1 -0
- package/dist/view/viewProps.d.ts +40 -0
- package/dist/view/viewProps.js +90 -0
- package/dist/view/viewProps.js.map +1 -0
- package/dist/widgets/AnalyticsBreakdownWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsBreakdownWidget.js +78 -11
- package/dist/widgets/AnalyticsBreakdownWidget.js.map +1 -1
- package/dist/widgets/AnalyticsGoalsWidget.d.ts +14 -0
- package/dist/widgets/AnalyticsGoalsWidget.js +196 -0
- package/dist/widgets/AnalyticsGoalsWidget.js.map +1 -0
- package/dist/widgets/AnalyticsMetricWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsMetricWidget.js +63 -13
- package/dist/widgets/AnalyticsMetricWidget.js.map +1 -1
- package/dist/widgets/AnalyticsRealtimeWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsRealtimeWidget.js +44 -22
- package/dist/widgets/AnalyticsRealtimeWidget.js.map +1 -1
- package/dist/widgets/AnalyticsTrendWidget.d.ts +2 -1
- package/dist/widgets/AnalyticsTrendWidget.js +79 -16
- package/dist/widgets/AnalyticsTrendWidget.js.map +1 -1
- package/dist/widgets/RealtimeCounter.d.ts +4 -0
- package/dist/widgets/RealtimeCounter.js +18 -4
- package/dist/widgets/RealtimeCounter.js.map +1 -1
- package/dist/widgets/WidgetViewLink.js +17 -0
- package/dist/widgets/WidgetViewLink.js.map +1 -0
- package/dist/widgets/breakdownTypes.js +38 -0
- package/dist/widgets/breakdownTypes.js.map +1 -1
- package/dist/widgets/cardChrome.js +31 -7
- package/dist/widgets/cardChrome.js.map +1 -1
- package/dist/widgets/comparison.js +15 -1
- package/dist/widgets/comparison.js.map +1 -1
- package/dist/widgets/defaults.d.ts +6 -2
- package/dist/widgets/defaults.js +78 -23
- package/dist/widgets/defaults.js.map +1 -1
- package/dist/widgets/filterCaption.js +27 -0
- package/dist/widgets/filterCaption.js.map +1 -0
- package/dist/widgets/filterField.d.ts +19 -0
- package/dist/widgets/filterField.js +75 -0
- package/dist/widgets/filterField.js.map +1 -0
- package/dist/widgets/prepareWidgetRead.d.ts +7 -0
- package/dist/widgets/prepareWidgetRead.js +74 -0
- package/dist/widgets/prepareWidgetRead.js.map +1 -0
- package/dist/widgets/range.js +43 -12
- package/dist/widgets/range.js.map +1 -1
- package/dist/widgets/readForWidget.d.ts +26 -3
- package/dist/widgets/readForWidget.js +48 -44
- package/dist/widgets/readForWidget.js.map +1 -1
- package/dist/widgets/readForWidgetBreakdown.d.ts +34 -2
- package/dist/widgets/readForWidgetBreakdown.js +53 -49
- package/dist/widgets/readForWidgetBreakdown.js.map +1 -1
- package/dist/widgets/readForWidgetGoals.d.ts +67 -0
- package/dist/widgets/readForWidgetGoals.js +140 -0
- package/dist/widgets/readForWidgetGoals.js.map +1 -0
- package/dist/widgets/readForWidgetRealtime.d.ts +8 -0
- package/dist/widgets/readForWidgetRealtime.js +23 -21
- package/dist/widgets/readForWidgetRealtime.js.map +1 -1
- package/dist/widgets/readForWidgetSeries.d.ts +26 -2
- package/dist/widgets/readForWidgetSeries.js +78 -53
- package/dist/widgets/readForWidgetSeries.js.map +1 -1
- package/dist/widgets/readMeta.js +18 -0
- package/dist/widgets/readMeta.js.map +1 -0
- package/dist/widgets/realtimePoll.js +13 -1
- package/dist/widgets/realtimePoll.js.map +1 -1
- package/dist/widgets/registerWidgets.js +62 -10
- package/dist/widgets/registerWidgets.js.map +1 -1
- package/dist/widgets/types.d.ts +15 -0
- package/dist/widgets/types.js +16 -2
- package/dist/widgets/types.js.map +1 -1
- package/dist/widgets/viewLink.d.ts +22 -0
- package/dist/widgets/viewLink.js +86 -0
- package/dist/widgets/viewLink.js.map +1 -0
- package/package.json +27 -7
- package/dist/native/rollups/applyDistinctDeltas.js +0 -9
- package/dist/native/rollups/applyDistinctDeltas.js.map +0 -1
- package/dist/native/rollups/bumpRollup.js +0 -68
- package/dist/native/rollups/bumpRollup.js.map +0 -1
- package/dist/native/rollups/insertIfNew.js +0 -19
- package/dist/native/rollups/insertIfNew.js.map +0 -1
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import "./paths.js";
|
|
2
|
+
import "../core/contract.js";
|
|
3
|
+
import { getRuntime, platformReadGate, readAccessFor, resolveTimezoneFor } from "./runtime.js";
|
|
4
|
+
import { NO_STORE, RETRY_AFTER, analyticsError, errorResponse } from "./errors.js";
|
|
5
|
+
import { serializeCapabilities } from "../core/capabilities.js";
|
|
6
|
+
import { resolveQueryScope, resolveRequestedScope } from "../core/scopedRead.js";
|
|
7
|
+
import { goalSlugsFor } from "./goalHint.js";
|
|
8
|
+
import { previousWindow, withinLookback } from "../widgets/comparison.js";
|
|
9
|
+
import { parseQueryParams, readParam } from "../query/parse.js";
|
|
10
|
+
import { resolveSourcesForRequest } from "./readContextForRequest.js";
|
|
11
|
+
//#region src/plugin/queryEndpoint.ts
|
|
12
|
+
/**
|
|
13
|
+
* The query as the response echoes it: the date range's instants as ISO strings, every
|
|
14
|
+
* other field as the read carried it. `goalSlugs` rides along unchanged, so a client sees
|
|
15
|
+
* the scope's slugs, an empty list for a scope with no goals, or the string `'unresolved'`
|
|
16
|
+
* when the resolver failed.
|
|
17
|
+
*/
|
|
18
|
+
const serializeQuery = (query) => ({
|
|
19
|
+
...query,
|
|
20
|
+
dateRange: {
|
|
21
|
+
start: query.dateRange.start.toISOString(),
|
|
22
|
+
end: query.dateRange.end.toISOString()
|
|
23
|
+
}
|
|
24
|
+
});
|
|
25
|
+
/**
|
|
26
|
+
* Authenticated GET over the surfacing engine: the public read primitive the admin view
|
|
27
|
+
* and consumers' own dashboards are built on. Gating runs in a fixed order so a caller
|
|
28
|
+
* learns nothing from the answer it is not already entitled to: authentication, then
|
|
29
|
+
* `access.read`, then scope and source resolution (shared with the sources endpoint, so a
|
|
30
|
+
* tenant can select no source that endpoint does not list), then capability validation of
|
|
31
|
+
* every parameter against the selected source. Being listed is not sufficient: a shared
|
|
32
|
+
* source that cannot narrow to the caller's scope answers 403 with `param: 'source'`.
|
|
33
|
+
* Errors carry a code and the parameter at fault; adapter configuration and upstream error
|
|
34
|
+
* text never reach the response.
|
|
35
|
+
*/
|
|
36
|
+
const makeQueryHandler = () => async (req) => {
|
|
37
|
+
if (!req.user) return errorResponse(401, analyticsError("unauthorized", "analytics: authentication required"));
|
|
38
|
+
const runtime = getRuntime(req.payload);
|
|
39
|
+
if (!runtime) return errorResponse(503, analyticsError("unavailable", "analytics: not available"), RETRY_AFTER);
|
|
40
|
+
let adapterId = "unresolved";
|
|
41
|
+
try {
|
|
42
|
+
if (!await readAccessFor(runtime, req)) return errorResponse(403, analyticsError("forbidden", "analytics: read access denied"));
|
|
43
|
+
const params = new URL(req.url ?? "", "http://localhost").searchParams;
|
|
44
|
+
const platformRead = platformReadGate(runtime, req);
|
|
45
|
+
const requested = await resolveRequestedScope({
|
|
46
|
+
runtime,
|
|
47
|
+
req,
|
|
48
|
+
raw: params.get("scope"),
|
|
49
|
+
platformRead
|
|
50
|
+
});
|
|
51
|
+
if (!requested.ok) return requested.reason === "named" ? errorResponse(400, analyticsError("untrusted_scope", "analytics: scope is not permitted for this request", "scope")) : errorResponse(404, analyticsError("unknown_source", "analytics: no source is available for this request"));
|
|
52
|
+
const context = await resolveSourcesForRequest(req, {
|
|
53
|
+
platformRead,
|
|
54
|
+
scope: requested.scope
|
|
55
|
+
});
|
|
56
|
+
if (context.adapters.size === 0) return errorResponse(404, analyticsError("unknown_source", "analytics: no source is available for this request"));
|
|
57
|
+
const requestedSource = readParam(params, "source");
|
|
58
|
+
const adapter = context.adapters.get(requestedSource ?? context.defaultId ?? "");
|
|
59
|
+
if (!adapter) return errorResponse(404, analyticsError("unknown_source", "analytics: unknown source", "source"));
|
|
60
|
+
adapterId = adapter.id;
|
|
61
|
+
const queryScope = await resolveQueryScope({
|
|
62
|
+
runtime,
|
|
63
|
+
req,
|
|
64
|
+
scope: context.scope,
|
|
65
|
+
adapter,
|
|
66
|
+
platformRead
|
|
67
|
+
});
|
|
68
|
+
if (!queryScope.ok) return errorResponse(403, analyticsError("forbidden", "analytics: this source cannot be read for your scope", "source"));
|
|
69
|
+
const capabilities = serializeCapabilities(adapter.capabilities);
|
|
70
|
+
const parsed = parseQueryParams(params, {
|
|
71
|
+
capabilities,
|
|
72
|
+
timezone: await resolveTimezoneFor(runtime, req, context.scope === "*" ? null : context.scope)
|
|
73
|
+
});
|
|
74
|
+
if (!parsed.ok) return errorResponse(400, parsed.error);
|
|
75
|
+
const goalSlugs = await goalSlugsFor({
|
|
76
|
+
runtime,
|
|
77
|
+
req,
|
|
78
|
+
scope: context.scope === "*" ? null : context.scope,
|
|
79
|
+
metrics: parsed.value.query.metrics,
|
|
80
|
+
dimensions: parsed.value.query.dimensions
|
|
81
|
+
});
|
|
82
|
+
const query = {
|
|
83
|
+
...parsed.value.query,
|
|
84
|
+
...queryScope.queryScope === void 0 ? {} : { scope: queryScope.queryScope },
|
|
85
|
+
...goalSlugs === void 0 ? {} : { goalSlugs }
|
|
86
|
+
};
|
|
87
|
+
let comparisonRange = null;
|
|
88
|
+
if (parsed.value.compare === "previous") {
|
|
89
|
+
comparisonRange = previousWindow(query.dateRange, query.timezone);
|
|
90
|
+
if (!comparisonRange) return errorResponse(400, analyticsError("invalid_param", "analytics: the range is too long to compare against a previous period", "compare"));
|
|
91
|
+
if (!withinLookback(comparisonRange, adapter.capabilities.maxLookbackDays, { tz: query.timezone })) comparisonRange = null;
|
|
92
|
+
}
|
|
93
|
+
let result;
|
|
94
|
+
let comparison;
|
|
95
|
+
try {
|
|
96
|
+
[result, comparison] = await Promise.all([runtime.engine.read(adapter, query), comparisonRange ? runtime.engine.read(adapter, {
|
|
97
|
+
...query,
|
|
98
|
+
dateRange: comparisonRange
|
|
99
|
+
}) : void 0]);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
req.payload.logger?.warn(`analytics: query read failed for adapter "${adapter.id}": ${String(err)}`);
|
|
102
|
+
return errorResponse(503, analyticsError("unavailable", "analytics: source is temporarily unavailable"), RETRY_AFTER);
|
|
103
|
+
}
|
|
104
|
+
const body = {
|
|
105
|
+
result,
|
|
106
|
+
...comparison ? { comparison } : {},
|
|
107
|
+
source: {
|
|
108
|
+
id: adapter.id,
|
|
109
|
+
label: adapter.label,
|
|
110
|
+
kind: runtime.configAdapterIds.has(adapter.id) ? "config" : "runtime"
|
|
111
|
+
},
|
|
112
|
+
capabilities,
|
|
113
|
+
query: serializeQuery(query)
|
|
114
|
+
};
|
|
115
|
+
return Response.json(body, { headers: NO_STORE });
|
|
116
|
+
} catch (err) {
|
|
117
|
+
req.payload.logger?.error(`analytics: query failed for adapter "${adapterId}": ${String(err)}`);
|
|
118
|
+
return errorResponse(500, analyticsError("internal", "analytics: query failed"));
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
//#endregion
|
|
122
|
+
export { makeQueryHandler };
|
|
123
|
+
|
|
124
|
+
//# sourceMappingURL=queryEndpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queryEndpoint.js","names":[],"sources":["../../src/plugin/queryEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport { serializeCapabilities } from '../core/capabilities'\nimport {\n\ttype AnalyticsQuery,\n\ttype AnalyticsResult,\n\ttype DateRange,\n\tPLATFORM_SCOPE,\n} from '../core/contract'\nimport { resolveQueryScope, resolveRequestedScope } from '../core/scopedRead'\nimport { parseQueryParams, readParam } from '../query/parse'\nimport type { QueryResponse, SerializedAnalyticsQuery } from '../query/response'\nimport { previousWindow, withinLookback } from '../widgets/comparison'\nimport { analyticsError, errorResponse, NO_STORE, RETRY_AFTER } from './errors'\nimport { goalSlugsFor } from './goalHint'\nimport { QUERY_PATH } from './paths'\nimport { resolveSourcesForRequest } from './readContextForRequest'\nimport { getRuntime, platformReadGate, readAccessFor, resolveTimezoneFor } from './runtime'\n\nexport { QUERY_PATH }\n\n/**\n * The query as the response echoes it: the date range's instants as ISO strings, every\n * other field as the read carried it. `goalSlugs` rides along unchanged, so a client sees\n * the scope's slugs, an empty list for a scope with no goals, or the string `'unresolved'`\n * 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\n/**\n * Authenticated GET over the surfacing engine: the public read primitive the admin view\n * and consumers' own dashboards are built on. Gating runs in a fixed order so a caller\n * learns nothing from the answer it is not already entitled to: authentication, then\n * `access.read`, then scope and source resolution (shared with the sources endpoint, so a\n * tenant can select no source that endpoint does not list), then capability validation of\n * every parameter against the selected source. Being listed is not sufficient: a shared\n * source that cannot narrow to the caller's scope answers 403 with `param: 'source'`.\n * Errors carry a code and the parameter at fault; adapter configuration and upstream error\n * text never reach the response.\n */\nexport const makeQueryHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, analyticsError('unauthorized', 'analytics: authentication required'))\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\t// Both `unavailable` answers are retryable, so both carry the same delay: a client\n\t\t// backs off identically whether the plugin is still booting or a provider is down.\n\t\treturn errorResponse(\n\t\t\t503,\n\t\t\tanalyticsError('unavailable', 'analytics: not available'),\n\t\t\tRETRY_AFTER\n\t\t)\n\t}\n\tlet adapterId = 'unresolved'\n\ttry {\n\t\tif (!(await readAccessFor(runtime, req))) {\n\t\t\treturn errorResponse(403, analyticsError('forbidden', 'analytics: read access denied'))\n\t\t}\n\t\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\t\tconst platformRead = platformReadGate(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\tplatformRead,\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// Only a scope the caller itself named is ever named back to it.\n\t\t\treturn requested.reason === 'named'\n\t\t\t\t? errorResponse(\n\t\t\t\t\t\t400,\n\t\t\t\t\t\tanalyticsError(\n\t\t\t\t\t\t\t'untrusted_scope',\n\t\t\t\t\t\t\t'analytics: scope is not permitted for this request',\n\t\t\t\t\t\t\t'scope'\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t: errorResponse(\n\t\t\t\t\t\t404,\n\t\t\t\t\t\tanalyticsError('unknown_source', 'analytics: no source is available for this request')\n\t\t\t\t\t)\n\t\t}\n\t\tconst context = await resolveSourcesForRequest(req, { platformRead, scope: requested.scope })\n\t\tif (context.adapters.size === 0) {\n\t\t\treturn errorResponse(\n\t\t\t\t404,\n\t\t\t\tanalyticsError('unknown_source', 'analytics: no source is available for this request')\n\t\t\t)\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\tplatformRead,\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 timezone = await resolveTimezoneFor(\n\t\t\truntime,\n\t\t\treq,\n\t\t\tcontext.scope === PLATFORM_SCOPE ? null : context.scope\n\t\t)\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 goalSlugs = await goalSlugsFor({\n\t\t\truntime,\n\t\t\treq,\n\t\t\tscope: context.scope === PLATFORM_SCOPE ? null : context.scope,\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...(goalSlugs === undefined ? {} : { goalSlugs }),\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})\n\t\t\t) {\n\t\t\t\tcomparisonRange = null\n\t\t\t}\n\t\t}\n\t\tlet result: AnalyticsResult\n\t\tlet comparison: AnalyticsResult | undefined\n\t\ttry {\n\t\t\t;[result, comparison] = await Promise.all([\n\t\t\t\truntime.engine.read(adapter, query),\n\t\t\t\tcomparisonRange\n\t\t\t\t\t? runtime.engine.read(adapter, { ...query, dateRange: comparisonRange })\n\t\t\t\t\t: undefined,\n\t\t\t])\n\t\t} catch (err) {\n\t\t\t// Neither a fresh nor a stale entry survived the read: the source is down, not the\n\t\t\t// request wrong, so the client is told to retry rather than to change anything.\n\t\t\treq.payload.logger?.warn(\n\t\t\t\t`analytics: query read failed for adapter \"${adapter.id}\": ${String(err)}`\n\t\t\t)\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tanalyticsError('unavailable', 'analytics: source is temporarily unavailable'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t\tconst body: QueryResponse = {\n\t\t\tresult,\n\t\t\t...(comparison ? { comparison } : {}),\n\t\t\tsource: {\n\t\t\t\tid: adapter.id,\n\t\t\t\tlabel: 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}\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":"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"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import "../core/contract.js";
|
|
2
|
+
import { getRuntime, platformReadGate, resolveRegistryFor } from "./runtime.js";
|
|
3
|
+
import { serializeCapabilities } from "../core/capabilities.js";
|
|
4
|
+
import { resolveRequestedScope } from "../core/scopedRead.js";
|
|
5
|
+
//#region src/plugin/readContextForRequest.ts
|
|
6
|
+
const empty = () => ({
|
|
7
|
+
sources: [],
|
|
8
|
+
defaultId: null,
|
|
9
|
+
adapters: /* @__PURE__ */ new Map(),
|
|
10
|
+
scope: null
|
|
11
|
+
});
|
|
12
|
+
const fromRegistry = (args) => {
|
|
13
|
+
const { runtime, registry, scope } = args;
|
|
14
|
+
const adapters = registry.all();
|
|
15
|
+
return {
|
|
16
|
+
sources: adapters.map((adapter) => ({
|
|
17
|
+
id: adapter.id,
|
|
18
|
+
label: adapter.label,
|
|
19
|
+
kind: runtime.configAdapterIds.has(adapter.id) ? "config" : "runtime",
|
|
20
|
+
capabilities: serializeCapabilities(adapter.capabilities)
|
|
21
|
+
})),
|
|
22
|
+
defaultId: registry.default().id,
|
|
23
|
+
adapters: new Map(adapters.map((adapter) => [adapter.id, adapter])),
|
|
24
|
+
scope
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* The sources a request may read, resolved once for both read endpoints: the request's
|
|
29
|
+
* own scope (or one a caller already had gated), the per-scope registry, and each adapter's
|
|
30
|
+
* serialized capabilities. {@link resolveRequestedScope} owns the scope decision, so a
|
|
31
|
+
* cross-scope resolution resolves no sources at all rather than another tenant's. A
|
|
32
|
+
* resolution that fails outright degrades instead: nothing on a scoped install, where it is
|
|
33
|
+
* indistinguishable from a forged request, and the static config registry otherwise.
|
|
34
|
+
*/
|
|
35
|
+
const resolveSourcesForRequest = async (req, args = {}) => {
|
|
36
|
+
const runtime = getRuntime(req.payload);
|
|
37
|
+
if (!runtime) return empty();
|
|
38
|
+
const allowed = args.platformRead ?? platformReadGate(runtime, req);
|
|
39
|
+
const degrade = () => runtime.scoped ? empty() : fromRegistry({
|
|
40
|
+
runtime,
|
|
41
|
+
registry: runtime.registry,
|
|
42
|
+
scope: null
|
|
43
|
+
});
|
|
44
|
+
try {
|
|
45
|
+
let scope;
|
|
46
|
+
if (args.scope !== void 0) scope = args.scope;
|
|
47
|
+
else {
|
|
48
|
+
const requested = await resolveRequestedScope({
|
|
49
|
+
runtime,
|
|
50
|
+
req,
|
|
51
|
+
platformRead: allowed
|
|
52
|
+
});
|
|
53
|
+
if (!requested.ok) return requested.reason === "failed" ? degrade() : empty();
|
|
54
|
+
scope = requested.scope;
|
|
55
|
+
}
|
|
56
|
+
return fromRegistry({
|
|
57
|
+
runtime,
|
|
58
|
+
registry: await resolveRegistryFor(runtime, {
|
|
59
|
+
payload: req.payload,
|
|
60
|
+
req,
|
|
61
|
+
scope: scope === "*" ? null : scope
|
|
62
|
+
}),
|
|
63
|
+
scope
|
|
64
|
+
});
|
|
65
|
+
} catch (err) {
|
|
66
|
+
req.payload.logger?.warn(`analytics: source resolution failed: ${String(err)}`);
|
|
67
|
+
return degrade();
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
//#endregion
|
|
71
|
+
export { resolveSourcesForRequest };
|
|
72
|
+
|
|
73
|
+
//# sourceMappingURL=readContextForRequest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"readContextForRequest.js","names":[],"sources":["../../src/plugin/readContextForRequest.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport { type SerializedCapabilities, serializeCapabilities } from '../core/capabilities'\nimport { type AnalyticsAdapter, PLATFORM_SCOPE } from '../core/contract'\nimport type { AdapterRegistry } from '../core/registry'\nimport { resolveRequestedScope } from '../core/scopedRead'\nimport type { QuerySourceRef } from '../query/response'\nimport {\n\ttype AnalyticsRuntime,\n\tgetRuntime,\n\ttype PlatformReadGate,\n\tplatformReadGate,\n\tresolveRegistryFor,\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\nexport interface RequestSources {\n\t/** Wire rows for the resolved scope, in registry order; empty when none resolve. */\n\tsources: RequestSource[]\n\tdefaultId: string | null\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\nexport interface ResolveSourcesArgs {\n\t/**\n\t * A scope {@link resolveRequestedScope} already decided and gated for this request. It\n\t * replaces this call's own resolution, so pass only what that helper returned.\n\t */\n\tscope?: string | null\n\t/** Shared `platformRead` decision; one is created per call when omitted. */\n\tplatformRead?: PlatformReadGate\n}\n\nconst empty = (): RequestSources => ({\n\tsources: [],\n\tdefaultId: null,\n\tadapters: new Map(),\n\tscope: null,\n})\n\nconst fromRegistry = (args: {\n\truntime: AnalyticsRuntime\n\tregistry: AdapterRegistry\n\tscope: string | null\n}): RequestSources => {\n\tconst { runtime, registry, scope } = args\n\tconst adapters = registry.all()\n\treturn {\n\t\tsources: adapters.map((adapter) => ({\n\t\t\tid: adapter.id,\n\t\t\tlabel: adapter.label,\n\t\t\tkind: runtime.configAdapterIds.has(adapter.id) ? ('config' as const) : ('runtime' as const),\n\t\t\tcapabilities: serializeCapabilities(adapter.capabilities),\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 * The sources a request may read, resolved once for both read endpoints: the request's\n * own scope (or one a caller already had gated), the per-scope registry, and each adapter's\n * serialized capabilities. {@link resolveRequestedScope} owns the scope decision, so a\n * cross-scope resolution resolves no sources at all rather than another tenant's. A\n * resolution that fails outright degrades instead: nothing on a scoped install, where it is\n * indistinguishable from a forged request, and the static config registry otherwise.\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\tconst allowed = args.platformRead ?? platformReadGate(runtime, req)\n\tconst degrade = (): RequestSources =>\n\t\truntime.scoped ? empty() : fromRegistry({ runtime, registry: runtime.registry, scope: null })\n\ttry {\n\t\tlet scope: string | null\n\t\tif (args.scope !== undefined) {\n\t\t\tscope = args.scope\n\t\t} else {\n\t\t\tconst requested = await resolveRequestedScope({ runtime, req, platformRead: allowed })\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 registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: scope === PLATFORM_SCOPE ? null : scope,\n\t\t})\n\t\treturn fromRegistry({ runtime, registry, scope })\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":";;;;;AAuCA,MAAM,eAA+B;CACpC,SAAS,CAAC;CACV,WAAW;CACX,0BAAU,IAAI,IAAI;CAClB,OAAO;AACR;AAEA,MAAM,gBAAgB,SAIA;CACrB,MAAM,EAAE,SAAS,UAAU,UAAU;CACrC,MAAM,WAAW,SAAS,IAAI;CAC9B,OAAO;EACN,SAAS,SAAS,KAAK,aAAa;GACnC,IAAI,QAAQ;GACZ,OAAO,QAAQ;GACf,MAAM,QAAQ,iBAAiB,IAAI,QAAQ,EAAE,IAAK,WAAsB;GACxE,cAAc,sBAAsB,QAAQ,YAAY;EACzD,EAAE;EACF,WAAW,SAAS,QAAQ,EAAE;EAC9B,UAAU,IAAI,IAAI,SAAS,KAAK,YAAY,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC;EAClE;CACD;AACD;;;;;;;;;AAUA,MAAa,2BAA2B,OACvC,KACA,OAA2B,CAAC,MACC;CAC7B,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAO,MAAM;CAEd,MAAM,UAAU,KAAK,gBAAgB,iBAAiB,SAAS,GAAG;CAClE,MAAM,gBACL,QAAQ,SAAS,MAAM,IAAI,aAAa;EAAE;EAAS,UAAU,QAAQ;EAAU,OAAO;CAAK,CAAC;CAC7F,IAAI;EACH,IAAI;EACJ,IAAI,KAAK,UAAU,KAAA,GAClB,QAAQ,KAAK;OACP;GACN,MAAM,YAAY,MAAM,sBAAsB;IAAE;IAAS;IAAK,cAAc;GAAQ,CAAC;GACrF,IAAI,CAAC,UAAU,IACd,OAAO,UAAU,WAAW,WAAW,QAAQ,IAAI,MAAM;GAE1D,QAAQ,UAAU;EACnB;EAMA,OAAO,aAAa;GAAE;GAAS,UAAA,MALR,mBAAmB,SAAS;IAClD,SAAS,IAAI;IACb;IACA,OAAO,UAAA,MAA2B,OAAO;GAC1C,CAAC;GACwC;EAAM,CAAC;CACjD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,KAAK,wCAAwC,OAAO,GAAG,GAAG;EAC9E,OAAO,QAAQ;CAChB;AACD"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import "./paths.js";
|
|
2
|
+
import { getRuntime, readAccessFor } from "./runtime.js";
|
|
3
|
+
import { NO_STORE, RETRY_AFTER, analyticsError, errorResponse } from "./errors.js";
|
|
2
4
|
import { readForWidgetRealtime } from "../widgets/readForWidgetRealtime.js";
|
|
3
5
|
//#region src/plugin/realtimeEndpoint.ts
|
|
4
6
|
const ALLOWED_METRICS = ["visitors", "pageviews"];
|
|
@@ -11,24 +13,43 @@ const ALLOWED_WINDOWS = [
|
|
|
11
13
|
const DEFAULT_WINDOW = 30;
|
|
12
14
|
/**
|
|
13
15
|
* Authenticated GET handler for the realtime widget poller. Reads + clamps the query
|
|
14
|
-
* params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request
|
|
15
|
-
*
|
|
16
|
-
* is integer counts only.
|
|
16
|
+
* params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request
|
|
17
|
+
* and 403 when `access.read` denies, which defaults to any authenticated user (not
|
|
18
|
+
* admin-panel access specifically); the response is integer counts only. A source that
|
|
19
|
+
* throws answers a retryable 503 rather than an unhandled 500: the widget polls this every
|
|
20
|
+
* few seconds, and a provider outage is not a reason to burn a stack trace per poll. Only
|
|
21
|
+
* the read is retryable, though, so an `access.read` resolver that throws answers 500: that
|
|
22
|
+
* is a configuration bug, and telling the poller to come back would only repeat it. Every
|
|
23
|
+
* answer is `no-store`, since what it counts depends on the caller's own scope.
|
|
17
24
|
*/
|
|
18
25
|
const makeRealtimeHandler = () => async (req) => {
|
|
19
|
-
if (!req.user) return
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
windowMinutes
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
26
|
+
if (!req.user) return errorResponse(401, analyticsError("unauthorized", "analytics: authentication required"));
|
|
27
|
+
try {
|
|
28
|
+
const runtime = getRuntime(req.payload);
|
|
29
|
+
if (runtime && !await readAccessFor(runtime, req)) return errorResponse(403, analyticsError("forbidden", "analytics: read access denied"));
|
|
30
|
+
const params = new URL(req.url ?? "", "http://localhost").searchParams;
|
|
31
|
+
const rawMetric = params.get("metric");
|
|
32
|
+
const metric = ALLOWED_METRICS.includes(rawMetric) ? rawMetric : "visitors";
|
|
33
|
+
const rawWindow = Number(params.get("windowMinutes"));
|
|
34
|
+
const windowMinutes = ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW;
|
|
35
|
+
const dataSource = params.get("dataSource") ?? void 0;
|
|
36
|
+
try {
|
|
37
|
+
const result = await readForWidgetRealtime({
|
|
38
|
+
req,
|
|
39
|
+
metric,
|
|
40
|
+
windowMinutes,
|
|
41
|
+
adapterId: dataSource,
|
|
42
|
+
now: /* @__PURE__ */ new Date()
|
|
43
|
+
});
|
|
44
|
+
return Response.json(result, { headers: NO_STORE });
|
|
45
|
+
} catch (err) {
|
|
46
|
+
req.payload.logger?.warn(`analytics: realtime read failed: ${String(err)}`);
|
|
47
|
+
return errorResponse(503, analyticsError("unavailable", "analytics: source is temporarily unavailable"), RETRY_AFTER);
|
|
48
|
+
}
|
|
49
|
+
} catch (err) {
|
|
50
|
+
req.payload.logger?.error(`analytics: realtime request failed: ${String(err)}`);
|
|
51
|
+
return errorResponse(500, analyticsError("internal", "analytics: realtime read failed"));
|
|
52
|
+
}
|
|
32
53
|
};
|
|
33
54
|
//#endregion
|
|
34
55
|
export { makeRealtimeHandler };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"realtimeEndpoint.js","names":[],"sources":["../../src/plugin/realtimeEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { readForWidgetRealtime } from '../widgets/readForWidgetRealtime'\nimport { REALTIME_PATH } from './paths'\n\nexport { REALTIME_PATH }\n\nconst ALLOWED_METRICS: MetricKey[] = ['visitors', 'pageviews']\nconst ALLOWED_WINDOWS = [5, 15, 30, 60]\nconst DEFAULT_WINDOW = 30\n\n/**\n * Authenticated GET handler for the realtime widget poller. Reads + clamps the query\n * params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request
|
|
1
|
+
{"version":3,"file":"realtimeEndpoint.js","names":[],"sources":["../../src/plugin/realtimeEndpoint.ts"],"sourcesContent":["import type { PayloadHandler } from 'payload'\nimport type { MetricKey } from '../core/contract'\nimport { readForWidgetRealtime } from '../widgets/readForWidgetRealtime'\nimport { analyticsError, errorResponse, NO_STORE, RETRY_AFTER } from './errors'\nimport { REALTIME_PATH } from './paths'\nimport { getRuntime, readAccessFor } from './runtime'\n\nexport { REALTIME_PATH }\n\nconst ALLOWED_METRICS: MetricKey[] = ['visitors', 'pageviews']\nconst ALLOWED_WINDOWS = [5, 15, 30, 60]\nconst DEFAULT_WINDOW = 30\n\n/**\n * Authenticated GET handler for the realtime widget poller. Reads + clamps the query\n * params, then delegates to readForWidgetRealtime. Returns 401 for an anonymous request\n * and 403 when `access.read` denies, which defaults to any authenticated user (not\n * admin-panel access specifically); the response is integer counts only. A source that\n * throws answers a retryable 503 rather than an unhandled 500: the widget polls this every\n * few seconds, and a provider outage is not a reason to burn a stack trace per poll. Only\n * the read is retryable, though, so an `access.read` resolver that throws answers 500: that\n * is a configuration bug, and telling the poller to come back would only repeat it. Every\n * answer is `no-store`, since what it counts depends on the caller's own scope.\n */\nexport const makeRealtimeHandler = (): PayloadHandler => async (req) => {\n\tif (!req.user) {\n\t\treturn errorResponse(401, analyticsError('unauthorized', 'analytics: authentication required'))\n\t}\n\ttry {\n\t\tconst runtime = getRuntime(req.payload)\n\t\t// No runtime means no adapter to read, so the skipped gate protects no data.\n\t\tif (runtime && !(await readAccessFor(runtime, req))) {\n\t\t\treturn errorResponse(403, analyticsError('forbidden', 'analytics: read access denied'))\n\t\t}\n\t\tconst params = new URL(req.url ?? '', 'http://localhost').searchParams\n\t\tconst rawMetric = params.get('metric')\n\t\tconst metric: MetricKey = ALLOWED_METRICS.includes(rawMetric as MetricKey)\n\t\t\t? (rawMetric as MetricKey)\n\t\t\t: 'visitors'\n\t\tconst rawWindow = Number(params.get('windowMinutes'))\n\t\tconst windowMinutes = ALLOWED_WINDOWS.includes(rawWindow) ? rawWindow : DEFAULT_WINDOW\n\t\tconst dataSource = params.get('dataSource') ?? undefined\n\t\ttry {\n\t\t\tconst result = await readForWidgetRealtime({\n\t\t\t\treq,\n\t\t\t\tmetric,\n\t\t\t\twindowMinutes,\n\t\t\t\tadapterId: dataSource,\n\t\t\t\tnow: new Date(),\n\t\t\t})\n\t\t\treturn Response.json(result, { headers: NO_STORE })\n\t\t} catch (err) {\n\t\t\treq.payload.logger?.warn(`analytics: realtime read failed: ${String(err)}`)\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tanalyticsError('unavailable', 'analytics: source is temporarily unavailable'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t} catch (err) {\n\t\treq.payload.logger?.error(`analytics: realtime request failed: ${String(err)}`)\n\t\treturn errorResponse(500, analyticsError('internal', 'analytics: realtime read failed'))\n\t}\n}\n"],"mappings":";;;;;AASA,MAAM,kBAA+B,CAAC,YAAY,WAAW;AAC7D,MAAM,kBAAkB;CAAC;CAAG;CAAI;CAAI;AAAE;AACtC,MAAM,iBAAiB;;;;;;;;;;;;AAavB,MAAa,4BAA4C,OAAO,QAAQ;CACvE,IAAI,CAAC,IAAI,MACR,OAAO,cAAc,KAAK,eAAe,gBAAgB,oCAAoC,CAAC;CAE/F,IAAI;EACH,MAAM,UAAU,WAAW,IAAI,OAAO;EAEtC,IAAI,WAAW,CAAE,MAAM,cAAc,SAAS,GAAG,GAChD,OAAO,cAAc,KAAK,eAAe,aAAa,+BAA+B,CAAC;EAEvF,MAAM,SAAS,IAAI,IAAI,IAAI,OAAO,IAAI,kBAAkB,EAAE;EAC1D,MAAM,YAAY,OAAO,IAAI,QAAQ;EACrC,MAAM,SAAoB,gBAAgB,SAAS,SAAsB,IACrE,YACD;EACH,MAAM,YAAY,OAAO,OAAO,IAAI,eAAe,CAAC;EACpD,MAAM,gBAAgB,gBAAgB,SAAS,SAAS,IAAI,YAAY;EACxE,MAAM,aAAa,OAAO,IAAI,YAAY,KAAK,KAAA;EAC/C,IAAI;GACH,MAAM,SAAS,MAAM,sBAAsB;IAC1C;IACA;IACA;IACA,WAAW;IACX,qBAAK,IAAI,KAAK;GACf,CAAC;GACD,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;EACnD,SAAS,KAAK;GACb,IAAI,QAAQ,QAAQ,KAAK,oCAAoC,OAAO,GAAG,GAAG;GAC1E,OAAO,cACN,KACA,eAAe,eAAe,8CAA8C,GAC5E,WACD;EACD;CACD,SAAS,KAAK;EACb,IAAI,QAAQ,QAAQ,MAAM,uCAAuC,OAAO,GAAG,GAAG;EAC9E,OAAO,cAAc,KAAK,eAAe,YAAY,iCAAiC,CAAC;CACxF;AACD"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import "./paths.js";
|
|
2
|
+
import "../core/contract.js";
|
|
3
|
+
import { epochKeyFor } from "../surfacing/epoch.js";
|
|
4
|
+
import { cacheEpochFor, getRuntime, platformReadGate, readAccessFor } from "./runtime.js";
|
|
5
|
+
import { readCappedBody } from "../capture/requestBody.js";
|
|
6
|
+
import { NO_STORE, RETRY_AFTER, analyticsError, errorResponse } from "./errors.js";
|
|
7
|
+
import { resolveRequestedScope } from "../core/scopedRead.js";
|
|
8
|
+
//#region src/plugin/refreshEndpoint.ts
|
|
9
|
+
/** The body carries one optional scope string; anything larger is not this request. */
|
|
10
|
+
const MAX_REFRESH_BODY_BYTES = 4 * 1024;
|
|
11
|
+
/**
|
|
12
|
+
* How long one scope stays refreshed after this instance bumps it for a request. This is a
|
|
13
|
+
* debounce of invalidation, not request rate limiting: a looped POST would otherwise retire
|
|
14
|
+
* every cached read of a scope over and over and turn each of them into a provider call. It
|
|
15
|
+
* bounds only what the endpoint does, never how often a caller may ask, which is the edge's
|
|
16
|
+
* job. Collection hooks are not debounced: a save has to be visible on the next read.
|
|
17
|
+
*/
|
|
18
|
+
const REFRESH_DEBOUNCE_MS = 5e3;
|
|
19
|
+
/**
|
|
20
|
+
* Per-scope debounce state. Entries are pruned on every write rather than kept, so an
|
|
21
|
+
* instance that refreshes thousands of scopes over its life holds only the ones a bump
|
|
22
|
+
* could still be debounced against.
|
|
23
|
+
*/
|
|
24
|
+
const createRefreshDebounce = (now, windowMs = REFRESH_DEBOUNCE_MS) => {
|
|
25
|
+
const bumpedAt = /* @__PURE__ */ new Map();
|
|
26
|
+
return {
|
|
27
|
+
allows(key) {
|
|
28
|
+
const last = bumpedAt.get(key);
|
|
29
|
+
return last === void 0 || now() - last >= windowMs;
|
|
30
|
+
},
|
|
31
|
+
record(key) {
|
|
32
|
+
const at = now();
|
|
33
|
+
for (const [seen, when] of bumpedAt) if (at - when >= windowMs) bumpedAt.delete(seen);
|
|
34
|
+
bumpedAt.set(key, at);
|
|
35
|
+
},
|
|
36
|
+
get size() {
|
|
37
|
+
return bumpedAt.size;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* The optional `{ scope }` body. An empty body, a body that is not an object and a body
|
|
43
|
+
* with no `scope` all mean "my own scope": a refresh is a button, and callers that send
|
|
44
|
+
* nothing at all are the common case. Only a `scope` of the wrong type is a refusal.
|
|
45
|
+
*/
|
|
46
|
+
const parseBody = (bytes) => {
|
|
47
|
+
if (bytes.byteLength === 0) return { ok: true };
|
|
48
|
+
let parsed;
|
|
49
|
+
try {
|
|
50
|
+
parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
51
|
+
} catch {
|
|
52
|
+
return { ok: true };
|
|
53
|
+
}
|
|
54
|
+
if (typeof parsed !== "object" || parsed === null) return { ok: true };
|
|
55
|
+
if (!("scope" in parsed)) return { ok: true };
|
|
56
|
+
const scope = parsed.scope;
|
|
57
|
+
if (scope === void 0 || scope === null) return { ok: true };
|
|
58
|
+
return typeof scope === "string" ? {
|
|
59
|
+
ok: true,
|
|
60
|
+
scope
|
|
61
|
+
} : { ok: false };
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Authenticated POST raising one scope's cache epoch, which retires every cached read
|
|
65
|
+
* keyed on the old one across every instance. Gated exactly like the read endpoints:
|
|
66
|
+
* authentication, then `access.read`, then scope.
|
|
67
|
+
*
|
|
68
|
+
* Scope goes through `resolveRequestedScope`, the same decision the query endpoint reads
|
|
69
|
+
* with, so this endpoint refuses every request that endpoint refuses: a named scope needs
|
|
70
|
+
* `platformRead`, and so does a request whose own scope will not resolve on a scoped
|
|
71
|
+
* install. Both answer `400 untrusted_scope`. The wildcard bumps the install-wide token,
|
|
72
|
+
* because a cross-scope read stamps no scope on its query and its entries key on exactly
|
|
73
|
+
* that token.
|
|
74
|
+
*/
|
|
75
|
+
const makeRefreshHandler = (opts = {}) => {
|
|
76
|
+
const debounce = createRefreshDebounce(opts.now ?? Date.now);
|
|
77
|
+
return async (req) => {
|
|
78
|
+
if (!req.user) return errorResponse(401, analyticsError("unauthorized", "analytics: authentication required"));
|
|
79
|
+
const runtime = getRuntime(req.payload);
|
|
80
|
+
if (!runtime) return errorResponse(503, analyticsError("unavailable", "analytics: not available"), RETRY_AFTER);
|
|
81
|
+
try {
|
|
82
|
+
if (!await readAccessFor(runtime, req)) return errorResponse(403, analyticsError("forbidden", "analytics: read access denied"));
|
|
83
|
+
const read = await readCappedBody(req, MAX_REFRESH_BODY_BYTES);
|
|
84
|
+
if (!read.ok) return read.reason === "too-large" ? errorResponse(413, analyticsError("payload_too_large", "analytics: the refresh body is too large")) : errorResponse(400, analyticsError("invalid_param", "analytics: the refresh body could not be read", "scope"));
|
|
85
|
+
const body = parseBody(read.body);
|
|
86
|
+
if (!body.ok) return errorResponse(400, analyticsError("invalid_param", "analytics: scope must be a string", "scope"));
|
|
87
|
+
const requested = await resolveRequestedScope({
|
|
88
|
+
runtime,
|
|
89
|
+
req,
|
|
90
|
+
raw: body.scope ?? null,
|
|
91
|
+
platformRead: platformReadGate(runtime, req)
|
|
92
|
+
});
|
|
93
|
+
if (!requested.ok) return errorResponse(400, analyticsError("untrusted_scope", "analytics: scope is not permitted for this request", "scope"));
|
|
94
|
+
const scope = requested.scope === "*" ? null : requested.scope;
|
|
95
|
+
const key = epochKeyFor(scope);
|
|
96
|
+
if (!debounce.allows(key)) {
|
|
97
|
+
const debounced = { epoch: await cacheEpochFor(runtime, scope) };
|
|
98
|
+
return Response.json(debounced, { headers: NO_STORE });
|
|
99
|
+
}
|
|
100
|
+
const epoch = await (runtime.epoch?.bump(scope) ?? Promise.resolve("0"));
|
|
101
|
+
debounce.record(key);
|
|
102
|
+
const answer = { epoch };
|
|
103
|
+
return Response.json(answer, { headers: NO_STORE });
|
|
104
|
+
} catch (err) {
|
|
105
|
+
req.payload.logger?.warn(`analytics: cache refresh failed: ${String(err)}`);
|
|
106
|
+
return errorResponse(503, analyticsError("unavailable", "analytics: the cache could not be refreshed"), RETRY_AFTER);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
export { makeRefreshHandler };
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=refreshEndpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refreshEndpoint.js","names":[],"sources":["../../src/plugin/refreshEndpoint.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\nimport { readCappedBody } from '../capture/requestBody'\nimport { PLATFORM_SCOPE } from '../core/contract'\nimport { resolveRequestedScope } from '../core/scopedRead'\nimport type { RefreshResponse } from '../query/fetchQuery'\nimport { epochKeyFor, INITIAL_EPOCH } from '../surfacing/epoch'\nimport { analyticsError, errorResponse, NO_STORE, RETRY_AFTER } from './errors'\nimport { REFRESH_PATH } from './paths'\nimport { cacheEpochFor, getRuntime, platformReadGate, readAccessFor } from './runtime'\n\nexport { REFRESH_PATH }\n\n/** The body carries one optional scope string; anything larger is not this request. */\nexport const MAX_REFRESH_BODY_BYTES = 4 * 1024\n\n/**\n * How long one scope stays refreshed after this instance bumps it for a request. This is a\n * debounce of invalidation, not request rate limiting: a looped POST would otherwise retire\n * every cached read of a scope over and over and turn each of them into a provider call. It\n * bounds only what the endpoint does, never how often a caller may ask, which is the edge's\n * job. Collection hooks are not debounced: a save has to be visible on the next read.\n */\nexport const REFRESH_DEBOUNCE_MS = 5_000\n\nexport interface RefreshHandlerOptions {\n\t/** Clock behind the debounce window; `Date.now` unless a test injects one. */\n\tnow?: () => number\n}\n\nexport interface RefreshDebounce {\n\t/** Whether this scope may be bumped now; recording a bump is `record`'s job. */\n\tallows(key: string): boolean\n\t/** Marks the scope bumped, dropping every entry the window has already left. */\n\trecord(key: string): void\n\t/** Entries currently held, which is one window's distinct scopes at most. */\n\treadonly size: number\n}\n\n/**\n * Per-scope debounce state. Entries are pruned on every write rather than kept, so an\n * instance that refreshes thousands of scopes over its life holds only the ones a bump\n * could still be debounced against.\n */\nexport const createRefreshDebounce = (\n\tnow: () => number,\n\twindowMs: number = REFRESH_DEBOUNCE_MS\n): RefreshDebounce => {\n\tconst bumpedAt = new Map<string, number>()\n\treturn {\n\t\tallows(key) {\n\t\t\tconst last = bumpedAt.get(key)\n\t\t\treturn last === undefined || now() - last >= windowMs\n\t\t},\n\t\trecord(key) {\n\t\t\tconst at = now()\n\t\t\tfor (const [seen, when] of bumpedAt) {\n\t\t\t\tif (at - when >= windowMs) {\n\t\t\t\t\tbumpedAt.delete(seen)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbumpedAt.set(key, at)\n\t\t},\n\t\tget size() {\n\t\t\treturn bumpedAt.size\n\t\t},\n\t}\n}\n\ntype ParsedBody = { ok: true; scope?: string } | { ok: false }\n\n/**\n * The optional `{ scope }` body. An empty body, a body that is not an object and a body\n * with no `scope` all mean \"my own scope\": a refresh is a button, and callers that send\n * nothing at all are the common case. Only a `scope` of the wrong type is a refusal.\n */\nconst parseBody = (bytes: ArrayBuffer): ParsedBody => {\n\tif (bytes.byteLength === 0) {\n\t\treturn { ok: true }\n\t}\n\tlet parsed: unknown\n\ttry {\n\t\tparsed = JSON.parse(new TextDecoder().decode(bytes))\n\t} catch {\n\t\treturn { ok: true }\n\t}\n\tif (typeof parsed !== 'object' || parsed === null) {\n\t\treturn { ok: true }\n\t}\n\tif (!('scope' in parsed)) {\n\t\treturn { ok: true }\n\t}\n\tconst scope: unknown = parsed.scope\n\tif (scope === undefined || scope === null) {\n\t\treturn { ok: true }\n\t}\n\treturn typeof scope === 'string' ? { ok: true, scope } : { ok: false }\n}\n\n/**\n * Authenticated POST raising one scope's cache epoch, which retires every cached read\n * keyed on the old one across every instance. Gated exactly like the read endpoints:\n * authentication, then `access.read`, then scope.\n *\n * Scope goes through `resolveRequestedScope`, the same decision the query endpoint reads\n * with, so this endpoint refuses every request that endpoint refuses: a named scope needs\n * `platformRead`, and so does a request whose own scope will not resolve on a scoped\n * install. Both answer `400 untrusted_scope`. The wildcard bumps the install-wide token,\n * because a cross-scope read stamps no scope on its query and its entries key on exactly\n * that token.\n */\nexport const makeRefreshHandler = (opts: RefreshHandlerOptions = {}): PayloadHandler => {\n\tconst now = opts.now ?? Date.now\n\tconst debounce = createRefreshDebounce(now)\n\n\treturn async (req: PayloadRequest) => {\n\t\tif (!req.user) {\n\t\t\treturn errorResponse(\n\t\t\t\t401,\n\t\t\t\tanalyticsError('unauthorized', 'analytics: authentication required')\n\t\t\t)\n\t\t}\n\t\tconst runtime = getRuntime(req.payload)\n\t\tif (!runtime) {\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tanalyticsError('unavailable', 'analytics: not available'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t\ttry {\n\t\t\tif (!(await readAccessFor(runtime, req))) {\n\t\t\t\treturn errorResponse(403, analyticsError('forbidden', 'analytics: read access denied'))\n\t\t\t}\n\t\t\tconst read = await readCappedBody(req, MAX_REFRESH_BODY_BYTES)\n\t\t\tif (!read.ok) {\n\t\t\t\treturn read.reason === 'too-large'\n\t\t\t\t\t? errorResponse(\n\t\t\t\t\t\t\t413,\n\t\t\t\t\t\t\tanalyticsError('payload_too_large', 'analytics: the refresh body is too large')\n\t\t\t\t\t\t)\n\t\t\t\t\t: errorResponse(\n\t\t\t\t\t\t\t400,\n\t\t\t\t\t\t\tanalyticsError(\n\t\t\t\t\t\t\t\t'invalid_param',\n\t\t\t\t\t\t\t\t'analytics: the refresh body could not be read',\n\t\t\t\t\t\t\t\t'scope'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t)\n\t\t\t}\n\t\t\tconst body = parseBody(read.body)\n\t\t\tif (!body.ok) {\n\t\t\t\treturn errorResponse(\n\t\t\t\t\t400,\n\t\t\t\t\tanalyticsError('invalid_param', 'analytics: scope must be a string', 'scope')\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst requested = await resolveRequestedScope({\n\t\t\t\truntime,\n\t\t\t\treq,\n\t\t\t\traw: body.scope ?? null,\n\t\t\t\tplatformRead: platformReadGate(runtime, req),\n\t\t\t})\n\t\t\tif (!requested.ok) {\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'untrusted_scope',\n\t\t\t\t\t\t'analytics: scope is not permitted for this request',\n\t\t\t\t\t\t'scope'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst scope = requested.scope === PLATFORM_SCOPE ? null : requested.scope\n\t\t\tconst key = epochKeyFor(scope)\n\t\t\tif (!debounce.allows(key)) {\n\t\t\t\tconst debounced: RefreshResponse = { epoch: await cacheEpochFor(runtime, scope) }\n\t\t\t\treturn Response.json(debounced, { headers: NO_STORE })\n\t\t\t}\n\t\t\tconst epoch = await (runtime.epoch?.bump(scope) ?? Promise.resolve(INITIAL_EPOCH))\n\t\t\tdebounce.record(key)\n\t\t\tconst answer: RefreshResponse = { epoch }\n\t\t\treturn Response.json(answer, { headers: NO_STORE })\n\t\t} catch (err) {\n\t\t\t// A token that cannot be raised leaves the old numbers being served, which is a\n\t\t\t// retry rather than anything the caller can fix.\n\t\t\treq.payload.logger?.warn(`analytics: cache refresh failed: ${String(err)}`)\n\t\t\treturn errorResponse(\n\t\t\t\t503,\n\t\t\t\tanalyticsError('unavailable', 'analytics: the cache could not be refreshed'),\n\t\t\t\tRETRY_AFTER\n\t\t\t)\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;AAaA,MAAa,yBAAyB,IAAI;;;;;;;;AAS1C,MAAa,sBAAsB;;;;;;AAqBnC,MAAa,yBACZ,KACA,WAAmB,wBACE;CACrB,MAAM,2BAAW,IAAI,IAAoB;CACzC,OAAO;EACN,OAAO,KAAK;GACX,MAAM,OAAO,SAAS,IAAI,GAAG;GAC7B,OAAO,SAAS,KAAA,KAAa,IAAI,IAAI,QAAQ;EAC9C;EACA,OAAO,KAAK;GACX,MAAM,KAAK,IAAI;GACf,KAAK,MAAM,CAAC,MAAM,SAAS,UAC1B,IAAI,KAAK,QAAQ,UAChB,SAAS,OAAO,IAAI;GAGtB,SAAS,IAAI,KAAK,EAAE;EACrB;EACA,IAAI,OAAO;GACV,OAAO,SAAS;EACjB;CACD;AACD;;;;;;AASA,MAAM,aAAa,UAAmC;CACrD,IAAI,MAAM,eAAe,GACxB,OAAO,EAAE,IAAI,KAAK;CAEnB,IAAI;CACJ,IAAI;EACH,SAAS,KAAK,MAAM,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;CACpD,QAAQ;EACP,OAAO,EAAE,IAAI,KAAK;CACnB;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAC5C,OAAO,EAAE,IAAI,KAAK;CAEnB,IAAI,EAAE,WAAW,SAChB,OAAO,EAAE,IAAI,KAAK;CAEnB,MAAM,QAAiB,OAAO;CAC9B,IAAI,UAAU,KAAA,KAAa,UAAU,MACpC,OAAO,EAAE,IAAI,KAAK;CAEnB,OAAO,OAAO,UAAU,WAAW;EAAE,IAAI;EAAM;CAAM,IAAI,EAAE,IAAI,MAAM;AACtE;;;;;;;;;;;;;AAcA,MAAa,sBAAsB,OAA8B,CAAC,MAAsB;CAEvF,MAAM,WAAW,sBADL,KAAK,OAAO,KAAK,GACa;CAE1C,OAAO,OAAO,QAAwB;EACrC,IAAI,CAAC,IAAI,MACR,OAAO,cACN,KACA,eAAe,gBAAgB,oCAAoC,CACpE;EAED,MAAM,UAAU,WAAW,IAAI,OAAO;EACtC,IAAI,CAAC,SACJ,OAAO,cACN,KACA,eAAe,eAAe,0BAA0B,GACxD,WACD;EAED,IAAI;GACH,IAAI,CAAE,MAAM,cAAc,SAAS,GAAG,GACrC,OAAO,cAAc,KAAK,eAAe,aAAa,+BAA+B,CAAC;GAEvF,MAAM,OAAO,MAAM,eAAe,KAAK,sBAAsB;GAC7D,IAAI,CAAC,KAAK,IACT,OAAO,KAAK,WAAW,cACpB,cACA,KACA,eAAe,qBAAqB,0CAA0C,CAC/E,IACC,cACA,KACA,eACC,iBACA,iDACA,OACD,CACD;GAEH,MAAM,OAAO,UAAU,KAAK,IAAI;GAChC,IAAI,CAAC,KAAK,IACT,OAAO,cACN,KACA,eAAe,iBAAiB,qCAAqC,OAAO,CAC7E;GAED,MAAM,YAAY,MAAM,sBAAsB;IAC7C;IACA;IACA,KAAK,KAAK,SAAS;IACnB,cAAc,iBAAiB,SAAS,GAAG;GAC5C,CAAC;GACD,IAAI,CAAC,UAAU,IACd,OAAO,cACN,KACA,eACC,mBACA,sDACA,OACD,CACD;GAED,MAAM,QAAQ,UAAU,UAAA,MAA2B,OAAO,UAAU;GACpE,MAAM,MAAM,YAAY,KAAK;GAC7B,IAAI,CAAC,SAAS,OAAO,GAAG,GAAG;IAC1B,MAAM,YAA6B,EAAE,OAAO,MAAM,cAAc,SAAS,KAAK,EAAE;IAChF,OAAO,SAAS,KAAK,WAAW,EAAE,SAAS,SAAS,CAAC;GACtD;GACA,MAAM,QAAQ,OAAO,QAAQ,OAAO,KAAK,KAAK,KAAK,QAAQ,QAAA,GAAqB;GAChF,SAAS,OAAO,GAAG;GACnB,MAAM,SAA0B,EAAE,MAAM;GACxC,OAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,SAAS,CAAC;EACnD,SAAS,KAAK;GAGb,IAAI,QAAQ,QAAQ,KAAK,oCAAoC,OAAO,GAAG,GAAG;GAC1E,OAAO,cACN,KACA,eAAe,eAAe,6CAA6C,GAC3E,WACD;EACD;CACD;AACD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import { Payload, PayloadRequest } from "payload";
|
package/dist/plugin/runtime.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import "../core/contract.js";
|
|
1
2
|
//#region src/plugin/runtime.ts
|
|
2
3
|
/**
|
|
3
4
|
* Stored on the Payload instance (not a module global) so the runtime survives the
|
|
@@ -13,9 +14,40 @@ const setRuntime = (payload, runtime) => {
|
|
|
13
14
|
const getRuntime = (payload) => payload[RUNTIME_KEY];
|
|
14
15
|
const resolveScopeFor = (runtime, req) => runtime.resolveScope?.(req) ?? Promise.resolve(null);
|
|
15
16
|
const resolveTimezoneFor = (runtime, req, scope) => runtime.resolveTimezone?.(req, scope) ?? Promise.resolve("UTC");
|
|
17
|
+
/**
|
|
18
|
+
* The reporting timezone of a request, resolving its scope first and falling back to UTC
|
|
19
|
+
* when the plugin is not booted or resolution throws. Callers that must interpret a
|
|
20
|
+
* client-supplied or stored calendar day before the read begins use this; a read path
|
|
21
|
+
* already holding a resolved scope calls {@link resolveTimezoneFor} directly.
|
|
22
|
+
*/
|
|
23
|
+
const requestTimezone = async (req) => {
|
|
24
|
+
const runtime = getRuntime(req.payload);
|
|
25
|
+
if (!runtime) return "UTC";
|
|
26
|
+
try {
|
|
27
|
+
const scope = await resolveScopeFor(runtime, req);
|
|
28
|
+
return await resolveTimezoneFor(runtime, req, scope === "*" ? null : scope);
|
|
29
|
+
} catch {
|
|
30
|
+
return "UTC";
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
/** The scope's cache epoch token, the initial one wherever the runtime carries no store. */
|
|
34
|
+
const cacheEpochFor = (runtime, scope) => runtime.epoch?.get(scope) ?? Promise.resolve("0");
|
|
16
35
|
const resolveRegistryFor = (runtime, args) => runtime.resolveRegistry?.(args) ?? Promise.resolve(runtime.registry);
|
|
36
|
+
const resolveGoalsFor = (runtime, req, scope) => runtime.resolveGoals?.(req, scope) ?? Promise.resolve(runtime.goals ?? []);
|
|
37
|
+
const resolveGoalsDetailedFor = (runtime, req, scope) => runtime.resolveGoalsDetailed?.(req, scope) ?? Promise.resolve((runtime.goals ?? []).map((goal) => ({
|
|
38
|
+
goal,
|
|
39
|
+
source: "config"
|
|
40
|
+
})));
|
|
41
|
+
const readAccessFor = async (runtime, req) => runtime.readAccess ? await runtime.readAccess({ req }) : Boolean(req.user);
|
|
17
42
|
const platformReadFor = async (runtime, req) => runtime.platformRead ? await runtime.platformRead({ req }) : Boolean(req.user);
|
|
43
|
+
const platformReadGate = (runtime, req) => {
|
|
44
|
+
let pending;
|
|
45
|
+
return () => {
|
|
46
|
+
pending ??= platformReadFor(runtime, req);
|
|
47
|
+
return pending;
|
|
48
|
+
};
|
|
49
|
+
};
|
|
18
50
|
//#endregion
|
|
19
|
-
export { getRuntime, platformReadFor, resolveRegistryFor, resolveScopeFor, resolveTimezoneFor, setRuntime };
|
|
51
|
+
export { cacheEpochFor, getRuntime, platformReadFor, platformReadGate, readAccessFor, requestTimezone, resolveGoalsDetailedFor, resolveGoalsFor, resolveRegistryFor, resolveScopeFor, resolveTimezoneFor, setRuntime };
|
|
20
52
|
|
|
21
53
|
//# sourceMappingURL=runtime.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { ResolvedBinding } from '../binding/types'\nimport type { AdapterRegistry, RegistryResolver, ResolveRegistryArgs } from '../core/registry'\nimport type { Engine } from '../surfacing/engine'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/** The plugin's scopeResolver bound at init; absent runtimes resolve null. */\n\tresolveScope?: (req: PayloadRequest) => Promise<string | null>\n\t/** The plugin's reportingTimezone bound at init; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/**\n\t * Ids of the config-time adapters shared by every scope (the ones passed to\n\t * `adapters` in plugin options). Runtime provider adapters (resolved per scope\n\t * from the providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/** Gate for cross-scope reads; absent runtimes require an authenticated user. */\n\tplatformRead?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\n}\n\n/**\n * Stored on the Payload instance (not a module global) so the runtime survives the\n * separate `.` and `/rsc` bundles a consumer loads: a server-component bundle that\n * imported its own copy of a module-level map would never see what the plugin wrote.\n * `Symbol.for` keys into the cross-realm global symbol registry, so both bundles\n * resolve the same key on the same `payload` object.\n */\nconst RUNTIME_KEY = Symbol.for('@10x-media/analytics/runtime')\n\ntype RuntimeHost = { [RUNTIME_KEY]?: AnalyticsRuntime }\n\nexport const setRuntime = (payload: Payload, runtime: AnalyticsRuntime): void => {\n\t;(payload as unknown as RuntimeHost)[RUNTIME_KEY] = runtime\n}\n\nexport const getRuntime = (payload: Payload): AnalyticsRuntime | undefined =>\n\t(payload as unknown as RuntimeHost)[RUNTIME_KEY]\n\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => runtime.resolveScope?.(req) ?? Promise.resolve(null)\n\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => runtime.resolveTimezone?.(req, scope) ?? Promise.resolve(DEFAULT_TIMEZONE)\n\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<AdapterRegistry> => runtime.resolveRegistry?.(args) ?? Promise.resolve(runtime.registry)\n\nexport const platformReadFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<boolean> =>\n\truntime.platformRead ? await runtime.platformRead({ req }) : Boolean(req.user)\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"runtime.js","names":[],"sources":["../../src/plugin/runtime.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { ResolvedBinding } from '../binding/types'\nimport { PLATFORM_SCOPE } from '../core/contract'\nimport type { CaptureSlotOption, ConsentPolicy, ResolvedAutoCapture } from '../core/options'\nimport type { AdapterRegistry, RegistryResolver, ResolveRegistryArgs } from '../core/registry'\nimport type { ServerTrack } from '../core/serverEvent'\nimport type { GoalsResolver, ResolvedGoal } from '../goals/resolver'\nimport type { Goal } from '../goals/types'\nimport type { Engine } from '../surfacing/engine'\nimport { type EpochStore, INITIAL_EPOCH } from '../surfacing/epoch'\nimport { DEFAULT_TIMEZONE } from '../timeframe/tz'\n\nexport interface AnalyticsRuntime {\n\tregistry: AdapterRegistry\n\t/** Per-scope adapter resolution; absent runtimes fall back to the static registry. */\n\tresolveRegistry?: RegistryResolver\n\t/** The plugin's scopeResolver bound at init; absent runtimes resolve null. */\n\tresolveScope?: (req: PayloadRequest) => Promise<string | null>\n\t/** The plugin's reportingTimezone bound at init; absent runtimes resolve 'UTC'. */\n\tresolveTimezone?: (req: PayloadRequest, scope?: string | null) => Promise<string>\n\t/** Id of the config adapter shared by every scope, when one is designated. */\n\tplatformAdapterId?: string\n\t/** `capture.slots` overrides naming the adapter that fills each capture slot. */\n\tcaptureSlots?: { global?: CaptureSlotOption; tenant?: CaptureSlotOption }\n\t/**\n\t * `capture.paths` overrides for a slot's mount. Unset, the tracker config derives the\n\t * runtime proxy mount; set when the slot is served through Next rewrites instead.\n\t */\n\tcapturePaths?: { global?: string; tenant?: string }\n\t/**\n\t * Whether a slot's tracker waits for consent, evaluated per request-resolved adapter.\n\t * Absent runtimes fall back to the default: no gate for native, one for a vendor.\n\t */\n\tconsentFor?: ConsentPolicy\n\t/** Browser auto-capture toggles handed to the tracker; absent runtimes default all on. */\n\tautoCapture?: ResolvedAutoCapture\n\t/** Config goals, and the fallback wherever the merged resolution is unavailable. */\n\tgoals?: Goal[]\n\t/**\n\t * Config goals merged with the goals collection for a request's scope. Absent runtimes\n\t * fall back to `goals`.\n\t */\n\tresolveGoals?: GoalsResolver['resolve']\n\t/** The same merge, each goal tagged with where it came from. */\n\tresolveGoalsDetailed?: GoalsResolver['resolveDetailed']\n\t/** Slug of the goals collection when the install enabled it; the picker links to it. */\n\tgoalsCollectionSlug?: string\n\t/**\n\t * Records an event from server code, through whichever registered adapter accepts\n\t * server events. Rejects with an `AnalyticsTrackError` when none does.\n\t */\n\ttrack?: ServerTrack\n\t/**\n\t * Where the ingest endpoint listens, relative to `routes.api`, lifted at init from the\n\t * adapter that registered one. Absent runtimes fall back to the default mount.\n\t */\n\tingestPath?: string\n\t/**\n\t * `capture.proxy` limits for the runtime capture proxy. Deliberately separate from\n\t * `cache.timeoutMs`: that is a per-read provider deadline for authenticated dashboard\n\t * queries, this is a public request path with entirely different traffic.\n\t */\n\tcaptureProxy?: { timeoutMs: number; maxBodyBytes: number }\n\t/** The plugin's `trustedProxyHops`, read wherever a request's client address is. */\n\ttrustedProxyHops?: number\n\t/** True when the app configured a scopeResolver (scoped install); mirrors `resolved.scoped`. */\n\tscoped?: boolean\n\t/**\n\t * Ids of the config-time adapters shared by every scope (the ones passed to\n\t * `adapters` in plugin options). Runtime provider adapters (resolved per scope\n\t * from the providers collection or `providers.resolve`) are never in it.\n\t */\n\tconfigAdapterIds: ReadonlySet<string>\n\t/** Gate for cross-scope reads; absent runtimes require an authenticated user. */\n\tplatformRead?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\t/** Gate for the query endpoint; absent runtimes require an authenticated user. */\n\treadAccess?: (args: { req: PayloadRequest }) => boolean | Promise<boolean>\n\tbindings: Record<string, ResolvedBinding>\n\tengine: Engine\n\t/**\n\t * The per-scope cache epoch the engine keys on, shared with the reads that build their\n\t * own keys. Absent runtimes key on the initial token throughout.\n\t */\n\tepoch?: EpochStore\n\t/** Explicit TTL overrides; when a value is unset the adapter's recommendedTtl applies. */\n\tttl: { aggregate?: number; realtime?: number }\n\t/** Widget period-over-period comparison; false skips the previous-window read. */\n\tcomparison: boolean\n}\n\n/**\n * Stored on the Payload instance (not a module global) so the runtime survives the\n * separate `.` and `/rsc` bundles a consumer loads: a server-component bundle that\n * imported its own copy of a module-level map would never see what the plugin wrote.\n * `Symbol.for` keys into the cross-realm global symbol registry, so both bundles\n * resolve the same key on the same `payload` object.\n */\nconst RUNTIME_KEY = Symbol.for('@10x-media/analytics/runtime')\n\ntype RuntimeHost = { [RUNTIME_KEY]?: AnalyticsRuntime }\n\nexport const setRuntime = (payload: Payload, runtime: AnalyticsRuntime): void => {\n\t;(payload as unknown as RuntimeHost)[RUNTIME_KEY] = runtime\n}\n\nexport const getRuntime = (payload: Payload): AnalyticsRuntime | undefined =>\n\t(payload as unknown as RuntimeHost)[RUNTIME_KEY]\n\nexport const resolveScopeFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<string | null> => runtime.resolveScope?.(req) ?? Promise.resolve(null)\n\nexport const resolveTimezoneFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<string> => runtime.resolveTimezone?.(req, scope) ?? Promise.resolve(DEFAULT_TIMEZONE)\n\n/**\n * The reporting timezone of a request, resolving its scope first and falling back to UTC\n * when the plugin is not booted or resolution throws. Callers that must interpret a\n * client-supplied or stored calendar day before the read begins use this; a read path\n * already holding a resolved scope calls {@link resolveTimezoneFor} directly.\n */\nexport const requestTimezone = async (req: PayloadRequest): Promise<string> => {\n\tconst runtime = getRuntime(req.payload)\n\tif (!runtime) {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n\ttry {\n\t\t// The cross-scope marker is not a scope a reporting timezone can be resolved for;\n\t\t// `resolveReadContext` narrows it to null the same way.\n\t\tconst scope = await resolveScopeFor(runtime, req)\n\t\treturn await resolveTimezoneFor(runtime, req, scope === PLATFORM_SCOPE ? null : scope)\n\t} catch {\n\t\treturn DEFAULT_TIMEZONE\n\t}\n}\n\n/** The scope's cache epoch token, the initial one wherever the runtime carries no store. */\nexport const cacheEpochFor = (runtime: AnalyticsRuntime, scope?: string | null): Promise<string> =>\n\truntime.epoch?.get(scope) ?? Promise.resolve(INITIAL_EPOCH)\n\nexport const resolveRegistryFor = (\n\truntime: AnalyticsRuntime,\n\targs: ResolveRegistryArgs\n): Promise<AdapterRegistry> => runtime.resolveRegistry?.(args) ?? Promise.resolve(runtime.registry)\n\nexport const resolveGoalsFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<Goal[]> => runtime.resolveGoals?.(req, scope) ?? Promise.resolve(runtime.goals ?? [])\n\nexport const resolveGoalsDetailedFor = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tscope?: string | null\n): Promise<ResolvedGoal[]> =>\n\truntime.resolveGoalsDetailed?.(req, scope) ??\n\tPromise.resolve((runtime.goals ?? []).map((goal) => ({ goal, source: 'config' as const })))\n\nexport const readAccessFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<boolean> => (runtime.readAccess ? await runtime.readAccess({ req }) : Boolean(req.user))\n\nexport const platformReadFor = async (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): Promise<boolean> =>\n\truntime.platformRead ? await runtime.platformRead({ req }) : Boolean(req.user)\n\n/** A `platformRead` decision evaluated at most once, however many gates consult it. */\nexport type PlatformReadGate = () => Promise<boolean>\n\nexport const platformReadGate = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest\n): PlatformReadGate => {\n\tlet pending: Promise<boolean> | undefined\n\treturn () => {\n\t\tpending ??= platformReadFor(runtime, req)\n\t\treturn pending\n\t}\n}\n"],"mappings":";;;;;;;;;AAiGA,MAAM,cAAc,OAAO,IAAI,8BAA8B;AAI7D,MAAa,cAAc,SAAkB,YAAoC;CAC/E,QAAoC,eAAe;AACrD;AAEA,MAAa,cAAc,YACzB,QAAmC;AAErC,MAAa,mBACZ,SACA,QAC4B,QAAQ,eAAe,GAAG,KAAK,QAAQ,QAAQ,IAAI;AAEhF,MAAa,sBACZ,SACA,KACA,UACqB,QAAQ,kBAAkB,KAAK,KAAK,KAAK,QAAQ,QAAA,KAAwB;;;;;;;AAQ/F,MAAa,kBAAkB,OAAO,QAAyC;CAC9E,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,IAAI,CAAC,SACJ,OAAA;CAED,IAAI;EAGH,MAAM,QAAQ,MAAM,gBAAgB,SAAS,GAAG;EAChD,OAAO,MAAM,mBAAmB,SAAS,KAAK,UAAA,MAA2B,OAAO,KAAK;CACtF,QAAQ;EACP,OAAA;CACD;AACD;;AAGA,MAAa,iBAAiB,SAA2B,UACxD,QAAQ,OAAO,IAAI,KAAK,KAAK,QAAQ,QAAA,GAAqB;AAE3D,MAAa,sBACZ,SACA,SAC8B,QAAQ,kBAAkB,IAAI,KAAK,QAAQ,QAAQ,QAAQ,QAAQ;AAElG,MAAa,mBACZ,SACA,KACA,UACqB,QAAQ,eAAe,KAAK,KAAK,KAAK,QAAQ,QAAQ,QAAQ,SAAS,CAAC,CAAC;AAE/F,MAAa,2BACZ,SACA,KACA,UAEA,QAAQ,uBAAuB,KAAK,KAAK,KACzC,QAAQ,SAAS,QAAQ,SAAS,CAAC,GAAG,KAAK,UAAU;CAAE;CAAM,QAAQ;AAAkB,EAAE,CAAC;AAE3F,MAAa,gBAAgB,OAC5B,SACA,QACuB,QAAQ,aAAa,MAAM,QAAQ,WAAW,EAAE,IAAI,CAAC,IAAI,QAAQ,IAAI,IAAI;AAEjG,MAAa,kBAAkB,OAC9B,SACA,QAEA,QAAQ,eAAe,MAAM,QAAQ,aAAa,EAAE,IAAI,CAAC,IAAI,QAAQ,IAAI,IAAI;AAK9E,MAAa,oBACZ,SACA,QACsB;CACtB,IAAI;CACJ,aAAa;EACZ,YAAY,gBAAgB,SAAS,GAAG;EACxC,OAAO;CACR;AACD"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/plugin/scopeChange.ts
|
|
2
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
3
|
+
/**
|
|
4
|
+
* A document's scope as the read paths spell it. An unscoped install has no scope field at
|
|
5
|
+
* all, which reads as null, the same value its reads carry; a relationship-typed field can
|
|
6
|
+
* arrive populated, so its id is taken rather than the object.
|
|
7
|
+
*/
|
|
8
|
+
const docScope = (doc, scopeField) => {
|
|
9
|
+
if (!isRecord(doc)) return null;
|
|
10
|
+
const value = doc[scopeField];
|
|
11
|
+
if (typeof value === "string") return value === "" ? null : value;
|
|
12
|
+
if (typeof value === "number") return String(value);
|
|
13
|
+
if (isRecord(value)) {
|
|
14
|
+
const id = value.id;
|
|
15
|
+
return typeof id === "string" || typeof id === "number" ? String(id) : null;
|
|
16
|
+
}
|
|
17
|
+
return null;
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
export { docScope };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=scopeChange.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scopeChange.js","names":[],"sources":["../../src/plugin/scopeChange.ts"],"sourcesContent":["/** What a providers or goals document change tells the plugin about the scopes it touched. */\nexport interface ScopeChange {\n\tscope: string | null\n\t/** The scope the document was in before an update, so a move invalidates both. */\n\tpreviousScope?: string | null\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n\ttypeof value === 'object' && value !== null\n\n/**\n * A document's scope as the read paths spell it. An unscoped install has no scope field at\n * all, which reads as null, the same value its reads carry; a relationship-typed field can\n * arrive populated, so its id is taken rather than the object.\n */\nexport const docScope = (doc: unknown, scopeField: string): string | null => {\n\tif (!isRecord(doc)) {\n\t\treturn null\n\t}\n\tconst value = doc[scopeField]\n\tif (typeof value === 'string') {\n\t\treturn value === '' ? null : value\n\t}\n\tif (typeof value === 'number') {\n\t\treturn String(value)\n\t}\n\tif (isRecord(value)) {\n\t\tconst id = value.id\n\t\treturn typeof id === 'string' || typeof id === 'number' ? String(id) : null\n\t}\n\treturn null\n}\n"],"mappings":";AAOA,MAAM,YAAY,UACjB,OAAO,UAAU,YAAY,UAAU;;;;;;AAOxC,MAAa,YAAY,KAAc,eAAsC;CAC5E,IAAI,CAAC,SAAS,GAAG,GAChB,OAAO;CAER,MAAM,QAAQ,IAAI;CAClB,IAAI,OAAO,UAAU,UACpB,OAAO,UAAU,KAAK,OAAO;CAE9B,IAAI,OAAO,UAAU,UACpB,OAAO,OAAO,KAAK;CAEpB,IAAI,SAAS,KAAK,GAAG;EACpB,MAAM,KAAK,MAAM;EACjB,OAAO,OAAO,OAAO,YAAY,OAAO,OAAO,WAAW,OAAO,EAAE,IAAI;CACxE;CACA,OAAO;AACR"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/plugin/scopeFieldBoot.ts
|
|
2
|
+
/** Whether a top-level field of that name exists, looking through presentational wrappers. */
|
|
3
|
+
const hasField = (fields, name) => fields.some((field) => {
|
|
4
|
+
if ("name" in field && field.name) return field.name === name;
|
|
5
|
+
if ("fields" in field) return hasField(field.fields, name);
|
|
6
|
+
if ("tabs" in field) return field.tabs.some((tab) => !("name" in tab && tab.name) && hasField(tab.fields, name));
|
|
7
|
+
return false;
|
|
8
|
+
});
|
|
9
|
+
/**
|
|
10
|
+
* Fails the boot when a `scopeField` the plugin does not own never materialized on the
|
|
11
|
+
* collection. A tenant plugin registers its field after this plugin runs, so the check
|
|
12
|
+
* waits for the assembled config at init rather than guessing at config time.
|
|
13
|
+
*/
|
|
14
|
+
const validateScopeField = (payload, args) => {
|
|
15
|
+
const collection = payload.config.collections.find((c) => c.slug === args.slug);
|
|
16
|
+
if (!collection || hasField(collection.fields, args.scopeField)) return;
|
|
17
|
+
throw new Error(`analytics: ${args.option} "${args.scopeField}" does not exist on ${args.slug}; register the collection with your tenant plugin or use the default scope field`);
|
|
18
|
+
};
|
|
19
|
+
//#endregion
|
|
20
|
+
export { validateScopeField };
|
|
21
|
+
|
|
22
|
+
//# sourceMappingURL=scopeFieldBoot.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scopeFieldBoot.js","names":[],"sources":["../../src/plugin/scopeFieldBoot.ts"],"sourcesContent":["import type { Field, Payload } from 'payload'\n\n/** Whether a top-level field of that name exists, looking through presentational wrappers. */\nconst hasField = (fields: Field[], name: string): boolean =>\n\tfields.some((field) => {\n\t\tif ('name' in field && field.name) {\n\t\t\treturn field.name === name\n\t\t}\n\t\tif ('fields' in field) {\n\t\t\treturn hasField(field.fields, name)\n\t\t}\n\t\tif ('tabs' in field) {\n\t\t\treturn field.tabs.some(\n\t\t\t\t(tab) => !('name' in tab && tab.name) && hasField(tab.fields as Field[], name)\n\t\t\t)\n\t\t}\n\t\treturn false\n\t})\n\nexport interface ValidateScopeFieldArgs {\n\t/** Option path quoted in the error, e.g. `goals.collection.scopeField`. */\n\toption: string\n\tslug: string\n\tscopeField: string\n}\n\n/**\n * Fails the boot when a `scopeField` the plugin does not own never materialized on the\n * collection. A tenant plugin registers its field after this plugin runs, so the check\n * waits for the assembled config at init rather than guessing at config time.\n */\nexport const validateScopeField = (payload: Payload, args: ValidateScopeFieldArgs): void => {\n\tconst collection = payload.config.collections.find((c) => c.slug === args.slug)\n\tif (!collection || hasField(collection.fields, args.scopeField)) {\n\t\treturn\n\t}\n\tthrow new Error(\n\t\t`analytics: ${args.option} \"${args.scopeField}\" does not exist on ${args.slug}; register the collection with your tenant plugin or use the default scope field`\n\t)\n}\n"],"mappings":";;AAGA,MAAM,YAAY,QAAiB,SAClC,OAAO,MAAM,UAAU;CACtB,IAAI,UAAU,SAAS,MAAM,MAC5B,OAAO,MAAM,SAAS;CAEvB,IAAI,YAAY,OACf,OAAO,SAAS,MAAM,QAAQ,IAAI;CAEnC,IAAI,UAAU,OACb,OAAO,MAAM,KAAK,MAChB,QAAQ,EAAE,UAAU,OAAO,IAAI,SAAS,SAAS,IAAI,QAAmB,IAAI,CAC9E;CAED,OAAO;AACR,CAAC;;;;;;AAcF,MAAa,sBAAsB,SAAkB,SAAuC;CAC3F,MAAM,aAAa,QAAQ,OAAO,YAAY,MAAM,MAAM,EAAE,SAAS,KAAK,IAAI;CAC9E,IAAI,CAAC,cAAc,SAAS,WAAW,QAAQ,KAAK,UAAU,GAC7D;CAED,MAAM,IAAI,MACT,cAAc,KAAK,OAAO,IAAI,KAAK,WAAW,sBAAsB,KAAK,KAAK,iFAC/E;AACD"}
|