@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolvePath.js","names":[],"sources":["../../src/binding/resolvePath.ts"],"sourcesContent":["import type { AnalyticsBinding, BindingContext, BindingDoc } from './types'\n\nconst getByPath = (doc: BindingDoc, dotPath: string): unknown =>\n\tdotPath.split('.').reduce<unknown>((value, key) => {\n\t\tif (value && typeof value === 'object') {\n\t\t\treturn (value as Record<string, unknown>)[key]\n\t\t}\n\t\treturn undefined\n\t}, doc)\n\nconst nonEmptyString = (value: unknown): value is string =>\n\ttypeof value === 'string' && value.length > 0\n\n/**\n * Resolve a document's analytics path. The `path` resolver wins; the `pathField`\n * value is the fallback. Returns null when neither yields a non-empty string (for\n * example an unsaved document with no slug yet).\n */\nexport const resolvePath = async (\n\tbinding: AnalyticsBinding,\n\tdoc: BindingDoc,\n\tctx: BindingContext\n): Promise<string | null> => {\n\tif (binding.path) {\n\t\tconst resolved = await binding.path(doc, ctx)\n\t\tif (nonEmptyString(resolved)) return resolved\n\t}\n\tif (binding.pathField) {\n\t\tconst value = getByPath(doc, binding.pathField)\n\t\tif (nonEmptyString(value)) return value\n\t}\n\treturn null\n}\n\nconst CACHE_KEY = '__analyticsPathCache'\n\n/**\n * Resolve the path once per (doc, request): the same `doc` reference is handed to\n * every analytics field on a document, so caching the in-flight Promise on\n * `req.context` collapses an async (possibly ancestor-walking) resolver from once per\n * field to once per document, and shares it across concurrent field renders. When the\n * request carries no context bag (incomplete reqs in tests or unusual call sites), it\n * degrades to a direct, un-memoized resolve so the result stays correct.\n */\nexport const resolvePathCached = (\n\tbinding: AnalyticsBinding,\n\tdoc: BindingDoc,\n\tctx: BindingContext\n): Promise<string | null> => {\n\tconst context = ctx.req.context as Record<string, unknown> | undefined\n\tif (!context) {\n\t\treturn resolvePath(binding, doc, ctx)\n\t}\n\tlet cache = context[CACHE_KEY] as WeakMap<BindingDoc, Promise<string | null>> | undefined\n\tif (!cache) {\n\t\tcache = new WeakMap()\n\t\tcontext[CACHE_KEY] = cache\n\t}\n\tlet cached = cache.get(doc)\n\tif (!cached) {\n\t\tcached = resolvePath(binding, doc, ctx)\n\t\tcache.set(doc, cached)\n\t}\n\treturn cached\n}\n\n/**\n * Resolve a binding's hostname filter for one document. A function hostname is\n * awaited with the same `(doc, ctx)` a path resolver receives; a nullish or empty\n * result means no hostname filter is applied to the adapter query.\n */\nexport const resolveHostname = async (\n\tbinding: AnalyticsBinding,\n\tdoc: BindingDoc,\n\tctx: BindingContext\n): Promise<string | undefined> => {\n\tif (typeof binding.hostname === 'function') {\n\t\tconst resolved = await binding.hostname(doc, ctx)\n\t\treturn nonEmptyString(resolved) ? resolved : undefined\n\t}\n\treturn binding.hostname\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"resolvePath.js","names":[],"sources":["../../src/binding/resolvePath.ts"],"sourcesContent":["import { normalizeHostname } from '../native/ingest/requestHost'\nimport type { AnalyticsBinding, BindingContext, BindingDoc } from './types'\n\nconst getByPath = (doc: BindingDoc, dotPath: string): unknown =>\n\tdotPath.split('.').reduce<unknown>((value, key) => {\n\t\tif (value && typeof value === 'object') {\n\t\t\treturn (value as Record<string, unknown>)[key]\n\t\t}\n\t\treturn undefined\n\t}, doc)\n\nconst nonEmptyString = (value: unknown): value is string =>\n\ttypeof value === 'string' && value.length > 0\n\n/**\n * Resolve a document's analytics path. The `path` resolver wins; the `pathField`\n * value is the fallback. Returns null when neither yields a non-empty string (for\n * example an unsaved document with no slug yet).\n */\nexport const resolvePath = async (\n\tbinding: AnalyticsBinding,\n\tdoc: BindingDoc,\n\tctx: BindingContext\n): Promise<string | null> => {\n\tif (binding.path) {\n\t\tconst resolved = await binding.path(doc, ctx)\n\t\tif (nonEmptyString(resolved)) return resolved\n\t}\n\tif (binding.pathField) {\n\t\tconst value = getByPath(doc, binding.pathField)\n\t\tif (nonEmptyString(value)) return value\n\t}\n\treturn null\n}\n\nconst CACHE_KEY = '__analyticsPathCache'\n\n/**\n * Resolve the path once per (doc, request): the same `doc` reference is handed to\n * every analytics field on a document, so caching the in-flight Promise on\n * `req.context` collapses an async (possibly ancestor-walking) resolver from once per\n * field to once per document, and shares it across concurrent field renders. When the\n * request carries no context bag (incomplete reqs in tests or unusual call sites), it\n * degrades to a direct, un-memoized resolve so the result stays correct.\n */\nexport const resolvePathCached = (\n\tbinding: AnalyticsBinding,\n\tdoc: BindingDoc,\n\tctx: BindingContext\n): Promise<string | null> => {\n\tconst context = ctx.req.context as Record<string, unknown> | undefined\n\tif (!context) {\n\t\treturn resolvePath(binding, doc, ctx)\n\t}\n\tlet cache = context[CACHE_KEY] as WeakMap<BindingDoc, Promise<string | null>> | undefined\n\tif (!cache) {\n\t\tcache = new WeakMap()\n\t\tcontext[CACHE_KEY] = cache\n\t}\n\tlet cached = cache.get(doc)\n\tif (!cached) {\n\t\tcached = resolvePath(binding, doc, ctx)\n\t\tcache.set(doc, cached)\n\t}\n\treturn cached\n}\n\n/**\n * A binding's hostname as the stored events spell it, since a tenant's domain field often\n * carries a scheme, a port or mixed case and the native engine compares hostnames exactly.\n * A value that is no hostname at all is passed through untouched, so a provider that filters\n * on something else keeps whatever the binding gave it.\n */\nexport const hostnameFromBinding = (raw: string): string => {\n\tlet candidate = raw\n\tif (raw.includes('://')) {\n\t\ttry {\n\t\t\tcandidate = new URL(raw).host\n\t\t} catch {\n\t\t\treturn raw\n\t\t}\n\t}\n\treturn normalizeHostname(candidate) ?? raw\n}\n\n/**\n * Resolve a binding's hostname filter for one document. A function hostname is\n * awaited with the same `(doc, ctx)` a path resolver receives; a nullish or empty\n * result means no hostname filter is applied to the adapter query.\n */\nexport const resolveHostname = async (\n\tbinding: AnalyticsBinding,\n\tdoc: BindingDoc,\n\tctx: BindingContext\n): Promise<string | undefined> => {\n\tif (typeof binding.hostname === 'function') {\n\t\tconst resolved = await binding.hostname(doc, ctx)\n\t\treturn nonEmptyString(resolved) ? hostnameFromBinding(resolved) : undefined\n\t}\n\treturn binding.hostname === undefined ? undefined : hostnameFromBinding(binding.hostname)\n}\n"],"mappings":";;AAGA,MAAM,aAAa,KAAiB,YACnC,QAAQ,MAAM,GAAG,EAAE,QAAiB,OAAO,QAAQ;CAClD,IAAI,SAAS,OAAO,UAAU,UAC7B,OAAQ,MAAkC;AAG5C,GAAG,GAAG;AAEP,MAAM,kBAAkB,UACvB,OAAO,UAAU,YAAY,MAAM,SAAS;;;;;;AAO7C,MAAa,cAAc,OAC1B,SACA,KACA,QAC4B;CAC5B,IAAI,QAAQ,MAAM;EACjB,MAAM,WAAW,MAAM,QAAQ,KAAK,KAAK,GAAG;EAC5C,IAAI,eAAe,QAAQ,GAAG,OAAO;CACtC;CACA,IAAI,QAAQ,WAAW;EACtB,MAAM,QAAQ,UAAU,KAAK,QAAQ,SAAS;EAC9C,IAAI,eAAe,KAAK,GAAG,OAAO;CACnC;CACA,OAAO;AACR;AAEA,MAAM,YAAY;;;;;;;;;AAUlB,MAAa,qBACZ,SACA,KACA,QAC4B;CAC5B,MAAM,UAAU,IAAI,IAAI;CACxB,IAAI,CAAC,SACJ,OAAO,YAAY,SAAS,KAAK,GAAG;CAErC,IAAI,QAAQ,QAAQ;CACpB,IAAI,CAAC,OAAO;EACX,wBAAQ,IAAI,QAAQ;EACpB,QAAQ,aAAa;CACtB;CACA,IAAI,SAAS,MAAM,IAAI,GAAG;CAC1B,IAAI,CAAC,QAAQ;EACZ,SAAS,YAAY,SAAS,KAAK,GAAG;EACtC,MAAM,IAAI,KAAK,MAAM;CACtB;CACA,OAAO;AACR;;;;;;;AAQA,MAAa,uBAAuB,QAAwB;CAC3D,IAAI,YAAY;CAChB,IAAI,IAAI,SAAS,KAAK,GACrB,IAAI;EACH,YAAY,IAAI,IAAI,GAAG,EAAE;CAC1B,QAAQ;EACP,OAAO;CACR;CAED,OAAO,kBAAkB,SAAS,KAAK;AACxC;;;;;;AAOA,MAAa,kBAAkB,OAC9B,SACA,KACA,QACiC;CACjC,IAAI,OAAO,QAAQ,aAAa,YAAY;EAC3C,MAAM,WAAW,MAAM,QAAQ,SAAS,KAAK,GAAG;EAChD,OAAO,eAAe,QAAQ,IAAI,oBAAoB,QAAQ,IAAI,KAAA;CACnE;CACA,OAAO,QAAQ,aAAa,KAAA,IAAY,KAAA,IAAY,oBAAoB,QAAQ,QAAQ;AACzF"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { TrackerConfig } from "./trackerConfig.js";
|
|
2
|
+
import { Payload } from "payload";
|
|
3
|
+
|
|
4
|
+
//#region src/capture/getTrackerConfig.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`
|
|
7
|
+
* itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the
|
|
8
|
+
* same request it would over HTTP. `host` is lifted onto the request because Payload
|
|
9
|
+
* derives `req.host` from the URL rather than the header, and hostname-derived scoping is
|
|
10
|
+
* the common case.
|
|
11
|
+
*
|
|
12
|
+
* A fresh request object is built on every call: `createLocalReq` mutates the one it is
|
|
13
|
+
* given, so a shared literal would accumulate another caller's locale, user, and loader.
|
|
14
|
+
*/
|
|
15
|
+
declare const getTrackerConfig: (payload: Payload, args?: {
|
|
16
|
+
headers?: Headers;
|
|
17
|
+
}) => Promise<TrackerConfig>;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { getTrackerConfig };
|
|
20
|
+
//# sourceMappingURL=getTrackerConfig.d.ts.map
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { getRuntime } from "../plugin/runtime.js";
|
|
2
|
+
import { emptyTrackerConfig, resolveTrackerConfig } from "./trackerConfig.js";
|
|
3
|
+
import { createLocalReq } from "payload";
|
|
4
|
+
//#region src/capture/getTrackerConfig.ts
|
|
5
|
+
/**
|
|
6
|
+
* Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`
|
|
7
|
+
* itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the
|
|
8
|
+
* same request it would over HTTP. `host` is lifted onto the request because Payload
|
|
9
|
+
* derives `req.host` from the URL rather than the header, and hostname-derived scoping is
|
|
10
|
+
* the common case.
|
|
11
|
+
*
|
|
12
|
+
* A fresh request object is built on every call: `createLocalReq` mutates the one it is
|
|
13
|
+
* given, so a shared literal would accumulate another caller's locale, user, and loader.
|
|
14
|
+
*/
|
|
15
|
+
const getTrackerConfig = async (payload, args) => {
|
|
16
|
+
const headers = args?.headers ?? new Headers();
|
|
17
|
+
const host = headers.get("host");
|
|
18
|
+
const req = await createLocalReq({ req: {
|
|
19
|
+
headers,
|
|
20
|
+
...host ? { host } : {}
|
|
21
|
+
} }, payload);
|
|
22
|
+
const runtime = getRuntime(payload);
|
|
23
|
+
return runtime ? resolveTrackerConfig({
|
|
24
|
+
runtime,
|
|
25
|
+
req
|
|
26
|
+
}) : emptyTrackerConfig(req);
|
|
27
|
+
};
|
|
28
|
+
//#endregion
|
|
29
|
+
export { getTrackerConfig };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=getTrackerConfig.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getTrackerConfig.js","names":[],"sources":["../../src/capture/getTrackerConfig.ts"],"sourcesContent":["import { createLocalReq, type Payload, type PayloadRequest } from 'payload'\nimport { getRuntime } from '../plugin/runtime'\nimport { emptyTrackerConfig, resolveTrackerConfig, type TrackerConfig } from './trackerConfig'\n\n/**\n * Server-side twin of the tracker endpoint, for a Next app that renders `AnalyticsScripts`\n * itself: pass the incoming request's `headers()` and the host's `scopeResolver` sees the\n * same request it would over HTTP. `host` is lifted onto the request because Payload\n * derives `req.host` from the URL rather than the header, and hostname-derived scoping is\n * the common case.\n *\n * A fresh request object is built on every call: `createLocalReq` mutates the one it is\n * given, so a shared literal would accumulate another caller's locale, user, and loader.\n */\nexport const getTrackerConfig = async (\n\tpayload: Payload,\n\targs?: { headers?: Headers }\n): Promise<TrackerConfig> => {\n\tconst headers = args?.headers ?? new Headers()\n\tconst host = headers.get('host')\n\tconst req = await createLocalReq(\n\t\t{ req: { headers, ...(host ? { host } : {}) } as Partial<PayloadRequest> },\n\t\tpayload\n\t)\n\tconst runtime = getRuntime(payload)\n\treturn runtime ? resolveTrackerConfig({ runtime, req }) : emptyTrackerConfig(req)\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,mBAAmB,OAC/B,SACA,SAC4B;CAC5B,MAAM,UAAU,MAAM,WAAW,IAAI,QAAQ;CAC7C,MAAM,OAAO,QAAQ,IAAI,MAAM;CAC/B,MAAM,MAAM,MAAM,eACjB,EAAE,KAAK;EAAE;EAAS,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;CAAG,EAA6B,GACzE,OACD;CACA,MAAM,UAAU,WAAW,OAAO;CAClC,OAAO,UAAU,qBAAqB;EAAE;EAAS;CAAI,CAAC,IAAI,mBAAmB,GAAG;AACjF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/capture/mountPath.ts
|
|
2
|
+
/**
|
|
3
|
+
* One mount path, canonical: a leading slash, no trailing one, `/` for what reduces to
|
|
4
|
+
* the site root. Shared by the Next rewrites helper and the tracker config resolver so a
|
|
5
|
+
* `capture.paths` override and the rewrite it was mounted at cannot disagree over a slash.
|
|
6
|
+
*/
|
|
7
|
+
const normalizeMountPath = (path) => {
|
|
8
|
+
const trimmed = (path.startsWith("/") ? path : `/${path}`).replace(/\/+$/, "");
|
|
9
|
+
return trimmed === "" ? "/" : trimmed;
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { normalizeMountPath };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=mountPath.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mountPath.js","names":[],"sources":["../../src/capture/mountPath.ts"],"sourcesContent":["/**\n * One mount path, canonical: a leading slash, no trailing one, `/` for what reduces to\n * the site root. Shared by the Next rewrites helper and the tracker config resolver so a\n * `capture.paths` override and the rewrite it was mounted at cannot disagree over a slash.\n */\nexport const normalizeMountPath = (path: string): string => {\n\tconst withLeading = path.startsWith('/') ? path : `/${path}`\n\tconst trimmed = withLeading.replace(/\\/+$/, '')\n\treturn trimmed === '' ? '/' : trimmed\n}\n"],"mappings":";;;;;;AAKA,MAAa,sBAAsB,SAAyB;CAE3D,MAAM,WADc,KAAK,WAAW,GAAG,IAAI,OAAO,IAAI,QAC1B,QAAQ,QAAQ,EAAE;CAC9C,OAAO,YAAY,KAAK,MAAM;AAC/B"}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { clientIpFromHeaders } from "../native/ingest/clientIp.js";
|
|
2
|
+
import { PROXY_PATH } from "../plugin/paths.js";
|
|
3
|
+
import { getRuntime } from "../plugin/runtime.js";
|
|
4
|
+
import { buildDownstreamHeaders, buildUpstreamHeaders, matchProxyRoute } from "./proxyRoutes.js";
|
|
5
|
+
import { readCappedBody } from "./requestBody.js";
|
|
6
|
+
import { isCaptureSlot, resolveSlotAdapter } from "./slots.js";
|
|
7
|
+
//#region src/capture/proxyEndpoint.ts
|
|
8
|
+
/** Deadline for the upstream response headers, not for the body download. */
|
|
9
|
+
const DEFAULT_PROXY_TIMEOUT_MS = 1e4;
|
|
10
|
+
/** PostHog batches carrying session-replay data routinely exceed 64 KB. */
|
|
11
|
+
const DEFAULT_PROXY_MAX_BODY_BYTES = 1024 * 1024;
|
|
12
|
+
/** The path pattern the proxy is registered at, one entry per method. */
|
|
13
|
+
const PROXY_ENDPOINT_PATH = `${PROXY_PATH}/:slot/:path*`;
|
|
14
|
+
/**
|
|
15
|
+
* Payload matches an endpoint by exact method, and `@payloadcms/next` only routes these
|
|
16
|
+
* six, so the handler is registered for all of them: the three it serves, and the three
|
|
17
|
+
* it must answer 405 for rather than leaving to Payload's generic 404.
|
|
18
|
+
*/
|
|
19
|
+
const PROXY_METHODS = [
|
|
20
|
+
"get",
|
|
21
|
+
"post",
|
|
22
|
+
"options",
|
|
23
|
+
"put",
|
|
24
|
+
"patch",
|
|
25
|
+
"delete"
|
|
26
|
+
];
|
|
27
|
+
const ALLOWED_METHODS = "GET, POST, OPTIONS";
|
|
28
|
+
const SERVED_METHODS = new Set([
|
|
29
|
+
"GET",
|
|
30
|
+
"POST",
|
|
31
|
+
"OPTIONS"
|
|
32
|
+
]);
|
|
33
|
+
/**
|
|
34
|
+
* The proxy's only error answer, and the one endpoint here that sends no error envelope:
|
|
35
|
+
* it relays a vendor SDK's own traffic, and that SDK, not admin code, reads the answer.
|
|
36
|
+
*/
|
|
37
|
+
const empty = (status, headers) => new Response(null, {
|
|
38
|
+
status,
|
|
39
|
+
headers
|
|
40
|
+
});
|
|
41
|
+
/**
|
|
42
|
+
* The request path relative to the slot mount, still percent-encoded: path-to-regexp
|
|
43
|
+
* decodes it per segment, so re-encoding here would turn legal path characters
|
|
44
|
+
* (`,=+:@`) into escapes the vendor never sent.
|
|
45
|
+
*/
|
|
46
|
+
const subPath = (req, slot) => {
|
|
47
|
+
const pathname = req.pathname ?? (req.url ? new URL(req.url).pathname : "");
|
|
48
|
+
const mount = `${PROXY_PATH}/${slot}`;
|
|
49
|
+
const start = pathname.indexOf(mount);
|
|
50
|
+
if (start === -1) return "/";
|
|
51
|
+
return pathname.slice(start + mount.length) || "/";
|
|
52
|
+
};
|
|
53
|
+
const proxyLimits = (runtime) => ({
|
|
54
|
+
timeoutMs: runtime.captureProxy?.timeoutMs ?? 1e4,
|
|
55
|
+
maxBodyBytes: runtime.captureProxy?.maxBodyBytes ?? 1048576
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Public first-party proxy for a slot's vendor tracker: `${PROXY_PATH}/:slot/:path*`,
|
|
59
|
+
* registered for every method Payload routes.
|
|
60
|
+
*
|
|
61
|
+
* The only URLs it ever fetches are compiled from the slot adapter's own
|
|
62
|
+
* `capture.proxy.routes` templates, so an unfilled slot, an adapter without capture, or
|
|
63
|
+
* a path outside the declared routes is a 404 and nothing leaves the server. Credentials
|
|
64
|
+
* (`cookie`, `authorization`) never go upstream and `set-cookie` never comes back; a
|
|
65
|
+
* body over `capture.proxy.maxBodyBytes` is refused with 413 and one that dies in
|
|
66
|
+
* transit with 400, both before anything is forwarded; upstream failures answer 502
|
|
67
|
+
* without echoing the URL or the error.
|
|
68
|
+
*/
|
|
69
|
+
const makeProxyHandler = () => async (req) => {
|
|
70
|
+
const method = (req.method ?? "get").toUpperCase();
|
|
71
|
+
if (!SERVED_METHODS.has(method)) return empty(405, { allow: ALLOWED_METHODS });
|
|
72
|
+
if (method === "OPTIONS") return empty(204, { allow: ALLOWED_METHODS });
|
|
73
|
+
const runtime = getRuntime(req.payload);
|
|
74
|
+
const slot = req.routeParams?.slot;
|
|
75
|
+
if (!runtime || typeof slot !== "string" || !isCaptureSlot(slot)) return empty(404);
|
|
76
|
+
const adapter = await resolveSlotAdapter(runtime, req, slot);
|
|
77
|
+
const descriptor = adapter?.capture?.proxy;
|
|
78
|
+
if (!descriptor || descriptor.routes.length === 0) return empty(404);
|
|
79
|
+
const matched = matchProxyRoute(descriptor.routes, subPath(req, slot), { trailingSlashes: descriptor.trailingSlashes });
|
|
80
|
+
if (!matched) return empty(404);
|
|
81
|
+
const { upstreamUrl } = matched;
|
|
82
|
+
const search = req.search ?? (req.url ? new URL(req.url).search : "");
|
|
83
|
+
if (search && search !== "?") {
|
|
84
|
+
const incoming = search.startsWith("?") ? search.slice(1) : search;
|
|
85
|
+
upstreamUrl.search = upstreamUrl.search ? `${upstreamUrl.search}&${incoming}` : `?${incoming}`;
|
|
86
|
+
}
|
|
87
|
+
const limits = proxyLimits(runtime);
|
|
88
|
+
let body;
|
|
89
|
+
if (method === "POST") {
|
|
90
|
+
const read = await readCappedBody(req, limits.maxBodyBytes);
|
|
91
|
+
if (!read.ok) return empty(read.reason === "too-large" ? 413 : 400);
|
|
92
|
+
body = read.body;
|
|
93
|
+
}
|
|
94
|
+
const controller = new AbortController();
|
|
95
|
+
const timer = setTimeout(() => controller.abort(), limits.timeoutMs);
|
|
96
|
+
try {
|
|
97
|
+
const upstream = await fetch(upstreamUrl, {
|
|
98
|
+
method,
|
|
99
|
+
headers: buildUpstreamHeaders(req.headers, clientIpFromHeaders(req.headers, { trustedProxyHops: runtime.trustedProxyHops }), descriptor.forwardHeaders ?? []),
|
|
100
|
+
body,
|
|
101
|
+
redirect: "manual",
|
|
102
|
+
signal: controller.signal
|
|
103
|
+
});
|
|
104
|
+
return new Response(upstream.body, {
|
|
105
|
+
status: upstream.status,
|
|
106
|
+
headers: buildDownstreamHeaders(upstream.headers)
|
|
107
|
+
});
|
|
108
|
+
} catch (err) {
|
|
109
|
+
req.payload?.logger?.warn(`analytics: capture proxy upstream failed for "${adapter?.id}": ${String(err)}`);
|
|
110
|
+
return empty(502);
|
|
111
|
+
} finally {
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
/** The six endpoint entries the plugin registers, all sharing one handler. */
|
|
116
|
+
const proxyEndpoints = () => {
|
|
117
|
+
const handler = makeProxyHandler();
|
|
118
|
+
return PROXY_METHODS.map((method) => ({
|
|
119
|
+
method,
|
|
120
|
+
path: PROXY_ENDPOINT_PATH,
|
|
121
|
+
handler
|
|
122
|
+
}));
|
|
123
|
+
};
|
|
124
|
+
//#endregion
|
|
125
|
+
export { DEFAULT_PROXY_MAX_BODY_BYTES, DEFAULT_PROXY_TIMEOUT_MS, proxyEndpoints };
|
|
126
|
+
|
|
127
|
+
//# sourceMappingURL=proxyEndpoint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxyEndpoint.js","names":[],"sources":["../../src/capture/proxyEndpoint.ts"],"sourcesContent":["import type { Endpoint, PayloadHandler, PayloadRequest } from 'payload'\nimport { clientIpFromHeaders } from '../native/ingest/clientIp'\nimport { PROXY_PATH } from '../plugin/paths'\nimport { type AnalyticsRuntime, getRuntime } from '../plugin/runtime'\nimport { buildDownstreamHeaders, buildUpstreamHeaders, matchProxyRoute } from './proxyRoutes'\nimport { readCappedBody } from './requestBody'\nimport { type CaptureSlot, isCaptureSlot, resolveSlotAdapter } from './slots'\n\nexport { PROXY_PATH }\n\n/** Deadline for the upstream response headers, not for the body download. */\nexport const DEFAULT_PROXY_TIMEOUT_MS = 10_000\n\n/** PostHog batches carrying session-replay data routinely exceed 64 KB. */\nexport const DEFAULT_PROXY_MAX_BODY_BYTES = 1024 * 1024\n\n/** The path pattern the proxy is registered at, one entry per method. */\nexport const PROXY_ENDPOINT_PATH = `${PROXY_PATH}/:slot/:path*`\n\n/**\n * Payload matches an endpoint by exact method, and `@payloadcms/next` only routes these\n * six, so the handler is registered for all of them: the three it serves, and the three\n * it must answer 405 for rather than leaving to Payload's generic 404.\n */\nexport const PROXY_METHODS: ReadonlyArray<Endpoint['method']> = [\n\t'get',\n\t'post',\n\t'options',\n\t'put',\n\t'patch',\n\t'delete',\n]\n\nconst ALLOWED_METHODS = 'GET, POST, OPTIONS'\nconst SERVED_METHODS = new Set(['GET', 'POST', 'OPTIONS'])\n\n/**\n * The proxy's only error answer, and the one endpoint here that sends no error envelope:\n * it relays a vendor SDK's own traffic, and that SDK, not admin code, reads the answer.\n */\nconst empty = (status: number, headers?: HeadersInit) => new Response(null, { status, headers })\n\n/**\n * The request path relative to the slot mount, still percent-encoded: path-to-regexp\n * decodes it per segment, so re-encoding here would turn legal path characters\n * (`,=+:@`) into escapes the vendor never sent.\n */\nconst subPath = (req: PayloadRequest, slot: CaptureSlot): string => {\n\tconst pathname = req.pathname ?? (req.url ? new URL(req.url).pathname : '')\n\tconst mount = `${PROXY_PATH}/${slot}`\n\tconst start = pathname.indexOf(mount)\n\tif (start === -1) {\n\t\treturn '/'\n\t}\n\treturn pathname.slice(start + mount.length) || '/'\n}\n\nconst proxyLimits = (runtime: AnalyticsRuntime) => ({\n\ttimeoutMs: runtime.captureProxy?.timeoutMs ?? DEFAULT_PROXY_TIMEOUT_MS,\n\tmaxBodyBytes: runtime.captureProxy?.maxBodyBytes ?? DEFAULT_PROXY_MAX_BODY_BYTES,\n})\n\n/**\n * Public first-party proxy for a slot's vendor tracker: `${PROXY_PATH}/:slot/:path*`,\n * registered for every method Payload routes.\n *\n * The only URLs it ever fetches are compiled from the slot adapter's own\n * `capture.proxy.routes` templates, so an unfilled slot, an adapter without capture, or\n * a path outside the declared routes is a 404 and nothing leaves the server. Credentials\n * (`cookie`, `authorization`) never go upstream and `set-cookie` never comes back; a\n * body over `capture.proxy.maxBodyBytes` is refused with 413 and one that dies in\n * transit with 400, both before anything is forwarded; upstream failures answer 502\n * without echoing the URL or the error.\n */\nexport const makeProxyHandler = (): PayloadHandler => async (req) => {\n\tconst method = (req.method ?? 'get').toUpperCase()\n\tif (!SERVED_METHODS.has(method)) {\n\t\treturn empty(405, { allow: ALLOWED_METHODS })\n\t}\n\t// The tracker is same-origin, so a preflight never reaches a real deployment. Answering\n\t// locally beats forwarding one and stripping the CORS headers that made it meaningful.\n\tif (method === 'OPTIONS') {\n\t\treturn empty(204, { allow: ALLOWED_METHODS })\n\t}\n\tconst runtime = getRuntime(req.payload)\n\tconst slot = (req.routeParams as { slot?: unknown } | undefined)?.slot\n\tif (!runtime || typeof slot !== 'string' || !isCaptureSlot(slot)) {\n\t\treturn empty(404)\n\t}\n\tconst adapter = await resolveSlotAdapter(runtime, req, slot)\n\tconst descriptor = adapter?.capture?.proxy\n\tif (!descriptor || descriptor.routes.length === 0) {\n\t\treturn empty(404)\n\t}\n\tconst matched = matchProxyRoute(descriptor.routes, subPath(req, slot), {\n\t\ttrailingSlashes: descriptor.trailingSlashes,\n\t})\n\tif (!matched) {\n\t\treturn empty(404)\n\t}\n\tconst { upstreamUrl } = matched\n\tconst search = req.search ?? (req.url ? new URL(req.url).search : '')\n\tif (search && search !== '?') {\n\t\tconst incoming = search.startsWith('?') ? search.slice(1) : search\n\t\tupstreamUrl.search = upstreamUrl.search ? `${upstreamUrl.search}&${incoming}` : `?${incoming}`\n\t}\n\tconst limits = proxyLimits(runtime)\n\t// Buffered rather than streamed: a duplex request stream fails as a hung upstream\n\t// connection, and the cap has to be enforced before any of it is forwarded anyway.\n\tlet body: ArrayBuffer | undefined\n\tif (method === 'POST') {\n\t\tconst read = await readCappedBody(req, limits.maxBodyBytes)\n\t\tif (!read.ok) {\n\t\t\treturn empty(read.reason === 'too-large' ? 413 : 400)\n\t\t}\n\t\tbody = read.body\n\t}\n\t// The deadline covers time-to-headers only. AbortSignal.timeout would keep running\n\t// against the body stream and truncate a slow but healthy download.\n\tconst controller = new AbortController()\n\tconst timer = setTimeout(() => controller.abort(), limits.timeoutMs)\n\ttry {\n\t\tconst upstream = await fetch(upstreamUrl, {\n\t\t\tmethod,\n\t\t\theaders: buildUpstreamHeaders(\n\t\t\t\treq.headers,\n\t\t\t\tclientIpFromHeaders(req.headers, { trustedProxyHops: runtime.trustedProxyHops }),\n\t\t\t\tdescriptor.forwardHeaders ?? []\n\t\t\t),\n\t\t\tbody,\n\t\t\tredirect: 'manual',\n\t\t\tsignal: controller.signal,\n\t\t})\n\t\treturn new Response(upstream.body, {\n\t\t\tstatus: upstream.status,\n\t\t\theaders: buildDownstreamHeaders(upstream.headers),\n\t\t})\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(\n\t\t\t`analytics: capture proxy upstream failed for \"${adapter?.id}\": ${String(err)}`\n\t\t)\n\t\treturn empty(502)\n\t} finally {\n\t\tclearTimeout(timer)\n\t}\n}\n\n/** The six endpoint entries the plugin registers, all sharing one handler. */\nexport const proxyEndpoints = (): Endpoint[] => {\n\tconst handler = makeProxyHandler()\n\treturn PROXY_METHODS.map((method) => ({ method, path: PROXY_ENDPOINT_PATH, handler }))\n}\n"],"mappings":";;;;;;;;AAWA,MAAa,2BAA2B;;AAGxC,MAAa,+BAA+B,OAAO;;AAGnD,MAAa,sBAAsB,GAAG,WAAW;;;;;;AAOjD,MAAa,gBAAmD;CAC/D;CACA;CACA;CACA;CACA;CACA;AACD;AAEA,MAAM,kBAAkB;AACxB,MAAM,iBAAiB,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAS,CAAC;;;;;AAMzD,MAAM,SAAS,QAAgB,YAA0B,IAAI,SAAS,MAAM;CAAE;CAAQ;AAAQ,CAAC;;;;;;AAO/F,MAAM,WAAW,KAAqB,SAA8B;CACnE,MAAM,WAAW,IAAI,aAAa,IAAI,MAAM,IAAI,IAAI,IAAI,GAAG,EAAE,WAAW;CACxE,MAAM,QAAQ,GAAG,WAAW,GAAG;CAC/B,MAAM,QAAQ,SAAS,QAAQ,KAAK;CACpC,IAAI,UAAU,IACb,OAAO;CAER,OAAO,SAAS,MAAM,QAAQ,MAAM,MAAM,KAAK;AAChD;AAEA,MAAM,eAAe,aAA+B;CACnD,WAAW,QAAQ,cAAc,aAAA;CACjC,cAAc,QAAQ,cAAc,gBAAA;AACrC;;;;;;;;;;;;;AAcA,MAAa,yBAAyC,OAAO,QAAQ;CACpE,MAAM,UAAU,IAAI,UAAU,OAAO,YAAY;CACjD,IAAI,CAAC,eAAe,IAAI,MAAM,GAC7B,OAAO,MAAM,KAAK,EAAE,OAAO,gBAAgB,CAAC;CAI7C,IAAI,WAAW,WACd,OAAO,MAAM,KAAK,EAAE,OAAO,gBAAgB,CAAC;CAE7C,MAAM,UAAU,WAAW,IAAI,OAAO;CACtC,MAAM,OAAQ,IAAI,aAAgD;CAClE,IAAI,CAAC,WAAW,OAAO,SAAS,YAAY,CAAC,cAAc,IAAI,GAC9D,OAAO,MAAM,GAAG;CAEjB,MAAM,UAAU,MAAM,mBAAmB,SAAS,KAAK,IAAI;CAC3D,MAAM,aAAa,SAAS,SAAS;CACrC,IAAI,CAAC,cAAc,WAAW,OAAO,WAAW,GAC/C,OAAO,MAAM,GAAG;CAEjB,MAAM,UAAU,gBAAgB,WAAW,QAAQ,QAAQ,KAAK,IAAI,GAAG,EACtE,iBAAiB,WAAW,gBAC7B,CAAC;CACD,IAAI,CAAC,SACJ,OAAO,MAAM,GAAG;CAEjB,MAAM,EAAE,gBAAgB;CACxB,MAAM,SAAS,IAAI,WAAW,IAAI,MAAM,IAAI,IAAI,IAAI,GAAG,EAAE,SAAS;CAClE,IAAI,UAAU,WAAW,KAAK;EAC7B,MAAM,WAAW,OAAO,WAAW,GAAG,IAAI,OAAO,MAAM,CAAC,IAAI;EAC5D,YAAY,SAAS,YAAY,SAAS,GAAG,YAAY,OAAO,GAAG,aAAa,IAAI;CACrF;CACA,MAAM,SAAS,YAAY,OAAO;CAGlC,IAAI;CACJ,IAAI,WAAW,QAAQ;EACtB,MAAM,OAAO,MAAM,eAAe,KAAK,OAAO,YAAY;EAC1D,IAAI,CAAC,KAAK,IACT,OAAO,MAAM,KAAK,WAAW,cAAc,MAAM,GAAG;EAErD,OAAO,KAAK;CACb;CAGA,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,OAAO,SAAS;CACnE,IAAI;EACH,MAAM,WAAW,MAAM,MAAM,aAAa;GACzC;GACA,SAAS,qBACR,IAAI,SACJ,oBAAoB,IAAI,SAAS,EAAE,kBAAkB,QAAQ,iBAAiB,CAAC,GAC/E,WAAW,kBAAkB,CAAC,CAC/B;GACA;GACA,UAAU;GACV,QAAQ,WAAW;EACpB,CAAC;EACD,OAAO,IAAI,SAAS,SAAS,MAAM;GAClC,QAAQ,SAAS;GACjB,SAAS,uBAAuB,SAAS,OAAO;EACjD,CAAC;CACF,SAAS,KAAK;EACb,IAAI,SAAS,QAAQ,KACpB,iDAAiD,SAAS,GAAG,KAAK,OAAO,GAAG,GAC7E;EACA,OAAO,MAAM,GAAG;CACjB,UAAU;EACT,aAAa,KAAK;CACnB;AACD;;AAGA,MAAa,uBAAmC;CAC/C,MAAM,UAAU,iBAAiB;CACjC,OAAO,cAAc,KAAK,YAAY;EAAE;EAAQ,MAAM;EAAqB;CAAQ,EAAE;AACtF"}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { compile, match } from "path-to-regexp";
|
|
2
|
+
//#region src/capture/proxyRoutes.ts
|
|
3
|
+
/** Request headers every vendor proxy forwards upstream. */
|
|
4
|
+
const FORWARDED_REQUEST_HEADERS = [
|
|
5
|
+
"content-type",
|
|
6
|
+
"accept",
|
|
7
|
+
"accept-encoding",
|
|
8
|
+
"accept-language",
|
|
9
|
+
"user-agent",
|
|
10
|
+
"origin",
|
|
11
|
+
"referer",
|
|
12
|
+
"if-none-match",
|
|
13
|
+
"if-modified-since"
|
|
14
|
+
];
|
|
15
|
+
/**
|
|
16
|
+
* Never forwarded, whatever a descriptor's `forwardHeaders` asks for: credentials
|
|
17
|
+
* the vendor has no business seeing, and the forwarding chain the proxy sets itself.
|
|
18
|
+
*/
|
|
19
|
+
const NEVER_FORWARDED_REQUEST_HEADERS = new Set([
|
|
20
|
+
"cookie",
|
|
21
|
+
"authorization",
|
|
22
|
+
"proxy-authorization",
|
|
23
|
+
"host",
|
|
24
|
+
"forwarded",
|
|
25
|
+
"x-forwarded-for",
|
|
26
|
+
"x-forwarded-host",
|
|
27
|
+
"x-forwarded-proto",
|
|
28
|
+
"x-real-ip"
|
|
29
|
+
]);
|
|
30
|
+
/**
|
|
31
|
+
* The only upstream response headers passed back. `content-encoding` and
|
|
32
|
+
* `content-length` are deliberately absent: fetch decodes the body but leaves both
|
|
33
|
+
* describing the compressed bytes, so forwarding either corrupts the response.
|
|
34
|
+
*/
|
|
35
|
+
const FORWARDED_RESPONSE_HEADERS = [
|
|
36
|
+
"content-type",
|
|
37
|
+
"cache-control",
|
|
38
|
+
"etag",
|
|
39
|
+
"last-modified",
|
|
40
|
+
"vary"
|
|
41
|
+
];
|
|
42
|
+
const isSafeUpstream = (url) => url.protocol === "https:" || url.protocol === "http:";
|
|
43
|
+
const PATH_SAFE_ESCAPES = /%(24|26|2B|2C|3A|3D|40)/gi;
|
|
44
|
+
const encodeSegment = (segment) => encodeURIComponent(segment).replace(PATH_SAFE_ESCAPES, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
45
|
+
const paramSegments = (value) => Array.isArray(value) ? value.map(String) : typeof value === "string" ? [value] : [];
|
|
46
|
+
/** A dot segment would collapse when assigned to `URL.pathname`, escaping the route prefix. */
|
|
47
|
+
const hasDotSegment = (params) => Object.values(params).flatMap(paramSegments).some((segment) => segment === "." || segment === "..");
|
|
48
|
+
/**
|
|
49
|
+
* First declared route whose `source` matches `path` (percent-encoded, relative to the
|
|
50
|
+
* slot mount), compiled into its absolute upstream URL. Null when no route matches, so
|
|
51
|
+
* the caller answers 404: an upstream URL only ever comes from a descriptor template,
|
|
52
|
+
* never from the request.
|
|
53
|
+
*/
|
|
54
|
+
const matchProxyRoute = (routes, path, options = {}) => {
|
|
55
|
+
for (const route of routes) {
|
|
56
|
+
let template;
|
|
57
|
+
try {
|
|
58
|
+
template = new URL(route.upstream);
|
|
59
|
+
} catch {
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (!isSafeUpstream(template)) continue;
|
|
63
|
+
const matched = match(route.source, { decode: decodeURIComponent })(path);
|
|
64
|
+
if (!matched) continue;
|
|
65
|
+
const params = matched.params;
|
|
66
|
+
if (hasDotSegment(params)) return null;
|
|
67
|
+
let compiled;
|
|
68
|
+
try {
|
|
69
|
+
compiled = compile(template.pathname, { encode: encodeSegment })(params);
|
|
70
|
+
} catch {
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
const keepSlash = options.trailingSlashes === true && path.endsWith("/") && !compiled.endsWith("/");
|
|
74
|
+
const upstreamUrl = new URL(template.href);
|
|
75
|
+
upstreamUrl.pathname = compiled === "" ? "/" : `${compiled}${keepSlash ? "/" : ""}`;
|
|
76
|
+
return { upstreamUrl };
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* The headers the upstream request carries: the allowlist plus a descriptor's own
|
|
82
|
+
* extras, and `X-Forwarded-For` from the resolved client IP so vendor geo stays
|
|
83
|
+
* correct. An absent IP sends no header rather than a fabricated one.
|
|
84
|
+
*/
|
|
85
|
+
const buildUpstreamHeaders = (incoming, clientIp, extra = []) => {
|
|
86
|
+
const out = new Headers();
|
|
87
|
+
const names = [...FORWARDED_REQUEST_HEADERS, ...extra.map((name) => name.toLowerCase())];
|
|
88
|
+
for (const name of names) {
|
|
89
|
+
if (NEVER_FORWARDED_REQUEST_HEADERS.has(name)) continue;
|
|
90
|
+
const value = incoming.get(name);
|
|
91
|
+
if (value !== null) out.set(name, value);
|
|
92
|
+
}
|
|
93
|
+
if (clientIp) out.set("x-forwarded-for", clientIp);
|
|
94
|
+
return out;
|
|
95
|
+
};
|
|
96
|
+
/** The headers the client sees: the response allowlist, so `set-cookie` can never pass. */
|
|
97
|
+
const buildDownstreamHeaders = (upstream) => {
|
|
98
|
+
const out = new Headers();
|
|
99
|
+
for (const name of FORWARDED_RESPONSE_HEADERS) {
|
|
100
|
+
const value = upstream.get(name);
|
|
101
|
+
if (value !== null) out.set(name, value);
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
export { buildDownstreamHeaders, buildUpstreamHeaders, matchProxyRoute };
|
|
107
|
+
|
|
108
|
+
//# sourceMappingURL=proxyRoutes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxyRoutes.js","names":[],"sources":["../../src/capture/proxyRoutes.ts"],"sourcesContent":["import { compile, match } from 'path-to-regexp'\nimport type { ProxyRoute } from '../core/capture'\n\n/** Request headers every vendor proxy forwards upstream. */\nexport const FORWARDED_REQUEST_HEADERS = [\n\t'content-type',\n\t'accept',\n\t'accept-encoding',\n\t'accept-language',\n\t'user-agent',\n\t'origin',\n\t'referer',\n\t'if-none-match',\n\t'if-modified-since',\n]\n\n/**\n * Never forwarded, whatever a descriptor's `forwardHeaders` asks for: credentials\n * the vendor has no business seeing, and the forwarding chain the proxy sets itself.\n */\nconst NEVER_FORWARDED_REQUEST_HEADERS = new Set([\n\t'cookie',\n\t'authorization',\n\t'proxy-authorization',\n\t'host',\n\t'forwarded',\n\t'x-forwarded-for',\n\t'x-forwarded-host',\n\t'x-forwarded-proto',\n\t'x-real-ip',\n])\n\n/**\n * The only upstream response headers passed back. `content-encoding` and\n * `content-length` are deliberately absent: fetch decodes the body but leaves both\n * describing the compressed bytes, so forwarding either corrupts the response.\n */\nexport const FORWARDED_RESPONSE_HEADERS = [\n\t'content-type',\n\t'cache-control',\n\t'etag',\n\t'last-modified',\n\t'vary',\n]\n\nexport interface ProxyMatch {\n\tupstreamUrl: URL\n}\n\nexport interface MatchProxyRouteOptions {\n\t/** `ProxyDescriptor.trailingSlashes`: keep a request's trailing slash upstream. */\n\ttrailingSlashes?: boolean\n}\n\nconst isSafeUpstream = (url: URL): boolean => url.protocol === 'https:' || url.protocol === 'http:'\n\n// encodeURIComponent escapes every RFC 3986 sub-delim plus ':' and '@', all of which are\n// legal inside a path segment, so a vendor URL would not round-trip byte for byte. Restore\n// exactly those; '/', '?' and '#' stay escaped because they would change the URL's shape,\n// and ';' because some upstreams read it as a matrix-param separator.\nconst PATH_SAFE_ESCAPES = /%(24|26|2B|2C|3A|3D|40)/gi\n\nconst encodeSegment = (segment: string): string =>\n\tencodeURIComponent(segment).replace(PATH_SAFE_ESCAPES, (_, hex: string) =>\n\t\tString.fromCharCode(Number.parseInt(hex, 16))\n\t)\n\nconst paramSegments = (value: unknown): string[] =>\n\tArray.isArray(value) ? value.map(String) : typeof value === 'string' ? [value] : []\n\n/** A dot segment would collapse when assigned to `URL.pathname`, escaping the route prefix. */\nconst hasDotSegment = (params: Record<string, unknown>): boolean =>\n\tObject.values(params)\n\t\t.flatMap(paramSegments)\n\t\t.some((segment) => segment === '.' || segment === '..')\n\n/**\n * First declared route whose `source` matches `path` (percent-encoded, relative to the\n * slot mount), compiled into its absolute upstream URL. Null when no route matches, so\n * the caller answers 404: an upstream URL only ever comes from a descriptor template,\n * never from the request.\n */\nexport const matchProxyRoute = (\n\troutes: ProxyRoute[],\n\tpath: string,\n\toptions: MatchProxyRouteOptions = {}\n): ProxyMatch | null => {\n\tfor (const route of routes) {\n\t\tlet template: URL\n\t\ttry {\n\t\t\ttemplate = new URL(route.upstream)\n\t\t} catch {\n\t\t\tcontinue\n\t\t}\n\t\tif (!isSafeUpstream(template)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst matched = match(route.source, { decode: decodeURIComponent })(path)\n\t\tif (!matched) {\n\t\t\tcontinue\n\t\t}\n\t\tconst params = matched.params as Record<string, unknown>\n\t\tif (hasDotSegment(params)) {\n\t\t\treturn null\n\t\t}\n\t\tlet compiled: string\n\t\ttry {\n\t\t\tcompiled = compile(template.pathname, { encode: encodeSegment })(params)\n\t\t} catch {\n\t\t\t// A template naming a param its source never produces is a broken descriptor,\n\t\t\t// not a request the client can fix: skip it rather than throwing a public 500.\n\t\t\tcontinue\n\t\t}\n\t\t// path-to-regexp drops the trailing slash a wildcard consumed. Only a descriptor\n\t\t// that asks for it gets it back, because only PostHog's capture endpoints need it.\n\t\tconst keepSlash =\n\t\t\toptions.trailingSlashes === true && path.endsWith('/') && !compiled.endsWith('/')\n\t\tconst upstreamUrl = new URL(template.href)\n\t\tupstreamUrl.pathname = compiled === '' ? '/' : `${compiled}${keepSlash ? '/' : ''}`\n\t\treturn { upstreamUrl }\n\t}\n\treturn null\n}\n\n/**\n * The headers the upstream request carries: the allowlist plus a descriptor's own\n * extras, and `X-Forwarded-For` from the resolved client IP so vendor geo stays\n * correct. An absent IP sends no header rather than a fabricated one.\n */\nexport const buildUpstreamHeaders = (\n\tincoming: Headers,\n\tclientIp: string | null,\n\textra: string[] = []\n): Headers => {\n\tconst out = new Headers()\n\tconst names = [...FORWARDED_REQUEST_HEADERS, ...extra.map((name) => name.toLowerCase())]\n\tfor (const name of names) {\n\t\tif (NEVER_FORWARDED_REQUEST_HEADERS.has(name)) {\n\t\t\tcontinue\n\t\t}\n\t\tconst value = incoming.get(name)\n\t\tif (value !== null) {\n\t\t\tout.set(name, value)\n\t\t}\n\t}\n\tif (clientIp) {\n\t\tout.set('x-forwarded-for', clientIp)\n\t}\n\treturn out\n}\n\n/** The headers the client sees: the response allowlist, so `set-cookie` can never pass. */\nexport const buildDownstreamHeaders = (upstream: Headers): Headers => {\n\tconst out = new Headers()\n\tfor (const name of FORWARDED_RESPONSE_HEADERS) {\n\t\tconst value = upstream.get(name)\n\t\tif (value !== null) {\n\t\t\tout.set(name, value)\n\t\t}\n\t}\n\treturn out\n}\n"],"mappings":";;;AAIA,MAAa,4BAA4B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD;;;;;AAMA,MAAM,kCAAkC,IAAI,IAAI;CAC/C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;;;;;AAOD,MAAa,6BAA6B;CACzC;CACA;CACA;CACA;CACA;AACD;AAWA,MAAM,kBAAkB,QAAsB,IAAI,aAAa,YAAY,IAAI,aAAa;AAM5F,MAAM,oBAAoB;AAE1B,MAAM,iBAAiB,YACtB,mBAAmB,OAAO,EAAE,QAAQ,oBAAoB,GAAG,QAC1D,OAAO,aAAa,OAAO,SAAS,KAAK,EAAE,CAAC,CAC7C;AAED,MAAM,iBAAiB,UACtB,MAAM,QAAQ,KAAK,IAAI,MAAM,IAAI,MAAM,IAAI,OAAO,UAAU,WAAW,CAAC,KAAK,IAAI,CAAC;;AAGnF,MAAM,iBAAiB,WACtB,OAAO,OAAO,MAAM,EAClB,QAAQ,aAAa,EACrB,MAAM,YAAY,YAAY,OAAO,YAAY,IAAI;;;;;;;AAQxD,MAAa,mBACZ,QACA,MACA,UAAkC,CAAC,MACZ;CACvB,KAAK,MAAM,SAAS,QAAQ;EAC3B,IAAI;EACJ,IAAI;GACH,WAAW,IAAI,IAAI,MAAM,QAAQ;EAClC,QAAQ;GACP;EACD;EACA,IAAI,CAAC,eAAe,QAAQ,GAC3B;EAED,MAAM,UAAU,MAAM,MAAM,QAAQ,EAAE,QAAQ,mBAAmB,CAAC,EAAE,IAAI;EACxE,IAAI,CAAC,SACJ;EAED,MAAM,SAAS,QAAQ;EACvB,IAAI,cAAc,MAAM,GACvB,OAAO;EAER,IAAI;EACJ,IAAI;GACH,WAAW,QAAQ,SAAS,UAAU,EAAE,QAAQ,cAAc,CAAC,EAAE,MAAM;EACxE,QAAQ;GAGP;EACD;EAGA,MAAM,YACL,QAAQ,oBAAoB,QAAQ,KAAK,SAAS,GAAG,KAAK,CAAC,SAAS,SAAS,GAAG;EACjF,MAAM,cAAc,IAAI,IAAI,SAAS,IAAI;EACzC,YAAY,WAAW,aAAa,KAAK,MAAM,GAAG,WAAW,YAAY,MAAM;EAC/E,OAAO,EAAE,YAAY;CACtB;CACA,OAAO;AACR;;;;;;AAOA,MAAa,wBACZ,UACA,UACA,QAAkB,CAAC,MACN;CACb,MAAM,MAAM,IAAI,QAAQ;CACxB,MAAM,QAAQ,CAAC,GAAG,2BAA2B,GAAG,MAAM,KAAK,SAAS,KAAK,YAAY,CAAC,CAAC;CACvF,KAAK,MAAM,QAAQ,OAAO;EACzB,IAAI,gCAAgC,IAAI,IAAI,GAC3C;EAED,MAAM,QAAQ,SAAS,IAAI,IAAI;EAC/B,IAAI,UAAU,MACb,IAAI,IAAI,MAAM,KAAK;CAErB;CACA,IAAI,UACH,IAAI,IAAI,mBAAmB,QAAQ;CAEpC,OAAO;AACR;;AAGA,MAAa,0BAA0B,aAA+B;CACrE,MAAM,MAAM,IAAI,QAAQ;CACxB,KAAK,MAAM,QAAQ,4BAA4B;EAC9C,MAAM,QAAQ,SAAS,IAAI,IAAI;EAC/B,IAAI,UAAU,MACb,IAAI,IAAI,MAAM,KAAK;CAErB;CACA,OAAO;AACR"}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
//#region src/capture/requestBody.ts
|
|
2
|
+
const tooLarge = {
|
|
3
|
+
ok: false,
|
|
4
|
+
reason: "too-large"
|
|
5
|
+
};
|
|
6
|
+
const unreadable = {
|
|
7
|
+
ok: false,
|
|
8
|
+
reason: "unreadable"
|
|
9
|
+
};
|
|
10
|
+
const concat = (chunks, total) => {
|
|
11
|
+
const out = new Uint8Array(total);
|
|
12
|
+
let offset = 0;
|
|
13
|
+
for (const chunk of chunks) {
|
|
14
|
+
out.set(chunk, offset);
|
|
15
|
+
offset += chunk.byteLength;
|
|
16
|
+
}
|
|
17
|
+
return out.buffer;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Buffers a request body, refusing anything over `maxBytes`. A declared `content-length`
|
|
21
|
+
* short-circuits before a byte is read; a chunked body declares no length at all, so the
|
|
22
|
+
* running total is checked per chunk and the read is cancelled the moment it passes the
|
|
23
|
+
* cap. A stream that errors mid-read (a beacon from a tab that is already unloading is
|
|
24
|
+
* routine, not exceptional) resolves as `unreadable` rather than throwing, which would
|
|
25
|
+
* escape the handler into Payload's routeError as a 500.
|
|
26
|
+
*/
|
|
27
|
+
const readCappedBody = async (req, maxBytes) => {
|
|
28
|
+
const declared = req.headers.get("content-length");
|
|
29
|
+
if (declared !== null) {
|
|
30
|
+
const length = Number(declared);
|
|
31
|
+
if (Number.isFinite(length) && length > maxBytes) return tooLarge;
|
|
32
|
+
}
|
|
33
|
+
const stream = req.body;
|
|
34
|
+
if (!stream) try {
|
|
35
|
+
const buffered = await req.arrayBuffer?.() ?? /* @__PURE__ */ new ArrayBuffer(0);
|
|
36
|
+
return buffered.byteLength > maxBytes ? tooLarge : {
|
|
37
|
+
ok: true,
|
|
38
|
+
body: buffered
|
|
39
|
+
};
|
|
40
|
+
} catch {
|
|
41
|
+
return unreadable;
|
|
42
|
+
}
|
|
43
|
+
const reader = stream.getReader();
|
|
44
|
+
const chunks = [];
|
|
45
|
+
let total = 0;
|
|
46
|
+
try {
|
|
47
|
+
while (true) {
|
|
48
|
+
const { done, value } = await reader.read();
|
|
49
|
+
if (done) break;
|
|
50
|
+
total += value.byteLength;
|
|
51
|
+
if (total > maxBytes) {
|
|
52
|
+
await reader.cancel();
|
|
53
|
+
return tooLarge;
|
|
54
|
+
}
|
|
55
|
+
chunks.push(value);
|
|
56
|
+
}
|
|
57
|
+
} catch {
|
|
58
|
+
return unreadable;
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
ok: true,
|
|
62
|
+
body: concat(chunks, total)
|
|
63
|
+
};
|
|
64
|
+
};
|
|
65
|
+
//#endregion
|
|
66
|
+
export { readCappedBody };
|
|
67
|
+
|
|
68
|
+
//# sourceMappingURL=requestBody.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"requestBody.js","names":[],"sources":["../../src/capture/requestBody.ts"],"sourcesContent":["/** The subset of a Request the capped reader needs, so a PayloadRequest satisfies it. */\nexport interface CappedBodySource {\n\theaders: Headers\n\tbody?: ReadableStream<Uint8Array> | null\n\tarrayBuffer?: () => Promise<ArrayBuffer>\n}\n\n/**\n * `too-large` is the caller's 413; `unreadable` is its 400. They are distinct because a\n * body that died in transit is the client's problem to retry, not a limit it exceeded.\n */\nexport type CappedBodyResult =\n\t| { ok: true; body: ArrayBuffer }\n\t| { ok: false; reason: 'too-large' | 'unreadable' }\n\nconst tooLarge = { ok: false, reason: 'too-large' } as const\nconst unreadable = { ok: false, reason: 'unreadable' } as const\n\nconst concat = (chunks: Uint8Array[], total: number): ArrayBuffer => {\n\tconst out = new Uint8Array(total)\n\tlet offset = 0\n\tfor (const chunk of chunks) {\n\t\tout.set(chunk, offset)\n\t\toffset += chunk.byteLength\n\t}\n\treturn out.buffer\n}\n\n/**\n * Buffers a request body, refusing anything over `maxBytes`. A declared `content-length`\n * short-circuits before a byte is read; a chunked body declares no length at all, so the\n * running total is checked per chunk and the read is cancelled the moment it passes the\n * cap. A stream that errors mid-read (a beacon from a tab that is already unloading is\n * routine, not exceptional) resolves as `unreadable` rather than throwing, which would\n * escape the handler into Payload's routeError as a 500.\n */\nexport const readCappedBody = async (\n\treq: CappedBodySource,\n\tmaxBytes: number\n): Promise<CappedBodyResult> => {\n\tconst declared = req.headers.get('content-length')\n\tif (declared !== null) {\n\t\tconst length = Number(declared)\n\t\tif (Number.isFinite(length) && length > maxBytes) {\n\t\t\treturn tooLarge\n\t\t}\n\t}\n\tconst stream = req.body\n\tif (!stream) {\n\t\ttry {\n\t\t\tconst buffered = (await req.arrayBuffer?.()) ?? new ArrayBuffer(0)\n\t\t\treturn buffered.byteLength > maxBytes ? tooLarge : { ok: true, body: buffered }\n\t\t} catch {\n\t\t\treturn unreadable\n\t\t}\n\t}\n\tconst reader = stream.getReader()\n\tconst chunks: Uint8Array[] = []\n\tlet total = 0\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read()\n\t\t\tif (done) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttotal += value.byteLength\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel()\n\t\t\t\treturn tooLarge\n\t\t\t}\n\t\t\tchunks.push(value)\n\t\t}\n\t} catch {\n\t\treturn unreadable\n\t}\n\treturn { ok: true, body: concat(chunks, total) }\n}\n"],"mappings":";AAeA,MAAM,WAAW;CAAE,IAAI;CAAO,QAAQ;AAAY;AAClD,MAAM,aAAa;CAAE,IAAI;CAAO,QAAQ;AAAa;AAErD,MAAM,UAAU,QAAsB,UAA+B;CACpE,MAAM,MAAM,IAAI,WAAW,KAAK;CAChC,IAAI,SAAS;CACb,KAAK,MAAM,SAAS,QAAQ;EAC3B,IAAI,IAAI,OAAO,MAAM;EACrB,UAAU,MAAM;CACjB;CACA,OAAO,IAAI;AACZ;;;;;;;;;AAUA,MAAa,iBAAiB,OAC7B,KACA,aAC+B;CAC/B,MAAM,WAAW,IAAI,QAAQ,IAAI,gBAAgB;CACjD,IAAI,aAAa,MAAM;EACtB,MAAM,SAAS,OAAO,QAAQ;EAC9B,IAAI,OAAO,SAAS,MAAM,KAAK,SAAS,UACvC,OAAO;CAET;CACA,MAAM,SAAS,IAAI;CACnB,IAAI,CAAC,QACJ,IAAI;EACH,MAAM,WAAY,MAAM,IAAI,cAAc,qBAAM,IAAI,YAAY,CAAC;EACjE,OAAO,SAAS,aAAa,WAAW,WAAW;GAAE,IAAI;GAAM,MAAM;EAAS;CAC/E,QAAQ;EACP,OAAO;CACR;CAED,MAAM,SAAS,OAAO,UAAU;CAChC,MAAM,SAAuB,CAAC;CAC9B,IAAI,QAAQ;CACZ,IAAI;EACH,OAAO,MAAM;GACZ,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;GAC1C,IAAI,MACH;GAED,SAAS,MAAM;GACf,IAAI,QAAQ,UAAU;IACrB,MAAM,OAAO,OAAO;IACpB,OAAO;GACR;GACA,OAAO,KAAK,KAAK;EAClB;CACD,QAAQ;EACP,OAAO;CACR;CACA,OAAO;EAAE,IAAI;EAAM,MAAM,OAAO,QAAQ,KAAK;CAAE;AAChD"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { PayloadRequest } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/capture/slots.d.ts
|
|
4
|
+
/** The two capture slots an install can fill: the platform's own and the tenant's. */
|
|
5
|
+
type CaptureSlot = 'global' | 'tenant';
|
|
6
|
+
//#endregion
|
|
7
|
+
export { CaptureSlot };
|
|
8
|
+
//# sourceMappingURL=slots.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { resolveRegistryFor, resolveScopeFor } from "../plugin/runtime.js";
|
|
2
|
+
//#region src/capture/slots.ts
|
|
3
|
+
const CAPTURE_SLOTS = ["global", "tenant"];
|
|
4
|
+
const isCaptureSlot = (value) => CAPTURE_SLOTS.includes(value);
|
|
5
|
+
/**
|
|
6
|
+
* The adapter filling one capture slot for this request, or null when the slot is
|
|
7
|
+
* unfilled. `global` is install-wide, so it resolves out of the config registry only:
|
|
8
|
+
* the `capture.slots.global` override, else the designated `platformAdapter`, else the
|
|
9
|
+
* single config adapter when there is exactly one. `tenant` resolves out of the
|
|
10
|
+
* request's own per-scope registry (which includes that scope's runtime providers) and
|
|
11
|
+
* is null whenever no scope resolves. Any resolution failure degrades to null, so the
|
|
12
|
+
* proxy 404s instead of throwing.
|
|
13
|
+
*
|
|
14
|
+
* A slot configured `false` is null before any of that runs: an explicit disable outranks
|
|
15
|
+
* every default, and nothing happens on its behalf, not even a scope lookup.
|
|
16
|
+
*
|
|
17
|
+
* `scope` passes in an already-resolved scope so a caller filling both slots (and the
|
|
18
|
+
* request's goals) calls the host's resolver once; omit it and the tenant slot resolves
|
|
19
|
+
* its own.
|
|
20
|
+
*/
|
|
21
|
+
const resolveSlotAdapterFor = async (args) => {
|
|
22
|
+
const { runtime, req, slot, scope } = args;
|
|
23
|
+
const configured = runtime.captureSlots?.[slot];
|
|
24
|
+
if (configured === false) return null;
|
|
25
|
+
try {
|
|
26
|
+
if (slot === "global") {
|
|
27
|
+
if (configured) return runtime.registry.get(configured);
|
|
28
|
+
if (runtime.platformAdapterId) return runtime.registry.get(runtime.platformAdapterId);
|
|
29
|
+
const all = runtime.registry.all();
|
|
30
|
+
return all.length === 1 ? all[0] : null;
|
|
31
|
+
}
|
|
32
|
+
const resolved = scope === void 0 ? await resolveScopeFor(runtime, req) : scope;
|
|
33
|
+
if (resolved === null) return null;
|
|
34
|
+
const registry = await resolveRegistryFor(runtime, {
|
|
35
|
+
payload: req.payload,
|
|
36
|
+
req,
|
|
37
|
+
scope: resolved
|
|
38
|
+
});
|
|
39
|
+
return configured ? registry.get(configured) : registry.default();
|
|
40
|
+
} catch (err) {
|
|
41
|
+
req.payload?.logger?.warn(`analytics: capture slot "${slot}" resolution failed: ${String(err)}`);
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
/** {@link resolveSlotAdapterFor} for a caller holding one slot and no scope of its own. */
|
|
46
|
+
const resolveSlotAdapter = (runtime, req, slot) => resolveSlotAdapterFor({
|
|
47
|
+
runtime,
|
|
48
|
+
req,
|
|
49
|
+
slot
|
|
50
|
+
});
|
|
51
|
+
//#endregion
|
|
52
|
+
export { CAPTURE_SLOTS, isCaptureSlot, resolveSlotAdapter, resolveSlotAdapterFor };
|
|
53
|
+
|
|
54
|
+
//# sourceMappingURL=slots.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"slots.js","names":[],"sources":["../../src/capture/slots.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\nimport type { AnalyticsAdapter } from '../core/contract'\nimport { type AnalyticsRuntime, resolveRegistryFor, resolveScopeFor } from '../plugin/runtime'\n\n/** The two capture slots an install can fill: the platform's own and the tenant's. */\nexport type CaptureSlot = 'global' | 'tenant'\n\nexport const CAPTURE_SLOTS: readonly CaptureSlot[] = ['global', 'tenant']\n\nexport const isCaptureSlot = (value: string): value is CaptureSlot =>\n\t(CAPTURE_SLOTS as readonly string[]).includes(value)\n\n/**\n * The adapter filling one capture slot for this request, or null when the slot is\n * unfilled. `global` is install-wide, so it resolves out of the config registry only:\n * the `capture.slots.global` override, else the designated `platformAdapter`, else the\n * single config adapter when there is exactly one. `tenant` resolves out of the\n * request's own per-scope registry (which includes that scope's runtime providers) and\n * is null whenever no scope resolves. Any resolution failure degrades to null, so the\n * proxy 404s instead of throwing.\n *\n * A slot configured `false` is null before any of that runs: an explicit disable outranks\n * every default, and nothing happens on its behalf, not even a scope lookup.\n *\n * `scope` passes in an already-resolved scope so a caller filling both slots (and the\n * request's goals) calls the host's resolver once; omit it and the tenant slot resolves\n * its own.\n */\nexport const resolveSlotAdapterFor = async (args: {\n\truntime: AnalyticsRuntime\n\treq: PayloadRequest\n\tslot: CaptureSlot\n\tscope?: string | null\n}): Promise<AnalyticsAdapter | null> => {\n\tconst { runtime, req, slot, scope } = args\n\tconst configured = runtime.captureSlots?.[slot]\n\tif (configured === false) {\n\t\treturn null\n\t}\n\ttry {\n\t\tif (slot === 'global') {\n\t\t\tif (configured) {\n\t\t\t\treturn runtime.registry.get(configured)\n\t\t\t}\n\t\t\tif (runtime.platformAdapterId) {\n\t\t\t\treturn runtime.registry.get(runtime.platformAdapterId)\n\t\t\t}\n\t\t\tconst all = runtime.registry.all()\n\t\t\treturn all.length === 1 ? (all[0] as AnalyticsAdapter) : null\n\t\t}\n\t\tconst resolved = scope === undefined ? await resolveScopeFor(runtime, req) : scope\n\t\tif (resolved === null) {\n\t\t\treturn null\n\t\t}\n\t\tconst registry = await resolveRegistryFor(runtime, {\n\t\t\tpayload: req.payload,\n\t\t\treq,\n\t\t\tscope: resolved,\n\t\t})\n\t\treturn configured ? registry.get(configured) : registry.default()\n\t} catch (err) {\n\t\treq.payload?.logger?.warn(`analytics: capture slot \"${slot}\" resolution failed: ${String(err)}`)\n\t\treturn null\n\t}\n}\n\n/** {@link resolveSlotAdapterFor} for a caller holding one slot and no scope of its own. */\nexport const resolveSlotAdapter = (\n\truntime: AnalyticsRuntime,\n\treq: PayloadRequest,\n\tslot: CaptureSlot\n): Promise<AnalyticsAdapter | null> => resolveSlotAdapterFor({ runtime, req, slot })\n"],"mappings":";;AAOA,MAAa,gBAAwC,CAAC,UAAU,QAAQ;AAExE,MAAa,iBAAiB,UAC5B,cAAoC,SAAS,KAAK;;;;;;;;;;;;;;;;;AAkBpD,MAAa,wBAAwB,OAAO,SAKJ;CACvC,MAAM,EAAE,SAAS,KAAK,MAAM,UAAU;CACtC,MAAM,aAAa,QAAQ,eAAe;CAC1C,IAAI,eAAe,OAClB,OAAO;CAER,IAAI;EACH,IAAI,SAAS,UAAU;GACtB,IAAI,YACH,OAAO,QAAQ,SAAS,IAAI,UAAU;GAEvC,IAAI,QAAQ,mBACX,OAAO,QAAQ,SAAS,IAAI,QAAQ,iBAAiB;GAEtD,MAAM,MAAM,QAAQ,SAAS,IAAI;GACjC,OAAO,IAAI,WAAW,IAAK,IAAI,KAA0B;EAC1D;EACA,MAAM,WAAW,UAAU,KAAA,IAAY,MAAM,gBAAgB,SAAS,GAAG,IAAI;EAC7E,IAAI,aAAa,MAChB,OAAO;EAER,MAAM,WAAW,MAAM,mBAAmB,SAAS;GAClD,SAAS,IAAI;GACb;GACA,OAAO;EACR,CAAC;EACD,OAAO,aAAa,SAAS,IAAI,UAAU,IAAI,SAAS,QAAQ;CACjE,SAAS,KAAK;EACb,IAAI,SAAS,QAAQ,KAAK,4BAA4B,KAAK,uBAAuB,OAAO,GAAG,GAAG;EAC/F,OAAO;CACR;AACD;;AAGA,MAAa,sBACZ,SACA,KACA,SACsC,sBAAsB;CAAE;CAAS;CAAK;AAAK,CAAC"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { TrackerGoal } from "../goals/types.js";
|
|
2
|
+
import { CaptureClientKind, CaptureSnippet, CaptureSupport } from "../core/capture.js";
|
|
3
|
+
import { CaptureSlot } from "./slots.js";
|
|
4
|
+
import { ResolvedAutoCapture } from "../core/options.js";
|
|
5
|
+
import { PayloadRequest } from "payload";
|
|
6
|
+
|
|
7
|
+
//#region src/capture/trackerConfig.d.ts
|
|
8
|
+
interface TrackerSlotConfig {
|
|
9
|
+
slot: CaptureSlot;
|
|
10
|
+
kind: CaptureClientKind;
|
|
11
|
+
adapterId: string;
|
|
12
|
+
/** Mount the snippet and the sink talk to: the runtime proxy, or a `capture.paths` override. */
|
|
13
|
+
path: string;
|
|
14
|
+
snippet: CaptureSnippet;
|
|
15
|
+
client: CaptureSupport['client'];
|
|
16
|
+
requiresConsent: boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Everything the browser tracker needs, and nothing else. Serialized to any visitor by the
|
|
20
|
+
* public tracker endpoint, so it carries only what an adapter puts in `capture.client` and
|
|
21
|
+
* `capture.snippet`: never a query credential, never a goal's admin-facing name.
|
|
22
|
+
*/
|
|
23
|
+
interface TrackerConfig {
|
|
24
|
+
slots: TrackerSlotConfig[];
|
|
25
|
+
autoCapture: ResolvedAutoCapture;
|
|
26
|
+
/** The request scope's goals, config merged with the goals collection. */
|
|
27
|
+
goals: TrackerGoal[];
|
|
28
|
+
/** Where the native sink posts events, derived from the app's own `routes.api`. */
|
|
29
|
+
ingestPath: string;
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { TrackerConfig, TrackerSlotConfig };
|
|
33
|
+
//# sourceMappingURL=trackerConfig.d.ts.map
|